stigmergy 1.0.57

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 (94) hide show
  1. package/LICENSE +19 -0
  2. package/README.de.md +301 -0
  3. package/README.en.md +301 -0
  4. package/README.es.md +301 -0
  5. package/README.fr.md +301 -0
  6. package/README.ja.md +301 -0
  7. package/README.ko.md +301 -0
  8. package/README.md +301 -0
  9. package/README.ru.md +301 -0
  10. package/README.zh.md +301 -0
  11. package/package.json +82 -0
  12. package/src/adapters/claude/__init__.py +13 -0
  13. package/src/adapters/claude/claude_skills_integration.py +609 -0
  14. package/src/adapters/claude/hook_adapter.py +663 -0
  15. package/src/adapters/claude/install_claude_integration.py +265 -0
  16. package/src/adapters/claude/skills_hook_adapter.py +841 -0
  17. package/src/adapters/claude/standalone_claude_adapter.py +384 -0
  18. package/src/adapters/cline/__init__.py +20 -0
  19. package/src/adapters/cline/config.py +108 -0
  20. package/src/adapters/cline/install_cline_integration.py +617 -0
  21. package/src/adapters/cline/mcp_server.py +713 -0
  22. package/src/adapters/cline/standalone_cline_adapter.py +459 -0
  23. package/src/adapters/codebuddy/__init__.py +13 -0
  24. package/src/adapters/codebuddy/buddy_adapter.py +1125 -0
  25. package/src/adapters/codebuddy/install_codebuddy_integration.py +279 -0
  26. package/src/adapters/codebuddy/skills_hook_adapter.py +672 -0
  27. package/src/adapters/codebuddy/skills_integration.py +395 -0
  28. package/src/adapters/codebuddy/standalone_codebuddy_adapter.py +403 -0
  29. package/src/adapters/codex/__init__.py +11 -0
  30. package/src/adapters/codex/base.py +46 -0
  31. package/src/adapters/codex/install_codex_integration.py +311 -0
  32. package/src/adapters/codex/mcp_server.py +493 -0
  33. package/src/adapters/codex/natural_language_parser.py +82 -0
  34. package/src/adapters/codex/slash_command_adapter.py +326 -0
  35. package/src/adapters/codex/standalone_codex_adapter.py +362 -0
  36. package/src/adapters/copilot/__init__.py +13 -0
  37. package/src/adapters/copilot/install_copilot_integration.py +564 -0
  38. package/src/adapters/copilot/mcp_adapter.py +772 -0
  39. package/src/adapters/copilot/mcp_server.py +168 -0
  40. package/src/adapters/copilot/standalone_copilot_adapter.py +114 -0
  41. package/src/adapters/gemini/__init__.py +13 -0
  42. package/src/adapters/gemini/extension_adapter.py +690 -0
  43. package/src/adapters/gemini/install_gemini_integration.py +257 -0
  44. package/src/adapters/gemini/standalone_gemini_adapter.py +366 -0
  45. package/src/adapters/iflow/__init__.py +7 -0
  46. package/src/adapters/iflow/hook_adapter.py +1038 -0
  47. package/src/adapters/iflow/hook_installer.py +536 -0
  48. package/src/adapters/iflow/install_iflow_integration.py +271 -0
  49. package/src/adapters/iflow/official_hook_adapter.py +1272 -0
  50. package/src/adapters/iflow/standalone_iflow_adapter.py +48 -0
  51. package/src/adapters/iflow/workflow_adapter.py +793 -0
  52. package/src/adapters/qoder/hook_installer.py +732 -0
  53. package/src/adapters/qoder/install_qoder_integration.py +265 -0
  54. package/src/adapters/qoder/notification_hook_adapter.py +863 -0
  55. package/src/adapters/qoder/standalone_qoder_adapter.py +48 -0
  56. package/src/adapters/qwen/__init__.py +17 -0
  57. package/src/adapters/qwencode/__init__.py +13 -0
  58. package/src/adapters/qwencode/inheritance_adapter.py +818 -0
  59. package/src/adapters/qwencode/install_qwencode_integration.py +276 -0
  60. package/src/adapters/qwencode/standalone_qwencode_adapter.py +399 -0
  61. package/src/atomic_collaboration_handler.py +461 -0
  62. package/src/cli_collaboration_agent.py +697 -0
  63. package/src/collaboration/hooks.py +315 -0
  64. package/src/core/__init__.py +21 -0
  65. package/src/core/ai_environment_scanner.py +331 -0
  66. package/src/core/base_adapter.py +220 -0
  67. package/src/core/cli_hook_integration.py +406 -0
  68. package/src/core/cross_cli_executor.py +713 -0
  69. package/src/core/cross_cli_mapping.py +1163 -0
  70. package/src/core/cross_platform_encoding.py +365 -0
  71. package/src/core/cross_platform_safe_cli.py +894 -0
  72. package/src/core/direct_cli_executor.py +805 -0
  73. package/src/core/direct_cli_hook_system.py +958 -0
  74. package/src/core/enhanced_init_processor.py +427 -0
  75. package/src/core/graceful_cli_executor.py +912 -0
  76. package/src/core/md_enhancer.py +342 -0
  77. package/src/core/md_generator.py +619 -0
  78. package/src/core/models.py +218 -0
  79. package/src/core/parser.py +108 -0
  80. package/src/core/real_cli_hook_system.py +852 -0
  81. package/src/core/real_cross_cli_system.py +925 -0
  82. package/src/core/verified_cross_cli_system.py +961 -0
  83. package/src/deploy.js +737 -0
  84. package/src/enhanced_deploy.js +303 -0
  85. package/src/enhanced_universal_cli_setup.py +930 -0
  86. package/src/kimi_wrapper.py +104 -0
  87. package/src/main.js +1309 -0
  88. package/src/shell_integration.py +398 -0
  89. package/src/simple-main.js +315 -0
  90. package/src/smart_router_creator.py +323 -0
  91. package/src/universal_cli_setup.py +1289 -0
  92. package/src/utils/__init__.py +12 -0
  93. package/src/utils/cli_detector.py +445 -0
  94. package/src/utils/file_utils.py +246 -0
