aidev-bkplugin 2.2.2rc51__tar.gz → 2.2.2rc58__tar.gz

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.
Files changed (110) hide show
  1. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/PKG-INFO +2 -2
  2. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/apps.py +1 -1
  3. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/services/approval_resume.py +42 -4
  4. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/services/otel_metrics.py +7 -10
  5. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/tasks.py +1 -1
  6. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/views/session.py +79 -15
  7. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/pyproject.toml +2 -2
  8. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/services/test_otel_metrics.py +5 -5
  9. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/test_apps.py +12 -9
  10. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/test_management_metrics.py +10 -8
  11. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/views/test_session_pv_files_views.py +112 -20
  12. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/views/test_session_view.py +136 -0
  13. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/__init__.py +0 -0
  14. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/constants.py +0 -0
  15. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/enums.py +0 -0
  16. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/management/__init__.py +0 -0
  17. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/management/commands/__init__.py +0 -0
  18. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/management/commands/upgrade_sessions.py +0 -0
  19. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/migrations/0001_initial.py +0 -0
  20. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/migrations/0002_event_delivery.py +0 -0
  21. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/migrations/__init__.py +0 -0
  22. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/models.py +0 -0
  23. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/openapi/__init__.py +0 -0
  24. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/openapi/urls.py +0 -0
  25. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/openapi/views.py +0 -0
  26. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/packages/__init__.py +0 -0
  27. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/packages/apigw/__init__.py +0 -0
  28. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/packages/apigw/permissions.py +0 -0
  29. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/packages/checkpoint/__init__.py +0 -0
  30. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/packages/checkpoint/bk_django_saver.py +0 -0
  31. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/packages/drf/__init__.py +0 -0
  32. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/packages/drf/authentication.py +0 -0
  33. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/packages/drf/decorators.py +0 -0
  34. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/packages/drf/exception.py +0 -0
  35. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/packages/drf/renderers.py +0 -0
  36. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/permissions.py +0 -0
  37. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/private/__init__.py +0 -0
  38. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/private/permissions.py +0 -0
  39. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/private/urls.py +0 -0
  40. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/private/views.py +0 -0
  41. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/serializers/__init__.py +0 -0
  42. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/serializers/agent.py +0 -0
  43. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/serializers/chat_completion.py +0 -0
  44. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/serializers/llm.py +0 -0
  45. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/serializers/user_operation.py +0 -0
  46. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/services/__init__.py +0 -0
  47. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/services/agent_bkplugin.py +0 -0
  48. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/services/agent_builder.py +0 -0
  49. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/services/agent_config.py +0 -0
  50. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/services/agent_execution.py +0 -0
  51. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/services/agent_helpers.py +0 -0
  52. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/services/agent_session.py +0 -0
  53. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/services/chat_tracing.py +0 -0
  54. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/services/database_event_bus.py +0 -0
  55. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/services/event_resource_manager.py +0 -0
  56. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/services/event_tracing.py +0 -0
  57. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/services/execution.py +0 -0
  58. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/services/llm.py +0 -0
  59. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/services/metric_runtime.py +0 -0
  60. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/services/user_operation.py +0 -0
  61. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/settings.py +0 -0
  62. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/urls.py +0 -0
  63. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/utils.py +0 -0
  64. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/views/__init__.py +0 -0
  65. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/views/agent.py +0 -0
  66. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/views/base.py +0 -0
  67. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/views/chat.py +0 -0
  68. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/views/chat_group.py +0 -0
  69. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/views/flow_agent.py +0 -0
  70. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/views/llm.py +0 -0
  71. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/aidev_bkplugin/views/user_operation.py +0 -0
  72. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/readme.md +0 -0
  73. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/__init__.py +0 -0
  74. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/apps.py +0 -0
  75. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/conftest.py +0 -0
  76. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/database_events/__init__.py +0 -0
  77. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/database_events/conftest.py +0 -0
  78. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/database_events/test_bus.py +0 -0
  79. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/database_events/test_resource_manager.py +0 -0
  80. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/database_events/test_tracing.py +0 -0
  81. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/packages/__init__.py +0 -0
  82. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/packages/drf/test_renderers_trace.py +0 -0
  83. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/packages/test_bk_django_saver.py +0 -0
  84. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/packages/test_bk_django_saver_async.py +0 -0
  85. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/private/__init__.py +0 -0
  86. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/private/test_private_views.py +0 -0
  87. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/services/__init__.py +0 -0
  88. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/services/agent/__init__.py +0 -0
  89. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/services/agent/conftest.py +0 -0
  90. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/services/agent/test_agent_config_fetcher.py +0 -0
  91. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/services/agent/test_builder.py +0 -0
  92. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/services/agent/test_session_manager.py +0 -0
  93. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/services/test_agent_completion.py +0 -0
  94. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/services/test_agui_handler.py +0 -0
  95. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/services/test_approval_resume.py +0 -0
  96. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/services/test_approval_resume_tracing.py +0 -0
  97. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/services/test_bkplugin.py +0 -0
  98. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/services/test_execution.py +0 -0
  99. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/services/test_llm.py +0 -0
  100. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/services/test_resume_consumer.py +0 -0
  101. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/services/test_thread_chat_completion.py +0 -0
  102. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/services/test_user_operation.py +0 -0
  103. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/settings.py +0 -0
  104. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/test_constants.py +0 -0
  105. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/views/__init__.py +0 -0
  106. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/views/test_agent_view.py +0 -0
  107. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/views/test_chat_agent_code_propagation.py +0 -0
  108. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/views/test_chat_completion_serializer.py +0 -0
  109. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/views/test_chat_flow_agent.py +0 -0
  110. {aidev_bkplugin-2.2.2rc51 → aidev_bkplugin-2.2.2rc58}/tests/views/test_chat_stream_status.py +0 -0
