@phuetz/code-buddy 1.6.0 → 2.0.0

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 (2247) hide show
  1. package/LICENSE +90 -21
  2. package/README.md +145 -349
  3. package/codebuddy-runtime.json +24 -0
  4. package/dist/advanced/session-replay.js +3 -2
  5. package/dist/agent/agent-state.d.ts +4 -1
  6. package/dist/agent/agent-state.js +9 -3
  7. package/dist/agent/architect-mode.js +1 -1
  8. package/dist/agent/autonomous/agentic-coding-contract.d.ts +28 -28
  9. package/dist/agent/autonomous/agentic-coding-runner.d.ts +14 -4
  10. package/dist/agent/autonomous/agentic-coding-runner.js +176 -27
  11. package/dist/agent/autonomous/checkpoint-manager.js +3 -12
  12. package/dist/agent/autonomous/codex-autonomy-directive.d.ts +10 -0
  13. package/dist/agent/autonomous/codex-autonomy-directive.js +25 -0
  14. package/dist/agent/autonomous/edit-proposal-producer.js +2 -2
  15. package/dist/agent/autonomous/fleet-task-types.d.ts +2 -2
  16. package/dist/agent/autonomous/fleet-task-types.js +2 -2
  17. package/dist/agent/autonomous/fleet-tick-handler.d.ts +3 -3
  18. package/dist/agent/autonomous/fleet-tick-handler.js +14 -8
  19. package/dist/agent/autonomous/recursive-improvement.d.ts +23 -0
  20. package/dist/agent/autonomous/recursive-improvement.js +114 -0
  21. package/dist/agent/autonomous/verification-loop.js +4 -2
  22. package/dist/agent/codebuddy-agent.d.ts +93 -6
  23. package/dist/agent/codebuddy-agent.js +452 -58
  24. package/dist/agent/council-lesson-proposer.d.ts +80 -13
  25. package/dist/agent/council-lesson-proposer.js +201 -43
  26. package/dist/agent/deep-research-ckg.d.ts +176 -0
  27. package/dist/agent/deep-research-ckg.js +250 -0
  28. package/dist/agent/deep-research-storm.d.ts +222 -0
  29. package/dist/agent/deep-research-storm.js +689 -0
  30. package/dist/agent/deep-research.d.ts +329 -0
  31. package/dist/agent/deep-research.js +994 -0
  32. package/dist/agent/delegation/thread-delegation.d.ts +80 -0
  33. package/dist/agent/delegation/thread-delegation.js +472 -0
  34. package/dist/agent/delegation/thread-task-runner.d.ts +37 -0
  35. package/dist/agent/delegation/thread-task-runner.js +89 -0
  36. package/dist/agent/dev-loop/dev-loop.d.ts +120 -0
  37. package/dist/agent/dev-loop/dev-loop.js +404 -0
  38. package/dist/agent/dev-loop/structural-gate.d.ts +32 -0
  39. package/dist/agent/dev-loop/structural-gate.js +120 -0
  40. package/dist/agent/execution/agent-executor.d.ts +52 -31
  41. package/dist/agent/execution/agent-executor.js +1520 -547
  42. package/dist/agent/execution/context-pipeline.d.ts +54 -6
  43. package/dist/agent/execution/context-pipeline.js +285 -88
  44. package/dist/agent/execution/incremental-token-counter.d.ts +15 -0
  45. package/dist/agent/execution/incremental-token-counter.js +36 -0
  46. package/dist/agent/execution/ordered-tool-executor.d.ts +14 -0
  47. package/dist/agent/execution/ordered-tool-executor.js +54 -0
  48. package/dist/agent/execution/post-tool-handlers.d.ts +1 -1
  49. package/dist/agent/execution/post-tool-handlers.js +2 -2
  50. package/dist/agent/execution/query-classifier.d.ts +2 -0
  51. package/dist/agent/execution/query-classifier.js +2 -0
  52. package/dist/agent/execution/tool-dependency-graph.js +7 -0
  53. package/dist/agent/execution/tool-selection-strategy.d.ts +20 -0
  54. package/dist/agent/execution/tool-selection-strategy.js +145 -23
  55. package/dist/agent/facades/message-history-manager.d.ts +1 -1
  56. package/dist/agent/facades/message-history-manager.js +1 -1
  57. package/dist/agent/facades/model-routing-facade.d.ts +31 -1
  58. package/dist/agent/facades/model-routing-facade.js +86 -2
  59. package/dist/agent/facades/session-facade.d.ts +10 -2
  60. package/dist/agent/facades/session-facade.js +59 -1
  61. package/dist/agent/film/film-producer.d.ts +98 -0
  62. package/dist/agent/film/film-producer.js +289 -0
  63. package/dist/agent/film/scene-planner.d.ts +38 -0
  64. package/dist/agent/film/scene-planner.js +93 -0
  65. package/dist/agent/film/trailer-planner.d.ts +23 -0
  66. package/dist/agent/film/trailer-planner.js +242 -0
  67. package/dist/agent/film/video-studio.d.ts +72 -0
  68. package/dist/agent/film/video-studio.js +249 -0
  69. package/dist/agent/flow/planning-flow.d.ts +3 -0
  70. package/dist/agent/flow/planning-flow.js +70 -8
  71. package/dist/agent/hermes-claw-migrate.d.ts +62 -0
  72. package/dist/agent/hermes-claw-migrate.js +189 -15
  73. package/dist/agent/hermes-memory-providers.js +3 -3
  74. package/dist/agent/hermes-parity-manifest.js +69 -15
  75. package/dist/agent/infrastructure/agent-infrastructure.d.ts +1 -0
  76. package/dist/agent/infrastructure/agent-infrastructure.js +1 -1
  77. package/dist/agent/isolation/agent-workspace.js +5 -2
  78. package/dist/agent/learning/skill-background-writes.js +9 -4
  79. package/dist/agent/learning-agent.js +4 -4
  80. package/dist/agent/learning-background-writes.js +9 -5
  81. package/dist/agent/lesson-candidate-queue.d.ts +4 -0
  82. package/dist/agent/lesson-candidate-queue.js +9 -3
  83. package/dist/agent/lesson-provenance.js +9 -3
  84. package/dist/agent/lessons-tracker.d.ts +68 -1
  85. package/dist/agent/lessons-tracker.js +218 -36
  86. package/dist/agent/loop-detection-service.d.ts +56 -0
  87. package/dist/agent/loop-detection-service.js +207 -0
  88. package/dist/agent/middleware/auto-observation.d.ts +2 -0
  89. package/dist/agent/middleware/auto-observation.js +4 -2
  90. package/dist/agent/middleware/auto-repair-middleware.d.ts +2 -0
  91. package/dist/agent/middleware/auto-repair-middleware.js +27 -4
  92. package/dist/agent/middleware/changed-files.d.ts +19 -0
  93. package/dist/agent/middleware/changed-files.js +113 -0
  94. package/dist/agent/middleware/cost-limit.d.ts +0 -2
  95. package/dist/agent/middleware/cost-limit.js +0 -3
  96. package/dist/agent/middleware/index.d.ts +2 -0
  97. package/dist/agent/middleware/index.js +1 -0
  98. package/dist/agent/middleware/pipeline.d.ts +9 -0
  99. package/dist/agent/middleware/pipeline.js +18 -0
  100. package/dist/agent/middleware/plan-completion-audit.d.ts +76 -0
  101. package/dist/agent/middleware/plan-completion-audit.js +157 -0
  102. package/dist/agent/middleware/quality-gate-middleware.d.ts +43 -1
  103. package/dist/agent/middleware/quality-gate-middleware.js +198 -40
  104. package/dist/agent/middleware/types.d.ts +6 -0
  105. package/dist/agent/middleware/verification-enforcement.d.ts +10 -3
  106. package/dist/agent/middleware/verification-enforcement.js +43 -13
  107. package/dist/agent/middleware/workflow-guard.js +7 -0
  108. package/dist/agent/model-benchmark.js +11 -17
  109. package/dist/agent/model-tier.d.ts +2 -2
  110. package/dist/agent/model-tier.js +10 -7
  111. package/dist/agent/multi-agent/agent-memory-integration.js +3 -2
  112. package/dist/agent/multi-agent/base-agent.d.ts +12 -1
  113. package/dist/agent/multi-agent/base-agent.js +58 -10
  114. package/dist/agent/multi-agent/enhanced-coordination.js +1 -0
  115. package/dist/agent/multi-agent/metrics-persistence.js +28 -14
  116. package/dist/agent/multi-agent/multi-agent-system.d.ts +5 -0
  117. package/dist/agent/multi-agent/multi-agent-system.js +81 -4
  118. package/dist/agent/multi-agent/session-fleet-bridge.js +2 -1
  119. package/dist/agent/multi-agent/session-registry.js +9 -3
  120. package/dist/agent/multi-agent/team-manager.d.ts +11 -0
  121. package/dist/agent/multi-agent/team-manager.js +94 -5
  122. package/dist/agent/multi-agent/types.d.ts +10 -1
  123. package/dist/agent/multi-agent/workflow-multi-persistence.js +16 -8
  124. package/dist/agent/multi-agent/workflow-persistence.js +9 -6
  125. package/dist/agent/observer/trigger-registry.js +3 -5
  126. package/dist/agent/operating-modes.d.ts +3 -0
  127. package/dist/agent/operating-modes.js +15 -22
  128. package/dist/agent/pipelines.d.ts +2 -4
  129. package/dist/agent/pipelines.js +1 -1
  130. package/dist/agent/plan-mode.js +1 -1
  131. package/dist/agent/prompt-suggestions.js +2 -1
  132. package/dist/agent/prompt-tool-observation.d.ts +55 -0
  133. package/dist/agent/prompt-tool-observation.js +165 -0
  134. package/dist/agent/reasoning/tree-of-thought.js +1 -1
  135. package/dist/agent/repair/repair-engine.js +1 -1
  136. package/dist/agent/repo-profiler.d.ts +12 -1
  137. package/dist/agent/repo-profiler.js +21 -15
  138. package/dist/agent/repo-profiling/cache.js +6 -9
  139. package/dist/agent/research-worker-provider.d.ts +38 -0
  140. package/dist/agent/research-worker-provider.js +30 -0
  141. package/dist/agent/science/experiment-decision.d.ts +48 -0
  142. package/dist/agent/science/experiment-decision.js +65 -0
  143. package/dist/agent/science/experiment-empirical-gate.d.ts +83 -0
  144. package/dist/agent/science/experiment-empirical-gate.js +156 -0
  145. package/dist/agent/science/experiment-fitness.d.ts +112 -0
  146. package/dist/agent/science/experiment-fitness.js +188 -0
  147. package/dist/agent/science/experiment-loop.d.ts +196 -0
  148. package/dist/agent/science/experiment-loop.js +765 -0
  149. package/dist/agent/science/experiment-orchestrator.d.ts +203 -0
  150. package/dist/agent/science/experiment-orchestrator.js +454 -0
  151. package/dist/agent/science/experiment-sandbox-backends.d.ts +56 -0
  152. package/dist/agent/science/experiment-sandbox-backends.js +201 -0
  153. package/dist/agent/science/experiment-sandbox.d.ts +105 -0
  154. package/dist/agent/science/experiment-sandbox.js +196 -0
  155. package/dist/agent/science/experiment-variant-store.d.ts +108 -0
  156. package/dist/agent/science/experiment-variant-store.js +156 -0
  157. package/dist/agent/science/human-gate.d.ts +31 -0
  158. package/dist/agent/science/human-gate.js +32 -0
  159. package/dist/agent/self-improvement/authored-artifact-gate.js +28 -3
  160. package/dist/agent/self-improvement/authored-tool-runtime.d.ts +4 -2
  161. package/dist/agent/self-improvement/authored-tool-runtime.js +8 -3
  162. package/dist/agent/self-improvement/authored-tool-store.js +3 -2
  163. package/dist/agent/self-improvement/capability-benchmark.js +89 -2
  164. package/dist/agent/self-improvement/continuous-benchmark.d.ts +105 -0
  165. package/dist/agent/self-improvement/continuous-benchmark.js +355 -0
  166. package/dist/agent/self-improvement/delegation-facts.d.ts +105 -0
  167. package/dist/agent/self-improvement/delegation-facts.js +483 -0
  168. package/dist/agent/self-improvement/digest-sources.d.ts +56 -0
  169. package/dist/agent/self-improvement/digest-sources.js +294 -0
  170. package/dist/agent/self-improvement/digest.d.ts +169 -0
  171. package/dist/agent/self-improvement/digest.js +543 -0
  172. package/dist/agent/self-improvement/engine.d.ts +11 -6
  173. package/dist/agent/self-improvement/engine.js +13 -7
  174. package/dist/agent/self-improvement/evolution/ast-novelty.d.ts +20 -0
  175. package/dist/agent/self-improvement/evolution/ast-novelty.js +81 -0
  176. package/dist/agent/self-improvement/evolution/code-variant-store.d.ts +101 -0
  177. package/dist/agent/self-improvement/evolution/code-variant-store.js +229 -0
  178. package/dist/agent/self-improvement/evolution/evolution-engine.d.ts +199 -0
  179. package/dist/agent/self-improvement/evolution/evolution-engine.js +503 -0
  180. package/dist/agent/self-improvement/evolution/feature-map.d.ts +24 -0
  181. package/dist/agent/self-improvement/evolution/feature-map.js +88 -0
  182. package/dist/agent/self-improvement/evolution/model-bandit.d.ts +57 -0
  183. package/dist/agent/self-improvement/evolution/model-bandit.js +98 -0
  184. package/dist/agent/self-improvement/evolution/protected-paths.d.ts +31 -0
  185. package/dist/agent/self-improvement/evolution/protected-paths.js +105 -0
  186. package/dist/agent/self-improvement/evolution/research-weakness-source.d.ts +56 -0
  187. package/dist/agent/self-improvement/evolution/research-weakness-source.js +161 -0
  188. package/dist/agent/self-improvement/evolution/scrub-env.d.ts +22 -0
  189. package/dist/agent/self-improvement/evolution/scrub-env.js +40 -0
  190. package/dist/agent/self-improvement/evolution/variant-fitness.d.ts +86 -0
  191. package/dist/agent/self-improvement/evolution/variant-fitness.js +217 -0
  192. package/dist/agent/self-improvement/evolution/variant-planner.d.ts +41 -0
  193. package/dist/agent/self-improvement/evolution/variant-planner.js +156 -0
  194. package/dist/agent/self-improvement/evolution/weakness-selector.d.ts +38 -0
  195. package/dist/agent/self-improvement/evolution/weakness-selector.js +108 -0
  196. package/dist/agent/self-improvement/evolution/worktree-scorer.d.ts +44 -0
  197. package/dist/agent/self-improvement/evolution/worktree-scorer.js +99 -0
  198. package/dist/agent/self-improvement/evolutionary-archive.js +3 -2
  199. package/dist/agent/self-improvement/experience-source.d.ts +60 -7
  200. package/dist/agent/self-improvement/experience-source.js +78 -8
  201. package/dist/agent/self-improvement/index.d.ts +1 -0
  202. package/dist/agent/self-improvement/index.js +6 -3
  203. package/dist/agent/self-improvement/learning-store.d.ts +16 -0
  204. package/dist/agent/self-improvement/learning-store.js +83 -3
  205. package/dist/agent/self-improvement/llm-drafter.d.ts +3 -1
  206. package/dist/agent/self-improvement/llm-drafter.js +20 -2
  207. package/dist/agent/self-improvement/llm-tool-proposer.js +1 -1
  208. package/dist/agent/self-improvement/proposal-store.d.ts +46 -0
  209. package/dist/agent/self-improvement/proposal-store.js +87 -0
  210. package/dist/agent/self-improvement/proposer.d.ts +1 -1
  211. package/dist/agent/self-improvement/proposer.js +94 -2
  212. package/dist/agent/self-improvement/rule-store.js +5 -4
  213. package/dist/agent/self-improvement/sandbox-scorer.d.ts +1 -1
  214. package/dist/agent/self-improvement/sandbox-scorer.js +8 -4
  215. package/dist/agent/self-improvement/self-knowledge.d.ts +1 -1
  216. package/dist/agent/self-improvement/self-knowledge.js +8 -8
  217. package/dist/agent/self-improvement/skill-benchmark.js +27 -0
  218. package/dist/agent/self-improvement/skill-consolidator.js +16 -0
  219. package/dist/agent/self-improvement/skill-engine.d.ts +7 -0
  220. package/dist/agent/self-improvement/skill-engine.js +54 -28
  221. package/dist/agent/self-improvement/skill-gate.d.ts +4 -4
  222. package/dist/agent/self-improvement/skill-gate.js +38 -20
  223. package/dist/agent/self-improvement/skill-mutator.d.ts +20 -1
  224. package/dist/agent/self-improvement/skill-mutator.js +138 -19
  225. package/dist/agent/self-improvement/skill-proposer.js +2 -1
  226. package/dist/agent/self-improvement/skill-types.d.ts +4 -0
  227. package/dist/agent/self-improvement/strategy-engine.d.ts +54 -0
  228. package/dist/agent/self-improvement/strategy-engine.js +104 -0
  229. package/dist/agent/self-improvement/strategy-gate.d.ts +49 -0
  230. package/dist/agent/self-improvement/strategy-gate.js +243 -0
  231. package/dist/agent/self-improvement/strategy-live.d.ts +39 -0
  232. package/dist/agent/self-improvement/strategy-live.js +114 -0
  233. package/dist/agent/self-improvement/strategy-proposer.d.ts +30 -0
  234. package/dist/agent/self-improvement/strategy-proposer.js +114 -0
  235. package/dist/agent/self-improvement/strategy-replay.d.ts +40 -0
  236. package/dist/agent/self-improvement/strategy-replay.js +150 -0
  237. package/dist/agent/self-improvement/strategy-runtime.d.ts +43 -0
  238. package/dist/agent/self-improvement/strategy-runtime.js +56 -0
  239. package/dist/agent/self-improvement/strategy-store.d.ts +38 -0
  240. package/dist/agent/self-improvement/strategy-store.js +139 -0
  241. package/dist/agent/self-improvement/strategy-types.d.ts +229 -0
  242. package/dist/agent/self-improvement/strategy-types.js +90 -0
  243. package/dist/agent/self-improvement/tool-benchmark.js +164 -8
  244. package/dist/agent/self-improvement/tool-engine.d.ts +12 -3
  245. package/dist/agent/self-improvement/tool-engine.js +59 -31
  246. package/dist/agent/self-improvement/tool-gate.d.ts +2 -0
  247. package/dist/agent/self-improvement/tool-gate.js +26 -0
  248. package/dist/agent/self-improvement/tool-skill-mutator.d.ts +1 -1
  249. package/dist/agent/self-improvement/tool-skill-mutator.js +20 -2
  250. package/dist/agent/self-improvement/tool-types.d.ts +5 -3
  251. package/dist/agent/self-improvement/types.d.ts +7 -3
  252. package/dist/agent/session-end-flush.js +2 -1
  253. package/dist/agent/specialized/agent-registry.d.ts +1 -0
  254. package/dist/agent/specialized/agent-registry.js +118 -0
  255. package/dist/agent/specialized/excel-agent.js +15 -1
  256. package/dist/agent/specialized/index.d.ts +1 -0
  257. package/dist/agent/specialized/index.js +2 -0
  258. package/dist/agent/specialized/pdf-agent.js +4 -2
  259. package/dist/agent/specialized/swe-agent-adapter.js +8 -0
  260. package/dist/agent/specialized/swe-agent.d.ts +16 -1
  261. package/dist/agent/specialized/swe-agent.js +75 -7
  262. package/dist/agent/specialized/types.d.ts +31 -1
  263. package/dist/agent/specialized/types.js +26 -0
  264. package/dist/agent/specialized/verifier-agent.d.ts +53 -0
  265. package/dist/agent/specialized/verifier-agent.js +342 -0
  266. package/dist/agent/streaming/message-reducer.js +73 -19
  267. package/dist/agent/streaming/streaming-handler.d.ts +24 -0
  268. package/dist/agent/streaming/streaming-handler.js +136 -1
  269. package/dist/agent/subagents.d.ts +10 -4
  270. package/dist/agent/subagents.js +39 -6
  271. package/dist/agent/thinking/extended-thinking.js +1 -1
  272. package/dist/agent/todo-tracker.js +5 -4
  273. package/dist/agent/tool-executor.d.ts +10 -1
  274. package/dist/agent/tool-executor.js +29 -0
  275. package/dist/agent/tool-handler.d.ts +49 -2
  276. package/dist/agent/tool-handler.js +738 -181
  277. package/dist/agent/types.d.ts +3 -5
  278. package/dist/agent/wide-research-checkpoint.d.ts +77 -0
  279. package/dist/agent/wide-research-checkpoint.js +361 -0
  280. package/dist/agent/wide-research-files.d.ts +11 -0
  281. package/dist/agent/wide-research-files.js +189 -0
  282. package/dist/agent/wide-research.d.ts +148 -3
  283. package/dist/agent/wide-research.js +833 -56
  284. package/dist/analytics/code-evolution.js +20 -15
  285. package/dist/analytics/complexity-analyzer.js +2 -2
  286. package/dist/analytics/cost-report.d.ts +71 -0
  287. package/dist/analytics/cost-report.js +724 -0
  288. package/dist/analytics/dashboard.js +8 -7
  289. package/dist/analytics/index.d.ts +2 -0
  290. package/dist/analytics/index.js +2 -0
  291. package/dist/analytics/repo-explainer-collector.d.ts +13 -0
  292. package/dist/analytics/repo-explainer-collector.js +351 -0
  293. package/dist/analytics/repo-explainer.d.ts +224 -0
  294. package/dist/analytics/repo-explainer.js +605 -0
  295. package/dist/analytics/roi-tracker.js +11 -9
  296. package/dist/api/webhooks.js +9 -14
  297. package/dist/app/application-factory.d.ts +1 -1
  298. package/dist/app/application-factory.js +6 -5
  299. package/dist/auth/profile-manager.js +8 -4
  300. package/dist/avatar/avatar-event-bus.d.ts +16 -0
  301. package/dist/avatar/avatar-event-bus.js +53 -0
  302. package/dist/avatar/avatar-gateway-bridge.d.ts +26 -0
  303. package/dist/avatar/avatar-gateway-bridge.js +54 -0
  304. package/dist/avatar/avatar-protocol.d.ts +133 -0
  305. package/dist/avatar/avatar-protocol.js +241 -0
  306. package/dist/avatar/avatar-renderer-registry.d.ts +56 -0
  307. package/dist/avatar/avatar-renderer-registry.js +191 -0
  308. package/dist/avatar/avatar-renderer-simulator.d.ts +31 -0
  309. package/dist/avatar/avatar-renderer-simulator.js +160 -0
  310. package/dist/browser-automation/browser-manager.d.ts +15 -1
  311. package/dist/browser-automation/browser-manager.js +101 -0
  312. package/dist/browser-automation/browser-operator-executor.d.ts +89 -7
  313. package/dist/browser-automation/browser-operator-executor.js +1280 -58
  314. package/dist/browser-automation/browser-operator-runtime.d.ts +87 -0
  315. package/dist/browser-automation/browser-operator-runtime.js +441 -0
  316. package/dist/browser-automation/browser-operator-session.js +4 -3
  317. package/dist/browser-automation/browser-tool.d.ts +17 -2
  318. package/dist/browser-automation/browser-tool.js +101 -39
  319. package/dist/browser-automation/internet-scout-plan.d.ts +1 -0
  320. package/dist/browser-automation/internet-scout-plan.js +17 -0
  321. package/dist/browser-automation/profile-manager.js +5 -3
  322. package/dist/browser-automation/types.d.ts +25 -0
  323. package/dist/cache/advanced-lru-cache.js +4 -4
  324. package/dist/cache/cache-manager.js +9 -10
  325. package/dist/cache/embedding-cache.js +6 -5
  326. package/dist/cache/llm-response-cache.js +3 -4
  327. package/dist/capture/screen-recorder.d.ts +2 -0
  328. package/dist/capture/screen-recorder.js +6 -4
  329. package/dist/capture/screen-watcher.d.ts +6 -3
  330. package/dist/capture/screen-watcher.js +86 -9
  331. package/dist/channels/channel-cognitive-port.d.ts +46 -0
  332. package/dist/channels/channel-cognitive-port.js +182 -0
  333. package/dist/channels/channel-model-override.d.ts +47 -0
  334. package/dist/channels/channel-model-override.js +62 -0
  335. package/dist/channels/companion-channel-profile.d.ts +68 -0
  336. package/dist/channels/companion-channel-profile.js +142 -0
  337. package/dist/channels/companion-channel-turn.d.ts +30 -0
  338. package/dist/channels/companion-channel-turn.js +38 -0
  339. package/dist/channels/core.d.ts +37 -3
  340. package/dist/channels/core.js +63 -6
  341. package/dist/channels/discord/client.js +34 -14
  342. package/dist/channels/dm-pairing.d.ts +18 -4
  343. package/dist/channels/dm-pairing.js +199 -33
  344. package/dist/channels/gateway-lifecycle.d.ts +2 -0
  345. package/dist/channels/gateway-lifecycle.js +1 -0
  346. package/dist/channels/identity-links.d.ts +19 -1
  347. package/dist/channels/identity-links.js +68 -12
  348. package/dist/channels/matrix/index.js +6 -2
  349. package/dist/channels/pro/pro-features.js +17 -0
  350. package/dist/channels/pro/run-tracker.js +9 -4
  351. package/dist/channels/pro/scoped-auth.js +10 -8
  352. package/dist/channels/provider-failure-speech.d.ts +28 -0
  353. package/dist/channels/provider-failure-speech.js +128 -0
  354. package/dist/channels/reconnection-manager.d.ts +2 -0
  355. package/dist/channels/reconnection-manager.js +7 -2
  356. package/dist/channels/resolve-channel-secret.d.ts +43 -0
  357. package/dist/channels/resolve-channel-secret.js +82 -0
  358. package/dist/channels/slack/block-builder.d.ts +12 -0
  359. package/dist/channels/slack/block-builder.js +70 -2
  360. package/dist/channels/slack/client.js +62 -15
  361. package/dist/channels/slack/types.d.ts +20 -1
  362. package/dist/channels/telegram/client.d.ts +36 -3
  363. package/dist/channels/telegram/client.js +438 -84
  364. package/dist/channels/telegram/types.d.ts +2 -0
  365. package/dist/channels/webhook-server.js +8 -1
  366. package/dist/channels/whatsapp/index.js +2 -1
  367. package/dist/checkpoints/ghost-snapshot.js +15 -9
  368. package/dist/checkpoints/persistent-checkpoint-manager.js +15 -8
  369. package/dist/cli/command-routing.d.ts +22 -0
  370. package/dist/cli/command-routing.js +54 -0
  371. package/dist/cli/first-run.d.ts +17 -0
  372. package/dist/cli/first-run.js +40 -0
  373. package/dist/cli/headless-options.d.ts +22 -0
  374. package/dist/cli/headless-options.js +112 -0
  375. package/dist/cli/headless-prompt-progress.d.ts +22 -0
  376. package/dist/cli/headless-prompt-progress.js +35 -0
  377. package/dist/cli/headless.js +2 -2
  378. package/dist/cli/listen-port.d.ts +8 -0
  379. package/dist/cli/listen-port.js +20 -0
  380. package/dist/cli/permission-mode-option.d.ts +14 -0
  381. package/dist/cli/permission-mode-option.js +64 -0
  382. package/dist/cli/requested-profile.d.ts +15 -0
  383. package/dist/cli/requested-profile.js +27 -0
  384. package/dist/cli/unknown-option-hint.d.ts +16 -0
  385. package/dist/cli/unknown-option-hint.js +116 -0
  386. package/dist/cli/voice-command.d.ts +32 -0
  387. package/dist/cli/voice-command.js +96 -0
  388. package/dist/codebuddy/abort-signal.d.ts +7 -0
  389. package/dist/codebuddy/abort-signal.js +31 -0
  390. package/dist/codebuddy/client.d.ts +68 -0
  391. package/dist/codebuddy/client.js +460 -11
  392. package/dist/codebuddy/fleet-tool-defs.js +5 -0
  393. package/dist/codebuddy/llm-retry.d.ts +24 -0
  394. package/dist/codebuddy/llm-retry.js +124 -0
  395. package/dist/codebuddy/provider-error-classifier.d.ts +86 -0
  396. package/dist/codebuddy/provider-error-classifier.js +410 -0
  397. package/dist/codebuddy/provider-failover-error.d.ts +16 -0
  398. package/dist/codebuddy/provider-failover-error.js +50 -0
  399. package/dist/codebuddy/provider-failover-kind.d.ts +15 -0
  400. package/dist/codebuddy/provider-failover-kind.js +172 -0
  401. package/dist/codebuddy/provider-handoff.d.ts +35 -0
  402. package/dist/codebuddy/provider-handoff.js +294 -0
  403. package/dist/codebuddy/providers/ollama-native-transport.d.ts +130 -0
  404. package/dist/codebuddy/providers/ollama-native-transport.js +387 -0
  405. package/dist/codebuddy/providers/provider-agy-cli.d.ts +29 -0
  406. package/dist/codebuddy/providers/provider-agy-cli.js +264 -0
  407. package/dist/codebuddy/providers/provider-chatgpt-responses.d.ts +59 -7
  408. package/dist/codebuddy/providers/provider-chatgpt-responses.js +519 -164
  409. package/dist/codebuddy/providers/provider-gemini-cli.js +95 -13
  410. package/dist/codebuddy/providers/provider-gemini-native.d.ts +2 -0
  411. package/dist/codebuddy/providers/provider-gemini-native.js +199 -86
  412. package/dist/codebuddy/providers/provider-openai-compat.d.ts +82 -0
  413. package/dist/codebuddy/providers/provider-openai-compat.js +469 -45
  414. package/dist/codebuddy/stream-retry.d.ts +21 -8
  415. package/dist/codebuddy/stream-retry.js +44 -40
  416. package/dist/codebuddy/tool-definitions/advanced-tools.d.ts +4 -0
  417. package/dist/codebuddy/tool-definitions/advanced-tools.js +188 -0
  418. package/dist/codebuddy/tool-definitions/agent-tools.d.ts +5 -0
  419. package/dist/codebuddy/tool-definitions/agent-tools.js +195 -7
  420. package/dist/codebuddy/tool-definitions/browser-tools.d.ts +1 -0
  421. package/dist/codebuddy/tool-definitions/browser-tools.js +65 -1
  422. package/dist/codebuddy/tool-definitions/code-exec-tools.d.ts +8 -0
  423. package/dist/codebuddy/tool-definitions/code-exec-tools.js +29 -0
  424. package/dist/codebuddy/tool-definitions/code-explorer-tools.js +4 -0
  425. package/dist/codebuddy/tool-definitions/comfy-recipe-tools.d.ts +3 -0
  426. package/dist/codebuddy/tool-definitions/comfy-recipe-tools.js +37 -0
  427. package/dist/codebuddy/tool-definitions/core-tools.d.ts +2 -0
  428. package/dist/codebuddy/tool-definitions/core-tools.js +58 -2
  429. package/dist/codebuddy/tool-definitions/delegate-agent-tools.d.ts +11 -0
  430. package/dist/codebuddy/tool-definitions/delegate-agent-tools.js +50 -0
  431. package/dist/codebuddy/tool-definitions/design-tools.d.ts +6 -0
  432. package/dist/codebuddy/tool-definitions/design-tools.js +35 -0
  433. package/dist/codebuddy/tool-definitions/exit-plan-mode-tools.d.ts +1 -0
  434. package/dist/codebuddy/tool-definitions/exit-plan-mode-tools.js +23 -1
  435. package/dist/codebuddy/tool-definitions/index.d.ts +16 -7
  436. package/dist/codebuddy/tool-definitions/index.js +27 -8
  437. package/dist/codebuddy/tool-definitions/lsp-tools.d.ts +7 -1
  438. package/dist/codebuddy/tool-definitions/lsp-tools.js +104 -1
  439. package/dist/codebuddy/tool-definitions/meeting-tools.d.ts +4 -0
  440. package/dist/codebuddy/tool-definitions/meeting-tools.js +32 -0
  441. package/dist/codebuddy/tool-definitions/moa-tools.js +7 -2
  442. package/dist/codebuddy/tool-definitions/multimodal-tools.d.ts +14 -0
  443. package/dist/codebuddy/tool-definitions/multimodal-tools.js +615 -3
  444. package/dist/codebuddy/tool-definitions/research-tools.d.ts +20 -0
  445. package/dist/codebuddy/tool-definitions/research-tools.js +98 -0
  446. package/dist/codebuddy/tool-definitions/self-describe-tools.d.ts +4 -0
  447. package/dist/codebuddy/tool-definitions/self-describe-tools.js +28 -0
  448. package/dist/codebuddy/tool-definitions/self-evolution-tools.d.ts +4 -0
  449. package/dist/codebuddy/tool-definitions/self-evolution-tools.js +31 -0
  450. package/dist/codebuddy/tool-definitions/verify-tools.d.ts +14 -0
  451. package/dist/codebuddy/tool-definitions/verify-tools.js +36 -0
  452. package/dist/codebuddy/tool-definitions/web-tools.d.ts +4 -0
  453. package/dist/codebuddy/tool-definitions/web-tools.js +135 -0
  454. package/dist/codebuddy/tool-definitions/workspace-tools.d.ts +4 -0
  455. package/dist/codebuddy/tool-definitions/workspace-tools.js +43 -0
  456. package/dist/codebuddy/tools.d.ts +15 -17
  457. package/dist/codebuddy/tools.js +235 -55
  458. package/dist/cognition/budget-reservations.d.ts +27 -0
  459. package/dist/cognition/budget-reservations.js +70 -0
  460. package/dist/cognition/cognitive-bus-client.d.ts +94 -0
  461. package/dist/cognition/cognitive-bus-client.js +724 -0
  462. package/dist/cognition/cognitive-hub.d.ts +93 -0
  463. package/dist/cognition/cognitive-hub.js +366 -0
  464. package/dist/cognition/cognitive-mesh.d.ts +38 -0
  465. package/dist/cognition/cognitive-mesh.js +263 -0
  466. package/dist/cognition/cognitive-port.d.ts +35 -0
  467. package/dist/cognition/cognitive-port.js +80 -0
  468. package/dist/cognition/cognitive-wire-contract.d.ts +1542 -0
  469. package/dist/cognition/cognitive-wire-contract.js +164 -0
  470. package/dist/cognition/context-renderer.d.ts +52 -0
  471. package/dist/cognition/context-renderer.js +227 -0
  472. package/dist/cognition/global-workspace.d.ts +39 -0
  473. package/dist/cognition/global-workspace.js +181 -0
  474. package/dist/cognition/index.d.ts +9 -0
  475. package/dist/cognition/index.js +10 -0
  476. package/dist/cognition/llm-specialist.d.ts +40 -0
  477. package/dist/cognition/llm-specialist.js +93 -0
  478. package/dist/cognition/sensory-workspace.d.ts +57 -0
  479. package/dist/cognition/sensory-workspace.js +346 -0
  480. package/dist/cognition/types.d.ts +93 -0
  481. package/dist/cognition/types.js +7 -0
  482. package/dist/cognition/voice-specialists.d.ts +21 -0
  483. package/dist/cognition/voice-specialists.js +89 -0
  484. package/dist/cognition/world-model.d.ts +95 -0
  485. package/dist/cognition/world-model.js +228 -0
  486. package/dist/collaboration/ai-colab-manager.js +12 -13
  487. package/dist/collaboration/team-session.js +25 -11
  488. package/dist/commands/apply-permission-mode.d.ts +27 -0
  489. package/dist/commands/apply-permission-mode.js +35 -0
  490. package/dist/commands/assistant.d.ts +3 -0
  491. package/dist/commands/assistant.js +1022 -0
  492. package/dist/commands/campaign.d.ts +6 -0
  493. package/dist/commands/campaign.js +140 -0
  494. package/dist/commands/capsule.d.ts +2 -0
  495. package/dist/commands/capsule.js +104 -0
  496. package/dist/commands/changelog.d.ts +29 -0
  497. package/dist/commands/changelog.js +283 -0
  498. package/dist/commands/cli/acp-command.js +4 -1
  499. package/dist/commands/cli/backup-command.d.ts +9 -0
  500. package/dist/commands/cli/backup-command.js +47 -0
  501. package/dist/commands/cli/evolve-command.d.ts +26 -0
  502. package/dist/commands/cli/evolve-command.js +259 -0
  503. package/dist/commands/cli/fleet-commands.js +105 -0
  504. package/dist/commands/cli/improve-command.d.ts +2 -1
  505. package/dist/commands/cli/improve-command.js +309 -20
  506. package/dist/commands/cli/native-engine-commands.js +405 -28
  507. package/dist/commands/cli/sensory-command.d.ts +8 -0
  508. package/dist/commands/cli/sensory-command.js +27 -0
  509. package/dist/commands/cli/speak-command.js +87 -24
  510. package/dist/commands/cli/tools-commands.js +68 -36
  511. package/dist/commands/cli/utility-commands.js +34 -9
  512. package/dist/commands/client-dispatcher.d.ts +1 -0
  513. package/dist/commands/client-dispatcher.js +40 -21
  514. package/dist/commands/compress.js +3 -0
  515. package/dist/commands/cost.d.ts +33 -0
  516. package/dist/commands/cost.js +342 -0
  517. package/dist/commands/council-scoreboard.d.ts +8 -0
  518. package/dist/commands/council-scoreboard.js +68 -0
  519. package/dist/commands/council.d.ts +16 -24
  520. package/dist/commands/council.js +247 -255
  521. package/dist/commands/curator-cli.d.ts +14 -0
  522. package/dist/commands/curator-cli.js +57 -0
  523. package/dist/commands/delegate.js +82 -25
  524. package/dist/commands/dev/golden-path.d.ts +71 -0
  525. package/dist/commands/dev/golden-path.js +317 -0
  526. package/dist/commands/dev/index.d.ts +3 -0
  527. package/dist/commands/dev/index.js +151 -119
  528. package/dist/commands/dev/issue-pipeline.js +7 -7
  529. package/dist/commands/dev/workflows.d.ts +2 -0
  530. package/dist/commands/dev/workflows.js +39 -6
  531. package/dist/commands/enhanced-command-handler.d.ts +3 -0
  532. package/dist/commands/enhanced-command-handler.js +29 -12
  533. package/dist/commands/exchange.d.ts +2 -0
  534. package/dist/commands/exchange.js +193 -0
  535. package/dist/commands/explain.d.ts +12 -0
  536. package/dist/commands/explain.js +135 -0
  537. package/dist/commands/film.d.ts +18 -0
  538. package/dist/commands/film.js +239 -0
  539. package/dist/commands/flow.js +15 -5
  540. package/dist/commands/forge.d.ts +2 -0
  541. package/dist/commands/forge.js +102 -0
  542. package/dist/commands/goal-cli.d.ts +3 -0
  543. package/dist/commands/goal-cli.js +9 -4
  544. package/dist/commands/gpu-worker.d.ts +14 -0
  545. package/dist/commands/gpu-worker.js +135 -0
  546. package/dist/commands/handlers/agents-handler.d.ts +11 -2
  547. package/dist/commands/handlers/agents-handler.js +79 -13
  548. package/dist/commands/handlers/auth-handlers.js +12 -5
  549. package/dist/commands/handlers/backup-handlers.d.ts +40 -0
  550. package/dist/commands/handlers/backup-handlers.js +784 -57
  551. package/dist/commands/handlers/batch-handlers.d.ts +72 -2
  552. package/dist/commands/handlers/batch-handlers.js +443 -37
  553. package/dist/commands/handlers/branch-handlers.d.ts +1 -0
  554. package/dist/commands/handlers/channel-handlers.d.ts +7 -2
  555. package/dist/commands/handlers/channel-handlers.js +1705 -103
  556. package/dist/commands/handlers/companion-handler.js +130 -9
  557. package/dist/commands/handlers/daily-reset-handler.d.ts +1 -1
  558. package/dist/commands/handlers/daily-reset-handler.js +1 -1
  559. package/dist/commands/handlers/deepthink-handler.d.ts +2 -0
  560. package/dist/commands/handlers/deepthink-handler.js +49 -0
  561. package/dist/commands/handlers/extra-handlers.js +23 -24
  562. package/dist/commands/handlers/fleet-handler.d.ts +3 -4
  563. package/dist/commands/handlers/fleet-handler.js +82 -35
  564. package/dist/commands/handlers/goal-handler.d.ts +13 -0
  565. package/dist/commands/handlers/goal-handler.js +26 -7
  566. package/dist/commands/handlers/grill-me-handler.d.ts +2 -0
  567. package/dist/commands/handlers/grill-me-handler.js +41 -0
  568. package/dist/commands/handlers/heartbeat-handler.d.ts +2 -2
  569. package/dist/commands/handlers/heartbeat-handler.js +2 -2
  570. package/dist/commands/handlers/index.d.ts +3 -2
  571. package/dist/commands/handlers/index.js +4 -2
  572. package/dist/commands/handlers/memory-handlers.js +40 -0
  573. package/dist/commands/handlers/permissions-handlers.js +3 -2
  574. package/dist/commands/handlers/pr-handlers.js +15 -17
  575. package/dist/commands/handlers/security-handlers.d.ts +1 -1
  576. package/dist/commands/handlers/security-handlers.js +3 -3
  577. package/dist/commands/handlers/slash-session-handlers.d.ts +9 -0
  578. package/dist/commands/handlers/slash-session-handlers.js +134 -0
  579. package/dist/commands/handlers/swarm-handler.js +41 -2
  580. package/dist/commands/handlers/team-handlers.d.ts +28 -1
  581. package/dist/commands/handlers/team-handlers.js +243 -2
  582. package/dist/commands/handlers/think-handlers.js +2 -1
  583. package/dist/commands/handlers/vibe-handlers.js +8 -1
  584. package/dist/commands/handlers/worktree-handlers.js +23 -12
  585. package/dist/commands/headless-slash.d.ts +9 -0
  586. package/dist/commands/headless-slash.js +41 -3
  587. package/dist/commands/import.d.ts +34 -0
  588. package/dist/commands/import.js +478 -0
  589. package/dist/commands/index.d.ts +0 -1
  590. package/dist/commands/index.js +0 -1
  591. package/dist/commands/influencer.d.ts +2 -0
  592. package/dist/commands/influencer.js +87 -0
  593. package/dist/commands/intent.d.ts +6 -0
  594. package/dist/commands/intent.js +131 -0
  595. package/dist/commands/intents.d.ts +10 -0
  596. package/dist/commands/intents.js +163 -0
  597. package/dist/commands/lessons.js +91 -0
  598. package/dist/commands/llm-provider-resolution.d.ts +20 -0
  599. package/dist/commands/llm-provider-resolution.js +74 -13
  600. package/dist/commands/login-prerequisites.d.ts +11 -0
  601. package/dist/commands/login-prerequisites.js +23 -0
  602. package/dist/commands/loop-cli.d.ts +31 -0
  603. package/dist/commands/loop-cli.js +189 -0
  604. package/dist/commands/lora.d.ts +6 -0
  605. package/dist/commands/lora.js +445 -0
  606. package/dist/commands/maison-food.d.ts +10 -0
  607. package/dist/commands/maison-food.js +485 -0
  608. package/dist/commands/maison.d.ts +17 -0
  609. package/dist/commands/maison.js +236 -0
  610. package/dist/commands/mcp.d.ts +6 -0
  611. package/dist/commands/mcp.js +236 -7
  612. package/dist/commands/meeting.d.ts +8 -0
  613. package/dist/commands/meeting.js +31 -0
  614. package/dist/commands/pairing.js +7 -8
  615. package/dist/commands/papers/ask.d.ts +47 -0
  616. package/dist/commands/papers/ask.js +105 -0
  617. package/dist/commands/papers/index.d.ts +19 -0
  618. package/dist/commands/papers/index.js +54 -0
  619. package/dist/commands/provider.d.ts +9 -0
  620. package/dist/commands/provider.js +178 -10
  621. package/dist/commands/replay.d.ts +11 -0
  622. package/dist/commands/replay.js +131 -0
  623. package/dist/commands/research/deep.d.ts +66 -0
  624. package/dist/commands/research/deep.js +236 -0
  625. package/dist/commands/research/discover-searxng.d.ts +25 -0
  626. package/dist/commands/research/discover-searxng.js +62 -0
  627. package/dist/commands/research/index.d.ts +24 -2
  628. package/dist/commands/research/index.js +456 -79
  629. package/dist/commands/research/knowledge-ingest.d.ts +170 -0
  630. package/dist/commands/research/knowledge-ingest.js +449 -0
  631. package/dist/commands/research/wire-research-worker.d.ts +9 -0
  632. package/dist/commands/research/wire-research-worker.js +18 -0
  633. package/dist/commands/run-cli/index.d.ts +3 -1
  634. package/dist/commands/run-cli/index.js +53 -2
  635. package/dist/commands/science/deps.d.ts +95 -0
  636. package/dist/commands/science/deps.js +343 -0
  637. package/dist/commands/science/index.d.ts +31 -0
  638. package/dist/commands/science/index.js +285 -0
  639. package/dist/commands/science/loop-option.d.ts +40 -0
  640. package/dist/commands/science/loop-option.js +91 -0
  641. package/dist/commands/science/sandbox-option.d.ts +44 -0
  642. package/dist/commands/science/sandbox-option.js +42 -0
  643. package/dist/commands/scrape.d.ts +18 -0
  644. package/dist/commands/scrape.js +159 -0
  645. package/dist/commands/self.d.ts +9 -0
  646. package/dist/commands/self.js +56 -0
  647. package/dist/commands/shadow.d.ts +3 -0
  648. package/dist/commands/shadow.js +72 -0
  649. package/dist/commands/share.d.ts +13 -0
  650. package/dist/commands/share.js +71 -0
  651. package/dist/commands/shell-prefix.d.ts +4 -22
  652. package/dist/commands/shell-prefix.js +11 -73
  653. package/dist/commands/skills-cli/index.d.ts +2 -0
  654. package/dist/commands/skills-cli/index.js +190 -15
  655. package/dist/commands/slash/builtin-commands.js +41 -21
  656. package/dist/commands/slash-commands.js +4 -1
  657. package/dist/commands/token.d.ts +80 -0
  658. package/dist/commands/token.js +319 -0
  659. package/dist/commands/try.d.ts +72 -0
  660. package/dist/commands/try.js +357 -0
  661. package/dist/commands/update.d.ts +14 -1
  662. package/dist/commands/update.js +97 -15
  663. package/dist/commands/vision-train.d.ts +15 -0
  664. package/dist/commands/vision-train.js +214 -0
  665. package/dist/commands/whoami-status.d.ts +17 -0
  666. package/dist/commands/whoami-status.js +34 -0
  667. package/dist/commands/widgets.d.ts +2 -0
  668. package/dist/commands/widgets.js +179 -0
  669. package/dist/commands/ws.d.ts +7 -0
  670. package/dist/commands/ws.js +100 -0
  671. package/dist/companion/assistant-config.d.ts +79 -0
  672. package/dist/companion/assistant-config.js +1148 -0
  673. package/dist/companion/attached-image-grounding.d.ts +29 -0
  674. package/dist/companion/attached-image-grounding.js +285 -0
  675. package/dist/companion/away-mode.d.ts +80 -0
  676. package/dist/companion/away-mode.js +269 -0
  677. package/dist/companion/camera-share.d.ts +65 -0
  678. package/dist/companion/camera-share.js +321 -0
  679. package/dist/companion/camera.d.ts +8 -0
  680. package/dist/companion/camera.js +57 -31
  681. package/dist/companion/cards.js +7 -10
  682. package/dist/companion/check-in.js +23 -8
  683. package/dist/companion/companion-doctor.d.ts +58 -0
  684. package/dist/companion/companion-doctor.js +194 -0
  685. package/dist/companion/companion-history.d.ts +23 -0
  686. package/dist/companion/companion-history.js +22 -0
  687. package/dist/companion/companion-mode.d.ts +77 -1
  688. package/dist/companion/companion-mode.js +916 -6
  689. package/dist/companion/companion-photo-intake.d.ts +40 -0
  690. package/dist/companion/companion-photo-intake.js +112 -0
  691. package/dist/companion/companion-photo.d.ts +144 -0
  692. package/dist/companion/companion-photo.js +318 -0
  693. package/dist/companion/companion-turn.d.ts +88 -0
  694. package/dist/companion/companion-turn.js +223 -0
  695. package/dist/companion/companion-voice-character.d.ts +62 -0
  696. package/dist/companion/companion-voice-character.js +148 -0
  697. package/dist/companion/competitive-radar.js +14 -13
  698. package/dist/companion/continuity.d.ts +62 -0
  699. package/dist/companion/continuity.js +284 -0
  700. package/dist/companion/conversation-improvement-loop.d.ts +61 -0
  701. package/dist/companion/conversation-improvement-loop.js +317 -0
  702. package/dist/companion/conversation-quality-insights.d.ts +56 -0
  703. package/dist/companion/conversation-quality-insights.js +161 -0
  704. package/dist/companion/cooking-timer-runner.d.ts +20 -0
  705. package/dist/companion/cooking-timer-runner.js +98 -0
  706. package/dist/companion/core-adapter.d.ts +60 -0
  707. package/dist/companion/core-adapter.js +111 -0
  708. package/dist/companion/crisis-safety.d.ts +52 -0
  709. package/dist/companion/crisis-safety.js +150 -0
  710. package/dist/companion/daily-interaction-budget.d.ts +34 -0
  711. package/dist/companion/daily-interaction-budget.js +260 -0
  712. package/dist/companion/dialogue-percepts.d.ts +16 -0
  713. package/dist/companion/dialogue-percepts.js +50 -0
  714. package/dist/companion/event-followups.d.ts +58 -0
  715. package/dist/companion/event-followups.js +213 -0
  716. package/dist/companion/fashion-scene-catalog.d.ts +29 -0
  717. package/dist/companion/fashion-scene-catalog.js +141 -0
  718. package/dist/companion/gateway-inbox.js +25 -13
  719. package/dist/companion/gateway.d.ts +1 -0
  720. package/dist/companion/gateway.js +37 -17
  721. package/dist/companion/home-interaction-policy.d.ts +31 -0
  722. package/dist/companion/home-interaction-policy.js +89 -0
  723. package/dist/companion/household-time.d.ts +9 -0
  724. package/dist/companion/household-time.js +15 -0
  725. package/dist/companion/idle-loop.d.ts +53 -0
  726. package/dist/companion/idle-loop.js +254 -0
  727. package/dist/companion/impulses.js +148 -23
  728. package/dist/companion/inner-life.d.ts +60 -0
  729. package/dist/companion/inner-life.js +112 -0
  730. package/dist/companion/jokes.d.ts +21 -0
  731. package/dist/companion/jokes.js +175 -0
  732. package/dist/companion/lisa-selfie-cache.d.ts +36 -0
  733. package/dist/companion/lisa-selfie-cache.js +123 -0
  734. package/dist/companion/lisa-selfie-ingest.d.ts +36 -0
  735. package/dist/companion/lisa-selfie-ingest.js +205 -0
  736. package/dist/companion/lisa-selfie-refill.d.ts +32 -0
  737. package/dist/companion/lisa-selfie-refill.js +121 -0
  738. package/dist/companion/lisa-selfie-router.d.ts +40 -0
  739. package/dist/companion/lisa-selfie-router.js +156 -0
  740. package/dist/companion/lisa-selfie.d.ts +97 -0
  741. package/dist/companion/lisa-selfie.js +542 -0
  742. package/dist/companion/maison-voice-actions.d.ts +34 -0
  743. package/dist/companion/maison-voice-actions.js +192 -0
  744. package/dist/companion/migration.d.ts +63 -0
  745. package/dist/companion/migration.js +270 -0
  746. package/dist/companion/mission-board.js +7 -10
  747. package/dist/companion/mission-runner.js +2 -3
  748. package/dist/companion/mobile-conversation-log.d.ts +19 -0
  749. package/dist/companion/mobile-conversation-log.js +157 -0
  750. package/dist/companion/mobile-history.d.ts +34 -0
  751. package/dist/companion/mobile-history.js +123 -0
  752. package/dist/companion/mysoulmate-image-prompts.d.ts +26 -0
  753. package/dist/companion/mysoulmate-image-prompts.js +278 -0
  754. package/dist/companion/orchestrator.d.ts +32 -0
  755. package/dist/companion/orchestrator.js +49 -0
  756. package/dist/companion/percepts.d.ts +70 -0
  757. package/dist/companion/percepts.js +251 -18
  758. package/dist/companion/personas/copine.d.ts +8 -0
  759. package/dist/companion/personas/copine.js +195 -0
  760. package/dist/companion/personas/index.d.ts +19 -0
  761. package/dist/companion/personas/index.js +33 -0
  762. package/dist/companion/personas/types.d.ts +34 -0
  763. package/dist/companion/personas/types.js +8 -0
  764. package/dist/companion/photo-memory-fr.d.ts +36 -0
  765. package/dist/companion/photo-memory-fr.js +291 -0
  766. package/dist/companion/prefetch-config.d.ts +38 -0
  767. package/dist/companion/prefetch-config.js +119 -0
  768. package/dist/companion/prefetch-engine.d.ts +87 -0
  769. package/dist/companion/prefetch-engine.js +513 -0
  770. package/dist/companion/presence-loop.d.ts +85 -0
  771. package/dist/companion/presence-loop.js +297 -0
  772. package/dist/companion/privacy.js +3 -2
  773. package/dist/companion/proactive-engine.d.ts +97 -0
  774. package/dist/companion/proactive-engine.js +447 -0
  775. package/dist/companion/recent-said.d.ts +30 -0
  776. package/dist/companion/recent-said.js +98 -0
  777. package/dist/companion/relational-benchmark-scenarios.d.ts +191 -0
  778. package/dist/companion/relational-benchmark-scenarios.js +227 -0
  779. package/dist/companion/relational-context.d.ts +71 -0
  780. package/dist/companion/relational-context.js +302 -0
  781. package/dist/companion/relational-episode-evaluator.d.ts +117 -0
  782. package/dist/companion/relational-episode-evaluator.js +453 -0
  783. package/dist/companion/relationship-evolution.d.ts +2 -0
  784. package/dist/companion/relationship-evolution.js +30 -0
  785. package/dist/companion/relationship-state.d.ts +106 -0
  786. package/dist/companion/relationship-state.js +293 -0
  787. package/dist/companion/reminder-runner.d.ts +33 -0
  788. package/dist/companion/reminder-runner.js +183 -0
  789. package/dist/companion/reminders.d.ts +228 -0
  790. package/dist/companion/reminders.js +906 -0
  791. package/dist/companion/reply-augment.d.ts +87 -0
  792. package/dist/companion/reply-augment.js +464 -0
  793. package/dist/companion/safety-ledger.js +19 -12
  794. package/dist/companion/self-evaluation.js +22 -23
  795. package/dist/companion/shared-photo-memory.d.ts +65 -0
  796. package/dist/companion/shared-photo-memory.js +145 -0
  797. package/dist/companion/shared-photos.d.ts +88 -0
  798. package/dist/companion/shared-photos.js +321 -0
  799. package/dist/companion/signature-locations.d.ts +16 -0
  800. package/dist/companion/signature-locations.js +108 -0
  801. package/dist/companion/skill-curator.d.ts +9 -0
  802. package/dist/companion/skill-curator.js +147 -58
  803. package/dist/companion/untrusted-text.d.ts +22 -0
  804. package/dist/companion/untrusted-text.js +47 -0
  805. package/dist/companion/user-name.d.ts +18 -0
  806. package/dist/companion/user-name.js +22 -0
  807. package/dist/companion/visual-consent.d.ts +40 -0
  808. package/dist/companion/visual-consent.js +98 -0
  809. package/dist/companion/visual-grounding.d.ts +83 -0
  810. package/dist/companion/visual-grounding.js +474 -0
  811. package/dist/companion/voice-callbacks.d.ts +9 -0
  812. package/dist/companion/voice-callbacks.js +84 -0
  813. package/dist/companion/voice-guidance.d.ts +23 -0
  814. package/dist/companion/voice-guidance.js +85 -0
  815. package/dist/companion/voice-improvement-loop.d.ts +53 -0
  816. package/dist/companion/voice-improvement-loop.js +279 -0
  817. package/dist/companion/voice-incident-repair.d.ts +41 -0
  818. package/dist/companion/voice-incident-repair.js +214 -0
  819. package/dist/config/constants.d.ts +41 -0
  820. package/dist/config/constants.js +14 -0
  821. package/dist/config/env-schema.d.ts +2 -0
  822. package/dist/config/env-schema.js +714 -5
  823. package/dist/config/feature-flags.js +8 -12
  824. package/dist/config/feature-surface.d.ts +12 -0
  825. package/dist/config/feature-surface.js +86 -0
  826. package/dist/config/headless-local-prompt.d.ts +9 -0
  827. package/dist/config/headless-local-prompt.js +39 -0
  828. package/dist/config/local-runtime-context.d.ts +41 -0
  829. package/dist/config/local-runtime-context.js +430 -0
  830. package/dist/config/model-registry.js +4 -0
  831. package/dist/config/model-strengths.d.ts +14 -0
  832. package/dist/config/model-strengths.js +15 -0
  833. package/dist/config/model-tools.d.ts +56 -0
  834. package/dist/config/model-tools.js +819 -21
  835. package/dist/config/secret-ref.d.ts +22 -3
  836. package/dist/config/secret-ref.js +103 -41
  837. package/dist/config/toml-config.d.ts +20 -4
  838. package/dist/config/toml-config.js +40 -2
  839. package/dist/context/auto-compact-threshold.d.ts +1 -1
  840. package/dist/context/auto-compact-threshold.js +1 -1
  841. package/dist/context/codebase-map.js +9 -4
  842. package/dist/context/codebase-rag/codebase-rag.js +7 -6
  843. package/dist/context/codebase-rag/hnsw-store.js +9 -4
  844. package/dist/context/codebase-rag/vector-store.js +4 -4
  845. package/dist/context/compaction/parallel-summarizer.js +1 -0
  846. package/dist/context/compression.js +25 -29
  847. package/dist/context/context-manager-v2.d.ts +95 -7
  848. package/dist/context/context-manager-v2.js +442 -89
  849. package/dist/context/context-manager-v3.d.ts +4 -0
  850. package/dist/context/context-manager-v3.js +68 -9
  851. package/dist/context/cross-encoder-reranker.js +8 -3
  852. package/dist/context/default-context-engine.js +1 -1
  853. package/dist/context/enhanced-compression.d.ts +26 -2
  854. package/dist/context/enhanced-compression.js +81 -30
  855. package/dist/context/file-mentions.d.ts +46 -0
  856. package/dist/context/file-mentions.js +245 -0
  857. package/dist/context/importance-scorer.js +4 -3
  858. package/dist/context/jit-context.d.ts +7 -0
  859. package/dist/context/jit-context.js +22 -4
  860. package/dist/context/lm-resizer-compressor.d.ts +102 -0
  861. package/dist/context/lm-resizer-compressor.js +593 -0
  862. package/dist/context/precompaction-flush.js +1 -1
  863. package/dist/context/restorable-compression.d.ts +59 -14
  864. package/dist/context/restorable-compression.js +310 -60
  865. package/dist/context/segment-archive.d.ts +36 -0
  866. package/dist/context/segment-archive.js +220 -0
  867. package/dist/context/smart-compaction.d.ts +7 -0
  868. package/dist/context/smart-compaction.js +84 -15
  869. package/dist/context/token-counter.d.ts +6 -0
  870. package/dist/context/token-counter.js +41 -0
  871. package/dist/context/token-juice.d.ts +72 -0
  872. package/dist/context/token-juice.js +220 -0
  873. package/dist/context/tool-observation-optimizer.d.ts +90 -0
  874. package/dist/context/tool-observation-optimizer.js +231 -0
  875. package/dist/context/tool-pair-preserver.d.ts +1 -1
  876. package/dist/context/tool-pair-preserver.js +1 -1
  877. package/dist/context/transcript-repair.d.ts +16 -3
  878. package/dist/context/transcript-repair.js +72 -35
  879. package/dist/context/types.d.ts +2 -0
  880. package/dist/conversation/argument-obligations.d.ts +65 -0
  881. package/dist/conversation/argument-obligations.js +157 -0
  882. package/dist/conversation/companion-model-routing.d.ts +121 -0
  883. package/dist/conversation/companion-model-routing.js +810 -0
  884. package/dist/conversation/conversation-benchmark.d.ts +143 -0
  885. package/dist/conversation/conversation-benchmark.js +766 -0
  886. package/dist/conversation/conversation-blind-comparison.d.ts +135 -0
  887. package/dist/conversation/conversation-blind-comparison.js +451 -0
  888. package/dist/conversation/conversation-evaluator.d.ts +56 -0
  889. package/dist/conversation/conversation-evaluator.js +335 -0
  890. package/dist/conversation/conversation-orchestrator.d.ts +32 -0
  891. package/dist/conversation/conversation-orchestrator.js +59 -0
  892. package/dist/conversation/conversation-pilot-corpus.d.ts +33 -0
  893. package/dist/conversation/conversation-pilot-corpus.js +313 -0
  894. package/dist/conversation/conversation-quality.d.ts +31 -0
  895. package/dist/conversation/conversation-quality.js +280 -0
  896. package/dist/conversation/conversation-state.d.ts +23 -0
  897. package/dist/conversation/conversation-state.js +117 -0
  898. package/dist/conversation/cross-channel-bridge.d.ts +127 -0
  899. package/dist/conversation/cross-channel-bridge.js +785 -0
  900. package/dist/conversation/deliberation-thread.d.ts +18 -0
  901. package/dist/conversation/deliberation-thread.js +303 -0
  902. package/dist/conversation/dialogue-act.d.ts +11 -0
  903. package/dist/conversation/dialogue-act.js +132 -0
  904. package/dist/conversation/discourse-planner.d.ts +3 -0
  905. package/dist/conversation/discourse-planner.js +141 -0
  906. package/dist/conversation/fresh-context.d.ts +54 -0
  907. package/dist/conversation/fresh-context.js +258 -0
  908. package/dist/conversation/prefetched-turn-context.d.ts +45 -0
  909. package/dist/conversation/prefetched-turn-context.js +209 -0
  910. package/dist/conversation/relationship-safety.d.ts +37 -0
  911. package/dist/conversation/relationship-safety.js +407 -0
  912. package/dist/conversation/semantic-response-gate.d.ts +262 -0
  913. package/dist/conversation/semantic-response-gate.js +656 -0
  914. package/dist/conversation/semantic-response-runtime.d.ts +79 -0
  915. package/dist/conversation/semantic-response-runtime.js +419 -0
  916. package/dist/conversation/shared-relationship-state.d.ts +60 -0
  917. package/dist/conversation/shared-relationship-state.js +262 -0
  918. package/dist/conversation/types.d.ts +77 -0
  919. package/dist/conversation/types.js +3 -0
  920. package/dist/conversation/voice-continuity.d.ts +13 -0
  921. package/dist/conversation/voice-continuity.js +48 -0
  922. package/dist/council/conductor.d.ts +26 -0
  923. package/dist/council/conductor.js +292 -0
  924. package/dist/council/council-engine.d.ts +29 -0
  925. package/dist/council/council-engine.js +458 -0
  926. package/dist/council/deliberation-health.d.ts +58 -0
  927. package/dist/council/deliberation-health.js +108 -0
  928. package/dist/council/judge.d.ts +69 -0
  929. package/dist/council/judge.js +183 -0
  930. package/dist/council/peers.d.ts +19 -0
  931. package/dist/council/peers.js +47 -0
  932. package/dist/council/signals.d.ts +26 -0
  933. package/dist/council/signals.js +156 -0
  934. package/dist/council/task-types.d.ts +16 -0
  935. package/dist/council/task-types.js +58 -0
  936. package/dist/council/triage.d.ts +48 -0
  937. package/dist/council/triage.js +228 -0
  938. package/dist/council/types.d.ts +292 -0
  939. package/dist/council/types.js +20 -0
  940. package/dist/council/with-timeout.d.ts +10 -0
  941. package/dist/council/with-timeout.js +29 -0
  942. package/dist/curator/curator.d.ts +79 -0
  943. package/dist/curator/curator.js +317 -0
  944. package/dist/daemon/agent-task-executor.js +51 -0
  945. package/dist/daemon/autonomous-daemon.d.ts +2 -0
  946. package/dist/daemon/autonomous-daemon.js +4 -1
  947. package/dist/daemon/autonomous-loop.d.ts +9 -0
  948. package/dist/daemon/autonomous-loop.js +57 -1
  949. package/dist/daemon/autonomy-bench-candidates.d.ts +33 -0
  950. package/dist/daemon/autonomy-bench-candidates.js +68 -0
  951. package/dist/daemon/autonomy-briefing.d.ts +112 -0
  952. package/dist/daemon/autonomy-briefing.js +359 -0
  953. package/dist/daemon/autonomy-run-journal.d.ts +20 -0
  954. package/dist/daemon/autonomy-run-journal.js +41 -0
  955. package/dist/daemon/daily-reset.d.ts +2 -2
  956. package/dist/daemon/daily-reset.js +16 -15
  957. package/dist/daemon/ollama-task-executor.js +9 -1
  958. package/dist/database/database-manager.d.ts +1 -1
  959. package/dist/database/database-manager.js +6 -4
  960. package/dist/database/optional-sqlite.d.ts +20 -0
  961. package/dist/database/optional-sqlite.js +101 -0
  962. package/dist/design/design-system-registry.d.ts +21 -0
  963. package/dist/design/design-system-registry.js +106 -0
  964. package/dist/desktop/codebuddy-engine-adapter.d.ts +34 -0
  965. package/dist/desktop/codebuddy-engine-adapter.js +306 -21
  966. package/dist/desktop/electron-launch-args.d.ts +7 -0
  967. package/dist/desktop/electron-launch-args.js +13 -0
  968. package/dist/desktop/engine-adapter.d.ts +6 -0
  969. package/dist/desktop/launcher.js +2 -1
  970. package/dist/desktop/permission-bridge.d.ts +12 -1
  971. package/dist/desktop/permission-bridge.js +12 -5
  972. package/dist/desktop-automation/omniparser-runner.d.ts +1 -0
  973. package/dist/desktop-automation/omniparser-runner.js +12 -1
  974. package/dist/desktop-automation/smart-snapshot.js +7 -0
  975. package/dist/desktop-automation/windows-native-provider.js +1 -1
  976. package/dist/doctor/assistant-runtime.d.ts +90 -0
  977. package/dist/doctor/assistant-runtime.js +472 -0
  978. package/dist/doctor/env-sanity.d.ts +17 -0
  979. package/dist/doctor/env-sanity.js +74 -0
  980. package/dist/doctor/index.d.ts +37 -0
  981. package/dist/doctor/index.js +389 -37
  982. package/dist/doctor/llm-key-check.d.ts +17 -0
  983. package/dist/doctor/llm-key-check.js +100 -0
  984. package/dist/doctor/ollama-model-selection.d.ts +16 -0
  985. package/dist/doctor/ollama-model-selection.js +55 -0
  986. package/dist/embeddings/embedding-provider.d.ts +1 -0
  987. package/dist/embeddings/embedding-provider.js +21 -9
  988. package/dist/errors/crash-recovery.js +6 -4
  989. package/dist/events/index.d.ts +1 -1
  990. package/dist/events/types.d.ts +44 -0
  991. package/dist/export/repo-explanation.d.ts +10 -0
  992. package/dist/export/repo-explanation.js +334 -0
  993. package/dist/export/session-share.d.ts +34 -0
  994. package/dist/export/session-share.js +687 -0
  995. package/dist/fleet/autonomous-tick-broadcaster.d.ts +1 -1
  996. package/dist/fleet/capability-registry.d.ts +9 -0
  997. package/dist/fleet/capability-registry.js +268 -56
  998. package/dist/fleet/colab-store.d.ts +3 -4
  999. package/dist/fleet/colab-store.js +6 -26
  1000. package/dist/fleet/compatible-model.d.ts +39 -0
  1001. package/dist/fleet/compatible-model.js +148 -0
  1002. package/dist/fleet/consolidation/collecte.d.ts +31 -0
  1003. package/dist/fleet/consolidation/collecte.js +86 -0
  1004. package/dist/fleet/consolidation/digest-texte.d.ts +11 -0
  1005. package/dist/fleet/consolidation/digest-texte.js +52 -0
  1006. package/dist/fleet/consolidation/thalamus.d.ts +35 -0
  1007. package/dist/fleet/consolidation/thalamus.js +151 -0
  1008. package/dist/fleet/consolidation/types.d.ts +66 -0
  1009. package/dist/fleet/consolidation/types.js +22 -0
  1010. package/dist/fleet/cost-tracker.d.ts +11 -0
  1011. package/dist/fleet/cost-tracker.js +64 -17
  1012. package/dist/fleet/fleet-cost-cap.d.ts +36 -0
  1013. package/dist/fleet/fleet-cost-cap.js +175 -0
  1014. package/dist/fleet/fleet-http-surface.d.ts +24 -0
  1015. package/dist/fleet/fleet-http-surface.js +72 -0
  1016. package/dist/fleet/fleet-listener.d.ts +1 -1
  1017. package/dist/fleet/fleet-listener.js +4 -0
  1018. package/dist/fleet/model-capability-heuristics.d.ts +31 -0
  1019. package/dist/fleet/model-capability-heuristics.js +49 -0
  1020. package/dist/fleet/model-inventory.d.ts +46 -0
  1021. package/dist/fleet/model-inventory.js +242 -0
  1022. package/dist/fleet/model-scoreboard.d.ts +118 -13
  1023. package/dist/fleet/model-scoreboard.js +339 -27
  1024. package/dist/fleet/model-selector.d.ts +83 -0
  1025. package/dist/fleet/model-selector.js +218 -0
  1026. package/dist/fleet/peer-chat-bridge.d.ts +9 -2
  1027. package/dist/fleet/peer-chat-bridge.js +133 -19
  1028. package/dist/fleet/peer-chat-client-factory.d.ts +28 -2
  1029. package/dist/fleet/peer-chat-client-factory.js +195 -22
  1030. package/dist/fleet/peer-ckg-bridge.d.ts +67 -0
  1031. package/dist/fleet/peer-ckg-bridge.js +467 -0
  1032. package/dist/fleet/peer-mission-exchange-bridge.d.ts +8 -0
  1033. package/dist/fleet/peer-mission-exchange-bridge.js +127 -0
  1034. package/dist/fleet/peer-session-bridge.d.ts +7 -1
  1035. package/dist/fleet/peer-session-bridge.js +98 -17
  1036. package/dist/fleet/peer-session-store.d.ts +2 -0
  1037. package/dist/fleet/peer-session-store.js +6 -5
  1038. package/dist/fleet/peer-text-sanitizer.d.ts +59 -0
  1039. package/dist/fleet/peer-text-sanitizer.js +99 -0
  1040. package/dist/fleet/peer-tool-bridge.js +38 -10
  1041. package/dist/fleet/privacy-lint.js +80 -8
  1042. package/dist/fleet/saga-store.d.ts +25 -1
  1043. package/dist/fleet/saga-store.js +34 -6
  1044. package/dist/fleet/task-router.d.ts +17 -1
  1045. package/dist/fleet/task-router.js +65 -20
  1046. package/dist/fleet/types.d.ts +9 -5
  1047. package/dist/gateway/device-pairing.js +5 -11
  1048. package/dist/gateway/ws-transport.d.ts +1 -5
  1049. package/dist/gateway/ws-transport.js +2 -22
  1050. package/dist/git/changelog.d.ts +36 -0
  1051. package/dist/git/changelog.js +109 -0
  1052. package/dist/git/worktree-sessions.js +1 -1
  1053. package/dist/goals/counterfactual-forge.d.ts +70 -0
  1054. package/dist/goals/counterfactual-forge.js +184 -0
  1055. package/dist/goals/criterion-progress.d.ts +24 -0
  1056. package/dist/goals/criterion-progress.js +59 -0
  1057. package/dist/goals/evidence-artifact.d.ts +18 -0
  1058. package/dist/goals/evidence-artifact.js +76 -0
  1059. package/dist/goals/goal-decomposer.d.ts +15 -0
  1060. package/dist/goals/goal-decomposer.js +89 -4
  1061. package/dist/goals/goal-loop.d.ts +29 -0
  1062. package/dist/goals/goal-loop.js +92 -6
  1063. package/dist/goals/goal-manager.d.ts +1 -0
  1064. package/dist/goals/goal-manager.js +4 -1
  1065. package/dist/goals/goal-state.d.ts +10 -0
  1066. package/dist/goals/goal-state.js +21 -1
  1067. package/dist/goals/goal-store.js +4 -6
  1068. package/dist/goals/index.d.ts +11 -0
  1069. package/dist/goals/index.js +11 -0
  1070. package/dist/goals/intent-graph.d.ts +40 -0
  1071. package/dist/goals/intent-graph.js +133 -0
  1072. package/dist/goals/mission-constitution.d.ts +59 -0
  1073. package/dist/goals/mission-constitution.js +132 -0
  1074. package/dist/goals/mission-exchange.d.ts +86 -0
  1075. package/dist/goals/mission-exchange.js +216 -0
  1076. package/dist/goals/outcome-capsule.d.ts +80 -0
  1077. package/dist/goals/outcome-capsule.js +186 -0
  1078. package/dist/goals/proof-ledger.d.ts +79 -0
  1079. package/dist/goals/proof-ledger.js +181 -0
  1080. package/dist/goals/proven-outcome-lessons.d.ts +11 -0
  1081. package/dist/goals/proven-outcome-lessons.js +30 -0
  1082. package/dist/goals/proven-outcome-memory.d.ts +55 -0
  1083. package/dist/goals/proven-outcome-memory.js +125 -0
  1084. package/dist/goals/shadow-twin.d.ts +57 -0
  1085. package/dist/goals/shadow-twin.js +110 -0
  1086. package/dist/gpu-worker/gpu-media-worker-server.d.ts +49 -0
  1087. package/dist/gpu-worker/gpu-media-worker-server.js +637 -0
  1088. package/dist/harness/contract.d.ts +84 -84
  1089. package/dist/hooks/advanced-hooks.js +6 -4
  1090. package/dist/hooks/env-persistence.js +5 -6
  1091. package/dist/hooks/hook-manager.js +8 -7
  1092. package/dist/hooks/hook-system.js +6 -4
  1093. package/dist/hooks/lifecycle-hooks.js +6 -3
  1094. package/dist/hooks/moltbot/moltbot-hooks-manager.js +8 -3
  1095. package/dist/hooks/moltbot/session-persistence-manager.js +15 -7
  1096. package/dist/hooks/moltbot/setup-utilities.js +6 -4
  1097. package/dist/hooks/smart-hooks.js +6 -4
  1098. package/dist/hooks/use-input-handler.js +9 -63
  1099. package/dist/hooks/user-hooks.d.ts +10 -1
  1100. package/dist/hooks/user-hooks.js +77 -1
  1101. package/dist/identity/companion-identity.d.ts +4 -1
  1102. package/dist/identity/companion-identity.js +134 -4
  1103. package/dist/identity/identity-manager.d.ts +1 -1
  1104. package/dist/identity/identity-manager.js +7 -6
  1105. package/dist/identity/lisa-introspection.d.ts +36 -0
  1106. package/dist/identity/lisa-introspection.js +411 -0
  1107. package/dist/identity/operational-self-model.d.ts +143 -0
  1108. package/dist/identity/operational-self-model.js +974 -0
  1109. package/dist/index.d.ts +3 -1
  1110. package/dist/index.js +987 -223
  1111. package/dist/input/context-mentions.d.ts +7 -1
  1112. package/dist/input/context-mentions.js +18 -20
  1113. package/dist/input/text-to-speech.d.ts +3 -0
  1114. package/dist/input/text-to-speech.js +70 -27
  1115. package/dist/input/voice-control.d.ts +1 -0
  1116. package/dist/input/voice-control.js +24 -18
  1117. package/dist/input/voice-input-enhanced.d.ts +1 -0
  1118. package/dist/input/voice-input-enhanced.js +31 -16
  1119. package/dist/integrations/ci-autofix-pipeline.js +15 -20
  1120. package/dist/integrations/ide/server.js +3 -2
  1121. package/dist/integrations/json-rpc/server.js +4 -2
  1122. package/dist/integrations/mcp/mcp-server.js +4 -2
  1123. package/dist/integrations/opentelemetry-integration.js +6 -4
  1124. package/dist/integrations/pubcommander-bridge.d.ts +5 -0
  1125. package/dist/integrations/pubcommander-bridge.js +61 -0
  1126. package/dist/integrations/sentry-integration.js +9 -3
  1127. package/dist/intelligence/semantic-search.js +9 -12
  1128. package/dist/intelligence/user-preferences.js +8 -11
  1129. package/dist/intents/intent-checker.d.ts +34 -0
  1130. package/dist/intents/intent-checker.js +175 -0
  1131. package/dist/intents/intent-generator.d.ts +12 -0
  1132. package/dist/intents/intent-generator.js +86 -0
  1133. package/dist/intents/intent-store.d.ts +62 -0
  1134. package/dist/intents/intent-store.js +263 -0
  1135. package/dist/interpreter/computer/skills.js +3 -2
  1136. package/dist/interpreter/interpreter-service.js +18 -9
  1137. package/dist/kanban/kanban-board-registry.js +6 -4
  1138. package/dist/kanban/kanban-store.js +5 -7
  1139. package/dist/knowledge/code-graph-persistence.js +8 -16
  1140. package/dist/knowledge/graph-drift.js +14 -11
  1141. package/dist/knowledge/knowledge-manager.js +2 -1
  1142. package/dist/knowledge/scanners/index.d.ts +3 -0
  1143. package/dist/knowledge/scanners/index.js +57 -29
  1144. package/dist/knowledge/workspace-indexer.js +22 -15
  1145. package/dist/life-rhythm/cooking-timer-store.d.ts +50 -0
  1146. package/dist/life-rhythm/cooking-timer-store.js +240 -0
  1147. package/dist/life-rhythm/day-context.d.ts +30 -0
  1148. package/dist/life-rhythm/day-context.js +198 -0
  1149. package/dist/life-rhythm/etalab-holiday-provider.d.ts +40 -0
  1150. package/dist/life-rhythm/etalab-holiday-provider.js +318 -0
  1151. package/dist/life-rhythm/home-mode-store.d.ts +32 -0
  1152. package/dist/life-rhythm/home-mode-store.js +184 -0
  1153. package/dist/life-rhythm/index.d.ts +6 -0
  1154. package/dist/life-rhythm/index.js +7 -0
  1155. package/dist/life-rhythm/types.d.ts +88 -0
  1156. package/dist/life-rhythm/types.js +33 -0
  1157. package/dist/life-rhythm/zoned-minute.d.ts +24 -0
  1158. package/dist/life-rhythm/zoned-minute.js +113 -0
  1159. package/dist/location/index.d.ts +2 -12
  1160. package/dist/location/index.js +129 -56
  1161. package/dist/logging/interaction-logger.js +29 -46
  1162. package/dist/lora/dataset-v3-plan.d.ts +27 -0
  1163. package/dist/lora/dataset-v3-plan.js +121 -0
  1164. package/dist/lora/dataset.d.ts +26 -0
  1165. package/dist/lora/dataset.js +165 -0
  1166. package/dist/lora/fal-krea-trainer.d.ts +54 -0
  1167. package/dist/lora/fal-krea-trainer.js +197 -0
  1168. package/dist/lora/generate-training-set.d.ts +61 -0
  1169. package/dist/lora/generate-training-set.js +190 -0
  1170. package/dist/lora/identity-dataset-gate.d.ts +104 -0
  1171. package/dist/lora/identity-dataset-gate.js +204 -0
  1172. package/dist/lora/identity-dataset-promotion.d.ts +32 -0
  1173. package/dist/lora/identity-dataset-promotion.js +269 -0
  1174. package/dist/lora/index.d.ts +11 -0
  1175. package/dist/lora/index.js +12 -0
  1176. package/dist/lora/install-comfy.d.ts +14 -0
  1177. package/dist/lora/install-comfy.js +63 -0
  1178. package/dist/lora/lisa-avatar-bible.d.ts +85 -0
  1179. package/dist/lora/lisa-avatar-bible.js +275 -0
  1180. package/dist/lora/local-plan.d.ts +10 -0
  1181. package/dist/lora/local-plan.js +205 -0
  1182. package/dist/lora/pack-dataset.d.ts +7 -0
  1183. package/dist/lora/pack-dataset.js +39 -0
  1184. package/dist/lora/quality-gate.d.ts +31 -0
  1185. package/dist/lora/quality-gate.js +90 -0
  1186. package/dist/lora/types.d.ts +66 -0
  1187. package/dist/lora/types.js +5 -0
  1188. package/dist/lsp/lsp-client.d.ts +12 -0
  1189. package/dist/lsp/lsp-client.js +45 -9
  1190. package/dist/lsp/server.js +1 -1
  1191. package/dist/mcp/approval-elicitation.d.ts +1 -0
  1192. package/dist/mcp/approval-elicitation.js +2 -0
  1193. package/dist/mcp/client.d.ts +15 -1
  1194. package/dist/mcp/client.js +110 -24
  1195. package/dist/mcp/config.d.ts +12 -1
  1196. package/dist/mcp/config.js +55 -12
  1197. package/dist/mcp/index.d.ts +1 -1
  1198. package/dist/mcp/mcp-agent-tools.d.ts +1 -1
  1199. package/dist/mcp/mcp-agent-tools.js +76 -73
  1200. package/dist/mcp/mcp-ckg-tools.d.ts +31 -0
  1201. package/dist/mcp/mcp-ckg-tools.js +121 -0
  1202. package/dist/mcp/mcp-client.js +8 -5
  1203. package/dist/mcp/mcp-desktop-tools.d.ts +1 -1
  1204. package/dist/mcp/mcp-desktop-tools.js +105 -99
  1205. package/dist/mcp/mcp-memory-tools.d.ts +1 -1
  1206. package/dist/mcp/mcp-memory-tools.js +63 -61
  1207. package/dist/mcp/mcp-oauth.js +5 -2
  1208. package/dist/mcp/mcp-server.d.ts +48 -79
  1209. package/dist/mcp/mcp-server.js +445 -478
  1210. package/dist/mcp/mcp-session-tools.d.ts +1 -1
  1211. package/dist/mcp/mcp-session-tools.js +95 -92
  1212. package/dist/mcp/profiles.d.ts +18 -0
  1213. package/dist/mcp/profiles.js +65 -0
  1214. package/dist/mcp/prompt-footprint.d.ts +21 -0
  1215. package/dist/mcp/prompt-footprint.js +39 -0
  1216. package/dist/meals/allergens.d.ts +19 -0
  1217. package/dist/meals/allergens.js +122 -0
  1218. package/dist/meals/compatibility.d.ts +6 -0
  1219. package/dist/meals/compatibility.js +109 -0
  1220. package/dist/meals/food-inventory-store.d.ts +51 -0
  1221. package/dist/meals/food-inventory-store.js +257 -0
  1222. package/dist/meals/index.d.ts +10 -0
  1223. package/dist/meals/index.js +11 -0
  1224. package/dist/meals/meal-engine.d.ts +7 -0
  1225. package/dist/meals/meal-engine.js +206 -0
  1226. package/dist/meals/meal-plan-store.d.ts +73 -0
  1227. package/dist/meals/meal-plan-store.js +271 -0
  1228. package/dist/meals/private-json-store.d.ts +9 -0
  1229. package/dist/meals/private-json-store.js +92 -0
  1230. package/dist/meals/profile-store.d.ts +49 -0
  1231. package/dist/meals/profile-store.js +296 -0
  1232. package/dist/meals/profile-validator.d.ts +7 -0
  1233. package/dist/meals/profile-validator.js +124 -0
  1234. package/dist/meals/recipe-normalizer.d.ts +7 -0
  1235. package/dist/meals/recipe-normalizer.js +162 -0
  1236. package/dist/meals/store-validation.d.ts +21 -0
  1237. package/dist/meals/store-validation.js +101 -0
  1238. package/dist/meals/types.d.ts +170 -0
  1239. package/dist/meals/types.js +12 -0
  1240. package/dist/media/comfy-health-supervisor.d.ts +142 -0
  1241. package/dist/media/comfy-health-supervisor.js +608 -0
  1242. package/dist/media/comfyui-recipe-contract.d.ts +696 -0
  1243. package/dist/media/comfyui-recipe-contract.js +580 -0
  1244. package/dist/media/comfyui-recipe-engine.d.ts +3 -0
  1245. package/dist/media/comfyui-recipe-engine.js +4 -0
  1246. package/dist/media/comfyui-recipe-registry.d.ts +35 -0
  1247. package/dist/media/comfyui-recipe-registry.js +385 -0
  1248. package/dist/media/comfyui-recipe-runtime.d.ts +135 -0
  1249. package/dist/media/comfyui-recipe-runtime.js +942 -0
  1250. package/dist/media/content-tier.d.ts +25 -0
  1251. package/dist/media/content-tier.js +29 -0
  1252. package/dist/meeting/analyzer.d.ts +24 -0
  1253. package/dist/meeting/analyzer.js +402 -0
  1254. package/dist/meeting/index.d.ts +13 -0
  1255. package/dist/meeting/index.js +48 -0
  1256. package/dist/meeting/markdown.d.ts +3 -0
  1257. package/dist/meeting/markdown.js +51 -0
  1258. package/dist/meeting/output.d.ts +13 -0
  1259. package/dist/meeting/output.js +155 -0
  1260. package/dist/meeting/transcript.d.ts +25 -0
  1261. package/dist/meeting/transcript.js +292 -0
  1262. package/dist/meeting/types.d.ts +112 -0
  1263. package/dist/meeting/types.js +9 -0
  1264. package/dist/memory/adapters/network-memory-adapters.d.ts +19 -4
  1265. package/dist/memory/adapters/network-memory-adapters.js +4 -4
  1266. package/dist/memory/auto-memory.js +5 -2
  1267. package/dist/memory/background-extractor.d.ts +43 -0
  1268. package/dist/memory/background-extractor.js +368 -0
  1269. package/dist/memory/buddy-memory-client.d.ts +40 -0
  1270. package/dist/memory/buddy-memory-client.js +198 -0
  1271. package/dist/memory/ckg-engine-policy.d.ts +19 -0
  1272. package/dist/memory/ckg-engine-policy.js +45 -0
  1273. package/dist/memory/ckg-fact-reconciliation.d.ts +81 -0
  1274. package/dist/memory/ckg-fact-reconciliation.js +155 -0
  1275. package/dist/memory/ckg-redaction.d.ts +2 -0
  1276. package/dist/memory/ckg-redaction.js +25 -0
  1277. package/dist/memory/coding-style-analyzer.js +2 -2
  1278. package/dist/memory/collective-knowledge-graph.d.ts +380 -0
  1279. package/dist/memory/collective-knowledge-graph.js +1228 -0
  1280. package/dist/memory/enhanced-memory.d.ts +29 -0
  1281. package/dist/memory/enhanced-memory.js +153 -63
  1282. package/dist/memory/facts-memory.d.ts +9 -4
  1283. package/dist/memory/facts-memory.js +21 -4
  1284. package/dist/memory/hybrid-mmr.d.ts +71 -0
  1285. package/dist/memory/hybrid-mmr.js +127 -0
  1286. package/dist/memory/hybrid-search.js +4 -1
  1287. package/dist/memory/knowledge-graph.d.ts +23 -2
  1288. package/dist/memory/knowledge-graph.js +62 -47
  1289. package/dist/memory/memory-candidate-queue.js +9 -4
  1290. package/dist/memory/memory-consolidation.d.ts +8 -0
  1291. package/dist/memory/memory-consolidation.js +66 -17
  1292. package/dist/memory/memory-forgetting.d.ts +57 -0
  1293. package/dist/memory/memory-forgetting.js +87 -0
  1294. package/dist/memory/ocr-memory-pipeline.js +16 -10
  1295. package/dist/memory/persistent-memory.d.ts +98 -0
  1296. package/dist/memory/persistent-memory.js +711 -119
  1297. package/dist/memory/presence-injector.d.ts +1 -1
  1298. package/dist/memory/presence-injector.js +9 -4
  1299. package/dist/memory/semantic-memory-search.js +12 -9
  1300. package/dist/memory/subagent-memory.js +8 -8
  1301. package/dist/memory/user-model.js +9 -4
  1302. package/dist/metrics/metrics-collector.d.ts +1 -0
  1303. package/dist/metrics/metrics-collector.js +11 -2
  1304. package/dist/nodes/device-node.d.ts +5 -2
  1305. package/dist/nodes/device-node.js +65 -19
  1306. package/dist/nodes/index.d.ts +32 -2
  1307. package/dist/nodes/index.js +208 -7
  1308. package/dist/nodes/transports/adb-transport.d.ts +2 -6
  1309. package/dist/nodes/transports/adb-transport.js +29 -13
  1310. package/dist/nodes/transports/base-transport.d.ts +10 -0
  1311. package/dist/observability/run-store.d.ts +6 -1
  1312. package/dist/observability/run-store.js +89 -22
  1313. package/dist/observability/run-trajectory-load.d.ts +16 -0
  1314. package/dist/observability/run-trajectory-load.js +266 -0
  1315. package/dist/observability/run-trajectory.d.ts +168 -0
  1316. package/dist/observability/run-trajectory.js +468 -0
  1317. package/dist/observability/run-viewer.d.ts +5 -1
  1318. package/dist/observability/run-viewer.js +83 -9
  1319. package/dist/observability/turn-metrics.d.ts +86 -0
  1320. package/dist/observability/turn-metrics.js +201 -0
  1321. package/dist/offline/offline-mode.js +10 -9
  1322. package/dist/openclaw/gateway-bridge.js +3 -2
  1323. package/dist/optimization/latency-optimizer.d.ts +2 -1
  1324. package/dist/optimization/latency-optimizer.js +2 -2
  1325. package/dist/optimization/model-routing.d.ts +3 -0
  1326. package/dist/orchestration/orchestrator.js +4 -1
  1327. package/dist/orchestration/types.d.ts +2 -0
  1328. package/dist/performance/lazy-loader.js +2 -1
  1329. package/dist/performance/tool-cache.d.ts +4 -0
  1330. package/dist/performance/tool-cache.js +4 -2
  1331. package/dist/persistence/conversation-branches.js +9 -2
  1332. package/dist/persistence/session-store.d.ts +26 -0
  1333. package/dist/persistence/session-store.js +56 -17
  1334. package/dist/personas/persona-manager.d.ts +39 -1
  1335. package/dist/personas/persona-manager.js +276 -38
  1336. package/dist/plugins/bundled/groq-provider.js +10 -7
  1337. package/dist/plugins/bundled/openrouter-provider.js +2 -1
  1338. package/dist/plugins/code-explorer/CodeExplorerManager.d.ts +52 -4
  1339. package/dist/plugins/code-explorer/CodeExplorerManager.js +201 -31
  1340. package/dist/plugins/code-explorer/code-explorer-client.d.ts +36 -0
  1341. package/dist/plugins/code-explorer/code-explorer-client.js +86 -0
  1342. package/dist/plugins/code-explorer/index.d.ts +1 -3
  1343. package/dist/plugins/code-explorer/index.js +0 -1
  1344. package/dist/plugins/git-pinned-marketplace.js +3 -2
  1345. package/dist/plugins/plugin-manager.js +6 -9
  1346. package/dist/plugins/sandbox-worker.js +1 -1
  1347. package/dist/prompts/system-base.js +27 -3
  1348. package/dist/protocols/a2a/codebuddy-executor.d.ts +9 -0
  1349. package/dist/protocols/a2a/codebuddy-executor.js +25 -6
  1350. package/dist/protocols/a2a/index.d.ts +6 -0
  1351. package/dist/protocols/a2a/index.js +32 -3
  1352. package/dist/protocols/acp/acp-agentic-runner.d.ts +6 -2
  1353. package/dist/protocols/acp/acp-agentic-runner.js +91 -15
  1354. package/dist/protocols/acp/acp-session-store.js +28 -5
  1355. package/dist/protocols/acp/acp-stdio-server.d.ts +13 -0
  1356. package/dist/protocols/acp/acp-stdio-server.js +30 -3
  1357. package/dist/providers/active-llm-model-pool.d.ts +45 -0
  1358. package/dist/providers/active-llm-model-pool.js +139 -0
  1359. package/dist/providers/active-llm-registry.js +48 -8
  1360. package/dist/providers/auxiliary-provider.d.ts +1 -1
  1361. package/dist/providers/auxiliary-provider.js +23 -10
  1362. package/dist/providers/chatgpt-models.d.ts +71 -0
  1363. package/dist/providers/chatgpt-models.js +302 -0
  1364. package/dist/providers/codex-oauth.d.ts +8 -0
  1365. package/dist/providers/codex-oauth.js +47 -39
  1366. package/dist/providers/gemini-oauth.js +7 -6
  1367. package/dist/providers/grok-provider.js +1 -1
  1368. package/dist/providers/index.d.ts +3 -0
  1369. package/dist/providers/index.js +3 -0
  1370. package/dist/providers/local-model-resolver.d.ts +66 -0
  1371. package/dist/providers/local-model-resolver.js +128 -0
  1372. package/dist/providers/model-egress.d.ts +8 -0
  1373. package/dist/providers/model-egress.js +62 -0
  1374. package/dist/providers/model-provider-compat.d.ts +13 -0
  1375. package/dist/providers/model-provider-compat.js +48 -0
  1376. package/dist/providers/provider-catalog.d.ts +4 -1
  1377. package/dist/providers/provider-catalog.js +494 -28
  1378. package/dist/providers/provider-failover-notify.d.ts +15 -0
  1379. package/dist/providers/provider-failover-notify.js +93 -0
  1380. package/dist/providers/provider-failover-policy.d.ts +28 -0
  1381. package/dist/providers/provider-failover-policy.js +188 -0
  1382. package/dist/providers/provider-failover-user-notice.d.ts +13 -0
  1383. package/dist/providers/provider-failover-user-notice.js +49 -0
  1384. package/dist/providers/provider-fallback.d.ts +1 -0
  1385. package/dist/providers/provider-fallback.js +1 -1
  1386. package/dist/providers/provider-health.d.ts +46 -0
  1387. package/dist/providers/provider-health.js +249 -0
  1388. package/dist/providers/turboquant-provider.d.ts +1 -1
  1389. package/dist/providers/xai-oauth.js +7 -34
  1390. package/dist/queue/persistent-queue.js +9 -6
  1391. package/dist/renderers/charts/special-charts.d.ts +7 -1
  1392. package/dist/renderers/charts/special-charts.js +5 -0
  1393. package/dist/renderers/weather-conditions.d.ts +20 -0
  1394. package/dist/renderers/weather-conditions.js +74 -0
  1395. package/dist/renderers/weather-renderer.js +4 -18
  1396. package/dist/rendering/ansi.d.ts +4 -0
  1397. package/dist/rendering/ansi.js +149 -0
  1398. package/dist/rendering/index.d.ts +19 -0
  1399. package/dist/rendering/index.js +18 -0
  1400. package/dist/rendering/markdown-core.d.ts +13 -0
  1401. package/dist/rendering/markdown-core.js +18 -0
  1402. package/dist/rendering/plain.d.ts +2 -0
  1403. package/dist/rendering/plain.js +91 -0
  1404. package/dist/rendering/telegram-html.d.ts +27 -0
  1405. package/dist/rendering/telegram-html.js +290 -0
  1406. package/dist/research/auto-ingest.d.ts +45 -0
  1407. package/dist/research/auto-ingest.js +85 -0
  1408. package/dist/research/code-explorer-source.d.ts +29 -0
  1409. package/dist/research/code-explorer-source.js +76 -0
  1410. package/dist/research/connector-source.d.ts +25 -0
  1411. package/dist/research/connector-source.js +314 -0
  1412. package/dist/research/paper-qa/answer.d.ts +72 -0
  1413. package/dist/research/paper-qa/answer.js +227 -0
  1414. package/dist/research/paper-qa/corpus.d.ts +36 -0
  1415. package/dist/research/paper-qa/corpus.js +102 -0
  1416. package/dist/research/paper-qa/disk-embedding-cache.d.ts +28 -0
  1417. package/dist/research/paper-qa/disk-embedding-cache.js +193 -0
  1418. package/dist/research/paper-qa/index.d.ts +31 -0
  1419. package/dist/research/paper-qa/index.js +24 -0
  1420. package/dist/research/paper-qa/paper-qa-pipeline.d.ts +107 -0
  1421. package/dist/research/paper-qa/paper-qa-pipeline.js +163 -0
  1422. package/dist/research/paper-qa/passage-index.d.ts +203 -0
  1423. package/dist/research/paper-qa/passage-index.js +405 -0
  1424. package/dist/research/paper-qa/pdf-structure.d.ts +37 -0
  1425. package/dist/research/paper-qa/pdf-structure.js +377 -0
  1426. package/dist/research/paper-qa/persistent-corpus-index.d.ts +23 -0
  1427. package/dist/research/paper-qa/persistent-corpus-index.js +122 -0
  1428. package/dist/research/paper-qa/prose-chunker.d.ts +19 -0
  1429. package/dist/research/paper-qa/prose-chunker.js +201 -0
  1430. package/dist/research/paper-qa/provenance.d.ts +24 -0
  1431. package/dist/research/paper-qa/provenance.js +40 -0
  1432. package/dist/research/paper-qa/rcs.d.ts +78 -0
  1433. package/dist/research/paper-qa/rcs.js +200 -0
  1434. package/dist/research/paper-qa/types.d.ts +124 -0
  1435. package/dist/research/paper-qa/types.js +13 -0
  1436. package/dist/research/publication-sources.d.ts +34 -0
  1437. package/dist/research/publication-sources.js +131 -0
  1438. package/dist/research/relation-classifier.d.ts +13 -0
  1439. package/dist/research/relation-classifier.js +58 -0
  1440. package/dist/research/research-topics.d.ts +13 -0
  1441. package/dist/research/research-topics.js +81 -0
  1442. package/dist/review/apply-transaction.d.ts +40 -0
  1443. package/dist/review/apply-transaction.js +112 -0
  1444. package/dist/review/diff-model.d.ts +39 -0
  1445. package/dist/review/diff-model.js +124 -0
  1446. package/dist/review/llm-client.d.ts +30 -0
  1447. package/dist/review/llm-client.js +98 -0
  1448. package/dist/review/llm-reviewer.d.ts +16 -0
  1449. package/dist/review/llm-reviewer.js +122 -0
  1450. package/dist/review/review-engine.d.ts +54 -0
  1451. package/dist/review/review-engine.js +0 -0
  1452. package/dist/review/revision-loop.d.ts +67 -0
  1453. package/dist/review/revision-loop.js +160 -0
  1454. package/dist/review/static-gate.d.ts +13 -0
  1455. package/dist/review/static-gate.js +110 -0
  1456. package/dist/review/types.d.ts +122 -0
  1457. package/dist/review/types.js +24 -0
  1458. package/dist/review/write-gate.d.ts +55 -0
  1459. package/dist/review/write-gate.js +121 -0
  1460. package/dist/sandbox/auto-sandbox.d.ts +4 -2
  1461. package/dist/sandbox/auto-sandbox.js +14 -1
  1462. package/dist/sandbox/docker-sandbox.d.ts +39 -0
  1463. package/dist/sandbox/docker-sandbox.js +292 -14
  1464. package/dist/sandbox/execpolicy.d.ts +36 -1
  1465. package/dist/sandbox/execpolicy.js +375 -40
  1466. package/dist/sandbox/os-sandbox.d.ts +53 -0
  1467. package/dist/sandbox/os-sandbox.js +315 -70
  1468. package/dist/sandbox/sandbox-backend.d.ts +2 -0
  1469. package/dist/scheduler/cron-scheduler.d.ts +1 -0
  1470. package/dist/scheduler/cron-scheduler.js +142 -41
  1471. package/dist/scripting/codebuddy-bindings.js +2 -1
  1472. package/dist/search/bm25.js +5 -2
  1473. package/dist/search/usearch-index.js +7 -5
  1474. package/dist/security/audit-logger.js +14 -7
  1475. package/dist/security/bash-allowlist/allowlist-store.d.ts +8 -2
  1476. package/dist/security/bash-allowlist/allowlist-store.js +52 -12
  1477. package/dist/security/bash-allowlist/approval-flow.d.ts +1 -1
  1478. package/dist/security/bash-allowlist/approval-flow.js +10 -8
  1479. package/dist/security/bash-allowlist/deny-guard.d.ts +14 -0
  1480. package/dist/security/bash-allowlist/deny-guard.js +61 -0
  1481. package/dist/security/bash-allowlist/types.d.ts +5 -0
  1482. package/dist/security/bash-parser.d.ts +32 -0
  1483. package/dist/security/bash-parser.js +129 -14
  1484. package/dist/security/dangerous-patterns.js +18 -3
  1485. package/dist/security/declarative-rules.d.ts +1 -1
  1486. package/dist/security/declarative-rules.js +242 -65
  1487. package/dist/security/dependency-vuln-scanner.js +4 -4
  1488. package/dist/security/dev-origins.d.ts +40 -0
  1489. package/dist/security/dev-origins.js +111 -0
  1490. package/dist/security/docker-sandbox/manager.js +1 -1
  1491. package/dist/security/env-blocklist.d.ts +7 -0
  1492. package/dist/security/env-blocklist.js +22 -2
  1493. package/dist/security/guardian-agent.d.ts +0 -5
  1494. package/dist/security/guardian-agent.js +17 -6
  1495. package/dist/security/index.d.ts +3 -0
  1496. package/dist/security/index.js +2 -0
  1497. package/dist/security/native-sandbox.d.ts +80 -0
  1498. package/dist/security/native-sandbox.js +455 -0
  1499. package/dist/security/pack-contents-policy.d.ts +49 -0
  1500. package/dist/security/pack-contents-policy.js +139 -0
  1501. package/dist/security/permission-config.js +2 -5
  1502. package/dist/security/permission-modes.d.ts +11 -0
  1503. package/dist/security/permission-modes.js +71 -7
  1504. package/dist/security/policy-amendments.js +40 -22
  1505. package/dist/security/policy-engine.js +39 -12
  1506. package/dist/security/powershell-parser.d.ts +40 -0
  1507. package/dist/security/powershell-parser.js +198 -0
  1508. package/dist/security/remote-approval.d.ts +0 -1
  1509. package/dist/security/remote-approval.js +3 -2
  1510. package/dist/security/safe-binaries.d.ts +13 -1
  1511. package/dist/security/safe-binaries.js +240 -32
  1512. package/dist/security/safe-fetch.d.ts +7 -0
  1513. package/dist/security/safe-fetch.js +101 -0
  1514. package/dist/security/sandbox.js +2 -2
  1515. package/dist/security/secret-patterns.d.ts +18 -0
  1516. package/dist/security/secret-patterns.js +232 -0
  1517. package/dist/security/secret-scrubber.d.ts +31 -0
  1518. package/dist/security/secret-scrubber.js +170 -0
  1519. package/dist/security/secrets-detector.d.ts +3 -1
  1520. package/dist/security/secrets-detector.js +3 -106
  1521. package/dist/security/security-modes.js +2 -1
  1522. package/dist/security/session-encryption.d.ts +7 -2
  1523. package/dist/security/session-encryption.js +28 -7
  1524. package/dist/security/shell-env-policy.js +11 -2
  1525. package/dist/security/skill-scanner.d.ts +2 -2
  1526. package/dist/security/skill-scanner.js +237 -11
  1527. package/dist/security/ssrf-guard.d.ts +13 -0
  1528. package/dist/security/ssrf-guard.js +27 -0
  1529. package/dist/security/text-deobfuscation.d.ts +41 -0
  1530. package/dist/security/text-deobfuscation.js +256 -0
  1531. package/dist/security/tool-permissions.js +2 -3
  1532. package/dist/security/tool-policy/approval-scope.d.ts +11 -0
  1533. package/dist/security/tool-policy/approval-scope.js +67 -0
  1534. package/dist/security/tool-policy/policy-manager.d.ts +9 -0
  1535. package/dist/security/tool-policy/policy-manager.js +28 -1
  1536. package/dist/security/tool-policy/profiles.js +24 -0
  1537. package/dist/security/tool-policy/tool-groups.js +26 -3
  1538. package/dist/security/tool-policy/types.d.ts +3 -1
  1539. package/dist/security/tool-policy/types.js +2 -0
  1540. package/dist/security/trust-folders.js +3 -2
  1541. package/dist/security/write-policy.d.ts +8 -0
  1542. package/dist/security/write-policy.js +63 -1
  1543. package/dist/self-model/evolution-notes.d.ts +51 -0
  1544. package/dist/self-model/evolution-notes.js +324 -0
  1545. package/dist/sensory/agent-reply.d.ts +136 -0
  1546. package/dist/sensory/agent-reply.js +682 -0
  1547. package/dist/sensory/alert.d.ts +18 -0
  1548. package/dist/sensory/alert.js +105 -0
  1549. package/dist/sensory/arrival-opener.d.ts +102 -0
  1550. package/dist/sensory/arrival-opener.js +292 -0
  1551. package/dist/sensory/audio-scene.d.ts +24 -0
  1552. package/dist/sensory/audio-scene.js +74 -0
  1553. package/dist/sensory/camera-keyframe-policy.d.ts +11 -0
  1554. package/dist/sensory/camera-keyframe-policy.js +43 -0
  1555. package/dist/sensory/conversation-cues.d.ts +55 -0
  1556. package/dist/sensory/conversation-cues.js +140 -0
  1557. package/dist/sensory/domain-event-bridge.d.ts +7 -0
  1558. package/dist/sensory/domain-event-bridge.js +134 -0
  1559. package/dist/sensory/dreaming.d.ts +17 -0
  1560. package/dist/sensory/dreaming.js +52 -2
  1561. package/dist/sensory/elevenlabs-library.d.ts +91 -0
  1562. package/dist/sensory/elevenlabs-library.js +303 -0
  1563. package/dist/sensory/episodic-journal.d.ts +69 -0
  1564. package/dist/sensory/episodic-journal.js +240 -0
  1565. package/dist/sensory/error-watch-reaction.d.ts +41 -0
  1566. package/dist/sensory/error-watch-reaction.js +312 -0
  1567. package/dist/sensory/heartbeat-fallback.d.ts +46 -0
  1568. package/dist/sensory/heartbeat-fallback.js +171 -0
  1569. package/dist/sensory/heartbeat-scheduler.d.ts +6 -0
  1570. package/dist/sensory/heartbeat-scheduler.js +27 -7
  1571. package/dist/sensory/hybrid-reply.d.ts +132 -0
  1572. package/dist/sensory/hybrid-reply.js +1217 -0
  1573. package/dist/sensory/reactions.d.ts +6 -0
  1574. package/dist/sensory/reactions.js +10 -1
  1575. package/dist/sensory/respond-decider.d.ts +124 -0
  1576. package/dist/sensory/respond-decider.js +608 -0
  1577. package/dist/sensory/rule-templates.d.ts +30 -0
  1578. package/dist/sensory/rule-templates.js +100 -0
  1579. package/dist/sensory/schedule-emitter.d.ts +24 -0
  1580. package/dist/sensory/schedule-emitter.js +57 -0
  1581. package/dist/sensory/screen-reaction.js +15 -1
  1582. package/dist/sensory/semantic-vision-reaction.d.ts +36 -0
  1583. package/dist/sensory/semantic-vision-reaction.js +342 -0
  1584. package/dist/sensory/sensory-action-executor.d.ts +98 -0
  1585. package/dist/sensory/sensory-action-executor.js +473 -0
  1586. package/dist/sensory/sensory-bridge.d.ts +11 -1
  1587. package/dist/sensory/sensory-bridge.js +59 -7
  1588. package/dist/sensory/sensory-rules-engine.d.ts +81 -0
  1589. package/dist/sensory/sensory-rules-engine.js +434 -0
  1590. package/dist/sensory/sensory-status.d.ts +102 -0
  1591. package/dist/sensory/sensory-status.js +291 -0
  1592. package/dist/sensory/speech-engine-config.d.ts +68 -0
  1593. package/dist/sensory/speech-engine-config.js +157 -0
  1594. package/dist/sensory/speech-reaction.d.ts +183 -7
  1595. package/dist/sensory/speech-reaction.js +2141 -35
  1596. package/dist/sensory/speech-sanitizer.d.ts +12 -0
  1597. package/dist/sensory/speech-sanitizer.js +143 -0
  1598. package/dist/sensory/system-vitals-emitter.d.ts +130 -0
  1599. package/dist/sensory/system-vitals-emitter.js +514 -0
  1600. package/dist/sensory/tts-cache.d.ts +76 -0
  1601. package/dist/sensory/tts-cache.js +0 -0
  1602. package/dist/sensory/turn-detector.d.ts +28 -0
  1603. package/dist/sensory/turn-detector.js +57 -0
  1604. package/dist/sensory/vision-description-safety.d.ts +4 -0
  1605. package/dist/sensory/vision-description-safety.js +25 -0
  1606. package/dist/sensory/vision-reaction.d.ts +21 -7
  1607. package/dist/sensory/vision-reaction.js +209 -18
  1608. package/dist/sensory/voice-activity.d.ts +69 -0
  1609. package/dist/sensory/voice-activity.js +271 -0
  1610. package/dist/sensory/voice-clock.d.ts +19 -0
  1611. package/dist/sensory/voice-clock.js +111 -0
  1612. package/dist/sensory/voice-entrainment.d.ts +62 -0
  1613. package/dist/sensory/voice-entrainment.js +176 -0
  1614. package/dist/sensory/voice-interactions.d.ts +13 -0
  1615. package/dist/sensory/voice-interactions.js +258 -0
  1616. package/dist/sensory/voice-loop.d.ts +618 -0
  1617. package/dist/sensory/voice-loop.js +3581 -0
  1618. package/dist/sensory/voice-replay-lab.d.ts +32 -0
  1619. package/dist/sensory/voice-replay-lab.js +109 -0
  1620. package/dist/sensory/voice-stream.d.ts +121 -0
  1621. package/dist/sensory/voice-stream.js +598 -0
  1622. package/dist/sensory/voice-turn-coordinator.d.ts +88 -0
  1623. package/dist/sensory/voice-turn-coordinator.js +258 -0
  1624. package/dist/sensory/voice-turn-taking.d.ts +26 -0
  1625. package/dist/sensory/voice-turn-taking.js +59 -0
  1626. package/dist/server/agent-adapter.d.ts +49 -3
  1627. package/dist/server/agent-adapter.js +26 -4
  1628. package/dist/server/channel-a2a-bridge.js +1 -1
  1629. package/dist/server/exposure-diagnostic.d.ts +25 -0
  1630. package/dist/server/exposure-diagnostic.js +51 -0
  1631. package/dist/server/heartbeat-monitor.d.ts +13 -0
  1632. package/dist/server/heartbeat-monitor.js +8 -3
  1633. package/dist/server/http-agent-sessions.d.ts +32 -0
  1634. package/dist/server/http-agent-sessions.js +245 -0
  1635. package/dist/server/index.d.ts +3 -0
  1636. package/dist/server/index.js +913 -46
  1637. package/dist/server/mcp/approval-elicitation.d.ts +144 -0
  1638. package/dist/server/mcp/approval-elicitation.js +377 -0
  1639. package/dist/server/middleware/auth.d.ts +11 -0
  1640. package/dist/server/middleware/auth.js +54 -0
  1641. package/dist/server/middleware/error-handler.d.ts +5 -0
  1642. package/dist/server/middleware/error-handler.js +30 -4
  1643. package/dist/server/middleware/index.d.ts +1 -1
  1644. package/dist/server/middleware/index.js +1 -1
  1645. package/dist/server/mobile/album.d.ts +46 -0
  1646. package/dist/server/mobile/album.js +144 -0
  1647. package/dist/server/mobile/assets/app.js +3036 -0
  1648. package/dist/server/mobile/assets/emoji-data.js +508 -0
  1649. package/dist/server/mobile/assets/icon-192.png +0 -0
  1650. package/dist/server/mobile/assets/icon-512.png +0 -0
  1651. package/dist/server/mobile/assets/icon-96.png +0 -0
  1652. package/dist/server/mobile/assets/icon.svg +12 -0
  1653. package/dist/server/mobile/assets/index.html +261 -0
  1654. package/dist/server/mobile/assets/manifest.webmanifest +37 -0
  1655. package/dist/server/mobile/assets/styles.css +831 -0
  1656. package/dist/server/mobile/assets/sw.js +149 -0
  1657. package/dist/server/mobile/chat-extras.d.ts +9 -0
  1658. package/dist/server/mobile/chat-extras.js +24 -0
  1659. package/dist/server/mobile/index.d.ts +22 -0
  1660. package/dist/server/mobile/index.js +287 -0
  1661. package/dist/server/mobile/link-preview.d.ts +24 -0
  1662. package/dist/server/mobile/link-preview.js +139 -0
  1663. package/dist/server/mobile/push.d.ts +38 -0
  1664. package/dist/server/mobile/push.js +190 -0
  1665. package/dist/server/mobile/status.d.ts +23 -0
  1666. package/dist/server/mobile/status.js +107 -0
  1667. package/dist/server/mobile/telegram-forward.d.ts +14 -0
  1668. package/dist/server/mobile/telegram-forward.js +32 -0
  1669. package/dist/server/mobile/voice-note.d.ts +54 -0
  1670. package/dist/server/mobile/voice-note.js +305 -0
  1671. package/dist/server/origin-check.d.ts +4 -5
  1672. package/dist/server/origin-check.js +43 -8
  1673. package/dist/server/routes/canvas.d.ts +7 -1
  1674. package/dist/server/routes/canvas.js +138 -24
  1675. package/dist/server/routes/chat.js +340 -203
  1676. package/dist/server/routes/cognition.d.ts +3 -0
  1677. package/dist/server/routes/cognition.js +75 -0
  1678. package/dist/server/routes/health.js +93 -81
  1679. package/dist/server/routes/index.d.ts +5 -1
  1680. package/dist/server/routes/index.js +5 -1
  1681. package/dist/server/routes/lessons.d.ts +13 -0
  1682. package/dist/server/routes/lessons.js +111 -0
  1683. package/dist/server/routes/memory.d.ts +12 -0
  1684. package/dist/server/routes/memory.js +191 -131
  1685. package/dist/server/routes/runs.d.ts +9 -0
  1686. package/dist/server/routes/runs.js +50 -0
  1687. package/dist/server/routes/sessions.js +8 -1
  1688. package/dist/server/routes/tools.js +93 -74
  1689. package/dist/server/routes/webhooks.js +56 -46
  1690. package/dist/server/tunnel-manager.js +21 -1
  1691. package/dist/server/types.d.ts +25 -1
  1692. package/dist/server/webhook-agent-queue.d.ts +12 -0
  1693. package/dist/server/webhook-agent-queue.js +58 -0
  1694. package/dist/server/websocket/cognition-bridge.d.ts +13 -0
  1695. package/dist/server/websocket/cognition-bridge.js +334 -0
  1696. package/dist/server/websocket/confirmation-bridge.d.ts +22 -0
  1697. package/dist/server/websocket/confirmation-bridge.js +178 -0
  1698. package/dist/server/websocket/desktop-handler.d.ts +17 -0
  1699. package/dist/server/websocket/desktop-handler.js +177 -16
  1700. package/dist/server/websocket/handler.d.ts +123 -1
  1701. package/dist/server/websocket/handler.js +852 -67
  1702. package/dist/server/websocket/index.d.ts +2 -1
  1703. package/dist/server/websocket/index.js +2 -1
  1704. package/dist/server/websocket/peer-rpc.d.ts +1 -1
  1705. package/dist/server/websocket/peer-rpc.js +25 -3
  1706. package/dist/services/prompt-builder.d.ts +47 -2
  1707. package/dist/services/prompt-builder.js +310 -99
  1708. package/dist/sessions/timeline-snapshot.d.ts +35 -0
  1709. package/dist/sessions/timeline-snapshot.js +144 -0
  1710. package/dist/sessions/timeline.d.ts +33 -0
  1711. package/dist/sessions/timeline.js +85 -0
  1712. package/dist/shared/context-optimization-metadata.d.ts +29 -0
  1713. package/dist/shared/context-optimization-metadata.js +73 -0
  1714. package/dist/shared/engine-types.d.ts +26 -0
  1715. package/dist/skills/bash-injection.d.ts +2 -2
  1716. package/dist/skills/bash-injection.js +9 -2
  1717. package/dist/skills/bundled/code-explorer.skill.md +50 -0
  1718. package/dist/skills/bundled/file-edit.skill.md +62 -0
  1719. package/dist/skills/bundled/git-commit.skill.md +66 -0
  1720. package/dist/skills/bundled/pubcommander-control/SKILL.md +33 -0
  1721. package/dist/skills/bundled/pubcommander-control/agents/openai.yaml +4 -0
  1722. package/dist/skills/bundled/typescript-expert.skill.md +21 -0
  1723. package/dist/skills/bundled/weather.skill.md +48 -0
  1724. package/dist/skills/bundled/web-app-testing.skill.md +71 -0
  1725. package/dist/skills/bundled/web-search.skill.md +56 -0
  1726. package/dist/skills/hub.js +52 -30
  1727. package/dist/skills/index.d.ts +6 -3
  1728. package/dist/skills/index.js +19 -4
  1729. package/dist/skills/parser.js +2 -0
  1730. package/dist/skills/registry.d.ts +52 -0
  1731. package/dist/skills/registry.js +291 -14
  1732. package/dist/skills/skill-exchange.d.ts +61 -0
  1733. package/dist/skills/skill-exchange.js +523 -0
  1734. package/dist/skills/skill-importer.d.ts +2 -2
  1735. package/dist/skills/skill-importer.js +76 -17
  1736. package/dist/skills/skill-registry.js +3 -2
  1737. package/dist/skills/skill-signing.d.ts +20 -0
  1738. package/dist/skills/skill-signing.js +106 -0
  1739. package/dist/skills/skill-sources.d.ts +3 -2
  1740. package/dist/skills/skill-sources.js +5 -4
  1741. package/dist/skills/types.d.ts +4 -0
  1742. package/dist/spec/spec-store.js +7 -6
  1743. package/dist/speculative/shadow-workspace.d.ts +79 -0
  1744. package/dist/speculative/shadow-workspace.js +500 -0
  1745. package/dist/talk-mode/index.d.ts +4 -4
  1746. package/dist/talk-mode/index.js +3 -3
  1747. package/dist/talk-mode/providers/elevenlabs-client.d.ts +48 -0
  1748. package/dist/talk-mode/providers/elevenlabs-client.js +117 -0
  1749. package/dist/talk-mode/providers/elevenlabs.js +12 -23
  1750. package/dist/talk-mode/providers/index.d.ts +3 -1
  1751. package/dist/talk-mode/providers/index.js +2 -0
  1752. package/dist/talk-mode/providers/pocket-tts.d.ts +88 -0
  1753. package/dist/talk-mode/providers/pocket-tts.js +334 -0
  1754. package/dist/talk-mode/providers/voicebox-tts.d.ts +24 -0
  1755. package/dist/talk-mode/providers/voicebox-tts.js +120 -0
  1756. package/dist/talk-mode/types.d.ts +39 -1
  1757. package/dist/tasks/background-tasks.js +22 -5
  1758. package/dist/telemetry/otel-tracer.js +5 -2
  1759. package/dist/templates/design-system-apply.d.ts +23 -0
  1760. package/dist/templates/design-system-apply.js +100 -0
  1761. package/dist/templates/project-scaffolding.d.ts +2 -0
  1762. package/dist/templates/project-scaffolding.js +616 -1
  1763. package/dist/themes/theme-manager.js +9 -6
  1764. package/dist/themes/theme-schema.d.ts +46 -46
  1765. package/dist/tools/advanced/multi-file-editor.js +3 -1
  1766. package/dist/tools/advanced/operation-history.js +2 -1
  1767. package/dist/tools/app-server-tool.d.ts +66 -0
  1768. package/dist/tools/app-server-tool.js +423 -0
  1769. package/dist/tools/apply-patch.d.ts +31 -1
  1770. package/dist/tools/apply-patch.js +214 -19
  1771. package/dist/tools/authored-tools-manifest-2.d.ts +17 -0
  1772. package/dist/tools/authored-tools-manifest-2.js +133 -0
  1773. package/dist/tools/authored-tools-manifest.d.ts +15 -0
  1774. package/dist/tools/authored-tools-manifest.js +13 -0
  1775. package/dist/tools/bash/bash-tool.d.ts +36 -3
  1776. package/dist/tools/bash/bash-tool.js +240 -100
  1777. package/dist/tools/bash/command-validator.d.ts +1 -1
  1778. package/dist/tools/bash/command-validator.js +115 -40
  1779. package/dist/tools/bash/execution-policy.d.ts +42 -0
  1780. package/dist/tools/bash/execution-policy.js +278 -0
  1781. package/dist/tools/bash/security-patterns.js +43 -5
  1782. package/dist/tools/bash/streaming-executor.d.ts +1 -1
  1783. package/dist/tools/bash/streaming-executor.js +124 -18
  1784. package/dist/tools/build-project-tool.d.ts +25 -0
  1785. package/dist/tools/build-project-tool.js +30 -0
  1786. package/dist/tools/bundle-analyze-tool.d.ts +28 -0
  1787. package/dist/tools/bundle-analyze-tool.js +39 -0
  1788. package/dist/tools/code-exec-tool.d.ts +55 -23
  1789. package/dist/tools/code-exec-tool.js +598 -111
  1790. package/dist/tools/code-explorer-tool.d.ts +1 -1
  1791. package/dist/tools/code-explorer-tool.js +25 -1
  1792. package/dist/tools/code-review.js +5 -0
  1793. package/dist/tools/code-stats-tool.d.ts +43 -0
  1794. package/dist/tools/code-stats-tool.js +70 -0
  1795. package/dist/tools/codebase-replace-tool.js +2 -2
  1796. package/dist/tools/comfy-recipe-tool.d.ts +37 -0
  1797. package/dist/tools/comfy-recipe-tool.js +693 -0
  1798. package/dist/tools/community-search.d.ts +93 -0
  1799. package/dist/tools/community-search.js +334 -0
  1800. package/dist/tools/computer-control-harness.js +5 -2
  1801. package/dist/tools/computer-control-tool.d.ts +8 -0
  1802. package/dist/tools/computer-control-tool.js +71 -26
  1803. package/dist/tools/context-expand-tool.d.ts +19 -0
  1804. package/dist/tools/context-expand-tool.js +132 -0
  1805. package/dist/tools/csv/csv-parse.d.ts +19 -0
  1806. package/dist/tools/csv/csv-parse.js +132 -0
  1807. package/dist/tools/csv/csv-wiring.d.ts +8 -0
  1808. package/dist/tools/csv/csv-wiring.js +9 -0
  1809. package/dist/tools/csv-analyze-tool.d.ts +11 -0
  1810. package/dist/tools/csv-analyze-tool.js +114 -0
  1811. package/dist/tools/csv-preview-tool.d.ts +34 -0
  1812. package/dist/tools/csv-preview-tool.js +69 -0
  1813. package/dist/tools/db-migration.js +11 -3
  1814. package/dist/tools/deep-research-tool.d.ts +68 -0
  1815. package/dist/tools/deep-research-tool.js +257 -0
  1816. package/dist/tools/deferred-schema-state.d.ts +19 -0
  1817. package/dist/tools/deferred-schema-state.js +33 -0
  1818. package/dist/tools/dep-inspect-tool.d.ts +32 -0
  1819. package/dist/tools/dep-inspect-tool.js +74 -0
  1820. package/dist/tools/design-system-tool.d.ts +10 -0
  1821. package/dist/tools/design-system-tool.js +95 -0
  1822. package/dist/tools/device-tool.d.ts +2 -1
  1823. package/dist/tools/device-tool.js +21 -0
  1824. package/dist/tools/diagram-tool.js +8 -2
  1825. package/dist/tools/diff-files-tool.d.ts +28 -0
  1826. package/dist/tools/diff-files-tool.js +49 -0
  1827. package/dist/tools/enhanced-search.js +32 -16
  1828. package/dist/tools/env-doctor-tool.d.ts +30 -0
  1829. package/dist/tools/env-doctor-tool.js +54 -0
  1830. package/dist/tools/execute-code-rpc-invoker.js +2 -2
  1831. package/dist/tools/execute-code-runner.d.ts +21 -0
  1832. package/dist/tools/execute-code-runner.js +117 -8
  1833. package/dist/tools/extension-forge-tool.d.ts +29 -0
  1834. package/dist/tools/extension-forge-tool.js +288 -0
  1835. package/dist/tools/fetch-tool.js +7 -3
  1836. package/dist/tools/file-search-tool.d.ts +41 -0
  1837. package/dist/tools/file-search-tool.js +99 -0
  1838. package/dist/tools/format-project-tool.d.ts +28 -0
  1839. package/dist/tools/format-project-tool.js +45 -0
  1840. package/dist/tools/git-summary-tool.d.ts +36 -0
  1841. package/dist/tools/git-summary-tool.js +65 -0
  1842. package/dist/tools/git-tool.js +16 -4
  1843. package/dist/tools/gpu-avatar-delivery.d.ts +16 -0
  1844. package/dist/tools/gpu-avatar-delivery.js +67 -0
  1845. package/dist/tools/gpu-media-worker.d.ts +96 -0
  1846. package/dist/tools/gpu-media-worker.js +363 -0
  1847. package/dist/tools/gui-tool.js +92 -13
  1848. package/dist/tools/http-probe-tool.d.ts +25 -0
  1849. package/dist/tools/http-probe-tool.js +40 -0
  1850. package/dist/tools/image-tool.js +29 -16
  1851. package/dist/tools/index.d.ts +6 -1
  1852. package/dist/tools/index.js +5 -0
  1853. package/dist/tools/interactive-bash.d.ts +29 -1
  1854. package/dist/tools/interactive-bash.js +141 -21
  1855. package/dist/tools/json-query-tool.d.ts +30 -0
  1856. package/dist/tools/json-query-tool.js +49 -0
  1857. package/dist/tools/license-check-tool.d.ts +22 -0
  1858. package/dist/tools/license-check-tool.js +43 -0
  1859. package/dist/tools/lint-project-tool.d.ts +52 -0
  1860. package/dist/tools/lint-project-tool.js +143 -0
  1861. package/dist/tools/local-binary-launch.d.ts +14 -0
  1862. package/dist/tools/local-binary-launch.js +63 -0
  1863. package/dist/tools/lsp-navigation-tools.d.ts +87 -0
  1864. package/dist/tools/lsp-navigation-tools.js +470 -0
  1865. package/dist/tools/markdown-convert.d.ts +51 -0
  1866. package/dist/tools/markdown-convert.js +159 -0
  1867. package/dist/tools/media-generation-tool.d.ts +90 -1
  1868. package/dist/tools/media-generation-tool.js +1553 -11
  1869. package/dist/tools/meeting-notes-tool.d.ts +25 -0
  1870. package/dist/tools/meeting-notes-tool.js +240 -0
  1871. package/dist/tools/merge-conflict-tool.js +1 -1
  1872. package/dist/tools/metadata.d.ts +7 -1
  1873. package/dist/tools/metadata.js +823 -13
  1874. package/dist/tools/mixture-of-agents-tool.d.ts +7 -0
  1875. package/dist/tools/mixture-of-agents-tool.js +230 -31
  1876. package/dist/tools/multi-edit.js +42 -18
  1877. package/dist/tools/ocr-tool.d.ts +43 -0
  1878. package/dist/tools/ocr-tool.js +24 -18
  1879. package/dist/tools/omission-placeholder-detector.js +12 -6
  1880. package/dist/tools/paper-qa-tool.d.ts +73 -0
  1881. package/dist/tools/paper-qa-tool.js +313 -0
  1882. package/dist/tools/peer-chain-tool.js +4 -1
  1883. package/dist/tools/peer-delegate-tool.d.ts +2 -0
  1884. package/dist/tools/peer-delegate-tool.js +11 -1
  1885. package/dist/tools/port-check-tool.d.ts +31 -0
  1886. package/dist/tools/port-check-tool.js +25 -0
  1887. package/dist/tools/project-map-tool.d.ts +39 -0
  1888. package/dist/tools/project-map-tool.js +128 -0
  1889. package/dist/tools/register-tool-handler.d.ts +2 -2
  1890. package/dist/tools/register-tool-handler.js +7 -4
  1891. package/dist/tools/registry/advanced-tools.js +1 -1
  1892. package/dist/tools/registry/attention-tools.d.ts +3 -3
  1893. package/dist/tools/registry/attention-tools.js +14 -10
  1894. package/dist/tools/registry/authored-extra-tools.d.ts +20 -0
  1895. package/dist/tools/registry/authored-extra-tools.js +147 -0
  1896. package/dist/tools/registry/bash-tools.d.ts +2 -2
  1897. package/dist/tools/registry/bash-tools.js +7 -3
  1898. package/dist/tools/registry/browser-operator-tools.d.ts +1 -1
  1899. package/dist/tools/registry/browser-operator-tools.js +17 -3
  1900. package/dist/tools/registry/browser-tools.d.ts +1 -1
  1901. package/dist/tools/registry/browser-tools.js +38 -33
  1902. package/dist/tools/registry/code-explorer-tools.js +6 -1
  1903. package/dist/tools/registry/comfy-recipe-tools.d.ts +2 -0
  1904. package/dist/tools/registry/comfy-recipe-tools.js +5 -0
  1905. package/dist/tools/registry/context-expand-tools.d.ts +3 -0
  1906. package/dist/tools/registry/context-expand-tools.js +6 -0
  1907. package/dist/tools/registry/csv-tools.d.ts +12 -0
  1908. package/dist/tools/registry/csv-tools.js +62 -0
  1909. package/dist/tools/registry/delegate-agent-tools.d.ts +64 -0
  1910. package/dist/tools/registry/delegate-agent-tools.js +206 -0
  1911. package/dist/tools/registry/design-tools.d.ts +12 -0
  1912. package/dist/tools/registry/design-tools.js +80 -0
  1913. package/dist/tools/registry/fleet-tools.js +6 -0
  1914. package/dist/tools/registry/index.d.ts +25 -5
  1915. package/dist/tools/registry/index.js +80 -6
  1916. package/dist/tools/registry/interactive-adapters.d.ts +37 -0
  1917. package/dist/tools/registry/interactive-adapters.js +116 -0
  1918. package/dist/tools/registry/lsp-tools.d.ts +3 -3
  1919. package/dist/tools/registry/lsp-tools.js +9 -3
  1920. package/dist/tools/registry/meeting-tools.d.ts +3 -0
  1921. package/dist/tools/registry/meeting-tools.js +6 -0
  1922. package/dist/tools/registry/memory-tools.js +32 -20
  1923. package/dist/tools/registry/misc-tools.d.ts +1 -1
  1924. package/dist/tools/registry/misc-tools.js +7 -4
  1925. package/dist/tools/registry/moa-tools.js +13 -0
  1926. package/dist/tools/registry/multimodal-tools.d.ts +73 -1
  1927. package/dist/tools/registry/multimodal-tools.js +581 -4
  1928. package/dist/tools/registry/process-tools.d.ts +16 -0
  1929. package/dist/tools/registry/process-tools.js +136 -1
  1930. package/dist/tools/registry/remind-tools.d.ts +23 -0
  1931. package/dist/tools/registry/remind-tools.js +120 -0
  1932. package/dist/tools/registry/research-tools.d.ts +17 -0
  1933. package/dist/tools/registry/research-tools.js +21 -0
  1934. package/dist/tools/registry/search-tools.d.ts +6 -6
  1935. package/dist/tools/registry/search-tools.js +30 -17
  1936. package/dist/tools/registry/secrets-tools.d.ts +33 -0
  1937. package/dist/tools/registry/secrets-tools.js +71 -0
  1938. package/dist/tools/registry/self-describe-tools.d.ts +23 -0
  1939. package/dist/tools/registry/self-describe-tools.js +156 -0
  1940. package/dist/tools/registry/self-evolution-tools.d.ts +13 -0
  1941. package/dist/tools/registry/self-evolution-tools.js +97 -0
  1942. package/dist/tools/registry/text-editor-tools.d.ts +26 -4
  1943. package/dist/tools/registry/text-editor-tools.js +102 -6
  1944. package/dist/tools/registry/tool-alias-map.d.ts +8 -0
  1945. package/dist/tools/registry/tool-alias-map.js +47 -0
  1946. package/dist/tools/registry/tool-aliases.d.ts +3 -4
  1947. package/dist/tools/registry/tool-aliases.js +12 -48
  1948. package/dist/tools/registry/types.d.ts +5 -0
  1949. package/dist/tools/registry/verify-tools.d.ts +50 -0
  1950. package/dist/tools/registry/verify-tools.js +136 -0
  1951. package/dist/tools/registry/video-studio-tools.d.ts +13 -0
  1952. package/dist/tools/registry/video-studio-tools.js +21 -0
  1953. package/dist/tools/registry/vision-tools.d.ts +15 -1
  1954. package/dist/tools/registry/vision-tools.js +252 -27
  1955. package/dist/tools/registry/web-test-tool.d.ts +66 -0
  1956. package/dist/tools/registry/web-test-tool.js +321 -0
  1957. package/dist/tools/registry/web-tools.d.ts +43 -0
  1958. package/dist/tools/registry/web-tools.js +281 -1
  1959. package/dist/tools/review-gate-helper.d.ts +44 -0
  1960. package/dist/tools/review-gate-helper.js +110 -0
  1961. package/dist/tools/route-peer-tool.js +62 -11
  1962. package/dist/tools/sbom-generate-tool.d.ts +22 -0
  1963. package/dist/tools/sbom-generate-tool.js +41 -0
  1964. package/dist/tools/scaffold-app-tool.d.ts +48 -0
  1965. package/dist/tools/scaffold-app-tool.js +144 -0
  1966. package/dist/tools/screenshot-tool.js +5 -2
  1967. package/dist/tools/search.d.ts +17 -0
  1968. package/dist/tools/search.js +31 -8
  1969. package/dist/tools/self-describe.d.ts +73 -0
  1970. package/dist/tools/self-describe.js +298 -0
  1971. package/dist/tools/stock-quote.d.ts +67 -0
  1972. package/dist/tools/stock-quote.js +645 -0
  1973. package/dist/tools/submit-plan-tool.js +1 -1
  1974. package/dist/tools/test-runner-tool.d.ts +38 -0
  1975. package/dist/tools/test-runner-tool.js +96 -0
  1976. package/dist/tools/text-editor.js +91 -8
  1977. package/dist/tools/text-to-speech-tool.d.ts +1 -1
  1978. package/dist/tools/text-to-speech-tool.js +48 -2
  1979. package/dist/tools/todo-scan-tool.d.ts +39 -0
  1980. package/dist/tools/todo-scan-tool.js +53 -0
  1981. package/dist/tools/tool-manager.js +8 -0
  1982. package/dist/tools/tool-search.js +11 -3
  1983. package/dist/tools/tool-selector.d.ts +7 -0
  1984. package/dist/tools/tool-selector.js +27 -13
  1985. package/dist/tools/tools-md-generator.js +2 -2
  1986. package/dist/tools/types.d.ts +16 -0
  1987. package/dist/tools/types.js +5 -1
  1988. package/dist/tools/video/approved-media-source.d.ts +8 -0
  1989. package/dist/tools/video/approved-media-source.js +59 -0
  1990. package/dist/tools/video/book-manuscript-source.d.ts +49 -0
  1991. package/dist/tools/video/book-manuscript-source.js +263 -0
  1992. package/dist/tools/video/character-in-location.d.ts +42 -0
  1993. package/dist/tools/video/character-in-location.js +161 -0
  1994. package/dist/tools/video/cinematic-trailer-plan.d.ts +203 -0
  1995. package/dist/tools/video/cinematic-trailer-plan.js +498 -0
  1996. package/dist/tools/video/cloud-understand.d.ts +91 -0
  1997. package/dist/tools/video/cloud-understand.js +214 -0
  1998. package/dist/tools/video/comfy-client.d.ts +38 -0
  1999. package/dist/tools/video/comfy-client.js +227 -0
  2000. package/dist/tools/video/comfy-workflow-template.d.ts +70 -0
  2001. package/dist/tools/video/comfy-workflow-template.js +194 -0
  2002. package/dist/tools/video/describe-frame.d.ts +36 -0
  2003. package/dist/tools/video/describe-frame.js +68 -0
  2004. package/dist/tools/video/film-assemble.d.ts +234 -0
  2005. package/dist/tools/video/film-assemble.js +959 -0
  2006. package/dist/tools/video/film-project.d.ts +152 -0
  2007. package/dist/tools/video/film-project.js +312 -0
  2008. package/dist/tools/video/frame-dedup.d.ts +46 -0
  2009. package/dist/tools/video/frame-dedup.js +110 -0
  2010. package/dist/tools/video/frame-sample.d.ts +72 -0
  2011. package/dist/tools/video/frame-sample.js +238 -0
  2012. package/dist/tools/video/google-flow-driver.d.ts +131 -0
  2013. package/dist/tools/video/google-flow-driver.js +312 -0
  2014. package/dist/tools/video/google-flow-handoff.d.ts +75 -0
  2015. package/dist/tools/video/google-flow-handoff.js +121 -0
  2016. package/dist/tools/video/google-flow-plan-export.d.ts +21 -0
  2017. package/dist/tools/video/google-flow-plan-export.js +123 -0
  2018. package/dist/tools/video/google-flow-result-import.d.ts +92 -0
  2019. package/dist/tools/video/google-flow-result-import.js +297 -0
  2020. package/dist/tools/video/hybrid-video-router.d.ts +34 -0
  2021. package/dist/tools/video/hybrid-video-router.js +113 -0
  2022. package/dist/tools/video/localized-media.d.ts +50 -0
  2023. package/dist/tools/video/localized-media.js +128 -0
  2024. package/dist/tools/video/long-form-plan.d.ts +37 -0
  2025. package/dist/tools/video/long-form-plan.js +83 -0
  2026. package/dist/tools/video/long-form-production.d.ts +49 -0
  2027. package/dist/tools/video/long-form-production.js +168 -0
  2028. package/dist/tools/video/long-transcribe.d.ts +94 -0
  2029. package/dist/tools/video/long-transcribe.js +206 -0
  2030. package/dist/tools/video/media-fetch.d.ts +94 -0
  2031. package/dist/tools/video/media-fetch.js +311 -0
  2032. package/dist/tools/video/mermaid-render.d.ts +34 -0
  2033. package/dist/tools/video/mermaid-render.js +127 -0
  2034. package/dist/tools/video/narration.d.ts +96 -0
  2035. package/dist/tools/video/narration.js +505 -0
  2036. package/dist/tools/video/native-fashion-defects.d.ts +27 -0
  2037. package/dist/tools/video/native-fashion-defects.js +80 -0
  2038. package/dist/tools/video/scene-render.d.ts +108 -0
  2039. package/dist/tools/video/scene-render.js +418 -0
  2040. package/dist/tools/video/subtitles.d.ts +49 -0
  2041. package/dist/tools/video/subtitles.js +116 -0
  2042. package/dist/tools/video/video-ckg.d.ts +123 -0
  2043. package/dist/tools/video/video-ckg.js +188 -0
  2044. package/dist/tools/video/video-research-card.d.ts +58 -0
  2045. package/dist/tools/video/video-research-card.js +468 -0
  2046. package/dist/tools/video/video-understanding.d.ts +159 -0
  2047. package/dist/tools/video/video-understanding.js +534 -0
  2048. package/dist/tools/video/visual-gate-report.d.ts +139 -0
  2049. package/dist/tools/video/visual-gate-report.js +379 -0
  2050. package/dist/tools/video/voice-rights-registry.d.ts +13 -0
  2051. package/dist/tools/video/voice-rights-registry.js +142 -0
  2052. package/dist/tools/video/youtube-captions.d.ts +51 -0
  2053. package/dist/tools/video/youtube-captions.js +102 -0
  2054. package/dist/tools/video/youtube-master-quality.d.ts +163 -0
  2055. package/dist/tools/video/youtube-master-quality.js +379 -0
  2056. package/dist/tools/video/youtube-storyboard.d.ts +43 -0
  2057. package/dist/tools/video/youtube-storyboard.js +194 -0
  2058. package/dist/tools/video-flow-handoff-tool.d.ts +181 -0
  2059. package/dist/tools/video-flow-handoff-tool.js +261 -0
  2060. package/dist/tools/video-long-form-plan-tool.d.ts +31 -0
  2061. package/dist/tools/video-long-form-plan-tool.js +87 -0
  2062. package/dist/tools/video-quality-gate-tool.d.ts +97 -0
  2063. package/dist/tools/video-quality-gate-tool.js +189 -0
  2064. package/dist/tools/video-route-tool.d.ts +128 -0
  2065. package/dist/tools/video-route-tool.js +126 -0
  2066. package/dist/tools/video-studio-tool-helpers.d.ts +22 -0
  2067. package/dist/tools/video-studio-tool-helpers.js +128 -0
  2068. package/dist/tools/video-trailer-plan-tool.d.ts +60 -0
  2069. package/dist/tools/video-trailer-plan-tool.js +103 -0
  2070. package/dist/tools/vision/blender-render.d.ts +76 -0
  2071. package/dist/tools/vision/blender-render.js +121 -0
  2072. package/dist/tools/vision/image-processor.d.ts +1 -0
  2073. package/dist/tools/vision/image-processor.js +8 -1
  2074. package/dist/tools/vision/load-sharp.d.ts +53 -0
  2075. package/dist/tools/vision/load-sharp.js +48 -0
  2076. package/dist/tools/vision/mean-luma.d.ts +4 -0
  2077. package/dist/tools/vision/mean-luma.js +189 -0
  2078. package/dist/tools/vision/object-detection.d.ts +90 -0
  2079. package/dist/tools/vision/object-detection.js +403 -0
  2080. package/dist/tools/vision/vision-analysis.js +2 -1
  2081. package/dist/tools/weather.d.ts +33 -0
  2082. package/dist/tools/weather.js +183 -0
  2083. package/dist/tools/web-scrape-tool.d.ts +63 -0
  2084. package/dist/tools/web-scrape-tool.js +318 -0
  2085. package/dist/tools/web-search.d.ts +67 -6
  2086. package/dist/tools/web-search.js +231 -68
  2087. package/dist/tools/workspace-tools.d.ts +39 -0
  2088. package/dist/tools/workspace-tools.js +347 -0
  2089. package/dist/tracks/track-manager.js +9 -8
  2090. package/dist/triggers/webhook-trigger.js +10 -18
  2091. package/dist/ui/components/ChatHistory.js +12 -0
  2092. package/dist/ui/components/ChatInterface.js +6 -2
  2093. package/dist/ui/components/FileAutocomplete.d.ts +6 -1
  2094. package/dist/ui/components/FileAutocomplete.js +136 -76
  2095. package/dist/ui/components/FuzzyPicker.d.ts +5 -0
  2096. package/dist/ui/components/FuzzyPicker.js +1 -1
  2097. package/dist/ui/http-server/server.js +2 -2
  2098. package/dist/undo/checkpoint-manager.d.ts +3 -0
  2099. package/dist/undo/checkpoint-manager.js +6 -1
  2100. package/dist/utils/approval-pattern-tracker.js +5 -13
  2101. package/dist/utils/ascii-banner.d.ts +1 -1
  2102. package/dist/utils/ascii-banner.js +1 -1
  2103. package/dist/utils/atomic-write.d.ts +77 -0
  2104. package/dist/utils/atomic-write.js +530 -0
  2105. package/dist/utils/audio-player.d.ts +1 -0
  2106. package/dist/utils/audio-player.js +7 -3
  2107. package/dist/utils/autonomy-manager.js +12 -3
  2108. package/dist/utils/command-exists.d.ts +14 -0
  2109. package/dist/utils/command-exists.js +43 -0
  2110. package/dist/utils/config-validation/schema.d.ts +13 -13
  2111. package/dist/utils/config-validation/schema.js +33 -1
  2112. package/dist/utils/confirmation-service.d.ts +60 -1
  2113. package/dist/utils/confirmation-service.js +204 -41
  2114. package/dist/utils/cost-tracker.d.ts +66 -1
  2115. package/dist/utils/cost-tracker.js +100 -17
  2116. package/dist/utils/history-manager.js +6 -7
  2117. package/dist/utils/init-project.js +17 -13
  2118. package/dist/utils/input-validation/index.d.ts +16 -16
  2119. package/dist/utils/installation-id.js +7 -22
  2120. package/dist/utils/interactive-setup.js +7 -12
  2121. package/dist/utils/json-salvage.d.ts +22 -0
  2122. package/dist/utils/json-salvage.js +91 -0
  2123. package/dist/utils/llm-retry.js +3 -0
  2124. package/dist/utils/logger.d.ts +1 -0
  2125. package/dist/utils/logger.js +16 -5
  2126. package/dist/utils/model-router.js +8 -12
  2127. package/dist/utils/model-utils.js +14 -0
  2128. package/dist/utils/output-sanitizer.d.ts +4 -8
  2129. package/dist/utils/output-sanitizer.js +10 -10
  2130. package/dist/utils/output-schema-validator.d.ts +7 -0
  2131. package/dist/utils/output-schema-validator.js +25 -1
  2132. package/dist/utils/response-cache.js +11 -22
  2133. package/dist/utils/ripgrep-path.d.ts +11 -0
  2134. package/dist/utils/ripgrep-path.js +60 -0
  2135. package/dist/utils/semantic-cache.js +4 -7
  2136. package/dist/utils/settings-manager.d.ts +27 -4
  2137. package/dist/utils/settings-manager.js +51 -39
  2138. package/dist/utils/shell-completions.js +25 -34
  2139. package/dist/utils/shell-configuration.d.ts +39 -0
  2140. package/dist/utils/shell-configuration.js +106 -0
  2141. package/dist/utils/stream-stall-guard.d.ts +39 -0
  2142. package/dist/utils/stream-stall-guard.js +123 -0
  2143. package/dist/utils/subprocess-env.d.ts +15 -0
  2144. package/dist/utils/subprocess-env.js +112 -0
  2145. package/dist/utils/telegram-api-base.d.ts +9 -0
  2146. package/dist/utils/telegram-api-base.js +15 -0
  2147. package/dist/utils/telemetry-config.js +16 -13
  2148. package/dist/utils/update-notifier.js +5 -10
  2149. package/dist/utils/validators.js +1 -2
  2150. package/dist/versioning/config-migrator.js +3 -2
  2151. package/dist/versioning/migration-manager.js +5 -4
  2152. package/dist/versioning/version-detector.js +2 -1
  2153. package/dist/vision-train/assets.d.ts +37 -0
  2154. package/dist/vision-train/assets.js +97 -0
  2155. package/dist/vision-train/ckg-publish.d.ts +26 -0
  2156. package/dist/vision-train/ckg-publish.js +36 -0
  2157. package/dist/vision-train/coco-to-labels.d.ts +63 -0
  2158. package/dist/vision-train/coco-to-labels.js +63 -0
  2159. package/dist/vision-train/curriculum.d.ts +29 -0
  2160. package/dist/vision-train/curriculum.js +49 -0
  2161. package/dist/vision-train/engine.d.ts +56 -0
  2162. package/dist/vision-train/engine.js +55 -0
  2163. package/dist/vision-train/report.d.ts +15 -0
  2164. package/dist/vision-train/report.js +72 -0
  2165. package/dist/vision-train/scorer.d.ts +67 -0
  2166. package/dist/vision-train/scorer.js +114 -0
  2167. package/dist/vision-train/yolo-labels.d.ts +13 -0
  2168. package/dist/vision-train/yolo-labels.js +66 -0
  2169. package/dist/voice/elevenlabs-voice.d.ts +53 -0
  2170. package/dist/voice/elevenlabs-voice.js +412 -0
  2171. package/dist/voice/kyutai-local-voice.d.ts +33 -0
  2172. package/dist/voice/kyutai-local-voice.js +198 -0
  2173. package/dist/voice/local-tts.d.ts +106 -3
  2174. package/dist/voice/local-tts.js +672 -35
  2175. package/dist/voice/local-whisper.d.ts +11 -0
  2176. package/dist/voice/local-whisper.js +18 -2
  2177. package/dist/voice/pcm-edges.d.ts +43 -0
  2178. package/dist/voice/pcm-edges.js +210 -0
  2179. package/dist/voice/perceived-latency-benchmark.d.ts +56 -0
  2180. package/dist/voice/perceived-latency-benchmark.js +218 -0
  2181. package/dist/voice/tts-bank.d.ts +72 -0
  2182. package/dist/voice/tts-bank.js +172 -0
  2183. package/dist/voice/tts-latency-benchmark.d.ts +36 -0
  2184. package/dist/voice/tts-latency-benchmark.js +76 -0
  2185. package/dist/voice/tts-volume.d.ts +86 -0
  2186. package/dist/voice/tts-volume.js +378 -0
  2187. package/dist/voice/two-speed-voice.d.ts +19 -0
  2188. package/dist/voice/two-speed-voice.js +40 -0
  2189. package/dist/voice/voice-to-code.js +1 -1
  2190. package/dist/voice/voicebox-tts.d.ts +150 -0
  2191. package/dist/voice/voicebox-tts.js +669 -0
  2192. package/dist/voice/wake-word.d.ts +2 -0
  2193. package/dist/voice/wake-word.js +30 -10
  2194. package/dist/webhooks/webhook-manager.js +10 -18
  2195. package/dist/widgets/auto-widget.d.ts +27 -0
  2196. package/dist/widgets/auto-widget.js +111 -0
  2197. package/dist/widgets/canvas-publish.d.ts +15 -0
  2198. package/dist/widgets/canvas-publish.js +39 -0
  2199. package/dist/widgets/curated/news.d.ts +2 -0
  2200. package/dist/widgets/curated/news.js +46 -0
  2201. package/dist/widgets/curated/stock.d.ts +1 -0
  2202. package/dist/widgets/curated/stock.js +87 -0
  2203. package/dist/widgets/curated/weather.d.ts +2 -0
  2204. package/dist/widgets/curated/weather.js +93 -0
  2205. package/dist/widgets/template-engine.d.ts +19 -0
  2206. package/dist/widgets/template-engine.js +134 -0
  2207. package/dist/widgets/widget-engine.d.ts +24 -0
  2208. package/dist/widgets/widget-engine.js +153 -0
  2209. package/dist/widgets/widget-gate.d.ts +19 -0
  2210. package/dist/widgets/widget-gate.js +144 -0
  2211. package/dist/widgets/widget-image-renderer.d.ts +4 -0
  2212. package/dist/widgets/widget-image-renderer.js +164 -0
  2213. package/dist/widgets/widget-matcher.d.ts +48 -0
  2214. package/dist/widgets/widget-matcher.js +109 -0
  2215. package/dist/widgets/widget-proposer.d.ts +17 -0
  2216. package/dist/widgets/widget-proposer.js +75 -0
  2217. package/dist/widgets/widget-registry.d.ts +36 -0
  2218. package/dist/widgets/widget-registry.js +231 -0
  2219. package/dist/widgets/widget-types.d.ts +100 -0
  2220. package/dist/widgets/widget-types.js +17 -0
  2221. package/dist/wizard/environment-detection.d.ts +67 -0
  2222. package/dist/wizard/environment-detection.js +210 -0
  2223. package/dist/wizard/onboarding.d.ts +21 -1
  2224. package/dist/wizard/onboarding.js +202 -27
  2225. package/dist/workflows/state-manager.js +8 -2
  2226. package/dist/workspace/workspace-config.d.ts +37 -0
  2227. package/dist/workspace/workspace-config.js +199 -0
  2228. package/dist/workspace/workspace-isolation.d.ts +19 -0
  2229. package/dist/workspace/workspace-isolation.js +124 -39
  2230. package/dist/workspace/workspace-manager.js +19 -14
  2231. package/examples/claude_desktop_config.json +8 -0
  2232. package/package.json +75 -31
  2233. package/.codebuddy/README.md +0 -65
  2234. package/dist/agent/middleware/learning-first-middleware.d.ts +0 -79
  2235. package/dist/agent/middleware/learning-first-middleware.js +0 -271
  2236. package/dist/agent/middleware/tool-filter-middleware.d.ts +0 -45
  2237. package/dist/agent/middleware/tool-filter-middleware.js +0 -122
  2238. package/dist/codebuddy/tool-definitions/batch-tools.d.ts +0 -10
  2239. package/dist/codebuddy/tool-definitions/batch-tools.js +0 -46
  2240. package/dist/codebuddy/tool-definitions/graph-tools.d.ts +0 -13
  2241. package/dist/codebuddy/tool-definitions/graph-tools.js +0 -78
  2242. package/dist/plugins/code-explorer/CodeExplorerMCPClient.d.ts +0 -129
  2243. package/dist/plugins/code-explorer/CodeExplorerMCPClient.js +0 -143
  2244. package/dist/tools/registry/batch-tools.d.ts +0 -36
  2245. package/dist/tools/registry/batch-tools.js +0 -135
  2246. package/dist/tools/registry/graph-tools.d.ts +0 -45
  2247. package/dist/tools/registry/graph-tools.js +0 -283
