txcode-sdk 0.1.0__py3-none-any.whl → 0.4.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.
Files changed (112) hide show
  1. example/__init__.py +1 -0
  2. example/code_example.py +96 -0
  3. example/code_session.py +80 -0
  4. example/code_tool.py +110 -0
  5. example/constants.py +6 -0
  6. example/query_session.py +70 -0
  7. example/ws_server.py +105 -0
  8. txcode_sdk/__init__.py +33 -1
  9. txcode_sdk/_compat/__init__.py +5 -0
  10. txcode_sdk/_compat/dataclasses.py +121 -0
  11. txcode_sdk/_compat/resources.py +19 -0
  12. txcode_sdk/agent/__init__.py +16 -0
  13. txcode_sdk/agent/base_agent.py +31 -28
  14. txcode_sdk/agent/chat/agent_tool.py +5 -1
  15. txcode_sdk/agent/chat/chat_agent.py +4 -2
  16. txcode_sdk/agent/chat/prompts/__init__.py +1 -0
  17. txcode_sdk/agent/code/code_agent.py +4 -2
  18. txcode_sdk/agent/code/prompts/__init__.py +1 -0
  19. txcode_sdk/agent/common/common_agent.py +5 -1
  20. txcode_sdk/agent/common/prompt/__init__.py +0 -0
  21. txcode_sdk/agent/design/__init__.py +4 -0
  22. txcode_sdk/agent/design/agent_tool.py +1 -0
  23. txcode_sdk/agent/design/design_agent.py +28 -0
  24. txcode_sdk/agent/design/prompts/__init__.py +1 -0
  25. txcode_sdk/agent/design/prompts/role.txt +36 -0
  26. txcode_sdk/agent/discuss/__init__.py +4 -0
  27. txcode_sdk/agent/discuss/agent_tool.py +1 -0
  28. txcode_sdk/agent/discuss/discuss_agent.py +28 -0
  29. txcode_sdk/agent/discuss/prompts/__init__.py +1 -0
  30. txcode_sdk/agent/discuss/prompts/role.txt +28 -0
  31. txcode_sdk/agent/dream/__init__.py +4 -0
  32. txcode_sdk/agent/dream/agent_tool.py +1 -0
  33. txcode_sdk/agent/dream/dream_agent.py +28 -0
  34. txcode_sdk/agent/dream/prompts/__init__.py +1 -0
  35. txcode_sdk/agent/dream/prompts/role.txt +21 -0
  36. txcode_sdk/agent/mem/mem_agent.py +8 -8
  37. txcode_sdk/agent/mem/prompts/__init__.py +1 -0
  38. txcode_sdk/agent/name/__init__.py +3 -0
  39. txcode_sdk/agent/name/name_agent.py +55 -0
  40. txcode_sdk/agent/name/prompts/__init__.py +1 -0
  41. txcode_sdk/agent/name/prompts/role.txt +8 -0
  42. txcode_sdk/agent/plan/__init__.py +4 -0
  43. txcode_sdk/agent/plan/agent_tool.py +1 -0
  44. txcode_sdk/agent/plan/plan_agent.py +30 -0
  45. txcode_sdk/agent/plan/prompts/__init__.py +1 -0
  46. txcode_sdk/agent/plan/prompts/role.txt +47 -0
  47. txcode_sdk/agent/shell/__init__.py +4 -0
  48. txcode_sdk/agent/shell/agent_tool.py +1 -0
  49. txcode_sdk/agent/shell/prompts/__init__.py +1 -0
  50. txcode_sdk/agent/shell/prompts/role.txt +29 -0
  51. txcode_sdk/agent/shell/shell_agent.py +28 -0
  52. txcode_sdk/agent/skill/__init__.py +4 -0
  53. txcode_sdk/agent/skill/agent_tool.py +1 -0
  54. txcode_sdk/agent/skill/prompts/__init__.py +1 -0
  55. txcode_sdk/agent/skill/prompts/role.txt +62 -0
  56. txcode_sdk/agent/skill/skill_agent.py +80 -0
  57. txcode_sdk/agent/summarizer/prompts/__init__.py +1 -0
  58. txcode_sdk/agent/summarizer/summarizer_agent.py +7 -7
  59. txcode_sdk/agent/task/prompts/__init__.py +1 -0
  60. txcode_sdk/agent/task/task_agent.py +4 -2
  61. txcode_sdk/agent/test/__init__.py +4 -0
  62. txcode_sdk/agent/test/agent_tool.py +1 -0
  63. txcode_sdk/agent/test/prompts/__init__.py +1 -0
  64. txcode_sdk/agent/test/prompts/role.txt +21 -0
  65. txcode_sdk/agent/test/test_agent.py +32 -0
  66. txcode_sdk/agent/tool_registry.py +21 -16
  67. txcode_sdk/client.py +154 -17
  68. txcode_sdk/compact/compressor.py +6 -5
  69. txcode_sdk/hooks/__init__.py +1 -1
  70. txcode_sdk/hooks/handlers/base.py +3 -2
  71. txcode_sdk/hooks/handlers/memory.py +1 -1
  72. txcode_sdk/hooks/processor.py +4 -3
  73. txcode_sdk/hooks/queue.py +5 -5
  74. txcode_sdk/hooks/types.py +6 -4
  75. txcode_sdk/provider/base.py +12 -8
  76. txcode_sdk/provider/deepseek_provider.py +8 -55
  77. txcode_sdk/provider/openai_provider.py +56 -40
  78. txcode_sdk/provider/router.py +1 -1
  79. txcode_sdk/provider/txcode_ai.py +200 -0
  80. txcode_sdk/server/__init__.py +5 -0
  81. txcode_sdk/server/__main__.py +198 -0
  82. txcode_sdk/server/handler.py +542 -0
  83. txcode_sdk/server/json_store.py +50 -0
  84. txcode_sdk/server/project_manager.py +120 -0
  85. txcode_sdk/server/provider_config.py +346 -0
  86. txcode_sdk/server/server.py +83 -0
  87. txcode_sdk/server/websocket.py +234 -0
  88. txcode_sdk/session/manager.py +16 -15
  89. txcode_sdk/skills/__init__.py +9 -5
  90. txcode_sdk/specs/__init__.py +24 -14
  91. txcode_sdk/tools/bash_tool.py +3 -3
  92. txcode_sdk/tools/edit_file.py +12 -11
  93. txcode_sdk/tools/glob_tool.py +5 -4
  94. txcode_sdk/tools/grep_tool.py +5 -4
  95. txcode_sdk/tools/memory_tool.py +1 -1
  96. txcode_sdk/tools/read_file.py +6 -5
  97. txcode_sdk/tools/todo_read.py +40 -0
  98. txcode_sdk/tools/todo_read.txt +15 -0
  99. txcode_sdk/tools/todo_write.py +66 -0
  100. txcode_sdk/tools/todo_write.txt +47 -0
  101. txcode_sdk/tools/web_shell_exec.py +77 -0
  102. txcode_sdk/tools/web_shell_exec.txt +14 -0
  103. txcode_sdk/tools/write_file.py +3 -3
  104. txcode_sdk/types.py +33 -30
  105. txcode_sdk-0.4.0.dist-info/METADATA +254 -0
  106. txcode_sdk-0.4.0.dist-info/RECORD +136 -0
  107. {txcode_sdk-0.1.0.dist-info → txcode_sdk-0.4.0.dist-info}/WHEEL +2 -1
  108. txcode_sdk-0.4.0.dist-info/entry_points.txt +2 -0
  109. txcode_sdk-0.4.0.dist-info/top_level.txt +2 -0
  110. txcode_sdk-0.1.0.dist-info/METADATA +0 -58
  111. txcode_sdk-0.1.0.dist-info/RECORD +0 -64
  112. {txcode_sdk-0.1.0.dist-info → txcode_sdk-0.4.0.dist-info}/licenses/LICENSE +0 -0
