Repository navigation
Expand file tree
/
Copy pathexecutor.py
More file actions
2985 lines (2729 loc) · 155 KB
/
Copy pathexecutor.py
File metadata and controls
2985 lines (2729 loc) · 155 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import asyncio
import base64
import json
import logging
import os
import re
import time
import uuid
import asyncio
from datetime import datetime, timezone
from typing import Any, Optional
from a2a.server.agent_execution import AgentExecutor, RequestContext
from a2a.server.events import EventQueue
from a2a.helpers import (
new_task,
new_text_artifact_update_event,
new_text_status_update_event,
)
from a2a.types import TaskState
from google.protobuf.json_format import ParseDict
from processgpt_agent_sdk.artifacts import download_file
from core.chat.ui_text import NO_DETAIL, NO_RESULT, asks_to_save, defect_line, done_todos, reply_lang, t as ui_t
from langchain_core.messages import AIMessageChunk, ToolMessage
from langgraph.types import Overwrite
from typing_extensions import override
from core.agents.agent import build_agent, resolve_skill_sources
from core.agents.steering import SteeringMiddleware
from core.bpm.tools import set_process_context
from core.storage.checkpointer import (
get_async_postgres_checkpointer,
get_shared_memory_checkpointer,
get_workitem_checkpointer,
resolve_checkpoint_thread_id,
)
from core.chat.hitl import (
extract_interrupt_payload,
find_interrupt_payload,
is_duplicate_hitl_request,
normalize_hitl_payload,
records_human_answered,
workitem_resume_answer,
)
from processgpt_agent_sdk.chat_registry import get_run_registry
from processgpt_agent_sdk.chat_mode import persist_chat_to_db
from processgpt_agent_sdk.steering import (
REASON_AWAITING_HUMAN_INPUT,
SteerDirective,
SteerResult,
)
from core.chat.callbacks import ToolTrackingCallback
from core.agents.input_builder import (
build_graph_inputs,
choose_reclaim_inputs,
resume_kind_of,
build_user_message,
collect_recent_messages,
extract_skill_command,
log_pinned_skill_outcome,
resolve_chat_room_id,
resolve_handover_room_id,
)
from core.chat.activity import (
fetch_child_activity_todo,
load_activity_capabilities,
load_activity_root_agent,
resolve_root_agent,
load_subprocess_subagents,
)
from core.chat.chat_room import (
CtxAccumulator,
a_set_chat_room_context,
a_set_chat_room_preview,
a_update_chat_room_context,
a_upsert_chat_room_start,
build_initial_chat_room_context,
)
from core.chat.event_tap import EventTapStreamer
from core.chat.tool_arg_stream import ToolArgTextStreamer
from core.llm.mcp import (
fetch_tenant_mcp,
hidden_server_names,
hidden_tool_names,
load_chat_root_tools,
reset_hidden_servers,
reset_hidden_tools,
reset_request_user_jwt,
resolve_user_placeholders,
set_hidden_servers,
set_hidden_tools,
set_request_user_jwt,
)
from core.skills.git_skill_fetcher import prefetch_git_skills
from core.skills.local_system_skills import seed_local_system_skills
from core.skills.skills import add_skill_reload_inputs, resolve_slash_skill
from core.skills.tools import _skills_from_tool_args, _current_tenant_id as _skill_tenant_id, _current_user_id as _skill_user_id
from core.utils.output_utils import extract_final_text, extract_json_text
from core.chat.input_images import images_note, resolve_images, split_input_images
from core.chat.result_summary import split_result_summary
from core.llm.token_hygiene import ToolResultTruncationMiddleware
from core.agents.skill_creator_subagents import build_skill_creator_subagents
from core.agents.team import choose_team, team_card_text, team_message_hint
from core.chat.stream_scope import is_subagent_namespace
from core.deterministic import MODE_UNDO_PENDING, try_deterministic_execution
from core.rag.process_knowledge import (
chat_selection as _kb_chat_selection,
knowledge_note as _kb_note,
prepare_task_knowledge,
set_generation_knowledge,
)
# 우리 기능(프로세스 생성 HITL 캡처/이름도출)에서 사용하는 contextvar — incoming 에는 없으나 유지.
from core.skills.tools import _current_conversation_id as _skill_conversation_id
from core.skills.tools import _current_user_request as _skill_user_request
from core.skills.tools import _bpmn_work_dir
from core.skills.tools import bpmn_container_base as _bpmn_container_base
from core.skills.tools import checkout_container_base as _checkout_container_base
from core.sandbox.docker_sandbox import set_workspace_scope
from core.storage.worktree import BranchState, commit_turn, materialize as materialize_branch
from core.storage.storage import (
download_workspace_directory,
remove_workspace_files,
set_tenant_id as _set_storage_tenant_id,
upload_workspace_directory,
workspace_file_set,
)
logger = logging.getLogger(__name__)
# deepagent 가 샌드박스 workspace 에 생성/수정하는 산출물 파일을 프론트(Claude Desktop식 파일 UI)로
# 실시간 전달하기 위한 설정. write_file/edit_file 도구가 건드린 /workspace 하위 파일을 file_artifact 로 보낸다.
# 에이전트에게 바인딩된 파일 도구는 deepagents 기본 도구뿐이다(프로세스 정의 전용
# write/update 도구는 더 이상 부착하지 않는다 — core/agents/agent.py 참고).
_FILE_TOOL_NAMES = ("write_file", "edit_file")
_FILE_ARTIFACT_MAX_BYTES = 400_000 # 미리보기에 과한 대용량 파일은 잘라 보냄
# 스킬 평가(test-runner/evaluator) 실행 산출물 디렉터리. 회차마다 outputs/·grading.json 이
# 수십 개씩 쌓이는 내부 작업 파일이라 사용자 산출물 패널에 띄우지 않는다 — 결과 요약은
# complete_skill_creation 이 DB(skill_eval_runs/_results)에 남긴다.
_EVAL_RUN_PATH_MARKER = "/.skill-evals/"
# 채팅 산출물에서 스킬이 만든 hwpx 컨테이너 경로를 잡아내기 위한 패턴.
_HWPX_PATH_RE = re.compile(r"/workspace/[^\s\"']+\.hwpx")
# 폼 출력에서 샌드박스 바이너리 파일(pdf/docx 등) 경로를 감지하기 위한 패턴.
_WS_BINARY_FILE_RE = re.compile(
r"/workspace/[^\s\"']+\.(?:pdf|docx?|xlsx?|pptx?)",
re.IGNORECASE,
)
def _validation_failure_summary(failures: list[dict], max_items: int = 3, lang: str = "ko") -> str:
"""검증 실패 목록을 사용자에게 보여줄 짧은 불릿으로 요약한다."""
lines: list[str] = []
for failure in failures:
for defect in (failure.get("defects") or [])[:max_items]:
if not isinstance(defect, dict):
continue
detail = defect_line(defect, lang)
if detail:
lines.append(f"- {detail}")
if not lines:
return f"- {NO_DETAIL.get(lang) or NO_DETAIL['ko']}"
return "\n".join(lines[:max_items])
def _completion_error_summary(result: str, max_items: int = 3, lang: str = "ko") -> str:
"""complete_process_generation 의 "ERROR: {...}" 결과에서 사용자에게 보일 이유를 뽑는다."""
body = result[len("ERROR:"):].strip() if result.startswith("ERROR:") else result
try:
obj = json.loads(body)
except Exception:
return f"- {body[:300]}" if body else f"- {NO_RESULT.get(lang) or NO_RESULT['ko']}"
failures = obj.get("validation_errors") if isinstance(obj, dict) else None
if isinstance(failures, list) and failures:
return _validation_failure_summary(failures, max_items, lang)
return f"- {obj.get('message') if isinstance(obj, dict) else body}"
def _identified_notes_text(room_dir, conversation_id: str) -> str:
"""식별 화면에서 전환한 방이면, 흐름을 그대로 두었다는 안내와 되돌린 변경의 이유를 붙인다."""
from core.skills.identified import load_identified_definition, read_notes
from core.skills.tools import definition_work_dirs as _definition_dirs
if not load_identified_definition(conversation_id):
return ""
notes: list[str] = []
for directory in _definition_dirs(room_dir, conversation_id):
notes.extend(n for n in read_notes(directory) if n not in notes)
text = "\n\n인계 기록에서 도출된 흐름(단계·담당자·순서·분기)은 그대로 두고 폼·스킬·에이전트만 보강했어요."
if notes:
text += "\n생성 중 바꾸려던 흐름은 반영하지 않았어요:\n" + "\n".join(f"- {n}" for n in notes[:5])
return text
def _ws_file_meta(path: str) -> tuple[str, str]:
"""container 경로 → (파일명, 확장자 소문자)."""
from pathlib import PurePosixPath
p = PurePosixPath(str(path or ""))
return p.name, p.suffix.lower()
async def _read_ws_file_content(tenant_id: str, path: str) -> str | None:
"""샌드박스 backend 로 workspace 파일 내용을 읽어 문자열로 반환(실패 시 None)."""
try:
from core.agents.agent import _BASE_DIR as _AGENT_BASE_DIR, _SKILLS_DIR as _AGENT_SKILLS_DIR
from core.sandbox.docker_sandbox import get_or_create_sandbox
backend = get_or_create_sandbox(
tenant_id,
workspace_host=_AGENT_BASE_DIR / "workspace",
skills_host=_AGENT_SKILLS_DIR,
)
results = await asyncio.to_thread(backend.download_files, [path])
if results:
res = results[0]
content = getattr(res, "content", None)
if content is not None and not getattr(res, "error", None):
return content.decode("utf-8", errors="replace")
except Exception:
logger.warning("file_artifact: workspace 파일 읽기 실패 path=%s", path, exc_info=True)
return None
def _office_mcp_url() -> str:
"""office-mcp streamable-http 엔드포인트 URL (deep-research 와 동일 env 사용)."""
raw = (os.environ.get("PROCESS_GPT_OFFICE_MCP_URL") or "").strip()
if not raw:
raw = "http://localhost:1192/mcp/"
# /mcp 경로 보장 + 트레일링 슬래시(streamable-http)
if not raw.rstrip("/").endswith("/mcp"):
raw = raw.rstrip("/") + "/mcp"
if not raw.endswith("/"):
raw = raw + "/"
return raw
async def _call_office_mcp_tool(tool: str, arguments: dict) -> dict | None:
"""office-mcp 도구를 JSON-RPC(tools/call)로 호출하고 결과 dict 를 반환한다(실패 시 None).
office-mcp(main.py)는 stateless_http + json_response 이므로 프론트처럼 bare POST 로 호출 가능.
"""
import httpx
url = _office_mcp_url()
payload = {
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {"name": tool, "arguments": arguments},
}
try:
# office-mcp(streamable-http)는 /mcp/ → /mcp 로 307 리다이렉트할 수 있어 반드시 따라가야 한다
# (httpx 는 기본적으로 리다이렉트를 안 따라감 → raise_for_status 에서 터짐).
async with httpx.AsyncClient(timeout=300, follow_redirects=True) as client:
r = await client.post(
url,
json=payload,
headers={"Content-Type": "application/json", "Accept": "application/json, text/event-stream"},
)
r.raise_for_status()
data = r.json()
except Exception:
logger.warning("office-mcp 호출 실패 | tool=%s url=%s", tool, url, exc_info=True)
return None
result = data.get("result") if isinstance(data, dict) else None
if not isinstance(result, dict):
logger.warning("office-mcp 응답 형식 이상 | tool=%s data=%.200s", tool, str(data))
return None
if isinstance(result.get("structuredContent"), dict):
sc = result["structuredContent"]
# FastMCP 는 dict 반환을 {"result": {...}} 로 감싸기도 한다.
return sc.get("result") if isinstance(sc.get("result"), dict) else sc
for c in result.get("content") or []:
if isinstance(c, dict) and c.get("type") == "text":
try:
return json.loads(c.get("text") or "")
except Exception:
continue
return None
async def _materialize_hwpx_form_outputs(tenant_id: str, final_text: str) -> str:
"""worklist 폼 출력 JSON 안의 샌드박스 hwpx 경로(/workspace/*.hwpx)를 실제 문서로 실체화한다.
스킬(hwpx-writer)이 만든 .hwpx 는 Docker 샌드박스 안에만 있고 폼값엔 컨테이너 경로만 담긴다.
그 파일을 꺼내 base64 로 office-mcp(store_and_render_hwpx)에 넘겨 storage 업로드 + HTML 변환을
시키고(=deepagents 는 storage 직접 미접근), 폼값을 {path:file_url, name, html_url, ext} 로 바꾼다.
이러면 프론트 FileField 다운로드 + HwpxViewer 미리보기/편집(html_url·file_url) 이 그대로 동작한다.
실패는 베스트에포트(원본 경로 유지)."""
if not final_text or ".hwpx" not in final_text.lower():
return final_text
try:
obj = json.loads(final_text)
except Exception:
return final_text
if not isinstance(obj, (dict, list)):
return final_text
try:
from core.agents.agent import _BASE_DIR as _AGENT_BASE_DIR, _SKILLS_DIR as _AGENT_SKILLS_DIR
from core.sandbox.docker_sandbox import get_or_create_sandbox
except Exception:
logger.warning("hwpx 실체화: sandbox 모듈 로드 실패", exc_info=True)
return final_text
from pathlib import PurePosixPath
backend = get_or_create_sandbox(
tenant_id,
workspace_host=_AGENT_BASE_DIR / "workspace",
skills_host=_AGENT_SKILLS_DIR,
)
cache: dict[str, dict] = {}
async def _resolve(path_val: str) -> dict | None:
container_path = path_val if path_val.startswith("/") else "/" + path_val
if not container_path.startswith("/workspace"):
return None
if container_path in cache:
return cache[container_path]
results = await asyncio.to_thread(backend.download_files, [container_path])
res = results[0] if results else None
content = getattr(res, "content", None) if res else None
if content is None or getattr(res, "error", None):
logger.warning("hwpx 실체화: 샌드박스에 파일 없음 | path=%s", container_path)
return None
name = PurePosixPath(container_path).name
b64 = base64.b64encode(content).decode("ascii")
out = await _call_office_mcp_tool(
"store_and_render_hwpx",
{"base64_data": b64, "file_name": name, "tenant_id": tenant_id or ""},
)
if not out or not out.get("file_url"):
logger.warning("hwpx 실체화: office-mcp 결과 없음 | path=%s", container_path)
return None
val = {
"path": out.get("file_url"),
# 이름은 원래 것을 쓴다. 저장소가 돌려주는 이름은 아스키로 추려져
# '주차장_안전_안내문.hwpx' 가 'edited-_20260918_010111.hwpx' 로 남는다.
# 사람이 보는 이름은 무엇인지를 말해야 한다.
"name": name or out.get("file_name"),
"html_url": out.get("html_url") or "",
"ext": ".hwpx",
}
cache[container_path] = val
logger.info("hwpx 실체화 완료 | %s → file_url=%s html_url=%s", container_path, val["path"], val["html_url"])
return val
async def _walk(node):
if isinstance(node, dict):
for k, v in list(node.items()):
node[k] = await _walk(v)
return node
if isinstance(node, list):
return [await _walk(x) for x in node]
if isinstance(node, str):
s = node.strip()
if s.lower().endswith(".hwpx") and ("workspace/" in s or s.startswith("/workspace")):
r = await _resolve(s)
return r if r is not None else node
return node
try:
obj = await _walk(obj)
except Exception:
logger.warning("hwpx 실체화: JSON 순회 실패", exc_info=True)
return final_text
return json.dumps(obj, ensure_ascii=False)
async def _materialize_ws_file_form_outputs(
tenant_id: str, final_text: str, conversation_id: str = "",
) -> str:
"""worklist 폼 출력 JSON 안의 샌드박스 바이너리 파일 경로를 받을 수 있는 주소로 바꾼다.
예전에는 이 서버 메모리(또는 Redis)에 담고 한 시간짜리 토큰 주소를 폼값에 박았다.
그 시간이 지나거나 파드가 바뀌면 끝이었다 — 결재선을 타고 며칠 뒤에 열어 본 사람은
빈손이었다. 채팅 산출물에서 이미 겪은 것과 같은 일이다.
지금은 채팅과 **같은 규약**을 탄다(`core/chat/artifacts.py`). 비공개 버킷에 보관하고
폼값에 서명 주소와 함께 `file_id` 를 싣는다 — 주소가 죽어도 파일은 남아 있고,
화면이 그 열쇠로 새 주소를 받아 간다.
폼값은 {path, name, ext, file_id, url_expires_at} 가 된다. `path` 는 그대로라
프론트 FileField 다운로드는 손대지 않아도 동작한다.
실패는 베스트에포트(원본 경로 유지)."""
if not final_text or not _WS_BINARY_FILE_RE.search(final_text):
return final_text
try:
obj = json.loads(final_text)
except Exception:
return final_text
if not isinstance(obj, (dict, list)):
return final_text
try:
from core.agents.agent import _BASE_DIR as _AGENT_BASE_DIR, _SKILLS_DIR as _AGENT_SKILLS_DIR
from core.sandbox.docker_sandbox import get_or_create_sandbox
from core.chat.artifacts import publish_one
except Exception:
logger.warning("ws 파일 실체화: 모듈 로드 실패", exc_info=True)
return final_text
from pathlib import PurePosixPath
backend = get_or_create_sandbox(
tenant_id,
workspace_host=_AGENT_BASE_DIR / "workspace",
skills_host=_AGENT_SKILLS_DIR,
)
cache: dict[str, dict] = {}
async def _resolve(path_val: str) -> dict | None:
container_path = path_val if path_val.startswith("/") else "/" + path_val
if not container_path.startswith("/workspace"):
return None
if container_path in cache:
return cache[container_path]
results = await asyncio.to_thread(backend.download_files, [container_path])
res = results[0] if results else None
content = getattr(res, "content", None) if res else None
if content is None or getattr(res, "error", None):
logger.warning("ws 파일 실체화: 샌드박스에 파일 없음 | path=%s", container_path)
return None
p = PurePosixPath(container_path)
name = p.name
ext = p.suffix.lower()
record = await publish_one(
tenant_id=tenant_id,
conversation_id=conversation_id,
file_name=name,
content=content,
)
if not record or not record.get("file_url"):
# 지어낸 주소로 폼값을 채우지 않는다. 경로가 남는 편이 낫다.
logger.warning("ws 파일 실체화: 주소를 받지 못했다 | path=%s", container_path)
return None
val = {
"path": record["file_url"],
"name": name,
"ext": ext,
# 주소는 만료된다. 이 열쇠로 다시 받는다.
"file_id": str(record.get("file_id") or ""),
"url_expires_at": str(record.get("url_expires_at") or ""),
}
cache[container_path] = val
logger.info("ws 파일 실체화 완료 | %s → 서명 주소", container_path)
return val
async def _walk(node):
if isinstance(node, dict):
for k, v in list(node.items()):
node[k] = await _walk(v)
return node
if isinstance(node, list):
return [await _walk(x) for x in node]
if isinstance(node, str):
s = node.strip()
if s.startswith("/workspace") and _WS_BINARY_FILE_RE.search(s):
r = await _resolve(s)
return r if r is not None else node
return node
try:
obj = await _walk(obj)
except Exception:
logger.warning("ws 파일 실체화: JSON 순회 실패", exc_info=True)
return final_text
return json.dumps(obj, ensure_ascii=False)
async def _publish_chat_artifacts(
tenant_id: str, conversation_id: str, text: str, extra_paths: list[str] | None = None,
) -> tuple[str, list[dict]]:
"""채팅 답변에 남은 샌드박스 산출물을 비공개 버킷에 보관하고, 본문을 받을 수 있는 주소로 바꾼다.
무엇을 어디에 두고 어떤 주소로 내주는지는 SDK 가 모든 에이전트 공용으로 정한다
(`core/chat/artifacts.py`). 여기서는 샌드박스에서 파일을 꺼내 주는 일만 한다.
실패는 베스트에포트다. 산출물을 못 올려도 답변 자체는 그대로 보인다 —
경로가 남는 것이 답변이 통째로 사라지는 것보다 낫다.
"""
from core.chat.artifacts import publish_chat_artifacts
from core.chat.file_links import find_document_paths
if not find_document_paths(text) and not extra_paths:
return text, []
try:
from core.agents.agent import _BASE_DIR as _AGENT_BASE_DIR, _SKILLS_DIR as _AGENT_SKILLS_DIR
from core.sandbox.docker_sandbox import get_or_create_sandbox
except Exception:
logger.warning("채팅 산출물: 모듈 로드 실패", exc_info=True)
return text, []
backend = get_or_create_sandbox(
tenant_id,
workspace_host=_AGENT_BASE_DIR / "workspace",
skills_host=_AGENT_SKILLS_DIR,
)
async def _fetch(container_path: str):
results = await asyncio.to_thread(backend.download_files, [container_path])
res = results[0] if results else None
content = getattr(res, "content", None) if res else None
if content is None or getattr(res, "error", None):
return None
return content
return await publish_chat_artifacts(
tenant_id=tenant_id, conversation_id=conversation_id, text=text, fetch=_fetch,
extra_paths=extra_paths or [],
)
async def _emit_chat_hwpx_artifacts(streamer, tenant_id: str, texts: list[str], collected: set[str] | None = None) -> None:
"""채팅 경로: 스킬이 샌드박스에 만든 hwpx 를 office-mcp 로 실체화(storage 업로드 + HTML 변환)하고,
기존 채팅 파이프라인(onToolEnd → pushHwpxArtifact)이 인식하는 tool_end 이벤트로 내보낸다.
이렇게 하면 채팅 우측 아티팩트 패널에 HwpxViewer(미리보기·편집)가 그대로 뜬다(프론트 무수정).
실패는 베스트에포트."""
if streamer is None:
return
paths: set[str] = set(collected or set())
for txt in texts or []:
if txt:
for m in _HWPX_PATH_RE.findall(txt):
paths.add(m)
if not paths:
return
try:
from core.agents.agent import _BASE_DIR as _AGENT_BASE_DIR, _SKILLS_DIR as _AGENT_SKILLS_DIR
from core.sandbox.docker_sandbox import get_or_create_sandbox
except Exception:
logger.warning("채팅 hwpx: sandbox 모듈 로드 실패", exc_info=True)
return
from pathlib import PurePosixPath
backend = get_or_create_sandbox(
tenant_id,
workspace_host=_AGENT_BASE_DIR / "workspace",
skills_host=_AGENT_SKILLS_DIR,
)
for cp in sorted(paths):
try:
results = await asyncio.to_thread(backend.download_files, [cp])
res = results[0] if results else None
content = getattr(res, "content", None) if res else None
if content is None or getattr(res, "error", None):
continue
name = PurePosixPath(cp).name
out = await _call_office_mcp_tool(
"store_and_render_hwpx",
{"base64_data": base64.b64encode(content).decode("ascii"), "file_name": name, "tenant_id": tenant_id or ""},
)
if not out or not out.get("html_url"):
logger.warning("채팅 hwpx: office-mcp 결과 없음 | path=%s", cp)
continue
await streamer.send_json({"type": "tool_end", "output": out})
logger.info("채팅 hwpx 아티팩트 emit | %s → html_url=%s", cp, out.get("html_url"))
except Exception:
logger.warning("채팅 hwpx 실체화 실패 | path=%s", cp, exc_info=True)
def _rewrites_history(messages_update) -> bool:
"""`[RemoveMessage(REMOVE_ALL), *지난 메시지]` 꼴의 갱신이면 True.
deepagents 의 PatchToolCallsMiddleware 는 지난 턴이 답 없는 도구 호출(예: HITL 질문)로
끝나면, 다음 턴 시작에 대화 기록 전체를 이 꼴로 다시 쓴다. 그 안의 지난 write_file 호출을
이번 턴 것으로 처리하면 지난 파일이 이번 턴 산출물(file_artifact)로 다시 나간다.
"""
from langchain_core.messages import RemoveMessage
from langgraph.graph.message import REMOVE_ALL_MESSAGES
first = messages_update[0] if isinstance(messages_update, list) and messages_update else None
return isinstance(first, RemoveMessage) and first.id == REMOVE_ALL_MESSAGES
def _file_artifact_payload(path: str, content: str | None, op: str) -> dict:
name, ext = _ws_file_meta(path)
text = content if isinstance(content, str) else ""
truncated = False
if len(text.encode("utf-8", errors="replace")) > _FILE_ARTIFACT_MAX_BYTES:
text = text[:_FILE_ARTIFACT_MAX_BYTES]
truncated = True
return {
"type": "file_artifact",
"op": op, # 'create' | 'edit'
"path": str(path),
"name": name,
"ext": ext,
"content": text,
"truncated": truncated,
}
def _handover_agent(row: dict, agents: list) -> dict:
"""이 할 일을 받은 에이전트(이름·id). 방 메시지의 발신자로 쓴다.
이름이 비면 화면이 'agent:<id>' 를 발신자로 보여 준다. 실행 목록에 없으면 users 에서 찾는다.
"""
agent_id = str(row.get("user_id") or "").split(",")[0].strip()
for a in agents or []:
if isinstance(a, dict) and str(a.get("id") or "") == agent_id:
name = a.get("name") or a.get("username") or ""
if name:
return {"id": agent_id, "name": name}
name = str(row.get("username") or "")
if not name and agent_id:
try:
from core.storage.db import get_supabase
res = get_supabase().table("users").select("username").eq("id", agent_id).limit(1).execute()
name = str(((res.data or [{}])[0] or {}).get("username") or "")
except Exception:
logger.warning("인계 에이전트 이름 조회 실패 | agent=%s", agent_id, exc_info=True)
return {"id": agent_id, "name": name}
def _readable_result(text: str) -> str:
"""폼 결과 JSON({"defaultform": {"free_input": "..."}})에서 사람이 읽을 글을 꺼낸다.
할 일 폴러의 최종 답은 폼값 JSON 이다. 그대로 방에 올리면 넘긴 사람이 JSON 원문을 읽게 된다.
"""
raw = (text or "").strip()
try:
obj = json.loads(raw)
except (ValueError, TypeError):
return raw
parts: list[str] = []
def walk(v):
if isinstance(v, str):
if v.strip():
parts.append(v.strip())
elif isinstance(v, dict):
for x in v.values():
walk(x)
elif isinstance(v, list):
for x in v:
walk(x)
walk(obj)
return "\n\n".join(parts) if parts else raw
async def _sync_room_workspace(
tenant_id: str, room_id: str, worktree_state: BranchState | None, files_before: set[str] | None = None,
) -> None:
"""턴이 만든·고친 작업 폴더 파일을 남겨 다음 턴(다른 파드 포함)이 이어서 읽게 한다.
인계 워크트리 방은 방 브랜치에 커밋한다(바뀐 것이 없으면 커밋하지 않는다).
브랜치가 없는 방은 예전처럼 방 폴더를 통째로 올린다. `files_before`(턴 시작의 파일
목록)가 있으면 이번 턴에 지운 파일을 먼저 storage 에서 지운다 — 올리기만 하면 지운
파일이 storage 에 남아 Lite 공유 폴더 변형에서 삭제가 빠진다. 턴 시작에 이 파드에
없던 파일(다른 파드가 만든 것)은 건드리지 않는다. 지우기를 올리기보다 먼저 해, 올린
파일의 새 시각을 보고 끝을 판단하는 Lite 가 삭제 전 목록을 거두지 않게 한다.
"""
room_dir = _bpmn_work_dir()
if not room_dir.exists():
return
_set_storage_tenant_id(tenant_id)
if worktree_state is not None:
res = await asyncio.to_thread(commit_turn, tenant_id, worktree_state, room_dir)
logger.info("워크트리 커밋 | room_id=%s created=%s commit=%s", room_id, res.get("created"), res.get("commit_id"))
return
if files_before:
gone = files_before - workspace_file_set(room_dir)
if gone:
removed = await asyncio.to_thread(remove_workspace_files, room_id, gone)
logger.info("워크스페이스 삭제 반영 | room_id=%s | %s", room_id, removed)
result = await asyncio.to_thread(upload_workspace_directory, room_id, room_dir)
logger.info("워크스페이스 동기화 | room_id=%s | %s", room_id, result.splitlines()[0] if result else "")
async def _post_handover_result(
*, tenant_id: str, room_id: str, todo_id: str, text: str, agent: dict, since_ns: int,
worktree_state: BranchState | None = None, files_before: set[str] | None = None,
) -> None:
"""인계받은 할 일을 마친 결과를 그 방의 에이전트 답으로 남긴다.
할 일 폴러는 결과를 할 일 output 에만 남겨, 일을 넘긴 사람이 방에서 결과를 보고 다음
사람에게 이어 줄 수 없었다. 문서 산출물은 채팅과 같은 규약으로 보관해 `pdfFiles` 로
싣는다 — 방을 열면 작업 폴더와 인계 후보에 뜬다. 작업 폴더는 저장소에 올려, 다음에
이 방에서 일하는 에이전트가 이어서 읽는다.
메시지 키를 할 일 id 로 고정해 다시 실행돼도 한 건만 남는다. 실패는 베스트에포트.
"""
try:
doc_paths = await asyncio.to_thread(_room_document_paths, room_id, since_ns)
content, records = await _publish_chat_artifacts(tenant_id, room_id, _readable_result(text), doc_paths)
except Exception:
logger.warning("인계 결과 산출물 보관 실패 | room=%s", room_id, exc_info=True)
content, records = _readable_result(text), []
try:
await _sync_room_workspace(tenant_id, room_id, worktree_state, files_before)
except Exception:
logger.warning("인계 방 작업 폴더 동기화 실패 | room=%s", room_id, exc_info=True)
message = {
"role": "assistant",
"name": agent.get("name") or "",
"agentId": agent.get("id") or "",
"email": f"agent:{agent.get('id') or ''}",
"content": content,
"contentType": "text",
"timeStamp": datetime.now(timezone.utc).isoformat(),
"uuid": f"handover-result-{todo_id}",
}
if records:
message["pdfFiles"] = [download_file(r) for r in records]
try:
from processgpt_agent_sdk.database import insert_chat_message
await insert_chat_message(
uuid=f"handover-result-{todo_id}", chat_id=room_id, messages=message, tenant_id=tenant_id,
)
await a_set_chat_room_preview(room_id=room_id, text=content)
logger.info("인계 결과를 방에 남김 | room=%s todo=%s 문서=%d", room_id, todo_id, len(records))
except Exception:
logger.warning("인계 결과 방 저장 실패 | room=%s", room_id, exc_info=True)
def _room_document_paths(chat_room_id: str, since_ns: int) -> list[str]:
"""이번 턴에 작업 폴더에 생긴 문서 산출물(docx·pdf 등)의 컨테이너 경로.
docx·pdf 는 바이너리라 `write_file` 스트림(텍스트)으로는 화면에 뜨지 않는다. 그래서
예전에는 **답변 본문에 경로가 적혔을 때만** 사용자에게 갔다 — 모델이 경로를 적지 않은
턴의 문서는 만들어졌다는 말만 남고 받을 길이 없었다. 글이 아니라 폴더를 본다.
"""
try:
from core.chat.file_links import find_room_documents
from core.skills.tools import (
_conv_slug,
bpmn_container_base as _bcb,
tenant_workspace_root,
)
except Exception:
logger.warning("문서 산출물 스캔: 모듈 로드 실패", exc_info=True)
return []
slug = _conv_slug(chat_room_id or "")
if not slug:
return []
try:
room_host = tenant_workspace_root() / ".bpmn" / slug
return find_room_documents(room_host, _bcb(chat_room_id or ""), since_ns=since_ns)
except Exception:
logger.warning("문서 산출물 스캔 실패 | room=%s", chat_room_id, exc_info=True)
return []
def _document_artifact_payload(record: dict) -> dict | None:
"""산출물 레코드를 작업 폴더가 읽는 `file_artifact` 로 옮긴다.
텍스트 산출물과 달리 내용을 싣지 않는다 — 바이너리는 화면이 렌더할 수 없고, 받을 수만
있으면 된다. 대신 서명 주소와 `file_id` 를 싣는다. 주소는 한 시간이면 죽지만 파일은
남아 있어서, 화면이 그 열쇠로 새 주소를 받아 간다.
"""
url = str(record.get("file_url") or "")
if not url:
return None
name = str(record.get("file_name") or "")
path = str(record.get("source_path") or "") or f"/workspace/{name}"
path_name, ext = _ws_file_meta(path)
return {
"type": "file_artifact",
"op": "create",
"path": path,
"name": name or path_name,
"ext": ext,
# 바이너리는 미리보기 내용이 없다. 화면은 url 로 받거나(미리보기 불가 형식)
# 주소를 그대로 그린다(pdf·이미지).
"content": "",
"truncated": False,
"url": url,
"file_id": str(record.get("file_id") or ""),
"url_expires_at": str(record.get("url_expires_at") or ""),
"content_type": str(record.get("content_type") or ""),
"size_bytes": record.get("size_bytes") or 0,
}
CHAT_ERROR_PREFIX = "⚠️ 오류가 발생했습니다: "
def _chat_error_display_text(error_text: str, partial_text: str = "") -> str:
"""오류로 끝난 턴의 assistant 본문. 부분 응답이 있으면 살려서 뒤에 오류를 붙인다."""
partial = (partial_text or "").strip()
display = f"{CHAT_ERROR_PREFIX}{error_text or '에이전트 응답 오류'}"
return f"{partial}\n\n{display}" if partial else display
async def _persist_chat_error_message(
context: RequestContext,
*,
task_id: str,
context_id: str,
error_text: str,
partial_text: str = "",
) -> None:
"""오류로 끝난 채팅 턴도 assistant 메시지를 chats 에 남긴다.
오류를 SSE 로만 보내면 화면에는 보이지만 DB 에는 아무 것도 남지 않는다. 그래서
새로고침하거나 방에 다시 들어오면 사용자 질문만 있고 답은 아예 오지 않은 것처럼
보인다 — 실제로 그랬다. 성공 턴과 같은 저장 경로(SDK persist_chat_to_db)를 쓰고,
프론트가 보낸 response_message_uuid 로 upsert 하므로 같은 턴이 두 row 로
갈라지지도 않는다.
"""
req = getattr(context, "req", None)
if req is None:
# 프로세스/워크리스트 경로(ChatRequestContext 가 아님) — chats 저장 대상이 아니다.
return
display = _chat_error_display_text(error_text, partial_text)
evt = new_text_artifact_update_event(
task_id=task_id,
context_id=context_id,
name="assistant_response",
text=display,
last_chunk=True,
)
ParseDict({"role": "assistant", "isError": True, "error": error_text}, evt.metadata)
await persist_chat_to_db(req, evt, display)
async def _emit_document_artifacts(streamer, records: list[dict]) -> None:
"""거둔 문서 산출물을 작업 폴더 목록에 띄운다. 실패는 베스트에포트."""
if streamer is None:
return
for record in records or []:
payload = _document_artifact_payload(record)
if payload is None:
continue
try:
await streamer.send_json(payload)
logger.info("문서 산출물 작업 폴더 emit | %s", payload["path"])
except Exception:
logger.warning("문서 산출물 emit 실패 | %s", payload.get("path"), exc_info=True)
# 응답이 "병합 요청(PR)을 올렸다"고 보고하는지 판단할 표식.
# PR 을 올린 턴은 저장 버튼을 누를 일이 없으므로 기본 안내 문구로 덮어쓰면 안 된다.
_PULL_REQUEST_MARKERS = (
"PR created",
"pull/",
"merge_requests/",
"PR #",
"병합 요청",
"병합해 주세요",
)
def _reports_pull_request(text: str | None) -> bool:
"""응답 본문이 PR 생성 결과를 알리고 있으면 True."""
body = text or ""
return any(marker in body for marker in _PULL_REQUEST_MARKERS)
async def _reemit_room_artifacts(streamer, chat_room_id: str) -> None:
"""검증/완료 후 방의 모든 산출물 파일을 file_artifact(edit)로 재전송한다.
complete 가 결정적으로 만든 forms/·skills/·manifest.json 등은 에이전트의 write_file
스트림을 거치지 않아 프론트 패널에 안 떠 저장도 누락됐다. 여기서 전부 다시 보내
패널 표시 + 저장 대상에 포함되게 한다."""
if streamer is None:
return
try:
from core.skills.tools import (
bpmn_container_base as _bcb,
_conv_slug,
process_work_dirs,
tenant_workspace_root,
)
except Exception:
return
base_container = _bcb(chat_room_id or "") # /workspace/.bpmn/<slug>
slug = _conv_slug(chat_room_id or "")
bpmn_host = tenant_workspace_root() / ".bpmn"
room_host = bpmn_host / slug if slug else bpmn_host
if not room_host.exists():
return
# 프로세스 폴더들 + (단독 스킬용) 방 base 자체를 항상 포함해 base 바로 아래 skills/ 도 스캔한다.
proc_dirs = process_work_dirs(room_host, chat_room_id or "")
if room_host not in proc_dirs:
proc_dirs.append(room_host)
seen: set = set()
previewable_suffixes = {".bpmn", ".json", ".md", ".markdown", ".html", ".htm", ".form", ".xml", ".dmn", ".yaml", ".yml", ".txt", ".csv"}
excluded_names = {".process-validation.json", "validation-report.md"}
for pdir in proc_dirs:
# 최종 산출물은 특정 파일명만 열거하지 않고 지원 형식을 재전송한다. 그래야 모델이
# 추가로 만든 Markdown/HTML/JSON도 라이브 표시와 새로고침 복원에서 누락되지 않는다.
# 방 루트는 stale process-*까지 재귀하지 않고 단독 산출물과 skills만 스캔한다.
if pdir == room_host:
candidates = [fp for fp in pdir.iterdir() if fp.is_file()]
if (pdir / "skills").is_dir():
candidates += list((pdir / "skills").rglob("*"))
else:
candidates = list(pdir.rglob("*"))
targets = sorted(
fp for fp in candidates
if fp.is_file()
and (fp.suffix.lower() in previewable_suffixes or fp.name in {"process-definition.json", "manifest.json"})
and fp.name.lower() not in excluded_names
)
for hp in targets:
try:
key = hp.as_posix()
if key in seen:
continue
seen.add(key)
rel = hp.relative_to(room_host).as_posix()
cpath = f"{base_container}/{rel}"
# replay: 이번 턴에 고친 것이 아니라 패널 표시·저장을 위해 다시 보내는 것이다.
# 화면(Lite)은 이 표시로 방에 있던 메모(.md)를 이번 턴의 산출물 카드로 착각하지 않는다.
await streamer.send_json({**_file_artifact_payload(cpath, hp.read_text(encoding="utf-8"), "edit"), "replay": True})
except Exception:
continue
# 결정론적 실행 카드의 crew_type. `result` 를 쓰면 안 된다 — 프론트는 그 값을 "제출할
# 수 있는 산출물"로 읽어 채택 버튼을 붙이고(`EventTimeline.isSubmittableTask`), 생성기는
# 표본의 폼 산출물을 그 값으로 찾는다. 이 카드가 싣는 것은 폼 값이 아니라 실행 방식과
# 도구 호출 결과라서, `result` 로 두면 채택 버튼이 둘이 되고 그중 하나는 누르는 순간
# 폼에 실행 로그 JSON 을 밀어 넣는다. 폼 값은 뒤따르는 `최종 결과 반환` 이 싣는다.
_DETERMINISTIC_CARD_CREW_TYPE = "deterministic"
async def _enqueue_status(
event_queue: EventQueue,
*,
task_id: str,
context_id: str,
state: TaskState,
text: str,
event_type: str,
job_id: str,
crew_type: Optional[str] = "deepagents"
) -> None:
evt = new_text_status_update_event(task_id=task_id, context_id=context_id, state=state, text=text)
ParseDict({"event_type": event_type, "job_id": job_id, "crew_type": crew_type}, evt.metadata)
await event_queue.enqueue_event(evt)
async def _emit_human_asked(
event_queue: EventQueue,
*,
task_id: str,
context_id: str,
interrupt_payload: dict[str, Any],
run_state: dict[str, Any],
checkpoint_thread_id: str,
job_id: str,
streamer: Any = None,
) -> dict[str, Any]:
question = (
interrupt_payload.get("question") if isinstance(interrupt_payload, dict) else None
) or "이 작업을 계속 진행하려면 추가 입력이 필요합니다."
context_text = (
interrupt_payload.get("context", "") if isinstance(interrupt_payload, dict) else ""
)
options_payload = (
interrupt_payload.get("options") if isinstance(interrupt_payload, dict) else None
)
multi_select_payload = bool(
interrupt_payload.get("multi_select") if isinstance(interrupt_payload, dict) else False
)
pending_field = "human_response"
is_duplicate = is_duplicate_hitl_request(
run_state, question=question, pending_field=pending_field
)
new_run_state = {
"pending_field": pending_field,
"tool_name": "request_human_input",
"last_question": question,
"checkpoint_thread_id": checkpoint_thread_id or "",
}
# 이 턴은 여기서 끝나고 방은 사람의 답을 기다린다 — 두 갈래 모두 마찬가지다.
_mark_awaiting_human(context_id)
if is_duplicate:
# 같은 질문을 다시 물은 경우다. 여기서 done 마커만 보내고 끝내면 어시스턴트 메시지가
# 하나도 남지 않아, 사용자 화면에는 "답변했는데 아무 반응이 없는" 멈춘 상태로 보인다.
# 억제(= 새 run_state 로 갱신하지 않음)는 유지하되, 질문 본문은 반드시 남겨 사용자가
# 다시 답할 수 있게 한다.
logger.info("중복 HITL 요청 억제 | task_id=%s question=%.80s", task_id, question)
if streamer:
hitl_content = json.dumps(
{
"type": "human_input_required",
"question": question,
"context": context_text,
"options": options_payload or [],
"multi_select": multi_select_payload,
"run_state": new_run_state,
},
ensure_ascii=False,