@@ -6,7 +6,17 @@
6
6
  */
7
7
  import fs from 'fs';
8
8
  import path from 'path';
9
+ import { createHash } from 'node:crypto';
10
+ import { deriveArgumentObligations, isRuntimeEvidenceVerificationRequest, } from '../../conversation/argument-obligations.js';
11
+ import { shouldRunSemanticResponseGate } from '../../conversation/semantic-response-gate.js';
12
+ import { MODEL_NAME_PATTERN, clearSessionModelOverride, getSessionModelOverride, resolveChannelModel, setSessionModelOverride, __resetSessionModelOverridesForTests, } from '../../channels/channel-model-override.js';
9
13
  import { logger } from '../../utils/logger.js';
14
+ import { channelEnvToken, resolveChannelSecret } from '../../channels/resolve-channel-secret.js';
15
+ import { getChannelCognitivePort, } from '../../channels/channel-cognitive-port.js';
16
+ import { assembleCompanionChannelPrompt, channelWaitNoticeMs, companionWaitNoticeText, isCompanionSurfaceEnabled, shouldUseCompanionChannelProfile, } from '../../channels/companion-channel-profile.js';
17
+ import { runCompanionChannelTurn } from '../../channels/companion-channel-turn.js';
18
+ import { speakChannelProviderFailure } from '../../channels/provider-failure-speech.js';
19
+ import { prependUserFacingFailoverNotice } from '../../providers/provider-failover-user-notice.js';
10
20
  /**
11
21
  * Start every enabled channel from config and wire the inbound AI receiver loop
12
22
  * (`registerAIMessageHandler`). Shared by `buddy channels start` (CLI) and the
@@ -17,29 +27,72 @@ import { logger } from '../../utils/logger.js';
17
27
  * is the DM-pairing gate inside `registerAIMessageHandler`. Never throws on a
18
28
  * single channel failure — it collects the outcome per channel.
19
29
  */
