adaptive-memory-multi-model-router 1.2.2 → 1.3.1

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 (195) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +146 -66
  3. package/dist/index.d.ts +1 -1
  4. package/dist/index.js +1 -1
  5. package/dist/integrations/airtable.js +20 -0
  6. package/dist/integrations/discord.js +18 -0
  7. package/dist/integrations/github.js +23 -0
  8. package/dist/integrations/gmail.js +19 -0
  9. package/dist/integrations/google-calendar.js +18 -0
  10. package/dist/integrations/index.js +61 -0
  11. package/dist/integrations/jira.js +21 -0
  12. package/dist/integrations/linear.js +19 -0
  13. package/dist/integrations/notion.js +19 -0
  14. package/dist/integrations/slack.js +18 -0
  15. package/dist/integrations/telegram.js +19 -0
  16. package/dist/providers/registry.js +7 -3
  17. package/docs/ARCHITECTURAL-IMPROVEMENTS-2025.md +1391 -0
  18. package/docs/ARCHITECTURAL-IMPROVEMENTS-REVISED-2025.md +1051 -0
  19. package/docs/CONFIGURATION.md +476 -0
  20. package/docs/COUNCIL_DECISION.json +308 -0
  21. package/docs/COUNCIL_SUMMARY.md +265 -0
  22. package/docs/COUNCIL_V2.2_DECISION.md +416 -0
  23. package/docs/IMPROVEMENT_ROADMAP.md +515 -0
  24. package/docs/LLM_COUNCIL_DECISION.md +508 -0
  25. package/docs/QUICK_START_VISIBILITY.md +782 -0
  26. package/docs/REDDIT_GAP_ANALYSIS.md +299 -0
  27. package/docs/RESEARCH_BACKED_IMPROVEMENTS.md +1180 -0
  28. package/docs/TMLPD_QNA.md +751 -0
  29. package/docs/TMLPD_V2.1_COMPLETE.md +763 -0
  30. package/docs/TMLPD_V2.2_RESEARCH_ROADMAP.md +754 -0
  31. package/docs/V2.2_IMPLEMENTATION_COMPLETE.md +446 -0
  32. package/docs/V2_IMPLEMENTATION_GUIDE.md +388 -0
  33. package/docs/VISIBILITY_ADOPTION_PLAN.md +1005 -0
  34. package/docs/launch-content/LAUNCH_EXECUTION_CHECKLIST.md +421 -0
  35. package/docs/launch-content/README.md +457 -0
  36. package/docs/launch-content/assets/cost_comparison_100_tasks.png +0 -0
  37. package/docs/launch-content/assets/cumulative_savings.png +0 -0
  38. package/docs/launch-content/assets/parallel_speedup.png +0 -0
  39. package/docs/launch-content/assets/provider_pricing_comparison.png +0 -0
  40. package/docs/launch-content/assets/task_breakdown_comparison.png +0 -0
  41. package/docs/launch-content/generate_charts.py +313 -0
  42. package/docs/launch-content/hn_show_post.md +139 -0
  43. package/docs/launch-content/partner_outreach_templates.md +745 -0
  44. package/docs/launch-content/reddit_posts.md +467 -0
  45. package/docs/launch-content/twitter_thread.txt +460 -0
  46. package/examples/QUICKSTART.md +1 -1
  47. package/openclaw-alexa-bridge/ALL_REMAINING_FIXES_PLAN.md +313 -0
  48. package/openclaw-alexa-bridge/REMAINING_FIXES_SUMMARY.md +277 -0
  49. package/openclaw-alexa-bridge/src/alexa_handler_no_tmlpd.js +1234 -0
  50. package/openclaw-alexa-bridge/test_fixes.js +77 -0
  51. package/package.json +120 -29
  52. package/package.json.tmp +0 -0
  53. package/qna/TMLPD_QNA.md +3 -3
  54. package/skill/SKILL.md +2 -2
  55. package/src/__tests__/integration/tmpld_integration.test.py +540 -0
  56. package/src/agents/skill_enhanced_agent.py +318 -0
  57. package/src/memory/__init__.py +15 -0
  58. package/src/memory/agentic_memory.py +353 -0
  59. package/src/memory/semantic_memory.py +444 -0
  60. package/src/memory/simple_memory.py +466 -0
  61. package/src/memory/working_memory.py +447 -0
  62. package/src/orchestration/__init__.py +52 -0
  63. package/src/orchestration/execution_engine.py +353 -0
  64. package/src/orchestration/halo_orchestrator.py +367 -0
  65. package/src/orchestration/mcts_workflow.py +498 -0
  66. package/src/orchestration/role_assigner.py +473 -0
  67. package/src/orchestration/task_planner.py +522 -0
  68. package/src/providers/__init__.py +67 -0
  69. package/src/providers/anthropic.py +304 -0
  70. package/src/providers/base.py +241 -0
  71. package/src/providers/cerebras.py +373 -0
  72. package/src/providers/registry.py +476 -0
  73. package/src/routing/__init__.py +30 -0
  74. package/src/routing/universal_router.py +621 -0
  75. package/src/skills/TMLPD-QUICKREF.md +210 -0
  76. package/src/skills/TMLPD-SETUP-SUMMARY.md +157 -0
  77. package/src/skills/TMLPD.md +540 -0
  78. package/src/skills/__tests__/skill_manager.test.ts +328 -0
  79. package/src/skills/skill_manager.py +385 -0
  80. package/src/skills/test-tmlpd.sh +108 -0
  81. package/src/skills/tmlpd-category.yaml +67 -0
  82. package/src/skills/tmlpd-monitoring.yaml +188 -0
  83. package/src/skills/tmlpd-phase.yaml +132 -0
  84. package/src/state/__init__.py +17 -0
  85. package/src/state/simple_checkpoint.py +508 -0
  86. package/src/tmlpd_agent.py +464 -0
  87. package/src/tmpld_v2.py +427 -0
  88. package/src/workflows/__init__.py +18 -0
  89. package/src/workflows/advanced_difficulty_classifier.py +377 -0
  90. package/src/workflows/chaining_executor.py +417 -0
  91. package/src/workflows/difficulty_integration.py +209 -0
  92. package/src/workflows/orchestrator.py +469 -0
  93. package/src/workflows/orchestrator_executor.py +456 -0
  94. package/src/workflows/parallelization_executor.py +382 -0
  95. package/src/workflows/router.py +311 -0
  96. package/test_integration_simple.py +86 -0
  97. package/test_mcts_workflow.py +150 -0
  98. package/test_templd_integration.py +262 -0
  99. package/test_universal_router.py +275 -0
  100. package/tmlpd-pi-extension/README.md +36 -0
  101. package/tmlpd-pi-extension/dist/cache/prefixCache.d.ts +114 -0
  102. package/tmlpd-pi-extension/dist/cache/prefixCache.d.ts.map +1 -0
  103. package/tmlpd-pi-extension/dist/cache/prefixCache.js +285 -0
  104. package/tmlpd-pi-extension/dist/cache/prefixCache.js.map +1 -0
  105. package/tmlpd-pi-extension/dist/cache/responseCache.d.ts +58 -0
  106. package/tmlpd-pi-extension/dist/cache/responseCache.d.ts.map +1 -0
  107. package/tmlpd-pi-extension/dist/cache/responseCache.js +153 -0
  108. package/tmlpd-pi-extension/dist/cache/responseCache.js.map +1 -0
  109. package/tmlpd-pi-extension/dist/cli.js +59 -0
  110. package/tmlpd-pi-extension/dist/cost/costTracker.d.ts +95 -0
  111. package/tmlpd-pi-extension/dist/cost/costTracker.d.ts.map +1 -0
  112. package/tmlpd-pi-extension/dist/cost/costTracker.js +240 -0
  113. package/tmlpd-pi-extension/dist/cost/costTracker.js.map +1 -0
  114. package/tmlpd-pi-extension/dist/index.d.ts +723 -0
  115. package/tmlpd-pi-extension/dist/index.d.ts.map +1 -0
  116. package/tmlpd-pi-extension/dist/index.js +239 -0
  117. package/tmlpd-pi-extension/dist/index.js.map +1 -0
  118. package/tmlpd-pi-extension/dist/memory/episodicMemory.d.ts +82 -0
  119. package/tmlpd-pi-extension/dist/memory/episodicMemory.d.ts.map +1 -0
  120. package/tmlpd-pi-extension/dist/memory/episodicMemory.js +145 -0
  121. package/tmlpd-pi-extension/dist/memory/episodicMemory.js.map +1 -0
  122. package/tmlpd-pi-extension/dist/orchestration/haloOrchestrator.d.ts +102 -0
  123. package/tmlpd-pi-extension/dist/orchestration/haloOrchestrator.d.ts.map +1 -0
  124. package/tmlpd-pi-extension/dist/orchestration/haloOrchestrator.js +207 -0
  125. package/tmlpd-pi-extension/dist/orchestration/haloOrchestrator.js.map +1 -0
  126. package/tmlpd-pi-extension/dist/orchestration/mctsWorkflow.d.ts +85 -0
  127. package/tmlpd-pi-extension/dist/orchestration/mctsWorkflow.d.ts.map +1 -0
  128. package/tmlpd-pi-extension/dist/orchestration/mctsWorkflow.js +210 -0
  129. package/tmlpd-pi-extension/dist/orchestration/mctsWorkflow.js.map +1 -0
  130. package/tmlpd-pi-extension/dist/providers/localProvider.d.ts +102 -0
  131. package/tmlpd-pi-extension/dist/providers/localProvider.d.ts.map +1 -0
  132. package/tmlpd-pi-extension/dist/providers/localProvider.js +338 -0
  133. package/tmlpd-pi-extension/dist/providers/localProvider.js.map +1 -0
  134. package/tmlpd-pi-extension/dist/providers/registry.d.ts +55 -0
  135. package/tmlpd-pi-extension/dist/providers/registry.d.ts.map +1 -0
  136. package/tmlpd-pi-extension/dist/providers/registry.js +138 -0
  137. package/tmlpd-pi-extension/dist/providers/registry.js.map +1 -0
  138. package/tmlpd-pi-extension/dist/routing/advancedRouter.d.ts +68 -0
  139. package/tmlpd-pi-extension/dist/routing/advancedRouter.d.ts.map +1 -0
  140. package/tmlpd-pi-extension/dist/routing/advancedRouter.js +332 -0
  141. package/tmlpd-pi-extension/dist/routing/advancedRouter.js.map +1 -0
  142. package/tmlpd-pi-extension/dist/tools/tmlpdTools.d.ts +101 -0
  143. package/tmlpd-pi-extension/dist/tools/tmlpdTools.d.ts.map +1 -0
  144. package/tmlpd-pi-extension/dist/tools/tmlpdTools.js +368 -0
  145. package/tmlpd-pi-extension/dist/tools/tmlpdTools.js.map +1 -0
  146. package/tmlpd-pi-extension/dist/utils/batchProcessor.d.ts +96 -0
  147. package/tmlpd-pi-extension/dist/utils/batchProcessor.d.ts.map +1 -0
  148. package/tmlpd-pi-extension/dist/utils/batchProcessor.js +170 -0
  149. package/tmlpd-pi-extension/dist/utils/batchProcessor.js.map +1 -0
  150. package/tmlpd-pi-extension/dist/utils/compression.d.ts +61 -0
  151. package/tmlpd-pi-extension/dist/utils/compression.d.ts.map +1 -0
  152. package/tmlpd-pi-extension/dist/utils/compression.js +281 -0
  153. package/tmlpd-pi-extension/dist/utils/compression.js.map +1 -0
  154. package/tmlpd-pi-extension/dist/utils/reliability.d.ts +74 -0
  155. package/tmlpd-pi-extension/dist/utils/reliability.d.ts.map +1 -0
  156. package/tmlpd-pi-extension/dist/utils/reliability.js +177 -0
  157. package/tmlpd-pi-extension/dist/utils/reliability.js.map +1 -0
  158. package/tmlpd-pi-extension/dist/utils/speculativeDecoding.d.ts +117 -0
  159. package/tmlpd-pi-extension/dist/utils/speculativeDecoding.d.ts.map +1 -0
  160. package/tmlpd-pi-extension/dist/utils/speculativeDecoding.js +246 -0
  161. package/tmlpd-pi-extension/dist/utils/speculativeDecoding.js.map +1 -0
  162. package/tmlpd-pi-extension/dist/utils/tokenUtils.d.ts +50 -0
  163. package/tmlpd-pi-extension/dist/utils/tokenUtils.d.ts.map +1 -0
  164. package/tmlpd-pi-extension/dist/utils/tokenUtils.js +124 -0
  165. package/tmlpd-pi-extension/dist/utils/tokenUtils.js.map +1 -0
  166. package/tmlpd-pi-extension/examples/QUICKSTART.md +183 -0
  167. package/tmlpd-pi-extension/package-lock.json +75 -0
  168. package/tmlpd-pi-extension/package.json +172 -0
  169. package/tmlpd-pi-extension/python/examples.py +53 -0
  170. package/tmlpd-pi-extension/python/integrations.py +330 -0
  171. package/tmlpd-pi-extension/python/setup.py +28 -0
  172. package/tmlpd-pi-extension/python/tmlpd.py +369 -0
  173. package/tmlpd-pi-extension/qna/REDDIT_GAP_ANALYSIS.md +299 -0
  174. package/tmlpd-pi-extension/qna/TMLPD_QNA.md +751 -0
  175. package/tmlpd-pi-extension/skill/SKILL.md +238 -0
  176. package/{src → tmlpd-pi-extension/src}/index.ts +1 -1
  177. package/tmlpd-pi-extension/tsconfig.json +18 -0
  178. package/demo/research-demo.js +0 -266
  179. package/notebooks/quickstart.ipynb +0 -157
  180. package/rust/tmlpd.h +0 -268
  181. package/src/cache/prefixCache.ts +0 -365
  182. package/src/routing/advancedRouter.ts +0 -406
  183. package/src/utils/speculativeDecoding.ts +0 -344
  184. /package/{src → tmlpd-pi-extension/src}/cache/responseCache.ts +0 -0
  185. /package/{src → tmlpd-pi-extension/src}/cost/costTracker.ts +0 -0
  186. /package/{src → tmlpd-pi-extension/src}/memory/episodicMemory.ts +0 -0
  187. /package/{src → tmlpd-pi-extension/src}/orchestration/haloOrchestrator.ts +0 -0
  188. /package/{src → tmlpd-pi-extension/src}/orchestration/mctsWorkflow.ts +0 -0
  189. /package/{src → tmlpd-pi-extension/src}/providers/localProvider.ts +0 -0
  190. /package/{src → tmlpd-pi-extension/src}/providers/registry.ts +0 -0
  191. /package/{src → tmlpd-pi-extension/src}/tools/tmlpdTools.ts +0 -0
  192. /package/{src → tmlpd-pi-extension/src}/utils/batchProcessor.ts +0 -0
  193. /package/{src → tmlpd-pi-extension/src}/utils/compression.ts +0 -0
  194. /package/{src → tmlpd-pi-extension/src}/utils/reliability.ts +0 -0
  195. /package/{src → tmlpd-pi-extension/src}/utils/tokenUtils.ts +0 -0
