ltcai 11.1.0 → 11.4.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 (289) hide show
  1. package/README.md +47 -54
  2. package/docs/CHANGELOG.md +94 -0
  3. package/docs/COMMUNITY_AND_PLUGINS.md +1 -1
  4. package/docs/DEVELOPMENT.md +1 -1
  5. package/docs/FEATURE_AUDIT_v11.2.0.md +393 -0
  6. package/docs/LAYOUT_REBUILD_SPEC.md +9 -1
  7. package/docs/MULTI_AGENT_RUNTIME.md +1 -1
  8. package/docs/ONBOARDING.md +1 -1
  9. package/docs/OPERATIONS.md +6 -2
  10. package/docs/PERMISSION_MODE.md +1 -1
  11. package/docs/TRUST_MODEL.md +1 -1
  12. package/docs/WHY_LATTICE.md +1 -1
  13. package/docs/architecture.md +6 -2
  14. package/docs/kg-schema.md +2 -2
  15. package/docs/v11.3.0_PLAN.md +202 -0
  16. package/docs/v11.4.0_RUST_FOUNDATION_PLAN.md +176 -0
  17. package/lattice_brain/__init__.py +1 -1
  18. package/lattice_brain/gates.py +125 -0
  19. package/lattice_brain/graph/_kg_common/__init__.py +287 -0
  20. package/lattice_brain/graph/_kg_common/extraction.py +516 -0
  21. package/lattice_brain/graph/_kg_common/relations.py +161 -0
  22. package/lattice_brain/graph/_kg_common/text.py +479 -0
  23. package/lattice_brain/graph/discovery_index/__init__.py +35 -0
  24. package/lattice_brain/graph/discovery_index/cleanup.py +182 -0
  25. package/lattice_brain/graph/discovery_index/extract.py +137 -0
  26. package/lattice_brain/graph/discovery_index/scan.py +411 -0
  27. package/lattice_brain/graph/discovery_index/upsert.py +495 -0
  28. package/lattice_brain/graph/fusion.py +35 -4
  29. package/lattice_brain/graph/projection/__init__.py +42 -0
  30. package/lattice_brain/graph/projection/curation.py +500 -0
  31. package/lattice_brain/graph/{projection.py → projection/v2_schema.py} +81 -485
  32. package/lattice_brain/graph/retrieval/__init__.py +54 -0
  33. package/lattice_brain/graph/retrieval/context.py +197 -0
  34. package/lattice_brain/graph/retrieval/graph_view.py +319 -0
  35. package/lattice_brain/graph/retrieval/hybrid.py +488 -0
  36. package/lattice_brain/graph/retrieval/maintenance.py +121 -0
  37. package/lattice_brain/graph/retrieval/signals.py +95 -0
  38. package/lattice_brain/graph/retrieval_vector/__init__.py +42 -0
  39. package/lattice_brain/graph/retrieval_vector/fingerprint.py +97 -0
  40. package/lattice_brain/graph/retrieval_vector/indexing.py +347 -0
  41. package/lattice_brain/graph/retrieval_vector/search.py +560 -0
  42. package/lattice_brain/graph/retrieval_vector/status.py +374 -0
  43. package/lattice_brain/graph/schema.py +9 -0
  44. package/lattice_brain/graph/store.py +9 -0
  45. package/lattice_brain/graph/vector_index/selector.py +32 -2
  46. package/lattice_brain/ingestion/__init__.py +130 -0
  47. package/lattice_brain/ingestion/_contract.py +90 -0
  48. package/lattice_brain/ingestion/constants.py +127 -0
  49. package/lattice_brain/ingestion/folder_scan.py +57 -0
  50. package/lattice_brain/ingestion/folders.py +258 -0
  51. package/lattice_brain/ingestion/hashing.py +26 -0
  52. package/lattice_brain/ingestion/jobs_api.py +107 -0
  53. package/lattice_brain/ingestion/models.py +80 -0
  54. package/lattice_brain/ingestion/pipeline.py +486 -0
  55. package/lattice_brain/ingestion/quality.py +209 -0
  56. package/lattice_brain/ingestion/routing.py +295 -0
  57. package/lattice_brain/multimodal/__init__.py +164 -0
  58. package/lattice_brain/multimodal/audio.py +77 -0
  59. package/lattice_brain/multimodal/common.py +118 -0
  60. package/lattice_brain/{multimodal.py → multimodal/images.py} +22 -262
  61. package/lattice_brain/multimodal/ports.py +169 -0
  62. package/lattice_brain/multimodal/video.py +410 -0
  63. package/lattice_brain/portability/__init__.py +90 -0
  64. package/lattice_brain/portability/_contract.py +42 -0
  65. package/lattice_brain/portability/backups.py +338 -0
  66. package/lattice_brain/portability/bundles.py +136 -0
  67. package/lattice_brain/portability/constants.py +93 -0
  68. package/lattice_brain/portability/fsops.py +138 -0
  69. package/lattice_brain/portability/service.py +41 -0
  70. package/lattice_brain/portability/sharing.py +714 -0
  71. package/lattice_brain/runtime/__init__.py +1 -1
  72. package/lattice_brain/runtime/multi_agent.py +1 -1
  73. package/lattice_brain/sealed_box.py +244 -0
  74. package/lattice_brain/synthesis.py +24 -1
  75. package/latticeai/__init__.py +1 -1
  76. package/latticeai/api/brain_intelligence.py +4 -0
  77. package/latticeai/api/chat.py +11 -0
  78. package/latticeai/api/chat_helpers.py +16 -3
  79. package/latticeai/api/chat_hybrid.py +32 -1
  80. package/latticeai/api/chronicle.py +63 -0
  81. package/latticeai/api/features.py +70 -0
  82. package/latticeai/api/local_files.py +102 -0
  83. package/latticeai/api/portability.py +39 -4
  84. package/latticeai/api/review_queue.py +126 -0
  85. package/latticeai/api/search.py +16 -2
  86. package/latticeai/core/agent/__init__.py +93 -0
  87. package/latticeai/core/agent/_contract.py +79 -0
  88. package/latticeai/core/agent/context.py +57 -0
  89. package/latticeai/core/agent/deps.py +125 -0
  90. package/latticeai/core/agent/execution.py +622 -0
  91. package/latticeai/core/agent/planning.py +145 -0
  92. package/latticeai/core/agent/recovery.py +157 -0
  93. package/latticeai/core/agent/runtime.py +210 -0
  94. package/latticeai/core/agent/verification.py +231 -0
  95. package/latticeai/core/config.py +4 -1
  96. package/latticeai/core/context_builder.py +6 -3
  97. package/latticeai/core/embedding_providers/__init__.py +151 -0
  98. package/latticeai/core/embedding_providers/base.py +199 -0
  99. package/latticeai/core/embedding_providers/captions.py +162 -0
  100. package/latticeai/core/embedding_providers/profiles.py +126 -0
  101. package/latticeai/core/embedding_providers/text.py +350 -0
  102. package/latticeai/core/embedding_providers/vision.py +352 -0
  103. package/latticeai/core/file_generation/__init__.py +115 -0
  104. package/latticeai/core/file_generation/bundles.py +76 -0
  105. package/latticeai/core/file_generation/extraction.py +154 -0
  106. package/latticeai/core/file_generation/inference.py +235 -0
  107. package/latticeai/core/file_generation/orchestration.py +152 -0
  108. package/latticeai/core/file_generation/prompting.py +117 -0
  109. package/latticeai/core/file_generation/repair.py +114 -0
  110. package/latticeai/core/file_generation/sanitize.py +61 -0
  111. package/latticeai/core/file_generation/validation.py +201 -0
  112. package/latticeai/core/legacy_compatibility.py +1 -1
  113. package/latticeai/core/marketplace.py +1 -1
  114. package/latticeai/core/messages.py +152 -0
  115. package/latticeai/core/model_compat.py +73 -2
  116. package/latticeai/core/workspace_os_constants.py +1 -1
  117. package/latticeai/integrations/telegram_bot/__init__.py +123 -0
  118. package/latticeai/integrations/telegram_bot/__main__.py +17 -0
  119. package/latticeai/integrations/telegram_bot/config.py +86 -0
  120. package/latticeai/integrations/telegram_bot/dispatch.py +311 -0
  121. package/latticeai/integrations/telegram_bot/flows.py +478 -0
  122. package/latticeai/integrations/telegram_bot/helpers.py +322 -0
  123. package/latticeai/integrations/telegram_bot/screens.py +394 -0
  124. package/latticeai/models/model_providers.py +12 -4
  125. package/latticeai/models/router/__init__.py +88 -0
  126. package/latticeai/models/router/_contract.py +66 -0
  127. package/latticeai/models/router/branding.py +56 -0
  128. package/latticeai/models/router/catalog.py +69 -0
  129. package/latticeai/models/router/documents.py +199 -0
  130. package/latticeai/models/router/errors.py +37 -0
  131. package/latticeai/models/router/generation.py +258 -0
  132. package/latticeai/models/router/loading.py +291 -0
  133. package/latticeai/models/router/local_models.py +85 -0
  134. package/latticeai/models/router/registry.py +147 -0
  135. package/latticeai/runtime/build_phases/__init__.py +82 -0
  136. package/latticeai/runtime/build_phases/features.py +407 -0
  137. package/latticeai/runtime/build_phases/foundation.py +555 -0
  138. package/latticeai/runtime/build_phases/web.py +492 -0
  139. package/latticeai/runtime/chat_wiring.py +4 -0
  140. package/latticeai/runtime/feature_toggle_wiring.py +163 -0
  141. package/latticeai/runtime/router_registration.py +11 -0
  142. package/latticeai/runtime/runtime_context.py +1 -0
  143. package/latticeai/services/app_context.py +8 -0
  144. package/latticeai/services/architecture_readiness.py +48 -19
  145. package/latticeai/services/automation_intelligence.py +22 -2
  146. package/latticeai/services/brain_intelligence/__init__.py +58 -0
  147. package/latticeai/services/brain_intelligence/_contract.py +71 -0
  148. package/latticeai/services/brain_intelligence/consistency.py +193 -0
  149. package/latticeai/services/brain_intelligence/constants.py +47 -0
  150. package/latticeai/services/brain_intelligence/digest.py +258 -0
  151. package/latticeai/services/brain_intelligence/health.py +331 -0
  152. package/latticeai/services/brain_intelligence/proposals.py +264 -0
  153. package/latticeai/services/brain_intelligence/sampling.py +84 -0
  154. package/latticeai/services/brain_intelligence/service.py +48 -0
  155. package/latticeai/services/chronicle.py +557 -0
  156. package/latticeai/services/command_center.py +10 -4
  157. package/latticeai/services/feature_toggles.py +502 -0
  158. package/latticeai/services/folder_watch.py +122 -1
  159. package/latticeai/services/hybrid_chat.py +56 -5
  160. package/latticeai/services/interop_bridges.py +978 -0
  161. package/latticeai/services/memory_service/__init__.py +52 -0
  162. package/latticeai/services/memory_service/_contract.py +100 -0
  163. package/latticeai/services/memory_service/brief.py +431 -0
  164. package/latticeai/services/memory_service/constants.py +57 -0
  165. package/latticeai/services/memory_service/maintenance.py +138 -0
  166. package/latticeai/services/memory_service/manager.py +186 -0
  167. package/latticeai/services/memory_service/proof.py +136 -0
  168. package/latticeai/services/memory_service/recall.py +225 -0
  169. package/latticeai/services/memory_service/service.py +48 -0
  170. package/latticeai/services/memory_service/stores.py +110 -0
  171. package/latticeai/services/model_capability_registry.py +434 -261
  172. package/latticeai/services/model_catalog.py +95 -61
  173. package/latticeai/services/model_recommendation.py +18 -11
  174. package/latticeai/services/model_runtime/__init__.py +322 -0
  175. package/latticeai/services/model_runtime/cloud.py +87 -0
  176. package/latticeai/services/model_runtime/download.py +282 -0
  177. package/latticeai/services/model_runtime/engines.py +341 -0
  178. package/latticeai/services/model_runtime/loading.py +178 -0
  179. package/latticeai/services/model_runtime/service.py +129 -0
  180. package/latticeai/services/model_runtime/state.py +131 -0
  181. package/latticeai/services/model_runtime/status.py +255 -0
  182. package/latticeai/services/multimodal_ports.py +26 -1
  183. package/latticeai/services/obsidian_bridge.py +16 -25
  184. package/latticeai/services/product_readiness.py +15 -7
  185. package/latticeai/services/search_service.py +149 -2
  186. package/latticeai/services/tool_dispatch.py +4 -0
  187. package/latticeai/setup/auto_setup.py +27 -30
  188. package/latticeai/setup/wizard/__init__.py +126 -0
  189. package/latticeai/setup/wizard/catalog.py +172 -0
  190. package/latticeai/setup/wizard/detect.py +323 -0
  191. package/latticeai/setup/wizard/install.py +348 -0
  192. package/latticeai/setup/wizard/paths.py +168 -0
  193. package/latticeai/setup/wizard/plans.py +74 -0
  194. package/latticeai/setup/wizard/recommend.py +320 -0
  195. package/package.json +6 -2
  196. package/scripts/bump_version.py +14 -0
  197. package/scripts/capture_release_evidence.mjs +33 -21
  198. package/scripts/check_current_release_docs.mjs +1 -1
  199. package/scripts/check_i18n_namespace_coverage.mjs +41 -4
  200. package/scripts/check_max_file_lines.mjs +102 -0
  201. package/scripts/check_release_evidence_bound.mjs +30 -15
  202. package/scripts/check_screenshot_pixel_delta.py +34 -4
  203. package/scripts/check_server_i18n.mjs +2 -0
  204. package/scripts/generate_rust_parity_fixtures.py +562 -0
  205. package/scripts/lib/mock_server_fingerprint.mjs +94 -0
  206. package/scripts/release_screen_claims.json +44 -2
  207. package/scripts/verify_hf_model_registry.py +253 -218
  208. package/src-tauri/Cargo.lock +361 -3
  209. package/src-tauri/Cargo.toml +6 -1
  210. package/src-tauri/src/backend.rs +349 -0
  211. package/src-tauri/src/folder.rs +33 -0
  212. package/src-tauri/src/main.rs +97 -399
  213. package/src-tauri/tauri.conf.json +1 -1
  214. package/static/app/asset-manifest.json +41 -37
  215. package/static/app/assets/Act-yYpYnn0v.js +1 -0
  216. package/static/app/assets/AdminConsole-DL3Cr5pL.js +1 -0
  217. package/static/app/assets/{Brain-CzCsI1mi.js → Brain-C1HBN0Wf.js} +2 -2
  218. package/static/app/assets/BrainHome-DoXRhUUC.js +2 -0
  219. package/static/app/assets/BrainSignals-6yR6ir5t.js +1 -0
  220. package/static/app/assets/Capture-CFIRsFNE.js +1 -0
  221. package/static/app/assets/Chronicle-BZbEgiwN.js +1 -0
  222. package/static/app/assets/CommandPalette-D2pMxC2I.js +1 -0
  223. package/static/app/assets/Library-DwO3yZST.js +1 -0
  224. package/static/app/assets/{LivingBrain-BXMWIK_2.js → LivingBrain-Jn1GK0-S.js} +1 -1
  225. package/static/app/assets/ProductFlow-B-w1R4Oo.js +1 -0
  226. package/static/app/assets/ReviewCard-6B27X8Vg.js +3 -0
  227. package/static/app/assets/System-DW8F-2xL.js +1 -0
  228. package/static/app/assets/arrow-left-DXvKg9U6.js +1 -0
  229. package/static/app/assets/{bot-4BvN07ux.js → bot-IM_E_Y12.js} +1 -1
  230. package/static/app/assets/brain-Ci1CkWjM.js +1 -0
  231. package/static/app/assets/{button-CDjtnAoU.js → button-COwyqfHM.js} +1 -1
  232. package/static/app/assets/circle-check-DfInj-qD.js +1 -0
  233. package/static/app/assets/{circle-pause-D_RMn7tp.js → circle-pause-DEM4A1Y5.js} +1 -1
  234. package/static/app/assets/{circle-play-B5OpB8ae.js → circle-play-C9djDuLd.js} +1 -1
  235. package/static/app/assets/{cpu-BIlWInHf.js → cpu-DFdo1gw-.js} +1 -1
  236. package/static/app/assets/{download-BtjXfL3z.js → download-SnJL6oqk.js} +1 -1
  237. package/static/app/assets/{folder-open-DefMpxI2.js → folder-open-CqZeDkjE.js} +1 -1
  238. package/static/app/assets/{hard-drive-BQ8NZVkw.js → hard-drive-j1jJXYYf.js} +1 -1
  239. package/static/app/assets/{index-vtEfYvQY.css → index-BLPb5lmE.css} +1 -1
  240. package/static/app/assets/index-_u5iUHDr.js +10 -0
  241. package/static/app/assets/input-B0lPdRQZ.js +1 -0
  242. package/static/app/assets/link-2-CoFbooHS.js +1 -0
  243. package/static/app/assets/{permissionCopy-BqZ5tsgL.js → permissionCopy-BsyLxtao.js} +1 -1
  244. package/static/app/assets/primitives-DEbN-d6p.js +1 -0
  245. package/static/app/assets/search-BybIWPNd.js +1 -0
  246. package/static/app/assets/{share-2-D5zg_0fY.js → share-2-CVtZ_ewX.js} +1 -1
  247. package/static/app/assets/{shield-alert-B5pZzkUb.js → shield-alert-CBi2GNWM.js} +1 -1
  248. package/static/app/assets/{textarea-nEVIweKY.js → textarea-DNMpB5ih.js} +1 -1
  249. package/static/app/assets/{useFocusTrap-Cm99AHlz.js → useFocusTrap-C83t3GXF.js} +1 -1
  250. package/static/app/assets/useMutation-DtbJDoyz.js +1 -0
  251. package/static/app/assets/{useQuery-Dm__N6bL.js → useQuery-Dcp1OChy.js} +1 -1
  252. package/static/app/assets/utils-BlZr7Pd4.js +4 -0
  253. package/static/app/assets/workspace-jJY4RuAV.js +1 -0
  254. package/static/app/index.html +4 -4
  255. package/static/sw.js +1 -1
  256. package/lattice_brain/graph/_kg_common.py +0 -1331
  257. package/lattice_brain/graph/discovery_index.py +0 -1141
  258. package/lattice_brain/graph/retrieval.py +0 -1120
  259. package/lattice_brain/graph/retrieval_vector.py +0 -1293
  260. package/lattice_brain/ingestion.py +0 -1377
  261. package/lattice_brain/portability.py +0 -1210
  262. package/latticeai/core/agent.py +0 -1412
  263. package/latticeai/core/embedding_providers.py +0 -1196
  264. package/latticeai/core/file_generation.py +0 -1047
  265. package/latticeai/integrations/telegram_bot.py +0 -1390
  266. package/latticeai/models/router.py +0 -1007
  267. package/latticeai/runtime/build_phases.py +0 -1422
  268. package/latticeai/services/brain_intelligence.py +0 -967
  269. package/latticeai/services/memory_service.py +0 -1177
  270. package/latticeai/services/model_runtime.py +0 -1281
  271. package/latticeai/setup/wizard.py +0 -1277
  272. package/static/app/assets/Act-D0HWqtn0.js +0 -1
  273. package/static/app/assets/AdminConsole-D-QDW-A4.js +0 -1
  274. package/static/app/assets/BrainHome-Btns-_TA.js +0 -2
  275. package/static/app/assets/BrainSignals-2dHQNkns.js +0 -1
  276. package/static/app/assets/Capture-CT8v1StE.js +0 -1
  277. package/static/app/assets/CommandPalette-DoLXC2KH.js +0 -1
  278. package/static/app/assets/Library-DDoxFE5c.js +0 -1
  279. package/static/app/assets/ProductFlow-DOYf7JIs.js +0 -1
  280. package/static/app/assets/ReviewCard-COQsqidK.js +0 -3
  281. package/static/app/assets/System-BRllvYXd.js +0 -1
  282. package/static/app/assets/arrow-left-DnyMzss-.js +0 -1
  283. package/static/app/assets/brain-uMb_5hnO.js +0 -1
  284. package/static/app/assets/index-0AvoEBzJ.js +0 -10
  285. package/static/app/assets/input-B_5ZJ9oy.js +0 -1
  286. package/static/app/assets/primitives-CVwew78r.js +0 -1
  287. package/static/app/assets/search-DkhnOKZt.js +0 -1
  288. package/static/app/assets/utils-DcDMoZIe.js +0 -4
  289. package/static/app/assets/workspace-LtRRSKTf.js +0 -1
