polyrob 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (745) hide show
  1. agents/README.md +453 -0
  2. agents/__init__.py +164 -0
  3. agents/base_agent.py +743 -0
  4. agents/personality/character.py +119 -0
  5. agents/personality/character_manager.py +309 -0
  6. agents/personality/characters/rob.character.json +56 -0
  7. agents/personality/characters/trump.character.json +63 -0
  8. agents/personality/persona_render.py +78 -0
  9. agents/personality/persona_resolver.py +115 -0
  10. agents/prompt/__init__.py +58 -0
  11. agents/prompt/base_prompt.py +92 -0
  12. agents/prompt/system.py +417 -0
  13. agents/task/README_PATH_MANAGEMENT.md +141 -0
  14. agents/task/__init__.py +162 -0
  15. agents/task/agent/__init__.py +70 -0
  16. agents/task/agent/agent_state.py +408 -0
  17. agents/task/agent/async_delegation.py +274 -0
  18. agents/task/agent/autonomy_state.py +275 -0
  19. agents/task/agent/conversation.py +75 -0
  20. agents/task/agent/core/__init__.py +6 -0
  21. agents/task/agent/core/aux_metering.py +61 -0
  22. agents/task/agent/core/background_review.py +157 -0
  23. agents/task/agent/core/construction.py +1179 -0
  24. agents/task/agent/core/conversational_exit.py +49 -0
  25. agents/task/agent/core/correspondent_gate.py +227 -0
  26. agents/task/agent/core/curator.py +246 -0
  27. agents/task/agent/core/episodic_digest.py +103 -0
  28. agents/task/agent/core/error_recovery.py +480 -0
  29. agents/task/agent/core/history_io.py +257 -0
  30. agents/task/agent/core/llm_provisioning.py +287 -0
  31. agents/task/agent/core/llm_runner.py +547 -0
  32. agents/task/agent/core/logging_io.py +276 -0
  33. agents/task/agent/core/loop_detection.py +262 -0
  34. agents/task/agent/core/memory_prefetch.py +325 -0
  35. agents/task/agent/core/memory_writer.py +667 -0
  36. agents/task/agent/core/model_introspection.py +82 -0
  37. agents/task/agent/core/model_swap.py +177 -0
  38. agents/task/agent/core/next_action_internal.py +1331 -0
  39. agents/task/agent/core/output_validation.py +303 -0
  40. agents/task/agent/core/project_context.py +272 -0
  41. agents/task/agent/core/resources.py +93 -0
  42. agents/task/agent/core/result_processing.py +389 -0
  43. agents/task/agent/core/run_loop.py +661 -0
  44. agents/task/agent/core/safety_lifecycle.py +228 -0
  45. agents/task/agent/core/secret_guard.py +293 -0
  46. agents/task/agent/core/self_wake.py +280 -0
  47. agents/task/agent/core/session_metadata.py +104 -0
  48. agents/task/agent/core/step.py +781 -0
  49. agents/task/agent/core/step_execution.py +398 -0
  50. agents/task/agent/core/step_telemetry.py +222 -0
  51. agents/task/agent/core/test_aux_metering.py +50 -0
  52. agents/task/agent/core/test_billing_failover.py +68 -0
  53. agents/task/agent/core/test_fatal_error_classifier.py +38 -0
  54. agents/task/agent/core/test_judge_validation.py +275 -0
  55. agents/task/agent/core/test_model_swap.py +190 -0
  56. agents/task/agent/core/test_reflection_offload.py +54 -0
  57. agents/task/agent/core/turn_input.py +8 -0
  58. agents/task/agent/core/untrusted_wrap.py +103 -0
  59. agents/task/agent/core/user_ingress.py +228 -0
  60. agents/task/agent/hitl_manager.py +396 -0
  61. agents/task/agent/log_sanitize.py +36 -0
  62. agents/task/agent/message_manager/config.py +97 -0
  63. agents/task/agent/message_manager/service.py +758 -0
  64. agents/task/agent/message_manager/tests.py +305 -0
  65. agents/task/agent/message_manager/tool_call_builder.py +539 -0
  66. agents/task/agent/message_manager/tool_message_repair.py +364 -0
  67. agents/task/agent/message_manager/views.py +143 -0
  68. agents/task/agent/messages/__init__.py +8 -0
  69. agents/task/agent/messages/builders.py +309 -0
  70. agents/task/agent/messages/compactor.py +611 -0
  71. agents/task/agent/messages/context_references.py +271 -0
  72. agents/task/agent/messages/filters.py +333 -0
  73. agents/task/agent/messages/guidance.py +328 -0
  74. agents/task/agent/messages/persistence.py +448 -0
  75. agents/task/agent/messages/retrieval.py +506 -0
  76. agents/task/agent/messages/sqlite_persistence.py +85 -0
  77. agents/task/agent/messages/test_compaction_upgrade.py +349 -0
  78. agents/task/agent/messages/test_persistence_subdir_fix.py +28 -0
  79. agents/task/agent/messages/test_sqlite_persistence.py +54 -0
  80. agents/task/agent/messages/token_counter.py +532 -0
  81. agents/task/agent/orchestrator.py +776 -0
  82. agents/task/agent/profile_manager.py +105 -0
  83. agents/task/agent/profile_registry.py +173 -0
  84. agents/task/agent/prompts.py +1090 -0
  85. agents/task/agent/scenario_registry.py +226 -0
  86. agents/task/agent/service.py +509 -0
  87. agents/task/agent/session.py +984 -0
  88. agents/task/agent/skill_discovery.py +110 -0
  89. agents/task/agent/skill_frontmatter.py +94 -0
  90. agents/task/agent/skill_manager.py +1201 -0
  91. agents/task/agent/skill_store.py +627 -0
  92. agents/task/agent/skill_validation.py +56 -0
  93. agents/task/agent/skill_writer.py +492 -0
  94. agents/task/agent/sub_agent_manager.py +1137 -0
  95. agents/task/agent/test_session_disk_recovery.py +34 -0
  96. agents/task/agent/tests.py +513 -0
  97. agents/task/agent/tool_call_tracker.py +511 -0
  98. agents/task/agent/views.py +469 -0
  99. agents/task/config.py +432 -0
  100. agents/task/constants.py +1384 -0
  101. agents/task/flag_defaults.py +63 -0
  102. agents/task/goals/__init__.py +1 -0
  103. agents/task/goals/autonomy_marker.py +28 -0
  104. agents/task/goals/board.py +690 -0
  105. agents/task/goals/completion_judge.py +247 -0
  106. agents/task/goals/context.py +62 -0
  107. agents/task/goals/dispatcher.py +848 -0
  108. agents/task/goals/escalation.py +102 -0
  109. agents/task/goals/planner.py +114 -0
  110. agents/task/logging_config.py +155 -0
  111. agents/task/path.py +991 -0
  112. agents/task/robust_parse_config.py +400 -0
  113. agents/task/runtime/__init__.py +0 -0
  114. agents/task/runtime/run_as_session.py +130 -0
  115. agents/task/runtime_safety.py +308 -0
  116. agents/task/session/__init__.py +5 -0
  117. agents/task/session/browser_pool.py +130 -0
  118. agents/task/session/cleanup.py +612 -0
  119. agents/task/session/execution.py +397 -0
  120. agents/task/session/feed.py +200 -0
  121. agents/task/session/hitl_ingress.py +201 -0
  122. agents/task/session/hooks.py +83 -0
  123. agents/task/session/multi_agent.py +243 -0
  124. agents/task/session/workspace.py +91 -0
  125. agents/task/session_registry.py +91 -0
  126. agents/task/session_route.py +35 -0
  127. agents/task/sqlite_session_registry.py +261 -0
  128. agents/task/surface_config.py +185 -0
  129. agents/task/telemetry/__init__.py +58 -0
  130. agents/task/telemetry/event_log.py +180 -0
  131. agents/task/telemetry/formatters.py +642 -0
  132. agents/task/telemetry/manager.py +571 -0
  133. agents/task/telemetry/memory_events.py +66 -0
  134. agents/task/telemetry/self_events.py +53 -0
  135. agents/task/telemetry/sequence.py +160 -0
  136. agents/task/telemetry/service.py +1265 -0
  137. agents/task/telemetry/views.py +882 -0
  138. agents/task/templates.py +98 -0
  139. agents/task/test_aux_chain.py +151 -0
  140. agents/task/test_aux_router.py +41 -0
  141. agents/task/tests/test_parse_robustness.py +170 -0
  142. agents/task/tool_defaults.py +110 -0
  143. agents/task/utils.py +762 -0
  144. agents/task/utils_json.py +768 -0
  145. agents/task/utils_webview.py +86 -0
  146. agents/task/workspace_context.py +229 -0
  147. agents/task_agent_lite.py +2398 -0
  148. api/README.md +683 -0
  149. api/TASK_API_DOCS.md +151 -0
  150. api/__init__.py +0 -0
  151. api/a2a/__init__.py +37 -0
  152. api/a2a/agent_card.py +337 -0
  153. api/a2a/client.py +657 -0
  154. api/a2a/endpoints.py +375 -0
  155. api/a2a/models.py +268 -0
  156. api/a2a/streaming.py +419 -0
  157. api/a2a/task_handler.py +929 -0
  158. api/admin_endpoints.py +1584 -0
  159. api/app.py +923 -0
  160. api/auth_constants.py +28 -0
  161. api/auth_endpoints.py +402 -0
  162. api/auth_state.py +36 -0
  163. api/chat_via_task.py +42 -0
  164. api/conversation_manager.py +231 -0
  165. api/dependencies.py +186 -0
  166. api/eip8004_endpoints.py +452 -0
  167. api/hyperliquid_models.py +174 -0
  168. api/hyperliquid_routes.py +450 -0
  169. api/interfaces.py +207 -0
  170. api/jwt_middleware.py +83 -0
  171. api/kb/__init__.py +1 -0
  172. api/kb/endpoints.py +314 -0
  173. api/mcp_models.py +279 -0
  174. api/mcp_routes.py +438 -0
  175. api/middleware.py +526 -0
  176. api/models.py +176 -0
  177. api/openai_compat/__init__.py +0 -0
  178. api/openai_compat/model_map.py +25 -0
  179. api/openai_compat/models.py +59 -0
  180. api/openai_compat/router.py +140 -0
  181. api/payment_endpoints.py +444 -0
  182. api/payment_verification.py +138 -0
  183. api/polymarket_models.py +155 -0
  184. api/polymarket_routes.py +501 -0
  185. api/pricing_endpoints.py +89 -0
  186. api/session_routing.py +54 -0
  187. api/skill_endpoints.py +453 -0
  188. api/task_http_api.py +1856 -0
  189. api/webhooks.py +52 -0
  190. api/x402_endpoints.py +280 -0
  191. avatar/README.md +44 -0
  192. avatar/__init__.py +1 -0
  193. avatar/config/rob.json +7 -0
  194. avatar/mindprint.js +395 -0
  195. avatar/renders/rob.meta.json +20 -0
  196. avatar/renders/rob.png +0 -0
  197. avatar/studio.html +373 -0
  198. avatar/webview/avatar-live.js +44 -0
  199. cli/README.md +89 -0
  200. cli/__init__.py +0 -0
  201. cli/cli_surface.py +67 -0
  202. cli/commands/__init__.py +0 -0
  203. cli/commands/_bootstrap.py +49 -0
  204. cli/commands/_errors.py +53 -0
  205. cli/commands/chat.py +973 -0
  206. cli/commands/config.py +100 -0
  207. cli/commands/dashboard.py +103 -0
  208. cli/commands/doctor.py +222 -0
  209. cli/commands/email.py +174 -0
  210. cli/commands/gateway.py +346 -0
  211. cli/commands/goals.py +509 -0
  212. cli/commands/init.py +276 -0
  213. cli/commands/journey.py +30 -0
  214. cli/commands/kb.py +280 -0
  215. cli/commands/model.py +107 -0
  216. cli/commands/owner.py +431 -0
  217. cli/commands/pfp.py +232 -0
  218. cli/commands/run.py +414 -0
  219. cli/commands/serve.py +41 -0
  220. cli/commands/session.py +684 -0
  221. cli/commands/skill_install.py +786 -0
  222. cli/commands/skills.py +128 -0
  223. cli/commands/subagents.py +100 -0
  224. cli/commands/surface.py +81 -0
  225. cli/commands/telegram.py +185 -0
  226. cli/commands/todos.py +209 -0
  227. cli/commands/tools.py +102 -0
  228. cli/commands/update.py +316 -0
  229. cli/commands/whatsapp.py +175 -0
  230. cli/config_store.py +276 -0
  231. cli/gitignore.py +43 -0
  232. cli/inventory.py +46 -0
  233. cli/keys.py +101 -0
  234. cli/persona.py +17 -0
  235. cli/polyrob.py +137 -0
  236. cli/ui/__init__.py +64 -0
  237. cli/ui/activity.py +141 -0
  238. cli/ui/app.py +538 -0
  239. cli/ui/banner.py +233 -0
  240. cli/ui/blocks.py +534 -0
  241. cli/ui/bootstrap_notice.py +47 -0
  242. cli/ui/commands/__init__.py +41 -0
  243. cli/ui/commands/h_cron.py +64 -0
  244. cli/ui/commands/h_journey.py +164 -0
  245. cli/ui/commands/h_kb.py +121 -0
  246. cli/ui/commands/h_learn.py +100 -0
  247. cli/ui/commands/h_mcp.py +215 -0
  248. cli/ui/commands/h_self.py +113 -0
  249. cli/ui/commands/h_skills.py +314 -0
  250. cli/ui/commands/handlers.py +1672 -0
  251. cli/ui/commands/registry.py +426 -0
  252. cli/ui/dialog.py +425 -0
  253. cli/ui/event_registry.py +110 -0
  254. cli/ui/event_specs.py +45 -0
  255. cli/ui/events.py +433 -0
  256. cli/ui/identity.py +15 -0
  257. cli/ui/lifecycle.py +159 -0
  258. cli/ui/live_hooks.py +43 -0
  259. cli/ui/model_selector.py +532 -0
  260. cli/ui/persistent_loop.py +181 -0
  261. cli/ui/pick.py +113 -0
  262. cli/ui/plain_renderer.py +351 -0
  263. cli/ui/renderer.py +384 -0
  264. cli/ui/rich_renderer.py +533 -0
  265. cli/ui/secrets.py +115 -0
  266. cli/ui/state.py +376 -0
  267. cli/ui/statusbar.py +231 -0
  268. cli/ui/streaming.py +254 -0
  269. cli/ui/terminal_render.py +105 -0
  270. cli/ui/theme.py +132 -0
  271. cli/update/__init__.py +6 -0
  272. cli/update/context.py +121 -0
  273. cli/update/detect.py +176 -0
  274. cli/update/engine.py +95 -0
  275. cli/update/migrate_guarded.py +55 -0
  276. cli/update/process_guard.py +215 -0
  277. cli/update/runners.py +78 -0
  278. cli/update/snapshot.py +270 -0
  279. cli/update/versions.py +205 -0
  280. core/README.md +377 -0
  281. core/__init__.py +174 -0
  282. core/assets.py +87 -0
  283. core/async_bridge.py +76 -0
  284. core/autonomy_runtime.py +259 -0
  285. core/base_component.py +302 -0
  286. core/bootstrap.py +681 -0
  287. core/bot.py +310 -0
  288. core/config.py +833 -0
  289. core/constants.py +126 -0
  290. core/container.py +462 -0
  291. core/db_manifest.py +101 -0
  292. core/embedding.py +57 -0
  293. core/env.py +39 -0
  294. core/exceptions.py +287 -0
  295. core/flags.py +144 -0
  296. core/flags_catalog.py +345 -0
  297. core/home_migration.py +62 -0
  298. core/identity.py +118 -0
  299. core/initialization.py +1004 -0
  300. core/instance.py +537 -0
  301. core/interactive_gate.py +96 -0
  302. core/logging.py +436 -0
  303. core/owner_doc_writer.py +176 -0
  304. core/pairing.py +193 -0
  305. core/path_safety.py +20 -0
  306. core/paths.py +27 -0
  307. core/payment_config.py +21 -0
  308. core/permissions.py +322 -0
  309. core/runtime_config.py +96 -0
  310. core/runtime_paths.py +135 -0
  311. core/seams.py +35 -0
  312. core/secret_scan.py +25 -0
  313. core/secret_scrub.py +71 -0
  314. core/secrets.py +35 -0
  315. core/security_logging_filter.py +148 -0
  316. core/self_context_writer.py +333 -0
  317. core/self_evolution.py +294 -0
  318. core/session_context.py +47 -0
  319. core/sqlite_util.py +59 -0
  320. core/surfaces/__init__.py +16 -0
  321. core/surfaces/access.py +118 -0
  322. core/surfaces/binding.py +88 -0
  323. core/surfaces/bootstrap.py +78 -0
  324. core/surfaces/circuit.py +168 -0
  325. core/surfaces/continuity.py +77 -0
  326. core/surfaces/correspondents.py +228 -0
  327. core/surfaces/dispatcher.py +216 -0
  328. core/surfaces/envelopes.py +75 -0
  329. core/surfaces/gc.py +30 -0
  330. core/surfaces/idempotency.py +57 -0
  331. core/surfaces/inbound_webhook.py +124 -0
  332. core/surfaces/media.py +32 -0
  333. core/surfaces/message_router.py +91 -0
  334. core/surfaces/outbound_allowlist.py +80 -0
  335. core/surfaces/outbound_dispatcher.py +110 -0
  336. core/surfaces/outbound_mirror.py +37 -0
  337. core/surfaces/outbound_queue.py +107 -0
  338. core/surfaces/outbound_target.py +12 -0
  339. core/surfaces/owner_admin.py +29 -0
  340. core/surfaces/proactive.py +78 -0
  341. core/surfaces/progress.py +108 -0
  342. core/surfaces/rate_bucket.py +21 -0
  343. core/surfaces/registry.py +51 -0
  344. core/surfaces/rendering.py +53 -0
  345. core/surfaces/send_policy.py +14 -0
  346. core/surfaces/serialize.py +24 -0
  347. core/surfaces/session_chat_registry.py +112 -0
  348. core/surfaces/session_policy.py +60 -0
  349. core/surfaces/surface.py +288 -0
  350. core/surfaces/transcription.py +88 -0
  351. core/surfaces/voice_echo.py +26 -0
  352. core/surfaces/voice_guard.py +23 -0
  353. core/tickers.py +174 -0
  354. core/tool_catalog.py +192 -0
  355. core/version.py +75 -0
  356. core/wallet/__init__.py +5 -0
  357. core/wallet/agent_wallet.py +59 -0
  358. core/wallet/audit_sink.py +61 -0
  359. core/wallet/config.py +70 -0
  360. core/wallet/factory.py +87 -0
  361. core/wallet/policy.py +104 -0
  362. core/wallet/signer.py +51 -0
  363. cron/README.md +65 -0
  364. cron/__init__.py +0 -0
  365. cron/delivery.py +277 -0
  366. cron/digest.py +124 -0
  367. cron/jobs.py +207 -0
  368. cron/runner.py +297 -0
  369. cron/schedule.py +194 -0
  370. cron/scheduler.py +201 -0
  371. cron/service.py +57 -0
  372. cron/wake_gate.py +223 -0
  373. data/__init__.py +1 -0
  374. data/prompts/autov2_prompts.json +87 -0
  375. data/prompts/skills/browser-automation/SKILL.md +43 -0
  376. data/prompts/skills/coding-workflow/SKILL.md +36 -0
  377. data/prompts/skills/crypto-trading-safety/SKILL.md +53 -0
  378. data/prompts/skills/document-writing/SKILL.md +33 -0
  379. data/prompts/skills/email-comms/SKILL.md +33 -0
  380. data/prompts/skills/file-data-ops/SKILL.md +35 -0
  381. data/prompts/skills/hyperliquid-account-review/SKILL.md +48 -0
  382. data/prompts/skills/hyperliquid-market-data/SKILL.md +52 -0
  383. data/prompts/skills/hyperliquid-trading/SKILL.md +59 -0
  384. data/prompts/skills/lead-research/SKILL.md +86 -0
  385. data/prompts/skills/market-research-brief/SKILL.md +104 -0
  386. data/prompts/skills/person-analyzer/SKILL.md +124 -0
  387. data/prompts/skills/polymarket-market-research/SKILL.md +54 -0
  388. data/prompts/skills/polymarket-portfolio-review/SKILL.md +50 -0
  389. data/prompts/skills/polymarket-trading/SKILL.md +55 -0
  390. data/prompts/skills/presentation-creator/SKILL.md +36 -0
  391. data/prompts/skills/project-analyzer/SKILL.md +169 -0
  392. data/prompts/skills/rules.json +268 -0
  393. data/prompts/skills/secret-handling/SKILL.md +20 -0
  394. data/prompts/skills/skill-authoring/SKILL.md +31 -0
  395. data/prompts/skills/skill-security-review/SKILL.md +27 -0
  396. data/prompts/skills/social-discovery/SKILL.md +57 -0
  397. data/prompts/skills/task-planning/SKILL.md +33 -0
  398. data/prompts/skills/web-research/SKILL.md +39 -0
  399. data/prompts/skills/web-scraping/SKILL.md +73 -0
  400. data/prompts/skills/x-engagement/SKILL.md +69 -0
  401. data/prompts/system_prompts.json +4 -0
  402. data/subscription_channels.json +5 -0
  403. modules/README.md +503 -0
  404. modules/__init__.py +124 -0
  405. modules/auth/__init__.py +13 -0
  406. modules/auth/api_key_manager.py +157 -0
  407. modules/auth/identity_mapper.py +380 -0
  408. modules/auth/siwe_auth.py +273 -0
  409. modules/auth/tier_manager.py +173 -0
  410. modules/base_module.py +190 -0
  411. modules/credits/__init__.py +29 -0
  412. modules/credits/balance_manager.py +237 -0
  413. modules/credits/cost_utils.py +129 -0
  414. modules/credits/pricing.py +139 -0
  415. modules/credits/unified_ledger.py +148 -0
  416. modules/credits/usage_meter.py +310 -0
  417. modules/credits/usage_tracker.py +674 -0
  418. modules/database/__init__.py +33 -0
  419. modules/database/audit_log.py +322 -0
  420. modules/database/auth_tables.py +276 -0
  421. modules/database/connection.py +644 -0
  422. modules/database/connection_pool.py +305 -0
  423. modules/database/conversation_contexts.py +446 -0
  424. modules/database/database_manager.py +237 -0
  425. modules/database/hyperliquid.py +375 -0
  426. modules/database/polymarket.py +574 -0
  427. modules/database/user_mcp_servers.py +728 -0
  428. modules/database/user_profiles.py +562 -0
  429. modules/database/utils.py +107 -0
  430. modules/database/x402_tables.py +92 -0
  431. modules/eip8004/README.md +1069 -0
  432. modules/eip8004/__init__.py +65 -0
  433. modules/eip8004/contracts.py +498 -0
  434. modules/eip8004/models.py +271 -0
  435. modules/eip8004/registration.py +148 -0
  436. modules/eip8004/reputation.py +367 -0
  437. modules/eip8004/validation.py +277 -0
  438. modules/llm/__init__.py +97 -0
  439. modules/llm/adapters.py +963 -0
  440. modules/llm/anthropic_client.py +831 -0
  441. modules/llm/available_models.py +106 -0
  442. modules/llm/brain_scrubber.py +137 -0
  443. modules/llm/cache_hints.py +162 -0
  444. modules/llm/deepseek_client.py +562 -0
  445. modules/llm/gemini_client.py +1367 -0
  446. modules/llm/llm_client.py +1139 -0
  447. modules/llm/llm_client_registry.py +188 -0
  448. modules/llm/llm_factory.py +237 -0
  449. modules/llm/llm_manager.py +1036 -0
  450. modules/llm/messages.py +374 -0
  451. modules/llm/model_registry.py +1935 -0
  452. modules/llm/nvidia_client.py +125 -0
  453. modules/llm/openai_client.py +800 -0
  454. modules/llm/openrouter_client.py +969 -0
  455. modules/llm/profiles.py +178 -0
  456. modules/llm/test_anthropic_cache_capture.py +35 -0
  457. modules/llm/test_cached_pricing_derivation.py +24 -0
  458. modules/llm/think_scrubber.py +444 -0
  459. modules/llm/token_counter.py +268 -0
  460. modules/memory/__init__.py +35 -0
  461. modules/memory/backend_factory.py +83 -0
  462. modules/memory/cache_manager.py +186 -0
  463. modules/memory/episodic.py +108 -0
  464. modules/memory/local_vector_memory_provider.py +552 -0
  465. modules/memory/memory_manager.py +225 -0
  466. modules/memory/models.py +312 -0
  467. modules/memory/provider.py +210 -0
  468. modules/memory/registry.py +205 -0
  469. modules/memory/sqlite_memory_provider.py +767 -0
  470. modules/memory/task/__init__.py +52 -0
  471. modules/memory/task/compaction_manager.py +157 -0
  472. modules/memory/task/context_retriever.py +809 -0
  473. modules/memory/task/hierarchical_memory.py +1002 -0
  474. modules/memory/task/lexical_retriever.py +71 -0
  475. modules/memory/task/null_context_manager.py +213 -0
  476. modules/memory/task/phase_manager.py +625 -0
  477. modules/memory/task/reflection_service.py +157 -0
  478. modules/memory/task/semantic_retriever.py +218 -0
  479. modules/memory/task/task_context_manager.py +1165 -0
  480. modules/memory/task/test_forgetting_engages.py +24 -0
  481. modules/memory/task/test_reflection_llm.py +39 -0
  482. modules/memory/task/test_threat_scan.py +53 -0
  483. modules/memory/task/threat_scan.py +90 -0
  484. modules/memory/test_sqlite_memory_provider.py +106 -0
  485. modules/memory/user_profile_manager.py +527 -0
  486. modules/payments/__init__.py +11 -0
  487. modules/payments/deposit_monitor.py +478 -0
  488. modules/payments/price_oracle.py +70 -0
  489. modules/payments/treasury_sweeper.py +401 -0
  490. modules/payments/wallet_generator.py +145 -0
  491. modules/pfp/__init__.py +1 -0
  492. modules/pfp/config.py +92 -0
  493. modules/pfp/mesh.py +565 -0
  494. modules/pfp/push.py +69 -0
  495. modules/pfp/renderer.py +85 -0
  496. modules/pfp/store.py +82 -0
  497. modules/skills/__init__.py +1 -0
  498. modules/skills/skill_usage.py +248 -0
  499. modules/transcription/__init__.py +24 -0
  500. modules/transcription/base.py +20 -0
  501. modules/transcription/faster_whisper_transcriber.py +55 -0
  502. modules/x402/README.md +249 -0
  503. modules/x402/__init__.py +22 -0
  504. modules/x402/invoicing.py +416 -0
  505. modules/x402/middleware.py +364 -0
  506. modules/x402/settlement_watcher.py +145 -0
  507. modules/x402/x402_integration.py +344 -0
  508. polyrob-0.5.0.dist-info/METADATA +482 -0
  509. polyrob-0.5.0.dist-info/RECORD +745 -0
  510. polyrob-0.5.0.dist-info/WHEEL +5 -0
  511. polyrob-0.5.0.dist-info/entry_points.txt +2 -0
  512. polyrob-0.5.0.dist-info/licenses/LICENSE +21 -0
  513. polyrob-0.5.0.dist-info/top_level.txt +12 -0
  514. surfaces/README.md +70 -0
  515. surfaces/__init__.py +0 -0
  516. surfaces/email/__init__.py +0 -0
  517. surfaces/email/dedup.py +44 -0
  518. surfaces/email/harness.py +187 -0
  519. surfaces/email/inbound.py +159 -0
  520. surfaces/email/seed.py +60 -0
  521. surfaces/email/surface.py +105 -0
  522. surfaces/telegram/__init__.py +0 -0
  523. surfaces/telegram/dedup.py +83 -0
  524. surfaces/telegram/harness.py +886 -0
  525. surfaces/telegram/inbound.py +145 -0
  526. surfaces/telegram/interactive_tools.py +49 -0
  527. surfaces/telegram/markdown.py +347 -0
  528. surfaces/telegram/rate_limit.py +167 -0
  529. surfaces/telegram/surface.py +187 -0
  530. surfaces/telegram/voice.py +52 -0
  531. surfaces/whatsapp/__init__.py +0 -0
  532. surfaces/whatsapp/client.py +51 -0
  533. surfaces/whatsapp/harness.py +62 -0
  534. surfaces/whatsapp/inbound.py +132 -0
  535. surfaces/whatsapp/surface.py +64 -0
  536. surfaces/whatsapp/window.py +34 -0
  537. tools/README.md +578 -0
  538. tools/__init__.py +424 -0
  539. tools/alchemy/__init__.py +5 -0
  540. tools/alchemy/alchemy_tool.py +389 -0
  541. tools/anysite/__init__.py +17 -0
  542. tools/anysite/client.py +88 -0
  543. tools/anysite/tool.py +89 -0
  544. tools/base_tool.py +468 -0
  545. tools/browser/__init__.py +22 -0
  546. tools/browser/actions.py +118 -0
  547. tools/browser/browser.py +1457 -0
  548. tools/browser/browser_manager.py +690 -0
  549. tools/browser/context.py +1748 -0
  550. tools/browser/playwright_utils.py +137 -0
  551. tools/browser/views.py +56 -0
  552. tools/code_exec/SANDBOX_SECURITY.md +144 -0
  553. tools/code_exec/__init__.py +178 -0
  554. tools/code_exec/backend.py +73 -0
  555. tools/code_exec/backends/__init__.py +1 -0
  556. tools/code_exec/backends/docker.py +779 -0
  557. tools/code_exec/backends/local_subprocess.py +154 -0
  558. tools/code_exec/env_policy.py +45 -0
  559. tools/code_exec/result.py +42 -0
  560. tools/code_exec/sandbox_guard.py +59 -0
  561. tools/code_exec/tool.py +227 -0
  562. tools/coding/__init__.py +50 -0
  563. tools/coding/edit.py +107 -0
  564. tools/coding/search.py +113 -0
  565. tools/coding/tool.py +353 -0
  566. tools/collabland/__init__.py +5 -0
  567. tools/collabland/collabland_tool.py +471 -0
  568. tools/controller/__init__.py +0 -0
  569. tools/controller/_helpers.py +165 -0
  570. tools/controller/action_registration.py +1765 -0
  571. tools/controller/approval.py +244 -0
  572. tools/controller/approval_interactive.py +90 -0
  573. tools/controller/delegation.py +195 -0
  574. tools/controller/execution.py +797 -0
  575. tools/controller/execution_context.py +141 -0
  576. tools/controller/hooks.py +135 -0
  577. tools/controller/introspection.py +344 -0
  578. tools/controller/mcp_registrar.py +190 -0
  579. tools/controller/message_send.py +31 -0
  580. tools/controller/registry/__init__.py +4 -0
  581. tools/controller/registry/schema_generators.py +395 -0
  582. tools/controller/registry/schema_sanitizer.py +406 -0
  583. tools/controller/registry/service.py +1266 -0
  584. tools/controller/registry/views.py +151 -0
  585. tools/controller/service.py +409 -0
  586. tools/controller/tool_management.py +334 -0
  587. tools/controller/types.py +28 -0
  588. tools/controller/views.py +450 -0
  589. tools/cronjob_tools.py +166 -0
  590. tools/crypto_trade_gate.py +59 -0
  591. tools/descriptors.py +452 -0
  592. tools/dom/__init__.py +0 -0
  593. tools/dom/history_tree_processor/service.py +244 -0
  594. tools/dom/history_tree_processor/view.py +99 -0
  595. tools/dom/service.py +471 -0
  596. tools/dom/views.py +346 -0
  597. tools/email_tool.py +403 -0
  598. tools/exceptions.py +169 -0
  599. tools/filesystem.py +1038 -0
  600. tools/filesystem_docproc.py +331 -0
  601. tools/filesystem_pdf.py +755 -0
  602. tools/git/__init__.py +42 -0
  603. tools/git/tool.py +258 -0
  604. tools/github/__init__.py +33 -0
  605. tools/github/client.py +94 -0
  606. tools/github/tool.py +237 -0
  607. tools/goal_tools.py +309 -0
  608. tools/hyperliquid/__init__.py +56 -0
  609. tools/hyperliquid/models.py +233 -0
  610. tools/hyperliquid/service.py +1680 -0
  611. tools/knowledge_ingest.py +950 -0
  612. tools/mcp/README.md +535 -0
  613. tools/mcp/__init__.py +52 -0
  614. tools/mcp/catalog.py +115 -0
  615. tools/mcp/config.py +337 -0
  616. tools/mcp/mcp_tool.py +1415 -0
  617. tools/mcp/param_coercion.py +289 -0
  618. tools/mcp/protocol.py +1520 -0
  619. tools/mcp/rate_limit.py +50 -0
  620. tools/mcp/security.py +424 -0
  621. tools/mcp/self_install.py +111 -0
  622. tools/mcp/server_manager.py +829 -0
  623. tools/mcp/subscriptions.py +72 -0
  624. tools/mcp/user_mcp_service.py +899 -0
  625. tools/mcp/validation_tracker.py +89 -0
  626. tools/mcp/views.py +346 -0
  627. tools/oauth/__init__.py +17 -0
  628. tools/oauth/manager.py +75 -0
  629. tools/oauth/provider.py +69 -0
  630. tools/oauth/providers/__init__.py +1 -0
  631. tools/oauth/providers/generic_oauth2.py +96 -0
  632. tools/perplexity_tool.py +280 -0
  633. tools/polymarket/__init__.py +41 -0
  634. tools/polymarket/clob_adapter.py +76 -0
  635. tools/polymarket/models.py +182 -0
  636. tools/polymarket/service.py +2082 -0
  637. tools/self_env/__init__.py +61 -0
  638. tools/self_env/tool.py +274 -0
  639. tools/shell/__init__.py +80 -0
  640. tools/shell/backend_pool.py +118 -0
  641. tools/shell/discipline.py +62 -0
  642. tools/shell/executor.py +157 -0
  643. tools/shell/loopback_allow.py +87 -0
  644. tools/shell/process_registry.py +113 -0
  645. tools/shell/process_tool.py +131 -0
  646. tools/shell/state.py +129 -0
  647. tools/shell/tool.py +151 -0
  648. tools/task_tool.py +637 -0
  649. tools/twitter_tool.py +2086 -0
  650. tools/user_directory.py +179 -0
  651. tools/web_fetch/__init__.py +3 -0
  652. tools/web_fetch/fetcher.py +144 -0
  653. tools/web_fetch/render.py +44 -0
  654. tools/web_fetch/tool.py +60 -0
  655. tools/x402/__init__.py +60 -0
  656. tools/x402/client.py +47 -0
  657. tools/x402/invoice_tool.py +143 -0
  658. tools/x402/real_client.py +250 -0
  659. tools/x402/service.py +131 -0
  660. utils/README.md +498 -0
  661. utils/__init__.py +46 -0
  662. utils/auth_utils.py +114 -0
  663. utils/bounded_collections.py +162 -0
  664. utils/circuit_breaker.py +389 -0
  665. utils/gif_utils.py +435 -0
  666. utils/markdown_utils.py +291 -0
  667. utils/message_utils.py +147 -0
  668. utils/metrics.py +36 -0
  669. utils/path_validator.py +227 -0
  670. utils/rate_limit_manager.py +399 -0
  671. utils/result_size.py +296 -0
  672. utils/time_utils.py +206 -0
  673. utils/user_utils.py +188 -0
  674. webview/README.md +111 -0
  675. webview/RENAME_AND_ALIGN_HANDOFF.md +200 -0
  676. webview/__init__.py +8 -0
  677. webview/activity.py +636 -0
  678. webview/owner_auth.py +108 -0
  679. webview/pages.py +448 -0
  680. webview/repair_sessions.py +399 -0
  681. webview/server.py +4323 -0
  682. webview/server_launcher.py +112 -0
  683. webview/static/css/activity.css +89 -0
  684. webview/static/css/chat.css +1772 -0
  685. webview/static/css/components.css +1190 -0
  686. webview/static/css/config-panel.css +651 -0
  687. webview/static/css/pages/admin.css +766 -0
  688. webview/static/css/pages/profile.css +231 -0
  689. webview/static/css/pages/settings.css +297 -0
  690. webview/static/css/pages/signin.css +316 -0
  691. webview/static/css/style.css +4250 -0
  692. webview/static/css/variables.css +147 -0
  693. webview/static/css/workspace-fullwidth-fix.css +109 -0
  694. webview/static/img/favicon.ico +0 -0
  695. webview/static/js/activity.js +394 -0
  696. webview/static/js/admin/activity.js +186 -0
  697. webview/static/js/admin/dashboard.js +163 -0
  698. webview/static/js/admin/user_detail.js +400 -0
  699. webview/static/js/admin/users.js +174 -0
  700. webview/static/js/admin/utils.js +214 -0
  701. webview/static/js/chat.js +3178 -0
  702. webview/static/js/config-panel.js +522 -0
  703. webview/static/js/constants.js +20 -0
  704. webview/static/js/error-handler.js +226 -0
  705. webview/static/js/ethers.min.js +1 -0
  706. webview/static/js/event-filter.js +137 -0
  707. webview/static/js/event-store.js +351 -0
  708. webview/static/js/file-attachments.js +374 -0
  709. webview/static/js/file-loader.js +163 -0
  710. webview/static/js/index.js +103 -0
  711. webview/static/js/performance-utils.js +196 -0
  712. webview/static/js/profile.js +396 -0
  713. webview/static/js/screenshot.js +386 -0
  714. webview/static/js/session.js +1527 -0
  715. webview/static/js/settings.js +1288 -0
  716. webview/static/js/sidebar-data.js +766 -0
  717. webview/static/js/sidebar-toggle.js +296 -0
  718. webview/static/js/socket.io.min.js +7 -0
  719. webview/static/js/stats.js +355 -0
  720. webview/static/js/ui-utils.js +420 -0
  721. webview/static/js/workspace.js +966 -0
  722. webview/stats_service.py +613 -0
  723. webview/templates/__init__.py +1 -0
  724. webview/templates/__pycache__/__init__.cpython-311.pyc +0 -0
  725. webview/templates/activity.html +36 -0
  726. webview/templates/admin/activity.html +122 -0
  727. webview/templates/admin/dashboard.html +112 -0
  728. webview/templates/admin/user_detail.html +228 -0
  729. webview/templates/admin/users.html +105 -0
  730. webview/templates/autonomy.html +60 -0
  731. webview/templates/error.html +133 -0
  732. webview/templates/finance.html +90 -0
  733. webview/templates/identity.html +73 -0
  734. webview/templates/index.html +42 -0
  735. webview/templates/layout.html +125 -0
  736. webview/templates/memory.html +59 -0
  737. webview/templates/owner_login.html +15 -0
  738. webview/templates/profile.html +121 -0
  739. webview/templates/session.html +312 -0
  740. webview/templates/settings.html +534 -0
  741. webview/templates/sidebar.html +112 -0
  742. webview/templates/signin.html +213 -0
  743. webview/templates/status.html +14 -0
  744. webview/templates/system.html +45 -0
  745. webview/webgate.py +196 -0
