dsh-plugin-image-workbench 1.1.5 → 1.1.7

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 (173) hide show
  1. package/LICENSE +21 -21
  2. package/README.en.md +5 -3
  3. package/README.md +7 -3
  4. package/client.js +241 -241
  5. package/cordis.patch.yml +14 -14
  6. package/host.js +51 -0
  7. package/install.mjs +333 -387
  8. package/package.json +3 -2
  9. package/scripts/fetch-style-images.mjs +104 -0
  10. package/scripts/vendor-snapshot.py +154 -154
  11. package/server/access.py +26 -26
  12. package/server/app.py +1371 -1329
  13. package/server/catalog.py +147 -147
  14. package/server/composer.py +391 -391
  15. package/server/drafts.py +158 -158
  16. package/server/history.py +575 -575
  17. package/server/imaging.py +172 -172
  18. package/server/pool.py +1335 -1335
  19. package/server/pool_admin.py +921 -921
  20. package/server/pool_service.py +1073 -1073
  21. package/server/requirements.txt +6 -6
  22. package/server/smoke_check.py +402 -402
  23. package/server/static/access.html +202 -202
  24. package/server/static/index.html +15 -0
  25. package/vendor/chatgpt2api/source/.env.example +82 -82
  26. package/vendor/chatgpt2api/source/.python-version +1 -1
  27. package/vendor/chatgpt2api/source/LICENSE +21 -21
  28. package/vendor/chatgpt2api/source/README.md +391 -391
  29. package/vendor/chatgpt2api/source/VERSION +1 -1
  30. package/vendor/chatgpt2api/source/api/__init__.py +2 -2
  31. package/vendor/chatgpt2api/source/api/accounts.py +537 -537
  32. package/vendor/chatgpt2api/source/api/ai.py +217 -217
  33. package/vendor/chatgpt2api/source/api/app.py +62 -62
  34. package/vendor/chatgpt2api/source/api/errors.py +46 -46
  35. package/vendor/chatgpt2api/source/api/image_inputs.py +309 -309
  36. package/vendor/chatgpt2api/source/api/image_tasks.py +120 -120
  37. package/vendor/chatgpt2api/source/api/support.py +134 -134
  38. package/vendor/chatgpt2api/source/api/system.py +365 -365
  39. package/vendor/chatgpt2api/source/assets/kunrouai.svg +50 -50
  40. package/vendor/chatgpt2api/source/config.default.json +108 -108
  41. package/vendor/chatgpt2api/source/main.py +9 -9
  42. package/vendor/chatgpt2api/source/pyproject.toml +27 -27
  43. package/vendor/chatgpt2api/source/scripts/init_proxy_config.py +186 -186
  44. package/vendor/chatgpt2api/source/scripts/migrate_storage.py +163 -163
  45. package/vendor/chatgpt2api/source/scripts/privoxy-warp.conf +13 -13
  46. package/vendor/chatgpt2api/source/scripts/test_outlook_token_mailbox.py +385 -385
  47. package/vendor/chatgpt2api/source/scripts/test_storage.py +129 -129
  48. package/vendor/chatgpt2api/source/scripts/verify_oauth_refresh.py +92 -92
  49. package/vendor/chatgpt2api/source/services/account_service.py +1757 -1757
  50. package/vendor/chatgpt2api/source/services/auth_service.py +253 -253
  51. package/vendor/chatgpt2api/source/services/backup_service.py +671 -671
  52. package/vendor/chatgpt2api/source/services/config.py +667 -667
  53. package/vendor/chatgpt2api/source/services/content_filter.py +242 -242
  54. package/vendor/chatgpt2api/source/services/cpa_service.py +315 -315
  55. package/vendor/chatgpt2api/source/services/editable_file_task_service.py +260 -260
  56. package/vendor/chatgpt2api/source/services/image_service.py +376 -376
  57. package/vendor/chatgpt2api/source/services/image_storage_service.py +405 -405
  58. package/vendor/chatgpt2api/source/services/image_tags_service.py +76 -76
  59. package/vendor/chatgpt2api/source/services/image_task_service.py +550 -550
  60. package/vendor/chatgpt2api/source/services/log_service.py +337 -337
  61. package/vendor/chatgpt2api/source/services/model_service.py +182 -182
  62. package/vendor/chatgpt2api/source/services/oauth_login_service.py +267 -267
  63. package/vendor/chatgpt2api/source/services/openai_backend_api.py +2763 -2763
  64. package/vendor/chatgpt2api/source/services/openai_oauth.py +32 -32
  65. package/vendor/chatgpt2api/source/services/protocol/__init__.py +2 -2
  66. package/vendor/chatgpt2api/source/services/protocol/anthropic_v1_messages.py +307 -307
  67. package/vendor/chatgpt2api/source/services/protocol/chat_completion_cache.py +238 -238
  68. package/vendor/chatgpt2api/source/services/protocol/conversation.py +1644 -1644
  69. package/vendor/chatgpt2api/source/services/protocol/error_response.py +124 -124
  70. package/vendor/chatgpt2api/source/services/protocol/openai_search.py +19 -19
  71. package/vendor/chatgpt2api/source/services/protocol/openai_v1_chat_complete.py +316 -316
  72. package/vendor/chatgpt2api/source/services/protocol/openai_v1_image_edit.py +86 -86
  73. package/vendor/chatgpt2api/source/services/protocol/openai_v1_image_generations.py +42 -42
  74. package/vendor/chatgpt2api/source/services/protocol/openai_v1_models.py +53 -53
  75. package/vendor/chatgpt2api/source/services/protocol/openai_v1_response.py +453 -453
  76. package/vendor/chatgpt2api/source/services/protocol/web_search_tool.py +160 -160
  77. package/vendor/chatgpt2api/source/services/proxy_service.py +648 -648
  78. package/vendor/chatgpt2api/source/services/storage/__init__.py +5 -5
  79. package/vendor/chatgpt2api/source/services/storage/base.py +38 -38
  80. package/vendor/chatgpt2api/source/services/storage/database_storage.py +194 -194
  81. package/vendor/chatgpt2api/source/services/storage/factory.py +104 -104
  82. package/vendor/chatgpt2api/source/services/storage/git_storage.py +183 -183
  83. package/vendor/chatgpt2api/source/services/storage/json_storage.py +95 -95
  84. package/vendor/chatgpt2api/source/services/sub2api_service.py +531 -531
  85. package/vendor/chatgpt2api/source/utils/helper.py +469 -469
  86. package/vendor/chatgpt2api/source/utils/image_tokens.py +346 -346
  87. package/vendor/chatgpt2api/source/utils/log.py +110 -110
  88. package/vendor/chatgpt2api/source/utils/pkce.py +19 -19
  89. package/vendor/chatgpt2api/source/utils/pow.py +207 -207
  90. package/vendor/chatgpt2api/source/utils/sentinel.py +159 -159
  91. package/vendor/chatgpt2api/source/utils/turnstile.py +184 -184
  92. package/vendor/chatgpt2api/source/uv.lock +904 -904
  93. package/vendor/chatgpt2api/source/web/bun.lock +1501 -1501
  94. package/vendor/chatgpt2api/source/web/components.json +24 -24
  95. package/vendor/chatgpt2api/source/web/eslint.config.mjs +17 -17
  96. package/vendor/chatgpt2api/source/web/next.config.ts +40 -40
  97. package/vendor/chatgpt2api/source/web/package.json +58 -58
  98. package/vendor/chatgpt2api/source/web/postcss.config.mjs +5 -5
  99. package/vendor/chatgpt2api/source/web/src/app/accounts/components/account-import-dialog.tsx +925 -925
  100. package/vendor/chatgpt2api/source/web/src/app/accounts/page.tsx +1307 -1307
  101. package/vendor/chatgpt2api/source/web/src/app/debug/components/chat-panel.tsx +224 -224
  102. package/vendor/chatgpt2api/source/web/src/app/debug/components/editable-file-panel.tsx +444 -444
  103. package/vendor/chatgpt2api/source/web/src/app/debug/components/ppt-panel.tsx +9 -9
  104. package/vendor/chatgpt2api/source/web/src/app/debug/components/psd-panel.tsx +9 -9
  105. package/vendor/chatgpt2api/source/web/src/app/debug/components/search-panel.tsx +172 -172
  106. package/vendor/chatgpt2api/source/web/src/app/debug/components/skill-panel.tsx +169 -169
  107. package/vendor/chatgpt2api/source/web/src/app/debug/components/types.ts +39 -39
  108. package/vendor/chatgpt2api/source/web/src/app/debug/page.tsx +59 -59
  109. package/vendor/chatgpt2api/source/web/src/app/globals.css +230 -230
  110. package/vendor/chatgpt2api/source/web/src/app/image/components/image-composer.tsx +542 -542
  111. package/vendor/chatgpt2api/source/web/src/app/image/components/image-results.tsx +554 -554
  112. package/vendor/chatgpt2api/source/web/src/app/image/components/image-sidebar.tsx +176 -176
  113. package/vendor/chatgpt2api/source/web/src/app/image/page.tsx +1799 -1799
  114. package/vendor/chatgpt2api/source/web/src/app/image-manager/page.tsx +732 -732
  115. package/vendor/chatgpt2api/source/web/src/app/layout.tsx +50 -50
  116. package/vendor/chatgpt2api/source/web/src/app/login/page.tsx +101 -101
  117. package/vendor/chatgpt2api/source/web/src/app/logs/page.tsx +356 -356
  118. package/vendor/chatgpt2api/source/web/src/app/page.tsx +30 -30
  119. package/vendor/chatgpt2api/source/web/src/app/settings/components/api-docs-card.tsx +341 -341
  120. package/vendor/chatgpt2api/source/web/src/app/settings/components/backup-settings-card.tsx +447 -447
  121. package/vendor/chatgpt2api/source/web/src/app/settings/components/base-url-card.tsx +71 -71
  122. package/vendor/chatgpt2api/source/web/src/app/settings/components/config-card.tsx +491 -491
  123. package/vendor/chatgpt2api/source/web/src/app/settings/components/cpa-pool-dialog.tsx +108 -108
  124. package/vendor/chatgpt2api/source/web/src/app/settings/components/cpa-pools-card.tsx +169 -169
  125. package/vendor/chatgpt2api/source/web/src/app/settings/components/import-browser-dialog.tsx +185 -185
  126. package/vendor/chatgpt2api/source/web/src/app/settings/components/proxy-runtime-card.tsx +379 -379
  127. package/vendor/chatgpt2api/source/web/src/app/settings/components/proxy-settings-card.tsx +127 -127
  128. package/vendor/chatgpt2api/source/web/src/app/settings/components/proxy-settings.tsx +200 -200
  129. package/vendor/chatgpt2api/source/web/src/app/settings/components/settings-header.tsx +12 -12
  130. package/vendor/chatgpt2api/source/web/src/app/settings/components/sub2api-connections.tsx +886 -886
  131. package/vendor/chatgpt2api/source/web/src/app/settings/components/third-party-apps-card.tsx +81 -81
  132. package/vendor/chatgpt2api/source/web/src/app/settings/components/user-keys-card.tsx +422 -422
  133. package/vendor/chatgpt2api/source/web/src/app/settings/page.tsx +135 -135
  134. package/vendor/chatgpt2api/source/web/src/app/settings/store.ts +1069 -1069
  135. package/vendor/chatgpt2api/source/web/src/components/date-range-filter.tsx +49 -49
  136. package/vendor/chatgpt2api/source/web/src/components/header-actions.tsx +24 -24
  137. package/vendor/chatgpt2api/source/web/src/components/image-lightbox.tsx +434 -434
  138. package/vendor/chatgpt2api/source/web/src/components/image-thumbnail.tsx +46 -46
  139. package/vendor/chatgpt2api/source/web/src/components/theme-script.tsx +18 -18
  140. package/vendor/chatgpt2api/source/web/src/components/theme-toggle.tsx +14 -14
  141. package/vendor/chatgpt2api/source/web/src/components/top-nav.tsx +263 -263
  142. package/vendor/chatgpt2api/source/web/src/components/ui/animated-theme-toggler.tsx +256 -256
  143. package/vendor/chatgpt2api/source/web/src/components/ui/badge.tsx +41 -41
  144. package/vendor/chatgpt2api/source/web/src/components/ui/button.tsx +59 -59
  145. package/vendor/chatgpt2api/source/web/src/components/ui/calendar.tsx +46 -46
  146. package/vendor/chatgpt2api/source/web/src/components/ui/card.tsx +61 -61
  147. package/vendor/chatgpt2api/source/web/src/components/ui/checkbox.tsx +27 -27
  148. package/vendor/chatgpt2api/source/web/src/components/ui/dia-text-reveal.tsx +267 -267
  149. package/vendor/chatgpt2api/source/web/src/components/ui/dialog.tsx +132 -132
  150. package/vendor/chatgpt2api/source/web/src/components/ui/field.tsx +13 -13
  151. package/vendor/chatgpt2api/source/web/src/components/ui/input.tsx +19 -19
  152. package/vendor/chatgpt2api/source/web/src/components/ui/label.tsx +24 -24
  153. package/vendor/chatgpt2api/source/web/src/components/ui/morphing-text.tsx +149 -149
  154. package/vendor/chatgpt2api/source/web/src/components/ui/popover.tsx +38 -38
  155. package/vendor/chatgpt2api/source/web/src/components/ui/select.tsx +175 -175
  156. package/vendor/chatgpt2api/source/web/src/components/ui/sheet.tsx +143 -143
  157. package/vendor/chatgpt2api/source/web/src/components/ui/table.tsx +29 -29
  158. package/vendor/chatgpt2api/source/web/src/components/ui/tabs.tsx +91 -91
  159. package/vendor/chatgpt2api/source/web/src/components/ui/text-3d-flip.tsx +269 -269
  160. package/vendor/chatgpt2api/source/web/src/components/ui/textarea.tsx +18 -18
  161. package/vendor/chatgpt2api/source/web/src/components/version-release-dialog.tsx +127 -127
  162. package/vendor/chatgpt2api/source/web/src/constants/common-env.ts +6 -6
  163. package/vendor/chatgpt2api/source/web/src/hooks/use-version-check.ts +85 -85
  164. package/vendor/chatgpt2api/source/web/src/lib/api.ts +926 -926
  165. package/vendor/chatgpt2api/source/web/src/lib/auth-session.ts +26 -26
  166. package/vendor/chatgpt2api/source/web/src/lib/release.ts +25 -25
  167. package/vendor/chatgpt2api/source/web/src/lib/request.ts +93 -93
  168. package/vendor/chatgpt2api/source/web/src/lib/use-auth-guard.ts +89 -89
  169. package/vendor/chatgpt2api/source/web/src/lib/utils.ts +6 -6
  170. package/vendor/chatgpt2api/source/web/src/store/auth.ts +112 -112
  171. package/vendor/chatgpt2api/source/web/src/store/editable-file-history.ts +33 -33
  172. package/vendor/chatgpt2api/source/web/src/store/image-conversations.ts +318 -318
  173. package/vendor/chatgpt2api/source/web/tsconfig.json +42 -42