@@ -0,0 +1,427 @@
1
+ """
2
+ TMLPD v2.2 - Backward-Compatible Integration Layer
3
+
4
+ This module provides a unified API that exposes both v2.1 and v2.2 features
5
+ in a backward-compatible way, ensuring existing v2.1 code continues to work.
6
+
7
+ Key Features:
8
+ - Backward-compatible with v2.1 API
9
+ - Exposes v2.2 features (HALO, Universal Router, MCTS)
10
+ - Smart defaults for automatic feature selection
11
+ - Progressive enhancement model
12
+ """
13
+
14
+ from typing import Dict, List, Any, Optional, Union
15
+ from dataclasses import dataclass
16
+ import logging
17
+
18
+ # Import v2.1 components (assuming they exist)
19
+ try:
20
+ from .difficulty_classifier import DifficultyClassifier, TaskDifficulty
21
+ from .enhanced_agent import TMLEnhancedAgent
22
+ V21_AVAILABLE = True
23
+ except ImportError:
24
+ V21_AVAILABLE = False
25
+ logging.warning("v2.1 components not found, running in v2.2-only mode")
26
+
27
+ # Import v2.2 components
28
+ from .orchestration import (
29
+ TaskPlanner, RoleAssigner, ExecutionEngine, HALOOrchestrator,
30
+ MCTSWorkflowSearch, TaskDecomposition, HALOOrchestrationResult
31
+ )
32
+ from .routing import UniversalModelRouter, ModelProfile, RoutingDecision
33
+
34
+
35
+ logger = logging.getLogger(__name__)
36
+
37
+
38
+ @dataclass
39
+ class TMLPDConfig:
40
+ """Configuration for TMLPD v2.2"""
41
+ # v2.1 settings
42
+ use_difficulty_classifier: bool = True
43
+ use_enhanced_agent: bool = True
44
+
45
+ # v2.2 settings
46
+ use_halo_orchestration: bool = False # Disabled by default for backward compatibility
47
+ use_universal_router: bool = False
48
+ use_mcts_optimization: bool = False
49
+
50
+ # HALO settings
51
+ max_concurrent_subtasks: int = 5
52
+ halo_optimization_target: str = "balanced" # "quality", "cost", "balanced"
53
+
54
+ # Universal Router settings
55
+ router_quality_target: float = 0.95
56
+ router_cost_weight: float = 0.5
57
+
58
+ # MCTS settings
59
+ mcts_simulations: int = 50
60
+ mcts_exploration_weight: float = 1.414
61
+
62
+ # Fallback settings
63
+ enable_fallback: bool = True
64
+ fallback_on_error: bool = True
65
+
66
+
67
+ class TMLPDOrchestrator:
68
+ """
69
+ Main TMLPD orchestrator with v2.1 + v2.2 support
70
+
71
+ This is the primary API for TMLPD v2.2. It automatically selects
72
+ the best orchestration strategy based on config and task complexity.
73
+
74
+ Backward Compatibility:
75
+ - Default behavior matches v2.1 (difficulty classification → enhanced agent)
76
+ - Enable v2.2 features via config
77
+ - All v2.1 API methods preserved
78
+ """
79
+
80
+ def __init__(self, config: Optional[TMLPDConfig] = None):
81
+ """
82
+ Initialize TMLPD orchestrator
83
+
84
+ Args:
85
+ config: Configuration for v2.1/v2.2 features
86
+ If None, uses defaults (v2.1 behavior)
87
+ """
88
+ self.config = config or TMLPDConfig()
89
+
90
+ # Initialize v2.1 components
91
+ if V21_AVAILABLE and self.config.use_difficulty_classifier:
92
+ self.difficulty_classifier = DifficultyClassifier()
93
+ else:
94
+ self.difficulty_classifier = None
95
+
96
+ if V21_AVAILABLE and self.config.use_enhanced_agent:
97
+ self.enhanced_agent = TMLEnhancedAgent()
98
+ else:
99
+ self.enhanced_agent = None
100
+
101
+ # Initialize v2.2 components
102
+ if self.config.use_halo_orchestration:
103
+ self.halo_orchestrator = HALOOrchestrator(
104
+ max_concurrent=self.config.max_concurrent_subtasks,
105
+ optimization_target=self.config.halo_optimization_target
106
+ )
107
+ self.mcts_search = MCTSWorkflowSearch(
108
+ RoleAssigner(),
109
+ ExecutionEngine(max_concurrent=self.config.max_concurrent_subtasks),
110
+ max_simulations=self.config.mcts_simulations
111
+ ) if self.config.use_mcts_optimization else None
112
+ else:
113
+ self.halo_orchestrator = None
114
+ self.mcts_search = None
115
+
116
+ if self.config.use_universal_router:
117
+ self.universal_router = UniversalModelRouter(
118
+ quality_target=self.config.router_quality_target,
119
+ cost_weight=self.config.router_cost_weight
120
+ )
121
+ else:
122
+ self.universal_router = None
123
+
124
+ logger.info(f"Initialized TMLPD v2.2 with config: {self.config}")
125
+
126
+ async def execute_task(
127
+ self,
128
+ task: Dict[str, Any],
129
+ preferred_model: Optional[str] = None
130
+ ) -> Dict[str, Any]:
131
+ """
132
+ Execute a task (main API method)
133
+
134
+ This method automatically selects the best execution strategy:
135
+ - If HALO enabled and task is complex → HALO orchestration
136
+ - If Universal Router enabled → smart routing
137
+ - Otherwise → v2.1 behavior (difficulty classification + enhanced agent)
138
+
139
+ Args:
140
+ task: Task with 'description' and optional 'context'
141
+ preferred_model: Specific model to use (overrides routing)
142
+
143
+ Returns:
144
+ Dict with execution results
145
+ """
146
+ logger.info(f"Executing task: {task.get('description', 'Unknown')}")
147
+
148
+ # Check if task is complex enough for HALO
149
+ should_use_halo = (
150
+ self.config.use_halo_orchestration and
151
+ self._is_complex_task(task)
152
+ )
153
+
154
+ if should_use_halo:
155
+ logger.info("Using HALO orchestration")
156
+ return await self._execute_with_halo(task)
157
+
158
+ # Use Universal Router if enabled
159
+ if self.config.use_universal_router and not preferred_model:
160
+ logger.info("Using Universal Router")
161
+ return await self._execute_with_router(task)
162
+
163
+ # Fall back to v2.1 behavior
164
+ logger.info("Using v2.1 execution path")
165
+ return await self._execute_v21(task, preferred_model)
166
+
167
+ async def _execute_with_halo(self, task: Dict[str, Any]) -> Dict[str, Any]:
168
+ """Execute using HALO orchestration (v2.2)"""
169
+ try:
170
+ result: HALOOrchestrationResult = await self.halo_orchestrator.orchestrate(task)
171
+
172
+ return {
173
+ "success": result.success,
174
+ "output": result.final_output,
175
+ "method": "halo_orchestration",
176
+ "metadata": {
177
+ "total_subtasks": result.metadata.get("total_subtasks", 0),
178
+ "parallel_speedup": result.metadata.get("parallel_speedup", 1.0),
179
+ "total_cost_usd": result.metadata.get("total_cost_usd", 0.0),
180
+ "orchestration_method": result.metadata.get("orchestration_method", "halo")
181
+ }
182
+ }
183
+ except Exception as e:
184
+ logger.error(f"HALO execution failed: {e}")
185
+ if self.config.fallback_on_error:
186
+ logger.info("Falling back to v2.1 execution")
187
+ return await self._execute_v21(task)
188
+
189
+ raise
190
+
191
+ async def _execute_with_router(self, task: Dict[str, Any]) -> Dict[str, Any]:
192
+ """Execute using Universal Router (v2.2)"""
193
+ try:
194
+ available_models = [
195
+ "anthropic/claude-3-5-sonnet-20241022",
196
+ "openai/gpt-4o",
197
+ "cerebras/llama-3.3-70b",
198
+ "groq/llama-3.3-70b"
199
+ ]
200
+
201
+ decision: RoutingDecision = await self.universal_router.route(task, available_models)
202
+
203
+ # Execute with selected model (simplified - would call actual LLM in production)
204
+ return {
205
+ "success": True,
206
+ "output": f"Executed with {decision.selected_model}",
207
+ "method": "universal_router",
208
+ "metadata": {
209
+ "selected_model": decision.selected_model,
210
+ "predicted_quality": decision.predicted_quality,
211
+ "estimated_cost": decision.estimated_cost,
212
+ "reasoning": decision.reasoning
213
+ }
214
+ }
215
+ except Exception as e:
216
+ logger.error(f"Router execution failed: {e}")
217
+ if self.config.fallback_on_error:
218
+ logger.info("Falling back to v2.1 execution")
219
+ return await self._execute_v21(task)
220
+
221
+ raise
222
+
223
+ async def _execute_v21(
224
+ self,
225
+ task: Dict[str, Any],
226
+ preferred_model: Optional[str] = None
227
+ ) -> Dict[str, Any]:
228
+ """Execute using v2.1 path (backward compatible)"""
229
+ if not V21_AVAILABLE:
230
+ # If v2.1 not available, use simple execution
231
+ return {
232
+ "success": True,
233
+ "output": f"Executed (simple mode): {task.get('description', '')}",
234
+ "method": "simple_fallback"
235
+ }
236
+
237
+ try:
238
+ # Difficulty classification
239
+ if self.difficulty_classifier:
240
+ difficulty = await self.difficulty_classifier.classify(task)
241
+ logger.info(f"Task difficulty: {difficulty}")
242
+ else:
243
+ difficulty = None
244
+
245
+ # Enhanced agent execution
246
+ if self.enhanced_agent:
247
+ result = await self.enhanced_agent.execute_task(task, preferred_model)
248
+ else:
249
+ result = {"success": True, "output": "Executed"}
250
+
251
+ return {
252
+ "success": result.get("success", True),
253
+ "output": result.get("output", ""),
254
+ "method": "v21_enhanced_agent",
255
+ "metadata": {
256
+ "difficulty": str(difficulty) if difficulty else "unknown",
257
+ "preferred_model": preferred_model
258
+ }
259
+ }
260
+ except Exception as e:
261
+ logger.error(f"v2.1 execution failed: {e}")
262
+ raise
263
+
264
+ def _is_complex_task(self, task: Dict[str, Any]) -> bool:
265
+ """
266
+ Determine if task is complex enough for HALO orchestration
267
+
268
+ Uses simple heuristics based on task description and context
269
+ """
270
+ description = task.get("description", "")
271
+ context = task.get("context", {})
272
+
273
+ # Complexity indicators
274
+ complexity_score = 0
275
+
276
+ # Length
277
+ if len(description.split()) > 50:
278
+ complexity_score += 1
279
+
280
+ # Multi-step indicators
281
+ multi_step_words = ["then", "after", "next", "finally", "additionally"]
282
+ if any(word in description.lower() for word in multi_step_words):
283
+ complexity_score += 1
284
+
285
+ # Technical complexity
286
+ technical_words = ["api", "database", "algorithm", "architecture", "system"]
287
+ if any(word in description.lower() for word in technical_words):
288
+ complexity_score += 1
289
+
290
+ # Requirements/constraints
291
+ if len(context.get("requirements", [])) > 2:
292
+ complexity_score += 1
293
+
294
+ # Task is complex if score >= 2
295
+ return complexity_score >= 2
296
+
297
+ # v2.1 Backward-compatible API methods
298
+ async def classify_difficulty(self, task: Dict[str, Any]) -> Optional[str]:
299
+ """Classify task difficulty (v2.1 API)"""
300
+ if self.difficulty_classifier:
301
+ result = await self.difficulty_classifier.classify(task)
302
+ return str(result)
303
+ return None
304
+
305
+ async def route_to_model(
306
+ self,
307
+ task: Dict[str, Any],
308
+ available_models: List[str]
309
+ ) -> Optional[str]:
310
+ """Route task to best model (v2.1 API + v2.2 enhancement)"""
311
+ if self.universal_router:
312
+ decision = await self.universal_router.route(task, available_models)
313
+ return decision.selected_model
314
+ return None
315
+
316
+ def get_config(self) -> TMLPDConfig:
317
+ """Get current configuration"""
318
+ return self.config
319
+
320
+ def update_config(self, **kwargs):
321
+ """Update configuration"""
322
+ for key, value in kwargs.items():
323
+ if hasattr(self.config, key):
324
+ setattr(self.config, key, value)
325
+ else:
326
+ logger.warning(f"Unknown config key: {key}")
327
+
328
+ logger.info(f"Updated config: {kwargs}")
329
+
330
+
331
+ # Convenience function for quick usage
332
+ async def execute_task_simple(
333
+ description: str,
334
+ context: Optional[Dict[str, Any]] = None,
335
+ use_halo: bool = False,
336
+ use_router: bool = False
337
+ ) -> Dict[str, Any]:
338
+ """
339
+ Simple API for one-off task execution
340
+
341
+ Args:
342
+ description: Task description
343
+ context: Optional task context
344
+ use_halo: Enable HALO orchestration
345
+ use_router: Enable Universal Router
346
+
347
+ Returns:
348
+ Execution result
349
+ """
350
+ config = TMLPDConfig(
351
+ use_halo_orchestration=use_halo,
352
+ use_universal_router=use_router
353
+ )
354
+
355
+ orchestrator = TMLPDOrchestrator(config)
356
+
357
+ task = {
358
+ "description": description,
359
+ "context": context or {}
360
+ }
361
+
362
+ return await orchestrator.execute_task(task)
363
+
364
+
365
+ # Example usage
366
+ async def main():
367
+ """Example of TMLPD v2.2 usage"""
368
+
369
+ print("=" * 70)
370
+ print("TMLPD v2.2 - Backward-Compatible API Demo")
371
+ print("=" * 70)
372
+
373
+ # Example 1: v2.1 behavior (default)
374
+ print("\n1. Default (v2.1 behavior):")
375
+ result = await execute_task_simple("What is 2+2?")
376
+ print(f" Method: {result['method']}")
377
+ print(f" Success: {result['success']}")
378
+
379
+ # Example 2: Enable Universal Router
380
+ print("\n2. With Universal Router (v2.2):")
381
+ result = await execute_task_simple(
382
+ "What is the capital of France?",
383
+ use_router=True
384
+ )
385
+ print(f" Method: {result['method']}")
386
+ print(f" Selected Model: {result['metadata'].get('selected_model', 'N/A')}")
387
+
388
+ # Example 3: Enable HALO for complex task
389
+ print("\n3. With HALO Orchestration (v2.2):")
390
+ result = await execute_task_simple(
391
+ "Build a REST API with authentication, database, and testing",
392
+ use_halo=True
393
+ )
394
+ print(f" Method: {result['method']}")
395
+ print(f" Success: {result['success']}")
396
+ if "subtasks" in result.get("metadata", {}):
397
+ print(f" Subtasks: {result['metadata']['total_subtasks']}")
398
+
399
+ # Example 4: Full v2.2 config
400
+ print("\n4. Full v2.2 Configuration:")
401
+ config = TMLPDConfig(
402
+ use_halo_orchestration=True,
403
+ use_universal_router=True,
404
+ use_mcts_optimization=True,
405
+ halo_optimization_target="balanced",
406
+ mcts_simulations=30
407
+ )
408
+
409
+ orchestrator = TMLPDOrchestrator(config)
410
+
411
+ task = {
412
+ "description": "Design and implement a microservices architecture",
413
+ "context": {"requirements": ["docker", "kubernetes", "api-gateway"]}
414
+ }
415
+
416
+ result = await orchestrator.execute_task(task)
417
+ print(f" Method: {result['method']}")
418
+ print(f" Success: {result['success']}")
419
+
420
+ print("\n" + "=" * 70)
421
+ print("Demo Complete")
422
+ print("=" * 70)
423
+
424
+
425
+ if __name__ == "__main__":
426
+ logging.basicConfig(level=logging.INFO)
427
+ asyncio.run(main())
@@ -0,0 +1,18 @@
1
+ """
2
+ TMLPD Workflows Module
3
+
4
+ This module provides workflow patterns following Anthropic's specification:
5
+ - Routing: Classify and route to appropriate handlers
6
+ - Orchestrator-Workers: Dynamic task breakdown and delegation
7
+ """
8
+
9
+ from .router import TaskRouter, route_and_execute
10
+ from .orchestrator import OrchestratorWorkflow, OrchestratorAgent, orchestrate_task
11
+
12
+ __all__ = [
13
+ "TaskRouter",
14
+ "route_and_execute",
15
+ "OrchestratorWorkflow",
16
+ "OrchestratorAgent",
17
+ "orchestrate_task"
18
+ ]