@tenex-chat/backend 0.9.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 (427) hide show
  1. package/README.md +194 -0
  2. package/dist/backend-wrapper.cjs +3 -0
  3. package/dist/src/index.js +331928 -0
  4. package/package.json +103 -0
  5. package/src/agents/AgentRegistry.ts +418 -0
  6. package/src/agents/AgentStorage.ts +1133 -0
  7. package/src/agents/ConfigResolver.ts +229 -0
  8. package/src/agents/agent-installer.ts +236 -0
  9. package/src/agents/agent-loader.ts +241 -0
  10. package/src/agents/constants.ts +82 -0
  11. package/src/agents/errors.ts +48 -0
  12. package/src/agents/execution/AgentExecutor.ts +561 -0
  13. package/src/agents/execution/ExecutionContextFactory.ts +112 -0
  14. package/src/agents/execution/MessageCompiler.ts +597 -0
  15. package/src/agents/execution/MessageSyncer.ts +100 -0
  16. package/src/agents/execution/PostCompletionChecker.ts +278 -0
  17. package/src/agents/execution/ProgressMonitor.ts +50 -0
  18. package/src/agents/execution/RALResolver.ts +177 -0
  19. package/src/agents/execution/SessionManager.ts +181 -0
  20. package/src/agents/execution/StreamCallbacks.ts +312 -0
  21. package/src/agents/execution/StreamExecutionHandler.ts +579 -0
  22. package/src/agents/execution/StreamSetup.ts +313 -0
  23. package/src/agents/execution/ToolEventHandlers.ts +239 -0
  24. package/src/agents/execution/ToolExecutionTracker.ts +498 -0
  25. package/src/agents/execution/ToolResultUtils.ts +97 -0
  26. package/src/agents/execution/ToolSupervisionWrapper.ts +174 -0
  27. package/src/agents/execution/constants.ts +16 -0
  28. package/src/agents/execution/index.ts +3 -0
  29. package/src/agents/execution/types.ts +96 -0
  30. package/src/agents/execution/utils.ts +26 -0
  31. package/src/agents/index.ts +4 -0
  32. package/src/agents/script-installer.ts +266 -0
  33. package/src/agents/supervision/SupervisorLLMService.ts +253 -0
  34. package/src/agents/supervision/SupervisorOrchestrator.ts +471 -0
  35. package/src/agents/supervision/heuristics/ConsecutiveToolsWithoutTodoHeuristic.ts +73 -0
  36. package/src/agents/supervision/heuristics/DelegationClaimHeuristic.ts +80 -0
  37. package/src/agents/supervision/heuristics/HeuristicRegistry.ts +114 -0
  38. package/src/agents/supervision/heuristics/PendingTodosHeuristic.ts +93 -0
  39. package/src/agents/supervision/heuristics/SilentAgentHeuristic.ts +54 -0
  40. package/src/agents/supervision/heuristics/index.ts +5 -0
  41. package/src/agents/supervision/index.ts +28 -0
  42. package/src/agents/supervision/registerHeuristics.ts +110 -0
  43. package/src/agents/supervision/supervisionHealthCheck.ts +123 -0
  44. package/src/agents/supervision/types.ts +171 -0
  45. package/src/agents/tool-names.ts +46 -0
  46. package/src/agents/tool-normalization.ts +184 -0
  47. package/src/agents/types/index.ts +2 -0
  48. package/src/agents/types/runtime.ts +74 -0
  49. package/src/agents/types/storage.ts +145 -0
  50. package/src/commands/agent/import/index.ts +6 -0
  51. package/src/commands/agent/import/openclaw-distiller.ts +57 -0
  52. package/src/commands/agent/import/openclaw-reader.ts +141 -0
  53. package/src/commands/agent/import/openclaw.ts +154 -0
  54. package/src/commands/agent/index.ts +6 -0
  55. package/src/commands/agent.ts +215 -0
  56. package/src/commands/daemon.ts +198 -0
  57. package/src/commands/doctor.ts +134 -0
  58. package/src/commands/setup/embed.ts +228 -0
  59. package/src/commands/setup/global-system-prompt.ts +223 -0
  60. package/src/commands/setup/image.ts +179 -0
  61. package/src/commands/setup/index.ts +16 -0
  62. package/src/commands/setup/interactive.ts +95 -0
  63. package/src/commands/setup/llm.ts +38 -0
  64. package/src/commands/setup/onboarding.ts +294 -0
  65. package/src/commands/setup/providers.ts +27 -0
  66. package/src/constants.ts +34 -0
  67. package/src/conversations/ConversationDiskReader.ts +148 -0
  68. package/src/conversations/ConversationRegistry.ts +728 -0
  69. package/src/conversations/ConversationStore.ts +868 -0
  70. package/src/conversations/MessageBuilder.ts +866 -0
  71. package/src/conversations/executionTime.ts +62 -0
  72. package/src/conversations/formatters/DelegationXmlFormatter.ts +64 -0
  73. package/src/conversations/formatters/ThreadedConversationFormatter.ts +303 -0
  74. package/src/conversations/formatters/index.ts +9 -0
  75. package/src/conversations/formatters/utils/MessageFormatter.ts +46 -0
  76. package/src/conversations/formatters/utils/TimestampFormatter.ts +56 -0
  77. package/src/conversations/formatters/utils/TreeBuilder.ts +131 -0
  78. package/src/conversations/formatters/utils/TreeRenderer.ts +49 -0
  79. package/src/conversations/index.ts +2 -0
  80. package/src/conversations/persistence/ToolMessageStorage.ts +143 -0
  81. package/src/conversations/search/ConversationIndexManager.ts +393 -0
  82. package/src/conversations/search/QueryParser.ts +114 -0
  83. package/src/conversations/search/SearchEngine.ts +175 -0
  84. package/src/conversations/search/SnippetExtractor.ts +345 -0
  85. package/src/conversations/search/embeddings/ConversationEmbeddingService.ts +484 -0
  86. package/src/conversations/search/embeddings/ConversationIndexingJob.ts +320 -0
  87. package/src/conversations/search/embeddings/IndexingStateManager.ts +338 -0
  88. package/src/conversations/search/embeddings/index.ts +18 -0
  89. package/src/conversations/search/index.ts +49 -0
  90. package/src/conversations/search/types.ts +124 -0
  91. package/src/conversations/services/CategoryManager.ts +160 -0
  92. package/src/conversations/services/ConversationResolver.ts +296 -0
  93. package/src/conversations/services/ConversationSummarizer.ts +234 -0
  94. package/src/conversations/services/MetadataDebounceManager.ts +188 -0
  95. package/src/conversations/services/index.ts +2 -0
  96. package/src/conversations/types.ts +148 -0
  97. package/src/conversations/utils/content-utils.ts +69 -0
  98. package/src/conversations/utils/image-placeholder.ts +281 -0
  99. package/src/conversations/utils/image-url-utils.ts +171 -0
  100. package/src/conversations/utils/multimodal-content.ts +90 -0
  101. package/src/conversations/utils/tool-result-truncator.ts +159 -0
  102. package/src/daemon/Daemon.ts +1883 -0
  103. package/src/daemon/ProjectRuntime.ts +657 -0
  104. package/src/daemon/RestartState.ts +152 -0
  105. package/src/daemon/RuntimeLifecycle.ts +268 -0
  106. package/src/daemon/SubscriptionManager.ts +305 -0
  107. package/src/daemon/UnixSocketTransport.ts +318 -0
  108. package/src/daemon/filters/SubscriptionFilterBuilder.ts +119 -0
  109. package/src/daemon/index.ts +9 -0
  110. package/src/daemon/routing/DaemonRouter.ts +491 -0
  111. package/src/daemon/types.ts +150 -0
  112. package/src/daemon/utils/routing-log.ts +76 -0
  113. package/src/daemon/utils/telemetry.ts +173 -0
  114. package/src/event-handler/agentDeletion.ts +383 -0
  115. package/src/event-handler/index.ts +749 -0
  116. package/src/event-handler/newConversation.ts +165 -0
  117. package/src/event-handler/project.ts +166 -0
  118. package/src/event-handler/reply.ts +18 -0
  119. package/src/events/NDKAgentDefinition.ts +292 -0
  120. package/src/events/NDKAgentLesson.ts +106 -0
  121. package/src/events/NDKEventMetadata.ts +34 -0
  122. package/src/events/NDKMCPTool.ts +60 -0
  123. package/src/events/NDKProjectStatus.ts +384 -0
  124. package/src/events/index.ts +4 -0
  125. package/src/index.ts +126 -0
  126. package/src/lib/agent-home.ts +334 -0
  127. package/src/lib/error-formatter.ts +200 -0
  128. package/src/lib/fs/filesystem.ts +128 -0
  129. package/src/lib/fs/index.ts +1 -0
  130. package/src/lib/json-parser.ts +30 -0
  131. package/src/lib/string.ts +15 -0
  132. package/src/lib/time.ts +74 -0
  133. package/src/llm/ChunkHandler.ts +277 -0
  134. package/src/llm/FinishHandler.ts +250 -0
  135. package/src/llm/LLMConfigEditor.ts +154 -0
  136. package/src/llm/LLMServiceFactory.ts +230 -0
  137. package/src/llm/MessageProcessor.ts +90 -0
  138. package/src/llm/RecordingState.ts +37 -0
  139. package/src/llm/StreamPublisher.ts +40 -0
  140. package/src/llm/TracingUtils.ts +77 -0
  141. package/src/llm/chunk-validators.ts +57 -0
  142. package/src/llm/constants.ts +6 -0
  143. package/src/llm/index.ts +12 -0
  144. package/src/llm/meta/MetaModelResolver.ts +352 -0
  145. package/src/llm/meta/index.ts +11 -0
  146. package/src/llm/middleware/flight-recorder.ts +188 -0
  147. package/src/llm/providers/MockProvider.ts +332 -0
  148. package/src/llm/providers/agent/ClaudeCodeProvider.ts +343 -0
  149. package/src/llm/providers/agent/ClaudeCodeToolsAdapter.ts +203 -0
  150. package/src/llm/providers/agent/CodexAppServerProvider.ts +214 -0
  151. package/src/llm/providers/agent/CodexAppServerToolsAdapter.ts +91 -0
  152. package/src/llm/providers/agent/index.ts +10 -0
  153. package/src/llm/providers/base/AgentProvider.ts +107 -0
  154. package/src/llm/providers/base/BaseProvider.ts +114 -0
  155. package/src/llm/providers/base/StandardProvider.ts +38 -0
  156. package/src/llm/providers/base/index.ts +9 -0
  157. package/src/llm/providers/index.ts +106 -0
  158. package/src/llm/providers/key-manager.ts +238 -0
  159. package/src/llm/providers/ollama-models.ts +105 -0
  160. package/src/llm/providers/openrouter-models.ts +102 -0
  161. package/src/llm/providers/provider-ids.ts +18 -0
  162. package/src/llm/providers/registry/ProviderRegistry.ts +414 -0
  163. package/src/llm/providers/registry/index.ts +7 -0
  164. package/src/llm/providers/standard/AnthropicProvider.ts +71 -0
  165. package/src/llm/providers/standard/OllamaProvider.ts +59 -0
  166. package/src/llm/providers/standard/OpenAIProvider.ts +44 -0
  167. package/src/llm/providers/standard/OpenRouterProvider.ts +103 -0
  168. package/src/llm/providers/standard/index.ts +10 -0
  169. package/src/llm/providers/types.ts +194 -0
  170. package/src/llm/providers/usage-metadata.ts +78 -0
  171. package/src/llm/service.ts +713 -0
  172. package/src/llm/types.ts +167 -0
  173. package/src/llm/utils/ConfigurationManager.ts +650 -0
  174. package/src/llm/utils/ConfigurationTester.ts +229 -0
  175. package/src/llm/utils/ModelSelector.ts +212 -0
  176. package/src/llm/utils/ProviderConfigUI.ts +177 -0
  177. package/src/llm/utils/claudeCodePromptCompiler.ts +141 -0
  178. package/src/llm/utils/codex-models.ts +53 -0
  179. package/src/llm/utils/context-window-cache.ts +30 -0
  180. package/src/llm/utils/models-dev-cache.ts +267 -0
  181. package/src/llm/utils/provider-setup.ts +50 -0
  182. package/src/llm/utils/tool-errors.ts +78 -0
  183. package/src/llm/utils/usage.ts +74 -0
  184. package/src/logging/EventRoutingLogger.ts +205 -0
  185. package/src/nostr/AgentEventDecoder.ts +357 -0
  186. package/src/nostr/AgentEventEncoder.ts +677 -0
  187. package/src/nostr/AgentProfilePublisher.ts +657 -0
  188. package/src/nostr/AgentPublisher.ts +437 -0
  189. package/src/nostr/BlossomService.ts +226 -0
  190. package/src/nostr/InterventionPublisher.ts +132 -0
  191. package/src/nostr/TagExtractor.ts +228 -0
  192. package/src/nostr/collectEvents.ts +83 -0
  193. package/src/nostr/constants.ts +38 -0
  194. package/src/nostr/encryption.ts +26 -0
  195. package/src/nostr/index.ts +31 -0
  196. package/src/nostr/keys.ts +17 -0
  197. package/src/nostr/kinds.ts +37 -0
  198. package/src/nostr/ndkClient.ts +72 -0
  199. package/src/nostr/relays.ts +43 -0
  200. package/src/nostr/trace-context.ts +39 -0
  201. package/src/nostr/types.ts +227 -0
  202. package/src/nostr/utils.ts +84 -0
  203. package/src/prompts/core/FragmentRegistry.ts +30 -0
  204. package/src/prompts/core/PromptBuilder.ts +98 -0
  205. package/src/prompts/core/index.ts +3 -0
  206. package/src/prompts/core/types.ts +13 -0
  207. package/src/prompts/fragments/00-global-system-prompt.ts +44 -0
  208. package/src/prompts/fragments/01-agent-identity.ts +69 -0
  209. package/src/prompts/fragments/02-agent-home-directory.ts +114 -0
  210. package/src/prompts/fragments/03-system-reminders-explanation.ts +14 -0
  211. package/src/prompts/fragments/04-relay-configuration.ts +38 -0
  212. package/src/prompts/fragments/05-delegation-chain.ts +45 -0
  213. package/src/prompts/fragments/06-agent-todos.ts +74 -0
  214. package/src/prompts/fragments/06-todo-usage-guidance.ts +34 -0
  215. package/src/prompts/fragments/07-meta-project-context.ts +234 -0
  216. package/src/prompts/fragments/08-active-conversations.ts +382 -0
  217. package/src/prompts/fragments/09-recent-conversations.ts +153 -0
  218. package/src/prompts/fragments/10-referenced-article.ts +21 -0
  219. package/src/prompts/fragments/11-nudges.ts +134 -0
  220. package/src/prompts/fragments/12-skills.ts +127 -0
  221. package/src/prompts/fragments/13-available-nudges.ts +122 -0
  222. package/src/prompts/fragments/15-available-agents.ts +53 -0
  223. package/src/prompts/fragments/16-stay-in-your-lane.ts +41 -0
  224. package/src/prompts/fragments/17-todo-before-delegation.ts +39 -0
  225. package/src/prompts/fragments/20-voice-mode.ts +62 -0
  226. package/src/prompts/fragments/22-scheduled-tasks.ts +175 -0
  227. package/src/prompts/fragments/24-retrieved-lessons.ts +26 -0
  228. package/src/prompts/fragments/25-rag-instructions.ts +333 -0
  229. package/src/prompts/fragments/26-mcp-resources.ts +237 -0
  230. package/src/prompts/fragments/27-memorized-reports.ts +77 -0
  231. package/src/prompts/fragments/28-agent-directed-monitoring.ts +32 -0
  232. package/src/prompts/fragments/29-rag-collections.ts +50 -0
  233. package/src/prompts/fragments/30-worktree-context.ts +98 -0
  234. package/src/prompts/fragments/31-agents-md-guidance.ts +96 -0
  235. package/src/prompts/fragments/32-process-metrics.ts +72 -0
  236. package/src/prompts/fragments/debug-mode.ts +48 -0
  237. package/src/prompts/fragments/delegation-completion.ts +44 -0
  238. package/src/prompts/fragments/index.ts +91 -0
  239. package/src/prompts/index.ts +21 -0
  240. package/src/prompts/utils/systemPromptBuilder.ts +777 -0
  241. package/src/scripts/migrate-prefix-index.ts +157 -0
  242. package/src/services/AgentDefinitionMonitor.ts +701 -0
  243. package/src/services/ConfigService.ts +723 -0
  244. package/src/services/CooldownRegistry.ts +199 -0
  245. package/src/services/LLMOperationsRegistry.ts +424 -0
  246. package/src/services/OwnerAgentListService.ts +354 -0
  247. package/src/services/PubkeyService.ts +308 -0
  248. package/src/services/agents/AgentMetadataStore.ts +72 -0
  249. package/src/services/agents/AgentResolution.ts +59 -0
  250. package/src/services/agents/EscalationService.ts +281 -0
  251. package/src/services/agents/NDKAgentDiscovery.ts +95 -0
  252. package/src/services/agents/index.ts +7 -0
  253. package/src/services/agents-md/AgentsMdService.ts +184 -0
  254. package/src/services/agents-md/SystemReminderInjector.ts +238 -0
  255. package/src/services/agents-md/index.ts +11 -0
  256. package/src/services/apns/APNsClient.ts +203 -0
  257. package/src/services/apns/APNsService.ts +358 -0
  258. package/src/services/apns/index.ts +11 -0
  259. package/src/services/apns/types.ts +80 -0
  260. package/src/services/compression/CompressionService.ts +445 -0
  261. package/src/services/compression/compression-schema.ts +28 -0
  262. package/src/services/compression/compression-types.ts +74 -0
  263. package/src/services/compression/compression-utils.ts +587 -0
  264. package/src/services/config/types.ts +394 -0
  265. package/src/services/dispatch/AgentDispatchService.ts +937 -0
  266. package/src/services/dispatch/AgentRouter.ts +181 -0
  267. package/src/services/dispatch/DelegationCompletionHandler.ts +232 -0
  268. package/src/services/embedding/EmbeddingProvider.ts +188 -0
  269. package/src/services/embedding/index.ts +5 -0
  270. package/src/services/event-context/EventContextService.ts +108 -0
  271. package/src/services/event-context/index.ts +2 -0
  272. package/src/services/heuristics/ContextBuilder.ts +106 -0
  273. package/src/services/heuristics/HeuristicEngine.ts +200 -0
  274. package/src/services/heuristics/formatters.ts +58 -0
  275. package/src/services/heuristics/index.ts +12 -0
  276. package/src/services/heuristics/rules/index.ts +25 -0
  277. package/src/services/heuristics/rules/todoBeforeDelegation.ts +69 -0
  278. package/src/services/heuristics/rules/todoReminderOnToolUse.ts +63 -0
  279. package/src/services/heuristics/types.ts +144 -0
  280. package/src/services/image/ImageGenerationService.ts +389 -0
  281. package/src/services/image/index.ts +12 -0
  282. package/src/services/intervention/InterventionService.ts +1352 -0
  283. package/src/services/intervention/index.ts +7 -0
  284. package/src/services/mcp/MCPManager.ts +683 -0
  285. package/src/services/mcp/McpNotificationDelivery.ts +139 -0
  286. package/src/services/mcp/McpSubscriptionService.ts +653 -0
  287. package/src/services/mcp/mcpInstaller.ts +130 -0
  288. package/src/services/nip46/Nip46SigningLog.ts +81 -0
  289. package/src/services/nip46/Nip46SigningService.ts +467 -0
  290. package/src/services/nip46/index.ts +4 -0
  291. package/src/services/nudge/NudgeService.ts +224 -0
  292. package/src/services/nudge/NudgeWhitelistService.ts +382 -0
  293. package/src/services/nudge/index.ts +5 -0
  294. package/src/services/nudge/types.ts +83 -0
  295. package/src/services/projects/ProjectContext.ts +672 -0
  296. package/src/services/projects/ProjectContextStore.ts +102 -0
  297. package/src/services/projects/index.ts +6 -0
  298. package/src/services/prompt-compiler/index.ts +15 -0
  299. package/src/services/prompt-compiler/prompt-compiler-service.ts +1143 -0
  300. package/src/services/pubkey-gate/PubkeyGateService.ts +93 -0
  301. package/src/services/pubkey-gate/index.ts +1 -0
  302. package/src/services/rag/EmbeddingProviderFactory.ts +292 -0
  303. package/src/services/rag/LanceDBMaintenanceService.ts +211 -0
  304. package/src/services/rag/RAGDatabaseService.ts +173 -0
  305. package/src/services/rag/RAGOperations.ts +682 -0
  306. package/src/services/rag/RAGService.ts +240 -0
  307. package/src/services/rag/RagSubscriptionService.ts +618 -0
  308. package/src/services/rag/rag-utils.ts +174 -0
  309. package/src/services/ral/PendingDelegationsRegistry.ts +168 -0
  310. package/src/services/ral/RALRegistry.ts +2782 -0
  311. package/src/services/ral/index.ts +4 -0
  312. package/src/services/ral/types.ts +292 -0
  313. package/src/services/reports/LocalReportStore.ts +380 -0
  314. package/src/services/reports/ReportEmbeddingService.ts +430 -0
  315. package/src/services/reports/ReportService.ts +440 -0
  316. package/src/services/reports/articleUtils.ts +52 -0
  317. package/src/services/reports/index.ts +7 -0
  318. package/src/services/scheduling/SchedulerService.ts +1057 -0
  319. package/src/services/scheduling/errors.ts +14 -0
  320. package/src/services/scheduling/index.ts +7 -0
  321. package/src/services/scheduling/utils.ts +77 -0
  322. package/src/services/search/SearchProviderRegistry.ts +78 -0
  323. package/src/services/search/UnifiedSearchService.ts +218 -0
  324. package/src/services/search/index.ts +47 -0
  325. package/src/services/search/projectFilter.ts +22 -0
  326. package/src/services/search/providers/ConversationSearchProvider.ts +48 -0
  327. package/src/services/search/providers/LessonSearchProvider.ts +75 -0
  328. package/src/services/search/providers/ReportSearchProvider.ts +49 -0
  329. package/src/services/search/types.ts +144 -0
  330. package/src/services/skill/SkillService.ts +482 -0
  331. package/src/services/skill/index.ts +2 -0
  332. package/src/services/skill/types.ts +70 -0
  333. package/src/services/status/OperationsStatusService.ts +276 -0
  334. package/src/services/status/ProjectStatusService.ts +522 -0
  335. package/src/services/status/index.ts +11 -0
  336. package/src/services/storage/PrefixKVStore.ts +242 -0
  337. package/src/services/storage/index.ts +1 -0
  338. package/src/services/system-reminder/SystemReminderUtils.ts +96 -0
  339. package/src/services/system-reminder/index.ts +7 -0
  340. package/src/services/trust-pubkeys/TrustPubkeyService.ts +325 -0
  341. package/src/services/trust-pubkeys/index.ts +2 -0
  342. package/src/telemetry/ConversationSpanManager.ts +111 -0
  343. package/src/telemetry/EventLoopMonitor.ts +206 -0
  344. package/src/telemetry/LLMSpanRegistry.ts +20 -0
  345. package/src/telemetry/NostrSpanProcessor.ts +89 -0
  346. package/src/telemetry/ToolCallSpanProcessor.ts +66 -0
  347. package/src/telemetry/diagnostics.ts +27 -0
  348. package/src/telemetry/setup.ts +120 -0
  349. package/src/tools/implementations/agents_discover.ts +121 -0
  350. package/src/tools/implementations/agents_hire.ts +127 -0
  351. package/src/tools/implementations/agents_list.ts +96 -0
  352. package/src/tools/implementations/agents_publish.ts +611 -0
  353. package/src/tools/implementations/agents_read.ts +173 -0
  354. package/src/tools/implementations/agents_write.ts +200 -0
  355. package/src/tools/implementations/ask.ts +411 -0
  356. package/src/tools/implementations/change_model.ts +141 -0
  357. package/src/tools/implementations/conversation_get.ts +661 -0
  358. package/src/tools/implementations/conversation_list.ts +377 -0
  359. package/src/tools/implementations/conversation_search.ts +370 -0
  360. package/src/tools/implementations/delegate.ts +327 -0
  361. package/src/tools/implementations/delegate_crossproject.ts +209 -0
  362. package/src/tools/implementations/delegate_followup.ts +300 -0
  363. package/src/tools/implementations/fs_edit.ts +162 -0
  364. package/src/tools/implementations/fs_glob.ts +182 -0
  365. package/src/tools/implementations/fs_grep.ts +513 -0
  366. package/src/tools/implementations/fs_read.ts +332 -0
  367. package/src/tools/implementations/fs_write.ts +113 -0
  368. package/src/tools/implementations/generate_image.ts +259 -0
  369. package/src/tools/implementations/home_fs.ts +515 -0
  370. package/src/tools/implementations/kill.ts +651 -0
  371. package/src/tools/implementations/learn.ts +166 -0
  372. package/src/tools/implementations/lesson-formatter.ts +38 -0
  373. package/src/tools/implementations/lesson_delete.ts +164 -0
  374. package/src/tools/implementations/lesson_get.ts +105 -0
  375. package/src/tools/implementations/lessons_list.ts +153 -0
  376. package/src/tools/implementations/mcp_resource_read.ts +161 -0
  377. package/src/tools/implementations/mcp_subscribe.ts +158 -0
  378. package/src/tools/implementations/mcp_subscription_stop.ts +85 -0
  379. package/src/tools/implementations/nostr_fetch.ts +149 -0
  380. package/src/tools/implementations/nostr_publish_as_user.ts +353 -0
  381. package/src/tools/implementations/project_list.ts +146 -0
  382. package/src/tools/implementations/rag_add_documents.ts +573 -0
  383. package/src/tools/implementations/rag_create_collection.ts +65 -0
  384. package/src/tools/implementations/rag_delete_collection.ts +68 -0
  385. package/src/tools/implementations/rag_list_collections.ts +77 -0
  386. package/src/tools/implementations/rag_query.ts +107 -0
  387. package/src/tools/implementations/rag_subscription_create.ts +105 -0
  388. package/src/tools/implementations/rag_subscription_delete.ts +80 -0
  389. package/src/tools/implementations/rag_subscription_get.ts +123 -0
  390. package/src/tools/implementations/rag_subscription_list.ts +128 -0
  391. package/src/tools/implementations/report_delete.ts +79 -0
  392. package/src/tools/implementations/report_read.ts +160 -0
  393. package/src/tools/implementations/report_write.ts +278 -0
  394. package/src/tools/implementations/reports_list.ts +77 -0
  395. package/src/tools/implementations/schedule_task.ts +104 -0
  396. package/src/tools/implementations/schedule_task_cancel.ts +62 -0
  397. package/src/tools/implementations/schedule_task_once.ts +128 -0
  398. package/src/tools/implementations/schedule_tasks_list.ts +79 -0
  399. package/src/tools/implementations/search.ts +160 -0
  400. package/src/tools/implementations/shell.ts +553 -0
  401. package/src/tools/implementations/todo.ts +260 -0
  402. package/src/tools/implementations/upload_blob.ts +381 -0
  403. package/src/tools/implementations/web_fetch.ts +153 -0
  404. package/src/tools/implementations/web_search.ts +250 -0
  405. package/src/tools/registry.ts +670 -0
  406. package/src/tools/types.ts +177 -0
  407. package/src/tools/utils.ts +256 -0
  408. package/src/types/event-ids.ts +320 -0
  409. package/src/types/index.ts +46 -0
  410. package/src/utils/agentFetcher.ts +107 -0
  411. package/src/utils/cli-error.ts +29 -0
  412. package/src/utils/conversation-id.ts +27 -0
  413. package/src/utils/conversation-utils.ts +1 -0
  414. package/src/utils/delegation-chain.ts +357 -0
  415. package/src/utils/error-handler.ts +42 -0
  416. package/src/utils/git/gitignore.ts +69 -0
  417. package/src/utils/git/index.ts +2 -0
  418. package/src/utils/git/initializeGitRepo.ts +204 -0
  419. package/src/utils/git/worktree.ts +260 -0
  420. package/src/utils/lessonFormatter.ts +70 -0
  421. package/src/utils/lessonTrust.ts +24 -0
  422. package/src/utils/lockfile.ts +123 -0
  423. package/src/utils/logger.ts +149 -0
  424. package/src/utils/nostr-entity-parser.ts +365 -0
  425. package/src/utils/process.ts +49 -0
  426. package/src/wrapper.ts +262 -0
  427. package/tsconfig.json +41 -0