example/__init__.py ADDED
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,96 @@
1
+ import asyncio
2
+ import json
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
7
+
8
+ from txcode_sdk import TxCodeClient
9
+ from txcode_sdk.types import StepInfo
10
+
11
+ from constants import API_KEY, BASE_URL, MAX_CONTEXT_TOKENS, MAX_ITERATIONS, MODEL, WORK_DIR
12
+
13
+
14
+ def on_step(step: StepInfo):
15
+ print(f"\n--- Iteration {step.iteration} ---")
16
+ for i, tc in enumerate(step.tool_calls):
17
+ print(f" Tool Call [{i}]: name={tc.name}")
18
+ print(f" arguments={json.dumps(tc.arguments, ensure_ascii=False)}")
19
+ if i < len(step.results):
20
+ res = step.results[i]
21
+ output = (res.output or "")[:200]
22
+ print(f" result: success={res.success}, output={output}")
23
+ if res.error:
24
+ print(f" error={res.error}")
25
+
26
+
27
+ async def _verify_last_message(client: TxCodeClient, session_id: str):
28
+ session = client.get_session(session_id)
29
+ if not session:
30
+ print("[FAIL] Session not found")
31
+ return
32
+
33
+ messages = session.get("messages", [])
34
+ if not messages:
35
+ print("[FAIL] No messages in session")
36
+ return
37
+
38
+ print(f"\nTotal messages in session: {len(messages)}")
39
+
40
+ ai_messages = [m for m in messages if m.get("role") in ("assistant", "tool")]
41
+ errors: list = []
42
+
43
+ for i, msg in enumerate(ai_messages):
44
+ role = msg.get("role", "")
45
+ content = msg.get("content", "")
46
+
47
+ if role == "assistant" and msg.get("content", "").startswith('{"type":"assistant_with_tools"'):
48
+ continue
49
+
50
+ if i > 0:
51
+ prev_role = ai_messages[i - 1].get("role", "")
52
+ if role == prev_role and role != "tool":
53
+ errors.append(f"Consecutive same role: index={msg.get('index')} role={role}")
54
+
55
+ if role == "tool":
56
+ if not content:
57
+ errors.append(f"Empty tool content: index={msg.get('index')}")
58
+
59
+ assistant_msgs = [m for m in ai_messages if m.get("role") == "assistant" and m.get("content") and not m.get("content", "").startswith('{"type":"assistant_with_tools"')]
60
+ if assistant_msgs:
61
+ last = assistant_msgs[-1]
62
+ if not last.get("content"):
63
+ errors.append("Final assistant message has empty content")
64
+
65
+ if errors:
66
+ print(f"[FAIL] {len(errors)} issue(s) found:")
67
+ for e in errors:
68
+ print(f" - {e}")
69
+ else:
70
+ print("[PASS] All message checks passed")
71
+
72
+
73
+ async def main():
74
+ client = TxCodeClient(
75
+ api_key=API_KEY,
76
+ base_url=BASE_URL,
77
+ model=MODEL,
78
+ agent_type="code",
79
+ max_context_tokens=MAX_CONTEXT_TOKENS,
80
+ max_iterations=MAX_ITERATIONS,
81
+ work_dir=WORK_DIR,
82
+ log_enabled=True,
83
+ )
84
+
85
+ result = await client.chat(
86
+ message="请列出当前目录下的所有 .py 文件",
87
+ on_step=on_step,
88
+ )
89
+
90
+ print(f"\n=== Final Answer ===\n{result.answer}")
91
+
92
+ await _verify_last_message(client, result.session_id)
93
+
94
+
95
+ if __name__ == "__main__":
96
+ asyncio.get_event_loop().run_until_complete(main())
@@ -0,0 +1,80 @@
1
+ import asyncio
2
+ import json
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
7
+
8
+ from txcode_sdk import TxCodeClient
9
+ from txcode_sdk.types import StepInfo
10
+
11
+ from constants import API_KEY, BASE_URL, MAX_CONTEXT_TOKENS, MAX_ITERATIONS, MODEL, WORK_DIR
12
+
13
+
14
+ def on_step(step: StepInfo):
15
+ print(f"\n--- Iteration {step.iteration} ---")
16
+ for i, tc in enumerate(step.tool_calls):
17
+ print(f" Tool Call [{i}]: name={tc.name}")
18
+ print(f" arguments={json.dumps(tc.arguments, ensure_ascii=False)}")
19
+
20
+
21
+ async def main():
22
+ client = TxCodeClient(
23
+ api_key=API_KEY,
24
+ base_url=BASE_URL,
25
+ model=MODEL,
26
+ agent_type="code",
27
+ max_context_tokens=MAX_CONTEXT_TOKENS,
28
+ max_iterations=MAX_ITERATIONS,
29
+ work_dir=WORK_DIR,
30
+ log_enabled=True,
31
+ )
32
+
33
+ session_id = "test-session-001"
34
+
35
+ print("=" * 60)
36
+ print("Round 1: 第一轮对话")
37
+ print("=" * 60)
38
+ result1 = await client.chat(
39
+ message="请记住我的名字叫小明",
40
+ session_id=session_id,
41
+ on_step=on_step,
42
+ )
43
+ print(f"\n[Round 1 Answer] {result1.answer}")
44
+
45
+ print("\n" + "=" * 60)
46
+ print("Round 2: 第二轮对话(相同 session_id)")
47
+ print("=" * 60)
48
+ result2 = await client.chat(
49
+ message="我叫什么名字?",
50
+ session_id=session_id,
51
+ on_step=on_step,
52
+ )
53
+ print(f"\n[Round 2 Answer] {result2.answer}")
54
+
55
+ print("\n" + "=" * 60)
56
+ print("会话验证")
57
+ print("=" * 60)
58
+
59
+ session = client.get_session(session_id)
60
+ if session:
61
+ messages = session.get("messages", [])
62
+ print(f"session_id: {session_id}")
63
+ print(f"消息总数: {len(messages)}")
64
+ for msg in messages:
65
+ role = msg.get("role", "")
66
+ content = msg.get("content", "")
67
+ if isinstance(content, str) and len(content) > 100:
68
+ content = content[:100] + "..."
69
+ print(f" [{role}] {content}")
70
+
71
+ if len(messages) >= 4:
72
+ print("\n[PASS] 会话包含两轮对话消息,上下文保持正常")
73
+ else:
74
+ print("\n[FAIL] 会话消息数不足,可能未保留上下文")
75
+ else:
76
+ print(f"[FAIL] 未找到 session: {session_id}")
77
+
78
+
79
+ if __name__ == "__main__":
80
+ asyncio.get_event_loop().run_until_complete(main())
example/code_tool.py ADDED
@@ -0,0 +1,110 @@
1
+ import asyncio
2
+ import json
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
7
+
8
+ from txcode_sdk import TxCodeClient
9
+ from txcode_sdk.types import StepInfo, Tool, ToolContext, ToolResult
10
+
11
+ from constants import API_KEY, BASE_URL, MAX_CONTEXT_TOKENS, MAX_ITERATIONS, MODEL, WORK_DIR
12
+
13
+
14
+ def _execute_calculator(args: dict, ctx: ToolContext) -> ToolResult:
15
+ op = args.get("operation")
16
+ a = args.get("a", 0)
17
+ b = args.get("b", 0)
18
+ ops = {
19
+ "add": a + b,
20
+ "subtract": a - b,
21
+ "multiply": a * b,
22
+ "divide": a / b if b else "Error: div by zero",
23
+ }
24
+ if op in ops:
25
+ return ToolResult(success=True, output=str(ops[op]))
26
+ return ToolResult(success=False, output="", error=f"Unknown operation: {op}")
27
+
28
+
29
+ calculator_tool = Tool(
30
+ name="calculator",
31
+ description="执行基本数学运算",
32
+ parameters={
33
+ "type": "object",
34
+ "properties": {
35
+ "operation": {"type": "string", "enum": ["add", "subtract", "multiply", "divide"]},
36
+ "a": {"type": "number"},
37
+ "b": {"type": "number"},
38
+ },
39
+ "required": ["operation", "a", "b"],
40
+ },
41
+ execute=_execute_calculator,
42
+ )
43
+
44
+
45
+ def on_step(step: StepInfo):
46
+ print(f"\n--- Iteration {step.iteration} ---")
47
+ for i, tc in enumerate(step.tool_calls):
48
+ print(f" Tool Call [{i}]: name={tc.name}")
49
+ print(f" arguments={json.dumps(tc.arguments, ensure_ascii=False)}")
50
+ if i < len(step.results):
51
+ res = step.results[i]
52
+ output = (res.output or "")[:200]
53
+ print(f" result: success={res.success}, output={output}")
54
+ if res.error:
55
+ print(f" error={res.error}")
56
+
57
+
58
+ async def _verify_tool_result(client: TxCodeClient, session_id: str):
59
+ session = client.get_session(session_id)
60
+ if not session:
61
+ print("[FAIL] Session not found")
62
+ return
63
+
64
+ messages = session.get("messages", [])
65
+ calculator_found = False
66
+ result_ok = False
67
+
68
+ for msg in messages:
69
+ content = msg.get("content", "")
70
+ if "calculator" in content:
71
+ calculator_found = True
72
+ if "126.0" in content or "126" in content:
73
+ result_ok = True
74
+
75
+ if calculator_found:
76
+ print("[PASS] Calculator tool was invoked")
77
+ else:
78
+ print("[FAIL] Calculator tool not found in session messages")
79
+
80
+ if result_ok:
81
+ print("[PASS] Expected result 126 found in session")
82
+ else:
83
+ print("[FAIL] Expected result 126 not found in session")
84
+
85
+
86
+ async def main():
87
+ client = TxCodeClient(
88
+ api_key=API_KEY,
89
+ base_url=BASE_URL,
90
+ model=MODEL,
91
+ agent_type="code",
92
+ tools=[calculator_tool],
93
+ max_context_tokens=MAX_CONTEXT_TOKENS,
94
+ max_iterations=MAX_ITERATIONS,
95
+ work_dir=WORK_DIR,
96
+ log_enabled=True,
97
+ )
98
+
99
+ result = await client.chat(
100
+ message="请用计算器工具计算 (15 + 27) * 3 的结果",
101
+ on_step=on_step,
102
+ )
103
+
104
+ print(f"\n=== Final Answer ===\n{result.answer}")
105
+
106
+ await _verify_tool_result(client, result.session_id)
107
+
108
+
109
+ if __name__ == "__main__":
110
+ asyncio.get_event_loop().run_until_complete(main())
example/constants.py ADDED
@@ -0,0 +1,6 @@
1
+ MODEL = "deepseek-v4-flash"
2
+ BASE_URL = "https://api.deepseek.com/v1"
3
+ API_KEY = "xxx"
4
+ MAX_CONTEXT_TOKENS = 150_000
5
+ MAX_ITERATIONS = 25
6
+ WORK_DIR = "."
@@ -0,0 +1,70 @@
1
+ import sys
2
+ from pathlib import Path
3
+
4
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
5
+
6
+ from txcode_sdk.session.manager import SessionManager
7
+ from txcode_sdk.types import StepInfo
8
+ from constants import WORK_DIR
9
+
10
+
11
+ def demo_list_sessions():
12
+ manager = SessionManager(WORK_DIR)
13
+ summaries = manager.list_sessions_summary()
14
+ print(f"=== Sessions ({len(summaries)}) ===")
15
+ for s in summaries:
16
+ print(f" {s['print_summary']}")
17
+
18
+
19
+ def demo_get_session_messages(session_id: str):
20
+ manager = SessionManager(WORK_DIR)
21
+ detail = manager.get_session_messages(session_id)
22
+ if not detail:
23
+ print(f"Session {session_id} not found")
24
+ return
25
+ print(f"\n=== Session: {detail['title']} ===")
26
+ for msg in detail["messages"]:
27
+ pm = msg.get("printMsg")
28
+ if pm:
29
+ try:
30
+ print(f" {pm}")
31
+ except UnicodeEncodeError:
32
+ safe_pm = pm.encode("ascii", errors="replace").decode("ascii")
33
+ print(f" {safe_pm}")
34
+
35
+
36
+ def demo_step_print():
37
+ from txcode_sdk.agent.base_agent import _build_step_print_msg
38
+ from txcode_sdk.types import StepInfo, ToolCallInfo, ToolResultInfo
39
+
40
+ step = StepInfo(
41
+ reasoning="need to find all Python files first",
42
+ tool_calls=[
43
+ ToolCallInfo(id="c1", name="glob", arguments={"pattern": "**/*.py"}),
44
+ ToolCallInfo(id="c2", name="read_file", arguments={"file_path": "/test/main.py"}),
45
+ ],
46
+ results=[
47
+ ToolResultInfo(name="glob", success=True, output="found 3 files"),
48
+ ToolResultInfo(name="read_file", success=False, error="not found"),
49
+ ],
50
+ iteration=1,
51
+ )
52
+ msg = _build_step_print_msg(step)
53
+ print(f"\n=== on_step printMsg ===")
54
+ if msg:
55
+ try:
56
+ print(msg)
57
+ except UnicodeEncodeError:
58
+ safe_msg = msg.encode("ascii", errors="replace").decode("ascii")
59
+ print(safe_msg)
60
+
61
+
62
+ if __name__ == "__main__":
63
+ demo_list_sessions()
64
+
65
+ manager = SessionManager(WORK_DIR)
66
+ sessions = manager.list_sessions_summary()
67
+ if sessions:
68
+ demo_get_session_messages(sessions[0]["id"])
69
+
70
+ demo_step_print()
example/ws_server.py ADDED
@@ -0,0 +1,105 @@
1
+ """进阶示例:自定义门禁硬件工具(open_door 等)+ 启动 WebSocket 服务。
2
+
3
+ 场景:`txcode-sdk serve` CLI 只支持内置工具(本地远程开发足够);
4
+ 需要对接门禁硬件控制(open_door / get_door_status 等)时,用本示例代码注册自定义工具。
5
+
6
+ 0.4.0 起支持供应商/模型/项目管理:ProviderConfigManager / ProjectManager 可注入
7
+ `TxCodeServer`(缺省内部构造读用户层 `~/.txcode/providers.json` / `projects.json`);
8
+ 本示例展示注入形态与运行期 set_provider / set_work_dir 用法。
9
+
10
+ 环境变量:TXCODE_API_KEY(必填)/ TXCODE_BASE_URL / TXCODE_MODEL / TXCODE_WORK_DIR
11
+ (CLI `txcode-sdk serve` 走 JSON 权威源装配,见 README;本示例直接读环境变量构造 client)"""
12
+
13
+ import asyncio
14
+ import os
15
+ import sys
16
+
17
+ from txcode_sdk import Tool, ToolResult, TxCodeClient
18
+ from txcode_sdk.server import TxCodeServer
19
+ from txcode_sdk.server.provider_config import ProviderConfigManager
20
+ from txcode_sdk.server.project_manager import ProjectManager
21
+
22
+
23
+ def open_door(args, ctx):
24
+ """门禁硬件控制逻辑(示例:实际对接 GPIO/串口/继电器等)。"""
25
+ door_id = args.get("door_id", "main")
26
+ print("[open_door] opening door:", door_id)
27
+ return ToolResult(success=True, output="door %s opened" % door_id)
28
+
29
+
30
+ def get_door_status(args, ctx):
31
+ """查询门禁状态。"""
32
+ return ToolResult(success=True, output="closed")
33
+
34
+
35
+ def _get_event_loop():
36
+ """3.6/3.12 双版本兼容:已在运行 loop 则复用;否则新建(避免 3.12 弃用警告)。"""
37
+ if hasattr(asyncio, "get_running_loop"):
38
+ try:
39
+ return asyncio.get_running_loop()
40
+ except RuntimeError:
41
+ pass
42
+ loop = asyncio.new_event_loop()
43
+ asyncio.set_event_loop(loop)
44
+ return loop
45
+
46
+
47
+ def main() -> int:
48
+ api_key = os.environ.get("TXCODE_API_KEY", "").strip()
49
+ if not api_key:
50
+ sys.stderr.write(
51
+ "[txcode-sdk] ERROR: TXCODE_API_KEY is not set, run: export TXCODE_API_KEY=sk-xxx\n"
52
+ )
53
+ return 1
54
+
55
+ client = TxCodeClient(
56
+ api_key=api_key,
57
+ base_url=os.environ.get("TXCODE_BASE_URL", "https://api.openai.com/v1").strip() or "https://api.openai.com/v1",
58
+ model=os.environ.get("TXCODE_MODEL", "gpt-4").strip() or "gpt-4",
59
+ work_dir=os.environ.get("TXCODE_WORK_DIR", "/opt/door-access").strip() or "/opt/door-access",
60
+ agent_type="code",
61
+ tools=[
62
+ Tool(
63
+ name="open_door",
64
+ description="打开门禁(硬件控制)",
65
+ parameters={
66
+ "type": "object",
67
+ "properties": {"door_id": {"type": "string", "description": "门编号"}},
68
+ },
69
+ execute=open_door,
70
+ ),
71
+ Tool(
72
+ name="get_door_status",
73
+ description="获取门禁状态",
74
+ parameters={"type": "object", "properties": {}},
75
+ execute=get_door_status,
76
+ ),
77
+ ],
78
+ )
79
+
80
+ # 0.4.0:供应商/项目管理器注入 TxCodeServer(缺省读 ~/.txcode/providers.json / projects.json)
81
+ provider_config = ProviderConfigManager()
82
+ project_manager = ProjectManager()
83
+
84
+ server = TxCodeServer(
85
+ client,
86
+ host="0.0.0.0",
87
+ port=41000,
88
+ provider_config=provider_config,
89
+ project_manager=project_manager,
90
+ )
91
+ loop = _get_event_loop()
92
+ loop.run_until_complete(server.start())
93
+ print("[txcode-sdk] WebSocket server listening on ws://0.0.0.0:%d/ws/code" % server.port)
94
+ print("[txcode-sdk] work_dir:", client.work_dir)
95
+ try:
96
+ loop.run_forever()
97
+ except KeyboardInterrupt:
98
+ pass
99
+ finally:
100
+ loop.run_until_complete(server.stop())
101
+ return 0
102
+
103
+
104
+ if __name__ == "__main__":
105
+ sys.exit(main())
txcode_sdk/__init__.py CHANGED
@@ -20,6 +20,14 @@ from .types import (
20
20
  ToolResultInfo,
21
21
  )