20
- export async function startConfiguredChannels(configPath, onlyType) {
30
+ export async function startConfiguredChannels(configPath, onlyType, onlyInstance) {
21
31
  const { getChannelManager } = await import('../../channels/index.js');
22
32
  const manager = getChannelManager();
23
33
  await registerAIMessageHandler(manager);
24
- const result = { registered: [], skipped: [], failed: [], noConfig: false };
34
+ const result = {
35
+ registered: [],
36
+ skipped: [],
37
+ failed: [],
38
+ deduplicated: [],
39
+ noConfig: false,
40
+ };
25
41
  const config = loadChannelConfig(configPath);
26
42
  if (!config || config.channels.length === 0) {
27
43
  result.noConfig = true;
28
44
  return result;
29
45
  }
30
- for (const chConfig of config.channels) {
31
- if (onlyType && chConfig.type !== onlyType) {
32
- continue;
33
- }
46
+ const normalizedInstance = onlyInstance?.trim().toLowerCase();
47
+ const selected = config.channels.filter((entry) => {
48
+ if (onlyType && entry.type !== onlyType)
49
+ return false;
50
+ if (!normalizedInstance)
51
+ return true;
52
+ const configuredName = typeof entry.options?.name === 'string'
53
+ ? entry.options.name.trim().toLowerCase()
54
+ : '';
55
+ return normalizedInstance === 'default'
56
+ ? configuredName.length === 0
57
+ : configuredName === normalizedInstance;
58
+ });
59
+ if (selected.length === 0) {
60
+ result.noConfig = true;
61
+ return result;
62
+ }
63
+ const lastByType = new Map();
64
+ const counts = new Map();
65
+ for (const entry of selected) {
66
+ lastByType.set(entry.type, entry);
67
+ counts.set(entry.type, (counts.get(entry.type) ?? 0) + 1);
68
+ }
69
+ result.deduplicated = [...counts.entries()]
70
+ .filter(([, count]) => count > 1)
71
+ .map(([type]) => type);
72
+ for (const chConfig of lastByType.values()) {
34
73
  if (!chConfig.enabled) {
35
74
  result.skipped.push(chConfig.type);
36
75
  continue;
37
76
  }
38
77
  try {
78
+ // A repeated admin start or a duplicate config must never leave an old
79
+ // poller/socket alive behind the manager's type-keyed replacement.
80
+ const channelType = chConfig.type;
81
+ const existing = manager.getChannel(channelType);
82
+ if (existing) {
83
+ await existing.disconnect();
84
+ manager.unregisterChannel(channelType);
85
+ }
39
86
  const channel = await instantiateChannel(chConfig);
40
87
  if (channel) {
41
88
  manager.registerChannel(channel);
42
- await channel.connect();
89
+ try {
90
+ await channel.connect();
91
+ }
92
+ catch (connectErr) {
93
+ manager.unregisterChannel(channelType);
94
+ throw connectErr;
95
+ }
43
96
  result.registered.push(chConfig.type);
44
97
  }
45
98
  }
@@ -53,25 +106,99 @@ export async function startConfiguredChannels(configPath, onlyType) {
53
106
  return result;
54
107
  }
55
108
  function getChannelConfigPaths(configPath) {
109
+ const envConfigPath = process.env.CODEBUDDY_CHANNEL_CONFIG?.trim();
110
+ const home = process.env.HOME || process.env.USERPROFILE || '';
56
111
  return configPath
57
112
  ? [configPath]
58
- : [
59
- path.join(process.cwd(), '.codebuddy', 'channels.json'),
60
- path.join(process.env.HOME || process.env.USERPROFILE || '', '.codebuddy', 'channels.json'),
61
- ];
113
+ : envConfigPath
114
+ ? [envConfigPath]
115
+ : [
116
+ path.join(process.cwd(), '.codebuddy', 'channels.json'),
117
+ path.join(home, '.codebuddy', 'channels.json'),
118
+ path.join(process.cwd(), '.codebuddy', 'settings.json'),
119
+ path.join(home, '.codebuddy', 'settings.json'),
120
+ ];
121
+ }
122
+ function mapSettingsChannelEntry(key, value) {
123
+ if (!value || typeof value !== 'object' || Array.isArray(value))
124
+ return null;
125
+ const entry = value;
126
+ const type = typeof entry.type === 'string' && entry.type.trim() ? entry.type.trim() : key;
127
+ const options = {
128
+ ...(entry.options && typeof entry.options === 'object' && !Array.isArray(entry.options)
129
+ ? entry.options
130
+ : {}),
131
+ };
132
+ if (Array.isArray(entry.adminUsers))
133
+ options.adminUsers = entry.adminUsers;
134
+ const mapped = {
135
+ type,
136
+ enabled: entry.enabled !== false,
137
+ };
138
+ if (typeof entry.token === 'string')
139
+ mapped.token = entry.token;
140
+ if (typeof entry.webhookUrl === 'string')
141
+ mapped.webhookUrl = entry.webhookUrl;
142
+ if (Array.isArray(entry.allowedUsers)) {
143
+ mapped.allowedUsers = entry.allowedUsers.filter((item) => typeof item === 'string');
144
+ }
145
+ if (Array.isArray(entry.allowedChannels)) {
146
+ mapped.allowedChannels = entry.allowedChannels.filter((item) => typeof item === 'string');
147
+ }
148
+ if (Object.keys(options).length > 0)
149
+ mapped.options = options;
150
+ return mapped;
151
+ }
152
+ function asChannelConfig(raw) {
153
+ if (!raw || typeof raw !== 'object')
154
+ return null;
155
+ const channelsField = raw.channels;
156
+ if (Array.isArray(channelsField)) {
157
+ return { channels: channelsField };
158
+ }
159
+ if (channelsField && typeof channelsField === 'object') {
160
+ const channels = Object.entries(channelsField)
161
+ .map(([key, value]) => mapSettingsChannelEntry(key, value))
162
+ .filter((entry) => entry !== null);
163
+ if (channels.length === 0)
164
+ return null;
165
+ return { channels };
166
+ }
167
+ return null;
168
+ }
169
+ function applyEnvChannelTokens(config) {
170
+ const telegramToken = channelEnvToken('telegram');
171
+ if (!telegramToken)
172
+ return config;
173
+ const existing = config.channels.find((channel) => channel.type === 'telegram');
174
+ if (existing) {
175
+ if (!existing.token)
176
+ existing.token = telegramToken;
177
+ return config;
178
+ }
179
+ return {
180
+ channels: [...config.channels, { type: 'telegram', enabled: true, token: telegramToken }],
181
+ };
62
182
  }
63
183
  export function loadChannelConfigWithPath(configPath) {
64
184
  for (const p of getChannelConfigPaths(configPath)) {
65
185
  try {
66
186
  if (fs.existsSync(p)) {
67
187
  const content = fs.readFileSync(p, 'utf-8');
68
- return { config: JSON.parse(content), path: p };
188
+ const parsed = asChannelConfig(JSON.parse(content));
189
+ if (!parsed)
190
+ continue;
191
+ return { config: applyEnvChannelTokens(parsed), path: p };
69
192
  }
70
193
  }
71
194
  catch (err) {
72
195
  logger.debug(`Failed to load channel config from ${p}`, { error: err instanceof Error ? err.message : String(err) });
73
196
  }
74
197
  }
198
+ const fromEnv = applyEnvChannelTokens({ channels: [] });
199
+ if (fromEnv.channels.length > 0) {
200
+ return { config: fromEnv, path: 'env:TELEGRAM_BOT_TOKEN' };
201
+ }
75
202
  return null;
76
203
  }
77
204
  export function loadChannelConfig(configPath) {
@@ -171,6 +298,9 @@ export function buildChannelStatusReport(allStatus, configPath, generatedAt = ne
171
298
  connected: status.connected,
172
299
  authenticated: status.authenticated,
173
300
  ...(status.lastActivity ? { lastActivity: status.lastActivity.toISOString() } : {}),
301
+ ...(status.lastSuccessfulPoll
302
+ ? { lastSuccessfulPoll: status.lastSuccessfulPoll.toISOString() }
303
+ : {}),
174
304
  ...(status.error ? { error: status.error } : {}),
175
305
  ...(status.info ? { info: status.info } : {}),
176
306
  }))
@@ -242,7 +372,10 @@ export async function handleChannels(action, options) {
242
372
  }
243
373
  console.log('Channel Status:\n');
244
374
  for (const [type, status] of Object.entries(allStatus)) {
245
- console.log(` ${type}: ${status.connected ? 'connected' : 'disconnected'}${status.error ? ` (error: ${status.error})` : ''}`);
375
+ const pollStatus = type === 'telegram'
376
+ ? `, last successful poll: ${status.lastSuccessfulPoll?.toISOString() ?? 'never'}`
377
+ : '';
378
+ console.log(` ${type}: ${status.connected ? 'connected' : 'disconnected'}${pollStatus}${status.error ? ` (error: ${status.error})` : ''}`);
246
379
  }
247
380
  if (Object.keys(allStatus).length === 0) {
248
381
  console.log(' No channels registered.');
@@ -255,7 +388,7 @@ export async function handleChannels(action, options) {
255
388
  const channelType = options.type;
256
389
  if (!channelType) {
257
390
  // Start all configured channels (shared with `buddy server` intake)
258
- const result = await startConfiguredChannels(options.config);
391
+ const result = await startConfiguredChannels(options.config, undefined, options.instance);
259
392
  if (result.noConfig) {
260
393
  console.log('No channel configuration found. Create .codebuddy/channels.json or use --config.');
261
394
  return;
@@ -263,25 +396,55 @@ export async function handleChannels(action, options) {
263
396
  for (const t of result.registered) {
264
397
  console.log(`[OK] ${t} channel started`);
265
398
  }
399
+ for (const t of result.deduplicated) {
400
+ console.log(`[SKIP] duplicate ${t} config collapsed (last declaration used)`);
401
+ }
266
402
  for (const f of result.failed) {
267
403
  console.log(`[FAIL] ${f.type}: ${f.error}`);
268
404
  }
405
+ if (result.failed.length > 0 && result.registered.length === 0) {
406
+ process.exitCode = 1;
407
+ }
269
408
  }
270
409
  else {
271
- const result = await startConfiguredChannels(options.config, channelType);
410
+ const result = await startConfiguredChannels(options.config, channelType, options.instance);
272
411
  if (result.noConfig) {
273
412
  console.log(`No configuration found for channel type: ${channelType}`);
413
+ process.exitCode = 1;
274
414
  return;
275
415
  }
276
416
  for (const t of result.registered) {
277
417
  console.log(`[OK] ${t} channel started`);
278
418
  }
419
+ for (const t of result.deduplicated) {
420
+ console.log(`[SKIP] duplicate ${t} config collapsed (last declaration used)`);
421
+ }
279
422
  for (const t of result.skipped) {
280
423
  console.log(`[SKIP] ${t} channel disabled`);
281
424
  }
282
425
  for (const f of result.failed) {
283
426
  console.log(`[FAIL] ${f.type}: ${f.error}`);
284
427
  }
428
+ if (result.failed.length > 0 && result.registered.length === 0) {
429
+ process.exitCode = 1;
430
+ }
431
+ }
432
+ break;
433
+ }
434
+ case 'pairing': {
435
+ const { getDMPairing } = await import('../../channels/dm-pairing.js');
436
+ const pairing = getDMPairing();
437
+ const stats = pairing.getStats();
438
+ console.log(`DM pairing: ${stats.enabled ? 'on' : 'off'} (DM_PAIRING_ENABLED, default on)`);
439
+ console.log(`Approved senders: ${stats.totalApproved}`);
440
+ const pending = pairing.listPending();
441
+ if (pending.length === 0) {
442
+ console.log('No pending pairing codes. An unknown DM generates a one-time code logged server-side only.');
443
+ break;
444
+ }
445
+ console.log(`Pending one-time codes (${pending.length}):`);
446
+ for (const request of pending) {
447
+ console.log(` [${request.channelType}] sender=${request.senderId} code=${request.code} expires=${request.expiresAt.toISOString()}`);
285
448
  }
286
449
  break;
287
450
  }
@@ -305,17 +468,348 @@ export async function handleChannels(action, options) {
305
468
  break;
306
469
  }
307
470
  default:
308
- console.log(`Usage: buddy channels [start|stop|status|list] [--type <type>] [--config <path>]`);
471
+ console.log(`Usage: buddy channels [start|stop|status|list|pairing] [--type <type>] [--instance <name|default>] [--config <path>]`);
309
472
  }
310
473
  }
311
474
  let aiHandlerRegistered = false;
475
+ const LISA_SELFIE_CONTINUATION_TTL_MS = 15 * 60_000;
476
+ const recentLisaSelfieSessions = new Map();
312
477
  /** Reset the one-shot registration guard. Test-only — never call in production. */
313
478
  export function __resetChannelAIHandlerForTests() {
314
479
  aiHandlerRegistered = false;
480
+ for (const key of channelAgentCache.keys()) {
481
+ evictChannelAgent(key, true);
482
+ }
483
+ channelTurnTails.clear();
484
+ channelBotPersonas.clear();
485
+ companionChannelHistories.clear();
486
+ recentLisaSelfieSessions.clear();
487
+ __resetSessionModelOverridesForTests();
315
488
  }
316
489
  const channelAgentCache = new Map();
490
+ const channelTurnTails = new Map();
491
+ const companionChannelHistories = new Map();
317
492
  const CHANNEL_AGENT_IDLE_MS = 2 * 60 * 60 * 1000; // evict after 2h idle
318
493
  const CHANNEL_AGENT_MAX = 50;
494
+ const DEFAULT_CHANNEL_TURN_TIMEOUT_MS = 3 * 60 * 1000;
495
+ const MIN_CHANNEL_TURN_TIMEOUT_MS = 1_000;
496
+ const MAX_CHANNEL_TURN_TIMEOUT_MS = 15 * 60 * 1000;
497
+ const CHANNEL_TURN_TIMEOUT_CLEANUP_MS = 10_000;
498
+ class ChannelTurnTimeoutError extends Error {
499
+ timeoutMs;
500
+ phase;
501
+ constructor(timeoutMs, phase) {
502
+ super(`channel turn timed out after ${timeoutMs}ms during ${phase}`);
503
+ this.timeoutMs = timeoutMs;
504
+ this.phase = phase;
505
+ this.name = 'ChannelTurnTimeoutError';
506
+ }
507
+ }
508
+ function channelTurnTimeoutMs(env = process.env) {
509
+ const configured = Number(env.CODEBUDDY_CHANNEL_TURN_TIMEOUT_MS);
510
+ if (!Number.isFinite(configured) || configured <= 0)
511
+ return DEFAULT_CHANNEL_TURN_TIMEOUT_MS;
512
+ return Math.min(MAX_CHANNEL_TURN_TIMEOUT_MS, Math.max(MIN_CHANNEL_TURN_TIMEOUT_MS, Math.floor(configured)));
513
+ }
514
+ function evictChannelAgent(sessionKey, discard = false) {
515
+ const cached = channelAgentCache.get(sessionKey);
516
+ channelAgentCache.delete(sessionKey);
517
+ try {
518
+ if (discard)
519
+ cached?.agent.dispose({ skipSessionLearning: true });
520
+ else
521
+ cached?.agent.dispose();
522
+ }
523
+ catch {
524
+ // Eviction must remain best-effort; the cache reference is already gone.
525
+ }
526
+ }
527
+ /**
528
+ * One in-flight generative turn per conversation. Commands and remote approval
529
+ * are handled before this queue, so an approval can still unblock a waiting
530
+ * tool while assistant drafts cannot race into the next turn's history.
531
+ */
532
+ async function serializeChannelTurn(sessionKey, task, lifecycle = {}) {
533
+ const queuedAt = Date.now();
534
+ const previous = channelTurnTails.get(sessionKey) ?? Promise.resolve();
535
+ const run = previous.catch(() => undefined).then(async () => {
536
+ const startedAt = Date.now();
537
+ const timeoutMs = channelTurnTimeoutMs();
538
+ const controller = new AbortController();
539
+ let phase = 'starting';
540
+ let watchdogCount = 0;
541
+ const diagnosticFields = {
542
+ ...lifecycle.diagnostics,
543
+ queueWaitMs: startedAt - queuedAt,
544
+ };
545
+ logger.info('Channel turn started', diagnosticFields);
546
+ lifecycle.onStart?.();
547
+ const watchdogIntervalMs = Math.min(30_000, Math.max(1_000, Math.floor(timeoutMs / 3)));
548
+ const watchdog = setInterval(() => {
549
+ watchdogCount++;
550
+ logger.warn('Channel turn watchdog still active', {
551
+ ...diagnosticFields,
552
+ phase,
553
+ elapsedMs: Date.now() - startedAt,
554
+ watchdogCount,
555
+ });
556
+ }, watchdogIntervalMs);
557
+ watchdog.unref?.();
558
+ let timeout;
559
+ let timeoutCleanup;
560
+ const timeoutError = new Promise((_, reject) => {
561
+ timeout = setTimeout(() => {
562
+ const error = new ChannelTurnTimeoutError(timeoutMs, phase);
563
+ controller.abort(error);
564
+ logger.error('Channel turn watchdog timed out', {
565
+ ...diagnosticFields,
566
+ phase,
567
+ elapsedMs: Date.now() - startedAt,
568
+ timeoutMs,
569
+ });
570
+ const cleanup = Promise.resolve(lifecycle.onTimeout?.(error))
571
+ .catch((cleanupError) => {
572
+ logger.warn('Channel turn timeout cleanup failed', {
573
+ ...diagnosticFields,
574
+ error: cleanupError instanceof Error ? cleanupError.message : String(cleanupError),
575
+ });
576
+ })
577
+ .then(() => true);
578
+ let cleanupTimer;
579
+ const cleanupDeadline = new Promise((resolve) => {
580
+ cleanupTimer = setTimeout(() => resolve(false), CHANNEL_TURN_TIMEOUT_CLEANUP_MS);
581
+ cleanupTimer.unref?.();
582
+ });
583
+ timeoutCleanup = Promise.race([cleanup, cleanupDeadline]).then((completed) => {
584
+ if (cleanupTimer)
585
+ clearTimeout(cleanupTimer);
586
+ if (!completed) {
587
+ logger.warn('Channel turn timeout cleanup exceeded deadline', {
588
+ ...diagnosticFields,
589
+ cleanupTimeoutMs: CHANNEL_TURN_TIMEOUT_CLEANUP_MS,
590
+ });
591
+ }
592
+ });
593
+ void timeoutCleanup.finally(() => reject(error));
594
+ }, timeoutMs);
595
+ timeout.unref?.();
596
+ });
597
+ const control = {
598
+ signal: controller.signal,
599
+ phase(nextPhase) {
600
+ phase = nextPhase;
601
+ logger.info('Channel turn phase', {
602
+ ...diagnosticFields,
603
+ phase,
604
+ elapsedMs: Date.now() - startedAt,
605
+ });
606
+ },
607
+ throwIfAborted() {
608
+ if (controller.signal.aborted)
609
+ throw controller.signal.reason;
610
+ },
611
+ };
612
+ try {
613
+ const controlledTask = task(control).catch(async (error) => {
614
+ // Abort checks inside the task can observe the timeout immediately.
615
+ // Keep the FIFO closed until timeout cleanup (including the visible
616
+ // fail-soft reply) has completed.
617
+ if (controller.signal.aborted && timeoutCleanup)
618
+ await timeoutCleanup;
619
+ throw error;
620
+ });
621
+ return await Promise.race([controlledTask, timeoutError]);
622
+ }
623
+ finally {
624
+ if (timeout)
625
+ clearTimeout(timeout);
626
+ clearInterval(watchdog);
627
+ lifecycle.onSettled?.();
628
+ logger.info('Channel turn settled', {
629
+ ...diagnosticFields,
630
+ phase,
631
+ elapsedMs: Date.now() - startedAt,
632
+ timedOut: controller.signal.aborted,
633
+ });
634
+ }
635
+ });
636
+ const tail = run.then(() => undefined, () => undefined);
637
+ channelTurnTails.set(sessionKey, tail);
638
+ try {
639
+ return await run;
640
+ }
641
+ finally {
642
+ if (channelTurnTails.get(sessionKey) === tail)
643
+ channelTurnTails.delete(sessionKey);
644
+ }
645
+ }
646
+ const CONVERSATIONAL_SLASH_VERBS = new Set([
647
+ 'analyse',
648
+ 'analyze',
649
+ 'cherche',
650
+ 'compare',
651
+ 'dis',
652
+ 'donne',
653
+ 'explique',
654
+ 'find',
655
+ 'montre',
656
+ 'raconte',
657
+ 'resume',
658
+ 'résume',
659
+ 'show',
660
+ 'tell',
661
+ ]);
662
+ /** Telegram users sometimes prefix a natural request with `/` as if it were a prompt box. */
663
+ function normalizeConversationalSlashMessage(message) {
664
+ const match = message.content.trim().match(/^\/([^\s@]+)(?:@[^\s]+)?\s+([\s\S]+)$/u);
665
+ const verb = match?.[1]?.toLocaleLowerCase('fr');
666
+ if (!match || !verb || !CONVERSATIONAL_SLASH_VERBS.has(verb))
667
+ return message;
668
+ return {
669
+ ...message,
670
+ content: `${match[1]} ${match[2]}`.trim(),
671
+ contentType: 'text',
672
+ isCommand: false,
673
+ commandName: undefined,
674
+ commandArgs: undefined,
675
+ };
676
+ }
677
+ /** Keep long or queued channel turns visibly alive without sending chat noise. */
678
+ function startChannelTypingHeartbeat(channel, channelId) {
679
+ const typingChannel = channel;
680
+ if (typeof typingChannel.sendTyping !== 'function')
681
+ return () => undefined;
682
+ let stopped = false;
683
+ let inFlight = false;
684
+ const reportFailure = (error) => {
685
+ logger.debug('Channel typing indicator unavailable', {
686
+ channelType: channel.type,
687
+ channelHash: hashForLog(channelId),
688
+ errorType: error instanceof Error ? error.name : 'unknown',
689
+ });
690
+ };
691
+ const ping = () => {
692
+ if (stopped || inFlight)
693
+ return;
694
+ inFlight = true;
695
+ void Promise.resolve()
696
+ .then(() => typingChannel.sendTyping(channelId))
697
+ .catch(reportFailure)
698
+ .finally(() => {
699
+ inFlight = false;
700
+ });
701
+ };
702
+ ping();
703
+ // Telegram displays sendChatAction for about five seconds. Refresh slightly
704
+ // before expiry while a turn waits in the per-session FIFO or runs the model.
705
+ const timer = setInterval(ping, 4_000);
706
+ timer.unref?.();
707
+ return () => {
708
+ stopped = true;
709
+ clearInterval(timer);
710
+ };
711
+ }
712
+ function channelTypingLifecycle(channel, channelId) {
713
+ let stopTyping = () => undefined;
714
+ return {
715
+ onStart: () => {
716
+ stopTyping = startChannelTypingHeartbeat(channel, channelId);
717
+ },
718
+ onSettled: () => stopTyping(),
719
+ };
720
+ }
721
+ function channelWaitNoticeLifecycle(channel, channelId, replyTo) {
722
+ const delayMs = channelWaitNoticeMs();
723
+ let timer;
724
+ let stopped = false;
725
+ return {
726
+ onStart: () => {
727
+ if (delayMs <= 0)
728
+ return;
729
+ timer = setTimeout(() => {
730
+ if (stopped)
731
+ return;
732
+ void channel
733
+ .send({
734
+ channelId,
735
+ content: companionWaitNoticeText(),
736
+ ...(replyTo ? { replyTo } : {}),
737
+ })
738
+ .catch((error) => {
739
+ logger.debug('Channel wait notice skipped', {
740
+ error: error instanceof Error ? error.message : String(error),
741
+ });
742
+ });
743
+ }, delayMs);
744
+ timer.unref?.();
745
+ },
746
+ onSettled: () => {
747
+ stopped = true;
748
+ if (timer)
749
+ clearTimeout(timer);
750
+ },
751
+ };
752
+ }
753
+ function rememberCompanionChannelTurn(sessionKey, userText, assistantText) {
754
+ const previous = companionChannelHistories.get(sessionKey) ?? [];
755
+ companionChannelHistories.set(sessionKey, [
756
+ ...previous,
757
+ { role: 'user', content: userText },
758
+ { role: 'assistant', content: assistantText },
759
+ ].slice(-20));
760
+ }
761
+ function hashForLog(value) {
762
+ if (value === undefined || value === null || value === '')
763
+ return undefined;
764
+ return createHash('sha256').update(String(value)).digest('hex').slice(0, 12);
765
+ }
766
+ function isAgentFailureResponse(value) {
767
+ return /^Sorry, I encountered an error:/i.test(value.trim());
768
+ }
769
+ function channelHistoryTurn(entry) {
770
+ const role = entry.role ?? entry.type;
771
+ if (role !== 'user' && role !== 'assistant')
772
+ return null;
773
+ if (typeof entry.content !== 'string')
774
+ return null;
775
+ const content = entry.content
776
+ .replace(/<companion_turn>[\s\S]*?<\/companion_turn>\s*/g, '')
777
+ .replace(/^Message de l'utilisateur\s*:\s*/i, '')
778
+ .trim();
779
+ return content ? { role, content } : null;
780
+ }
781
+ /**
782
+ * Read the real Telegram/channel discussion before choosing the companion
783
+ * model. Warm agents are authoritative; a cold daemon falls back to the same
784
+ * persisted SessionStore used by restoreChannelSession().
785
+ */
786
+ async function resolveChannelRoutingHistory(sessionKey, sharedHistory) {
787
+ if (sharedHistory.length > 0)
788
+ return sharedHistory.slice(-12);
789
+ const cached = channelAgentCache.get(sessionKey)?.agent;
790
+ if (cached) {
791
+ return cached
792
+ .getChatHistory()
793
+ .flatMap((entry) => {
794
+ const turn = channelHistoryTurn(entry);
795
+ return turn ? [turn] : [];
796
+ })
797
+ .slice(-12);
798
+ }
799
+ try {
800
+ const { getSessionStore } = await import('../../persistence/session-store.js');
801
+ const session = await getSessionStore().loadSession(sessionKey);
802
+ return (session?.messages ?? [])
803
+ .flatMap((entry) => {
804
+ const turn = channelHistoryTurn(entry);
805
+ return turn ? [turn] : [];
806
+ })
807
+ .slice(-12);
808
+ }
809
+ catch {
810
+ return [];
811
+ }
812
+ }
319
813
  const channelBotPersonas = new Map();
320
814
  export function registerChannelBotPersona(botId, persona) {
321
815
  if (botId)
@@ -368,20 +862,54 @@ async function persistChannelSession(agent, sessionKey) {
368
862
  logger.warn(`channel session persist failed: ${err instanceof Error ? err.message : String(err)}`);
369
863
  }
370
864
  }
371
- async function getOrCreateChannelAgent(sessionKey, resolved, agentConfig, botId) {
865
+ async function getOrCreateChannelAgent(sessionKey, resolved, agentConfig, botId, routeModel, companionRoute) {
372
866
  const now = Date.now();
373
867
  // Evict idle agents first.
374
868
  for (const [key, cached] of channelAgentCache) {
375
869
  if (now - cached.lastUsed > CHANNEL_AGENT_IDLE_MS)
376
- channelAgentCache.delete(key);
870
+ evictChannelAgent(key);
377
871
  }
872
+ // Per-bot persona (multi-bot): a bot may define its own model + system prompt.
873
+ const persona = botId ? channelBotPersonas.get(botId) : undefined;
874
+ // Hermes-style tiers, finest scope first: /model session override > matched
875
+ // route > bot persona > merged route default (includes the router-wide
876
+ // defaultAgent fallback — kept below persona) > provider default.
877
+ const { model, source } = resolveChannelModel({
878
+ sessionOverride: getSessionModelOverride(sessionKey),
879
+ routeModel,
880
+ personaModel: persona?.model,
881
+ companionModel: companionRoute?.model,
882
+ routeDefaultModel: agentConfig.model,
883
+ globalModel: resolved.model,
884
+ });
885
+ const runtimeResolved = source === 'companion-profile' && companionRoute
886
+ ? {
887
+ apiKey: companionRoute.apiKey,
888
+ baseUrl: companionRoute.baseURL,
889
+ model: companionRoute.model,
890
+ egress: companionRoute.egress,
891
+ }
892
+ : resolved;
893
+ const runtimeIdentity = createHash('sha256')
894
+ .update(`${runtimeResolved.apiKey}:${runtimeResolved.baseUrl}`)
895
+ .digest('hex')
896
+ .slice(0, 16);
378
897
  const hit = channelAgentCache.get(sessionKey);
379
- if (hit) {
898
+ if (hit && hit.runtimeIdentity === runtimeIdentity) {
380
899
  hit.lastUsed = now;
381
- return hit.agent;
900
+ // Reconcile a changed override on the cached agent (no eviction — the
901
+ // in-memory conversation history is what makes the chat feel continuous).
902
+ if (hit.agent.getCurrentModel() !== model)
903
+ hit.agent.setModel(model);
904
+ return {
905
+ agent: hit.agent,
906
+ effectiveRuntime: { ...runtimeResolved, model, egress: runtimeResolved.egress ?? 'cloud' },
907
+ };
382
908
  }
383
- // Per-bot persona (multi-bot): a bot may define its own model + system prompt.
384
- const persona = botId ? channelBotPersonas.get(botId) : undefined;
909
+ // A provider/endpoint change cannot be applied through setModel(). Recreate
910
+ // the agent, then restore its persisted transcript below.
911
+ if (hit)
912
+ evictChannelAgent(sessionKey);
385
913
  // Opt-in Code Explorer nudge (set CODE_EXPLORER_BIN): some models won't reach
386
914
  // for the code-graph MCP tools on their own and just say "I can't" — tell them
387
915
  // plainly that they can, and give the CLI fallback. No-op when the env is unset.
@@ -394,13 +922,19 @@ async function getOrCreateChannelAgent(sessionKey, resolved, agentConfig, botId)
394
922
  // path it names — the handler then delivers that file to the chat as a photo.
395
923
  const pythonHint = 'ACTING vs SHOWING: when the user asks you to draw, plot, generate, create, compute or build something, you MUST actually DO it by running tools/code now — do NOT just print the code or instructions and stop. Execute it and deliver the real artifact. ' +
396
924
  'For Python work needing packages (plotting, data, etc.): do NOT use `pip`/`pip3 install` (system Python is PEP 668-locked). Use `uv` — e.g. write the script to a file then run `uv run --with matplotlib --with pandas --with numpy python /tmp/plot.py` (matplotlib must use the Agg backend). When you produce a chart/image, SAVE it to an absolute path like `/tmp/<name>.png` and state that exact path in your reply — it is then sent to the user automatically as a photo.';
397
- const channelSystemPromptAppend = [persona?.systemPrompt, codeExplorerHint, pythonHint].filter(Boolean).join('\n\n') || undefined;
925
+ // System prompts APPEND (constructor arg 8, wrapped in <runtime_persona>)
926
+ // never the full-replace arg 9, which would drop the tool-calling base prompt
927
+ // and break tools on the channel path. Persona (bot identity) first, then the
928
+ // matched route's prompt (conversation instruction — more specific, later =
929
+ // higher salience). Both are complementary, not competing.
930
+ const channelSystemPromptAppend = [persona?.systemPrompt, agentConfig.systemPrompt, codeExplorerHint, pythonHint].filter(Boolean).join('\n\n') ||
931
+ undefined;
398
932
  const { CodeBuddyAgent } = await import('../../agent/codebuddy-agent.js');
399
- const model = persona?.model || agentConfig.model || resolved.model;
400
- const agent = new CodeBuddyAgent(resolved.apiKey || 'local', resolved.baseUrl, model, agentConfig.maxToolRounds ?? 6, // bounded (vs the 50-round default)
933
+ const agent = new CodeBuddyAgent(runtimeResolved.apiKey || 'local', runtimeResolved.baseUrl, model, agentConfig.maxToolRounds ?? 6, // bounded (vs the 50-round default)
401
934
  true, // useRAGToolSelection — relevant tools on demand, not all ~194
402
935
  process.env.CODEBUDDY_CHANNEL_PROMPT_ID || 'auto', // minimal/adaptive prompt, not the 73KB legacy
403
936
  process.cwd(), channelSystemPromptAppend);
937
+ agent.setRecoverySessionId?.(sessionKey);
404
938
  // Scope per-bot state (memory/lessons) to this bot so bots don't share facts.
405
939
  agent.setChannelBotId(botId);
406
940
  // Persistence: reload prior conversation from disk on a cold agent (after a
@@ -417,36 +951,202 @@ async function getOrCreateChannelAgent(sessionKey, resolved, agentConfig, botId)
417
951
  }
418
952
  }
419
953
  if (lruKey)
420
- channelAgentCache.delete(lruKey);
954
+ evictChannelAgent(lruKey);
421
955
  }
422
- channelAgentCache.set(sessionKey, { agent, lastUsed: now });
423
- return agent;
956
+ channelAgentCache.set(sessionKey, { agent, lastUsed: now, runtimeIdentity });
957
+ return {
958
+ agent,
959
+ effectiveRuntime: { ...runtimeResolved, model, egress: runtimeResolved.egress ?? 'cloud' },
960
+ };
961
+ }
962
+ function isChannelAllowlistedSender(channel, message) {
963
+ if (typeof channel.getAllowedUsers !== 'function')
964
+ return false;
965
+ const listed = channel.getAllowedUsers();
966
+ if (!listed || listed.length === 0)
967
+ return false;
968
+ const identities = [message.sender?.id, message.sender?.username].filter((value) => Boolean(value));
969
+ if (identities.length === 0)
970
+ return false;
971
+ const allowed = new Set(listed.map((entry) => entry.trim().replace(/^@/, '').toLowerCase()));
972
+ return identities.some((identity) => allowed.has(identity.trim().replace(/^@/, '').toLowerCase()));
424
973
  }
425
974
  export async function registerAIMessageHandler(manager) {
426
975
  if (aiHandlerRegistered)
427
976
  return;
428
977
  aiHandlerRegistered = true;
429
978
  manager.onMessage(async (message, channel) => {
979
+ let releaseTranscriptSnapshotHold;
980
+ let generativeSessionKey;
981
+ let generativeTurnEngaged = false;
982
+ let cognitiveTurn = null;
983
+ let deliveryState = 'not_started';
430
984
  try {
431
985
  // 1. DM pairing gate — unapproved senders get a code, then we stop.
986
+ // A sender already on the channel static allowlist skipped pairing in the
987
+ // adapter; do not re-gate them here (pairing default-on would otherwise
988
+ // refuse the operator's own Telegram id).
432
989
  const { checkDMPairing, getDMPairing } = await import('../../channels/core.js');
433
- const pairingStatus = await checkDMPairing(message);
434
- if (!pairingStatus.approved) {
435
- if (pairingStatus.code) {
990
+ if (!isChannelAllowlistedSender(channel, message)) {
991
+ const pairingStatus = await checkDMPairing(message);
992
+ if (!pairingStatus.approved) {
436
993
  const pairing = getDMPairing();
437
994
  const pairingMsg = pairing.getPairingMessage(pairingStatus);
438
- await channel.send({
439
- channelId: message.channel.id,
440
- content: pairingMsg,
441
- replyTo: message.id,
442
- });
995
+ if (pairingMsg) {
996
+ await channel.send({
997
+ channelId: message.channel.id,
998
+ content: pairingMsg,
999
+ replyTo: message.id,
1000
+ });
1001
+ }
1002
+ return;
443
1003
  }
444
- return;
445
1004
  }
446
1005
  // Nothing to answer (e.g. a non-text message with no transcription).
447
1006
  if (!message.content || !message.content.trim()) {
448
1007
  return;
449
1008
  }
1009
+ try {
1010
+ const { observeInboundForAwayPause } = await import('../../companion/away-mode.js');
1011
+ observeInboundForAwayPause(channel.type, message.content);
1012
+ }
1013
+ catch {
1014
+ /* travel-mode pause is optional and must never block inbound chat */
1015
+ }
1016
+ const sessionKey = message.sessionKey || 'default-global';
1017
+ // On-demand camera share (« qu'est-ce que tu vois ? ») — Telegram only.
1018
+ // The photo sender is scoped to the requesting chat, not the global alert chat.
1019
+ if (channel.type === 'telegram') {
1020
+ try {
1021
+ const { maybeHandleCameraShareRequest } = await import('../../companion/camera-share.js');
1022
+ const share = await maybeHandleCameraShareRequest(message.content, {
1023
+ surface: 'telegram',
1024
+ inboundChatId: message.channel.id,
1025
+ rootDir: process.cwd(),
1026
+ sendPhoto: async (caption, imagePath) => {
1027
+ const imageChannel = channel;
1028
+ if (typeof imageChannel.sendImageFile === 'function') {
1029
+ await imageChannel.sendImageFile(message.channel.id, imagePath, caption);
1030
+ return true;
1031
+ }
1032
+ const path = await import('node:path');
1033
+ const extension = path.extname(imagePath).slice(1).toLowerCase();
1034
+ const sent = await imageChannel.send({
1035
+ channelId: message.channel.id,
1036
+ content: caption,
1037
+ replyTo: message.id,
1038
+ attachments: [{
1039
+ type: 'image',
1040
+ filePath: imagePath,
1041
+ fileName: path.basename(imagePath),
1042
+ mimeType: extension === 'jpg' || extension === 'jpeg'
1043
+ ? 'image/jpeg'
1044
+ : `image/${extension || 'png'}`,
1045
+ }],
1046
+ });
1047
+ return Boolean(sent?.success);
1048
+ },
1049
+ });
1050
+ if (share) {
1051
+ await channel.send({
1052
+ channelId: message.channel.id,
1053
+ content: share.spokenReply,
1054
+ replyTo: message.id,
1055
+ });
1056
+ return;
1057
+ }
1058
+ }
1059
+ catch (cameraShareErr) {
1060
+ logger.warn('Camera share channel path failed', {
1061
+ error: cameraShareErr instanceof Error ? cameraShareErr.message : String(cameraShareErr),
1062
+ });
1063
+ }
1064
+ }
1065
+ // Lisa selfie — cache-first, BEFORE the LLM. Companion profile has no tools,
1066
+ // so a description of lisa_selfie / image_generate never fires here.
1067
+ if (process.env.CODEBUDDY_LISA_SELFIE !== 'false'
1068
+ && isCompanionSurfaceEnabled()) {
1069
+ try {
1070
+ const { tryServeCompanionSelfie } = await import('../../companion/lisa-selfie-router.js');
1071
+ const previousSelfie = recentLisaSelfieSessions.get(sessionKey);
1072
+ const hasRecentSelfie = previousSelfie !== undefined
1073
+ && Date.now() - previousSelfie.at <= LISA_SELFIE_CONTINUATION_TTL_MS;
1074
+ if (previousSelfie && !hasRecentSelfie)
1075
+ recentLisaSelfieSessions.delete(sessionKey);
1076
+ const served = await tryServeCompanionSelfie(message.content, {
1077
+ surface: channel.type === 'telegram' ? 'telegram' : 'mobile',
1078
+ hasRecentSelfie,
1079
+ includeImageBytes: false,
1080
+ });
1081
+ if (served) {
1082
+ if (served.imagePath) {
1083
+ const ch = channel;
1084
+ if (typeof ch.sendImageFile === 'function') {
1085
+ await ch.sendImageFile(message.channel.id, served.imagePath, served.caption);
1086
+ }
1087
+ else {
1088
+ const pathMod = await import('node:path');
1089
+ const ext = pathMod.extname(served.imagePath).slice(1) || 'png';
1090
+ await ch.send({
1091
+ channelId: message.channel.id,
1092
+ content: served.caption,
1093
+ replyTo: message.id,
1094
+ attachments: [
1095
+ {
1096
+ type: 'image',
1097
+ filePath: served.imagePath,
1098
+ fileName: pathMod.basename(served.imagePath),
1099
+ mimeType: served.mimeType
1100
+ ?? (ext === 'jpg' || ext === 'jpeg' ? 'image/jpeg' : `image/${ext}`),
1101
+ },
1102
+ ],
1103
+ });
1104
+ }
1105
+ recentLisaSelfieSessions.set(sessionKey, {
1106
+ at: Date.now(),
1107
+ mood: served.style ?? 'portrait',
1108
+ contentTier: served.contentTier,
1109
+ });
1110
+ }
1111
+ else {
1112
+ await channel.send({
1113
+ channelId: message.channel.id,
1114
+ content: served.caption,
1115
+ replyTo: message.id,
1116
+ });
1117
+ }
1118
+ // The selfie IS a turn of the conversation: without this the next
1119
+ // companion prompt has no trace of the photo that was just sent.
1120
+ rememberCompanionChannelTurn(sessionKey, message.content, served.caption);
1121
+ return;
1122
+ }
1123
+ }
1124
+ catch (selfieErr) {
1125
+ logger.warn('Lisa selfie channel path failed', {
1126
+ error: selfieErr instanceof Error ? selfieErr.message : String(selfieErr),
1127
+ });
1128
+ // fall through to normal AI handler
1129
+ }
1130
+ }
1131
+ const botId = message.channel?.botId;
1132
+ logger.info('Channel inbound message', {
1133
+ channelType: channel.type,
1134
+ sessionHash: hashForLog(sessionKey),
1135
+ botHash: hashForLog(botId),
1136
+ messageHash: hashForLog(message.id),
1137
+ contentType: message.contentType || 'text',
1138
+ contentLength: message.content.length,
1139
+ attachmentCount: message.attachments?.length ?? 0,
1140
+ });
1141
+ const normalizedMessage = normalizeConversationalSlashMessage(message);
1142
+ if (normalizedMessage !== message) {
1143
+ message = normalizedMessage;
1144
+ logger.info('Channel slash prompt reclassified as conversation', {
1145
+ channelType: channel.type,
1146
+ sessionHash: hashForLog(sessionKey),
1147
+ messageHash: hashForLog(message.id),
1148
+ });
1149
+ }
450
1150
  // /council <task> — convene the multi-LLM council (ask several capable
451
1151
  // LLMs, an impartial judge keeps the best, and it learns which model is
452
1152
  // best per task type over time). `/council` alone shows the scoreboard.
@@ -469,21 +1169,44 @@ export async function registerAIMessageHandler(manager) {
469
1169
  catch (councilErr) {
470
1170
  lines.push(`❌ Council a échoué : ${councilErr instanceof Error ? councilErr.message : String(councilErr)}`);
471
1171
  }
472
- // Telegram caps messages ~4096 chars; flush on line boundaries.
473
1172
  const full = lines.join('\n').trim() || '(aucune sortie)';
474
- let buf = '';
475
- const flush = async () => {
476
- if (buf) {
477
- await channel.send({ channelId: message.channel.id, content: buf });
1173
+ // Render the aligned tables (📊 détail par IA + learned ranking) in a
1174
+ // monospace code block so Telegram's proportional font doesn't break the
1175
+ // padded columns; the prose (the winning answer) stays normal text.
1176
+ let tableStart = full.indexOf('📊 Détail par IA');
1177
+ if (tableStart < 0)
1178
+ tableStart = full.search(/Learned model ranking|No council history/);
1179
+ const prose = tableStart >= 0 ? full.slice(0, tableStart).trim() : full;
1180
+ const tables = tableStart >= 0 ? full.slice(tableStart).trim() : '';
1181
+ // Telegram caps messages ~4096 chars; flush on line boundaries. Tables
1182
+ // go in an HTML <pre> block (monospace) — HTML is the robust mode: inside
1183
+ // <pre> only &, <, > need escaping (vs MarkdownV2's ~18 escapes / legacy
1184
+ // Markdown's fragility). See Telegram Bot API "Formatting options".
1185
+ const htmlEscape = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
1186
+ const sendChunked = async (text, mono) => {
1187
+ if (!text)
1188
+ return;
1189
+ const limit = mono ? 3500 : 3800;
1190
+ let buf = '';
1191
+ const flush = async () => {
1192
+ if (!buf)
1193
+ return;
1194
+ await channel.send({
1195
+ channelId: message.channel.id,
1196
+ content: mono ? '<pre>' + htmlEscape(buf) + '</pre>' : buf,
1197
+ parseMode: mono ? 'html' : undefined,
1198
+ });
478
1199
  buf = '';
1200
+ };
1201
+ for (const ln of text.split('\n')) {
1202
+ if (buf.length + ln.length + 1 > limit)
1203
+ await flush();
1204
+ buf += (buf ? '\n' : '') + ln;
479
1205
  }
1206
+ await flush();
480
1207
  };
481
- for (const ln of full.split('\n')) {
482
- if (buf.length + ln.length + 1 > 3800)
483
- await flush();
484
- buf += (buf ? '\n' : '') + ln;
485
- }
486
- await flush();
1208
+ await sendChunked(prose, false);
1209
+ await sendChunked(tables, true);
487
1210
  return;
488
1211
  }
489
1212
  // Remote tool-approval over Telegram. A daemon has no interactive terminal,
@@ -523,72 +1246,927 @@ export async function registerAIMessageHandler(manager) {
523
1246
  ? process.env.CODEBUDDY_PROVIDER
524
1247
  : 'auto';
525
1248
  const resolved = resolveProviderFromEnv(preferredProvider);
526
- if (!resolved) {
527
- logger.warn('No LLM provider for channel chat — set CODEBUDDY_PROVIDER + a provider key/env');
528
- return;
529
- }
530
- const { getRouteAgentConfig } = await import('../../channels/core.js');
1249
+ const { getRouteAgentConfig, resolveRoute } = await import('../../channels/core.js');
531
1250
  const agentConfig = getRouteAgentConfig(message);
532
- const sessionKey = message.sessionKey || 'default-global';
533
- // Reuse ONE agent per chat (cached by sessionKey) so multi-turn context
534
- // persists in-memory across messages; restored from disk on a cold start.
535
- // botId selects the per-bot persona and is already baked into sessionKey,
536
- // so different bots keep separate agents + histories.
537
- const botId = message.channel?.botId;
538
- const agent = await getOrCreateChannelAgent(sessionKey, resolved, agentConfig, botId);
539
- const entries = await agent.processUserMessage(message.content);
540
- const lastEntry = entries[entries.length - 1];
541
- const response = lastEntry ? String(lastEntry.content) : '';
542
- // 6. Deliver reply (text)
543
- await channel.send({
544
- channelId: message.channel.id,
545
- content: response,
546
- replyTo: message.id,
547
- });
548
- // 7. If the user SPOKE (voice note), answer by voice too — mirror the
549
- // modality. Best-effort: the text reply already landed, so a TTS/upload
550
- // failure (or a channel without voice support) is a no-op, never fatal.
551
- const userSpoke = message.attachments?.some((a) => a.type === 'voice' || a.type === 'audio');
552
- const voiceChannel = channel;
553
- if (userSpoke && response.trim() && typeof voiceChannel.sendVoiceReply === 'function') {
554
- try {
555
- await voiceChannel.sendVoiceReply(message.channel.id, response);
1251
+ // The "route" tier only counts an EXPLICITLY matched route — a
1252
+ // matchType of 'default' is the router-wide fallback and must not
1253
+ // outrank a bot persona (it lands in the route-default tier instead).
1254
+ const resolvedRoute = resolveRoute(message);
1255
+ const routeModel = resolvedRoute && resolvedRoute.matchType !== 'default' ? resolvedRoute.agent?.model : undefined;
1256
+ // /model per-conversation model override (Hermes parity: session tier).
1257
+ // `/model` shows the effective model + source, `/model <name>` overrides
1258
+ // this chat, `/model reset` reverts to the channel/global tiers. Handled
1259
+ // before the agent so it never burns an LLM turn. `(?:@\S+)?` accepts
1260
+ // Telegram's `/model@BotName` group form.
1261
+ const modelCmd = message.content.trim().match(/^\/model(?:@\S+)?(?:\s+(\S+))?\s*$/i);
1262
+ if (modelCmd) {
1263
+ const arg = modelCmd[1];
1264
+ const personaForShow = botId ? channelBotPersonas.get(botId) : undefined;
1265
+ const effective = () => {
1266
+ const { model, source } = resolveChannelModel({
1267
+ sessionOverride: getSessionModelOverride(sessionKey),
1268
+ routeModel,
1269
+ personaModel: personaForShow?.model,
1270
+ routeDefaultModel: agentConfig.model,
1271
+ globalModel: resolved?.model || 'indisponible',
1272
+ });
1273
+ return `${model} (source : ${source})`;
1274
+ };
1275
+ let reply;
1276
+ if (!arg) {
1277
+ reply = `Modèle : ${effective()} — /model <nom> pour changer, /model reset pour annuler`;
1278
+ }
1279
+ else if (arg.toLowerCase() === 'reset') {
1280
+ clearSessionModelOverride(sessionKey);
1281
+ reply = `Override retiré. Modèle effectif : ${effective()}`;
556
1282
  }
557
- catch (voiceErr) {
558
- logger.warn(`Voice reply skipped: ${voiceErr instanceof Error ? voiceErr.message : String(voiceErr)}`);
1283
+ else if (!MODEL_NAME_PATTERN.test(arg)) {
1284
+ reply = 'Nom de modèle invalide. Usage : /model <nom> | /model reset | /model';
1285
+ }
1286
+ else {
1287
+ setSessionModelOverride(sessionKey, arg);
1288
+ reply = `✅ Modèle de cette conversation : ${arg} — appliqué dès le prochain message. Si le modèle est invalide, /model reset pour revenir.`;
559
1289
  }
1290
+ await channel.send({ channelId: message.channel.id, content: reply, replyTo: message.id });
1291
+ return;
560
1292
  }
561
- // 7b. Deliver image artifacts: if the reply names image paths that exist
562
- // on disk (e.g. a chart the agent just generated), send them as photos.
563
- const imageChannel = channel;
564
- if (typeof imageChannel.sendImageFile === 'function') {
565
- const os = await import('node:os');
566
- const fsp = await import('node:fs/promises');
567
- const matches = response.match(/(?:~\/|\/)[\w./-]+\.(?:png|jpe?g|gif|webp)/gi) || [];
568
- const seen = new Set();
569
- for (const raw of matches) {
570
- const p = raw.startsWith('~/') ? os.homedir() + raw.slice(1) : raw;
571
- if (seen.has(p) || seen.size >= 4)
572
- continue;
573
- seen.add(p);
1293
+ const queuedAt = Date.now();
1294
+ await serializeChannelTurn(sessionKey, async (turn) => {
1295
+ const queueWaitMs = Date.now() - queuedAt;
1296
+ if (queueWaitMs >= 1_000) {
1297
+ logger.info('Channel turn dequeued after waiting', {
1298
+ channelType: channel.type,
1299
+ sessionHash: hashForLog(sessionKey),
1300
+ messageHash: hashForLog(message.id),
1301
+ queueWaitMs,
1302
+ });
1303
+ }
1304
+ turn.phase('continuity');
1305
+ turn.throwIfAborted();
1306
+ // Reuse ONE agent per chat (cached by sessionKey) so multi-turn context
1307
+ // persists in-memory across messages; restored from disk on a cold start.
1308
+ // botId selects the per-bot persona and is already baked into sessionKey,
1309
+ // so different bots keep separate agents + histories.
1310
+ const { getCrossChannelConversationBridge } = await import('../../conversation/cross-channel-bridge.js');
1311
+ const conversationBridge = getCrossChannelConversationBridge();
1312
+ const continuesVoiceConversation = !message.isCommand &&
1313
+ !message.content.trim().startsWith('/') &&
1314
+ conversationBridge.matchesChannel(channel.type, message.channel.id, message.threadId);
1315
+ // Snapshot BEFORE appending the current user turn. The current message is
1316
+ // supplied separately to the agent and must not appear twice in its prompt.
1317
+ const sharedConversationHistory = continuesVoiceConversation
1318
+ ? conversationBridge.history()
1319
+ : [];
1320
+ if (continuesVoiceConversation) {
1321
+ const claim = await conversationBridge.claimChannelTurnDurably({
1322
+ role: 'user',
1323
+ content: message.content,
1324
+ channel: channel.type,
1325
+ channelId: message.channel.id,
1326
+ ...(message.threadId ? { threadId: message.threadId } : {}),
1327
+ externalId: message.id,
1328
+ });
1329
+ turn.throwIfAborted();
1330
+ if (claim === 'duplicate') {
1331
+ logger.info('Duplicate channel turn skipped before generation', {
1332
+ channelType: channel.type,
1333
+ sessionHash: hashForLog(sessionKey),
1334
+ messageHash: hashForLog(message.id),
1335
+ });
1336
+ return;
1337
+ }
1338
+ if (claim === 'failed') {
1339
+ throw new Error('shared conversation journal claim failed');
1340
+ }
1341
+ }
1342
+ // Derived after appending the current turn, so an affect/support signal
1343
+ // observed on Telegram is available immediately to this very response.
1344
+ // The renderer is raw-free: it never repeats transcript text or personal
1345
+ // facts and is only used for the explicitly linked companion thread.
1346
+ const sharedRelationshipContext = continuesVoiceConversation
1347
+ ? conversationBridge.renderRelationshipContext()
1348
+ : '';
1349
+ const channelPersona = botId ? channelBotPersonas.get(botId) : undefined;
1350
+ const companionPersona = /\b(lisa|compagne|compagnon|companion)\b/i.test(`${channelPersona?.name ?? ''} ${channelPersona?.systemPrompt ?? ''}`);
1351
+ const companionConversation = (companionPersona || Boolean(channelPersona?.systemPrompt) || continuesVoiceConversation) &&
1352
+ process.env.CODEBUDDY_CHANNEL_CONVERSATION !== 'false';
1353
+ let companionRoute;
1354
+ const hasExplicitModel = Boolean(getSessionModelOverride(sessionKey) || routeModel || channelPersona?.model);
1355
+ if ((companionPersona || continuesVoiceConversation) &&
1356
+ companionConversation &&
1357
+ channel.type === 'telegram' &&
1358
+ !hasExplicitModel) {
1359
+ try {
1360
+ const routingHistory = await resolveChannelRoutingHistory(sessionKey, sharedConversationHistory);
1361
+ const { resolveCompanionModelRoute } = await import('../../conversation/companion-model-routing.js');
1362
+ companionRoute =
1363
+ (await resolveCompanionModelRoute({
1364
+ surface: 'telegram',
1365
+ text: message.content,
1366
+ history: routingHistory,
1367
+ env: process.env,
1368
+ })) ?? undefined;
1369
+ turn.throwIfAborted();
1370
+ }
1371
+ catch (error) {
1372
+ logger.debug('Companion pilot routing unavailable on channel', {
1373
+ channelType: channel.type,
1374
+ error: error instanceof Error ? error.message : String(error),
1375
+ });
1376
+ }
1377
+ }
1378
+ const runtimeResolved = resolved ??
1379
+ (companionRoute
1380
+ ? {
1381
+ apiKey: companionRoute.apiKey,
1382
+ baseUrl: companionRoute.baseURL,
1383
+ model: companionRoute.model,
1384
+ egress: companionRoute.egress,
1385
+ }
1386
+ : null);
1387
+ if (!runtimeResolved) {
1388
+ logger.warn('No LLM provider for channel chat — set CODEBUDDY_PROVIDER or activate an available companion route');
1389
+ const { conversationFailureReply } = await import('../../conversation/conversation-orchestrator.js');
1390
+ await channel.send({
1391
+ channelId: message.channel.id,
1392
+ content: conversationFailureReply(message.content),
1393
+ replyTo: message.id,
1394
+ });
1395
+ return;
1396
+ }
1397
+ const useCompanionProfile = shouldUseCompanionChannelProfile({
1398
+ text: message.content,
1399
+ isCommand: message.isCommand === true,
1400
+ });
1401
+ turn.phase('runtime');
1402
+ let agent;
1403
+ let effectiveRuntime = {
1404
+ apiKey: runtimeResolved.apiKey,
1405
+ baseUrl: runtimeResolved.baseUrl,
1406
+ model: runtimeResolved.model,
1407
+ egress: runtimeResolved.egress ?? 'cloud',
1408
+ };
1409
+ if (!useCompanionProfile) {
1410
+ const created = await getOrCreateChannelAgent(sessionKey, runtimeResolved, agentConfig, botId, routeModel, companionRoute);
1411
+ agent = created.agent;
1412
+ effectiveRuntime = created.effectiveRuntime;
1413
+ }
1414
+ turn.throwIfAborted();
1415
+ turn.phase('grounding');
1416
+ let attachedImageEvidence;
1417
+ // A photo shared with the companion is not an analysis request: it goes
1418
+ // through the shared-photo pipeline (privacy posture, reaction contract,
1419
+ // album, memory) instead of the analytical evidence card the agent path
1420
+ // uses. See `companion/companion-photo.ts`.
1421
+ let companionPhotos = null;
1422
+ const imageAttachmentCount = message.attachments?.filter((attachment) => attachment.type === 'image').length ?? 0;
1423
+ const telegramFileResolver = channel.type === 'telegram' &&
1424
+ typeof channel.getFileUrl === 'function'
1425
+ ? (reference) => channel.getFileUrl(reference)
1426
+ : undefined;
1427
+ if (imageAttachmentCount > 0 && useCompanionProfile) {
1428
+ try {
1429
+ const [{ loadChannelPhotos }, { prepareCompanionPhotos }] = await Promise.all([
1430
+ import('../../companion/companion-photo-intake.js'),
1431
+ import('../../companion/companion-photo.js'),
1432
+ ]);
1433
+ const loaded = await loadChannelPhotos(message.attachments, {
1434
+ ...(telegramFileResolver ? { resolveUrl: telegramFileResolver } : {}),
1435
+ signal: turn.signal,
1436
+ });
1437
+ turn.throwIfAborted();
1438
+ companionPhotos = await prepareCompanionPhotos(loaded, {
1439
+ caption: message.content,
1440
+ model: effectiveRuntime.model,
1441
+ baseUrl: effectiveRuntime.baseUrl,
1442
+ });
1443
+ logger.info('Companion shared-photo perception completed', {
1444
+ channelType: channel.type,
1445
+ sessionHash: hashForLog(sessionKey),
1446
+ messageHash: hashForLog(message.id),
1447
+ mode: companionPhotos?.mode,
1448
+ accepted: companionPhotos?.photos.length ?? 0,
1449
+ rejected: companionPhotos?.rejected.length ?? 0,
1450
+ });
1451
+ }
1452
+ catch (error) {
1453
+ turn.throwIfAborted();
1454
+ companionPhotos = null;
1455
+ logger.warn('Companion shared-photo perception unavailable', {
1456
+ channelType: channel.type,
1457
+ sessionHash: hashForLog(sessionKey),
1458
+ error: error instanceof Error ? error.message : String(error),
1459
+ });
1460
+ }
1461
+ }
1462
+ else if (imageAttachmentCount > 0) {
1463
+ const { groundAttachedImages, renderAttachedImageEvidence, } = await import('../../companion/attached-image-grounding.js');
1464
+ const visual = await groundAttachedImages(message.attachments, message.content, {
1465
+ ...(telegramFileResolver ? { resolveUrl: telegramFileResolver } : {}),
1466
+ });
1467
+ turn.throwIfAborted();
1468
+ attachedImageEvidence = renderAttachedImageEvidence(visual) || undefined;
1469
+ logger.info('Channel attached-image perception completed', {
1470
+ channelType: channel.type,
1471
+ sessionHash: hashForLog(sessionKey),
1472
+ messageHash: hashForLog(message.id),
1473
+ imageCount: visual.imageCount,
1474
+ status: visual.status,
1475
+ model: visual.model,
1476
+ reason: visual.reason,
1477
+ });
1478
+ }
1479
+ if (companionConversation && !useCompanionProfile) {
1480
+ cognitiveTurn = await getChannelCognitivePort().begin({
1481
+ channelType: channel.type,
1482
+ sessionKey,
1483
+ messageId: message.id,
1484
+ content: message.content,
1485
+ egress: effectiveRuntime.egress,
1486
+ });
1487
+ turn.throwIfAborted();
1488
+ }
1489
+ const agentInput = companionPhotos
1490
+ ? companionPhotos.userText
1491
+ : attachedImageEvidence
1492
+ ? `${message.content}\n\n${attachedImageEvidence}\n\n` +
1493
+ 'Réponds à la demande en t’appuyant sur cette fiche visuelle. Distingue les faits visibles des incertitudes.'
1494
+ : imageAttachmentCount > 0
1495
+ ? `${message.content}\n\nL’analyse des images jointes a échoué. Dis-le honnêtement et demande un nouvel envoi net si nécessaire.`
1496
+ : message.content;
1497
+ let transientConversationContext;
1498
+ let preparedConversation;
1499
+ let companionConversationHistory = [];
1500
+ let companionFreshEvidence;
1501
+ let prefetchedGroundedFallback;
1502
+ let prefetchedDirectResponse;
1503
+ if (companionConversation) {
1504
+ const [conversation, prefetchedContext, prefetchEngine] = await Promise.all([
1505
+ import('../../conversation/conversation-orchestrator.js'),
1506
+ import('../../conversation/prefetched-turn-context.js'),
1507
+ import('../../companion/prefetch-engine.js'),
1508
+ ]);
1509
+ const history = sharedConversationHistory.length
1510
+ ? sharedConversationHistory.slice(-12)
1511
+ : useCompanionProfile
1512
+ ? (companionChannelHistories.get(sessionKey) ?? []).slice(-12)
1513
+ : (agent
1514
+ ?.getChatHistory()
1515
+ .filter((entry) => entry.type === 'user' || entry.type === 'assistant')
1516
+ .slice(-12)
1517
+ .map((entry) => {
1518
+ const content = String(entry.content ?? '')
1519
+ .replace(/<companion_turn>[\s\S]*?<\/companion_turn>\s*/g, '')
1520
+ .replace(/^Message de l'utilisateur\s*:\s*/i, '')
1521
+ .trim();
1522
+ return {
1523
+ role: entry.type === 'user' ? 'user' : 'assistant',
1524
+ content,
1525
+ };
1526
+ })
1527
+ .filter((entry) => entry.content) ?? []);
1528
+ companionConversationHistory = history;
1529
+ const freshContext = process.env.CODEBUDDY_PREFETCH === 'false'
1530
+ ? null
1531
+ : prefetchedContext.resolvePrefetchedTurnContextForConversation(message.content, history, { allowStale: true });
1532
+ if (process.env.CODEBUDDY_PREFETCH !== 'false' &&
1533
+ (freshContext?.freshness === 'stale' ||
1534
+ (!freshContext && prefetchedContext.isPrefetchedTurnRequest(message.content)))) {
1535
+ void prefetchEngine.runPrefetchCycle().catch(() => undefined);
1536
+ }
1537
+ companionFreshEvidence =
1538
+ prefetchedContext.semanticReviewEvidenceFromPrefetch(freshContext);
1539
+ companionFreshEvidence = [companionFreshEvidence, attachedImageEvidence]
1540
+ .filter((part) => Boolean(part?.trim()))
1541
+ .join('\n\n') || undefined;
1542
+ prefetchedGroundedFallback = freshContext
1543
+ ? freshContext.text.trim() || freshContext.speech.trim() || undefined
1544
+ : undefined;
1545
+ if (freshContext &&
1546
+ prefetchedContext.shouldUsePrefetchedAnswerDirectly(message.content, freshContext)) {
1547
+ prefetchedDirectResponse = prefetchedGroundedFallback;
1548
+ }
1549
+ preparedConversation = conversation.prepareConversationTurn(message.content, history, {
1550
+ ...(sharedRelationshipContext
1551
+ ? { relationshipContext: sharedRelationshipContext }
1552
+ : {}),
1553
+ ...(freshContext ? { freshContext: freshContext.promptGuidance } : {}),
1554
+ });
1555
+ transientConversationContext = [
1556
+ preparedConversation.systemGuidance,
1557
+ cognitiveTurn?.turnContext,
1558
+ cognitiveTurn?.evidence,
1559
+ ].filter((part) => Boolean(part?.trim())).join('\n\n') || undefined;
1560
+ }
1561
+ const semanticReviewProfile = isRuntimeEvidenceVerificationRequest(message.content)
1562
+ ? 'factual_analytical'
1563
+ : undefined;
1564
+ const semanticReviewPlanned = !useCompanionProfile &&
1565
+ companionConversation &&
1566
+ !prefetchedDirectResponse &&
1567
+ preparedConversation !== undefined &&
1568
+ shouldRunSemanticResponseGate({
1569
+ plan: preparedConversation.plan,
1570
+ ...(semanticReviewProfile ? { profile: semanticReviewProfile } : {}),
1571
+ }) &&
1572
+ deriveArgumentObligations(preparedConversation.plan, message.content).length > 0;
1573
+ if (semanticReviewPlanned && agent) {
1574
+ const snapshotAgent = agent;
1575
+ snapshotAgent.suspendTranscriptSnapshots();
1576
+ let released = false;
1577
+ releaseTranscriptSnapshotHold = () => {
1578
+ if (released)
1579
+ return;
1580
+ released = true;
1581
+ if (channelAgentCache.get(sessionKey)?.agent === snapshotAgent) {
1582
+ snapshotAgent.resumeTranscriptSnapshots();
1583
+ }
1584
+ };
1585
+ }
1586
+ // From this point onward the cached agent may contain a user turn or an
1587
+ // assistant draft. Any later exception (including a rejected transport
1588
+ // promise) must discard that private state unless delivery and
1589
+ // persistence complete normally.
1590
+ generativeSessionKey = sessionKey;
1591
+ generativeTurnEngaged = Boolean(agent);
1592
+ let response = '';
1593
+ let rawAgentFailure = false;
1594
+ let hasGeneratedResponse = false;
1595
+ let successfulLisaSelfieToolResult = false;
1596
+ let shouldPersistChannelSession = Boolean(agent);
1597
+ let telegramWidget;
1598
+ if (prefetchedDirectResponse) {
1599
+ response = prefetchedDirectResponse;
1600
+ if (agent && !agent.recordTrustedExternalConversationTurn(agentInput, response)) {
1601
+ throw new Error('trusted prefetched turn could not be recorded');
1602
+ }
1603
+ logger.info('Channel served trusted prefetched companion response directly', {
1604
+ channelType: channel.type,
1605
+ sessionHash: hashForLog(sessionKey),
1606
+ messageHash: hashForLog(message.id),
1607
+ responseLength: response.length,
1608
+ });
1609
+ }
1610
+ else if (useCompanionProfile) {
1611
+ turn.phase('generation');
1612
+ const hasSharedPhotos = (companionPhotos?.photos.length ?? 0) > 0;
1613
+ const prompt = await assembleCompanionChannelPrompt({
1614
+ userText: agentInput,
1615
+ history: companionConversationHistory.length
1616
+ ? companionConversationHistory
1617
+ : companionChannelHistories.get(sessionKey),
1618
+ ...(hasSharedPhotos && companionPhotos
1619
+ ? { extraSystem: companionPhotos.guidance }
1620
+ : {}),
1621
+ });
1622
+ let companionMessages = prompt.messages;
1623
+ if (hasSharedPhotos && companionPhotos?.mode === 'cloud') {
1624
+ const { attachPhotoParts } = await import('../../companion/companion-photo.js');
1625
+ companionMessages = attachPhotoParts(prompt.messages, companionPhotos.photos);
1626
+ }
1627
+ logger.info('Companion channel profile prompt', {
1628
+ channelType: channel.type,
1629
+ sessionHash: hashForLog(sessionKey),
1630
+ tokenEstimate: prompt.tokenEstimate,
1631
+ messageCount: prompt.messages.length,
1632
+ sharedPhotos: companionPhotos?.photos.length ?? 0,
1633
+ });
1634
+ try {
1635
+ const generated = await runCompanionChannelTurn({
1636
+ apiKey: effectiveRuntime.apiKey,
1637
+ baseUrl: effectiveRuntime.baseUrl,
1638
+ model: effectiveRuntime.model,
1639
+ messages: companionMessages,
1640
+ signal: turn.signal,
1641
+ });
1642
+ turn.throwIfAborted();
1643
+ response = generated.text;
1644
+ hasGeneratedResponse = response.trim() !== '';
1645
+ if (hasSharedPhotos && companionPhotos) {
1646
+ // The album write is deliberately after the reply: a full disk must
1647
+ // cost the memory, never the reaction.
1648
+ const { rememberSharedPhotos } = await import('../../companion/shared-photo-memory.js');
1649
+ const stored = await rememberSharedPhotos(companionPhotos.photos, {
1650
+ surface: 'telegram',
1651
+ caption: message.content,
1652
+ });
1653
+ logger.info('Companion shared photos filed', {
1654
+ channelType: channel.type,
1655
+ sessionHash: hashForLog(sessionKey),
1656
+ stored: stored.length,
1657
+ });
1658
+ }
1659
+ }
1660
+ catch (error) {
1661
+ turn.throwIfAborted();
1662
+ response = speakChannelProviderFailure(error, {
1663
+ copine: Boolean(process.env.CODEBUDDY_COMPANION_PERSONA),
1664
+ });
1665
+ logger.warn('Companion channel provider failure spoken to conversation', {
1666
+ channelType: channel.type,
1667
+ sessionHash: hashForLog(sessionKey),
1668
+ error: error instanceof Error ? error.message : String(error),
1669
+ });
1670
+ }
1671
+ }
1672
+ else {
1673
+ turn.phase('generation');
1674
+ const entries = await agent.processUserMessage(agentInput, {
1675
+ surface: channel.type,
1676
+ ...(attachedImageEvidence || imageAttachmentCount > 0
1677
+ ? { introspectionText: message.content }
1678
+ : {}),
1679
+ ...(transientConversationContext
1680
+ ? {
1681
+ transientContext: transientConversationContext,
1682
+ relationshipSafety: companionConversation,
1683
+ }
1684
+ : {}),
1685
+ });
1686
+ successfulLisaSelfieToolResult = entries.some((entry) => entry.type === 'tool_result' &&
1687
+ entry.toolResult?.success === true &&
1688
+ entry.toolCall?.function?.name === 'lisa_selfie');
1689
+ turn.throwIfAborted();
1690
+ const lastEntry = entries[entries.length - 1];
1691
+ response = lastEntry ? String(lastEntry.content) : '';
1692
+ if (channel.type === 'telegram') {
1693
+ const { autoWidget } = await import('../../widgets/auto-widget.js');
1694
+ const widget = await autoWidget(response, entries
1695
+ .filter((entry) => entry.type === 'tool_result')
1696
+ .map((entry) => entry.toolResult ?? { output: entry.content }));
1697
+ if (widget.widgetHtml || widget.candidate) {
1698
+ telegramWidget = {
1699
+ ...(widget.widgetHtml ? { widgetHtml: widget.widgetHtml } : {}),
1700
+ ...(widget.candidate?.kind === 'payload' ? { data: widget.candidate.data } : {}),
1701
+ };
1702
+ }
1703
+ }
1704
+ rawAgentFailure = isAgentFailureResponse(response);
1705
+ hasGeneratedResponse = response.trim() !== '' && !rawAgentFailure;
1706
+ }
1707
+ if (hasGeneratedResponse) {
1708
+ response = prependUserFacingFailoverNotice(response, `channel:${channel.type}`);
1709
+ }
1710
+ if (!response.trim() || rawAgentFailure) {
1711
+ const { conversationFailureReply } = await import('../../conversation/conversation-orchestrator.js');
1712
+ const replacement = prefetchedGroundedFallback ??
1713
+ (rawAgentFailure
1714
+ ? speakChannelProviderFailure(response, {
1715
+ copine: Boolean(process.env.CODEBUDDY_COMPANION_PERSONA),
1716
+ })
1717
+ : conversationFailureReply(message.content, companionConversationHistory));
1718
+ if (prefetchedGroundedFallback) {
1719
+ logger.info('Channel provider failure recovered from prefetched companion context', {
1720
+ channelType: channel.type,
1721
+ sessionHash: hashForLog(sessionKey),
1722
+ });
1723
+ }
1724
+ if (rawAgentFailure) {
1725
+ if (agent && !agent.replaceLastAssistantResponse(response, replacement)) {
1726
+ evictChannelAgent(sessionKey, true);
1727
+ shouldPersistChannelSession = false;
1728
+ logger.error('Channel provider failure rewrite missed agent history', {
1729
+ channelType: channel.type,
1730
+ sessionHash: hashForLog(sessionKey),
1731
+ });
1732
+ }
1733
+ logger.warn('Channel provider failure spoken to conversation', {
1734
+ channelType: channel.type,
1735
+ sessionHash: hashForLog(sessionKey),
1736
+ });
1737
+ }
1738
+ response = replacement;
1739
+ }
1740
+ const semanticReviewEligible = semanticReviewPlanned &&
1741
+ hasGeneratedResponse &&
1742
+ !successfulLisaSelfieToolResult &&
1743
+ preparedConversation !== undefined;
1744
+ // The semantic reviewer may resolve to a different provider/egress than
1745
+ // the main model. Cognitive evidence was projected for the main route,
1746
+ // so it cannot cross this second model boundary without a new projection.
1747
+ const semanticEvidence = companionFreshEvidence?.trim() || undefined;
1748
+ if (semanticReviewEligible && preparedConversation) {
1749
+ turn.phase('review');
574
1750
  try {
575
- await fsp.access(p);
576
- await imageChannel.sendImageFile(message.channel.id, p);
1751
+ const { reviewSemanticResponse } = await import('../../conversation/semantic-response-runtime.js');
1752
+ const unreviewedResponse = response;
1753
+ const reviewed = await reviewSemanticResponse({
1754
+ request: message.content,
1755
+ draft: unreviewedResponse,
1756
+ plan: preparedConversation.plan,
1757
+ ...(semanticReviewProfile ? { profile: semanticReviewProfile } : {}),
1758
+ history: companionConversationHistory,
1759
+ ...(semanticEvidence ? { evidence: semanticEvidence } : {}),
1760
+ mainProvider: {
1761
+ apiKey: effectiveRuntime.apiKey,
1762
+ baseURL: effectiveRuntime.baseUrl,
1763
+ model: effectiveRuntime.model,
1764
+ },
1765
+ });
1766
+ turn.throwIfAborted();
1767
+ const rejectedFreshGrounding = reviewed.outcome === 'fail_open' &&
1768
+ (reviewed.audit?.issueCodes.includes('ungrounded_fresh_claim') === true ||
1769
+ reviewed.verificationAudit?.issueCodes.includes('ungrounded_fresh_claim') === true);
1770
+ const groundedRecovery = rejectedFreshGrounding
1771
+ ? prefetchedGroundedFallback ??
1772
+ "Je n’ai pas réussi à vérifier cette information fraîche avec une source exploitable. " +
1773
+ 'Je préfère ne pas l’inventer ; redemande-moi dans un instant.'
1774
+ : undefined;
1775
+ response = groundedRecovery ?? (reviewed.response.trim() || unreviewedResponse);
1776
+ if (response !== unreviewedResponse) {
1777
+ if (agent && !agent.replaceLastAssistantResponse(unreviewedResponse, response)) {
1778
+ // Delivery may continue with the reviewed text, but an agent
1779
+ // containing the rejected draft can neither be cached nor saved.
1780
+ evictChannelAgent(sessionKey, true);
1781
+ shouldPersistChannelSession = false;
1782
+ logger.error('Companion semantic rewrite missed agent history', {
1783
+ channelType: channel.type,
1784
+ sessionHash: hashForLog(sessionKey),
1785
+ });
1786
+ }
1787
+ }
1788
+ if (groundedRecovery) {
1789
+ logger.warn('Companion rejected ungrounded fresh response before delivery', {
1790
+ channelType: channel.type,
1791
+ sessionHash: hashForLog(sessionKey),
1792
+ recovery: prefetchedGroundedFallback ? 'prefetched_evidence' : 'honest_retry',
1793
+ });
1794
+ }
1795
+ logger.info('Companion semantic response gate completed', {
1796
+ channelType: channel.type,
1797
+ sessionHash: hashForLog(sessionKey),
1798
+ outcome: reviewed.outcome,
1799
+ reason: reviewed.reason,
1800
+ revisionAttempts: reviewed.revisionAttempts,
1801
+ issueCodes: reviewed.audit?.issueCodes ?? [],
1802
+ lowDimensions: reviewed.audit?.lowDimensions ?? [],
1803
+ });
1804
+ }
1805
+ catch (error) {
1806
+ // The shared runtime is fail-open; retain that property if module
1807
+ // loading itself is unavailable in an older packaged installation.
1808
+ logger.warn('Companion semantic response gate unavailable', {
1809
+ channelType: channel.type,
1810
+ sessionHash: hashForLog(sessionKey),
1811
+ errorType: error instanceof Error ? error.name : 'unknown',
1812
+ });
1813
+ }
1814
+ }
1815
+ if ((companionConversation || useCompanionProfile) && response.trim()) {
1816
+ const { guardRelationshipReply } = await import('../../conversation/relationship-safety.js');
1817
+ const guarded = guardRelationshipReply(response);
1818
+ const unguardedResponse = response;
1819
+ response = guarded.response;
1820
+ try {
1821
+ const { applyLimitsContract } = await import('../../companion/reply-augment.js');
1822
+ response = applyLimitsContract(response, { heard: message.content }).text;
577
1823
  }
578
1824
  catch {
579
- // path isn't a real/accessible image — skip
1825
+ /* limits contract is optional */
1826
+ }
1827
+ try {
1828
+ const { rememberSaid } = await import('../../companion/recent-said.js');
1829
+ rememberSaid(response, 'telegram');
1830
+ }
1831
+ catch {
1832
+ /* recent-said is optional */
1833
+ }
1834
+ if (guarded.intervened) {
1835
+ if (agent && !agent.replaceLastAssistantResponse(unguardedResponse, response)) {
1836
+ // Never retain a response that the delivery gate rejected. A cold
1837
+ // agent will restore the safe persisted transcript on the next turn.
1838
+ evictChannelAgent(sessionKey, true);
1839
+ shouldPersistChannelSession = false;
1840
+ logger.error('Companion relationship safety rewrite missed agent history', {
1841
+ channelType: channel.type,
1842
+ sessionHash: hashForLog(sessionKey),
1843
+ });
1844
+ }
1845
+ logger.warn('Companion relationship safety gate intervened on channel reply', {
1846
+ channelType: channel.type,
1847
+ sessionHash: hashForLog(sessionKey),
1848
+ issues: guarded.issues,
1849
+ });
580
1850
  }
581
1851
  }
582
- }
583
- // 8. Persist the conversation so it survives a daemon restart / cache eviction.
584
- await persistChannelSession(agent, sessionKey);
1852
+ let deliveryMode = response.trim() ? 'native' : 'fallback';
1853
+ let deliveredChunks = 0;
1854
+ let delivered = false;
1855
+ let deliveredAssistantContent = '';
1856
+ // 6. Deliver the reply. On Telegram, render the agent's markdown to the
1857
+ // robust HTML subset (bold / code / tables / links) so it doesn't show
1858
+ // raw; if Telegram rejects the HTML (success:false) fall back to plain
1859
+ // text. Other channels keep native markdown (Discord/Slack render it).
1860
+ turn.throwIfAborted();
1861
+ turn.phase('delivery');
1862
+ deliveryState = 'started';
1863
+ if (channel.type === 'telegram' && response.trim() && telegramWidget) {
1864
+ const result = await channel.send({
1865
+ channelId: message.channel.id,
1866
+ content: response,
1867
+ parseMode: 'plain',
1868
+ replyTo: message.id,
1869
+ channelData: { telegram: telegramWidget },
1870
+ });
1871
+ delivered = result?.success === true;
1872
+ deliveredChunks = delivered ? 1 : 0;
1873
+ if (delivered)
1874
+ deliveredAssistantContent = response;
1875
+ if (delivered)
1876
+ deliveryMode = 'telegram-widget';
1877
+ else
1878
+ deliveryMode = 'failed';
1879
+ }
1880
+ else if (channel.type === 'telegram' && response.trim()) {
1881
+ const { renderTelegramHtml, renderPlain, telegramHtmlChunkToPlain, } = await import('../../rendering/index.js');
1882
+ const chunks = renderTelegramHtml(response);
1883
+ const acceptedChunks = [];
1884
+ let ok = chunks.length > 0;
1885
+ for (let i = 0; i < chunks.length; i++) {
1886
+ let res;
1887
+ try {
1888
+ res = await channel.send({
1889
+ channelId: message.channel.id,
1890
+ content: chunks[i],
1891
+ parseMode: 'html',
1892
+ replyTo: i === 0 ? message.id : undefined,
1893
+ });
1894
+ }
1895
+ catch (error) {
1896
+ logger.warn('Telegram HTML chunk transport rejected', {
1897
+ sessionHash: hashForLog(sessionKey),
1898
+ messageHash: hashForLog(message.id),
1899
+ chunk: i + 1,
1900
+ error: error instanceof Error ? error.message : String(error),
1901
+ });
1902
+ ok = false;
1903
+ break;
1904
+ }
1905
+ if (!res?.success) {
1906
+ ok = false;
1907
+ break;
1908
+ }
1909
+ deliveredChunks++;
1910
+ acceptedChunks.push(chunks[i]);
1911
+ }
1912
+ if (!ok) {
1913
+ if (deliveredChunks === 0) {
1914
+ // First HTML chunk rejected: no user-visible prefix exists, so a
1915
+ // complete plain fallback is safe and cannot duplicate content.
1916
+ const fallback = await channel.send({
1917
+ channelId: message.channel.id,
1918
+ content: renderPlain(response),
1919
+ replyTo: message.id,
1920
+ });
1921
+ delivered = fallback?.success === true;
1922
+ deliveryMode = delivered ? 'plain-fallback' : 'failed';
1923
+ if (delivered) {
1924
+ deliveredChunks++;
1925
+ deliveredAssistantContent = response;
1926
+ }
1927
+ }
1928
+ else {
1929
+ // A later chunk failed. Re-sending the whole answer would repeat
1930
+ // every preceding chunk. Preserve only the prefix the person
1931
+ // actually saw; the generated full draft is still evicted below.
1932
+ delivered = false;
1933
+ deliveryMode = 'partial-failure';
1934
+ deliveredAssistantContent = acceptedChunks
1935
+ .map(telegramHtmlChunkToPlain)
1936
+ .filter(Boolean)
1937
+ .join('\n\n')
1938
+ .trim();
1939
+ }
1940
+ }
1941
+ else {
1942
+ deliveryMode = 'telegram-html';
1943
+ delivered = chunks.length > 0;
1944
+ if (delivered)
1945
+ deliveredAssistantContent = response;
1946
+ }
1947
+ }
1948
+ else {
1949
+ const result = await channel.send({
1950
+ channelId: message.channel.id,
1951
+ content: response,
1952
+ replyTo: message.id,
1953
+ });
1954
+ delivered = result?.success === true;
1955
+ deliveredChunks = delivered && response.trim() ? 1 : 0;
1956
+ if (delivered)
1957
+ deliveredAssistantContent = response;
1958
+ if (!delivered)
1959
+ deliveryMode = 'failed';
1960
+ }
1961
+ logger.info('Channel response delivered', {
1962
+ channelType: channel.type,
1963
+ sessionHash: hashForLog(sessionKey),
1964
+ botHash: hashForLog(botId),
1965
+ messageHash: hashForLog(message.id),
1966
+ responseLength: response.length,
1967
+ deliveryMode,
1968
+ deliveredChunks,
1969
+ delivered,
1970
+ });
1971
+ if (delivered)
1972
+ deliveryState = 'delivered';
1973
+ if (!delivered) {
1974
+ // The cached agent already contains the generated assistant turn. Drop
1975
+ // it and skip persistence so the next request cannot build on a reply
1976
+ // the user never received.
1977
+ evictChannelAgent(sessionKey, true);
1978
+ shouldPersistChannelSession = false;
1979
+ logger.warn('Channel response was not delivered; evicting transient agent state', {
1980
+ channelType: channel.type,
1981
+ sessionHash: hashForLog(sessionKey),
1982
+ messageHash: hashForLog(message.id),
1983
+ });
1984
+ }
1985
+ releaseTranscriptSnapshotHold?.();
1986
+ releaseTranscriptSnapshotHold = undefined;
1987
+ turn.phase('settlement');
1988
+ if (continuesVoiceConversation && deliveredAssistantContent) {
1989
+ const assistantClaim = await conversationBridge.claimChannelTurnDurably({
1990
+ role: 'assistant',
1991
+ content: deliveredAssistantContent,
1992
+ channel: channel.type,
1993
+ channelId: message.channel.id,
1994
+ ...(message.threadId ? { threadId: message.threadId } : {}),
1995
+ externalId: `${message.id}:assistant`,
1996
+ });
1997
+ turn.throwIfAborted();
1998
+ if (assistantClaim === 'failed') {
1999
+ logger.warn('Delivered channel turn could not be committed to shared continuity', {
2000
+ channelType: channel.type,
2001
+ sessionHash: hashForLog(sessionKey),
2002
+ messageHash: hashForLog(message.id),
2003
+ });
2004
+ }
2005
+ }
2006
+ if (cognitiveTurn) {
2007
+ // Remove ownership before awaiting: a post-delivery network failure is
2008
+ // a commit-uncertain state and must never fall through to release.
2009
+ const turnToSettle = cognitiveTurn;
2010
+ cognitiveTurn = null;
2011
+ try {
2012
+ if (delivered) {
2013
+ await turnToSettle.complete(deliveredAssistantContent);
2014
+ }
2015
+ else if (deliveredAssistantContent) {
2016
+ await turnToSettle.complete(deliveredAssistantContent, { cancelAfter: true });
2017
+ }
2018
+ else {
2019
+ await turnToSettle.fail();
2020
+ }
2021
+ turn.throwIfAborted();
2022
+ }
2023
+ catch (error) {
2024
+ logger.warn('Channel cognitive settlement uncertain', {
2025
+ channelType: channel.type,
2026
+ sessionHash: hashForLog(sessionKey),
2027
+ error: error instanceof Error ? error.message : String(error),
2028
+ });
2029
+ }
2030
+ }
2031
+ // 7. If the user SPOKE (voice note), answer by voice too — mirror the
2032
+ // modality. Best-effort: the text reply already landed, so a TTS/upload
2033
+ // failure (or a channel without voice support) is a no-op, never fatal.
2034
+ const userSpoke = message.attachments?.some((a) => a.type === 'voice' || a.type === 'audio');
2035
+ const voiceChannel = channel;
2036
+ if (delivered &&
2037
+ userSpoke &&
2038
+ response.trim() &&
2039
+ typeof voiceChannel.sendVoiceReply === 'function') {
2040
+ try {
2041
+ await voiceChannel.sendVoiceReply(message.channel.id, response);
2042
+ }
2043
+ catch (voiceErr) {
2044
+ logger.warn(`Voice reply skipped: ${voiceErr instanceof Error ? voiceErr.message : String(voiceErr)}`);
2045
+ }
2046
+ }
2047
+ // 7b. Deliver image artifacts: if the reply names image paths that exist
2048
+ // on disk (e.g. a chart the agent just generated), send them as photos.
2049
+ const imageChannel = channel;
2050
+ if (delivered && typeof imageChannel.sendImageFile === 'function') {
2051
+ const os = await import('node:os');
2052
+ const fsp = await import('node:fs/promises');
2053
+ const matches = response.match(/(?:~\/|\/)[\w./-]+\.(?:png|jpe?g|gif|webp)/gi) || [];
2054
+ const seen = new Set();
2055
+ for (const raw of matches) {
2056
+ const p = raw.startsWith('~/') ? os.homedir() + raw.slice(1) : raw;
2057
+ if (seen.has(p) || seen.size >= 4)
2058
+ continue;
2059
+ seen.add(p);
2060
+ try {
2061
+ await fsp.access(p);
2062
+ await imageChannel.sendImageFile(message.channel.id, p);
2063
+ }
2064
+ catch {
2065
+ // path isn't a real/accessible image — skip
2066
+ }
2067
+ }
2068
+ }
2069
+ // 8. Persist the conversation so it survives a daemon restart / cache eviction.
2070
+ turn.throwIfAborted();
2071
+ turn.phase('persistence');
2072
+ if (useCompanionProfile && response.trim()) {
2073
+ rememberCompanionChannelTurn(sessionKey, message.content, response);
2074
+ }
2075
+ if (shouldPersistChannelSession && agent)
2076
+ await persistChannelSession(agent, sessionKey);
2077
+ turn.throwIfAborted();
2078
+ }, {
2079
+ ...(() => {
2080
+ const typing = channelTypingLifecycle(channel, message.channel.id);
2081
+ const wait = channelWaitNoticeLifecycle(channel, message.channel.id, message.id);
2082
+ return {
2083
+ onStart: () => {
2084
+ typing.onStart();
2085
+ wait.onStart();
2086
+ },
2087
+ onSettled: () => {
2088
+ wait.onSettled();
2089
+ typing.onSettled();
2090
+ },
2091
+ };
2092
+ })(),
2093
+ onTimeout: async () => {
2094
+ await cognitiveTurn?.fail().catch(() => undefined);
2095
+ cognitiveTurn = null;
2096
+ releaseTranscriptSnapshotHold?.();
2097
+ releaseTranscriptSnapshotHold = undefined;
2098
+ if (generativeTurnEngaged && generativeSessionKey) {
2099
+ evictChannelAgent(generativeSessionKey, true);
2100
+ }
2101
+ if (deliveryState === 'not_started') {
2102
+ deliveryState = 'started';
2103
+ const result = await channel.send({
2104
+ channelId: message.channel.id,
2105
+ content: speakChannelProviderFailure(Object.assign(new Error('channel turn timed out after timeout during generation'), {
2106
+ name: 'ChannelTurnTimeoutError',
2107
+ }), { copine: Boolean(process.env.CODEBUDDY_COMPANION_PERSONA) }),
2108
+ replyTo: message.id,
2109
+ });
2110
+ if (result?.success)
2111
+ deliveryState = 'delivered';
2112
+ }
2113
+ },
2114
+ diagnostics: {
2115
+ channelType: channel.type,
2116
+ sessionHash: hashForLog(sessionKey),
2117
+ messageHash: hashForLog(message.id),
2118
+ },
2119
+ });
585
2120
  }
586
2121
  catch (err) {
587
- logger.error('Channel AI response failed', { error: err instanceof Error ? err.message : String(err) });
2122
+ await cognitiveTurn?.fail().catch(() => undefined);
2123
+ cognitiveTurn = null;
2124
+ releaseTranscriptSnapshotHold?.();
2125
+ releaseTranscriptSnapshotHold = undefined;
2126
+ if (generativeTurnEngaged && generativeSessionKey) {
2127
+ evictChannelAgent(generativeSessionKey, true);
2128
+ }
2129
+ const timedOut = err instanceof ChannelTurnTimeoutError;
2130
+ logger.error('Channel AI response failed', {
2131
+ error: err instanceof Error ? err.message : String(err),
2132
+ errorType: err instanceof Error ? err.name : 'unknown',
2133
+ deliveryState,
2134
+ });
2135
+ if (timedOut && deliveryState !== 'not_started') {
2136
+ // Delivery is either confirmed or transport-uncertain. Retrying here
2137
+ // could duplicate a late Telegram send, so only release the FIFO.
2138
+ return;
2139
+ }
2140
+ try {
2141
+ const { conversationFailureReply } = await import('../../conversation/conversation-orchestrator.js');
2142
+ const raw = err instanceof Error ? err.message : String(err);
2143
+ const spoken = timedOut || /sorry, i encountered an error/i.test(raw)
2144
+ ? speakChannelProviderFailure(err, {
2145
+ copine: Boolean(process.env.CODEBUDDY_COMPANION_PERSONA),
2146
+ })
2147
+ : conversationFailureReply(message.content);
2148
+ await channel.send({
2149
+ channelId: message.channel.id,
2150
+ content: spoken,
2151
+ replyTo: message.id,
2152
+ });
2153
+ }
2154
+ catch {
2155
+ /* delivery itself is unavailable; the error is already logged */
2156
+ }
588
2157
  }
589
2158
  });
590
2159
  }
591
- export async function instantiateChannel(config) {
2160
+ export async function instantiateChannel(configEntry) {
2161
+ // Resolve the auth token BEFORE building the channel config so every branch
2162
+ // below sees the effective token. Priority: an explicit literal `token` wins
2163
+ // (full backwards compat), otherwise fall back to the encrypted secret the
2164
+ // Cowork GUI stores under `channel:<type>:token`, otherwise no token. Never
2165
+ // throws, never logs the secret. See src/channels/resolve-channel-secret.ts.
2166
+ const config = {
2167
+ ...configEntry,
2168
+ token: resolveChannelSecret(configEntry.type, configEntry),
2169
+ };
592
2170
  const opts = config.options ?? {};
593
2171
  const channelConfig = {
594
2172
  type: config.type,
@@ -599,6 +2177,13 @@ export async function instantiateChannel(config) {
599
2177
  allowedChannels: config.allowedChannels,
600
2178
  options: opts,
601
2179
  };
2180
+ const optsAllowlist = Array.isArray(opts.allowedUsers)
2181
+ ? opts.allowedUsers.filter((item) => typeof item === 'string')
2182
+ : undefined;
2183
+ const inboundAllowlist = {
2184
+ allowedUsers: config.allowedUsers ?? optsAllowlist,
2185
+ allowedChannels: config.allowedChannels,
2186
+ };
602
2187
  switch (config.type) {
603
2188
  case 'telegram': {
604
2189
  const { TelegramChannel } = await import('../../channels/telegram/index.js');
@@ -617,15 +2202,32 @@ export async function instantiateChannel(config) {
617
2202
  // TelegramChannel reads `config.token` (client.ts) — pass `token`, not
618
2203
  // `botToken`, or it throws "Telegram bot token is required" and the
619
2204
  // channel never starts from channels.json / server intake.
620
- return new TelegramChannel({ token: config.token || '', ...opts });
2205
+ // Root `allowedUsers` used to be dropped here (only `...opts` was passed).
2206
+ return new TelegramChannel({
2207
+ ...channelConfig,
2208
+ token: config.token || '',
2209
+ ...opts,
2210
+ ...inboundAllowlist,
2211
+ });
621
2212
  }
622
2213
  case 'discord': {
623
2214
  const { DiscordChannel } = await import('../../channels/discord/index.js');
624
- return new DiscordChannel({ token: config.token || '', ...opts });
2215
+ return new DiscordChannel({
2216
+ ...channelConfig,
2217
+ token: config.token || '',
2218
+ ...opts,
2219
+ ...inboundAllowlist,
2220
+ });
625
2221
  }
626
2222
  case 'slack': {
627
2223
  const { SlackChannel } = await import('../../channels/slack/index.js');
628
- return new SlackChannel({ botToken: config.token || '', ...opts });
2224
+ return new SlackChannel({
2225
+ ...channelConfig,
2226
+ token: config.token || '',
2227
+ botToken: config.token || '',
2228
+ ...opts,
2229
+ ...inboundAllowlist,
2230
+ });
629
2231
  }
630
2232
  case 'whatsapp': {
631
2233
  const { WhatsAppChannel } = await import('../../channels/whatsapp/index.js');