@@ -1,9 +1,9 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: aidev-bkplugin
3
- Version: 2.2.2rc51
3
+ Version: 2.2.2rc58
4
4
  Summary: AiDev Agent Bkplugin builtin functions
5
5
  Requires-Python: <3.12,>=3.11
6
- Requires-Dist: aidev-agent>=2.2.2rc51
6
+ Requires-Dist: aidev-agent>=2.2.2rc58
7
7
  Requires-Dist: blueapps<5.0,>=4.15.1
8
8
  Requires-Dist: django<5.0,>=4.2.28
9
9
  Provides-Extra: opentelemetry
@@ -175,7 +175,7 @@ def init_bk_aidev_agent_otel() -> None:
175
175
  agent_info.get("agent_name"),
176
176
  agent_info.get("agent_sdk_version"),
177
177
  )
178
- if metric_settings.export_via_celery:
178
+ if metric_settings.has_bkm_config:
179
179
  metric_service = BkPluginMetricService(
180
180
  service_name=otel_config.service_name,
181
181
  endpoints=endpoints,
@@ -60,8 +60,12 @@ def _approval_resume_worker(session_code: str, username: str, graph_thread_id: s
60
60
  username,
61
61
  )
62
62
 
63
- # 1. 轮询是否需要续流(ITSM 回调后 is_resume 返回 True),无超时,收到回调前持续轮询
64
- handler = ApprovalStateHandler()
63
+ # 0. 轮询 handler:ApprovalStateHandler 直连平台 API(U-01 重构后自持数据访问,
64
+ # 不再收 resource_manager),username 预留 X-BKAIDEV-USER header 位。
65
+ # 注意:agent 构造保持在轮询**之后**——chat_history 须在回调落地后加载,
66
+ # 否则 resume 的 terminal_interrupt_ids 判定用的是回调前的陈旧记录,
67
+ # 已批中断不被排除而被重推(UAT:重推未 enrich 的北京审批卡)。
68
+ handler = ApprovalStateHandler(username=username)
65
69
  poll_count = 0
66
70
  while True:
67
71
  poll_count += 1
@@ -94,11 +98,38 @@ def _approval_resume_worker(session_code: str, username: str, graph_thread_id: s
94
98
  propagated_trace_context(approve_info.get("approval_trace_context")),
95
99
  recording_span("bkplugin.approval.resume", record_exception=False),
96
100
  ):
97
- _resume_approval(session_code, username, graph_thread_id, interrupts, approve_result)
101
+ _resume_approval(session_code, username, graph_thread_id, interrupts, approve_info)
98
102
 
99
103
 
100
- def _resume_approval(session_code, username, graph_thread_id, interrupts, approve_result):
104
+ def _resume_approval(
105
+ session_code: str,
106
+ username: str,
107
+ graph_thread_id: str,
108
+ interrupts: list[dict],
109
+ approve_info: dict,
110
+ ) -> None:
111
+ """审批回调后构建 agent 并后台续流(须在回调 trace 上下文内调用)。
112
+
113
+ Args:
114
+ session_code: 会话码。
115
+ username: 会话主人(续流执行身份)。
116
+ graph_thread_id: 图线程 id。
117
+ interrupts: 触发续流的 pending interrupts(来自 pending_interrupt 上下文)。
118
+ approve_info: ``ApprovalStateHandler.fetch_approve_result`` 富返回,
119
+ 含 ``approve_result`` 与本回调已终态审批的 ``interrupts``。
120
+ """
121
+ approve_result = approve_info["approve_result"]
122
+
101
123
  try:
124
+ # 串行语义:只 resume 本回调已终态的审批(approve_info.interrupts 元素 id
125
+ # 即该审批的 interrupt id)。其余 pending(工单未建/未回调)保持挂起——
126
+ # 全量 hydrate 会把未批的审批也标记 approved,串行门禁会拦下整个 resume,
127
+ # 图不拉起、下一张工单永远建不出来(UAT:第二次审批死锁)。
128
+ approved_ids = {
129
+ element.get("id")
130
+ for element in (approve_info.get("interrupts") or [])
131
+ if isinstance(element, dict) and element.get("id")
132
+ }
102
133
  resume_items = []
103
134
  for interrupt in interrupts:
104
135
  if not isinstance(interrupt, dict):
@@ -106,6 +137,8 @@ def _resume_approval(session_code, username, graph_thread_id, interrupts, approv
106
137
  interrupt_id = interrupt.get("id") or interrupt.get("interruptId")
107
138
  if not interrupt_id:
108
139
  continue
140
+ if approved_ids and interrupt_id not in approved_ids:
141
+ continue # 非本回调审批:保持挂起,等其自身工单终态
109
142
  # status / payload.approved 由 hydrate_resume_payload 根据三态统一填充
110
143
  resume_items.append({"interruptId": interrupt_id})
111
144
 
@@ -118,6 +151,8 @@ def _resume_approval(session_code, username, graph_thread_id, interrupts, approv
118
151
 
119
152
  ApprovalStateHandler.hydrate_resume_payload(resume_items, approve_result)
120
153
 
154
+ # 回调后构建 agent:chat_history 加载到回调后的最新记录(含已批终态),
155
+ # resume 侧 terminal 判定 / enrich 复用才能拿到正确数据
121
156
  builder = AgentBuilder(username=username)
122
157
  agent_instance = builder.by_session_code(session_code)
123
158
 
@@ -127,6 +162,9 @@ def _resume_approval(session_code, username, graph_thread_id, interrupts, approv
127
162
  thread_id=graph_thread_id,
128
163
  resume=resume_items,
129
164
  caller_trace_context=trace_headers(),
165
+ # 不传 executor:审批 approvers 来自工具审批配置(ItsmTicketCreator 读
166
+ # target.approval.approvers),与调用人无关——提单人(username)不可成为
167
+ # 审批身份(禁止自审批)。缺省时建单请求不带 X-BKAIDEV-USER 头。
130
168
  # 后台 drain(无 SSE 下游,下方 for _ in generator 自行排空):标记 background_only,
131
169
  # 使消费者读到 EOD 时不立即清理队列,保留缓存历史供前端在清理窗口内接管续流。
132
170
  background_only=True,
@@ -80,7 +80,6 @@ class MetricExportSettings:
80
80
  enabled: bool
81
81
  export_interval_millis: int = DEFAULT_METRIC_EXPORT_INTERVAL_MILLIS
82
82
  export_timeout_millis: int = 30000
83
- export_via_celery: bool = True
84
83
  bkm_push_mode: str = BKM_PUSH_MODE_CELERY
85
84
  bkm_data_id: int | None = None
86
85
  bkm_access_token: str = ""
@@ -88,6 +87,11 @@ class MetricExportSettings:
88
87
  bkm_target: str = ""
89
88
  task_ttl_seconds: int = DEFAULT_METRIC_TASK_TTL_SECONDS
90
89
 
90
+ @property
91
+ def has_bkm_config(self) -> bool:
92
+ """Whether all credentials required for BKM export are configured."""
93
+ return self.bkm_data_id is not None and bool(self.bkm_access_token and self.bkm_push_url)
94
+
91
95
  @classmethod
92
96
  def from_agent_info(cls, agent_info: dict[str, Any] | None, *, default_enabled: bool) -> "MetricExportSettings":
93
97
  otel_info = (agent_info or {}).get("otel_info") or {}
@@ -105,10 +109,6 @@ class MetricExportSettings:
105
109
  task_ttl_seconds = agent_settings.BKAI_AGENT_METRICS_TASK_TTL_SECONDS
106
110
  if task_ttl_seconds is None:
107
111
  task_ttl_seconds = metrics_info.get("task_ttl_seconds", DEFAULT_METRIC_TASK_TTL_SECONDS)
108
- export_via_celery = metrics_info.get(
109
- "export_via_celery",
110
- otel_info.get("metric_export_via_celery"),
111
- )
112
112
  bkm_push_mode = agent_settings.BKAI_AGENT_METRICS_PUSH_MODE
113
113
  if bkm_push_mode is None:
114
114
  bkm_push_mode = metrics_info.get(
@@ -126,8 +126,6 @@ class MetricExportSettings:
126
126
  push_url = _normalize_bkm_push_url(push_url)
127
127
  target = agent_settings.BKAI_AGENT_METRICS_TARGET or metrics_info.get("agent_target", "")
128
128
  has_bkm_config = data_id not in (None, "") and bool(access_token and push_url)
129
- if export_via_celery is None:
130
- export_via_celery = has_bkm_config
131
129
  environment_enabled = agent_settings.BKAI_AGENT_ENABLE_METRICS
132
130
  enabled = (
133
131
  environment_enabled
@@ -139,7 +137,6 @@ class MetricExportSettings:
139
137
  export_interval_millis=max(10_000, int(interval)),
140
138
  export_timeout_millis=max(1000, int(timeout)),
141
139
  task_ttl_seconds=max(1, int(task_ttl_seconds)),
142
- export_via_celery=_as_bool(export_via_celery),
143
140
  bkm_push_mode=bkm_push_mode,
144
141
  bkm_data_id=int(data_id) if data_id not in (None, "") else None,
145
142
  bkm_access_token=str(access_token or ""),
@@ -370,7 +367,7 @@ class BkPluginMetricService:
370
367
  logger.info("[aidev_bkplugin] metric export disabled")
371
368
  return False
372
369
  readers = []
373
- if self.settings.export_via_celery:
370
+ if self.settings.has_bkm_config:
374
371
  if self.settings.bkm_push_mode == BKM_PUSH_MODE_CELERY and self.enqueue_bkm_metrics is None:
375
372
  logger.warning("[aidev_bkplugin] BKM metric export enabled but Celery enqueue is unavailable")
376
373
  return False
@@ -406,7 +403,7 @@ class BkPluginMetricService:
406
403
  self.provider.shutdown()
407
404
  self.provider = None
408
405
  return False
409
- transport = f"bkm_{self.settings.bkm_push_mode}" if self.settings.export_via_celery else "otlp_direct"
406
+ transport = f"bkm_{self.settings.bkm_push_mode}" if self.settings.has_bkm_config else "otlp_direct"
410
407
  logger.info(
411
408
  "[aidev_bkplugin] metric export started with %d reader(s), transport=%s",
412
409
  len(readers),
@@ -19,7 +19,7 @@ logger = logging.getLogger(__name__)
19
19
  @shared_task(
20
20
  name="aidev_bkplugin.push_bkm_metrics",
21
21
  ignore_result=True,
22
- queue=agent_settings.BKAI_AGENT_TASK,
22
+ queue=agent_settings.BKAI_AGENT_QUEUE_METRIC,
23
23
  autoretry_for=(RetryableMetricPushError,),
24
24
  retry_backoff=True,
25
25
  retry_jitter=True,
@@ -5,18 +5,22 @@ from aidev_agent.services.messages_handler import GeneratorStreamingHelper
5
5
  from aidev_agent.services.messages_handler.constants import TimeoutConfig
6
6
  from aidev_agent.services.messages_handler.factory import message_handler_factory
7
7
  from aidev_agent.services.sandbox_pv_files import (
8
+ IMAGE_DOWNLOAD_URL_EXPIRES_IN,
8
9
  SandboxFileError,
9
10
  SandboxFileInvalidArgumentError,
10
11
  SandboxFileInvalidRequestError,
11
12
  SandboxFileNotFoundError,
12
13
  SandboxPvFileService,
14
+ fill_user_image_urls,
15
+ iter_user_images_missing_url,
16
+ validate_session_upload_files,
13
17
  )
14
18
  from bkapi_client_core.exceptions import HTTPResponseError
15
- from blueapps.core.exceptions import ClientBlueException
19
+ from blueapps.core.exceptions import ClientBlueException, ResourceNotFound, ServerBlueException
16
20
  from django.conf import settings
17
21
  from django.http import HttpResponse
18
22
  from rest_framework.decorators import action
19
- from rest_framework.parsers import FileUploadParser
23
+ from rest_framework.parsers import FileUploadParser, MultiPartParser
20
24
  from rest_framework.views import Response
21
25
 
22
26
  from aidev_bkplugin.constants import AGUI_PROTOCOL_VERSION, DEFAULT_SESSION_PAGE, DEFAULT_SESSION_PAGE_SIZE
@@ -136,15 +140,13 @@ class ChatSessionViewSet(PluginViewSet):
136
140
  # ------------------------------------------------------------------
137
141
 
138
142
  @staticmethod
139
- def _pv_exc_to_response(exc: SandboxFileError) -> Response:
140
- """沙箱文件异常 → HTTP 响应。"""
143
+ def _raise_pv_exc(exc: SandboxFileError) -> None:
144
+ """沙箱文件异常 → blueapps 异常,与 path is required 等入口同一套信封。"""
141
145
  if isinstance(exc, SandboxFileNotFoundError):
142
- status_code = 404
143
- elif isinstance(exc, (SandboxFileInvalidArgumentError, SandboxFileInvalidRequestError)):
144
- status_code = 400
145
- else:
146
- status_code = 500
147
- return Response(data={"message": str(exc)}, status=status_code)
146
+ raise ResourceNotFound(message=str(exc)) from exc
147
+ if isinstance(exc, (SandboxFileInvalidArgumentError, SandboxFileInvalidRequestError)):
148
+ raise ClientBlueException(message=str(exc)) from exc
149
+ raise ServerBlueException(message=str(exc)) from exc
148
150
 
149
151
  def _check_session_owner(self, request, session_code: str, require_access: bool = False) -> None:
150
152
  """校验 session 归属
@@ -215,6 +217,21 @@ class ChatSessionViewSet(PluginViewSet):
215
217
 
216
218
  return SandboxPvFileService(resource_manager=rm, executor_info=executor_info)
217
219
 
220
+ @staticmethod
221
+ def _resolve_upload_snapshot(rm) -> str:
222
+ """走平台 image 表查询:取 file-kit 已构建成功的最新镜像。"""
223
+ try:
224
+ result = rm.get_client().api.retrieve_latest_skill_version_image()
225
+ except Exception:
226
+ logger.exception("[pv_files] resolve_upload_snapshot 调平台失败")
227
+ raise
228
+ data = result.get("data") if isinstance(result, dict) else None
229
+ image = data.get("image") if isinstance(data, dict) else ""
230
+ image = image.strip() if isinstance(image, str) else ""
231
+ if not image:
232
+ logger.warning("[pv_files] resolve_upload_snapshot empty")
233
+ return image
234
+
218
235
  @action(["GET"], url_path="pv_files", detail=True)
219
236
  def pv_files(self, request, pk, **kwargs):
220
237
  self._check_session_owner(request, pk, require_access=False)
@@ -228,7 +245,7 @@ class ChatSessionViewSet(PluginViewSet):
228
245
  until=None,
229
246
  )
230
247
  except SandboxFileError as exc:
231
- return self._pv_exc_to_response(exc)
248
+ self._raise_pv_exc(exc)
232
249
  return Response(data=data)
233
250
 
234
251
  @action(["GET"], url_path="pv_files/stat", detail=True)
@@ -240,7 +257,7 @@ class ChatSessionViewSet(PluginViewSet):
240
257
  try:
241
258
  data = self._make_pv_file_service(request).stat_file(session_code=pk, path=path)
242
259
  except SandboxFileError as exc:
243
- return self._pv_exc_to_response(exc)
260
+ self._raise_pv_exc(exc)
244
261
  return Response(data=data)
245
262
 
246
263
  @action(["GET"], url_path="pv_files/preview", detail=True)
@@ -255,7 +272,7 @@ class ChatSessionViewSet(PluginViewSet):
255
272
  session_code=pk, path=path, max_bytes=max_bytes
256
273
  )
257
274
  except SandboxFileError as exc:
258
- return self._pv_exc_to_response(exc)
275
+ self._raise_pv_exc(exc)
259
276
  response = HttpResponse(content, content_type="text/plain; charset=utf-8")
260
277
  response["X-Truncated"] = "true" if truncated else "false"
261
278
  return response
@@ -272,14 +289,61 @@ class ChatSessionViewSet(PluginViewSet):
272
289
  session_code=pk, path=path, expires_in=expires_in
273
290
  )
274
291
  except SandboxFileError as exc:
275
- return self._pv_exc_to_response(exc)
292
+ self._raise_pv_exc(exc)
293
+ return Response(data=data)
294
+
295
+ @action(
296
+ ["POST"],
297
+ url_path="pv_files/upload",
298
+ detail=True,
299
+ parser_classes=[MultiPartParser],
300
+ )
301
+ def pv_files_upload(self, request, pk, **kwargs):
302
+ """批量上传文件到会话 PV。"""
303
+ self._check_session_owner(request, pk, require_access=True)
304
+ uploaded_files = request.FILES.getlist("files")
305
+ files = [
306
+ {
307
+ "name": upload_file.name,
308
+ "content": upload_file.read(),
309
+ "mime_type": upload_file.content_type or "application/octet-stream",
310
+ }
311
+ for upload_file in uploaded_files
312
+ ]
313
+ try:
314
+ validate_session_upload_files(files)
315
+ except SandboxFileError as exc:
316
+ self._raise_pv_exc(exc)
317
+
318
+ svc = self._make_pv_file_service(request)
319
+ snapshot = self._resolve_upload_snapshot(PluginResourceManager(username=request.user.username))
320
+ if snapshot:
321
+ svc._executor_info["snapshot"] = snapshot
322
+ try:
323
+ data = svc.upload_files(session_code=pk, files=files)
324
+ except SandboxFileError as exc:
325
+ self._raise_pv_exc(exc)
276
326
  return Response(data=data)
277
327
 
278
328
 
329
+ def _copy_session_content_payload(data):
330
+ """复制写消息 payload,避免改写原始 request.data。"""
331
+ if not isinstance(data, dict):
332
+ return data
333
+ payload = dict(data)
334
+ content = payload.get("content")
335
+ if isinstance(content, list):
336
+ payload["content"] = [dict(item) if isinstance(item, dict) else item for item in content]
337
+ return payload
338
+
339
+
279
340
  class ChatSessionContentViewSet(PluginViewSet):
280
341
  def create(self, request):
281
342
  username = request.user.username
282
- result = self.client.api.create_chat_session_content(json=request.data, headers={"X-BKAIDEV-USER": username})
343
+ payload = _copy_session_content_payload(request.data)
344
+ if isinstance(payload, dict) and any(iter_user_images_missing_url(payload)):
345
+ fill_user_image_urls(ChatSessionViewSet._make_pv_file_service(self, request), payload)
346
+ result = self.client.api.create_chat_session_content(json=payload, headers={"X-BKAIDEV-USER": username})
283
347
  return Response(data=result["data"])
284
348
 
285
349
  @action(["GET"], url_path="content", detail=False)
@@ -1,11 +1,11 @@
1
1
  [project]
2
2
  name = "aidev-bkplugin"
3
- version = "2.2.2rc51"
3
+ version = "2.2.2rc58"
4
4
  description = "AiDev Agent Bkplugin builtin functions"
5
5
  readme = "readme.md"
6
6
  requires-python = "<3.12,>=3.11"
7
7
  dependencies = [
8
- "aidev-agent>=2.2.2rc51",
8
+ "aidev-agent>=2.2.2rc58",
9
9
  "blueapps>=4.15.1, <5.0",
10
10
  "django>=4.2.28,<5.0",
11
11
  ]
@@ -161,7 +161,7 @@ def test_metric_settings_parse_nested_otel_info():
161
161
  assert settings.export_interval_millis == 10_000
162
162
  assert settings.export_timeout_millis == 7000
163
163
  assert settings.task_ttl_seconds == 120
164
- assert settings.export_via_celery is True
164
+ assert settings.has_bkm_config is True
165
165
  assert settings.bkm_data_id == 1001
166
166
  assert settings.bkm_access_token == "metric-secret"
167
167
  assert settings.bkm_push_url == "http://proxy:10205/v2/push/"
@@ -226,7 +226,7 @@ def test_metric_settings_use_local_environment_fallback(monkeypatch):
226
226
  assert settings.bkm_access_token == "local-secret"
227
227
  assert settings.bkm_push_url == "http://local-proxy:10205/v2/push/"
228
228
  assert settings.bkm_target == "local-target"
229
- assert settings.export_via_celery is True
229
+ assert settings.has_bkm_config is True
230
230
  assert settings.export_interval_millis == 25_000
231
231
  assert settings.bkm_push_mode == BKM_PUSH_MODE_DIRECT
232
232
  assert settings.task_ttl_seconds == 1800
@@ -239,7 +239,7 @@ def test_metric_settings_keep_direct_otlp_transport_without_bkm_config():
239
239
  assert settings.export_interval_millis == 10_000
240
240
  assert settings.bkm_push_mode == BKM_PUSH_MODE_CELERY
241
241
  assert settings.task_ttl_seconds == 3600
242
- assert settings.export_via_celery is False
242
+ assert settings.has_bkm_config is False
243
243
 
244
244
 
245
245
  def test_metric_settings_do_not_reuse_trace_credentials(monkeypatch):
@@ -582,8 +582,8 @@ def test_celery_task_exports_through_process_local_metric_service(mocker):
582
582
  service.push_bkm.assert_called_once_with("endpoint-fingerprint", "payload")
583
583
  assert tasks.push_bkm_metrics_task.shared_task_options["autoretry_for"] == (RetryableMetricPushError,)
584
584
  assert tasks.push_bkm_metrics_task.shared_task_options["max_retries"] == 3
585
- assert tasks.agent_settings.BKAI_AGENT_TASK == "bkai_agent_task"
586
- assert tasks.push_bkm_metrics_task.shared_task_options["queue"] == "bkai_agent_task"
585
+ assert tasks.agent_settings.BKAI_AGENT_QUEUE_METRIC == "bkai_agent_metric"
586
+ assert tasks.push_bkm_metrics_task.shared_task_options["queue"] == "bkai_agent_metric"
587
587
  assert tasks.run_bkplugin_background_agent_task.shared_task_options["queue"] == "bkai_agent_task"
588
588
 
589
589
 
@@ -83,7 +83,7 @@ def test_init_otel_deduplicates_endpoint_sources_before_instrumenting(mocker):
83
83
  endpoint = {"url": "https://collector.example/api", "token": "token", "exporter_type": ExporterType.GRPC}
84
84
  metric_settings = SimpleNamespace(
85
85
  enabled=False,
86
- export_via_celery=False,
86
+ has_bkm_config=False,
87
87
  export_interval_millis=1500,
88
88
  export_timeout_millis=7000,
89
89
  )
@@ -148,11 +148,14 @@ def test_management_commands_disable_metrics_and_traces_before_remote_config(moc
148
148
  ],
149
149
  )
150
150
  @pytest.mark.parametrize("enabled", [False, True])
151
- @pytest.mark.parametrize("via_celery", [False, True])
152
- def test_service_entries_preserve_metric_configuration(mocker, monkeypatch, argv, enabled, via_celery):
151
+ @pytest.mark.parametrize("has_bkm_config", [False, True])
152
+ def test_service_entries_preserve_metric_configuration(mocker, monkeypatch, argv, enabled, has_bkm_config):
153
153
  monkeypatch.setattr(apps.sys, "argv", argv)
154
154
  metric_settings = SimpleNamespace(
155
- enabled=enabled, export_via_celery=via_celery, export_interval_millis=1500, export_timeout_millis=7000
155
+ enabled=enabled,
156
+ has_bkm_config=has_bkm_config,
157
+ export_interval_millis=1500,
158
+ export_timeout_millis=7000,
156
159
  )
157
160
  config, instrumentor, _ = _mock_otel_inputs(mocker, {}, metric_settings)
158
161
  config.enable_traces = not enabled
@@ -165,8 +168,8 @@ def test_service_entries_preserve_metric_configuration(mocker, monkeypatch, argv
165
168
 
166
169
  assert config.enable_metrics is enabled
167
170
  assert config.enable_traces is (not enabled)
168
- assert config.metric_provider_managed_externally is (enabled and via_celery)
169
- assert metric_service.called is via_celery
171
+ assert config.metric_provider_managed_externally is (enabled and has_bkm_config)
172
+ assert metric_service.called is has_bkm_config
170
173
  apps.MetricExportSettings.from_agent_info.assert_called_once()
171
174
  instrumentor.instrument.assert_called_once_with()
172
175
 
@@ -177,7 +180,7 @@ def test_init_otel_keeps_direct_metric_export_in_agent_sdk(mocker, monkeypatch):
177
180
  monkeypatch.delattr(aidev_agent_packages, "opentelemetry", raising=False)
178
181
  settings = SimpleNamespace(
179
182
  enabled=True,
180
- export_via_celery=False,
183
+ has_bkm_config=False,
181
184
  export_interval_millis=1500,
182
185
  export_timeout_millis=7000,
183
186
  )
@@ -202,10 +205,10 @@ def test_init_otel_keeps_direct_metric_export_in_agent_sdk(mocker, monkeypatch):
202
205
  instrumentor.instrument.assert_called_once_with()
203
206
 
204
207
 
205
- def test_init_otel_uses_bkplugin_metric_provider_for_celery_export(mocker):
208
+ def test_init_otel_uses_bkplugin_metric_provider_for_bkm_export(mocker):
206
209
  settings = SimpleNamespace(
207
210
  enabled=True,
208
- export_via_celery=True,
211
+ has_bkm_config=True,
209
212
  export_interval_millis=1500,
210
213
  export_timeout_millis=7000,
211
214
  )
@@ -50,13 +50,15 @@ EXIT_PROBE = dedent("""
50
50
  # Keep the real SDK provider lifecycle; avoid unrelated agent wrappers.
51
51
  return SimpleNamespace(instrument=BkAgentOTelService(config).start)
52
52
 
53
- via_celery = sys.argv[1] == "celery"
53
+ use_bkm = sys.argv[1] == "bkm"
54
54
  sys.argv = ["bin/manage.py", sys.argv[2]]
55
- agent_info = {"otel_info": {"metrics": {
56
- "enabled": True, "export_via_celery": via_celery,
57
- "agent_data_id": 1, "agent_access_token": "test-token",
58
- "agent_push_url": "http://collector.example.com/v2/push/",
59
- }}}
55
+ metrics_config = {"enabled": True}
56
+ if use_bkm:
57
+ metrics_config.update({
58
+ "agent_data_id": 1, "agent_access_token": "test-token",
59
+ "agent_push_url": "http://collector.example.com/v2/push/",
60
+ })
61
+ agent_info = {"otel_info": {"metrics": metrics_config}}
60
62
  endpoint = {"url": "http://collector.example.com", "token": "", "exporter_type": ExporterType.HTTP}
61
63
  with (
62
64
  patch.object(apps, "get_otel_endpoint_by_json_str", return_value=[endpoint]),
@@ -77,13 +79,13 @@ EXIT_PROBE = dedent("""
77
79
  """)
78
80
 
79
81
 
80
- @pytest.mark.parametrize("transport", ["direct", "celery"])
82
+ @pytest.mark.parametrize("transport", ["otlp", "bkm"])
81
83
  @pytest.mark.parametrize("command", ["migrate", "upgrade_sessions"])
82
84
  def test_management_initialization_exits_without_metric_or_trace_export(transport, command):
83
85
  env = {
84
86
  **os.environ,
85
87
  "DJANGO_SETTINGS_MODULE": "tests.settings",
86
- "PYTHONPATH": os.pathsep.join([str(PLUGIN_ROOT), str(AGENT_ROOT)]),
88
+ "PYTHONPATH": os.pathsep.join([str(PLUGIN_ROOT), str(AGENT_ROOT), os.environ.get("PYTHONPATH", "")]),
87
89
  "BKAI_AGENT_OTEL_ENABLED": "true",
88
90
  "BKAI_AGENT_ENABLE_METRICS": "true",
89
91
  "BKAI_AGENT_ENABLE_TRACES": "true",