22
22
  from .agent.summarizer import SummarizerAgent, CompactCheck as SummarizerCompactCheck, CompactResult as SummarizerCompactResult
23
+ from .agent.design import DesignAgent
24
+ from .agent.discuss import DiscussionAgent
25
+ from .agent.dream import DreamAgent
26
+ from .agent.name import NameAgent
27
+ from .agent.plan import PlanAgent
28
+ from .agent.shell import ShellAgent
29
+ from .agent.skill import SkillAgent
30
+ from .agent.test import TestAgent
23
31
 
24
32
  __all__ = [
25
33
  "TxCodeClient",
@@ -44,6 +52,30 @@ __all__ = [
44
52
  "SummarizerAgent",
45
53
  "SummarizerCompactCheck",
46
54
  "SummarizerCompactResult",
55
+ "DesignAgent",
56
+ "DiscussionAgent",
57
+ "DreamAgent",
58
+ "NameAgent",
59
+ "PlanAgent",
60
+ "ShellAgent",
61
+ "SkillAgent",
62
+ "TestAgent",
47
63
  ]
48
64
 
49
- __version__ = "0.1.0"
65
+ try:
66
+ from .server import TxCodeServer
67
+ __all__.append("TxCodeServer")
68
+ except Exception:
69
+ TxCodeServer = None
70
+
71
+ try:
72
+ from .server.provider_config import ProviderConfigManager
73
+ from .server.project_manager import ProjectManager
74
+ from .server.json_store import JsonStore
75
+ __all__ += ["ProviderConfigManager", "ProjectManager", "JsonStore"]
76
+ except Exception:
77
+ ProviderConfigManager = None
78
+ ProjectManager = None
79
+ JsonStore = None
80
+
81
+ __version__ = "0.4.0"
@@ -0,0 +1,5 @@
1
+ """Python 3.6 兼容层:dataclasses / importlib.resources 替代实现(零第三方依赖)。"""
2
+
3
+ from . import dataclasses, resources # noqa: F401
4
+
5
+ __all__ = ["dataclasses", "resources"]
@@ -0,0 +1,121 @@
1
+ """Python 3.6 兼容的 dataclasses 迷你实现。
2
+
3
+ 仅实现本项目使用到的特性:
4
+ - ``@dataclass`` 装饰器(含 ``@dataclass()`` 括号形式)
5
+ - 字段默认值(``name: int = 0``)
6
+ - ``field(default=..., default_factory=...)``(hooks/types.py 的 metadata 用到)
7
+ - 自动生成 ``__init__`` / ``__repr__`` / ``__eq__``
8
+
9
+ 不实现 frozen / slots / order / field 校验等高级特性。
10
+ 自 Python 3.7 起标准库 dataclasses 存在,本模块仅在 3.6 环境被使用;
11
+ 为保持行为一致,3.7+ 环境下可直接改用标准库。
12
+ """
13
+
14
+
15
+ class _MISSING_TYPE(object):
16
+ def __repr__(self):
17
+ return "MISSING"
18
+
19
+
20
+ MISSING = _MISSING_TYPE()
21
+
22
+
23
+ class _Field(object):
24
+ __slots__ = ("default", "default_factory")
25
+
26
+ def __init__(self, default=MISSING, default_factory=MISSING):
27
+ self.default = default
28
+ self.default_factory = default_factory
29
+
30
+
31
+ def field(*, default=MISSING, default_factory=MISSING):
32
+ """为 dataclass 字段提供默认值 / 默认工厂的声明。"""
33
+ if default is not MISSING and default_factory is not MISSING:
34
+ raise TypeError("cannot specify both default and default_factory")
35
+ return _Field(default=default, default_factory=default_factory)
36
+
37
+
38
+ def dataclass(cls=None, *, init=True, repr=True, eq=True):
39
+ """类装饰器:根据类注解自动生成 __init__ / __repr__ / __eq__。"""
40
+
41
+ def wrap(target):
42
+ return _process_class(target, init=init, repr=repr, eq=eq)
43
+
44
+ if cls is None:
45
+ return wrap
46
+ return wrap(cls)
47
+
48
+
49
+ def _collect_fields(cls):
50
+ """按 __annotations__ 顺序收集 (name, default, default_factory)。"""
51
+ annotations = getattr(cls, "__annotations__", None) or {}
52
+ fields = []
53
+ for name in annotations:
54
+ raw = getattr(cls, name, MISSING)
55
+ if isinstance(raw, _Field):
56
+ default = raw.default
57
+ default_factory = raw.default_factory
58
+ elif raw is not MISSING:
59
+ default = raw
60
+ default_factory = MISSING
61
+ else:
62
+ default = MISSING
63
+ default_factory = MISSING
64
+ fields.append((name, default, default_factory))
65
+ return fields
66
+
67
+
68
+ def _make_init(fields):
69
+ args = []
70
+ for name, default, default_factory in fields:
71
+ if default is not MISSING:
72
+ args.append("%s=%r" % (name, default))
73
+ else:
74
+ args.append("%s=MISSING" % name)
75
+ lines = ["def __init__(self, %s):" % ", ".join(args)]
76
+ for name, default, default_factory in fields:
77
+ if default_factory is not MISSING:
78
+ lines.append(" if %s is MISSING:" % name)
79
+ lines.append(" %s = _factory_%s()" % (name, name))
80
+ lines.append(" self.%s = %s" % (name, name))
81
+ ns = {"MISSING": MISSING}
82
+ for name, default, default_factory in fields:
83
+ if default_factory is not MISSING:
84
+ ns["_factory_%s" % name] = default_factory
85
+ exec("\n".join(lines), ns)
86
+ return ns["__init__"]
87
+
88
+
89
+ def _make_repr(cls, fields):
90
+ names = [name for name, _, _ in fields]
91
+
92
+ def __repr__(self):
93
+ parts = ", ".join("%s=%r" % (name, getattr(self, name)) for name in names)
94
+ return "%s(%s)" % (cls.__name__, parts)
95
+
96
+ return __repr__
97
+
98
+
99
+ def _make_eq(fields):
100
+ names = [name for name, _, _ in fields]
101
+
102
+ def __eq__(self, other):
103
+ if other.__class__ is not self.__class__:
104
+ return NotImplemented
105
+ for name in names:
106
+ if getattr(self, name) != getattr(other, name):
107
+ return False
108
+ return True
109
+
110
+ return __eq__
111
+
112
+
113
+ def _process_class(cls, init, repr, eq):
114
+ fields = _collect_fields(cls)
115
+ if init:
116
+ cls.__init__ = _make_init(fields)
117
+ if repr:
118
+ cls.__repr__ = _make_repr(cls, fields)
119
+ if eq:
120
+ cls.__eq__ = _make_eq(fields)
121
+ return cls
@@ -0,0 +1,19 @@
1
+ """importlib.resources 的 Python 3.6 兼容封装(基于 pkgutil.get_data)。
2
+
3
+ ``pkgutil.get_data`` 自 Python 3.x 一直可用,且支持 zip 导入(wheel / zip 安装场景),
4
+ 替代 Python 3.9+ 的 ``importlib.resources.files(...).joinpath(...).read_text()``。
5
+ """
6
+
7
+ import pkgutil
8
+
9
+
10
+ def get_resource(package, filename):
11
+ """读取包内文本资源并返回字符串(UTF-8 解码)。"""
12
+ data = pkgutil.get_data(package, filename)
13
+ if data is None:
14
+ raise FileNotFoundError(
15
+ "No resource %r found in package %r" % (filename, package)
16
+ )
17
+ if isinstance(data, bytes):
18
+ return data.decode("utf-8")
19
+ return data