htmlgraph 0.20.1__py3-none-any.whl → 0.27.5__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 (304) hide show
  1. htmlgraph/.htmlgraph/.session-warning-state.json +6 -0
  2. htmlgraph/.htmlgraph/agents.json +72 -0
  3. htmlgraph/.htmlgraph/htmlgraph.db +0 -0
  4. htmlgraph/__init__.py +51 -1
  5. htmlgraph/__init__.pyi +123 -0
  6. htmlgraph/agent_detection.py +26 -10
  7. htmlgraph/agent_registry.py +2 -1
  8. htmlgraph/analytics/__init__.py +8 -1
  9. htmlgraph/analytics/cli.py +86 -20
  10. htmlgraph/analytics/cost_analyzer.py +391 -0
  11. htmlgraph/analytics/cost_monitor.py +664 -0
  12. htmlgraph/analytics/cost_reporter.py +675 -0
  13. htmlgraph/analytics/cross_session.py +617 -0
  14. htmlgraph/analytics/dependency.py +10 -6
  15. htmlgraph/analytics/pattern_learning.py +771 -0
  16. htmlgraph/analytics/session_graph.py +707 -0
  17. htmlgraph/analytics/strategic/__init__.py +80 -0
  18. htmlgraph/analytics/strategic/cost_optimizer.py +611 -0
  19. htmlgraph/analytics/strategic/pattern_detector.py +876 -0
  20. htmlgraph/analytics/strategic/preference_manager.py +709 -0
  21. htmlgraph/analytics/strategic/suggestion_engine.py +747 -0
  22. htmlgraph/analytics/work_type.py +67 -27
  23. htmlgraph/analytics_index.py +53 -20
  24. htmlgraph/api/__init__.py +3 -0
  25. htmlgraph/api/cost_alerts_websocket.py +416 -0
  26. htmlgraph/api/main.py +2498 -0
  27. htmlgraph/api/static/htmx.min.js +1 -0
  28. htmlgraph/api/static/style-redesign.css +1344 -0
  29. htmlgraph/api/static/style.css +1079 -0
  30. htmlgraph/api/templates/dashboard-redesign.html +1366 -0
  31. htmlgraph/api/templates/dashboard.html +794 -0
  32. htmlgraph/api/templates/partials/activity-feed-hierarchical.html +326 -0
  33. htmlgraph/api/templates/partials/activity-feed.html +1100 -0
  34. htmlgraph/api/templates/partials/agents-redesign.html +317 -0
  35. htmlgraph/api/templates/partials/agents.html +317 -0
  36. htmlgraph/api/templates/partials/event-traces.html +373 -0
  37. htmlgraph/api/templates/partials/features-kanban-redesign.html +509 -0
  38. htmlgraph/api/templates/partials/features.html +578 -0
  39. htmlgraph/api/templates/partials/metrics-redesign.html +346 -0
  40. htmlgraph/api/templates/partials/metrics.html +346 -0
  41. htmlgraph/api/templates/partials/orchestration-redesign.html +443 -0
  42. htmlgraph/api/templates/partials/orchestration.html +198 -0
  43. htmlgraph/api/templates/partials/spawners.html +375 -0
  44. htmlgraph/api/templates/partials/work-items.html +613 -0
  45. htmlgraph/api/websocket.py +538 -0
  46. htmlgraph/archive/__init__.py +24 -0
  47. htmlgraph/archive/bloom.py +234 -0
  48. htmlgraph/archive/fts.py +297 -0
  49. htmlgraph/archive/manager.py +583 -0
  50. htmlgraph/archive/search.py +244 -0
  51. htmlgraph/atomic_ops.py +560 -0
  52. htmlgraph/attribute_index.py +2 -1
  53. htmlgraph/bounded_paths.py +539 -0
  54. htmlgraph/builders/base.py +57 -2
  55. htmlgraph/builders/bug.py +19 -3
  56. htmlgraph/builders/chore.py +19 -3
  57. htmlgraph/builders/epic.py +19 -3
  58. htmlgraph/builders/feature.py +27 -3
  59. htmlgraph/builders/insight.py +2 -1
  60. htmlgraph/builders/metric.py +2 -1
  61. htmlgraph/builders/pattern.py +2 -1
  62. htmlgraph/builders/phase.py +19 -3
  63. htmlgraph/builders/spike.py +29 -3
  64. htmlgraph/builders/track.py +42 -1
  65. htmlgraph/cigs/__init__.py +81 -0
  66. htmlgraph/cigs/autonomy.py +385 -0
  67. htmlgraph/cigs/cost.py +475 -0
  68. htmlgraph/cigs/messages_basic.py +472 -0
  69. htmlgraph/cigs/messaging.py +365 -0
  70. htmlgraph/cigs/models.py +771 -0
  71. htmlgraph/cigs/pattern_storage.py +427 -0
  72. htmlgraph/cigs/patterns.py +503 -0
  73. htmlgraph/cigs/posttool_analyzer.py +234 -0
  74. htmlgraph/cigs/reporter.py +818 -0
  75. htmlgraph/cigs/tracker.py +317 -0
  76. htmlgraph/cli/.htmlgraph/.session-warning-state.json +6 -0
  77. htmlgraph/cli/.htmlgraph/agents.json +72 -0
  78. htmlgraph/cli/.htmlgraph/htmlgraph.db +0 -0
  79. htmlgraph/cli/__init__.py +42 -0
  80. htmlgraph/cli/__main__.py +6 -0
  81. htmlgraph/cli/analytics.py +1424 -0
  82. htmlgraph/cli/base.py +685 -0
  83. htmlgraph/cli/constants.py +206 -0
  84. htmlgraph/cli/core.py +954 -0
  85. htmlgraph/cli/main.py +147 -0
  86. htmlgraph/cli/models.py +475 -0
  87. htmlgraph/cli/templates/__init__.py +1 -0
  88. htmlgraph/cli/templates/cost_dashboard.py +399 -0
  89. htmlgraph/cli/work/__init__.py +239 -0
  90. htmlgraph/cli/work/browse.py +115 -0
  91. htmlgraph/cli/work/features.py +568 -0
  92. htmlgraph/cli/work/orchestration.py +676 -0
  93. htmlgraph/cli/work/report.py +728 -0
  94. htmlgraph/cli/work/sessions.py +466 -0
  95. htmlgraph/cli/work/snapshot.py +559 -0
  96. htmlgraph/cli/work/tracks.py +486 -0
  97. htmlgraph/cli_commands/__init__.py +1 -0
  98. htmlgraph/cli_commands/feature.py +195 -0
  99. htmlgraph/cli_framework.py +115 -0
  100. htmlgraph/collections/__init__.py +2 -0
  101. htmlgraph/collections/base.py +197 -14
  102. htmlgraph/collections/bug.py +2 -1
  103. htmlgraph/collections/chore.py +2 -1
  104. htmlgraph/collections/epic.py +2 -1
  105. htmlgraph/collections/feature.py +2 -1
  106. htmlgraph/collections/insight.py +2 -1
  107. htmlgraph/collections/metric.py +2 -1
  108. htmlgraph/collections/pattern.py +2 -1
  109. htmlgraph/collections/phase.py +2 -1
  110. htmlgraph/collections/session.py +194 -0
  111. htmlgraph/collections/spike.py +13 -2
  112. htmlgraph/collections/task_delegation.py +241 -0
  113. htmlgraph/collections/todo.py +14 -1
  114. htmlgraph/collections/traces.py +487 -0
  115. htmlgraph/config/cost_models.json +56 -0
  116. htmlgraph/config.py +190 -0
  117. htmlgraph/context_analytics.py +2 -1
  118. htmlgraph/converter.py +116 -7
  119. htmlgraph/cost_analysis/__init__.py +5 -0
  120. htmlgraph/cost_analysis/analyzer.py +438 -0
  121. htmlgraph/dashboard.html +2246 -248
  122. htmlgraph/dashboard.html.backup +6592 -0
  123. htmlgraph/dashboard.html.bak +7181 -0
  124. htmlgraph/dashboard.html.bak2 +7231 -0
  125. htmlgraph/dashboard.html.bak3 +7232 -0
  126. htmlgraph/db/__init__.py +38 -0
  127. htmlgraph/db/queries.py +790 -0
  128. htmlgraph/db/schema.py +1788 -0
  129. htmlgraph/decorators.py +317 -0
  130. htmlgraph/dependency_models.py +2 -1
  131. htmlgraph/deploy.py +26 -27
  132. htmlgraph/docs/API_REFERENCE.md +841 -0
  133. htmlgraph/docs/HTTP_API.md +750 -0
  134. htmlgraph/docs/INTEGRATION_GUIDE.md +752 -0
  135. htmlgraph/docs/ORCHESTRATION_PATTERNS.md +717 -0
  136. htmlgraph/docs/README.md +532 -0
  137. htmlgraph/docs/__init__.py +77 -0
  138. htmlgraph/docs/docs_version.py +55 -0
  139. htmlgraph/docs/metadata.py +93 -0
  140. htmlgraph/docs/migrations.py +232 -0
  141. htmlgraph/docs/template_engine.py +143 -0
  142. htmlgraph/docs/templates/_sections/cli_reference.md.j2 +52 -0
  143. htmlgraph/docs/templates/_sections/core_concepts.md.j2 +29 -0
  144. htmlgraph/docs/templates/_sections/sdk_basics.md.j2 +69 -0
  145. htmlgraph/docs/templates/base_agents.md.j2 +78 -0
  146. htmlgraph/docs/templates/example_user_override.md.j2 +47 -0
  147. htmlgraph/docs/version_check.py +163 -0
  148. htmlgraph/edge_index.py +2 -1
  149. htmlgraph/error_handler.py +544 -0
  150. htmlgraph/event_log.py +86 -37
  151. htmlgraph/event_migration.py +2 -1
  152. htmlgraph/file_watcher.py +12 -8
  153. htmlgraph/find_api.py +2 -1
  154. htmlgraph/git_events.py +67 -9
  155. htmlgraph/hooks/.htmlgraph/.session-warning-state.json +6 -0
  156. htmlgraph/hooks/.htmlgraph/agents.json +72 -0
  157. htmlgraph/hooks/.htmlgraph/index.sqlite +0 -0
  158. htmlgraph/hooks/__init__.py +8 -0
  159. htmlgraph/hooks/bootstrap.py +169 -0
  160. htmlgraph/hooks/cigs_pretool_enforcer.py +354 -0
  161. htmlgraph/hooks/concurrent_sessions.py +208 -0
  162. htmlgraph/hooks/context.py +350 -0
  163. htmlgraph/hooks/drift_handler.py +525 -0
  164. htmlgraph/hooks/event_tracker.py +790 -99
  165. htmlgraph/hooks/git_commands.py +175 -0
  166. htmlgraph/hooks/installer.py +5 -1
  167. htmlgraph/hooks/orchestrator.py +327 -76
  168. htmlgraph/hooks/orchestrator_reflector.py +31 -4
  169. htmlgraph/hooks/post_tool_use_failure.py +32 -7
  170. htmlgraph/hooks/post_tool_use_handler.py +257 -0
  171. htmlgraph/hooks/posttooluse.py +92 -19
  172. htmlgraph/hooks/pretooluse.py +527 -7
  173. htmlgraph/hooks/prompt_analyzer.py +637 -0
  174. htmlgraph/hooks/session_handler.py +668 -0
  175. htmlgraph/hooks/session_summary.py +395 -0
  176. htmlgraph/hooks/state_manager.py +504 -0
  177. htmlgraph/hooks/subagent_detection.py +202 -0
  178. htmlgraph/hooks/subagent_stop.py +369 -0
  179. htmlgraph/hooks/task_enforcer.py +99 -4
  180. htmlgraph/hooks/validator.py +212 -91
  181. htmlgraph/ids.py +2 -1
  182. htmlgraph/learning.py +125 -100
  183. htmlgraph/mcp_server.py +2 -1
  184. htmlgraph/models.py +217 -18
  185. htmlgraph/operations/README.md +62 -0
  186. htmlgraph/operations/__init__.py +79 -0
  187. htmlgraph/operations/analytics.py +339 -0
  188. htmlgraph/operations/bootstrap.py +289 -0
  189. htmlgraph/operations/events.py +244 -0
  190. htmlgraph/operations/fastapi_server.py +231 -0
  191. htmlgraph/operations/hooks.py +350 -0
  192. htmlgraph/operations/initialization.py +597 -0
  193. htmlgraph/operations/initialization.py.backup +228 -0
  194. htmlgraph/operations/server.py +303 -0
  195. htmlgraph/orchestration/__init__.py +58 -0
  196. htmlgraph/orchestration/claude_launcher.py +179 -0
  197. htmlgraph/orchestration/command_builder.py +72 -0
  198. htmlgraph/orchestration/headless_spawner.py +281 -0
  199. htmlgraph/orchestration/live_events.py +377 -0
  200. htmlgraph/orchestration/model_selection.py +327 -0
  201. htmlgraph/orchestration/plugin_manager.py +140 -0
  202. htmlgraph/orchestration/prompts.py +137 -0
  203. htmlgraph/orchestration/spawner_event_tracker.py +383 -0
  204. htmlgraph/orchestration/spawners/__init__.py +16 -0
  205. htmlgraph/orchestration/spawners/base.py +194 -0
  206. htmlgraph/orchestration/spawners/claude.py +173 -0
  207. htmlgraph/orchestration/spawners/codex.py +435 -0
  208. htmlgraph/orchestration/spawners/copilot.py +294 -0
  209. htmlgraph/orchestration/spawners/gemini.py +471 -0
  210. htmlgraph/orchestration/subprocess_runner.py +36 -0
  211. htmlgraph/{orchestration.py → orchestration/task_coordination.py} +16 -8
  212. htmlgraph/orchestration.md +563 -0
  213. htmlgraph/orchestrator-system-prompt-optimized.txt +863 -0
  214. htmlgraph/orchestrator.py +2 -1
  215. htmlgraph/orchestrator_config.py +357 -0
  216. htmlgraph/orchestrator_mode.py +115 -4
  217. htmlgraph/parallel.py +2 -1
  218. htmlgraph/parser.py +86 -6
  219. htmlgraph/path_query.py +608 -0
  220. htmlgraph/pattern_matcher.py +636 -0
  221. htmlgraph/pydantic_models.py +476 -0
  222. htmlgraph/quality_gates.py +350 -0
  223. htmlgraph/query_builder.py +2 -1
  224. htmlgraph/query_composer.py +509 -0
  225. htmlgraph/reflection.py +443 -0
  226. htmlgraph/refs.py +344 -0
  227. htmlgraph/repo_hash.py +512 -0
  228. htmlgraph/repositories/__init__.py +292 -0
  229. htmlgraph/repositories/analytics_repository.py +455 -0
  230. htmlgraph/repositories/analytics_repository_standard.py +628 -0
  231. htmlgraph/repositories/feature_repository.py +581 -0
  232. htmlgraph/repositories/feature_repository_htmlfile.py +668 -0
  233. htmlgraph/repositories/feature_repository_memory.py +607 -0
  234. htmlgraph/repositories/feature_repository_sqlite.py +858 -0
  235. htmlgraph/repositories/filter_service.py +620 -0
  236. htmlgraph/repositories/filter_service_standard.py +445 -0
  237. htmlgraph/repositories/shared_cache.py +621 -0
  238. htmlgraph/repositories/shared_cache_memory.py +395 -0
  239. htmlgraph/repositories/track_repository.py +552 -0
  240. htmlgraph/repositories/track_repository_htmlfile.py +619 -0
  241. htmlgraph/repositories/track_repository_memory.py +508 -0
  242. htmlgraph/repositories/track_repository_sqlite.py +711 -0
  243. htmlgraph/sdk/__init__.py +398 -0
  244. htmlgraph/sdk/__init__.pyi +14 -0
  245. htmlgraph/sdk/analytics/__init__.py +19 -0
  246. htmlgraph/sdk/analytics/engine.py +155 -0
  247. htmlgraph/sdk/analytics/helpers.py +178 -0
  248. htmlgraph/sdk/analytics/registry.py +109 -0
  249. htmlgraph/sdk/base.py +484 -0
  250. htmlgraph/sdk/constants.py +216 -0
  251. htmlgraph/sdk/core.pyi +308 -0
  252. htmlgraph/sdk/discovery.py +120 -0
  253. htmlgraph/sdk/help/__init__.py +12 -0
  254. htmlgraph/sdk/help/mixin.py +699 -0
  255. htmlgraph/sdk/mixins/__init__.py +15 -0
  256. htmlgraph/sdk/mixins/attribution.py +113 -0
  257. htmlgraph/sdk/mixins/mixin.py +410 -0
  258. htmlgraph/sdk/operations/__init__.py +12 -0
  259. htmlgraph/sdk/operations/mixin.py +427 -0
  260. htmlgraph/sdk/orchestration/__init__.py +17 -0
  261. htmlgraph/sdk/orchestration/coordinator.py +203 -0
  262. htmlgraph/sdk/orchestration/spawner.py +204 -0
  263. htmlgraph/sdk/planning/__init__.py +19 -0
  264. htmlgraph/sdk/planning/bottlenecks.py +93 -0
  265. htmlgraph/sdk/planning/mixin.py +211 -0
  266. htmlgraph/sdk/planning/parallel.py +186 -0
  267. htmlgraph/sdk/planning/queue.py +210 -0
  268. htmlgraph/sdk/planning/recommendations.py +87 -0
  269. htmlgraph/sdk/planning/smart_planning.py +319 -0
  270. htmlgraph/sdk/session/__init__.py +19 -0
  271. htmlgraph/sdk/session/continuity.py +57 -0
  272. htmlgraph/sdk/session/handoff.py +110 -0
  273. htmlgraph/sdk/session/info.py +309 -0
  274. htmlgraph/sdk/session/manager.py +103 -0
  275. htmlgraph/sdk/strategic/__init__.py +26 -0
  276. htmlgraph/sdk/strategic/mixin.py +563 -0
  277. htmlgraph/server.py +295 -107
  278. htmlgraph/session_hooks.py +300 -0
  279. htmlgraph/session_manager.py +285 -3
  280. htmlgraph/session_registry.py +587 -0
  281. htmlgraph/session_state.py +436 -0
  282. htmlgraph/session_warning.py +2 -1
  283. htmlgraph/sessions/__init__.py +23 -0
  284. htmlgraph/sessions/handoff.py +756 -0
  285. htmlgraph/system_prompts.py +450 -0
  286. htmlgraph/templates/orchestration-view.html +350 -0
  287. htmlgraph/track_builder.py +33 -1
  288. htmlgraph/track_manager.py +38 -0
  289. htmlgraph/transcript.py +18 -5
  290. htmlgraph/validation.py +115 -0
  291. htmlgraph/watch.py +2 -1
  292. htmlgraph/work_type_utils.py +2 -1
  293. {htmlgraph-0.20.1.data → htmlgraph-0.27.5.data}/data/htmlgraph/dashboard.html +2246 -248
  294. {htmlgraph-0.20.1.dist-info → htmlgraph-0.27.5.dist-info}/METADATA +95 -64
  295. htmlgraph-0.27.5.dist-info/RECORD +337 -0
  296. {htmlgraph-0.20.1.dist-info → htmlgraph-0.27.5.dist-info}/entry_points.txt +1 -1
  297. htmlgraph/cli.py +0 -4839
  298. htmlgraph/sdk.py +0 -2359
  299. htmlgraph-0.20.1.dist-info/RECORD +0 -118
  300. {htmlgraph-0.20.1.data → htmlgraph-0.27.5.data}/data/htmlgraph/styles.css +0 -0
  301. {htmlgraph-0.20.1.data → htmlgraph-0.27.5.data}/data/htmlgraph/templates/AGENTS.md.template +0 -0
  302. {htmlgraph-0.20.1.data → htmlgraph-0.27.5.data}/data/htmlgraph/templates/CLAUDE.md.template +0 -0
  303. {htmlgraph-0.20.1.data → htmlgraph-0.27.5.data}/data/htmlgraph/templates/GEMINI.md.template +0 -0
  304. {htmlgraph-0.20.1.dist-info → htmlgraph-0.27.5.dist-info}/WHEEL +0 -0
