txcode-sdk 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- txcode_sdk/__init__.py +49 -0
- txcode_sdk/agent/__init__.py +17 -0
- txcode_sdk/agent/base_agent.py +475 -0
- txcode_sdk/agent/chat/__init__.py +4 -0
- txcode_sdk/agent/chat/agent_tool.py +1 -0
- txcode_sdk/agent/chat/chat_agent.py +26 -0
- txcode_sdk/agent/chat/prompts/role.txt +31 -0
- txcode_sdk/agent/code/__init__.py +4 -0
- txcode_sdk/agent/code/agent_tool.py +1 -0
- txcode_sdk/agent/code/code_agent.py +26 -0
- txcode_sdk/agent/code/prompts/role.txt +51 -0
- txcode_sdk/agent/common/__init__.py +3 -0
- txcode_sdk/agent/common/common_agent.py +23 -0
- txcode_sdk/agent/common/prompt/role.txt +51 -0
- txcode_sdk/agent/mem/__init__.py +3 -0
- txcode_sdk/agent/mem/agent_tool.py +1 -0
- txcode_sdk/agent/mem/mem_agent.py +139 -0
- txcode_sdk/agent/mem/prompts/role.txt +36 -0
- txcode_sdk/agent/summarizer/__init__.py +3 -0
- txcode_sdk/agent/summarizer/prompts/role.txt +31 -0
- txcode_sdk/agent/summarizer/summarizer_agent.py +101 -0
- txcode_sdk/agent/task/__init__.py +4 -0
- txcode_sdk/agent/task/agent_tool.py +1 -0
- txcode_sdk/agent/task/prompts/role.txt +51 -0
- txcode_sdk/agent/task/task_agent.py +26 -0
- txcode_sdk/agent/tool_registry.py +119 -0
- txcode_sdk/client.py +215 -0
- txcode_sdk/compact/__init__.py +3 -0
- txcode_sdk/compact/compressor.py +74 -0
- txcode_sdk/hooks/__init__.py +19 -0
- txcode_sdk/hooks/handlers/__init__.py +4 -0
- txcode_sdk/hooks/handlers/base.py +19 -0
- txcode_sdk/hooks/handlers/memory.py +30 -0
- txcode_sdk/hooks/processor.py +19 -0
- txcode_sdk/hooks/queue.py +29 -0
- txcode_sdk/hooks/types.py +10 -0
- txcode_sdk/provider/__init__.py +6 -0
- txcode_sdk/provider/base.py +34 -0
- txcode_sdk/provider/deepseek_provider.py +60 -0
- txcode_sdk/provider/openai_provider.py +209 -0
- txcode_sdk/provider/router.py +13 -0
- txcode_sdk/session/__init__.py +3 -0
- txcode_sdk/session/manager.py +316 -0
- txcode_sdk/skills/__init__.py +43 -0
- txcode_sdk/specs/__init__.py +132 -0
- txcode_sdk/tools/__init__.py +3 -0
- txcode_sdk/tools/bash.txt +47 -0
- txcode_sdk/tools/bash_tool.py +79 -0
- txcode_sdk/tools/edit_file.py +141 -0
- txcode_sdk/tools/edit_file.txt +13 -0
- txcode_sdk/tools/glob.txt +12 -0
- txcode_sdk/tools/glob_tool.py +67 -0
- txcode_sdk/tools/grep.txt +14 -0
- txcode_sdk/tools/grep_tool.py +76 -0
- txcode_sdk/tools/memory_tool.py +78 -0
- txcode_sdk/tools/read_file.py +75 -0
- txcode_sdk/tools/read_file.txt +17 -0
- txcode_sdk/tools/write_file.py +43 -0
- txcode_sdk/tools/write_file.txt +11 -0
- txcode_sdk/types.py +158 -0
- txcode_sdk-0.1.0.dist-info/METADATA +58 -0
- txcode_sdk-0.1.0.dist-info/RECORD +64 -0
- txcode_sdk-0.1.0.dist-info/WHEEL +4 -0
- txcode_sdk-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
import json
|
|
5
|
+
import mimetypes
|
|
6
|
+
from datetime import datetime, timezone
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any, AsyncGenerator
|
|
9
|
+
|
|
10
|
+
from openai import AsyncOpenAI
|
|
11
|
+
|
|
12
|
+
from .base import BaseProvider
|
|
13
|
+
from ..types import (
|
|
14
|
+
ChatMessage,
|
|
15
|
+
ImageContent,
|
|
16
|
+
ProviderResponse,
|
|
17
|
+
TextContent,
|
|
18
|
+
TokenUsage,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _resolve_image_url(url: str) -> str:
|
|
23
|
+
if url.startswith("data:"):
|
|
24
|
+
return url
|
|
25
|
+
path = Path(url)
|
|
26
|
+
if path.is_file():
|
|
27
|
+
mime_type, _ = mimetypes.guess_type(str(path))
|
|
28
|
+
mime_type = mime_type or "image/png"
|
|
29
|
+
with open(path, "rb") as f:
|
|
30
|
+
b64 = base64.b64encode(f.read()).decode("utf-8")
|
|
31
|
+
return f"data:{mime_type};base64,{b64}"
|
|
32
|
+
return url
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class OpenAIProvider(BaseProvider):
|
|
36
|
+
def __init__(self, api_key: str, base_url: str = "https://api.openai.com/v1", model: str = "gpt-4"):
|
|
37
|
+
self._model = model
|
|
38
|
+
self._base_url = base_url
|
|
39
|
+
self._client = AsyncOpenAI(
|
|
40
|
+
api_key=api_key,
|
|
41
|
+
base_url=base_url,
|
|
42
|
+
default_headers={
|
|
43
|
+
"HTTP-Referer": "https://www.homecommunity.cn",
|
|
44
|
+
"X-Title": "txcode",
|
|
45
|
+
},
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
def get_model(self) -> str:
|
|
49
|
+
return self._model
|
|
50
|
+
|
|
51
|
+
def get_base_url(self) -> str:
|
|
52
|
+
return self._base_url
|
|
53
|
+
|
|
54
|
+
def _write_log(self, log_context: dict, event: str, extra: dict):
|
|
55
|
+
work_dir = log_context.get("work_dir", ".")
|
|
56
|
+
log_dir = Path(work_dir) / ".txcode" / "log"
|
|
57
|
+
log_dir.mkdir(parents=True, exist_ok=True)
|
|
58
|
+
entry = {
|
|
59
|
+
"timestamp": datetime.now(timezone.utc).isoformat(),
|
|
60
|
+
"session_id": log_context.get("session_id", ""),
|
|
61
|
+
"agent_type": log_context.get("agent_type", ""),
|
|
62
|
+
"iteration": log_context.get("iteration", 0),
|
|
63
|
+
"event": event,
|
|
64
|
+
**extra,
|
|
65
|
+
}
|
|
66
|
+
with open(log_dir / "txcode_access.log", "a", encoding="utf-8") as f:
|
|
67
|
+
f.write(json.dumps(entry, ensure_ascii=False, indent=2) + "\n")
|
|
68
|
+
|
|
69
|
+
async def chat(
|
|
70
|
+
self,
|
|
71
|
+
messages: list[ChatMessage],
|
|
72
|
+
tools: list[dict] | None = None,
|
|
73
|
+
abort_signal: Any = None,
|
|
74
|
+
log_context: dict | None = None,
|
|
75
|
+
) -> ProviderResponse:
|
|
76
|
+
resolved = await self._resolve_messages(messages)
|
|
77
|
+
kwargs: dict[str, Any] = {
|
|
78
|
+
"model": self._model,
|
|
79
|
+
"messages": resolved,
|
|
80
|
+
"temperature": 0.7,
|
|
81
|
+
"max_tokens": 8192,
|
|
82
|
+
}
|
|
83
|
+
if tools:
|
|
84
|
+
kwargs["tools"] = tools
|
|
85
|
+
kwargs["tool_choice"] = "auto"
|
|
86
|
+
|
|
87
|
+
if log_context:
|
|
88
|
+
self._write_log(log_context, "request", {
|
|
89
|
+
"model": self._model,
|
|
90
|
+
"messages": resolved,
|
|
91
|
+
"tools": tools or [],
|
|
92
|
+
})
|
|
93
|
+
|
|
94
|
+
response = await self._client.chat.completions.create(**kwargs)
|
|
95
|
+
parsed = self._parse_response(response)
|
|
96
|
+
|
|
97
|
+
if log_context:
|
|
98
|
+
self._write_log(log_context, "response", {
|
|
99
|
+
"model": self._model,
|
|
100
|
+
"finish_reason": parsed.finish_reason,
|
|
101
|
+
"content": parsed.content or "",
|
|
102
|
+
"tool_calls": parsed.tool_calls or [],
|
|
103
|
+
"usage": {
|
|
104
|
+
"prompt_tokens": parsed.usage.prompt_tokens,
|
|
105
|
+
"completion_tokens": parsed.usage.completion_tokens,
|
|
106
|
+
"total_tokens": parsed.usage.total_tokens,
|
|
107
|
+
} if parsed.usage else None,
|
|
108
|
+
})
|
|
109
|
+
|
|
110
|
+
return parsed
|
|
111
|
+
|
|
112
|
+
async def chat_stream(
|
|
113
|
+
self,
|
|
114
|
+
messages: list[ChatMessage],
|
|
115
|
+
tools: list[dict] | None = None,
|
|
116
|
+
abort_signal: Any = None,
|
|
117
|
+
) -> AsyncGenerator[str, None]:
|
|
118
|
+
resolved = await self._resolve_messages(messages)
|
|
119
|
+
kwargs: dict[str, Any] = {
|
|
120
|
+
"model": self._model,
|
|
121
|
+
"messages": resolved,
|
|
122
|
+
"temperature": 0.7,
|
|
123
|
+
"max_tokens": 2000,
|
|
124
|
+
"stream": True,
|
|
125
|
+
}
|
|
126
|
+
if tools:
|
|
127
|
+
kwargs["tools"] = tools
|
|
128
|
+
|
|
129
|
+
stream = await self._client.chat.completions.create(**kwargs)
|
|
130
|
+
async for chunk in stream:
|
|
131
|
+
delta = chunk.choices[0].delta if chunk.choices else None
|
|
132
|
+
if delta and delta.content:
|
|
133
|
+
yield delta.content
|
|
134
|
+
|
|
135
|
+
async def _resolve_messages(self, messages: list[ChatMessage]) -> list[dict]:
|
|
136
|
+
resolved: list[dict] = []
|
|
137
|
+
for msg in messages:
|
|
138
|
+
formatted = self._format_message(msg)
|
|
139
|
+
formatted["content"] = await self._resolve_content_images(msg.content)
|
|
140
|
+
resolved.append(formatted)
|
|
141
|
+
return resolved
|
|
142
|
+
|
|
143
|
+
def _format_message(self, msg: ChatMessage) -> dict:
|
|
144
|
+
formatted: dict = {"role": msg.role}
|
|
145
|
+
content = msg.content
|
|
146
|
+
if isinstance(content, list):
|
|
147
|
+
formatted["content"] = [c.to_dict() if hasattr(c, "to_dict") else c for c in content]
|
|
148
|
+
else:
|
|
149
|
+
formatted["content"] = content
|
|
150
|
+
|
|
151
|
+
if msg.name:
|
|
152
|
+
formatted["name"] = msg.name
|
|
153
|
+
if msg.tool_call_id:
|
|
154
|
+
formatted["tool_call_id"] = msg.tool_call_id
|
|
155
|
+
if msg.tool_calls:
|
|
156
|
+
formatted["tool_calls"] = msg.tool_calls
|
|
157
|
+
return formatted
|
|
158
|
+
|
|
159
|
+
async def _resolve_content_images(self, content: str | list) -> str | list:
|
|
160
|
+
if isinstance(content, str):
|
|
161
|
+
return content
|
|
162
|
+
resolved: list = []
|
|
163
|
+
for c in content:
|
|
164
|
+
if isinstance(c, ImageContent):
|
|
165
|
+
resolved.append(ImageContent(url=_resolve_image_url(c.image_url["url"])).to_dict())
|
|
166
|
+
elif hasattr(c, "to_dict"):
|
|
167
|
+
resolved.append(c.to_dict())
|
|
168
|
+
else:
|
|
169
|
+
resolved.append(c)
|
|
170
|
+
return resolved
|
|
171
|
+
|
|
172
|
+
def _parse_response(self, response: Any) -> ProviderResponse:
|
|
173
|
+
if not response.choices:
|
|
174
|
+
raise RuntimeError("Invalid response: no choices")
|
|
175
|
+
choice = response.choices[0]
|
|
176
|
+
msg = choice.message
|
|
177
|
+
|
|
178
|
+
usage = None
|
|
179
|
+
if response.usage:
|
|
180
|
+
usage = TokenUsage(
|
|
181
|
+
prompt_tokens=response.usage.prompt_tokens,
|
|
182
|
+
completion_tokens=response.usage.completion_tokens,
|
|
183
|
+
total_tokens=response.usage.total_tokens,
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
result = ProviderResponse(
|
|
187
|
+
content=msg.content or "",
|
|
188
|
+
finish_reason=choice.finish_reason or "stop",
|
|
189
|
+
usage=usage,
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
reasoning = getattr(msg, "reasoning_content", None) or getattr(response, "reasoning", None)
|
|
193
|
+
if reasoning:
|
|
194
|
+
result.reasoning = reasoning
|
|
195
|
+
|
|
196
|
+
if msg.tool_calls:
|
|
197
|
+
result.tool_calls = [
|
|
198
|
+
{
|
|
199
|
+
"id": tc.id,
|
|
200
|
+
"type": "function",
|
|
201
|
+
"function": {
|
|
202
|
+
"name": tc.function.name,
|
|
203
|
+
"arguments": tc.function.arguments,
|
|
204
|
+
},
|
|
205
|
+
}
|
|
206
|
+
for tc in msg.tool_calls
|
|
207
|
+
]
|
|
208
|
+
|
|
209
|
+
return result
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from .base import BaseProvider
|
|
4
|
+
from .openai_provider import OpenAIProvider
|
|
5
|
+
from .deepseek_provider import DeepSeekProvider
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class ProviderRouter:
|
|
9
|
+
@staticmethod
|
|
10
|
+
def create(api_key: str, base_url: str, model: str) -> BaseProvider:
|
|
11
|
+
if "deepseek" in base_url.lower() or model.lower().startswith("deepseek"):
|
|
12
|
+
return DeepSeekProvider(api_key, base_url, model)
|
|
13
|
+
return OpenAIProvider(api_key, base_url, model)
|
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import uuid
|
|
7
|
+
from datetime import datetime, timezone
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from ..types import ChatMessage, PrintMsgFormat
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _is_tool_success(tool_content: str) -> bool:
|
|
14
|
+
return not tool_content.startswith("Error:")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _format_tool_args(tool_name: str, args: dict) -> str:
|
|
18
|
+
key_map = {
|
|
19
|
+
"read_file": ["file_path"],
|
|
20
|
+
"write_file": ["file_path"],
|
|
21
|
+
"edit_file": ["file_path"],
|
|
22
|
+
"glob": ["pattern"],
|
|
23
|
+
"grep": ["pattern"],
|
|
24
|
+
"bash": ["command"],
|
|
25
|
+
}
|
|
26
|
+
keys = key_map.get(tool_name)
|
|
27
|
+
if keys:
|
|
28
|
+
parts = []
|
|
29
|
+
for k in keys:
|
|
30
|
+
v = args.get(k)
|
|
31
|
+
if v:
|
|
32
|
+
s = str(v)
|
|
33
|
+
if len(s) > 80:
|
|
34
|
+
s = s[:77] + "..."
|
|
35
|
+
parts.append(s)
|
|
36
|
+
result = " ".join(parts)
|
|
37
|
+
if len(result) > 80:
|
|
38
|
+
result = result[:77] + "..."
|
|
39
|
+
return result
|
|
40
|
+
for v in args.values():
|
|
41
|
+
if v:
|
|
42
|
+
s = str(v)
|
|
43
|
+
if len(s) > 80:
|
|
44
|
+
s = s[:77] + "..."
|
|
45
|
+
return s
|
|
46
|
+
return ""
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _build_print_msg(msg: dict, tool_results: dict[str, bool]) -> str | None:
|
|
50
|
+
role = msg.get("role", "")
|
|
51
|
+
content = msg.get("content", "")
|
|
52
|
+
|
|
53
|
+
if role == "tool":
|
|
54
|
+
return None
|
|
55
|
+
|
|
56
|
+
if role == "user":
|
|
57
|
+
text = content
|
|
58
|
+
if isinstance(content, list):
|
|
59
|
+
parts = []
|
|
60
|
+
for item in content:
|
|
61
|
+
if isinstance(item, dict) and item.get("type") == "text":
|
|
62
|
+
parts.append(item.get("text", ""))
|
|
63
|
+
elif isinstance(item, dict) and item.get("type") == "image_url":
|
|
64
|
+
url = item.get("image_url", {})
|
|
65
|
+
src = url.get("url", "") if isinstance(url, dict) else str(url)
|
|
66
|
+
parts.append(f"[Image: {src}]" if src else "[Image]")
|
|
67
|
+
elif hasattr(item, "type"):
|
|
68
|
+
if getattr(item, "type", "") == "text":
|
|
69
|
+
parts.append(getattr(item, "text", ""))
|
|
70
|
+
elif getattr(item, "type", "") == "image_url":
|
|
71
|
+
url = getattr(item, "image_url", {})
|
|
72
|
+
src = url.get("url", "") if isinstance(url, dict) else str(url)
|
|
73
|
+
parts.append(f"[Image: {src}]" if src else "[Image]")
|
|
74
|
+
text = " ".join(parts)
|
|
75
|
+
if len(text) > 200:
|
|
76
|
+
text = text[:197] + "..."
|
|
77
|
+
return f"{PrintMsgFormat.USER_PREFIX}: {text}" if text else f"{PrintMsgFormat.USER_PREFIX}: "
|
|
78
|
+
|
|
79
|
+
if role == "system":
|
|
80
|
+
text = content
|
|
81
|
+
if len(text) > 200:
|
|
82
|
+
text = text[:197] + "..."
|
|
83
|
+
return f"{PrintMsgFormat.SYSTEM_PREFIX}: {text}"
|
|
84
|
+
|
|
85
|
+
if role == "assistant":
|
|
86
|
+
parsed = None
|
|
87
|
+
try:
|
|
88
|
+
import json
|
|
89
|
+
parsed = json.loads(content)
|
|
90
|
+
except (json.JSONDecodeError, TypeError):
|
|
91
|
+
pass
|
|
92
|
+
|
|
93
|
+
if isinstance(parsed, dict) and parsed.get("type") == "assistant_with_tools":
|
|
94
|
+
tool_calls = parsed.get("toolCalls", [])
|
|
95
|
+
if not tool_calls:
|
|
96
|
+
return f"{PrintMsgFormat.ASSISTANT_PREFIX}: {content[:197]}..." if len(content) > 200 else f"{PrintMsgFormat.ASSISTANT_PREFIX}: {content}"
|
|
97
|
+
thought = parsed.get("thought", "") or "\u6267\u884c\u5de5\u5177"
|
|
98
|
+
parts = []
|
|
99
|
+
for tc in tool_calls:
|
|
100
|
+
tc_id = tc.get("id", "")
|
|
101
|
+
fn = tc.get("function", {})
|
|
102
|
+
name = fn.get("name", "unknown")
|
|
103
|
+
args_str = fn.get("arguments", "{}")
|
|
104
|
+
args = {}
|
|
105
|
+
try:
|
|
106
|
+
args = json.loads(args_str) if isinstance(args_str, str) else args_str
|
|
107
|
+
except (json.JSONDecodeError, TypeError):
|
|
108
|
+
pass
|
|
109
|
+
args_summary = _format_tool_args(name, args)
|
|
110
|
+
success = tool_results.get(tc_id)
|
|
111
|
+
if success is True:
|
|
112
|
+
mark = PrintMsgFormat.SUCCESS_MARK
|
|
113
|
+
elif success is False:
|
|
114
|
+
mark = PrintMsgFormat.FAILURE_MARK
|
|
115
|
+
else:
|
|
116
|
+
mark = PrintMsgFormat.UNKNOWN_MARK
|
|
117
|
+
parts.append(f"{{tool:'{mark} {name} {args_summary}', reason:'{thought}'}}")
|
|
118
|
+
return "; ".join(parts) if parts else None
|
|
119
|
+
|
|
120
|
+
text = content
|
|
121
|
+
if len(text) > 200:
|
|
122
|
+
text = text[:197] + "..."
|
|
123
|
+
return f"{PrintMsgFormat.ASSISTANT_PREFIX}: {text}"
|
|
124
|
+
|
|
125
|
+
return None
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class SessionManager:
|
|
129
|
+
def __init__(self, work_dir: str):
|
|
130
|
+
self._session_dir = Path(work_dir) / ".txcode" / "session"
|
|
131
|
+
self._locks: dict[str, asyncio.Lock] = {}
|
|
132
|
+
|
|
133
|
+
def _get_lock(self, session_id: str) -> asyncio.Lock:
|
|
134
|
+
if session_id not in self._locks:
|
|
135
|
+
self._locks[session_id] = asyncio.Lock()
|
|
136
|
+
return self._locks[session_id]
|
|
137
|
+
|
|
138
|
+
def _session_path(self, session_id: str) -> Path:
|
|
139
|
+
return self._session_dir / f"session_{session_id}.json"
|
|
140
|
+
|
|
141
|
+
def create(self, title: str = "") -> dict:
|
|
142
|
+
sid = uuid.uuid4().hex
|
|
143
|
+
now = datetime.now(timezone.utc).isoformat()
|
|
144
|
+
session = {
|
|
145
|
+
"id": sid,
|
|
146
|
+
"title": title,
|
|
147
|
+
"created_at": now,
|
|
148
|
+
"updated_at": now,
|
|
149
|
+
"prompt_tokens": 0,
|
|
150
|
+
"completion_tokens": 0,
|
|
151
|
+
"summary_message_index": None,
|
|
152
|
+
"messages": [],
|
|
153
|
+
}
|
|
154
|
+
self._session_dir.mkdir(parents=True, exist_ok=True)
|
|
155
|
+
with open(self._session_path(sid), "w", encoding="utf-8") as f:
|
|
156
|
+
json.dump(session, f, ensure_ascii=False, indent=2)
|
|
157
|
+
return session
|
|
158
|
+
|
|
159
|
+
def get(self, session_id: str) -> dict | None:
|
|
160
|
+
path = self._session_path(session_id)
|
|
161
|
+
if not path.exists():
|
|
162
|
+
return None
|
|
163
|
+
with open(path, "r", encoding="utf-8") as f:
|
|
164
|
+
return json.load(f)
|
|
165
|
+
|
|
166
|
+
def add_message(
|
|
167
|
+
self,
|
|
168
|
+
session_id: str,
|
|
169
|
+
role: str,
|
|
170
|
+
content: str,
|
|
171
|
+
keep_context: bool = True,
|
|
172
|
+
is_original: bool = False,
|
|
173
|
+
tool_call_id: str | None = None,
|
|
174
|
+
media_files: list[dict] | None = None,
|
|
175
|
+
) -> int:
|
|
176
|
+
session = self.get(session_id)
|
|
177
|
+
if not session:
|
|
178
|
+
return -1
|
|
179
|
+
|
|
180
|
+
messages = session.get("messages", [])
|
|
181
|
+
index = len(messages)
|
|
182
|
+
now = datetime.now(timezone.utc).isoformat()
|
|
183
|
+
|
|
184
|
+
msg: dict = {
|
|
185
|
+
"index": index,
|
|
186
|
+
"role": role,
|
|
187
|
+
"content": content,
|
|
188
|
+
"keep_context": keep_context,
|
|
189
|
+
"is_original": is_original,
|
|
190
|
+
"created_at": now,
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
if tool_call_id:
|
|
194
|
+
msg["tool_call_id"] = tool_call_id
|
|
195
|
+
if media_files:
|
|
196
|
+
msg["media_files"] = media_files
|
|
197
|
+
|
|
198
|
+
messages.append(msg)
|
|
199
|
+
session["updated_at"] = now
|
|
200
|
+
self._write(session_id, session)
|
|
201
|
+
return index
|
|
202
|
+
|
|
203
|
+
def get_messages_for_ai(
|
|
204
|
+
self, session_id: str, summary_index: int | None = None
|
|
205
|
+
) -> list[dict]:
|
|
206
|
+
session = self.get(session_id)
|
|
207
|
+
if not session:
|
|
208
|
+
return []
|
|
209
|
+
|
|
210
|
+
messages = session.get("messages", [])
|
|
211
|
+
if summary_index is not None:
|
|
212
|
+
messages = messages[summary_index:]
|
|
213
|
+
return messages
|
|
214
|
+
|
|
215
|
+
def update_tokens(self, session_id: str, prompt: int, completion: int):
|
|
216
|
+
session = self.get(session_id)
|
|
217
|
+
if not session:
|
|
218
|
+
return
|
|
219
|
+
session["prompt_tokens"] = session.get("prompt_tokens", 0) + prompt
|
|
220
|
+
session["completion_tokens"] = session.get("completion_tokens", 0) + completion
|
|
221
|
+
self._write(session_id, session)
|
|
222
|
+
|
|
223
|
+
def reset_tokens(self, session_id: str):
|
|
224
|
+
session = self.get(session_id)
|
|
225
|
+
if not session:
|
|
226
|
+
return
|
|
227
|
+
session["prompt_tokens"] = 0
|
|
228
|
+
session["completion_tokens"] = 0
|
|
229
|
+
self._write(session_id, session)
|
|
230
|
+
|
|
231
|
+
def update_summary(self, session_id: str, summary_index: int):
|
|
232
|
+
session = self.get(session_id)
|
|
233
|
+
if not session:
|
|
234
|
+
return
|
|
235
|
+
session["summary_message_index"] = summary_index
|
|
236
|
+
self._write(session_id, session)
|
|
237
|
+
|
|
238
|
+
def delete(self, session_id: str):
|
|
239
|
+
path = self._session_path(session_id)
|
|
240
|
+
if path.exists():
|
|
241
|
+
path.unlink()
|
|
242
|
+
|
|
243
|
+
def list_sessions(self) -> list[dict]:
|
|
244
|
+
self._session_dir.mkdir(parents=True, exist_ok=True)
|
|
245
|
+
sessions: list[dict] = []
|
|
246
|
+
for f in sorted(self._session_dir.glob("session_*.json")):
|
|
247
|
+
try:
|
|
248
|
+
with open(f, "r", encoding="utf-8") as fh:
|
|
249
|
+
sessions.append(json.load(fh))
|
|
250
|
+
except Exception:
|
|
251
|
+
continue
|
|
252
|
+
return sessions
|
|
253
|
+
|
|
254
|
+
def list_sessions_summary(self) -> list[dict]:
|
|
255
|
+
self._session_dir.mkdir(parents=True, exist_ok=True)
|
|
256
|
+
summaries: list[dict] = []
|
|
257
|
+
for f in sorted(self._session_dir.glob("session_*.json")):
|
|
258
|
+
try:
|
|
259
|
+
with open(f, "r", encoding="utf-8") as fh:
|
|
260
|
+
data = json.load(fh)
|
|
261
|
+
messages = data.get("messages", [])
|
|
262
|
+
first_user = ""
|
|
263
|
+
for m in messages:
|
|
264
|
+
if m.get("role") == "user":
|
|
265
|
+
first_user = m.get("content", "")
|
|
266
|
+
break
|
|
267
|
+
title = data.get("title", "") or first_user[:50]
|
|
268
|
+
created = data.get("created_at", "")[:10]
|
|
269
|
+
summary = {
|
|
270
|
+
"id": data.get("id", ""),
|
|
271
|
+
"title": title,
|
|
272
|
+
"created_at": data.get("created_at", ""),
|
|
273
|
+
"updated_at": data.get("updated_at", ""),
|
|
274
|
+
"message_count": len(messages),
|
|
275
|
+
"print_summary": f"[{created}] {title[:50]} ({len(messages)} messages)",
|
|
276
|
+
}
|
|
277
|
+
summaries.append(summary)
|
|
278
|
+
except Exception:
|
|
279
|
+
continue
|
|
280
|
+
return summaries
|
|
281
|
+
|
|
282
|
+
def get_session_messages(self, session_id: str) -> dict | None:
|
|
283
|
+
session = self.get(session_id)
|
|
284
|
+
if not session:
|
|
285
|
+
return None
|
|
286
|
+
messages = session.get("messages", [])
|
|
287
|
+
tool_results: dict[str, bool] = {}
|
|
288
|
+
for m in messages:
|
|
289
|
+
if m.get("role") == "tool":
|
|
290
|
+
tc_id = m.get("tool_call_id")
|
|
291
|
+
if tc_id:
|
|
292
|
+
tool_results[tc_id] = _is_tool_success(m.get("content", ""))
|
|
293
|
+
result_messages: list[dict] = []
|
|
294
|
+
for m in messages:
|
|
295
|
+
msg_copy = dict(m)
|
|
296
|
+
msg_copy["printMsg"] = _build_print_msg(m, tool_results)
|
|
297
|
+
result_messages.append(msg_copy)
|
|
298
|
+
created = session.get("created_at", "")[:10]
|
|
299
|
+
title = session.get("title", "")
|
|
300
|
+
if not title:
|
|
301
|
+
for m in messages:
|
|
302
|
+
if m.get("role") == "user":
|
|
303
|
+
title = m.get("content", "")[:50]
|
|
304
|
+
break
|
|
305
|
+
return {
|
|
306
|
+
"session_id": session.get("id", ""),
|
|
307
|
+
"title": title,
|
|
308
|
+
"created_at": session.get("created_at", ""),
|
|
309
|
+
"updated_at": session.get("updated_at", ""),
|
|
310
|
+
"messages": result_messages,
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
def _write(self, session_id: str, data: dict):
|
|
314
|
+
self._session_dir.mkdir(parents=True, exist_ok=True)
|
|
315
|
+
with open(self._session_path(session_id), "w", encoding="utf-8") as f:
|
|
316
|
+
json.dump(data, f, ensure_ascii=False, indent=2)
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def build_available_skills_prompt(work_dir: str) -> str:
|
|
7
|
+
skills_dir = Path(work_dir) / ".txcode" / "skills"
|
|
8
|
+
if not skills_dir.exists():
|
|
9
|
+
return "<available_skills>\n (无可用 Skills)\n</available_skills>"
|
|
10
|
+
|
|
11
|
+
skills: list[dict] = []
|
|
12
|
+
for entry in sorted(skills_dir.iterdir()):
|
|
13
|
+
if entry.is_dir():
|
|
14
|
+
skill_md = entry / "SKILL.md"
|
|
15
|
+
if skill_md.exists():
|
|
16
|
+
try:
|
|
17
|
+
content = skill_md.read_text("utf-8", errors="replace")
|
|
18
|
+
lines = [l.strip() for l in content.splitlines() if l.strip()]
|
|
19
|
+
name = entry.name
|
|
20
|
+
description = ""
|
|
21
|
+
if lines:
|
|
22
|
+
name = lines[0].strip("#").strip()
|
|
23
|
+
if len(lines) > 1:
|
|
24
|
+
description = lines[1]
|
|
25
|
+
skills.append({"name": name, "path": str(skill_md), "description": description})
|
|
26
|
+
except Exception:
|
|
27
|
+
pass
|
|
28
|
+
|
|
29
|
+
if not skills:
|
|
30
|
+
return "<available_skills>\n (无可用 Skills)\n</available_skills>"
|
|
31
|
+
|
|
32
|
+
xml_parts = []
|
|
33
|
+
for s in skills:
|
|
34
|
+
xml_parts.append(
|
|
35
|
+
f" <skill>\n <name>{_escape_xml(s['name'])}</name>\n"
|
|
36
|
+
f" <path>{_escape_xml(s['path'])}</path>\n"
|
|
37
|
+
f" <description>{_escape_xml(s['description'])}</description>\n </skill>"
|
|
38
|
+
)
|
|
39
|
+
return "<available_skills>\n" + "\n".join(xml_parts) + "\n</available_skills>"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _escape_xml(s: str) -> str:
|
|
43
|
+
return s.replace("&", "&").replace("<", "<").replace(">", ">").replace('"', """).replace("'", "'")
|