@@ -1,307 +1,307 @@
1
- from __future__ import annotations
2
-
3
- import html
4
- import json
5
- import re
6
- import time
7
- import uuid
8
- from collections.abc import Callable, Iterable, Iterator
9
- from dataclasses import dataclass
10
- from typing import Any
11
-
12
- from services.account_service import account_service
13
- from services.openai_backend_api import OpenAIBackendAPI
14
- from services.protocol.conversation import count_message_tokens, count_text_tokens, normalize_messages
15
- from services.protocol.openai_v1_chat_complete import collect_chat_content, stream_text_chat_completion
16
-
17
- XML_TOOL_RULE = """Tool output adapter: when calling tools, output ONLY this XML and no prose/markdown:
18
- <tool_calls><tool_call><tool_name>TOOL_NAME</tool_name><parameters><PARAM><![CDATA[value]]></PARAM></parameters></tool_call></tool_calls>"""
19
-
20
-
21
- @dataclass
22
- class MessageRequest:
23
- backend: OpenAIBackendAPI
24
- messages: list[dict[str, Any]]
25
- model: str
26
- tools: Any = None
27
-
28
-
29
- def _tool_meta(tool: dict[str, object]) -> tuple[str, str, object]:
30
- fn = tool.get("function") if isinstance(tool.get("function"), dict) else {}
31
- name = str(tool.get("name") or fn.get("name") or "").strip()
32
- desc = str(tool.get("description") or fn.get("description") or "").strip()
33
- schema = tool.get("input_schema") or tool.get("parameters") or fn.get("input_schema") or fn.get("parameters") or {}
34
- return name, desc, schema
35
-
36
-
37
- def build_tool_prompt(tools: object) -> str:
38
- if not isinstance(tools, list):
39
- return ""
40
- blocks = []
41
- for tool in tools:
42
- if not isinstance(tool, dict):
43
- continue
44
- name, desc, schema = _tool_meta(tool)
45
- if name:
46
- blocks.append(f"Tool: {name}\nDescription: {desc}\nParameters: {json.dumps(schema, ensure_ascii=False)}")
47
- if not blocks:
48
- return ""
49
- return "Available tools:\n" + "\n".join(blocks) + """
50
-
51
- Tool use rules:
52
- - If the user asks to list/read/search files, inspect project state, run a command, or answer from local code, you MUST call a suitable tool first. Do not say you cannot access files.
53
- - To call tools, output ONLY XML and no prose/markdown:
54
- <tool_calls><tool_call><tool_name>TOOL_NAME</tool_name><parameters><PARAM><![CDATA[value]]></PARAM></parameters></tool_call></tool_calls>
55
- - Put parameters under <parameters> using the exact schema names.
56
- """.strip()
57
-
58
-
59
- def merge_system(system: object, extra: str) -> object:
60
- system = compact_system(system)
61
- if _has_claude_code_system(system):
62
- extra = XML_TOOL_RULE
63
- if not extra:
64
- return system
65
- if isinstance(system, str) and system.strip():
66
- return f"{system.strip()}\n\n{extra}"
67
- if isinstance(system, list):
68
- return [*system, {"type": "text", "text": extra}]
69
- return extra
70
-
71
-
72
- def _has_claude_code_system(system: object) -> bool:
73
- if isinstance(system, str):
74
- return "You are Claude Code" in system
75
- if isinstance(system, list):
76
- return any(isinstance(item, dict) and "You are Claude Code" in str(item.get("text") or "") for item in system)
77
- return False
78
-
79
-
80
- def compact_system(system: object) -> object:
81
- if isinstance(system, str):
82
- return _compact_system_text(system)
83
- if isinstance(system, list):
84
- result = []
85
- for item in system:
86
- if isinstance(item, dict) and str(item.get("type") or "") == "text":
87
- copied = dict(item)
88
- copied["text"] = _compact_system_text(str(item.get("text") or ""))
89
- result.append(copied)
90
- else:
91
- result.append(item)
92
- return result
93
- return system
94
-
95
-
96
- def _compact_system_text(text: str) -> str:
97
- return text or ""
98
-
99
-
100
- def _compact_message_text(text: str) -> str:
101
- return text or ""
102
-
103
-
104
- def preprocess_payload(payload: dict[str, object], text_mapper: Callable[[str], str] | None = None) -> dict[str, object]:
105
- payload["messages"] = preprocess_messages(payload.get("messages"), text_mapper)
106
- payload["system"] = merge_system(payload.get("system"), build_tool_prompt(payload.get("tools")))
107
- return payload
108
-
109
-
110
- def message_request(body: dict[str, Any]) -> MessageRequest:
111
- payload = preprocess_payload(dict(body))
112
- model = str(payload.get("model") or "auto").strip() or "auto"
113
- return MessageRequest(
114
- backend=OpenAIBackendAPI(access_token=account_service.get_text_access_token(model=model)),
115
- messages=normalize_messages(payload.get("messages"), payload.get("system")),
116
- model=model,
117
- tools=payload.get("tools"),
118
- )
119
-
120
-
121
- def preprocess_messages(messages: object, text_mapper: Callable[[str], str] | None = None) -> object:
122
- if not isinstance(messages, list):
123
- return messages
124
- mapper = text_mapper or (lambda text: text)
125
- result = []
126
- for message in messages:
127
- if not isinstance(message, dict):
128
- continue
129
- item = dict(message)
130
- content = item.get("content")
131
- if isinstance(content, str):
132
- item["content"] = _compact_message_text(mapper(content))
133
- elif isinstance(content, list):
134
- item["content"] = [_preprocess_block(block, mapper) for block in content]
135
- result.append(item)
136
- return result
137
-
138
-
139
- def _preprocess_block(block: object, text_mapper: Callable[[str], str]) -> object:
140
- if not isinstance(block, dict):
141
- return block
142
- block_type = str(block.get("type") or "")
143
- if block_type == "text":
144
- item = dict(block)
145
- item["text"] = _compact_message_text(text_mapper(str(block.get("text") or "")))
146
- return item
147
- if block_type == "tool_use":
148
- return {"type": "text", "text": f"<tool_calls><tool_call><tool_name>{block.get('name') or ''}</tool_name><parameters>{json.dumps(block.get('input') or {}, ensure_ascii=False)}</parameters></tool_call></tool_calls>"}
149
- if block_type == "tool_result":
150
- return {"type": "text", "text": f"Tool result {block.get('tool_use_id') or ''}: {block.get('content') or ''}"}
151
- return block
152
-
153
-
154
- def message_response(model: str, text: str, input_tokens: int, output_tokens: int, tools: object = None) -> dict[str, object]:
155
- content, stop_reason = content_blocks(text, tools)
156
- return {
157
- "id": f"msg_{uuid.uuid4()}",
158
- "type": "message",
159
- "role": "assistant",
160
- "model": model,
161
- "content": content,
162
- "stop_reason": stop_reason,
163
- "stop_sequence": None,
164
- "usage": {"input_tokens": input_tokens, "output_tokens": output_tokens},
165
- }
166
-
167
-
168
- def content_blocks(text: str, tools: object = None) -> tuple[list[dict[str, object]], str]:
169
- calls = parse_tool_calls(text) if isinstance(tools, list) and tools else []
170
- text = strip_tool_markup(text)
171
- if calls:
172
- content = ([{"type": "text", "text": text}] if text else []) + [{"type": "tool_use", "id": f"toolu_{uuid.uuid4()}", "name": name, "input": args} for name, args in calls]
173
- return content, "tool_use"
174
- return [{"type": "text", "text": text}], "end_turn"
175
-
176
-
177
- def strip_tool_markup(text: str) -> str:
178
- return re.sub(r"(?is)<tool_calls\b[^>]*>.*?</tool_calls>|<tool_call\b[^>]*>.*?</tool_call>|<function_call\b[^>]*>.*?</function_call>|<invoke\b[^>]*>.*?</invoke>", "", text or "").strip()
179
-
180
-
181
- def streamable_text(text: str) -> str:
182
- text = text or ""
183
- match = re.search(r"(?is)<tool_calls\b|<tool_call\b|<function_call\b|<invoke\b", text)
184
- return text[:match.start()].rstrip() if match else text
185
-
186
-
187
- def parse_tool_calls(text: str) -> list[tuple[str, dict[str, object]]]:
188
- text = re.sub(r"(?is)```.*?```", "", text or "").strip()
189
- blocks = re.findall(r"(?is)<tool_call\b[^>]*>(.*?)</tool_call>|<function_call\b[^>]*>(.*?)</function_call>|<invoke\b[^>]*>(.*?)</invoke>", text)
190
- result = []
191
- for block in (next((part for part in match if part), "") for match in blocks):
192
- name = xml_value(block, "tool_name") or xml_value(block, "name") or xml_value(block, "function")
193
- params = xml_value(block, "parameters") or xml_value(block, "input") or xml_value(block, "arguments") or "{}"
194
- if name:
195
- result.append((name, parse_tool_params(params)))
196
- return result
197
-
198
-
199
- def xml_value(text: str, tag: str) -> str:
200
- match = re.search(rf"(?is)<{tag}\b[^>]*>(.*?)</{tag}>", text)
201
- if not match:
202
- return ""
203
- value = match.group(1).strip()
204
- cdata = re.fullmatch(r"(?is)<!\[CDATA\[(.*?)]]>", value)
205
- return html.unescape(cdata.group(1) if cdata else value).strip()
206
-
207
-
208
- def parse_tool_params(raw: str) -> dict[str, object]:
209
- raw = raw.strip()
210
- try:
211
- parsed = json.loads(raw)
212
- return parsed if isinstance(parsed, dict) else {}
213
- except Exception:
214
- return {m.group(1): parse_tool_value(m.group(2)) for m in re.finditer(r"(?is)<([\w.-]+)\b[^>]*>(.*?)</\1>", raw)}
215
-
216
-
217
- def parse_tool_value(raw: str) -> object:
218
- value = xml_value(f"<x>{raw}</x>", "x")
219
- try:
220
- return json.loads(value)
221
- except Exception:
222
- return value
223
-
224
-
225
- def stream_events(chunks: Iterable[dict[str, object]], model: str, input_tokens: int, output_tokens: Callable[[str], int], tools: object = None) -> Iterator[dict[str, object]]:
226
- message_id = f"msg_{uuid.uuid4()}"
227
- created = int(time.time())
228
- current_text = ""
229
- streamed_text = ""
230
- tool_mode = isinstance(tools, list) and bool(tools)
231
- tool_started = False
232
- text_open = False
233
- yield {"type": "message_start", "message": {"id": message_id, "type": "message", "role": "assistant", "model": model, "content": [], "stop_reason": None, "stop_sequence": None, "usage": {"input_tokens": input_tokens, "output_tokens": 0}}}
234
- if not tool_mode:
235
- text_open = True
236
- yield {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}
237
- for chunk in chunks:
238
- choice = (chunk.get("choices") or [{}])[0]
239
- delta = choice.get("delta") or {}
240
- text_delta = delta.get("content", "") if isinstance(delta, dict) else ""
241
- if text_delta:
242
- current_text += text_delta
243
- if not tool_started:
244
- visible_text = current_text if not tool_mode else streamable_text(current_text)
245
- if visible_text.startswith(streamed_text):
246
- text_delta = visible_text[len(streamed_text):]
247
- if text_delta:
248
- if not text_open:
249
- text_open = True
250
- yield {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}
251
- streamed_text = visible_text
252
- yield {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": text_delta}}
253
- tool_started = tool_mode and visible_text != current_text
254
- if choice.get("finish_reason"):
255
- content, stop_reason = content_blocks(current_text, tools)
256
- if text_open:
257
- yield {"type": "content_block_stop", "index": 0}
258
- if stop_reason == "tool_use":
259
- start_index = 1 if text_open else 0
260
- if content and content[0]["type"] == "text":
261
- remaining = str(content[0].get("text") or "")[len(streamed_text):]
262
- if remaining:
263
- if not text_open:
264
- yield {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}
265
- yield {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": remaining}}
266
- if not text_open:
267
- yield {"type": "content_block_stop", "index": 0}
268
- start_index = 1
269
- content = content[1:]
270
- yield from _stream_buffered_blocks(content, start_index)
271
- yield {"type": "message_delta", "delta": {"stop_reason": stop_reason, "stop_sequence": None}, "usage": {"output_tokens": output_tokens(current_text)}}
272
- break
273
- yield {"type": "message_stop", "created": created}
274
-
275
-
276
- def _stream_buffered_blocks(content: list[dict[str, object]], start_index: int = 0) -> Iterator[dict[str, object]]:
277
- for offset, block in enumerate(content):
278
- index = start_index + offset
279
- if block["type"] == "tool_use":
280
- start = {"type": "tool_use", "id": block["id"], "name": block["name"], "input": {}}
281
- delta = {"type": "input_json_delta", "partial_json": json.dumps(block.get("input") or {}, ensure_ascii=False)}
282
- else:
283
- start = {"type": "text", "text": ""}
284
- delta = {"type": "text_delta", "text": block.get("text") or ""}
285
- yield {"type": "content_block_start", "index": index, "content_block": start}
286
- yield {"type": "content_block_delta", "index": index, "delta": delta}
287
- yield {"type": "content_block_stop", "index": index}
288
-
289
-
290
- def handle(body: dict[str, Any]) -> dict[str, Any] | Iterator[dict[str, Any]]:
291
- request = message_request(body)
292
- if body.get("stream"):
293
- return stream_events(
294
- stream_text_chat_completion(request.backend, request.messages, request.model),
295
- request.model,
296
- count_message_tokens(request.messages, request.model),
297
- lambda text: count_text_tokens(text, request.model),
298
- request.tools,
299
- )
300
- text = collect_chat_content(stream_text_chat_completion(request.backend, request.messages, request.model))
301
- return message_response(
302
- request.model,
303
- text,
304
- count_message_tokens(request.messages, request.model),
305
- count_text_tokens(text, request.model),
306
- request.tools,
307
- )
1
+ from __future__ import annotations
2
+
3
+ import html
4
+ import json
5
+ import re
6
+ import time
7
+ import uuid
8
+ from collections.abc import Callable, Iterable, Iterator
9
+ from dataclasses import dataclass
10
+ from typing import Any
11
+
12
+ from services.account_service import account_service
13
+ from services.openai_backend_api import OpenAIBackendAPI
14
+ from services.protocol.conversation import count_message_tokens, count_text_tokens, normalize_messages
15
+ from services.protocol.openai_v1_chat_complete import collect_chat_content, stream_text_chat_completion
16
+
17
+ XML_TOOL_RULE = """Tool output adapter: when calling tools, output ONLY this XML and no prose/markdown:
18
+ <tool_calls><tool_call><tool_name>TOOL_NAME</tool_name><parameters><PARAM><![CDATA[value]]></PARAM></parameters></tool_call></tool_calls>"""
19
+
20
+
21
+ @dataclass
22
+ class MessageRequest:
23
+ backend: OpenAIBackendAPI
24
+ messages: list[dict[str, Any]]
25
+ model: str
26
+ tools: Any = None
27
+
28
+
29
+ def _tool_meta(tool: dict[str, object]) -> tuple[str, str, object]:
30
+ fn = tool.get("function") if isinstance(tool.get("function"), dict) else {}
31
+ name = str(tool.get("name") or fn.get("name") or "").strip()
32
+ desc = str(tool.get("description") or fn.get("description") or "").strip()
33
+ schema = tool.get("input_schema") or tool.get("parameters") or fn.get("input_schema") or fn.get("parameters") or {}
34
+ return name, desc, schema
35
+
36
+
37
+ def build_tool_prompt(tools: object) -> str:
38
+ if not isinstance(tools, list):
39
+ return ""
40
+ blocks = []
41
+ for tool in tools:
42
+ if not isinstance(tool, dict):
43
+ continue
44
+ name, desc, schema = _tool_meta(tool)
45
+ if name:
46
+ blocks.append(f"Tool: {name}\nDescription: {desc}\nParameters: {json.dumps(schema, ensure_ascii=False)}")
47
+ if not blocks:
48
+ return ""
49
+ return "Available tools:\n" + "\n".join(blocks) + """
50
+
51
+ Tool use rules:
52
+ - If the user asks to list/read/search files, inspect project state, run a command, or answer from local code, you MUST call a suitable tool first. Do not say you cannot access files.
53
+ - To call tools, output ONLY XML and no prose/markdown:
54
+ <tool_calls><tool_call><tool_name>TOOL_NAME</tool_name><parameters><PARAM><![CDATA[value]]></PARAM></parameters></tool_call></tool_calls>
55
+ - Put parameters under <parameters> using the exact schema names.
56
+ """.strip()
57
+
58
+
59
+ def merge_system(system: object, extra: str) -> object:
60
+ system = compact_system(system)
61
+ if _has_claude_code_system(system):
62
+ extra = XML_TOOL_RULE
63
+ if not extra:
64
+ return system
65
+ if isinstance(system, str) and system.strip():
66
+ return f"{system.strip()}\n\n{extra}"
67
+ if isinstance(system, list):
68
+ return [*system, {"type": "text", "text": extra}]
69
+ return extra
70
+
71
+
72
+ def _has_claude_code_system(system: object) -> bool:
73
+ if isinstance(system, str):
74
+ return "You are Claude Code" in system
75
+ if isinstance(system, list):
76
+ return any(isinstance(item, dict) and "You are Claude Code" in str(item.get("text") or "") for item in system)
77
+ return False
78
+
79
+
80
+ def compact_system(system: object) -> object:
81
+ if isinstance(system, str):
82
+ return _compact_system_text(system)
83
+ if isinstance(system, list):
84
+ result = []
85
+ for item in system:
86
+ if isinstance(item, dict) and str(item.get("type") or "") == "text":
87
+ copied = dict(item)
88
+ copied["text"] = _compact_system_text(str(item.get("text") or ""))
89
+ result.append(copied)
90
+ else:
91
+ result.append(item)
92
+ return result
93
+ return system
94
+
95
+
96
+ def _compact_system_text(text: str) -> str:
97
+ return text or ""
98
+
99
+
100
+ def _compact_message_text(text: str) -> str:
101
+ return text or ""
102
+
103
+
104
+ def preprocess_payload(payload: dict[str, object], text_mapper: Callable[[str], str] | None = None) -> dict[str, object]:
105
+ payload["messages"] = preprocess_messages(payload.get("messages"), text_mapper)
106
+ payload["system"] = merge_system(payload.get("system"), build_tool_prompt(payload.get("tools")))
107
+ return payload
108
+
109
+
110
+ def message_request(body: dict[str, Any]) -> MessageRequest:
111
+ payload = preprocess_payload(dict(body))
112
+ model = str(payload.get("model") or "auto").strip() or "auto"
113
+ return MessageRequest(
114
+ backend=OpenAIBackendAPI(access_token=account_service.get_text_access_token(model=model)),
115
+ messages=normalize_messages(payload.get("messages"), payload.get("system")),
116
+ model=model,
117
+ tools=payload.get("tools"),
118
+ )
119
+
120
+
121
+ def preprocess_messages(messages: object, text_mapper: Callable[[str], str] | None = None) -> object:
122
+ if not isinstance(messages, list):
123
+ return messages
124
+ mapper = text_mapper or (lambda text: text)
125
+ result = []
126
+ for message in messages:
127
+ if not isinstance(message, dict):
128
+ continue
129
+ item = dict(message)
130
+ content = item.get("content")
131
+ if isinstance(content, str):
132
+ item["content"] = _compact_message_text(mapper(content))
133
+ elif isinstance(content, list):
134
+ item["content"] = [_preprocess_block(block, mapper) for block in content]
135
+ result.append(item)
136
+ return result
137
+
138
+
139
+ def _preprocess_block(block: object, text_mapper: Callable[[str], str]) -> object:
140
+ if not isinstance(block, dict):
141
+ return block
142
+ block_type = str(block.get("type") or "")
143
+ if block_type == "text":
144
+ item = dict(block)
145
+ item["text"] = _compact_message_text(text_mapper(str(block.get("text") or "")))
146
+ return item
147
+ if block_type == "tool_use":
148
+ return {"type": "text", "text": f"<tool_calls><tool_call><tool_name>{block.get('name') or ''}</tool_name><parameters>{json.dumps(block.get('input') or {}, ensure_ascii=False)}</parameters></tool_call></tool_calls>"}
149
+ if block_type == "tool_result":
150
+ return {"type": "text", "text": f"Tool result {block.get('tool_use_id') or ''}: {block.get('content') or ''}"}
151
+ return block
152
+
153
+
154
+ def message_response(model: str, text: str, input_tokens: int, output_tokens: int, tools: object = None) -> dict[str, object]:
155
+ content, stop_reason = content_blocks(text, tools)
156
+ return {
157
+ "id": f"msg_{uuid.uuid4()}",
158
+ "type": "message",
159
+ "role": "assistant",
160
+ "model": model,
161
+ "content": content,
162
+ "stop_reason": stop_reason,
163
+ "stop_sequence": None,
164
+ "usage": {"input_tokens": input_tokens, "output_tokens": output_tokens},
165
+ }
166
+
167
+
168
+ def content_blocks(text: str, tools: object = None) -> tuple[list[dict[str, object]], str]:
169
+ calls = parse_tool_calls(text) if isinstance(tools, list) and tools else []
170
+ text = strip_tool_markup(text)
171
+ if calls:
172
+ content = ([{"type": "text", "text": text}] if text else []) + [{"type": "tool_use", "id": f"toolu_{uuid.uuid4()}", "name": name, "input": args} for name, args in calls]
173
+ return content, "tool_use"
174
+ return [{"type": "text", "text": text}], "end_turn"
175
+
176
+
177
+ def strip_tool_markup(text: str) -> str:
178
+ return re.sub(r"(?is)<tool_calls\b[^>]*>.*?</tool_calls>|<tool_call\b[^>]*>.*?</tool_call>|<function_call\b[^>]*>.*?</function_call>|<invoke\b[^>]*>.*?</invoke>", "", text or "").strip()
179
+
180
+
181
+ def streamable_text(text: str) -> str:
182
+ text = text or ""
183
+ match = re.search(r"(?is)<tool_calls\b|<tool_call\b|<function_call\b|<invoke\b", text)
184
+ return text[:match.start()].rstrip() if match else text
185
+
186
+
187
+ def parse_tool_calls(text: str) -> list[tuple[str, dict[str, object]]]:
188
+ text = re.sub(r"(?is)```.*?```", "", text or "").strip()
189
+ blocks = re.findall(r"(?is)<tool_call\b[^>]*>(.*?)</tool_call>|<function_call\b[^>]*>(.*?)</function_call>|<invoke\b[^>]*>(.*?)</invoke>", text)
190
+ result = []
191
+ for block in (next((part for part in match if part), "") for match in blocks):
192
+ name = xml_value(block, "tool_name") or xml_value(block, "name") or xml_value(block, "function")
193
+ params = xml_value(block, "parameters") or xml_value(block, "input") or xml_value(block, "arguments") or "{}"
194
+ if name:
195
+ result.append((name, parse_tool_params(params)))
196
+ return result
197
+
198
+
199
+ def xml_value(text: str, tag: str) -> str:
200
+ match = re.search(rf"(?is)<{tag}\b[^>]*>(.*?)</{tag}>", text)
201
+ if not match:
202
+ return ""
203
+ value = match.group(1).strip()
204
+ cdata = re.fullmatch(r"(?is)<!\[CDATA\[(.*?)]]>", value)
205
+ return html.unescape(cdata.group(1) if cdata else value).strip()
206
+
207
+
208
+ def parse_tool_params(raw: str) -> dict[str, object]:
209
+ raw = raw.strip()
210
+ try:
211
+ parsed = json.loads(raw)
212
+ return parsed if isinstance(parsed, dict) else {}
213
+ except Exception:
214
+ return {m.group(1): parse_tool_value(m.group(2)) for m in re.finditer(r"(?is)<([\w.-]+)\b[^>]*>(.*?)</\1>", raw)}
215
+
216
+
217
+ def parse_tool_value(raw: str) -> object:
218
+ value = xml_value(f"<x>{raw}</x>", "x")
219
+ try:
220
+ return json.loads(value)
221
+ except Exception:
222
+ return value
223
+
224
+
225
+ def stream_events(chunks: Iterable[dict[str, object]], model: str, input_tokens: int, output_tokens: Callable[[str], int], tools: object = None) -> Iterator[dict[str, object]]:
226
+ message_id = f"msg_{uuid.uuid4()}"
227
+ created = int(time.time())
228
+ current_text = ""
229
+ streamed_text = ""
230
+ tool_mode = isinstance(tools, list) and bool(tools)
231
+ tool_started = False
232
+ text_open = False
233
+ yield {"type": "message_start", "message": {"id": message_id, "type": "message", "role": "assistant", "model": model, "content": [], "stop_reason": None, "stop_sequence": None, "usage": {"input_tokens": input_tokens, "output_tokens": 0}}}
234
+ if not tool_mode:
235
+ text_open = True
236
+ yield {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}
237
+ for chunk in chunks:
238
+ choice = (chunk.get("choices") or [{}])[0]
239
+ delta = choice.get("delta") or {}
240
+ text_delta = delta.get("content", "") if isinstance(delta, dict) else ""
241
+ if text_delta:
242
+ current_text += text_delta
243
+ if not tool_started:
244
+ visible_text = current_text if not tool_mode else streamable_text(current_text)
245
+ if visible_text.startswith(streamed_text):
246
+ text_delta = visible_text[len(streamed_text):]
247
+ if text_delta:
248
+ if not text_open:
249
+ text_open = True
250
+ yield {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}
251
+ streamed_text = visible_text
252
+ yield {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": text_delta}}
253
+ tool_started = tool_mode and visible_text != current_text
254
+ if choice.get("finish_reason"):
255
+ content, stop_reason = content_blocks(current_text, tools)
256
+ if text_open:
257
+ yield {"type": "content_block_stop", "index": 0}
258
+ if stop_reason == "tool_use":
259
+ start_index = 1 if text_open else 0
260
+ if content and content[0]["type"] == "text":
261
+ remaining = str(content[0].get("text") or "")[len(streamed_text):]
262
+ if remaining:
263
+ if not text_open:
264
+ yield {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}
265
+ yield {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": remaining}}
266
+ if not text_open:
267
+ yield {"type": "content_block_stop", "index": 0}
268
+ start_index = 1
269
+ content = content[1:]
270
+ yield from _stream_buffered_blocks(content, start_index)
271
+ yield {"type": "message_delta", "delta": {"stop_reason": stop_reason, "stop_sequence": None}, "usage": {"output_tokens": output_tokens(current_text)}}
272
+ break
273
+ yield {"type": "message_stop", "created": created}
274
+
275
+
276
+ def _stream_buffered_blocks(content: list[dict[str, object]], start_index: int = 0) -> Iterator[dict[str, object]]:
277
+ for offset, block in enumerate(content):
278
+ index = start_index + offset
279
+ if block["type"] == "tool_use":
280
+ start = {"type": "tool_use", "id": block["id"], "name": block["name"], "input": {}}
281
+ delta = {"type": "input_json_delta", "partial_json": json.dumps(block.get("input") or {}, ensure_ascii=False)}
282
+ else:
283
+ start = {"type": "text", "text": ""}
284
+ delta = {"type": "text_delta", "text": block.get("text") or ""}
285
+ yield {"type": "content_block_start", "index": index, "content_block": start}
286
+ yield {"type": "content_block_delta", "index": index, "delta": delta}
287
+ yield {"type": "content_block_stop", "index": index}
288
+
289
+
290
+ def handle(body: dict[str, Any]) -> dict[str, Any] | Iterator[dict[str, Any]]:
291
+ request = message_request(body)
292
+ if body.get("stream"):
293
+ return stream_events(
294
+ stream_text_chat_completion(request.backend, request.messages, request.model),
295
+ request.model,
296
+ count_message_tokens(request.messages, request.model),
297
+ lambda text: count_text_tokens(text, request.model),
298
+ request.tools,
299
+ )
300
+ text = collect_chat_content(stream_text_chat_completion(request.backend, request.messages, request.model))
301
+ return message_response(
302
+ request.model,
303
+ text,
304
+ count_message_tokens(request.messages, request.model),
305
+ count_text_tokens(text, request.model),
306
+ request.tools,
307
+ )