@@ -0,0 +1,427 @@
1
+ """
2
+ Enhanced Init Processor - 增强的初始化处理器
3
+ 处理新老两种项目的 /init 指令,集成AI环境感知
4
+ """
5
+ import os
6
+ import asyncio
7
+ from pathlib import Path
8
+ from datetime import datetime
9
+ from typing import Dict, List, Optional, Any
10
+
11
+ from .models import (
12
+ ProjectStatus, InitResult, EnhancementResult, GeneratedDocument,
13
+ AIEnvironmentInfo, CLI_CONFIG_MAPPING
14
+ )
15
+ from .ai_environment_scanner import AIEnvironmentScanner
16
+ from .md_enhancer import MDDocumentEnhancer
17
+ from .md_generator import MDDocumentGenerator
18
+
19
+ import logging
20
+ logger = logging.getLogger(__name__)
21
+
22
+
23
+ class EnhancedInitProcessor:
24
+ """增强的初始化处理器 - 处理新老两种项目情况"""
25
+
26
+ def __init__(self, current_cli: str):
27
+ self.current_cli = current_cli
28
+ self.ai_environment_scanner = AIEnvironmentScanner(current_cli)
29
+ self.md_enhancer = MDDocumentEnhancer()
30
+ self.md_generator = MDDocumentGenerator()
31
+
32
+ async def process_init_command(self, project_path: str) -> InitResult:
33
+ """处理 /init 指令,自动检测新老项目"""
34
+ start_time = datetime.now()
35
+
36
+ try:
37
+ logger.info(f"开始处理 /init 指令,当前CLI: {self.current_cli},项目路径: {project_path}")
38
+
39
+ # 1. 检测项目类型(新老项目)
40
+ logger.info("检测项目状态...")
41
+ project_status = await self._detect_project_status(project_path)
42
+
43
+ # 2. 扫描AI环境
44
+ logger.info("扫描AI环境...")
45
+ ai_environment = await self.ai_environment_scanner.scan_ai_environment(project_path)
46
+
47
+ # 3. 根据项目类型处理
48
+ if project_status.is_existing_project:
49
+ # 老项目:增强现有MD文档
50
+ logger.info("检测到现有项目,开始增强现有MD文档...")
51
+ result = await self._enhance_existing_project(project_path, ai_environment)
52
+ result.project_type = "existing_project"
53
+ else:
54
+ # 新项目:生成完整MD文档
55
+ logger.info("检测到新项目,开始生成完整MD文档...")
56
+ result = await self._initialize_new_project(project_path, ai_environment)
57
+ result.project_type = "new_project"
58
+
59
+ # 4. 计算处理时间
60
+ processing_time = (datetime.now() - start_time).total_seconds()
61
+ result.processing_time = processing_time
62
+
63
+ logger.info(f"/init 指令处理完成,耗时: {processing_time:.2f}秒")
64
+ return result
65
+
66
+ except Exception as e:
67
+ logger.error(f"处理 /init 指令失败: {e}")
68
+ # 返回错误结果,但不抛出异常
69
+ return InitResult(
70
+ project_type="error",
71
+ ai_environment=None,
72
+ message=f"❌ 处理失败: {str(e)}",
73
+ processing_time=(datetime.now() - start_time).total_seconds()
74
+ )
75
+
76
+ async def _detect_project_status(self, project_path: str) -> ProjectStatus:
77
+ """检测项目状态"""
78
+ existing_md_files = []
79
+ project_path_obj = Path(project_path)
80
+
81
+ # 检查是否存在CLI工具的MD文档
82
+ cli_tools = list(CLI_CONFIG_MAPPING.keys())
83
+
84
+ for cli in cli_tools:
85
+ md_file = project_path_obj / f"{cli}.md"
86
+ if md_file.exists() and md_file.is_file():
87
+ existing_md_files.append(cli)
88
+ logger.debug(f"发现现有文档: {cli}.md")
89
+
90
+ is_existing = len(existing_md_files) > 0
91
+
92
+ logger.info(f"项目状态检测结果: {'现有项目' if is_existing else '新项目'}")
93
+ logger.info(f"现有MD文档: {existing_md_files}")
94
+
95
+ return ProjectStatus(
96
+ is_existing_project=is_existing,
97
+ existing_md_files=existing_md_files,
98
+ total_expected=len(cli_tools),
99
+ project_path=project_path
100
+ )
101
+
102
+ async def _enhance_existing_project(self,
103
+ project_path: str,
104
+ ai_environment: AIEnvironmentInfo) -> InitResult:
105
+ """老项目:增强现有MD文档"""
106
+ enhancement_results = {}
107
+ enhanced_count = 0
108
+
109
+ try:
110
+ # 增强所有现有的MD文档(不仅仅是当前CLI的文档)
111
+ for cli_name in ai_environment.available_clis:
112
+ md_path = Path(project_path) / f"{cli_name}.md"
113
+
114
+ if md_path.exists():
115
+ logger.info(f"增强现有文档: {cli_name}.md")
116
+
117
+ try:
118
+ # 读取现有文档
119
+ existing_content = await self._read_md_file(md_path)
120
+
121
+ # 生成协作感知内容
122
+ collaboration_content = await self.md_enhancer.generate_collaboration_section(
123
+ cli_name, ai_environment, current_cli=self.current_cli
124
+ )
125
+
126
+ # 增强现有文档
127
+ enhanced_content = await self.md_enhancer.enhance_existing_md(
128
+ existing_content, collaboration_content, cli_name
129
+ )
130
+
131
+ # 写回文件
132
+ await self._write_md_file(md_path, enhanced_content)
133
+
134
+ # 创建备份(可选)
135
+ await self._create_backup(md_path, existing_content)
136
+
137
+ enhancement_results[cli_name] = EnhancementResult(
138
+ enhanced=True,
139
+ added_collaboration_section=True,
140
+ original_sections=len(self._count_sections(existing_content)),
141
+ new_sections=len(self._count_sections(enhanced_content)),
142
+ enhancement_time=datetime.now()
143
+ )
144
+
145
+ enhanced_count += 1
146
+ logger.info(f"成功增强 {cli_name}.md")
147
+
148
+ except Exception as e:
149
+ logger.error(f"增强文档 {cli_name}.md 失败: {e}")
150
+ enhancement_results[cli_name] = EnhancementResult(
151
+ enhanced=False,
152
+ added_collaboration_section=False,
153
+ original_sections=0,
154
+ new_sections=0,
155
+ enhancement_time=datetime.now()
156
+ )
157
+
158
+ # 生成项目配置文件
159
+ await self._ensure_project_config(project_path, ai_environment)
160
+
161
+ message = f"✅ 已增强 {enhanced_count} 个CLI文档的协作感知"
162
+ if enhanced_count < len(ai_environment.available_clis):
163
+ missing_count = len(ai_environment.available_clis) - enhanced_count
164
+ message += f",{missing_count} 个文档增强失败"
165
+
166
+ return InitResult(
167
+ project_type="existing_project",
168
+ enhanced_documents=enhancement_results,
169
+ ai_environment=ai_environment,
170
+ message=message
171
+ )
172
+
173
+ except Exception as e:
174
+ logger.error(f"增强现有项目失败: {e}")
175
+ raise
176
+
177
+ async def _initialize_new_project(self,
178
+ project_path: str,
179
+ ai_environment: AIEnvironmentInfo) -> InitResult:
180
+ """新项目:生成完整MD文档"""
181
+ generated_documents = {}
182
+ generated_count = 0
183
+
184
+ try:
185
+ # 为每个可用的CLI工具生成完整的MD文档
186
+ for cli_name, cli_info in ai_environment.available_clis.items():
187
+ logger.info(f"生成文档: {cli_name}.md")
188
+
189
+ try:
190
+ # 生成完整MD文档
191
+ md_content = await self.md_generator.generate_complete_md(
192
+ cli_name, cli_info, ai_environment, current_cli=self.current_cli
193
+ )
194
+
195
+ md_path = Path(project_path) / f"{cli_name}.md"
196
+ await self._write_md_file(md_path, md_content)
197
+
198
+ generated_documents[cli_name] = GeneratedDocument(
199
+ file_path=str(md_path),
200
+ sections_count=self._count_sections(md_content),
201
+ includes_collaboration=True,
202
+ generation_time=datetime.now()
203
+ )
204
+
205
+ generated_count += 1
206
+ logger.info(f"成功生成 {cli_name}.md")
207
+
208
+ except Exception as e:
209
+ logger.error(f"生成文档 {cli_name}.md 失败: {e}")
210
+
211
+ # 创建项目配置目录和文件
212
+ await self._create_project_config(project_path, ai_environment)
213
+
214
+ # 创建 .ai-cli-project 目录
215
+ await self._create_ai_cli_project_dir(project_path, ai_environment)
216
+
217
+ message = f"✅ 已生成 {generated_count} 个完整CLI文档,包含协作感知"
218
+ if generated_count < len(ai_environment.available_clis):
219
+ missing_count = len(ai_environment.available_clis) - generated_count
220
+ message += f",{missing_count} 个文档生成失败"
221
+
222
+ return InitResult(
223
+ project_type="new_project",
224
+ generated_documents=generated_documents,
225
+ ai_environment=ai_environment,
226
+ message=message
227
+ )
228
+
229
+ except Exception as e:
230
+ logger.error(f"初始化新项目失败: {e}")
231
+ raise
232
+
233
+ async def _read_md_file(self, file_path: Path) -> str:
234
+ """读取MD文件"""
235
+ try:
236
+ with open(file_path, 'r', encoding='utf-8') as f:
237
+ return f.read()
238
+ except Exception as e:
239
+ logger.error(f"读取文件失败 {file_path}: {e}")
240
+ raise
241
+
242
+ async def _write_md_file(self, file_path: Path, content: str) -> None:
243
+ """写入MD文件"""
244
+ try:
245
+ # 确保目录存在
246
+ file_path.parent.mkdir(parents=True, exist_ok=True)
247
+
248
+ with open(file_path, 'w', encoding='utf-8') as f:
249
+ f.write(content)
250
+
251
+ except Exception as e:
252
+ logger.error(f"写入文件失败 {file_path}: {e}")
253
+ raise
254
+
255
+ async def _create_backup(self, file_path: Path, original_content: str) -> None:
256
+ """创建文件备份"""
257
+ try:
258
+ backup_dir = file_path.parent / ".ai-cli-backups"
259
+ backup_dir.mkdir(exist_ok=True)
260
+
261
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
262
+ backup_filename = f"{file_path.stem}_{timestamp}{file_path.suffix}"
263
+ backup_path = backup_dir / backup_filename
264
+
265
+ with open(backup_path, 'w', encoding='utf-8') as f:
266
+ f.write(original_content)
267
+
268
+ logger.debug(f"创建备份: {backup_path}")
269
+
270
+ except Exception as e:
271
+ logger.warning(f"创建备份失败: {e}")
272
+
273
+ def _count_sections(self, content: str) -> int:
274
+ """统计文档中的章节数量"""
275
+ sections = []
276
+ lines = content.split('\n')
277
+
278
+ for line in lines:
279
+ if line.strip().startswith('#'):
280
+ sections.append(line.strip())
281
+
282
+ return len(sections)
283
+
284
+ async def _ensure_project_config(self, project_path: str, ai_environment: AIEnvironmentInfo) -> None:
285
+ """确保项目配置文件存在"""
286
+ try:
287
+ config_dir = Path(project_path) / ".ai-cli-project"
288
+ config_dir.mkdir(exist_ok=True)
289
+
290
+ # 创建基础项目配置
291
+ config_file = config_dir / "project-config.json"
292
+ if not config_file.exists():
293
+ import json
294
+ project_config = {
295
+ "project_type": "enhanced_existing",
296
+ "last_update": datetime.now().isoformat(),
297
+ "available_tools": list(ai_environment.available_clis.keys()),
298
+ "current_cli": self.current_cli,
299
+ "collaboration_enabled": True,
300
+ "auto_scan": True
301
+ }
302
+
303
+ with open(config_file, 'w', encoding='utf-8') as f:
304
+ json.dump(project_config, f, indent=2, ensure_ascii=False)
305
+
306
+ logger.info(f"创建项目配置文件: {config_file}")
307
+
308
+ except Exception as e:
309
+ logger.warning(f"创建项目配置失败: {e}")
310
+
311
+ async def _create_project_config(self, project_path: str, ai_environment: AIEnvironmentInfo) -> None:
312
+ """为新项目创建配置文件"""
313
+ try:
314
+ config_dir = Path(project_path) / ".ai-cli-project"
315
+ config_dir.mkdir(exist_ok=True)
316
+
317
+ # 创建项目配置文件
318
+ import json
319
+ project_config = {
320
+ "project_type": "new_initialized",
321
+ "created_at": datetime.now().isoformat(),
322
+ "last_update": datetime.now().isoformat(),
323
+ "initiated_by": self.current_cli,
324
+ "available_tools": {
325
+ cli_name: {
326
+ "name": cli_info.display_name,
327
+ "version": cli_info.version,
328
+ "status": cli_info.status.value,
329
+ "enabled": True
330
+ }
331
+ for cli_name, cli_info in ai_environment.available_clis.items()
332
+ },
333
+ "collaboration": {
334
+ "enabled": True,
335
+ "auto_detect": True,
336
+ "protocols": ai_environment.collaboration_guide.protocols
337
+ },
338
+ "preferences": {
339
+ "primary_tool": self.current_cli,
340
+ "language": "mixed", # 支持中英文混合
341
+ "auto_backup": True
342
+ }
343
+ }
344
+
345
+ config_file = config_dir / "project-config.json"
346
+ with open(config_file, 'w', encoding='utf-8') as f:
347
+ json.dump(project_config, f, indent=2, ensure_ascii=False)
348
+
349
+ logger.info(f"创建新项目配置文件: {config_file}")
350
+
351
+ except Exception as e:
352
+ logger.warning(f"创建新项目配置失败: {e}")
353
+
354
+ async def _create_ai_cli_project_dir(self, project_path: str, ai_environment: AIEnvironmentInfo) -> None:
355
+ """创建 .ai-cli-project 目录结构"""
356
+ try:
357
+ ai_cli_dir = Path(project_path) / ".ai-cli-project"
358
+ ai_cli_dir.mkdir(exist_ok=True)
359
+
360
+ # 创建子目录
361
+ subdirs = ["logs", "backups", "cache", "templates"]
362
+ for subdir in subdirs:
363
+ (ai_cli_dir / subdir).mkdir(exist_ok=True)
364
+
365
+ # 创建 .gitignore
366
+ gitignore_path = ai_cli_dir / ".gitignore"
367
+ if not gitignore_path.exists():
368
+ gitignore_content = """# AI CLI Router generated files
369
+ logs/
370
+ backups/
371
+ cache/
372
+ *.log
373
+ *.tmp
374
+ .DS_Store
375
+ """
376
+ with open(gitignore_path, 'w', encoding='utf-8') as f:
377
+ f.write(gitignore_content)
378
+
379
+ # 创建 README.md
380
+ readme_path = ai_cli_dir / "README.md"
381
+ if not readme_path.exists():
382
+ readme_content = f"""# AI CLI Router 项目配置
383
+
384
+ 此目录包含 AI CLI Router 的项目特定配置文件。
385
+
386
+ ## 📁 目录结构
387
+
388
+ - `project-config.json` - 项目AI配置
389
+ - `logs/` - AI CLI操作日志
390
+ - `backups/` - 配置文件备份
391
+ - `cache/` - 临时缓存文件
392
+ - `templates/` - 自定义模板
393
+
394
+ ## 🤖 可用AI工具
395
+
396
+ {chr(10).join(f"- **{info.display_name}** v{info.version}" for info in ai_environment.available_clis.values())}
397
+
398
+ ## 📅 初始化信息
399
+
400
+ - 初始化时间: {ai_environment.generated_at.strftime('%Y-%m-%d %H:%M:%S')}
401
+ - 初始化工具: {self.current_cli}
402
+ - 扫描耗时: {ai_environment.scan_duration:.2f}秒
403
+
404
+ ## 🔧 配置管理
405
+
406
+ 使用以下命令管理项目配置:
407
+ ```bash
408
+ # 更新AI环境扫描
409
+ ai-cli-router scan
410
+
411
+ # 验证项目配置
412
+ ai-cli-router check-project
413
+
414
+ # 重置项目配置
415
+ ai-cli-router reset --project
416
+ ```
417
+
418
+ ---
419
+ *此目录由 AI CLI Router 自动生成和管理*
420
+ """
421
+ with open(readme_path, 'w', encoding='utf-8') as f:
422
+ f.write(readme_content)
423
+
424
+ logger.info(f"创建 .ai-cli-project 目录结构: {ai_cli_dir}")
425
+
426
+ except Exception as e:
427
+ logger.warning(f"创建 .ai-cli-project 目录失败: {e}")