@@ -10,7 +10,7 @@ from __future__ import annotations
10
10
 
11
11
  from typing import Dict
12
12
 
13
- WORKSPACE_OS_VERSION = "11.1.0"
13
+ WORKSPACE_OS_VERSION = "11.4.0"
14
14
 
15
15
  # Workspace types separate single-user Personal workspaces from shared
16
16
  # Organization workspaces. Both keep the same local-first JSON store; the type
@@ -0,0 +1,123 @@
1
+ """Telegram bridge — the phone-side surface of a local Lattice AI.
2
+
3
+ The bot mirrors the web app's capabilities onto a chat: server status, models,
4
+ Knowledge Graph counts, screenshots, history, document capture, the Review
5
+ Center, and the full human-in-the-loop agent handshake. It is fail-closed by
6
+ construction — no bot token, no chat allowlist, or no explicitly provisioned
7
+ server capability and the loop refuses to start.
8
+
9
+ Split into cohesive submodules in v11.3.0 (no behaviour change): ``config``
10
+ (environment, endpoints, logger and the authenticated server client),
11
+ ``helpers`` (chat-id registry, Telegram API, network, agent artifacts),
12
+ ``screens`` (the menu commands that report on the running system), ``flows``
13
+ (ask → render → approve, including the pending-plan state), and ``dispatch``
14
+ (command/callback routing and the poll loop). ``__main__`` keeps
15
+ ``python -m latticeai.integrations.telegram_bot`` working. This module
16
+ re-exports every name the single file exposed, so
17
+ ``latticeai.integrations.telegram_bot.X`` keeps working.
18
+
19
+ Stubbing note: rebinding one of these *here* changes only this module's name.
20
+ The submodule that calls it holds its own reference, so a test standing in for
21
+ ``CHAT_IDS_FILE``/``TOKEN``/``AGENT_WORKSPACE`` patches
22
+ ``…telegram_bot.helpers``, for ``_server_client``/``_bot_pending_plans``
23
+ ``…telegram_bot.flows`` (or ``…screens`` for a screen), and for ``get_updates``
24
+ ``…telegram_bot.dispatch``.
25
+ """
26
+
27
+ # The single file had no ``__all__``, so its public surface was "every module
28
+ # global" — including the names it imported for its own use. Every re-export
29
+ # below therefore uses the redundant-alias form: it reproduces exactly that
30
+ # surface, and it marks each name as deliberate rather than a leftover import.
31
+ from latticeai.cli.runtime import _load_env_file as _load_env_file
32
+ from latticeai.core.io_utils import atomic_write_json as atomic_write_json
33
+ from latticeai.core.logging_safety import (
34
+ install_sensitive_log_filter as install_sensitive_log_filter,
35
+ )
36
+ from latticeai.core.logging_safety import safe_log_text as safe_log_text
37
+ from latticeai.core.quiet import quiet as quiet
38
+
39
+ from .config import AGENT_RESUME_URL as AGENT_RESUME_URL
40
+ from .config import AGENT_URL as AGENT_URL
41
+ from .config import AGENT_WORKSPACE as AGENT_WORKSPACE
42
+ from .config import API_URL as API_URL
43
+ from .config import BASE_URL as BASE_URL
44
+ from .config import CHAT_IDS_FILE as CHAT_IDS_FILE
45
+ from .config import CHAT_URL as CHAT_URL
46
+ from .config import DATA_DIR as DATA_DIR
47
+ from .config import GRAPH_STATS_URL as GRAPH_STATS_URL
48
+ from .config import HISTORY_URL as HISTORY_URL
49
+ from .config import INVITE_CODE as INVITE_CODE
50
+ from .config import MAX_TELEGRAM_FILE_BYTES as MAX_TELEGRAM_FILE_BYTES
51
+ from .config import MCP_TOOLS_URL as MCP_TOOLS_URL
52
+ from .config import MODELS_URL as MODELS_URL
53
+ from .config import PROPOSALS_URL as PROPOSALS_URL
54
+ from .config import PUBLIC_WEB_URL as PUBLIC_WEB_URL
55
+ from .config import SERVER_PORT as SERVER_PORT
56
+ from .config import STATUS_URL as STATUS_URL
57
+ from .config import TOKEN as TOKEN
58
+ from .config import UPLOAD_DOC_URL as UPLOAD_DOC_URL
59
+ from .config import _get_server_session as _get_server_session
60
+ from .config import _server_client as _server_client
61
+ from .config import env_value as env_value
62
+ from .config import load_env_file as load_env_file
63
+ from .config import logger as logger
64
+ from .dispatch import HELP_TEXT as HELP_TEXT
65
+ from .dispatch import _log_task_exception as _log_task_exception
66
+ from .dispatch import handle_callback_query as handle_callback_query
67
+ from .dispatch import handle_command as handle_command
68
+ from .dispatch import run_bot as run_bot
69
+ from .flows import _approval_pause_id as _approval_pause_id
70
+ from .flows import _bot_pending_plans as _bot_pending_plans
71
+ from .flows import _is_approval_pause as _is_approval_pause
72
+ from .flows import _resume_payload as _resume_payload
73
+ from .flows import ask_ai as ask_ai
74
+ from .flows import format_artifact_card as format_artifact_card
75
+ from .flows import format_grounding_badge as format_grounding_badge
76
+ from .flows import format_proposals as format_proposals
77
+ from .flows import format_run_explanation as format_run_explanation
78
+ from .flows import handle_plan_callback as handle_plan_callback
79
+ from .flows import handle_proposal_callback as handle_proposal_callback
80
+ from .flows import process_ai_request as process_ai_request
81
+ from .flows import send_artifact_card as send_artifact_card
82
+ from .flows import send_grounding_badge as send_grounding_badge
83
+ from .flows import send_plan_for_approval as send_plan_for_approval
84
+ from .flows import send_run_explanation as send_run_explanation
85
+ from .flows import show_review_center as show_review_center
86
+ from .helpers import allowed_chat_ids as allowed_chat_ids
87
+ from .helpers import answer_callback as answer_callback
88
+ from .helpers import broadcast_web_chat as broadcast_web_chat
89
+ from .helpers import collect_generated_files as collect_generated_files
90
+ from .helpers import collect_preview_urls as collect_preview_urls
91
+ from .helpers import download_as_base64 as download_as_base64
92
+ from .helpers import download_telegram_file as download_telegram_file
93
+ from .helpers import edit_message as edit_message
94
+ from .helpers import get_graph_url as get_graph_url
95
+ from .helpers import get_lan_ip as get_lan_ip
96
+ from .helpers import get_updates as get_updates
97
+ from .helpers import get_web_url as get_web_url
98
+ from .helpers import is_chat_allowed as is_chat_allowed
99
+ from .helpers import load_chat_ids as load_chat_ids
100
+ from .helpers import parse_allowed_chat_ids as parse_allowed_chat_ids
101
+ from .helpers import register_chat_id as register_chat_id
102
+ from .helpers import resolve_workspace_file as resolve_workspace_file
103
+ from .helpers import save_chat_ids as save_chat_ids
104
+ from .helpers import send_chat_action as send_chat_action
105
+ from .helpers import send_document as send_document
106
+ from .helpers import send_generated_files as send_generated_files
107
+ from .helpers import send_message as send_message
108
+ from .helpers import send_photo as send_photo
109
+ from .helpers import send_preview_links as send_preview_links
110
+ from .screens import MAIN_MENU as MAIN_MENU
111
+ from .screens import _mac_ram_used_gb as _mac_ram_used_gb
112
+ from .screens import _unload_all_report as _unload_all_report
113
+ from .screens import clear_server_history as clear_server_history
114
+ from .screens import do_unload_model as do_unload_model
115
+ from .screens import process_document_file as process_document_file
116
+ from .screens import send_mcp_tools as send_mcp_tools
117
+ from .screens import send_web_link as send_web_link
118
+ from .screens import show_graph_stats as show_graph_stats
119
+ from .screens import show_history_summary as show_history_summary
120
+ from .screens import show_menu as show_menu
121
+ from .screens import show_model_info as show_model_info
122
+ from .screens import show_status as show_status
123
+ from .screens import take_screenshot as take_screenshot
@@ -0,0 +1,17 @@
1
+ """Script entry: ``python -m latticeai.integrations.telegram_bot``.
2
+
3
+ The single file carried this block under ``if __name__ == "__main__"``. A
4
+ package cannot: ``__init__`` is never ``__main__``. Moving it here verbatim is
5
+ what keeps the ``-m`` invocation working after the v11.3.0 split.
6
+ """
7
+
8
+ import asyncio
9
+
10
+ from latticeai.core.quiet import quiet
11
+ from latticeai.integrations.telegram_bot import run_bot
12
+
13
+ if __name__ == "__main__":
14
+ try:
15
+ asyncio.run(run_bot())
16
+ except KeyboardInterrupt:
17
+ quiet()
@@ -0,0 +1,86 @@
1
+ """Environment, endpoints, logger, and the bot's server capability.
2
+
3
+ Every value the bridge reads from the environment is resolved here, once, at
4
+ import — the module *is* the bot's configuration surface. Importing it has the
5
+ same side effects the single file had at its own import: the sensitive-log
6
+ filter is installed, ``.env`` is loaded, and the data directory is provisioned.
7
+
8
+ Security boundary (unchanged since 11.0.1): :func:`_server_client` is the only
9
+ authenticated client. It carries the explicitly provisioned bot-to-server
10
+ bearer capability and is used for Lattice-server calls alone — never for
11
+ api.telegram.org, which always gets the plain ``httpx.AsyncClient`` the poll
12
+ loop owns.
13
+
14
+ Stubbing note: a constant is read through the globals of the module that *uses*
15
+ it, so a test standing in for ``TOKEN``/``CHAT_IDS_FILE``/``AGENT_WORKSPACE``
16
+ patches ``helpers``/``screens``/``flows``/``dispatch``, not this module.
17
+ """
18
+
19
+ import logging
20
+ import os
21
+ from pathlib import Path
22
+
23
+ import httpx
24
+
25
+ from latticeai.cli.runtime import _load_env_file
26
+ from latticeai.core.logging_safety import install_sensitive_log_filter
27
+
28
+ install_sensitive_log_filter()
29
+
30
+ def load_env_file(path=".env"):
31
+ # Single source of truth: shared with ltcai_cli via latticeai.cli.runtime.
32
+ _load_env_file(Path(path))
33
+
34
+ load_env_file()
35
+
36
+ def env_value(primary: str, default: str = "") -> str:
37
+ return os.getenv(primary) or default
38
+
39
+ TOKEN = env_value("LATTICEAI_TELEGRAM_BOT_TOKEN")
40
+ API_URL = f"https://api.telegram.org/bot{TOKEN}"
41
+ SERVER_PORT = int(env_value("LATTICEAI_SERVER_PORT", "4825"))
42
+ BASE_URL = env_value("LATTICEAI_BASE_URL", env_value("LATTICEAI_SERVER_URL", f"http://127.0.0.1:{SERVER_PORT}")).rstrip("/")
43
+ CHAT_URL = f"{BASE_URL}/chat"
44
+ AGENT_URL = f"{BASE_URL}/agent"
45
+ MCP_TOOLS_URL = f"{BASE_URL}/mcp/tools"
46
+ HISTORY_URL = f"{BASE_URL}/history"
47
+ STATUS_URL = f"{BASE_URL}/status"
48
+ MODELS_URL = f"{BASE_URL}/models"
49
+ GRAPH_STATS_URL = f"{BASE_URL}/knowledge-graph/stats"
50
+ UPLOAD_DOC_URL = f"{BASE_URL}/upload/document"
51
+ PROPOSALS_URL = f"{BASE_URL}/api/proposals"
52
+
53
+ AGENT_RESUME_URL = f"{BASE_URL}/agent/resume"
54
+ AGENT_WORKSPACE = Path(env_value("LATTICEAI_AGENT_ROOT", "agent_workspace")).resolve()
55
+
56
+ MAX_TELEGRAM_FILE_BYTES = 45 * 1024 * 1024
57
+ INVITE_CODE = env_value("LATTICEAI_INVITE_CODE")
58
+ PUBLIC_WEB_URL = env_value("LATTICEAI_PUBLIC_URL")
59
+ DATA_DIR = Path(env_value("LATTICEAI_DATA_DIR", str(Path.home() / ".ltcai")))
60
+ DATA_DIR.mkdir(parents=True, exist_ok=True)
61
+ CHAT_IDS_FILE = Path(env_value("LATTICEAI_TELEGRAM_CHATS_FILE", str(DATA_DIR / "telegram_chats.json")))
62
+
63
+ logging.basicConfig(level=logging.INFO)
64
+ logger = logging.getLogger(__name__)
65
+
66
+ # ── Server session auth ───────────────────────────────────────────────────────
67
+
68
+ def _get_server_session() -> str:
69
+ """Return only the explicitly provisioned bot-to-server token.
70
+
71
+ Web sessions are hashed at rest and belong to interactive users. Scanning
72
+ ``sessions.json`` cannot recover a usable token and would couple the bot to
73
+ whichever administrator happened to be logged in most recently.
74
+ """
75
+ return env_value("LATTICEAI_SERVER_SESSION_TOKEN").strip()
76
+
77
+ def _server_client(**kwargs) -> httpx.AsyncClient:
78
+ """Return a server client authenticated by an explicit bearer capability."""
79
+ token = _get_server_session()
80
+ if not token:
81
+ raise RuntimeError(
82
+ "LATTICEAI_SERVER_SESSION_TOKEN is required for Telegram server API calls."
83
+ )
84
+ headers = dict(kwargs.pop("headers", {}) or {})
85
+ headers["Authorization"] = f"Bearer {token}"
86
+ return httpx.AsyncClient(headers=headers, **kwargs)
@@ -0,0 +1,311 @@
1
+ """Routing and lifecycle: the poll loop and the two things it can route to.
2
+
3
+ Slash commands (:func:`handle_command`), inline-button callbacks
4
+ (:func:`handle_callback_query`), and the long-poll loop (:func:`run_bot`) that
5
+ feeds both. This is the only layer that decides *what* happens for an incoming
6
+ update; every branch delegates to a screen or a flow and holds no logic of its
7
+ own beyond the routing table.
8
+
9
+ Fail-closed startup, unchanged: no bot token, no allowlist, or no server
10
+ capability means the loop never starts. Every allowed update is dispatched onto
11
+ its own task with an exception logger attached, so one failing handler cannot
12
+ stop the poll.
13
+
14
+ Stubbing note: ``get_updates``, ``TOKEN``, ``download_as_base64``,
15
+ ``process_ai_request``, ``handle_command``, ``handle_callback_query``, and every
16
+ screen/flow handler are read as *this* module's globals, so a test standing in
17
+ for any of them patches this module.
18
+ """
19
+
20
+ import asyncio
21
+
22
+ import httpx
23
+
24
+ from latticeai.core.logging_safety import safe_log_text
25
+
26
+ from .config import TOKEN, _get_server_session, logger
27
+ from .flows import (
28
+ _is_approval_pause,
29
+ ask_ai,
30
+ handle_plan_callback,
31
+ handle_proposal_callback,
32
+ process_ai_request,
33
+ send_plan_for_approval,
34
+ show_review_center,
35
+ )
36
+ from .helpers import (
37
+ allowed_chat_ids,
38
+ answer_callback,
39
+ download_as_base64,
40
+ get_updates,
41
+ is_chat_allowed,
42
+ register_chat_id,
43
+ send_chat_action,
44
+ send_message,
45
+ )
46
+ from .screens import (
47
+ clear_server_history,
48
+ do_unload_model,
49
+ process_document_file,
50
+ send_mcp_tools,
51
+ send_web_link,
52
+ show_graph_stats,
53
+ show_history_summary,
54
+ show_menu,
55
+ show_model_info,
56
+ show_status,
57
+ take_screenshot,
58
+ )
59
+
60
+ # ── Command dispatch ──────────────────────────────────────────────────────────
61
+
62
+ HELP_TEXT = """\
63
+ 🧠 Lattice AI 원격 제어 명령어
64
+
65
+ /menu — 메인 메뉴 (인라인 키보드)
66
+ /status — 서버 상태 및 메모리
67
+ /model — 현재 모델 + 언로드 버튼
68
+ /unload — 모든 모델 언로드 (RAM 해제)
69
+ /graph — Knowledge Graph 통계
70
+ /ss 또는 /screenshot — 현재 화면 캡처
71
+ /history [n] — 최근 대화 n건 (기본 5)
72
+ /clear [n] — 기록 정리 (마지막 n건 유지)
73
+ /web — 웹 UI 링크
74
+ /mcp — MCP 도구 목록
75
+ /review — 변경 제안 검토함 (승인/거절)
76
+ /help — 이 도움말
77
+
78
+ /agent <작업> — 멀티 LLM 에이전트 (계획 확인 후 실행)
79
+ /agent <작업> --exec <모델> --review <모델> — 실행/검토 LLM 지정
80
+
81
+ 일반 텍스트 → AI에게 질문
82
+ 사진 전송 → AI 이미지 분석
83
+ 문서 전송(PDF, DOCX, XLSX, PPTX, TXT, CSV) → Knowledge Graph 수집
84
+ """
85
+
86
+ async def handle_command(client, chat_id, command: str, args: str):
87
+ cmd = command.lower().lstrip("/").split("@")[0]
88
+
89
+ if cmd == "start":
90
+ await send_message(client, chat_id, "🧠 Lattice AI 원격 제어 준비 완료!")
91
+ await show_menu(client, chat_id)
92
+ elif cmd == "menu":
93
+ await show_menu(client, chat_id)
94
+ elif cmd == "status":
95
+ await show_status(client, chat_id)
96
+ elif cmd == "model":
97
+ await show_model_info(client, chat_id)
98
+ elif cmd == "unload":
99
+ await do_unload_model(client, chat_id)
100
+ elif cmd == "graph":
101
+ await show_graph_stats(client, chat_id)
102
+ elif cmd in {"ss", "screenshot"}:
103
+ await take_screenshot(client, chat_id)
104
+ elif cmd == "history":
105
+ n = int(args.strip()) if args.strip().isdigit() else 5
106
+ await show_history_summary(client, chat_id, n)
107
+ elif cmd in {"clear", "clear_history", "forget"}:
108
+ keep = int(args.strip()) if args.strip().isdigit() else 0
109
+ await clear_server_history(client, chat_id, keep)
110
+ elif cmd == "web":
111
+ await send_web_link(client, chat_id)
112
+ elif cmd == "mcp":
113
+ await send_mcp_tools(client, chat_id)
114
+ elif cmd in {"review", "proposals"}:
115
+ await show_review_center(client, chat_id)
116
+ elif cmd in {"help", "h"}:
117
+ await send_message(client, chat_id, HELP_TEXT)
118
+ elif cmd == "agent":
119
+ if not args:
120
+ await send_message(client, chat_id, "사용법: /agent <작업 내용>\n예: /agent 쇼핑몰 메인 페이지 HTML 만들어줘\n\n특정 AI 지정:\n/agent <작업> --exec openai/gpt-4o --review together:Qwen/Qwen3-VL-32B-Instruct")
121
+ return
122
+ # Parse optional --exec / --review flags
123
+ exec_model = reviewing_model = None
124
+ task_text = args
125
+ import re as _re
126
+ em = _re.search(r'--exec\s+(\S+)', args)
127
+ rm = _re.search(r'--review\s+(\S+)', args)
128
+ if em:
129
+ exec_model = em.group(1)
130
+ task_text = task_text.replace(em.group(0), "").strip()
131
+ if rm:
132
+ reviewing_model = rm.group(1)
133
+ task_text = task_text.replace(rm.group(0), "").strip()
134
+ await send_chat_action(client, chat_id, "typing")
135
+ data = await ask_ai(client, task_text, agent_mode=True,
136
+ executing_model=exec_model, reviewing_model=reviewing_model)
137
+ if isinstance(data, dict) and _is_approval_pause(data):
138
+ await send_plan_for_approval(client, chat_id, data)
139
+ else:
140
+ ans = data.get("response", str(data)) if isinstance(data, dict) else str(data)
141
+ await send_message(client, chat_id, ans)
142
+ else:
143
+ await send_message(client, chat_id, f"알 수 없는 명령어: /{cmd}\n/help 로 명령어 목록을 확인하세요.")
144
+
145
+ # ── Callback query handler ────────────────────────────────────────────────────
146
+
147
+ async def handle_callback_query(client, callback_query):
148
+ cq_id = callback_query.get("id", "")
149
+ chat_id = (
150
+ (callback_query.get("message") or {}).get("chat") or {}
151
+ ).get("id")
152
+ data = callback_query.get("data", "")
153
+
154
+ if not is_chat_allowed(chat_id):
155
+ logger.warning("허용되지 않은 텔레그램 callback 차단: %s", safe_log_text(chat_id))
156
+ await answer_callback(client, cq_id, "허용되지 않은 채팅입니다.")
157
+ return
158
+
159
+ await answer_callback(client, cq_id)
160
+
161
+ if data == "cmd:status":
162
+ await show_status(client, chat_id)
163
+ elif data == "cmd:model":
164
+ await show_model_info(client, chat_id)
165
+ elif data == "cmd:graph":
166
+ await show_graph_stats(client, chat_id)
167
+ elif data == "cmd:screenshot":
168
+ await take_screenshot(client, chat_id)
169
+ elif data == "cmd:history":
170
+ await show_history_summary(client, chat_id, 5)
171
+ elif data == "cmd:clear":
172
+ await clear_server_history(client, chat_id, 0)
173
+ elif data == "cmd:web":
174
+ await send_web_link(client, chat_id)
175
+ elif data == "cmd:mcp":
176
+ await send_mcp_tools(client, chat_id)
177
+ elif data == "cmd:review":
178
+ await show_review_center(client, chat_id)
179
+ elif data == "cmd:menu":
180
+ await show_menu(client, chat_id)
181
+ elif data.startswith("model:unload:"):
182
+ model_id = data[len("model:unload:"):]
183
+ await do_unload_model(client, chat_id, model_id)
184
+ elif data.startswith("plan:"):
185
+ task = asyncio.create_task(handle_plan_callback(client, chat_id, data))
186
+ task.add_done_callback(_log_task_exception)
187
+ elif data.startswith("proposal:"):
188
+ task = asyncio.create_task(handle_proposal_callback(client, chat_id, data))
189
+ task.add_done_callback(_log_task_exception)
190
+
191
+ # ── Main loop ─────────────────────────────────────────────────────────────────
192
+
193
+ async def run_bot():
194
+ if not TOKEN:
195
+ logger.warning("LATTICEAI_TELEGRAM_BOT_TOKEN이 설정되지 않아 텔레그램 봇을 시작하지 않습니다.")
196
+ return
197
+ if not allowed_chat_ids():
198
+ logger.error(
199
+ "LATTICEAI_TELEGRAM_ALLOWED_CHAT_IDS가 없어 텔레그램 봇을 시작하지 않습니다."
200
+ )
201
+ return
202
+ if not _get_server_session():
203
+ logger.error(
204
+ "LATTICEAI_SERVER_SESSION_TOKEN이 없어 텔레그램 봇을 시작하지 않습니다."
205
+ )
206
+ return
207
+
208
+ logger.info("🚀 비동기 텔레그램 봇 모드 시작!")
209
+ last_update_id = None
210
+ retry_delay = 1
211
+
212
+ async with httpx.AsyncClient() as client:
213
+ while True:
214
+ try:
215
+ updates = await get_updates(client, last_update_id)
216
+ retry_delay = 1
217
+ except Exception as e:
218
+ logger.error("get_updates 실패: %s", safe_log_text(e))
219
+ await asyncio.sleep(min(retry_delay, 30))
220
+ retry_delay = min(retry_delay * 2, 30)
221
+ continue
222
+
223
+ if not (updates and updates.get("ok")):
224
+ await asyncio.sleep(0.5)
225
+ continue
226
+
227
+ for update in updates.get("result", []):
228
+ try:
229
+ last_update_id = update.get("update_id") + 1
230
+
231
+ # ── Callback query (inline button press) ──────────────────
232
+ if "callback_query" in update:
233
+ task = asyncio.create_task(handle_callback_query(client, update["callback_query"]))
234
+ task.add_done_callback(_log_task_exception)
235
+ continue
236
+
237
+ if "message" not in update:
238
+ continue
239
+
240
+ msg = update["message"]
241
+ chat_id = msg["chat"]["id"]
242
+ if not is_chat_allowed(chat_id):
243
+ logger.warning(
244
+ "허용되지 않은 텔레그램 메시지 차단: %s",
245
+ safe_log_text(chat_id),
246
+ )
247
+ continue
248
+ register_chat_id(chat_id)
249
+ text = msg.get("text", "")
250
+ caption = msg.get("caption", "")
251
+
252
+ # ── Photo → vision AI ─────────────────────────────────────
253
+ if "photo" in msg:
254
+ file_id = msg["photo"][-1]["file_id"]
255
+ await send_message(client, chat_id, "📸 사진을 받았습니다. 분석을 시작합니다...")
256
+ image_data = await download_as_base64(client, file_id)
257
+ prompt = caption or text or "이 이미지를 분석해줘."
258
+ task = asyncio.create_task(process_ai_request(client, chat_id, prompt, image_data))
259
+ task.add_done_callback(_log_task_exception)
260
+ continue
261
+
262
+ # ── Document ──────────────────────────────────────────────
263
+ if "document" in msg:
264
+ doc = msg["document"]
265
+ mime = doc.get("mime_type", "")
266
+ filename = doc.get("file_name", "file")
267
+ if mime.startswith("image/"):
268
+ image_data = await download_as_base64(client, doc["file_id"])
269
+ prompt = caption or text or "이 이미지를 분석해줘."
270
+ task = asyncio.create_task(process_ai_request(client, chat_id, prompt, image_data))
271
+ else:
272
+ await send_message(client, chat_id, f"📄 {filename} 을 Knowledge Graph에 수집합니다...")
273
+ task = asyncio.create_task(
274
+ process_document_file(client, chat_id, doc["file_id"], filename, caption)
275
+ )
276
+ task.add_done_callback(_log_task_exception)
277
+ continue
278
+
279
+ # ── Voice / audio ─────────────────────────────────────────
280
+ if "voice" in msg or "audio" in msg:
281
+ await send_message(
282
+ client, chat_id,
283
+ "🎤 음성 메시지를 받았습니다. 현재 음성 인식(Whisper)이 설정되어 있지 않습니다.\n"
284
+ "텍스트로 질문을 보내주세요."
285
+ )
286
+ continue
287
+
288
+ if not text:
289
+ continue
290
+
291
+ # ── Commands ──────────────────────────────────────────────
292
+ if text.startswith("/"):
293
+ parts = text.split(None, 1)
294
+ command = parts[0]
295
+ args = parts[1] if len(parts) > 1 else ""
296
+ task = asyncio.create_task(handle_command(client, chat_id, command, args))
297
+ task.add_done_callback(_log_task_exception)
298
+ continue
299
+
300
+ # ── Plain text → AI ───────────────────────────────────────
301
+ task = asyncio.create_task(process_ai_request(client, chat_id, text))
302
+ task.add_done_callback(_log_task_exception)
303
+
304
+ except Exception as e:
305
+ logger.error("업데이트 처리 중 예외: %s", safe_log_text(e))
306
+
307
+ await asyncio.sleep(0.5)
308
+
309
+ def _log_task_exception(task):
310
+ if not task.cancelled() and task.exception():
311
+ logger.error("백그라운드 태스크 예외: %s", safe_log_text(task.exception()))