@@ -0,0 +1,1672 @@
1
+ """handlers.py — the slash-command handler functions + the default registry.
2
+
3
+ Each ``_h_*`` handler takes one ``CommandContext`` and renders through the
4
+ renderer (Rich table/panel or plain ``print_block``). ``build_default_registry``
5
+ wires them; ``default_registry`` is the process-wide singleton. Re-exported via
6
+ the package ``__init__`` (D6 — the god-file split).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ from pathlib import Path
13
+ from typing import Any, Dict, List, Optional
14
+
15
+ from cli.ui.commands.registry import (
16
+ Command,
17
+ CommandContext,
18
+ CommandRegistry,
19
+ ReplExit,
20
+ )
21
+
22
+
23
+ def _h_help(ctx: CommandContext) -> None:
24
+ lines = ["Commands:"]
25
+ reg = ctx.registry or default_registry()
26
+ for cmd in reg.commands():
27
+ invoke = f"/{cmd.name}"
28
+ if cmd.usage:
29
+ invoke = f"{invoke} {cmd.usage}"
30
+ alias_str = ""
31
+ if cmd.aliases:
32
+ alias_str = " (" + ", ".join(f"/{a}" for a in cmd.aliases) + ")"
33
+ lines.append(f" {invoke:<28} {cmd.help}{alias_str}")
34
+ ctx.emit("\n".join(lines), title="help")
35
+
36
+
37
+ def _h_exit(ctx: CommandContext) -> None:
38
+ raise ReplExit()
39
+
40
+
41
+ def _h_status(ctx: CommandContext) -> None:
42
+ """Live session status: model, tokens, cost estimate, ctx %, steps, compactions."""
43
+ state = ctx.state
44
+ # Refresh ctx metrics from the live message_manager when available.
45
+ agent = ctx.agent
46
+ if state is not None and agent is not None:
47
+ try:
48
+ state.poll(agent)
49
+ except Exception:
50
+ pass
51
+
52
+ console = ctx.console()
53
+ if console is not None and state is not None:
54
+ from rich.table import Table
55
+
56
+ table = Table(title="session status", title_justify="left", show_header=False)
57
+ table.add_column("k", style="bold")
58
+ table.add_column("v")
59
+ table.add_row("session", ctx.session_id[:16] or "—")
60
+ table.add_row("model", f"{state.model or '—'} ({state.provider or '—'})")
61
+ table.add_row("status", state.status or "—")
62
+ table.add_row("step", str(state.step))
63
+ table.add_row(
64
+ "tokens",
65
+ f"{state.tokens_in} in · {state.tokens_out} out · {state.tokens_total} total",
66
+ )
67
+ table.add_row("cost (est)", f"${state.cost_estimate_total:.4f}")
68
+ if state.ctx_percent:
69
+ table.add_row(
70
+ "context",
71
+ f"{state.ctx_percent:.0f}% ({state.ctx_tokens}/{state.ctx_max})",
72
+ )
73
+ table.add_row("compactions", str(state.compactions))
74
+ table.add_row("elapsed", f"{state.elapsed():.1f}s")
75
+ console.print(table)
76
+ return
77
+
78
+ # Plain fallback.
79
+ if state is None:
80
+ ctx.emit("(no session state)")
81
+ return
82
+ lines = [
83
+ f"session: {ctx.session_id[:16] or '—'}",
84
+ f"model: {state.model or '—'} ({state.provider or '—'})",
85
+ f"status: {state.status}",
86
+ f"step: {state.step}",
87
+ f"tokens: {state.tokens_in} in / {state.tokens_out} out / {state.tokens_total} total",
88
+ f"cost (est): ${state.cost_estimate_total:.4f}",
89
+ ]
90
+ if state.ctx_percent:
91
+ lines.append(
92
+ f"context: {state.ctx_percent:.0f}% ({state.ctx_tokens}/{state.ctx_max})"
93
+ )
94
+ lines += [
95
+ f"compactions: {state.compactions}",
96
+ f"elapsed: {state.elapsed():.1f}s",
97
+ ]
98
+ ctx.emit("\n".join(lines), title="status")
99
+
100
+
101
+ async def _h_usage(ctx: CommandContext) -> None:
102
+ """Authoritative usage breakdown (DB) with a labelled SessionState fallback.
103
+
104
+ CLI sessions skip credit checks, so the ``usage_records`` table is usually
105
+ empty for them — in that case we fall back to the llm_usage-file aggregation
106
+ already accumulated into ``SessionState`` and say which source we show.
107
+ """
108
+ breakdown = await _fetch_breakdown(ctx)
109
+
110
+ if breakdown and breakdown.get("by_type"):
111
+ _render_usage_breakdown(ctx, breakdown)
112
+ _maybe_note_estimate_drift(ctx, breakdown)
113
+ return
114
+
115
+ # Fallback: SessionState estimate (llm_usage files).
116
+ _render_usage_estimate(ctx)
117
+
118
+
119
+ async def _fetch_breakdown(ctx: CommandContext) -> Optional[Dict[str, Any]]:
120
+ """Pull ``get_session_breakdown`` via the orchestrator's usage_tracker."""
121
+ tracker = None
122
+ orchestrator = ctx.orchestrator
123
+ if orchestrator is None and ctx.task_agent is not None and ctx.session_id:
124
+ try:
125
+ orchestrator = ctx.task_agent.get_orchestrator(ctx.session_id)
126
+ except Exception:
127
+ orchestrator = None
128
+ if orchestrator is not None:
129
+ tracker = getattr(orchestrator, "usage_tracker", None)
130
+ if tracker is None:
131
+ return None
132
+ try:
133
+ return await tracker.get_session_breakdown(ctx.session_id)
134
+ except Exception:
135
+ return None
136
+
137
+
138
+ def _render_usage_breakdown(ctx: CommandContext, breakdown: Dict[str, Any]) -> None:
139
+ console = ctx.console()
140
+ by_type = breakdown.get("by_type", [])
141
+ if console is not None:
142
+ from rich.table import Table
143
+
144
+ table = Table(title="usage (DB — authoritative)", title_justify="left")
145
+ for col in ("type", "calls", "in", "out", "cache", "credits", "api $", "markup $"):
146
+ table.add_column(col)
147
+ for row in by_type:
148
+ tok = row.get("tokens", {})
149
+ table.add_row(
150
+ str(row.get("type", "")),
151
+ str(row.get("calls", 0)),
152
+ str(tok.get("input", 0)),
153
+ str(tok.get("output", 0)),
154
+ str(tok.get("cached", 0)),
155
+ f"{row.get('credits_charged', 0)}",
156
+ f"${row.get('api_cost_usd', 0):.4f}",
157
+ f"${row.get('markup_usd', 0):.4f}",
158
+ )
159
+ table.add_row(
160
+ "TOTAL",
161
+ "",
162
+ "",
163
+ "",
164
+ "",
165
+ f"{breakdown.get('total_credits_charged', 0)}",
166
+ f"${breakdown.get('total_api_cost_usd', 0):.4f}",
167
+ f"${breakdown.get('total_markup_usd', 0):.4f}",
168
+ )
169
+ console.print(table)
170
+ return
171
+
172
+ lines = ["usage (DB — authoritative):"]
173
+ for row in by_type:
174
+ tok = row.get("tokens", {})
175
+ lines.append(
176
+ f" {row.get('type', '')}: calls={row.get('calls', 0)} "
177
+ f"in={tok.get('input', 0)} out={tok.get('output', 0)} "
178
+ f"cache={tok.get('cached', 0)} credits={row.get('credits_charged', 0)} "
179
+ f"api=${row.get('api_cost_usd', 0):.4f} markup=${row.get('markup_usd', 0):.4f}"
180
+ )
181
+ lines.append(
182
+ f" TOTAL: credits={breakdown.get('total_credits_charged', 0)} "
183
+ f"api=${breakdown.get('total_api_cost_usd', 0):.4f} "
184
+ f"markup=${breakdown.get('total_markup_usd', 0):.4f}"
185
+ )
186
+ ctx.emit("\n".join(lines), title="usage")
187
+
188
+
189
+ def _maybe_note_estimate_drift(ctx: CommandContext, breakdown: Dict[str, Any]) -> None:
190
+ """Note when the live-bar estimate differs from the authoritative DB cost."""
191
+ state = ctx.state
192
+ if state is None:
193
+ return
194
+ est = state.cost_estimate_total
195
+ db = breakdown.get("total_api_cost_usd", 0) or 0
196
+ if est and abs(est - db) > max(0.0001, db * 0.01):
197
+ ctx.emit(
198
+ f"note: live-bar estimate ${est:.4f} differs from DB api cost ${db:.4f}"
199
+ )
200
+
201
+
202
+ def _render_usage_estimate(ctx: CommandContext) -> None:
203
+ state = ctx.state
204
+ if state is None:
205
+ ctx.emit("No usage recorded for this session.")
206
+ return
207
+ lines = [
208
+ "usage (estimate — from llm_usage files; CLI sessions skip DB credit tracking):",
209
+ f" tokens: {state.tokens_in} in · {state.tokens_out} out · {state.tokens_total} total",
210
+ f" cost (est): ${state.cost_estimate_total:.4f}",
211
+ ]
212
+ ctx.emit("\n".join(lines), title="usage")
213
+
214
+
215
+ def _h_tools(ctx: CommandContext) -> None:
216
+ """List the agent's registered actions, grouped by tool."""
217
+ actions = _registry_actions(ctx)
218
+ if not actions:
219
+ ctx.emit("(no registered tools — agent registry unavailable)")
220
+ return
221
+
222
+ grouped: Dict[str, List[str]] = {}
223
+ for name, action in sorted(actions.items()):
224
+ tool = getattr(action, "tool", None) or "default"
225
+ grouped.setdefault(tool, []).append(name)
226
+
227
+ console = ctx.console()
228
+ if console is not None:
229
+ from rich.table import Table
230
+
231
+ table = Table(title="registered tools", title_justify="left")
232
+ table.add_column("tool", style="bold")
233
+ table.add_column("actions")
234
+ for tool in sorted(grouped):
235
+ table.add_row(tool, ", ".join(grouped[tool]))
236
+ console.print(table)
237
+ return
238
+
239
+ lines = ["registered tools:"]
240
+ for tool in sorted(grouped):
241
+ lines.append(f" {tool}: {', '.join(grouped[tool])}")
242
+ ctx.emit("\n".join(lines), title="tools")
243
+
244
+
245
+ def _registry_actions(ctx: CommandContext) -> Dict[str, Any]:
246
+ """Best-effort fetch of the name→RegisteredAction dict from the agent.
247
+
248
+ Path: ``agent.controller.registry.registry.actions``. Tolerant of partial
249
+ stubs / missing layers (returns ``{}``).
250
+ """
251
+ agent = ctx.agent
252
+ if agent is None:
253
+ return {}
254
+ # Try a few plausible attribute paths (the proposal abbreviated this).
255
+ for path in (
256
+ ("controller", "registry", "registry", "actions"),
257
+ ("registry", "registry", "actions"),
258
+ ("controller", "registry", "actions"),
259
+ ):
260
+ obj: Any = agent
261
+ ok = True
262
+ for attr in path:
263
+ obj = getattr(obj, attr, None)
264
+ if obj is None:
265
+ ok = False
266
+ break
267
+ if ok and isinstance(obj, dict):
268
+ return obj
269
+ return {}
270
+
271
+
272
+ def _h_toolset(ctx: CommandContext) -> None:
273
+ """List named toolsets or show the current session's active tool ids.
274
+
275
+ Usage:
276
+ /toolset — list all named toolsets + current session tools
277
+ /toolset <name> — print what the named toolset resolves to (pruned for CLI)
278
+
279
+ NOTE: Live mid-session tool switching is not supported — the session's tool
280
+ set is fixed at creation time. ``/toolset <name>`` prints the resolved ids and
281
+ explains how to apply them on the NEXT session (``--toolset NAME`` on run, or
282
+ ``POLYROB_AGENT_TOOLSET=NAME`` env).
283
+ """
284
+ from agents.task.tool_defaults import TOOLSETS, resolve_toolset
285
+ from core.bootstrap import cli_unavailable_tools
286
+
287
+ args = ctx.args
288
+ console = ctx.console()
289
+
290
+ if args:
291
+ # /toolset <name> — show resolved + pruned ids for that name, with guidance.
292
+ name = args[0].strip().lower()
293
+ resolved = resolve_toolset(name)
294
+ unavailable = set(cli_unavailable_tools(resolved))
295
+ available = [t for t in resolved if t not in unavailable]
296
+ known = name in TOOLSETS
297
+ qualifier = "" if known else f" (unknown — fell back to 'default')"
298
+
299
+ if console is not None:
300
+ from rich.table import Table
301
+
302
+ table = Table(
303
+ title=f"toolset: {name}{qualifier}",
304
+ title_justify="left",
305
+ show_header=False,
306
+ )
307
+ table.add_column("k", style="bold")
308
+ table.add_column("v")
309
+ table.add_row("resolved ids", ", ".join(resolved) or "—")
310
+ table.add_row("CLI-available", ", ".join(available) or "—")
311
+ if unavailable:
312
+ table.add_row("not available in CLI", ", ".join(sorted(unavailable)))
313
+ table.add_row(
314
+ "to apply on next run",
315
+ f"polyrob run --toolset {name} <task>",
316
+ )
317
+ table.add_row(
318
+ "or set env",
319
+ f"POLYROB_AGENT_TOOLSET={name}",
320
+ )
321
+ table.add_row(
322
+ "note",
323
+ "Live tool switching is not supported — applies to NEW sessions only.",
324
+ )
325
+ console.print(table)
326
+ else:
327
+ lines = [
328
+ f"toolset: {name}{qualifier}",
329
+ f" resolved ids: {', '.join(resolved) or '—'}",
330
+ f" CLI-available: {', '.join(available) or '—'}",
331
+ ]
332
+ if unavailable:
333
+ lines.append(f" not available: {', '.join(sorted(unavailable))}")
334
+ lines += [
335
+ f" to apply: polyrob run --toolset {name} <task>",
336
+ f" or POLYROB_AGENT_TOOLSET={name}",
337
+ " note: live tool switching is not supported — new sessions only.",
338
+ ]
339
+ ctx.emit("\n".join(lines), title="toolset")
340
+ return
341
+
342
+ # /toolset (no arg) — list all named toolsets + current session tools.
343
+ # Current session tool ids: best-effort from registered actions.
344
+ actions = _registry_actions(ctx)
345
+ current_tools: List[str] = sorted(
346
+ {getattr(a, "tool", None) or "default" for a in actions.values()} - {"default"}
347
+ ) if actions else []
348
+
349
+ if console is not None:
350
+ from rich.table import Table
351
+
352
+ table = Table(title="named toolsets", title_justify="left")
353
+ table.add_column("name", style="bold")
354
+ table.add_column("ids")
355
+ table.add_column("CLI-available")
356
+ for ts_name, ts_ids in sorted(TOOLSETS.items()):
357
+ unavail = set(cli_unavailable_tools(ts_ids))
358
+ avail = [t for t in ts_ids if t not in unavail]
359
+ mark = " (unavailable tools pruned)" if unavail else ""
360
+ table.add_row(ts_name, ", ".join(ts_ids), ", ".join(avail) + mark)
361
+ console.print(table)
362
+
363
+ if current_tools:
364
+ console.print(f"current session tools: {', '.join(current_tools)}")
365
+ else:
366
+ console.print("(current session tool set unavailable)")
367
+ console.print(
368
+ "[dim]Use: polyrob run --toolset <name> <task> "
369
+ "or set POLYROB_AGENT_TOOLSET=<name>[/dim]"
370
+ )
371
+ else:
372
+ lines = ["named toolsets:"]
373
+ for ts_name, ts_ids in sorted(TOOLSETS.items()):
374
+ unavail = set(cli_unavailable_tools(ts_ids))
375
+ avail = [t for t in ts_ids if t not in unavail]
376
+ mark = " *" if unavail else ""
377
+ lines.append(f" {ts_name:<14} {', '.join(ts_ids)}")
378
+ if unavail:
379
+ lines.append(f" {'':14} CLI-available: {', '.join(avail)}{mark}")
380
+ if current_tools:
381
+ lines.append(f"current session: {', '.join(current_tools)}")
382
+ lines.append("Use: polyrob run --toolset <name> <task> or POLYROB_AGENT_TOOLSET=<name>")
383
+ ctx.emit("\n".join(lines), title="toolsets")
384
+
385
+
386
+ def _list_persona_names(characters_dir: Optional[Path] = None) -> List[str]:
387
+ """Return sorted persona names from ``*.character.json`` files.
388
+
389
+ Falls back gracefully: returns ``[]`` if the directory cannot be read.
390
+ Accepts an explicit *characters_dir* override for test isolation; otherwise
391
+ uses the canonical ``data/characters/`` path relative to the repo root (same
392
+ heuristic as ``CharacterManager``).
393
+ """
394
+ if characters_dir is None:
395
+ # Mirror CharacterManager: prefer data/characters/ when it contains files,
396
+ # else fall back to the package directory.
397
+ try:
398
+ from pathlib import Path as _Path
399
+
400
+ candidate = _Path("data") / "characters"
401
+ if not candidate.exists() or not list(candidate.glob("*.character.json")):
402
+ from agents.personality import character as _char_mod
403
+
404
+ candidate = _Path(_char_mod.__file__).parent / "characters"
405
+ characters_dir = candidate
406
+ except Exception:
407
+ return []
408
+
409
+ try:
410
+ return sorted(
411
+ # p.name = "researcher.character.json" → stem "researcher.character"
412
+ # We strip the trailing ".character" to get the bare slug.
413
+ p.stem.removesuffix(".character")
414
+ for p in characters_dir.glob("*.character.json")
415
+ )
416
+ except Exception:
417
+ return []
418
+
419
+
420
+ def _h_persona(ctx: CommandContext) -> None:
421
+ """List available personas or show guidance on switching the active persona.
422
+
423
+ Usage:
424
+ /persona — list all available persona names
425
+ /persona <name> — show the persona's bio and explain how to activate it
426
+
427
+ NOTE: Live mid-session persona switching is not supported — the character/
428
+ persona block is resolved at session-start time (gated by
429
+ ``TASK_PERSONALITY_BLOCK``). ``/persona <name>`` shows the persona description
430
+ and explains how to activate it on the NEXT session via the environment.
431
+ """
432
+ args = ctx.args
433
+ console = ctx.console()
434
+ names = _list_persona_names()
435
+
436
+ if args:
437
+ target = args[0].strip().lower()
438
+
439
+ # Try to load the bio from the character file for display.
440
+ bio: str = ""
441
+ adjectives: List[str] = []
442
+ topics: List[str] = []
443
+ try:
444
+ from pathlib import Path as _Path
445
+
446
+ chars_dir = _Path("data") / "characters"
447
+ char_file = chars_dir / f"{target}.character.json"
448
+ if char_file.exists():
449
+ import json as _json
450
+
451
+ data = _json.loads(char_file.read_text(encoding="utf-8"))
452
+ raw_bio = data.get("bio", "")
453
+ if isinstance(raw_bio, list):
454
+ bio = " ".join(raw_bio)
455
+ else:
456
+ bio = str(raw_bio)
457
+ adjectives = data.get("adjectives", [])
458
+ topics = data.get("topics", [])
459
+ except Exception:
460
+ pass
461
+
462
+ known = target in names
463
+ qualifier = "" if known else " (unknown)"
464
+
465
+ if console is not None:
466
+ from rich.table import Table
467
+
468
+ table = Table(
469
+ title=f"persona: {target}{qualifier}",
470
+ title_justify="left",
471
+ show_header=False,
472
+ )
473
+ table.add_column("k", style="bold")
474
+ table.add_column("v")
475
+ if bio:
476
+ table.add_row("bio", bio)
477
+ if adjectives:
478
+ table.add_row("adjectives", ", ".join(adjectives))
479
+ if topics:
480
+ table.add_row("topics", ", ".join(topics))
481
+ table.add_row("available personas", ", ".join(names) or "—")
482
+ table.add_row(
483
+ "to activate on next run",
484
+ "POLYROB_PERSONA=<template> polyrob … "
485
+ "(templates: general, research, coding, social, trading, blank)",
486
+ )
487
+ table.add_row(
488
+ "note",
489
+ "Live persona switching is not supported — applies to NEW sessions only.",
490
+ )
491
+ console.print(table)
492
+ else:
493
+ lines = [f"persona: {target}{qualifier}"]
494
+ if bio:
495
+ lines.append(f" bio: {bio}")
496
+ if adjectives:
497
+ lines.append(f" adjectives: {', '.join(adjectives)}")
498
+ if topics:
499
+ lines.append(f" topics: {', '.join(topics)}")
500
+ lines += [
501
+ f" available: {', '.join(names) or '—'}",
502
+ " to activate: POLYROB_PERSONA=<template> polyrob … "
503
+ "(templates: general, research, coding, social, trading, blank)",
504
+ " note: live persona switching is not supported — new sessions only.",
505
+ ]
506
+ ctx.emit("\n".join(lines), title="persona")
507
+ return
508
+
509
+ # /persona (no arg) — list all available persona names.
510
+ if console is not None:
511
+ from rich.table import Table
512
+
513
+ table = Table(title="available personas", title_justify="left")
514
+ table.add_column("name", style="bold")
515
+ table.add_column("bio")
516
+ for pname in names:
517
+ pbio = ""
518
+ try:
519
+ from pathlib import Path as _Path
520
+ import json as _json
521
+
522
+ pfile = _Path("data") / "characters" / f"{pname}.character.json"
523
+ if pfile.exists():
524
+ d = _json.loads(pfile.read_text(encoding="utf-8"))
525
+ raw = d.get("bio", "")
526
+ pbio = (raw if isinstance(raw, str) else " ".join(raw))[:80]
527
+ except Exception:
528
+ pass
529
+ table.add_row(pname, pbio)
530
+ console.print(table)
531
+ console.print(
532
+ "[dim]Set the CLI persona with POLYROB_PERSONA=<template> "
533
+ "(general, research, coding, social, trading, blank).[/dim]"
534
+ )
535
+ console.print(
536
+ "[dim]Or use /persona <name> for details. Live switching not supported.[/dim]"
537
+ )
538
+ else:
539
+ lines = ["available personas:"]
540
+ for pname in names:
541
+ lines.append(f" {pname}")
542
+ lines += [
543
+ "Set the CLI persona with POLYROB_PERSONA=<template> "
544
+ "(general, research, coding, social, trading, blank).",
545
+ "Or use /persona <name> for details. Live switching not supported.",
546
+ ]
547
+ ctx.emit("\n".join(lines), title="personas")
548
+
549
+
550
+ def _h_sessions(ctx: CommandContext) -> None:
551
+ """List all sessions from the session manager."""
552
+ task_agent = ctx.task_agent
553
+ sm = getattr(task_agent, "session_manager", None) if task_agent is not None else None
554
+ if sm is None:
555
+ ctx.emit("(session manager unavailable)")
556
+ return
557
+ try:
558
+ sessions = sm.get_all_sessions() or []
559
+ except Exception as exc:
560
+ ctx.emit(f"Could not list sessions: {exc}")
561
+ return
562
+ if not sessions:
563
+ ctx.emit("No sessions found.")
564
+ return
565
+
566
+ console = ctx.console()
567
+ if console is not None:
568
+ from rich.table import Table
569
+
570
+ table = Table(title="sessions", title_justify="left")
571
+ for col in ("id", "status", "created", "model"):
572
+ table.add_column(col)
573
+ for s in sessions:
574
+ table.add_row(
575
+ str(s.get("id", ""))[:16],
576
+ str(s.get("status", "")),
577
+ str(s.get("created_at", ""))[:19],
578
+ _session_model(s),
579
+ )
580
+ console.print(table)
581
+ return
582
+
583
+ lines = ["sessions:"]
584
+ for s in sessions:
585
+ lines.append(
586
+ f" {str(s.get('id', ''))[:16]} {s.get('status', '')} "
587
+ f"{str(s.get('created_at', ''))[:19]} {_session_model(s)}"
588
+ )
589
+ ctx.emit("\n".join(lines), title="sessions")
590
+
591
+
592
+ def _session_model(session: Dict[str, Any]) -> str:
593
+ agents = session.get("agents") or []
594
+ if agents and isinstance(agents, list):
595
+ first = agents[0]
596
+ if isinstance(first, dict):
597
+ return str(first.get("model", "") or "")
598
+ return str(session.get("model", "") or "")
599
+
600
+
601
+ def _h_history(ctx: CommandContext) -> None:
602
+ """Show the conversation turns (user + assistant)."""
603
+ convo = ctx.conversation
604
+ turns = list(getattr(convo, "turns", []) or [])
605
+ if not turns:
606
+ ctx.emit("No conversation history yet.")
607
+ return
608
+
609
+ console = ctx.console()
610
+ if console is not None:
611
+ from rich.table import Table
612
+
613
+ from cli.ui.identity import agent_display_name
614
+ table = Table(title="history", title_justify="left")
615
+ table.add_column("#", style="dim")
616
+ table.add_column("user")
617
+ table.add_column(agent_display_name())
618
+ for i, t in enumerate(turns, 1):
619
+ table.add_row(
620
+ str(i),
621
+ _truncate(getattr(t, "user", ""), 60),
622
+ _truncate(getattr(t, "assistant", ""), 60),
623
+ )
624
+ console.print(table)
625
+ return
626
+
627
+ lines = ["history:"]
628
+ for i, t in enumerate(turns, 1):
629
+ lines.append(f" [{i}] > {_truncate(getattr(t, 'user', ''), 80)}")
630
+ lines.append(f" {_truncate(getattr(t, 'assistant', ''), 80)}")
631
+ ctx.emit("\n".join(lines), title="history")
632
+
633
+
634
+ def _h_clear(ctx: CommandContext) -> None:
635
+ """Clear conversation history, keeping the system prompt."""
636
+ mm = ctx.message_manager
637
+ if mm is None:
638
+ ctx.emit("(no message manager — nothing to clear)")
639
+ return
640
+ try:
641
+ mm.clear_history_keep_system()
642
+ except Exception as exc:
643
+ ctx.emit(f"Could not clear history: {exc}")
644
+ return
645
+ turns = getattr(ctx.conversation, "turns", None)
646
+ if turns is not None:
647
+ try:
648
+ turns.clear()
649
+ except Exception:
650
+ pass
651
+ # Reset the live counters (step/ctx%/tool-calls) so /status + /steps don't show
652
+ # pre-clear values; cumulative session cost is preserved (real spend).
653
+ state = getattr(ctx, "state", None)
654
+ if state is not None and hasattr(state, "reset_after_clear"):
655
+ state.reset_after_clear()
656
+ ctx.emit("History cleared (system prompt kept; live counters reset, session cost preserved).")
657
+
658
+
659
+ async def _h_compact(ctx: CommandContext) -> None:
660
+ """Run LLM-based history compaction (async)."""
661
+ mm = ctx.message_manager
662
+ if mm is None:
663
+ ctx.emit("(no message manager — nothing to compact)")
664
+ return
665
+ ctx.emit("compacting history… (this may take a moment)")
666
+ try:
667
+ result = await mm.llm_compact_history()
668
+ except Exception as exc:
669
+ ctx.emit(f"Compaction failed: {exc}")
670
+ return
671
+ if result:
672
+ ctx.emit("History compacted.")
673
+ else:
674
+ ctx.emit("Compaction skipped (nothing to compact / not needed).")
675
+
676
+
677
+ def _current_model_tuple(ctx: CommandContext) -> Optional[tuple]:
678
+ """The (provider, model) the session is ACTUALLY running, for the picker's
679
+ 'keep' default — so it reflects the live model (incl. a fallback) rather than
680
+ a separately re-resolved default that can diverge from what's running."""
681
+ agent = ctx.agent
682
+ if agent is not None:
683
+ m = getattr(agent, "model_name", None)
684
+ p = getattr(agent, "llm_provider", None)
685
+ if m and p:
686
+ return (p, m)
687
+ state = ctx.state
688
+ if state is not None and getattr(state, "model", ""):
689
+ return (getattr(state, "provider", "") or "", state.model)
690
+ return None
691
+
692
+
693
+ async def _pick_model_interactive(preselect: Optional[tuple]):
694
+ """Run the arrow-key/fuzzy model selector, correct in every REPL mode.
695
+
696
+ Three cases:
697
+ * Persistent REPL (default): the prompt_toolkit ``Application`` owns the
698
+ screen. Drive its embedded :class:`~cli.ui.model_selector.ReplPicker`
699
+ (``app._picker``) — a conditional list above the input, resolved via a
700
+ Future. It runs on the event loop and never blocks stdin or routes through
701
+ patch_stdout's ``StdoutProxy`` (that was the old picker's missing-menu bug).
702
+ * Legacy/plain REPL or tests (no app / no picker): call the ASYNC standalone
703
+ selector, which opens its own throwaway ``Application`` via
704
+ ``await app.run_async()`` (TTY-safe — a non-TTY caller gets the resolved
705
+ default without prompting). It must be the async variant: this coroutine
706
+ already runs inside the REPL's event loop, so the SYNC ``run_standalone``
707
+ (which uses ``asyncio.run()``) would crash with "cannot be called from a
708
+ running event loop".
709
+
710
+ Fail-open to the async standalone selector so any prompt_toolkit hiccup can
711
+ never make ``/model`` unusable.
712
+ """
713
+ from cli.ui.model_selector import run_standalone_async
714
+
715
+ try:
716
+ from prompt_toolkit.application.current import get_app_or_none
717
+
718
+ app = get_app_or_none()
719
+ picker = getattr(app, "_picker", None) if app is not None else None
720
+ if picker is not None and getattr(app, "is_running", False):
721
+ from modules.llm.available_models import available_models, steer_notes
722
+ from cli.ui.model_selector import _default_idx, _resolved_default
723
+
724
+ choices = available_models()
725
+ if not choices:
726
+ return None
727
+ default = preselect or _resolved_default(None, choices)
728
+ return await picker.open(choices, _default_idx(choices, default), steer_notes())
729
+ except Exception:
730
+ pass
731
+ return await run_standalone_async(preselect=preselect)
732
+
733
+
734
+ async def _h_model(ctx: CommandContext) -> None:
735
+ """Swap the running session's model live + persist as the new-session default.
736
+
737
+ No args launches an interactive picker; all paths (explicit args,
738
+ ``provider/model`` shorthand, and the picker) converge on the same
739
+ persist+swap logic below.
740
+ """
741
+ from cli.config_store import (
742
+ set_default_model, check_provider_model, resolve_model_alias, _provider_for_model,
743
+ env_default_override_note,
744
+ )
745
+
746
+ args = ctx.args
747
+ if not args:
748
+ picked = await _pick_model_interactive(_current_model_tuple(ctx))
749
+ if not picked:
750
+ ctx.emit("Cancelled.")
751
+ return
752
+ provider, model = picked
753
+ elif len(args) == 1 and "/" in args[0]:
754
+ provider, model = args[0].split("/", 1)
755
+ elif len(args) == 1:
756
+ # No slash, single token: the only valid shape left is a `model_aliases`
757
+ # name (B6, e.g. `/model fav`) — expand it to (provider, model). Provider
758
+ # may be missing from the alias value (bare-model alias); infer it the same
759
+ # way an explicit `-m <model>` does.
760
+ alias = resolve_model_alias(args[0])
761
+ if not alias or not alias[1]:
762
+ ctx.emit(
763
+ f"Unknown alias '{args[0]}'. "
764
+ "Usage: /model <provider> <model>, /model <provider>/<model>, "
765
+ "or define it under model_aliases."
766
+ )
767
+ return
768
+ alias_provider, model = alias
769
+ provider = alias_provider or _provider_for_model(model)
770
+ if not provider:
771
+ ctx.emit(f"Alias '{args[0]}' has no provider and none could be inferred from '{model}'.")
772
+ return
773
+ elif len(args) >= 2:
774
+ provider, model = args[0], args[1]
775
+ else:
776
+ ctx.emit("Usage: /model <provider> <model>")
777
+ return
778
+ # Validate the provider (an unknown one is silently dropped on the next launch, so
779
+ # 'set' would be a lie) — matches the `polyrob model set-default` twin.
780
+ known, warning = check_provider_model(provider, model)
781
+ if not known:
782
+ ctx.emit(f"Unknown provider '{provider}'. Try /model <provider> <model> with a known provider.")
783
+ return
784
+ if warning:
785
+ ctx.emit(warning)
786
+ set_default_model(provider, model)
787
+ # Honest persistence: an env pin (CHAT_/DEFAULT_PROVIDER) outranks cli.json for
788
+ # new sessions, so don't claim "saved as the default" without the caveat.
789
+ override = env_default_override_note(provider)
790
+
791
+ def _with_note(msg: str) -> str:
792
+ return f"{msg}\n{override}" if override else msg
793
+
794
+ agent = ctx.agent
795
+ if agent is not None and hasattr(agent, "swap_model"):
796
+ res = await agent.swap_model(provider, model)
797
+ if res.get("ok"):
798
+ # Repaint the frame/toolbar NOW: SessionState.model is only set from an
799
+ # LLMCall event when still unset, so without this the bar would show the
800
+ # PRE-swap model until (and if) a later turn happened to reset it.
801
+ if ctx.state is not None:
802
+ ctx.state.model = res.get("model") or model
803
+ ctx.state.provider = res.get("provider") or provider
804
+ ctx.emit(_with_note(
805
+ f"Model swapped live: {model} ({provider}). Also saved as the default for new sessions."))
806
+ return
807
+ ctx.emit(_with_note(
808
+ f"Saved default {model} ({provider}); live swap failed ({res.get('error')}); "
809
+ "current session keeps its model."))
810
+ return
811
+ ctx.emit(_with_note(
812
+ f"Default model set: {model} ({provider}). Applies to NEW sessions (no live session to swap)."))
813
+
814
+
815
+ def _h_cwd(ctx: CommandContext) -> None:
816
+ """Show the session's workspace directory."""
817
+ try:
818
+ from agents.task.path import pm
819
+
820
+ path = pm().get_workspace_dir(ctx.session_id, ctx.user_id)
821
+ ctx.emit(str(path), title="cwd")
822
+ except Exception as exc:
823
+ ctx.emit(f"Could not resolve workspace dir: {exc}")
824
+
825
+
826
+ async def _h_memory(ctx: CommandContext) -> None:
827
+ """Show the active cross-session memory provider, or search it.
828
+
829
+ ``/memory`` → show the active provider (FTS / RAG / hybrid / none).
830
+ ``/memory search <query>`` → cross-session recall over the active provider.
831
+ """
832
+ try:
833
+ from modules.memory.registry import get_memory_registry
834
+
835
+ provider = get_memory_registry().active()
836
+ name = getattr(provider, "name", None) if provider is not None else None
837
+ external = bool(getattr(provider, "is_external", False)) if provider is not None else False
838
+
839
+ # ---- /memory search <query> -----------------------------------------
840
+ if ctx.args and str(ctx.args[0]).lower() == "search":
841
+ query = " ".join(ctx.args[1:]).strip()
842
+ if not query:
843
+ ctx.emit("Usage: /memory search <query>", title="memory")
844
+ return
845
+ if provider is None or not external or not callable(getattr(provider, "search", None)):
846
+ ctx.emit(
847
+ "No searchable memory backend active (recall disabled).",
848
+ title="memory",
849
+ )
850
+ return
851
+ hits = await provider.search(query, user_id=ctx.user_id or "local", limit=10)
852
+ text = hits.strip() if isinstance(hits, str) else str(hits or "").strip()
853
+ if not text:
854
+ ctx.emit("No matches.", title="memory")
855
+ return
856
+ ctx.emit(text, title="memory")
857
+ return
858
+
859
+ # ---- /memory (no args) — active provider name (legacy) ---------------
860
+ if not name or not external:
861
+ ctx.emit("No external memory backend active (recall disabled).", title="memory")
862
+ return
863
+ ctx.emit(f"Active memory provider: {name}", title="memory")
864
+ except Exception as exc:
865
+ ctx.emit(f"Could not resolve memory provider: {exc}", title="memory")
866
+
867
+
868
+ def _resolve_memory_backend_name() -> str:
869
+ """Best-effort name of the active cross-session memory provider, or 'none'."""
870
+ try:
871
+ from modules.memory.registry import get_memory_registry
872
+
873
+ provider = get_memory_registry().active()
874
+ name = getattr(provider, "name", None) if provider is not None else None
875
+ external = bool(getattr(provider, "is_external", False)) if provider is not None else False
876
+ if name and external:
877
+ return str(name)
878
+ except Exception:
879
+ pass
880
+ return "none"
881
+
882
+
883
+ def _session_info_rows(ctx: CommandContext) -> list:
884
+ """Build the (key, value) rows for ``/session`` — the identity snapshot.
885
+
886
+ Composes the existing resolvers (instance/owner/memory/workspace) fail-open
887
+ per field so a missing service degrades to a placeholder, never raises.
888
+ """
889
+ from core.instance import (
890
+ FRAMEWORK_NAME,
891
+ resolve_instance_id,
892
+ resolve_owner_principal,
893
+ )
894
+
895
+ state = ctx.state
896
+ model = getattr(state, "model", "") or "—"
897
+ provider = getattr(state, "provider", "") or "—"
898
+
899
+ owner = resolve_owner_principal() or "unbound (local owner)"
900
+
901
+ workspace = "—"
902
+ try:
903
+ from agents.task.path import pm
904
+
905
+ workspace = str(pm().get_workspace_dir(ctx.session_id, ctx.user_id))
906
+ except Exception:
907
+ pass
908
+
909
+ autonomy_on = False
910
+ try:
911
+ from agents.task.constants import local_mode_enabled
912
+
913
+ autonomy_on = bool(local_mode_enabled())
914
+ except Exception:
915
+ pass
916
+
917
+ rows = [
918
+ ("framework", FRAMEWORK_NAME),
919
+ ("instance", resolve_instance_id()),
920
+ ("owner", owner),
921
+ ("user", ctx.user_id or "local"),
922
+ ("session", ctx.session_id or "—"),
923
+ ("model", f"{model} ({provider})"),
924
+ ("memory", _resolve_memory_backend_name()),
925
+ ("autonomy", "on" if autonomy_on else "off"),
926
+ ("workspace", workspace),
927
+ ]
928
+ return rows
929
+
930
+
931
+ def _h_session(ctx: CommandContext) -> None:
932
+ """Full session identity snapshot: polyrob framework / instance, owner, user,
933
+ session id, model, memory backend, autonomy, workspace.
934
+
935
+ Distinct from ``/status`` (live token/cost metrics) — this is the static
936
+ identity card. Fail-open per field.
937
+ """
938
+ rows = _session_info_rows(ctx)
939
+ console = ctx.console()
940
+ if console is not None:
941
+ from rich.table import Table
942
+
943
+ table = Table(title="session", title_justify="left", show_header=False)
944
+ table.add_column("k", style="bold")
945
+ table.add_column("v")
946
+ for k, v in rows:
947
+ table.add_row(k, str(v))
948
+ console.print(table)
949
+ return
950
+ ctx.emit("\n".join(f"{k}: {v}" for k, v in rows), title="session")
951
+
952
+
953
+ def autonomy_status_lines(user_id: str, data_dir: str = "data") -> list:
954
+ """Build the /autonomy report: enabled loops + scheduled cron jobs / open goals.
955
+
956
+ Pure + fail-open: each store read is independently guarded so a missing/locked
957
+ DB degrades to an '(unavailable)' line instead of raising into the REPL.
958
+ """
959
+ import os
960
+ from agents.task.constants import AutonomyConfig, local_mode_enabled
961
+
962
+ lines = [f"local mode (POLYROB_LOCAL): {'on' if local_mode_enabled() else 'off'}"]
963
+ flags = [
964
+ ("self-wake", AutonomyConfig.self_wake_enabled()),
965
+ ("goals", AutonomyConfig.goals_enabled()),
966
+ ("curator", AutonomyConfig.curator_enabled()),
967
+ ("cron-run-loop", AutonomyConfig.cron_run_loop()),
968
+ ("background-review", AutonomyConfig.background_review_enabled()),
969
+ ]
970
+ lines.append("loops: " + ", ".join(f"{n}={'on' if v else 'off'}" for n, v in flags))
971
+
972
+ try:
973
+ from cron.service import CronService
974
+ from cron.jobs import CronJobStore
975
+ jobs = CronService(CronJobStore(os.path.join(data_dir, "cron.db"))).list_jobs(user_id=user_id)
976
+ lines.append(f"cron jobs: {len(jobs)}")
977
+ for j in jobs[:10]:
978
+ when = j.next_run_at.isoformat() if j.next_run_at else "-"
979
+ lines.append(f" - {j.id} [{j.status}] {j.schedule_spec} -> {when}: {j.task[:48]}")
980
+ except Exception as e: # fail-open: stores may not exist yet
981
+ lines.append(f"cron jobs: (unavailable: {e})")
982
+
983
+ try:
984
+ from agents.task.goals.board import GoalBoard
985
+ goals = GoalBoard(os.path.join(data_dir, "goals.db")).list(user_id=user_id)
986
+ open_goals = [g for g in goals if getattr(g, "status", "") not in ("done", "cancelled")]
987
+ lines.append(f"goals (open): {len(open_goals)}")
988
+ except Exception as e:
989
+ lines.append(f"goals (open): (unavailable: {e})")
990
+
991
+ return lines
992
+
993
+
994
+ def _h_autonomy(ctx: CommandContext) -> None:
995
+ """Show autonomy loop state + scheduled cron jobs / open goals (read-only)."""
996
+ data_dir = "data"
997
+ try:
998
+ cfg = getattr(ctx.container, "config", None)
999
+ data_dir = getattr(cfg, "data_dir", "data") or "data"
1000
+ except Exception:
1001
+ pass
1002
+ ctx.emit("\n".join(autonomy_status_lines(ctx.user_id or "local", data_dir)), title="autonomy")
1003
+
1004
+
1005
+ def _h_verbose(ctx: CommandContext) -> None:
1006
+ """Toggle reasoning/expand verbosity on the renderer.
1007
+
1008
+ Phase 2 left a ``(+N lines — /verbose)`` collapse hint in blocks.py; this
1009
+ flips ``renderer.verbose`` which the renderer consults when rendering steps
1010
+ (so the collapse is actually controllable).
1011
+ """
1012
+ renderer = ctx.renderer
1013
+ if renderer is None:
1014
+ ctx.emit("(no renderer)")
1015
+ return
1016
+ current = bool(getattr(renderer, "verbose", False))
1017
+ new = not current
1018
+ try:
1019
+ renderer.verbose = new
1020
+ except Exception:
1021
+ ctx.emit("This renderer does not support /verbose.")
1022
+ return
1023
+ ctx.emit(f"Verbose mode {'ON' if new else 'OFF'} (full reasoning, no collapse).")
1024
+
1025
+
1026
+ def _h_quiet(ctx: CommandContext) -> None:
1027
+ """Toggle the default tool transcript on the renderer.
1028
+
1029
+ The tool call/result lines are ON by default; ``/quiet`` mutes them for a
1030
+ clean chat-only view (dialog + final answer). This is a separate axis from
1031
+ ``/verbose`` (the full raw trace) — quieting tools does not affect verbose.
1032
+ """
1033
+ renderer = ctx.renderer
1034
+ if renderer is None:
1035
+ ctx.emit("(no renderer)")
1036
+ return
1037
+ current = bool(getattr(renderer, "show_tools", True))
1038
+ new = not current
1039
+ try:
1040
+ renderer.show_tools = new
1041
+ except Exception:
1042
+ ctx.emit("This renderer does not support /quiet.")
1043
+ return
1044
+ if new:
1045
+ ctx.emit("Tool transcript ON (tool calls + results shown).")
1046
+ else:
1047
+ ctx.emit("Tool transcript OFF (muted — chat only). /quiet to restore.")
1048
+
1049
+
1050
+ def _h_steps(ctx: CommandContext) -> None:
1051
+ """Re-render the last turn's trace (step blocks, tool lines, lifecycle).
1052
+
1053
+ The renderer keeps a per-turn ring buffer of typed RenderEvents; this
1054
+ replays it through the trace layer on demand — the retro counterpart to
1055
+ the live ``/verbose`` toggle.
1056
+ """
1057
+ renderer = ctx.renderer
1058
+ if renderer is None or not hasattr(renderer, "render_trace"):
1059
+ ctx.emit("(no renderer)")
1060
+ return
1061
+ count = renderer.render_trace()
1062
+ if not count:
1063
+ ctx.emit("No turn recorded yet — run a turn first, then /steps.")
1064
+
1065
+
1066
+ def _h_resume(ctx: CommandContext) -> None:
1067
+ """Replay a session's feed dir through the CURRENT renderer.
1068
+
1069
+ This is visual HISTORY replay (NOT live re-attach — out of scope, §11): we
1070
+ read the totally-ordered ``{seq:06d}_{type}*.json`` files and push each one
1071
+ through ``events.normalize`` into the same renderer the REPL uses.
1072
+ """
1073
+ args = ctx.args
1074
+ if not args:
1075
+ ctx.emit("Usage: /resume <session-id>")
1076
+ return
1077
+ target = args[0]
1078
+
1079
+ feed_dir = _resolve_feed_dir(ctx, target)
1080
+ if feed_dir is None or not feed_dir.is_dir():
1081
+ ctx.emit(f"No feed dir found for session {target}.")
1082
+ return
1083
+
1084
+ files = sorted(feed_dir.glob("[0-9]*_*.json"))
1085
+ if not files:
1086
+ ctx.emit(f"Feed dir for {target} is empty (nothing to replay).")
1087
+ return
1088
+
1089
+ ctx.emit(
1090
+ f"--- replaying session {target} ({len(files)} feed events) — "
1091
+ "visual history, not a live re-attach ---"
1092
+ )
1093
+
1094
+ from cli.ui.events import normalize
1095
+
1096
+ renderer = ctx.renderer
1097
+ for path in files:
1098
+ try:
1099
+ event_dict = json.loads(path.read_text(encoding="utf-8"))
1100
+ except (json.JSONDecodeError, OSError):
1101
+ continue
1102
+ try:
1103
+ event = normalize(event_dict)
1104
+ if renderer is not None:
1105
+ renderer.on_event(event)
1106
+ except Exception:
1107
+ continue
1108
+ ctx.emit(f"--- end of replay ({target}) ---")
1109
+
1110
+
1111
+ def _resolve_feed_dir(ctx: CommandContext, session_id: str) -> Optional[Path]:
1112
+ """Resolve a session's feed dir, preferring one that actually has feed files.
1113
+
1114
+ Candidates, in order:
1115
+ 1. ``pm().get_feed_dir(session_id, user_id)`` — but this CREATES an empty
1116
+ dir as a side effect, so it only WINS when it contains feed files.
1117
+ 2. CLI-store layout: ``./.polyrob/sessions/**/<session_id>/feed``.
1118
+ 3. CLI-store flat layout: ``./.polyrob/sessions/<session_id>/feed``.
1119
+
1120
+ We return the first candidate that contains ``[0-9]*_*.json`` files; if none
1121
+ has files we return the first existing dir (so the caller can report
1122
+ "empty"), else ``None`` (so the caller can report "not found").
1123
+ """
1124
+ candidates: List[Path] = []
1125
+
1126
+ # Consult pm() ONLY when the feed dir already exists with files — calling
1127
+ # get_feed_dir() on an unknown session id creates an empty orphan directory
1128
+ # as a side effect (get_subdir → get_session_root → ensure_directory_exists).
1129
+ # Instead we construct the candidate path from the pm data_root without any
1130
+ # mkdir calls and add it only when the dir is already present.
1131
+ try:
1132
+ from agents.task.path import pm
1133
+
1134
+ _pm = pm()
1135
+ clean_id = _pm.clean_session_id(session_id)
1136
+ clean_uid = _pm.clean_user_id(ctx.user_id or "local")
1137
+ _candidate = _pm.data_root / clean_uid / clean_id / "feed"
1138
+ if _candidate.is_dir():
1139
+ candidates.append(_candidate)
1140
+ except Exception:
1141
+ pass
1142
+
1143
+ try:
1144
+ root = Path.cwd() / ".polyrob" / "sessions"
1145
+ candidates.extend(root.glob(f"*/{session_id}/feed"))
1146
+ candidates.append(root / session_id / "feed")
1147
+ except Exception:
1148
+ pass
1149
+
1150
+ first_existing: Optional[Path] = None
1151
+ for candidate in candidates:
1152
+ try:
1153
+ if not candidate.is_dir():
1154
+ continue
1155
+ if first_existing is None:
1156
+ first_existing = candidate
1157
+ if any(candidate.glob("[0-9]*_*.json")):
1158
+ return candidate
1159
+ except Exception:
1160
+ continue
1161
+ return first_existing
1162
+
1163
+
1164
+ # ---------------------------------------------------------------------------
1165
+ # Additional slash command handlers (P1.5 REPL parity)
1166
+ # ---------------------------------------------------------------------------
1167
+
1168
+
1169
+ def _h_goals(ctx: CommandContext) -> None:
1170
+ """Show goals board summary."""
1171
+ try:
1172
+ from agents.task.goals.board import GoalBoard
1173
+ from core.runtime_config import get_data_root
1174
+ from pathlib import Path
1175
+
1176
+ data_root = Path(get_data_root())
1177
+ db_path = data_root / "goals.db"
1178
+
1179
+ if not db_path.exists():
1180
+ ctx.emit("Goals board not initialized (GOALS_ENABLED=off or no goals created)")
1181
+ return
1182
+
1183
+ board = GoalBoard(str(db_path))
1184
+ # Scope to THIS user (matches /autonomy at handlers.py autonomy_status_lines);
1185
+ # user_id=None returned every tenant's goals — wrong slice under multi-tenant
1186
+ # and inconsistent with the autonomy view. Local runs are user_id="local".
1187
+ goals = board.list(user_id=ctx.user_id or "local", limit=10)
1188
+
1189
+ if not goals:
1190
+ ctx.emit("No goals found")
1191
+ return
1192
+
1193
+ lines = [f"Goals board ({len(goals)} shown):"]
1194
+ for g in goals[:10]:
1195
+ status_color = {"ready": "🟢", "running": "🟡", "done": "✅", "blocked": "🔴", "cancelled": "⬜"}.get(g.status, "⚪")
1196
+ lines.append(f" {status_color} {g.id[:8]}: {g.title[:40]}")
1197
+
1198
+ if len(goals) >= 10:
1199
+ lines.append(f" ... (run `polyrob goals list` for all)")
1200
+
1201
+ ctx.emit("\n".join(lines))
1202
+ except Exception as e:
1203
+ ctx.emit(f"Goals: {e}")
1204
+
1205
+
1206
+ def _h_subagents(ctx: CommandContext) -> None:
1207
+ """Show delegation capability info + live background delegations for this session."""
1208
+ try:
1209
+ from agents.task.constants import TimeoutConfig
1210
+
1211
+ enabled = TimeoutConfig.get_sub_agents_enabled()
1212
+ max_concurrent = TimeoutConfig.get_max_concurrent_sub_agents()
1213
+ max_async = TimeoutConfig.get_max_async_sub_agents()
1214
+
1215
+ lines = [
1216
+ f"Delegation: {'enabled' if enabled else 'disabled'}",
1217
+ f"Max concurrent: {max_concurrent}",
1218
+ f"Max background: {max_async}",
1219
+ ]
1220
+
1221
+ # Live background (async) delegations tracked by this session's orchestrator —
1222
+ # the read-only counterpart to the delegate_task(background=true) tool, so
1223
+ # /subagents reflects what's actually running, not just static config.
1224
+ records = []
1225
+ reg = getattr(ctx.orchestrator, "async_delegation", None)
1226
+ if reg is not None:
1227
+ try:
1228
+ records = list(reg.list())
1229
+ except Exception:
1230
+ records = []
1231
+
1232
+ lines.append("")
1233
+ if records:
1234
+ lines.append(f"Background delegations ({len(records)}):")
1235
+ status_icon = {"running": "🟡", "completed": "✅", "error": "🔴", "timeout": "⏱️"}
1236
+ for r in records[:10]:
1237
+ icon = status_icon.get(getattr(r, "status", ""), "⚪")
1238
+ goal = _truncate(getattr(r, "goal", "") or "", 48)
1239
+ lines.append(f" {icon} {str(getattr(r, 'delegation_id', '?'))[:8]}: {goal}")
1240
+ else:
1241
+ lines.append("No active background delegations.")
1242
+
1243
+ ctx.emit("\n".join(lines), title="subagents")
1244
+ except Exception as e:
1245
+ ctx.emit(f"Subagents: {e}", title="subagents")
1246
+
1247
+
1248
+ def _h_todos(ctx: CommandContext) -> None:
1249
+ """Show todos from the agent's session todo file."""
1250
+ import re
1251
+ from agents.task.path import pm
1252
+
1253
+ # Resolve the SAME file the task tool writes (session-scoped), not ./todo.md in
1254
+ # CWD — the agent never writes there, so the old path always showed "no todos".
1255
+ todo_file = pm().get_todo_file_path(ctx.session_id, ctx.user_id)
1256
+ if not todo_file.exists():
1257
+ ctx.emit("No todos yet (the agent writes them via the task tool)")
1258
+ return
1259
+
1260
+ content = todo_file.read_text()
1261
+ items = []
1262
+ for line in content.splitlines():
1263
+ match = re.match(r'^-\s*\[([ x])\]\s*(.+)$', line.strip())
1264
+ if match:
1265
+ status, text = match.groups()
1266
+ items.append((status.lower() == "x", text.strip()))
1267
+
1268
+ if not items:
1269
+ ctx.emit("No todos in todo.md")
1270
+ return
1271
+
1272
+ completed = sum(1 for done, _ in items if done)
1273
+ total = len(items)
1274
+ lines = [f"Todos: {completed}/{total} completed"]
1275
+ for completed_flag, text in items[:10]:
1276
+ marker = "✓" if completed_flag else "○"
1277
+ lines.append(f" {marker} {text[:50]}")
1278
+
1279
+ if len(items) > 10:
1280
+ lines.append(f" ... ({len(items) - 10} more)")
1281
+
1282
+ ctx.emit("\n".join(lines))
1283
+
1284
+
1285
+ def _h_logs(ctx: CommandContext) -> None:
1286
+ """Show recent log entries for the session."""
1287
+ from agents.task.path import pm
1288
+
1289
+ # Resolve via pm() (the SSOT: data_root/user/session/logs) rather than a
1290
+ # hand-rolled CWD glob whose depth never matched the real layout.
1291
+ log_dir = pm().get_logs_dir(ctx.session_id, ctx.user_id)
1292
+
1293
+ if not log_dir or not log_dir.exists():
1294
+ ctx.emit(f"No logs found for session {ctx.session_id[:12]}")
1295
+ return
1296
+
1297
+ log_files = sorted(log_dir.glob("*.log"), key=lambda p: p.stat().st_mtime, reverse=True)[:3]
1298
+ if not log_files:
1299
+ ctx.emit(f"No log files in {log_dir}")
1300
+ return
1301
+
1302
+ lines = [f"Recent logs (last 3 files):"]
1303
+ for f in log_files:
1304
+ size = f.stat().st_size
1305
+ mtime = f.stat().st_mtime
1306
+ from datetime import datetime
1307
+ ts = datetime.fromtimestamp(mtime).strftime("%Y-%m-%d %H:%M")
1308
+ lines.append(f" {f.name} ({size} bytes, {ts})")
1309
+
1310
+ ctx.emit("\n".join(lines))
1311
+ ctx.emit("Use `polyrob logs` for full log access")
1312
+
1313
+
1314
+ def _h_export(ctx: CommandContext) -> None:
1315
+ """Export current session data."""
1316
+ args = ctx.args
1317
+ if not args:
1318
+ ctx.emit("Usage: /export <format> [output]")
1319
+ ctx.emit(" format: json (default) or txt")
1320
+ return
1321
+
1322
+ format_type = args[0] if args else "json"
1323
+ output = args[1] if len(args) > 1 else None
1324
+
1325
+ from datetime import datetime
1326
+ from agents.task.path import pm
1327
+
1328
+ # Resolve the session dir via pm() (works under POLYROB_DATA_DIR too, unlike the
1329
+ # old hardcoded <cwd>/.polyrob/sessions glob).
1330
+ session_dir = pm().get_session_root(ctx.session_id, ctx.user_id)
1331
+
1332
+ if output is None:
1333
+ # Default into the session workspace (SSOT) — the old bare filename dropped
1334
+ # the export into the process CWD, where it was easy to lose. An explicit
1335
+ # `output` arg is still honoured verbatim (the user's choice).
1336
+ try:
1337
+ session_dir.mkdir(parents=True, exist_ok=True)
1338
+ except Exception:
1339
+ pass
1340
+ output = str(session_dir / f"{ctx.session_id[:12]}_export.{format_type}")
1341
+
1342
+ # The useful payload is the conversation itself — serialize the turns, not just
1343
+ # three metadata fields (the old export was near-empty).
1344
+ turns = getattr(ctx.conversation, "turns", None) or []
1345
+ turns_data = [
1346
+ {"user": getattr(t, "user", ""), "assistant": getattr(t, "assistant", "")}
1347
+ for t in turns
1348
+ ]
1349
+ export_data = {
1350
+ "session_id": ctx.session_id,
1351
+ "exported_at": datetime.now().isoformat(),
1352
+ "session_dir": str(session_dir),
1353
+ "turns": turns_data,
1354
+ }
1355
+
1356
+ try:
1357
+ import json
1358
+ if format_type == "json":
1359
+ with open(output, "w") as f:
1360
+ json.dump(export_data, f, indent=2, default=str)
1361
+ else:
1362
+ with open(output, "w") as f:
1363
+ f.write(f"Session Export: {ctx.session_id[:12]}\n")
1364
+ f.write(f"Exported: {export_data['exported_at']}\n")
1365
+ for t in turns_data:
1366
+ f.write(f"\n> {t['user']}\n{t['assistant']}\n")
1367
+
1368
+ ctx.emit(f"Exported to {output} ({len(turns_data)} turn(s))")
1369
+ except Exception as e:
1370
+ ctx.emit(f"Export failed: {e}")
1371
+
1372
+
1373
+ # ---------------------------------------------------------------------------
1374
+ # Helpers
1375
+ # ---------------------------------------------------------------------------
1376
+
1377
+
1378
+ def _truncate(text: str, limit: int) -> str:
1379
+ flat = " ".join(str(text).split())
1380
+ if len(flat) <= limit:
1381
+ return flat
1382
+ return flat[: limit - 1] + "…"
1383
+
1384
+
1385
+ def _parse_window_seconds(arg: str) -> Optional[float]:
1386
+ """Parse a window token like '30m', '24h', '7d' -> seconds. None if unset/bad."""
1387
+ if not arg:
1388
+ return None
1389
+ arg = arg.strip().lower()
1390
+ try:
1391
+ if arg.endswith("m"):
1392
+ return float(arg[:-1]) * 60
1393
+ if arg.endswith("h"):
1394
+ return float(arg[:-1]) * 3600
1395
+ if arg.endswith("d"):
1396
+ return float(arg[:-1]) * 86400
1397
+ return float(arg) # bare number = seconds
1398
+ except Exception:
1399
+ return None
1400
+
1401
+
1402
+ def _h_telemetry(ctx: CommandContext) -> None:
1403
+ """Cross-session telemetry: autonomy/governance event counts + wallet spend.
1404
+
1405
+ Reads the durable event log (self_wake/cron_run/wallet_spend/tool_denied/…).
1406
+ Usage: /telemetry [window] e.g. `/telemetry 24h`, `/telemetry 7d`.
1407
+ """
1408
+ import time as _time
1409
+ try:
1410
+ from agents.task.telemetry.event_log import get_event_log, event_log_enabled
1411
+ except Exception as e:
1412
+ ctx.emit(f"(event log unavailable: {e})")
1413
+ return
1414
+ if not event_log_enabled():
1415
+ ctx.emit("(telemetry event log disabled — set TELEMETRY_EVENT_LOG_ENABLED=true)")
1416
+ return
1417
+
1418
+ window = ctx.args[0] if ctx.args else ""
1419
+ secs = _parse_window_seconds(window)
1420
+ since_ts = (_time.time() - secs) if secs else None
1421
+
1422
+ log = get_event_log()
1423
+ agg = log.aggregate(since_ts=since_ts)
1424
+ recent = log.query(since_ts=since_ts, limit=10)
1425
+
1426
+ scope = f"last {window}" if secs else "all time"
1427
+ counts = agg.get("counts_by_kind", {})
1428
+
1429
+ console = ctx.console()
1430
+ if console is not None:
1431
+ from rich.table import Table
1432
+ t = Table(title=f"telemetry — {scope}", title_justify="left", show_header=True)
1433
+ t.add_column("event kind", style="bold")
1434
+ t.add_column("count", justify="right")
1435
+ for kind, n in sorted(counts.items(), key=lambda kv: -kv[1]):
1436
+ t.add_row(kind, str(n))
1437
+ t.add_row("[dim]total[/dim]", f"[dim]{agg.get('total_events', 0)}[/dim]")
1438
+ t.add_row("[green]wallet spend[/green]", f"[green]${agg.get('total_spend_usd', 0.0):.4f}[/green]")
1439
+ console.print(t)
1440
+ if recent:
1441
+ rt = Table(title="recent events", title_justify="left", show_header=True)
1442
+ rt.add_column("kind"); rt.add_column("outcome/detail"); rt.add_column("session", style="dim")
1443
+ for r in recent:
1444
+ a = r.get("attrs", {})
1445
+ # memory_* events carry a scrubbed preview instead of an outcome (T4-02)
1446
+ detail = (a.get("outcome") or a.get("action") or a.get("reason")
1447
+ or a.get("preview") or "")
1448
+ rt.add_row(r["kind"], str(detail), (r.get("session_id") or "")[:12])
1449
+ console.print(rt)
1450
+ return
1451
+
1452
+ # Plain fallback.
1453
+ lines = [f"telemetry — {scope}:"]
1454
+ for kind, n in sorted(counts.items(), key=lambda kv: -kv[1]):
1455
+ lines.append(f" {kind}: {n}")
1456
+ lines.append(f" total events: {agg.get('total_events', 0)}")
1457
+ lines.append(f" wallet spend: ${agg.get('total_spend_usd', 0.0):.4f}")
1458
+ ctx.emit("\n".join(lines), title="telemetry")
1459
+
1460
+
1461
+ def _h_pending(ctx: CommandContext) -> None:
1462
+ """Owner review queue for the agent's self-evolution proposals (T4-06b/T4-07).
1463
+
1464
+ Umbrella over `core.self_evolution` — the same pipeline `polyrob owner
1465
+ pending/promote/reject` administers, now reachable without leaving the REPL.
1466
+ (NOT the marketplace-install quarantine — that stays under `/skills approve`.)
1467
+
1468
+ Usage:
1469
+ /pending — list pending proposals (skills + identity notes)
1470
+ /pending show <kind> <id> — full-body review of one proposal (T3-09)
1471
+ /pending approve <kind> <id> — promote to active (kind: skill | self_context)
1472
+ /pending reject <kind> <id> — reject (archive, recoverable)
1473
+ """
1474
+ import core.instance as _ci
1475
+ from core import self_evolution
1476
+
1477
+ uid = (ctx.user_id or "").strip() or "local"
1478
+ # The REPL is a trusted local operator surface ({cli,local,repl}); the
1479
+ # local=True bypass is the documented owner check for it. A bound owner
1480
+ # principal always wins; an unbound local operator IS the owner here.
1481
+ if not _ci.is_owner(uid, local=True):
1482
+ ctx.emit("(owner-only command — the review queue gates self-evolution)")
1483
+ return
1484
+
1485
+ cfg = getattr(ctx.container, "config", None) if ctx.container else None
1486
+ home_dir = getattr(cfg, "data_dir", "data") or "data"
1487
+ instance_id = _ci.resolve_instance_id()
1488
+
1489
+ args = list(ctx.args or [])
1490
+ if args and args[0].lower() in ("approve", "promote", "reject", "show"):
1491
+ if len(args) < 3:
1492
+ ctx.emit("usage: /pending show|approve|reject <kind> <id> (kind: skill | self_context)")
1493
+ return
1494
+ verb, kind, item_id = args[0].lower(), args[1], " ".join(args[2:])
1495
+ if verb == "show":
1496
+ ok, body = self_evolution.show(kind, item_id, user_id=uid,
1497
+ home_dir=home_dir, instance_id=instance_id)
1498
+ ctx.emit(body, title=f"pending {kind}:{item_id}" if ok else "pending",
1499
+ style="" if ok else "yellow")
1500
+ return
1501
+ fn = self_evolution.reject if verb == "reject" else self_evolution.promote
1502
+ ok, msg = fn(kind, item_id, user_id=uid, home_dir=home_dir, instance_id=instance_id)
1503
+ ctx.emit(msg, title="pending", style="" if ok else "yellow")
1504
+ return
1505
+
1506
+ items = self_evolution.list_pending(uid, home_dir=home_dir, instance_id=instance_id)
1507
+ if not items:
1508
+ ctx.emit("no pending proposals", title="pending")
1509
+ return
1510
+ lines = [f"{len(items)} pending proposal(s):"]
1511
+ for it in items:
1512
+ label = "identity" if it["kind"] == "self_context" else "skill"
1513
+ lines.append(f" [{label}] {it['kind']}:{it['id']} ({it['chars']} chars)")
1514
+ lines.append(f" {it['preview']}")
1515
+ lines.append("")
1516
+ lines.append("approve: /pending approve <kind> <id> reject: /pending reject <kind> <id>")
1517
+ ctx.emit("\n".join(lines), title="pending")
1518
+
1519
+
1520
+ # ---------------------------------------------------------------------------
1521
+ # Default registry (the built-in command set)
1522
+ # ---------------------------------------------------------------------------
1523
+
1524
+
1525
+ def build_default_registry() -> CommandRegistry:
1526
+ """Build the registry with all built-in commands registered."""
1527
+ reg = CommandRegistry()
1528
+ reg.register(Command("help", _h_help, "Show this help", aliases=("h", "?")))
1529
+ reg.register(Command("exit", _h_exit, "Leave the REPL", aliases=("quit", "q")))
1530
+ reg.register(Command("status", _h_status, "Live session status (tokens, cost, ctx)"))
1531
+ reg.register(
1532
+ Command("usage", _h_usage, "Authoritative usage breakdown (DB / estimate)", aliases=("cost",))
1533
+ )
1534
+ reg.register(
1535
+ Command("telemetry", _h_telemetry,
1536
+ "Cross-session event counts + wallet spend (arg: window e.g. 24h)")
1537
+ )
1538
+ from cli.ui.commands.h_journey import h_journey as _h_journey
1539
+ reg.register(
1540
+ Command("journey", _h_journey,
1541
+ "Timeline: what I did, learned, earned, changed (arg: window e.g. 24h|7d)",
1542
+ usage="[window]")
1543
+ )
1544
+ from cli.ui.commands.h_learn import h_learn as _h_learn
1545
+ reg.register(
1546
+ Command("learn", _h_learn,
1547
+ "Describe a procedure; distill it into a pending skill for review",
1548
+ usage="<description>")
1549
+ )
1550
+ reg.register(Command("tools", _h_tools, "List the agent's registered tools/actions"))
1551
+ reg.register(Command(
1552
+ "toolset",
1553
+ _h_toolset,
1554
+ "List named toolsets or resolve a specific toolset",
1555
+ usage="[name]",
1556
+ ))
1557
+ reg.register(Command(
1558
+ "persona",
1559
+ _h_persona,
1560
+ "List available personas or show details for a named persona",
1561
+ usage="[name]",
1562
+ ))
1563
+ reg.register(Command("sessions", _h_sessions, "List all known sessions"))
1564
+ reg.register(
1565
+ Command(
1566
+ "replay",
1567
+ _h_resume,
1568
+ "Replay a session's feed (visual history) — NOT a re-attach; continue a "
1569
+ "session with `polyrob run --resume <id>`",
1570
+ usage="<session-id>",
1571
+ aliases=("resume",),
1572
+ )
1573
+ )
1574
+ reg.register(Command("history", _h_history, "Show this conversation's turns"))
1575
+ reg.register(Command("clear", _h_clear, "Clear history (keep the system prompt)"))
1576
+ reg.register(Command("compact", _h_compact, "Compact history via the LLM (async)", aliases=("compress",)))
1577
+ reg.register(
1578
+ Command(
1579
+ "model",
1580
+ _h_model,
1581
+ "Swap the session model live + persist as default",
1582
+ usage="<provider> <model> | <provider>/<model> | <alias> (see model_aliases)",
1583
+ )
1584
+ )
1585
+ reg.register(Command("cwd", _h_cwd, "Show the session workspace directory"))
1586
+ reg.register(Command(
1587
+ "session", _h_session,
1588
+ "Session identity: polyrob/instance, owner, user, model, memory, workspace",
1589
+ aliases=("info",),
1590
+ ))
1591
+ from cli.ui.commands.h_self import h_self
1592
+ reg.register(Command(
1593
+ "self", h_self,
1594
+ "Show the instance identity (SOUL + SELF docs, read-only)",
1595
+ aliases=("identity", "soul"),
1596
+ ))
1597
+ reg.register(Command(
1598
+ "memory", _h_memory,
1599
+ "Show the memory provider; /memory search <query> to recall cross-session",
1600
+ usage="[search <query>]",
1601
+ ))
1602
+ reg.register(Command("verbose", _h_verbose, "Toggle the live trace (steps, tools, reasoning)"))
1603
+ reg.register(Command("quiet", _h_quiet, "Mute/restore the default tool transcript"))
1604
+ reg.register(Command("steps", _h_steps, "Show the last turn's steps/tools trace"))
1605
+ reg.register(Command(
1606
+ "autonomy", _h_autonomy,
1607
+ help="show autonomy loops + scheduled cron jobs / open goals",
1608
+ ))
1609
+ reg.register(Command("goals", _h_goals, "Show goals board summary"))
1610
+ reg.register(Command("subagents", _h_subagents, "Show delegation capability info"))
1611
+ reg.register(Command("todos", _h_todos, "Show workspace todos from todo.md"))
1612
+ reg.register(Command("logs", _h_logs, "Show recent log entries for this session"))
1613
+ reg.register(Command(
1614
+ "export",
1615
+ _h_export,
1616
+ "Export current session data",
1617
+ usage="<format> [output]",
1618
+ ))
1619
+ # Capability surfaces (each handler lives in its own cli/ui/commands/h_*.py
1620
+ # module so the REPL can reach subsystems the CLI groups already exposed —
1621
+ # skills / cron / mcp / kb. Read-only; imported locally to keep registry
1622
+ # construction cheap and dependency-light.
1623
+ from cli.ui.commands.h_skills import h_skills
1624
+ from cli.ui.commands.h_cron import h_cron
1625
+ from cli.ui.commands.h_mcp import h_mcp
1626
+ from cli.ui.commands.h_kb import h_kb
1627
+
1628
+ reg.register(Command(
1629
+ "skills", h_skills,
1630
+ "List/search skills; manage the install pipeline (list/info/install/approve/remove)",
1631
+ usage="[query | list | info <id> | install <spec> | approve <id> | remove <id>]",
1632
+ ))
1633
+ reg.register(Command(
1634
+ "cron", h_cron,
1635
+ "List scheduled cron jobs (read-only)",
1636
+ aliases=("crons",), usage="[list]",
1637
+ ))
1638
+ reg.register(Command("mcp", h_mcp, "List configured MCP servers + status", usage="[list]"))
1639
+ reg.register(Command(
1640
+ "kb", h_kb,
1641
+ "List + search the local knowledge base",
1642
+ usage="[list [collection] | search <query>]",
1643
+ ))
1644
+ reg.register(Command(
1645
+ "pending", _h_pending,
1646
+ "Review the agent's pending self-evolution proposals (show/approve/reject)",
1647
+ usage="[show|approve|reject <kind> <id>]",
1648
+ ))
1649
+ return reg
1650
+
1651
+
1652
+ _DEFAULT_REGISTRY: Optional[CommandRegistry] = None
1653
+
1654
+
1655
+ def default_registry() -> CommandRegistry:
1656
+ """Return the process-wide default registry (built once)."""
1657
+ global _DEFAULT_REGISTRY
1658
+ if _DEFAULT_REGISTRY is None:
1659
+ _DEFAULT_REGISTRY = build_default_registry()
1660
+ return _DEFAULT_REGISTRY
1661
+
1662
+
1663
+ def reset_default_registry() -> None:
1664
+ """Reset the process-wide default registry to ``None``.
1665
+
1666
+ Test-isolation seam: call this in teardown so the next test that calls
1667
+ ``default_registry()`` gets a freshly built registry rather than sharing
1668
+ state left by a previous test that may have registered extra commands or
1669
+ mutated the singleton.
1670
+ """
1671
+ global _DEFAULT_REGISTRY
1672
+ _DEFAULT_REGISTRY = None