@@ -0,0 +1,717 @@
1
+ # HtmlGraph Orchestration Patterns
2
+
3
+ Guide to spawning agents, delegating tasks, and coordinating multi-agent workflows.
4
+
5
+ ## Table of Contents
6
+
7
+ 1. [Core Concepts](#core-concepts)
8
+ 2. [Agent Selection](#agent-selection)
9
+ 3. [Task Delegation](#task-delegation)
10
+ 4. [Result Tracking](#result-tracking)
11
+ 5. [Cost Optimization](#cost-optimization)
12
+ 6. [Advanced Patterns](#advanced-patterns)
13
+ 7. [Troubleshooting](#troubleshooting)
14
+
15
+ ---
16
+
17
+ ## Core Concepts
18
+
19
+ ### Agent Spawning
20
+
21
+ Dynamically spawn specialized agents for specific tasks:
22
+
23
+ ```python
24
+ from htmlgraph.orchestration import HeadlessSpawner
25
+
26
+ spawner = HeadlessSpawner()
27
+
28
+ # Spawn different agents for different tasks
29
+ result = spawner.spawn_claude(
30
+ prompt="Implement user authentication module",
31
+ approval="auto"
32
+ )
33
+
34
+ result = spawner.spawn_gemini(
35
+ prompt="Analyze codebase for performance issues"
36
+ # model=None (default) - uses latest Gemini models including Gemini 3 preview
37
+ )
38
+
39
+ result = spawner.spawn_codex(
40
+ prompt="Generate API endpoint implementation",
41
+ sandbox="workspace-write"
42
+ )
43
+ ```
44
+
45
+ ### Task vs Agent
46
+
47
+ - **Agent**: An AI model spawned to complete work (Claude, Gemini, Codex, Copilot)
48
+ - **Task**: A delegated unit of work tracked in `.htmlgraph/task-delegations/`
49
+ - **Result**: The output of a completed task stored in HtmlGraph
50
+
51
+ ---
52
+
53
+ ## Agent Selection
54
+
55
+ ### Spawn Methods
56
+
57
+ #### Claude Spawning
58
+
59
+ ```python
60
+ from htmlgraph.orchestration import HeadlessSpawner
61
+
62
+ spawner = HeadlessSpawner()
63
+
64
+ result = spawner.spawn_claude(
65
+ prompt="Your task description",
66
+ approval="auto", # "auto", "manual", "never"
67
+ model="claude-opus", # Model to use
68
+ max_thinking_budget=10000, # Extended thinking budget
69
+ output_json=False
70
+ )
71
+
72
+ if result.success:
73
+ print(f"Output: {result.response}")
74
+ print(f"Tokens: {result.tokens_used}")
75
+ else:
76
+ print(f"Error: {result.error}")
77
+ ```
78
+
79
+ **Claude Models:**
80
+ - `claude-opus` - Most capable, highest cost
81
+ - `claude-sonnet` - Balanced capability/cost
82
+ - `claude-haiku` - Fastest, lowest cost
83
+
84
+ ---
85
+
86
+ #### Gemini Spawning
87
+
88
+ ```python
89
+ result = spawner.spawn_gemini(
90
+ prompt="Analyze this code for security issues",
91
+ # model=None (default) - RECOMMENDED: uses latest Gemini models
92
+ temperature=0.7, # Creativity (0-1)
93
+ output_json=False
94
+ )
95
+
96
+ if result.success:
97
+ print(result.response)
98
+ else:
99
+ print(f"Error: {result.error}")
100
+ ```
101
+
102
+ **Gemini Model Selection:**
103
+ - `None` (default) - **RECOMMENDED**: CLI chooses best available model (gemini-2.5-flash-lite, gemini-3-flash-preview)
104
+ - Explicit model specification is DISCOURAGED - older models may fail with newer CLI versions
105
+
106
+ **Available models (if you must specify):**
107
+ - `gemini-2.5-flash-lite` - Fast, efficient
108
+ - `gemini-3-flash-preview` - Gemini 3 with enhanced capabilities
109
+ - `gemini-2.5-pro` - More capable, slower
110
+
111
+ **DEPRECATED models (may cause errors):**
112
+ - `gemini-2.0-flash`, `gemini-1.5-pro`, `gemini-1.5-flash` - Use `None` instead
113
+
114
+ ---
115
+
116
+ #### Codex/GPT Spawning
117
+
118
+ ```python
119
+ result = spawner.spawn_codex(
120
+ prompt="Generate implementation for REST API",
121
+ sandbox="workspace-write", # Execution sandbox
122
+ model="gpt-4-turbo", # OpenAI model
123
+ full_auto=False, # Auto-execute code
124
+ output_json=True
125
+ )
126
+
127
+ if result.success:
128
+ print(result.response)
129
+ # Access raw JSONL events
130
+ for event in result.raw_output:
131
+ if event.get("type") == "item.completed":
132
+ print(f"Completed: {event['item']['type']}")
133
+ else:
134
+ print(f"Error: {result.error}")
135
+ ```
136
+
137
+ **Codex Sandbox Levels:**
138
+ - `read-only` - No write access (safe)
139
+ - `workspace-write` - Write to workspace only (recommended)
140
+ - `danger-full-access` - Unrestricted access (risky)
141
+
142
+ ---
143
+
144
+ #### Copilot Spawning
145
+
146
+ ```python
147
+ result = spawner.spawn_copilot(
148
+ prompt="Refactor this Python function",
149
+ model="gpt-4",
150
+ output_json=False
151
+ )
152
+
153
+ if result.success:
154
+ print(result.response)
155
+ else:
156
+ print(f"Error: {result.error}")
157
+ ```
158
+
159
+ ---
160
+
161
+ ### Model Selection Strategy
162
+
163
+ ```python
164
+ from htmlgraph.orchestration import (
165
+ select_model,
166
+ TaskType,
167
+ ComplexityLevel,
168
+ BudgetMode
169
+ )
170
+
171
+ # Automatically select best model
172
+ model = select_model(
173
+ task_type=TaskType.CODE_GENERATION, # Task classification
174
+ complexity=ComplexityLevel.HIGH, # Complexity assessment
175
+ budget_mode=BudgetMode.BALANCED # Cost preference
176
+ )
177
+ # Returns: "gpt-4-turbo" (or other optimal model)
178
+
179
+ # Use selected model
180
+ if model == "gpt-4-turbo":
181
+ result = spawner.spawn_codex(prompt="...", model=model)
182
+ elif model == "claude-opus":
183
+ result = spawner.spawn_claude(prompt="...", model=model)
184
+ elif model.startswith("gemini"):
185
+ result = spawner.spawn_gemini(prompt="...") # model=None recommended
186
+ ```
187
+
188
+ **Task Types:**
189
+ - `CODE_GENERATION` - Writing new code
190
+ - `CODE_REVIEW` - Analyzing code
191
+ - `DEBUGGING` - Finding/fixing bugs
192
+ - `DOCUMENTATION` - Writing docs
193
+ - `ARCHITECTURE` - Design decisions
194
+ - `TESTING` - Test generation
195
+ - `REFACTORING` - Code improvements
196
+
197
+ **Complexity Levels:**
198
+ - `LOW` - Simple, straightforward tasks
199
+ - `MEDIUM` - Moderate complexity
200
+ - `HIGH` - Complex, multi-step tasks
201
+
202
+ **Budget Modes:**
203
+ - `COST_OPTIMIZED` - Prefer cheaper models
204
+ - `BALANCED` - Mix cost/capability
205
+ - `QUALITY_FOCUSED` - Use best models
206
+
207
+ ---
208
+
209
+ ## Task Delegation
210
+
211
+ ### Simple Delegation
212
+
213
+ ```python
214
+ from htmlgraph import SDK, delegate_with_id
215
+
216
+ sdk = SDK(agent="orchestrator")
217
+
218
+ # Delegate single task
219
+ task_id = delegate_with_id(
220
+ prompt="Implement JWT authentication middleware",
221
+ agent="coder",
222
+ task_id="task-auth-001"
223
+ )
224
+
225
+ print(f"Delegated task: {task_id}")
226
+ ```
227
+
228
+ ### Parallel Delegation
229
+
230
+ ```python
231
+ from htmlgraph import parallel_delegate
232
+
233
+ # Delegate multiple tasks in parallel
234
+ tasks = [
235
+ {
236
+ "prompt": "Implement login endpoint",
237
+ "agent": "coder",
238
+ "task_id": "auth-login"
239
+ },
240
+ {
241
+ "prompt": "Implement logout endpoint",
242
+ "agent": "coder",
243
+ "task_id": "auth-logout"
244
+ },
245
+ {
246
+ "prompt": "Write authentication tests",
247
+ "agent": "tester",
248
+ "task_id": "auth-tests"
249
+ },
250
+ {
251
+ "prompt": "Document authentication API",
252
+ "agent": "writer",
253
+ "task_id": "auth-docs"
254
+ }
255
+ ]
256
+
257
+ results = parallel_delegate(tasks)
258
+
259
+ # Process results as they complete
260
+ for task_id, result in results.items():
261
+ print(f"{task_id}: {result['status']}")
262
+ if result['status'] == 'completed':
263
+ print(f"Output: {result['output']}")
264
+ ```
265
+
266
+ ---
267
+
268
+ ### Delegation with Fallback
269
+
270
+ ```python
271
+ # Try Codex, fallback to Claude if fails
272
+ result = spawner.spawn_codex(
273
+ prompt="Generate API implementation",
274
+ sandbox="workspace-write"
275
+ )
276
+
277
+ if not result.success:
278
+ print(f"Codex failed: {result.error}")
279
+ print("Falling back to Claude...")
280
+
281
+ result = spawner.spawn_claude(
282
+ prompt="Generate API implementation",
283
+ approval="auto"
284
+ )
285
+
286
+ print(f"Final result: {result.response}")
287
+ ```
288
+
289
+ ---
290
+
291
+ ## Result Tracking
292
+
293
+ ### Get Task Results
294
+
295
+ ```python
296
+ from htmlgraph import get_results_by_task_id
297
+
298
+ # Check task status
299
+ results = get_results_by_task_id("task-auth-001")
300
+
301
+ if results:
302
+ print(f"Status: {results['status']}")
303
+ print(f"Output: {results['output']}")
304
+ print(f"Tokens used: {results['tokens_used']}")
305
+ else:
306
+ print("Task not found")
307
+ ```
308
+
309
+ ### Track Delegations in SDK
310
+
311
+ ```python
312
+ sdk = SDK(agent="orchestrator")
313
+
314
+ # View all delegations
315
+ all_delegations = sdk.task_delegations.all()
316
+
317
+ # Query specific delegations
318
+ pending = sdk.task_delegations.where(status="pending")
319
+ completed = sdk.task_delegations.where(status="completed")
320
+ failed = sdk.task_delegations.where(status="failed")
321
+
322
+ # Get specific delegation
323
+ delegation = sdk.task_delegations.get("task-auth-001")
324
+ if delegation:
325
+ print(f"Agent: {delegation.agent}")
326
+ print(f"Status: {delegation.status}")
327
+ print(f"Result: {delegation.result}")
328
+ ```
329
+
330
+ ### Delegation Results Structure
331
+
332
+ ```python
333
+ {
334
+ "task_id": "task-auth-001",
335
+ "prompt": "Implement JWT authentication",
336
+ "agent": "coder",
337
+ "status": "completed", # or "pending", "in-progress", "failed"
338
+ "created_at": "2025-01-06T10:30:45.123Z",
339
+ "started_at": "2025-01-06T10:31:00.123Z",
340
+ "completed_at": "2025-01-06T10:45:00.123Z",
341
+ "output": "Authentication module implemented...",
342
+ "tokens_used": 8432,
343
+ "model": "claude-opus",
344
+ "cost": 0.45,
345
+ "error": null # If status is "failed"
346
+ }
347
+ ```
348
+
349
+ ---
350
+
351
+ ## Cost Optimization
352
+
353
+ ### Budget-Aware Selection
354
+
355
+ ```python
356
+ # Select model based on budget
357
+ model = select_model(
358
+ task_type=TaskType.CODE_GENERATION,
359
+ complexity=ComplexityLevel.MEDIUM,
360
+ budget_mode=BudgetMode.COST_OPTIMIZED
361
+ )
362
+ # Returns: "claude-haiku" (cheapest capable model)
363
+
364
+ # Spawn with selected model
365
+ if model == "claude-haiku":
366
+ result = spawner.spawn_claude(prompt="...", model=model)
367
+ ```
368
+
369
+ ### Token Usage Tracking
370
+
371
+ ```python
372
+ # Track tokens for cost calculation
373
+ delegations = sdk.task_delegations.all()
374
+
375
+ total_tokens = sum(d.tokens_used for d in delegations)
376
+ total_cost = sum(d.cost for d in delegations)
377
+
378
+ print(f"Total tokens: {total_tokens}")
379
+ print(f"Total cost: ${total_cost:.2f}")
380
+
381
+ # Cost by model
382
+ from collections import Counter
383
+ model_costs = Counter()
384
+ for d in delegations:
385
+ model_costs[d.model] += d.cost
386
+
387
+ for model, cost in model_costs.items():
388
+ print(f"{model}: ${cost:.2f}")
389
+ ```
390
+
391
+ ### Cost per Task Type
392
+
393
+ ```python
394
+ # Analyze spending by task type
395
+ task_type_costs = {}
396
+
397
+ for delegation in sdk.task_delegations.all():
398
+ task_type = delegation.properties.get("task_type", "unknown")
399
+ if task_type not in task_type_costs:
400
+ task_type_costs[task_type] = {
401
+ "count": 0,
402
+ "total_cost": 0,
403
+ "avg_cost": 0
404
+ }
405
+
406
+ task_type_costs[task_type]["count"] += 1
407
+ task_type_costs[task_type]["total_cost"] += delegation.cost
408
+ task_type_costs[task_type]["avg_cost"] = (
409
+ task_type_costs[task_type]["total_cost"] /
410
+ task_type_costs[task_type]["count"]
411
+ )
412
+
413
+ # Find most expensive task types
414
+ sorted_types = sorted(
415
+ task_type_costs.items(),
416
+ key=lambda x: x[1]["total_cost"],
417
+ reverse=True
418
+ )
419
+
420
+ print("Cost by task type:")
421
+ for task_type, stats in sorted_types:
422
+ print(f" {task_type}: ${stats['total_cost']:.2f} " +
423
+ f"({stats['count']} tasks, avg ${stats['avg_cost']:.2f})")
424
+ ```
425
+
426
+ ---
427
+
428
+ ## Advanced Patterns
429
+
430
+ ### Chain-of-Thought Delegation
431
+
432
+ Decompose complex tasks into subtasks:
433
+
434
+ ```python
435
+ # Step 1: Analysis (cheap/fast)
436
+ analysis_result = spawner.spawn_gemini(
437
+ prompt="Analyze the codebase structure"
438
+ # model=None - uses latest Gemini models (Gemini 3 preview)
439
+ )
440
+
441
+ # Step 2: Design (more capable)
442
+ design_result = spawner.spawn_claude(
443
+ prompt=f"""Based on this analysis:
444
+ {analysis_result.response}
445
+
446
+ Design the implementation approach.""",
447
+ model="claude-opus"
448
+ )
449
+
450
+ # Step 3: Implementation (best model for code)
451
+ impl_result = spawner.spawn_codex(
452
+ prompt=f"""Based on this design:
453
+ {design_result.response}
454
+
455
+ Implement the solution.""",
456
+ sandbox="workspace-write"
457
+ )
458
+
459
+ print(f"Final implementation: {impl_result.response}")
460
+ ```
461
+
462
+ ### Error Recovery Pattern
463
+
464
+ ```python
465
+ def spawn_with_fallback(primary_spawner_fn, fallback_spawner_fn):
466
+ """Try primary spawner, fallback on failure."""
467
+
468
+ result = primary_spawner_fn()
469
+
470
+ if result.success:
471
+ return result
472
+
473
+ print(f"Primary failed: {result.error}")
474
+ print("Attempting fallback...")
475
+
476
+ fallback_result = fallback_spawner_fn()
477
+
478
+ if fallback_result.success:
479
+ return fallback_result
480
+
481
+ print(f"Fallback also failed: {fallback_result.error}")
482
+ raise RuntimeError("All spawners failed")
483
+
484
+ # Usage
485
+ result = spawn_with_fallback(
486
+ primary_spawner_fn=lambda: spawner.spawn_codex(
487
+ prompt="Generate API",
488
+ sandbox="workspace-write"
489
+ ),
490
+ fallback_spawner_fn=lambda: spawner.spawn_claude(
491
+ prompt="Generate API",
492
+ approval="auto"
493
+ )
494
+ )
495
+ ```
496
+
497
+ ### Feedback Loop Pattern
498
+
499
+ ```python
500
+ from htmlgraph import SDK
501
+
502
+ sdk = SDK(agent="orchestrator")
503
+
504
+ def iterative_improvement(initial_prompt, improvement_cycles=3):
505
+ """Iteratively improve output through feedback."""
506
+
507
+ # Initial generation
508
+ result = spawner.spawn_claude(
509
+ prompt=initial_prompt,
510
+ approval="auto"
511
+ )
512
+
513
+ output = result.response
514
+
515
+ # Improvement cycles
516
+ for i in range(improvement_cycles):
517
+ # Get feedback
518
+ feedback = spawner.spawn_claude(
519
+ prompt=f"""Review this output and identify improvements:
520
+
521
+ {output}
522
+
523
+ Provide specific, actionable feedback.""",
524
+ approval="auto"
525
+ )
526
+
527
+ # Apply improvements
528
+ result = spawner.spawn_claude(
529
+ prompt=f"""Based on this feedback:
530
+
531
+ {feedback.response}
532
+
533
+ Improve the output:
534
+
535
+ {output}""",
536
+ approval="auto"
537
+ )
538
+
539
+ output = result.response
540
+
541
+ # Track iteration
542
+ sdk.task_delegations.create(
543
+ task_id=f"improvement-cycle-{i}",
544
+ feedback_iteration=i,
545
+ output_tokens=result.tokens_used
546
+ )
547
+
548
+ return output
549
+
550
+ improved_code = iterative_improvement(
551
+ "Generate a Python REST API",
552
+ improvement_cycles=3
553
+ )
554
+ ```
555
+
556
+ ### Multi-Agent Consensus
557
+
558
+ ```python
559
+ def get_consensus(prompt, num_agents=3):
560
+ """Get consensus from multiple agents."""
561
+
562
+ results = []
563
+
564
+ # Get multiple perspectives
565
+ results.append(("claude-opus", spawner.spawn_claude(
566
+ prompt=prompt, model="claude-opus"
567
+ )))
568
+
569
+ results.append(("gemini", spawner.spawn_gemini(
570
+ prompt=prompt # model=None uses latest Gemini models
571
+ )))
572
+
573
+ results.append(("gpt-4-turbo", spawner.spawn_codex(
574
+ prompt=prompt, model="gpt-4-turbo"
575
+ )))
576
+
577
+ # Synthesize consensus
578
+ outputs = "\n".join(
579
+ f"## {agent}\n{result.response}"
580
+ for agent, result in results
581
+ if result.success
582
+ )
583
+
584
+ consensus = spawner.spawn_claude(
585
+ prompt=f"""Review these perspectives and provide consensus:
586
+
587
+ {outputs}
588
+
589
+ Synthesize the best insights.""",
590
+ approval="auto"
591
+ )
592
+
593
+ return consensus.response
594
+
595
+ consensus_result = get_consensus(
596
+ "What's the best approach for caching?"
597
+ )
598
+ ```
599
+
600
+ ---
601
+
602
+ ## Troubleshooting
603
+
604
+ ### Agent Spawn Fails
605
+
606
+ **Problem:** `spawn_claude()` returns `success=False`
607
+
608
+ **Solutions:**
609
+ 1. Check API key is set
610
+ 2. Verify network connectivity
611
+ 3. Check rate limits
612
+ 4. Try fallback spawner
613
+
614
+ ```python
615
+ import os
616
+
617
+ # Verify API key
618
+ if not os.getenv("ANTHROPIC_API_KEY"):
619
+ print("ERROR: ANTHROPIC_API_KEY not set")
620
+
621
+ # Check connectivity
622
+ import socket
623
+ try:
624
+ socket.create_connection(("api.anthropic.com", 443), timeout=5)
625
+ except socket.error as e:
626
+ print(f"Network error: {e}")
627
+
628
+ # Try with longer timeout
629
+ result = spawner.spawn_claude(
630
+ prompt="...",
631
+ timeout=60 # Longer timeout
632
+ )
633
+ ```
634
+
635
+ ---
636
+
637
+ ### Task Delegation Not Tracked
638
+
639
+ **Problem:** Task doesn't appear in `sdk.task_delegations`
640
+
641
+ **Solutions:**
642
+ 1. Use `delegate_with_id()` for tracking
643
+ 2. Check `.htmlgraph/task-delegations/` directory exists
644
+ 3. Verify task_id is unique
645
+
646
+ ```python
647
+ # Create directory if missing
648
+ from pathlib import Path
649
+ Path(".htmlgraph/task-delegations").mkdir(exist_ok=True)
650
+
651
+ # Use proper delegation API
652
+ from htmlgraph import delegate_with_id
653
+
654
+ task_id = delegate_with_id(
655
+ prompt="...",
656
+ agent="coder",
657
+ task_id="unique-task-id" # Must be unique
658
+ )
659
+ ```
660
+
661
+ ---
662
+
663
+ ### High Costs
664
+
665
+ **Problem:** Spending too much on agent spawning
666
+
667
+ **Solutions:**
668
+ 1. Use cheaper models for simple tasks
669
+ 2. Implement task decomposition
670
+ 3. Track costs by agent/task type
671
+ 4. Use budget mode: COST_OPTIMIZED
672
+
673
+ ```python
674
+ # Use budget-aware selection
675
+ from htmlgraph.orchestration import (
676
+ select_model,
677
+ TaskType,
678
+ ComplexityLevel,
679
+ BudgetMode
680
+ )
681
+
682
+ model = select_model(
683
+ task_type=TaskType.CODE_GENERATION,
684
+ complexity=ComplexityLevel.LOW,
685
+ budget_mode=BudgetMode.COST_OPTIMIZED
686
+ )
687
+ # Returns: cheaper model for simple tasks
688
+
689
+ # Track costs
690
+ delegations = sdk.task_delegations.where(status="completed")
691
+ total_cost = sum(d.cost for d in delegations)
692
+ avg_cost = total_cost / len(delegations) if delegations else 0
693
+ print(f"Average cost per task: ${avg_cost:.2f}")
694
+ ```
695
+
696
+ ---
697
+
698
+ ## Best Practices
699
+
700
+ 1. **Always use task IDs for tracking** - Enables result retrieval
701
+ 2. **Implement fallback spawners** - Ensures reliability
702
+ 3. **Monitor token usage** - Control costs
703
+ 4. **Decompose complex tasks** - Improve accuracy
704
+ 5. **Track delegation results** - Enable learning
705
+ 6. **Use appropriate models** - Balance cost/quality
706
+ 7. **Test with cheaper models first** - Validate logic
707
+ 8. **Implement timeouts** - Prevent hanging
708
+ 9. **Cache results** - Avoid duplicate work
709
+ 10. **Monitor error rates** - Improve quality
710
+
711
+ ---
712
+
713
+ ## See Also
714
+
715
+ - [SDK API Reference](API_REFERENCE.md) - Complete SDK documentation
716
+ - [HTTP API Reference](HTTP_API.md) - REST endpoint documentation
717
+ - [Integration Guide](INTEGRATION_GUIDE.md) - Quick start examples