@@ -0,0 +1,333 @@
1
+ import { fragmentRegistry } from "../core/FragmentRegistry";
2
+ import type { PromptFragment } from "../core/types";
3
+
4
+ /**
5
+ * RAG (Retrieval-Augmented Generation) system instructions fragment
6
+ */
7
+ export const ragInstructionsFragment: PromptFragment = {
8
+ id: "rag-instructions",
9
+ priority: 25,
10
+ template: () => `# RAG (Retrieval-Augmented Generation) System
11
+
12
+ The RAG system provides semantic search and vector-based retrieval capabilities for enhanced agent memory and context management.
13
+
14
+ ## Architecture Overview
15
+
16
+ The RAG system follows clean architecture principles with clear separation of concerns:
17
+ - **RAGService**: Facade that coordinates all operations
18
+ - **RAGDatabaseService**: Handles database lifecycle and connections
19
+ - **RAGOperations**: Implements business logic for CRUD operations
20
+ - **EmbeddingProvider**: Abstraction for embedding generation (local or cloud-based)
21
+
22
+ ## Configuration
23
+
24
+ ### Setting Up Embedding Models
25
+
26
+ Configure your preferred embedding model using the CLI:
27
+
28
+ \`\`\`bash
29
+ # Global configuration (applies to all projects)
30
+ tenex setup embed
31
+
32
+ # Project-specific configuration
33
+ tenex setup embed --project
34
+ \`\`\`
35
+
36
+ The system supports:
37
+ - **Local Transformers**: Run models directly on your machine (no API key required)
38
+ - all-MiniLM-L6-v2 (default, fast)
39
+ - all-mpnet-base-v2 (better quality)
40
+ - Custom HuggingFace models
41
+ - **OpenAI**: Cloud-based embeddings (requires API key)
42
+ - text-embedding-3-small (fast, good quality)
43
+ - text-embedding-3-large (best quality)
44
+
45
+ ## Available Tools
46
+
47
+ ### 1. rag_create_collection
48
+ Create a new vector database collection for storing embeddings.
49
+
50
+ \`\`\`typescript
51
+ rag_create_collection({
52
+ name: "project_knowledge", // Alphanumeric with underscores only
53
+ schema: { // Optional custom schema
54
+ category: "string"
55
+ }
56
+ })
57
+ \`\`\`
58
+
59
+ ### 2. rag_add_documents
60
+ Add documents to a collection with automatic embedding generation.
61
+
62
+ \`\`\`typescript
63
+ rag_add_documents({
64
+ collection: "project_knowledge",
65
+ documents: [
66
+ {
67
+ content: "Document text content",
68
+ metadata: { type: "documentation", tags: ["api", "rest"] },
69
+ source: "api-docs.md",
70
+ id: "doc_001" // Optional custom ID
71
+ },
72
+ {
73
+ file_path: "./docs/README.md", // Can read from files
74
+ metadata: { type: "readme" }
75
+ }
76
+ ]
77
+ })
78
+ \`\`\`
79
+
80
+ ### 3. rag_query
81
+ Perform semantic search on a collection.
82
+
83
+ \`\`\`typescript
84
+ rag_query({
85
+ collection: "project_knowledge",
86
+ query_text: "How does authentication work?",
87
+ top_k: 5, // Number of results (1-100)
88
+ include_metadata: true // Include document metadata
89
+ })
90
+ \`\`\`
91
+
92
+ ### 4. rag_delete_collection
93
+ Remove a collection and all its documents.
94
+
95
+ \`\`\`typescript
96
+ rag_delete_collection({
97
+ name: "project_knowledge",
98
+ confirm: true // Required safety flag
99
+ })
100
+ \`\`\`
101
+
102
+ ### 5. rag_list_collections
103
+ List all available collections with optional statistics.
104
+
105
+ \`\`\`typescript
106
+ rag_list_collections({
107
+ include_stats: true // Include document counts per collection
108
+ })
109
+ \`\`\`
110
+
111
+ ## Best Practices
112
+
113
+ ### Collection Design
114
+ - **Single Purpose**: Create focused collections for specific domains
115
+ - **Naming Convention**: Use descriptive lowercase names with underscores
116
+ - ✅ \`agent_memory\`, \`code_snippets\`, \`user_preferences\`
117
+ - ❌ \`MyCollection\`, \`data-store\`, \`collection#1\`
118
+
119
+ ### Document Management
120
+ - **Metadata Strategy**: Always include relevant metadata for filtering
121
+ \`\`\`typescript
122
+ metadata: {
123
+ type: "code" | "documentation" | "conversation",
124
+ language?: string,
125
+ timestamp?: number,
126
+ tags?: string[],
127
+ source?: string
128
+ }
129
+ \`\`\`
130
+ - **Content Size**: Keep individual documents under 1MB for optimal performance
131
+ - **Batch Operations**: Add multiple documents in a single call for efficiency
132
+
133
+ ### Query Optimization
134
+ - **Natural Language**: Use conversational queries for best results
135
+ - ✅ "How to implement user authentication with JWT tokens"
136
+ - ❌ "auth jwt impl func"
137
+ - **Result Limits**: Use appropriate \`top_k\` values (5-10 for most cases)
138
+ - **Relevance Scores**: Results include scores (0-1) indicating similarity
139
+
140
+ ### Error Handling
141
+ All tools use standardized error responses:
142
+ \`\`\`json
143
+ {
144
+ "success": false,
145
+ "error": "Descriptive error message",
146
+ "toolName": "rag_query"
147
+ }
148
+ \`\`\`
149
+
150
+ ## Use Cases
151
+
152
+ ### 1. Agent Self-Reflection
153
+ Build persistent memory across conversations:
154
+
155
+ \`\`\`typescript
156
+ // Store insights and decisions
157
+ rag_create_collection({ name: "agent_insights" })
158
+
159
+ rag_add_documents({
160
+ collection: "agent_insights",
161
+ documents: [{
162
+ content: "User prefers TypeScript over JavaScript for all new projects",
163
+ metadata: {
164
+ type: "preference",
165
+ confidence: 0.9,
166
+ learned_from: "conversation_123"
167
+ }
168
+ }]
169
+ })
170
+
171
+ // Later, retrieve relevant context
172
+ rag_query({
173
+ collection: "agent_insights",
174
+ query_text: "What are the user's programming language preferences?"
175
+ })
176
+ \`\`\`
177
+
178
+ ### 2. Project Knowledge Base
179
+ Index project documentation and code:
180
+
181
+ \`\`\`typescript
182
+ rag_create_collection({ name: "project_docs" })
183
+
184
+ // Index all markdown files
185
+ rag_add_documents({
186
+ collection: "project_docs",
187
+ documents: [
188
+ { file_path: "README.md" },
189
+ { file_path: "docs/api.md" },
190
+ { file_path: "docs/architecture.md" }
191
+ ]
192
+ })
193
+
194
+ // Query for specific information
195
+ rag_query({
196
+ collection: "project_docs",
197
+ query_text: "API authentication methods"
198
+ })
199
+ \`\`\`
200
+
201
+ ### 3. Enhanced Lesson Learning
202
+ Combine with lesson_learn for semantic retrieval:
203
+
204
+ \`\`\`typescript
205
+ // After learning a lesson
206
+ lesson_learn({
207
+ title: "Async error handling",
208
+ lesson: "Always use try-catch with async/await"
209
+ })
210
+
211
+ // Store in RAG for semantic search
212
+ rag_add_documents({
213
+ collection: "lessons",
214
+ documents: [{
215
+ content: lesson.detailed || lesson.lesson,
216
+ metadata: {
217
+ title: lesson.title,
218
+ category: lesson.category,
219
+ hashtags: lesson.hashtags
220
+ }
221
+ }]
222
+ })
223
+
224
+ // Find related lessons semantically
225
+ rag_query({
226
+ collection: "lessons",
227
+ query_text: "How to handle promise rejections"
228
+ })
229
+ \`\`\`
230
+
231
+ ### 4. Code Pattern Recognition
232
+ Store and retrieve code patterns:
233
+
234
+ \`\`\`typescript
235
+ rag_create_collection({ name: "code_patterns" })
236
+
237
+ rag_add_documents({
238
+ collection: "code_patterns",
239
+ documents: [{
240
+ content: "const useAuth = () => { const [user, setUser] = useState(null); ... }",
241
+ metadata: {
242
+ pattern: "React Hook",
243
+ language: "TypeScript",
244
+ framework: "React",
245
+ complexity: "medium"
246
+ }
247
+ }]
248
+ })
249
+
250
+ rag_query({
251
+ collection: "code_patterns",
252
+ query_text: "authentication hook implementation"
253
+ })
254
+ \`\`\`
255
+
256
+ ## Integration with Other Tools
257
+
258
+ ### With grep
259
+ Index search results for faster future retrieval:
260
+ \`\`\`typescript
261
+ // After grep finds relevant files
262
+ rag_add_documents({
263
+ collection: "indexed_code",
264
+ documents: searchResults.map(file => ({
265
+ file_path: file,
266
+ metadata: { type: "code" }
267
+ }))
268
+ })
269
+ \`\`\`
270
+
271
+ ### With delegate
272
+ Share collections between agents:
273
+ \`\`\`typescript
274
+ delegate({
275
+ task: "Analyze the project documentation",
276
+ tools: ["rag_query"],
277
+ context: "Use collection 'project_docs' for analysis"
278
+ })
279
+ \`\`\`
280
+
281
+ ### With report_write
282
+ Store reports for easy retrieval:
283
+ \`\`\`typescript
284
+ report_write({ title: "Performance Analysis", content: "..." })
285
+
286
+ rag_add_documents({
287
+ collection: "reports",
288
+ documents: [{
289
+ content: report.content,
290
+ metadata: {
291
+ title: report.title,
292
+ type: "report",
293
+ created_at: Date.now()
294
+ }
295
+ }]
296
+ })
297
+ \`\`\`
298
+
299
+ ## Performance Considerations
300
+
301
+ 1. **Embedding Generation**: First-time model loading may take a few seconds
302
+ 2. **Batch Size**: Documents are processed in batches of 100 for optimal performance
303
+ 3. **Vector Dimensions**: Varies by model (384 for MiniLM, 768 for mpnet)
304
+ 4. **Storage**: LanceDB uses efficient columnar storage with compression
305
+ 5. **Query Speed**: Sub-second for collections under 100K documents
306
+
307
+ ## Troubleshooting
308
+
309
+ ### Common Issues
310
+
311
+ 1. **Collection Already Exists**
312
+ - Solution: Use unique names or delete existing collection first
313
+
314
+ 2. **Empty Query Results**
315
+ - Check if documents were successfully added
316
+ - Verify collection name is correct
317
+ - Try broader query terms
318
+
319
+ 3. **Slow Embedding Generation**
320
+ - First run downloads model (one-time)
321
+ - Consider using smaller model for speed
322
+ - Use cloud-based embeddings for better performance
323
+
324
+ 4. **Configuration Not Found**
325
+ - Run \`tenex setup embed\` to configure
326
+ - Check \`.tenex/embed.json\` exists
327
+ - Verify environment variables for API keys
328
+
329
+ Remember: RAG empowers agents with persistent, searchable knowledge that enhances capabilities across conversations!`,
330
+ };
331
+
332
+ // Register the fragment
333
+ fragmentRegistry.register(ragInstructionsFragment);
@@ -0,0 +1,237 @@
1
+ import type { Resource, ResourceTemplate } from "@modelcontextprotocol/sdk/types.js";
2
+ import type { MCPManager } from "@/services/mcp/MCPManager";
3
+ import { logger } from "@/utils/logger";
4
+ import { fragmentRegistry } from "../core/FragmentRegistry";
5
+ import type { PromptFragment } from "../core/types";
6
+
7
+ // Use official SDK types
8
+ type MCPResource = Resource;
9
+ type MCPResourceTemplate = ResourceTemplate;
10
+
11
+ interface ResourcesPerServer {
12
+ serverName: string;
13
+ resources: MCPResource[];
14
+ templates: MCPResourceTemplate[];
15
+ }
16
+
17
+ interface McpResourcesFragmentArgs {
18
+ agentPubkey: string;
19
+ mcpEnabled: boolean;
20
+ resourcesPerServer: ResourcesPerServer[];
21
+ }
22
+
23
+ /**
24
+ * Extract unique MCP server names from agent's tool list.
25
+ * MCP tools are namespaced as: mcp__serverName__toolName
26
+ */
27
+ export function extractAgentMcpServers(agentTools: string[]): string[] {
28
+ const servers = new Set<string>();
29
+ for (const tool of agentTools) {
30
+ if (tool.startsWith("mcp__")) {
31
+ const parts = tool.split("__");
32
+ if (parts.length >= 3) {
33
+ servers.add(parts[1]); // parts[1] is server name
34
+ }
35
+ }
36
+ }
37
+ return Array.from(servers);
38
+ }
39
+
40
+ /**
41
+ * Fetch resources from MCP servers that the agent has access to.
42
+ * Agent has access to a server if it has any tools from that server (mcp__serverName__*).
43
+ */
44
+ export async function fetchAgentMcpResources(
45
+ agentTools: string[],
46
+ mcpManager: MCPManager
47
+ ): Promise<ResourcesPerServer[]> {
48
+ const agentMcpServers = extractAgentMcpServers(agentTools);
49
+
50
+ if (agentMcpServers.length === 0) {
51
+ return [];
52
+ }
53
+
54
+ const runningServers = mcpManager.getRunningServers();
55
+
56
+ // Only show resources from servers the agent has tools for AND are running
57
+ const agentRunningServers = agentMcpServers.filter(s => runningServers.includes(s));
58
+
59
+ if (agentRunningServers.length === 0) {
60
+ return [];
61
+ }
62
+
63
+ const resourcesPerServer = await Promise.all(
64
+ agentRunningServers.map(async (serverName: string) => {
65
+ try {
66
+ const [resources, templates] = await Promise.all([
67
+ mcpManager.listResources(serverName),
68
+ mcpManager.listResourceTemplates(serverName),
69
+ ]);
70
+ logger.debug(
71
+ `Fetched ${resources.length} resources and ${templates.length} templates from '${serverName}'`
72
+ );
73
+ return { serverName, resources, templates };
74
+ } catch (error) {
75
+ logger.warn(`Failed to fetch MCP resources from '${serverName}':`, error);
76
+ return { serverName, resources: [], templates: [] };
77
+ }
78
+ })
79
+ );
80
+
81
+ return resourcesPerServer;
82
+ }
83
+
84
+ /**
85
+ * Format a single resource for display
86
+ */
87
+ function formatResource(
88
+ resource: { uri: string; name: string; description?: string; mimeType?: string },
89
+ serverName: string
90
+ ): string {
91
+ const lines: string[] = [];
92
+ lines.push(`- **${resource.name}** (\`${resource.uri}\`)`);
93
+ if (resource.description) {
94
+ lines.push(` ${resource.description}`);
95
+ }
96
+ lines.push(` Server: ${serverName}`);
97
+ if (resource.mimeType) {
98
+ lines.push(` Type: ${resource.mimeType}`);
99
+ }
100
+ return lines.join("\n");
101
+ }
102
+
103
+ /**
104
+ * Format a resource template for display
105
+ */
106
+ function formatTemplate(
107
+ template: { uriTemplate: string; name: string; description?: string; mimeType?: string },
108
+ serverName: string
109
+ ): string {
110
+ const lines: string[] = [];
111
+ lines.push(`- **${template.name}** (\`${template.uriTemplate}\`) *[Template]*`);
112
+ if (template.description) {
113
+ lines.push(` ${template.description}`);
114
+ }
115
+ lines.push(` Server: ${serverName}`);
116
+
117
+ // Extract parameter names from template
118
+ const params = template.uriTemplate.match(/\{([^}]+)\}/g);
119
+ if (params) {
120
+ const paramNames = params.map((p) => p.slice(1, -1)).join(", ");
121
+ lines.push(` **Required parameters:** ${paramNames}`);
122
+ lines.push(" **Note:** Expand this template with actual values before subscribing");
123
+ }
124
+
125
+ if (template.mimeType) {
126
+ lines.push(` Type: ${template.mimeType}`);
127
+ }
128
+ return lines.join("\n");
129
+ }
130
+
131
+ /**
132
+ * MCP Resources fragment - shows available resources for RAG subscription
133
+ */
134
+ export const mcpResourcesFragment: PromptFragment<McpResourcesFragmentArgs> = {
135
+ id: "mcp-resources",
136
+ priority: 26,
137
+
138
+ template: (args: McpResourcesFragmentArgs): string => {
139
+ if (!args.mcpEnabled || args.resourcesPerServer.length === 0) {
140
+ return ""; // Don't show if MCP is disabled or no resources
141
+ }
142
+
143
+ // Check if there are any actual resources or templates across all servers
144
+ const hasAnyResources = args.resourcesPerServer.some(
145
+ (server) => server.resources.length > 0 || server.templates.length > 0
146
+ );
147
+
148
+ if (!hasAnyResources) {
149
+ return ""; // Don't show fragment if no resources available
150
+ }
151
+
152
+ const sections: string[] = [];
153
+ const serverNames = args.resourcesPerServer.map((s) => s.serverName);
154
+ sections.push("# Available MCP Resources for RAG Subscription\n");
155
+ sections.push(
156
+ `You have access to MCP resources from ${serverNames.length} server${serverNames.length === 1 ? "" : "s"}: ${serverNames.join(", ")}\n`
157
+ );
158
+
159
+ let totalResources = 0;
160
+ let totalTemplates = 0;
161
+
162
+ for (const serverData of args.resourcesPerServer) {
163
+ const { serverName, resources, templates } = serverData;
164
+
165
+ if (resources.length === 0 && templates.length === 0) {
166
+ continue; // Skip servers with no resources
167
+ }
168
+
169
+ sections.push(`## Server: ${serverName}\n`);
170
+
171
+ // Direct resources
172
+ if (resources.length > 0) {
173
+ sections.push("### Direct Resources (ready to subscribe)\n");
174
+ for (const resource of resources) {
175
+ sections.push(formatResource(resource, serverName));
176
+ sections.push("");
177
+ }
178
+ totalResources += resources.length;
179
+ }
180
+
181
+ // Resource templates
182
+ if (templates.length > 0) {
183
+ sections.push("### Resource Templates (require parameter expansion)\n");
184
+ for (const template of templates) {
185
+ sections.push(formatTemplate(template, serverName));
186
+ sections.push("");
187
+ }
188
+ totalTemplates += templates.length;
189
+ }
190
+
191
+ sections.push("---\n");
192
+ }
193
+
194
+ // Add usage instructions
195
+ sections.push("## How to Use MCP Resources\n");
196
+
197
+ sections.push("### On-Demand Reading\n");
198
+ sections.push("Use the `mcp_resource_read` tool to fetch resource content immediately:\n");
199
+ sections.push('- **serverName**: The server name shown above (e.g., "nostr-provider")');
200
+ sections.push("- **resourceUri**: The exact URI shown in parentheses");
201
+ sections.push("- **description**: Why you're reading this resource\n");
202
+ sections.push("For templates, provide `templateParams` to expand `{placeholders}`.\n");
203
+
204
+ sections.push("### Persistent Subscriptions\n");
205
+ sections.push("Use the `rag_subscription_create` tool to stream updates into RAG collections:\n");
206
+ sections.push('- **subscriptionId**: Unique ID for your subscription (e.g., "global-feed")');
207
+ sections.push('- **mcpServerId**: The server name shown above (e.g., "nostr-provider")');
208
+ sections.push("- **resourceUri**: The exact URI (templates must be expanded first)");
209
+ sections.push("- **ragCollection**: RAG collection name");
210
+ sections.push("- **description**: What this subscription does\n");
211
+
212
+ sections.push(
213
+ `**Summary:** ${totalResources} direct resource${totalResources === 1 ? "" : "s"}, ${totalTemplates} template${totalTemplates === 1 ? "" : "s"} available`
214
+ );
215
+
216
+ return sections.join("\n");
217
+ },
218
+
219
+ validateArgs: (args: unknown): args is McpResourcesFragmentArgs => {
220
+ return (
221
+ typeof args === "object" &&
222
+ args !== null &&
223
+ "agentPubkey" in args &&
224
+ "mcpEnabled" in args &&
225
+ "resourcesPerServer" in args &&
226
+ typeof (args as McpResourcesFragmentArgs).agentPubkey === "string" &&
227
+ typeof (args as McpResourcesFragmentArgs).mcpEnabled === "boolean" &&
228
+ Array.isArray((args as McpResourcesFragmentArgs).resourcesPerServer)
229
+ );
230
+ },
231
+
232
+ expectedArgs:
233
+ "{ agentPubkey: string, mcpEnabled: boolean, resourcesPerServer: ResourcesPerServer[] }",
234
+ };
235
+
236
+ // Auto-register the fragment
237
+ fragmentRegistry.register(mcpResourcesFragment);
@@ -0,0 +1,77 @@
1
+ import type { ReportInfo } from "@/services/reports/ReportService";
2
+ import { fragmentRegistry } from "../core/FragmentRegistry";
3
+ import type { PromptFragment } from "../core/types";
4
+
5
+ /**
6
+ * Memorized reports fragment - injects reports marked with memorize=true or memorize_team=true
7
+ * into the agent's system prompt for persistent context.
8
+ *
9
+ * - memorize=true: Report is only injected into the authoring agent's system prompt
10
+ * - memorize_team=true: Report is injected into ALL agents' system prompts in the project
11
+ */
12
+ interface MemorizedReportsArgs {
13
+ reports: ReportInfo[];
14
+ }
15
+
16
+ export const memorizedReportsFragment: PromptFragment<MemorizedReportsArgs> = {
17
+ id: "memorized-reports",
18
+ priority: 27, // After RAG instructions, before worktree context
19
+ template: ({ reports }) => {
20
+ if (!reports || reports.length === 0) {
21
+ return ""; // No memorized reports
22
+ }
23
+
24
+ // Separate team-wide reports from agent-specific reports
25
+ const teamReports = reports.filter((r) => r.isMemorizedTeam);
26
+ const agentReports = reports.filter((r) => !r.isMemorizedTeam);
27
+
28
+ const parts: string[] = [];
29
+ parts.push("## Memorized Knowledge\n");
30
+
31
+ // Add team-wide reports first (if any)
32
+ if (teamReports.length > 0) {
33
+ parts.push("### Team-Wide Knowledge\n");
34
+ parts.push("*The following knowledge is shared across ALL agents in this project:*\n");
35
+
36
+ for (const report of teamReports) {
37
+ parts.push(`#### ${report.title || report.slug}`);
38
+ if (report.summary) {
39
+ parts.push(`*${report.summary}*\n`);
40
+ }
41
+ if (report.content) {
42
+ parts.push(report.content);
43
+ }
44
+ parts.push(""); // Empty line between reports
45
+ }
46
+ }
47
+
48
+ // Add agent-specific reports (if any)
49
+ if (agentReports.length > 0) {
50
+ if (teamReports.length > 0) {
51
+ parts.push("### Agent-Specific Knowledge\n");
52
+ parts.push("*The following knowledge is specific to your role:*\n");
53
+ } else {
54
+ parts.push(
55
+ "The following reports have been memorized and represent persistent knowledge for your role:\n"
56
+ );
57
+ }
58
+
59
+ for (const report of agentReports) {
60
+ const heading = teamReports.length > 0 ? "####" : "###";
61
+ parts.push(`${heading} ${report.title || report.slug}`);
62
+ if (report.summary) {
63
+ parts.push(`*${report.summary}*\n`);
64
+ }
65
+ if (report.content) {
66
+ parts.push(report.content);
67
+ }
68
+ parts.push(""); // Empty line between reports
69
+ }
70
+ }
71
+
72
+ return parts.join("\n");
73
+ },
74
+ };
75
+
76
+ // Register the fragment
77
+ fragmentRegistry.register(memorizedReportsFragment);
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Agent-Directed Monitoring Fragment
3
+ *
4
+ * Provides guidance on how agents can monitor delegated work using existing tools.
5
+ * Agents control when and how often to check on delegated tasks.
6
+ */
7
+
8
+ import type { PromptFragment } from "../core/types";
9
+
10
+ const MONITORING_GUIDANCE = `## Monitoring Delegated Work
11
+
12
+ When you delegate tasks to other agents, you can monitor their progress using existing tools:
13
+
14
+ 1. **Check Progress**: Use \`conversation_get\` with the delegation conversation ID. Optionally pass a \`prompt\` parameter to have the tool summarize the delegatee's progress.
15
+
16
+ 2. **Wait Between Checks**: Use \`shell()\` with \`sleep <seconds>\` to wait between progress checks. Choose intervals based on task complexity:
17
+ - Quick tasks (< 2 min expected): Check every 30 seconds
18
+ - Medium tasks (2-10 min): Check every 1-2 minutes
19
+ - Long tasks (> 10 min): Check every 3-5 minutes
20
+
21
+ 3. **When to Monitor**: You decide whether active monitoring is needed based on:
22
+ - Task criticality and deadline pressure
23
+ - Whether you need intermediate results
24
+ - The delegatee's reliability for the task type
25
+
26
+ Most delegations complete and return results automatically. Active monitoring is optional and primarily useful for long-running tasks where you want progress visibility.`;
27
+
28
+ export const agentDirectedMonitoringFragment: PromptFragment = {
29
+ id: "agent-directed-monitoring",
30
+ priority: 28, // After memorized reports (27), before worktree context (30)
31
+ template: () => MONITORING_GUIDANCE,
32
+ };