ltcai 11.2.0 → 11.5.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 (253) hide show
  1. package/README.md +50 -53
  2. package/docs/CHANGELOG.md +87 -0
  3. package/docs/COMMUNITY_AND_PLUGINS.md +1 -1
  4. package/docs/DEVELOPMENT.md +1 -1
  5. package/docs/MULTI_AGENT_RUNTIME.md +1 -1
  6. package/docs/ONBOARDING.md +1 -1
  7. package/docs/OPERATIONS.md +6 -2
  8. package/docs/PERMISSION_MODE.md +1 -1
  9. package/docs/TRUST_MODEL.md +1 -1
  10. package/docs/WHY_LATTICE.md +1 -1
  11. package/docs/kg-schema.md +2 -2
  12. package/docs/v11.3.0_PLAN.md +202 -0
  13. package/docs/v11.4.0_RUST_FOUNDATION_PLAN.md +181 -0
  14. package/docs/v11.5.0_RUST_COMPLETE_PLAN.md +145 -0
  15. package/lattice_brain/__init__.py +1 -1
  16. package/lattice_brain/graph/_kg_common/__init__.py +287 -0
  17. package/lattice_brain/graph/_kg_common/extraction.py +516 -0
  18. package/lattice_brain/graph/_kg_common/relations.py +161 -0
  19. package/lattice_brain/graph/_kg_common/text.py +479 -0
  20. package/lattice_brain/graph/discovery_index/__init__.py +35 -0
  21. package/lattice_brain/graph/discovery_index/cleanup.py +182 -0
  22. package/lattice_brain/graph/discovery_index/extract.py +137 -0
  23. package/lattice_brain/graph/discovery_index/scan.py +411 -0
  24. package/lattice_brain/graph/discovery_index/upsert.py +495 -0
  25. package/lattice_brain/graph/projection/__init__.py +42 -0
  26. package/lattice_brain/graph/projection/curation.py +500 -0
  27. package/lattice_brain/graph/{projection.py → projection/v2_schema.py} +15 -477
  28. package/lattice_brain/graph/retrieval/__init__.py +54 -0
  29. package/lattice_brain/graph/retrieval/context.py +197 -0
  30. package/lattice_brain/graph/retrieval/graph_view.py +319 -0
  31. package/lattice_brain/graph/retrieval/hybrid.py +488 -0
  32. package/lattice_brain/graph/retrieval/maintenance.py +121 -0
  33. package/lattice_brain/graph/retrieval/signals.py +95 -0
  34. package/lattice_brain/graph/retrieval_vector/__init__.py +42 -0
  35. package/lattice_brain/graph/retrieval_vector/fingerprint.py +97 -0
  36. package/lattice_brain/graph/retrieval_vector/indexing.py +347 -0
  37. package/lattice_brain/graph/retrieval_vector/search.py +560 -0
  38. package/lattice_brain/graph/retrieval_vector/status.py +374 -0
  39. package/lattice_brain/ingestion/__init__.py +130 -0
  40. package/lattice_brain/ingestion/_contract.py +90 -0
  41. package/lattice_brain/ingestion/constants.py +127 -0
  42. package/lattice_brain/ingestion/folder_scan.py +57 -0
  43. package/lattice_brain/ingestion/folders.py +258 -0
  44. package/lattice_brain/ingestion/hashing.py +26 -0
  45. package/lattice_brain/ingestion/jobs_api.py +107 -0
  46. package/lattice_brain/ingestion/models.py +80 -0
  47. package/lattice_brain/ingestion/pipeline.py +486 -0
  48. package/lattice_brain/ingestion/quality.py +209 -0
  49. package/lattice_brain/ingestion/routing.py +295 -0
  50. package/lattice_brain/multimodal/__init__.py +164 -0
  51. package/lattice_brain/multimodal/audio.py +77 -0
  52. package/lattice_brain/multimodal/common.py +118 -0
  53. package/lattice_brain/multimodal/images.py +498 -0
  54. package/lattice_brain/multimodal/ports.py +169 -0
  55. package/lattice_brain/multimodal/video.py +410 -0
  56. package/lattice_brain/portability/__init__.py +90 -0
  57. package/lattice_brain/portability/_contract.py +42 -0
  58. package/lattice_brain/portability/backups.py +338 -0
  59. package/lattice_brain/portability/bundles.py +136 -0
  60. package/lattice_brain/portability/constants.py +93 -0
  61. package/lattice_brain/portability/fsops.py +138 -0
  62. package/lattice_brain/portability/service.py +41 -0
  63. package/lattice_brain/{portability.py → portability/sharing.py} +44 -677
  64. package/lattice_brain/runtime/__init__.py +1 -1
  65. package/lattice_brain/runtime/multi_agent.py +1 -1
  66. package/latticeai/__init__.py +1 -1
  67. package/latticeai/api/chronicle.py +63 -0
  68. package/latticeai/api/index_jobs.py +145 -0
  69. package/latticeai/core/agent/__init__.py +93 -0
  70. package/latticeai/core/agent/_contract.py +79 -0
  71. package/latticeai/core/agent/context.py +57 -0
  72. package/latticeai/core/agent/deps.py +125 -0
  73. package/latticeai/core/agent/execution.py +622 -0
  74. package/latticeai/core/agent/planning.py +145 -0
  75. package/latticeai/core/agent/recovery.py +157 -0
  76. package/latticeai/core/agent/runtime.py +210 -0
  77. package/latticeai/core/agent/verification.py +231 -0
  78. package/latticeai/core/embedding_providers/__init__.py +151 -0
  79. package/latticeai/core/embedding_providers/base.py +199 -0
  80. package/latticeai/core/embedding_providers/captions.py +162 -0
  81. package/latticeai/core/embedding_providers/profiles.py +126 -0
  82. package/latticeai/core/embedding_providers/text.py +350 -0
  83. package/latticeai/core/embedding_providers/vision.py +352 -0
  84. package/latticeai/core/file_generation/__init__.py +115 -0
  85. package/latticeai/core/file_generation/bundles.py +76 -0
  86. package/latticeai/core/file_generation/extraction.py +154 -0
  87. package/latticeai/core/file_generation/inference.py +235 -0
  88. package/latticeai/core/file_generation/orchestration.py +152 -0
  89. package/latticeai/core/file_generation/prompting.py +117 -0
  90. package/latticeai/core/file_generation/repair.py +114 -0
  91. package/latticeai/core/file_generation/sanitize.py +61 -0
  92. package/latticeai/core/file_generation/validation.py +201 -0
  93. package/latticeai/core/legacy_compatibility.py +1 -1
  94. package/latticeai/core/marketplace.py +1 -1
  95. package/latticeai/core/messages.py +14 -0
  96. package/latticeai/core/workspace_os_constants.py +1 -1
  97. package/latticeai/integrations/telegram_bot/__init__.py +123 -0
  98. package/latticeai/integrations/telegram_bot/__main__.py +17 -0
  99. package/latticeai/integrations/telegram_bot/config.py +86 -0
  100. package/latticeai/integrations/telegram_bot/dispatch.py +311 -0
  101. package/latticeai/integrations/telegram_bot/flows.py +478 -0
  102. package/latticeai/integrations/telegram_bot/helpers.py +322 -0
  103. package/latticeai/integrations/telegram_bot/screens.py +394 -0
  104. package/latticeai/models/router/__init__.py +88 -0
  105. package/latticeai/models/router/_contract.py +66 -0
  106. package/latticeai/models/router/branding.py +56 -0
  107. package/latticeai/models/router/catalog.py +69 -0
  108. package/latticeai/models/router/documents.py +199 -0
  109. package/latticeai/models/router/errors.py +37 -0
  110. package/latticeai/models/router/generation.py +258 -0
  111. package/latticeai/models/router/loading.py +291 -0
  112. package/latticeai/models/router/local_models.py +85 -0
  113. package/latticeai/models/router/registry.py +147 -0
  114. package/latticeai/runtime/build_phases/__init__.py +82 -0
  115. package/latticeai/runtime/build_phases/features.py +421 -0
  116. package/latticeai/runtime/build_phases/foundation.py +555 -0
  117. package/latticeai/runtime/build_phases/web.py +492 -0
  118. package/latticeai/runtime/runtime_context.py +1 -0
  119. package/latticeai/services/architecture_readiness.py +48 -19
  120. package/latticeai/services/brain_intelligence/__init__.py +58 -0
  121. package/latticeai/services/brain_intelligence/_contract.py +71 -0
  122. package/latticeai/services/brain_intelligence/consistency.py +193 -0
  123. package/latticeai/services/brain_intelligence/constants.py +47 -0
  124. package/latticeai/services/brain_intelligence/digest.py +258 -0
  125. package/latticeai/services/brain_intelligence/health.py +331 -0
  126. package/latticeai/services/brain_intelligence/proposals.py +264 -0
  127. package/latticeai/services/brain_intelligence/sampling.py +84 -0
  128. package/latticeai/services/brain_intelligence/service.py +48 -0
  129. package/latticeai/services/chronicle.py +557 -0
  130. package/latticeai/services/memory_service/__init__.py +52 -0
  131. package/latticeai/services/memory_service/_contract.py +100 -0
  132. package/latticeai/services/memory_service/brief.py +431 -0
  133. package/latticeai/services/memory_service/constants.py +57 -0
  134. package/latticeai/services/memory_service/maintenance.py +138 -0
  135. package/latticeai/services/memory_service/manager.py +186 -0
  136. package/latticeai/services/memory_service/proof.py +136 -0
  137. package/latticeai/services/memory_service/recall.py +225 -0
  138. package/latticeai/services/memory_service/service.py +48 -0
  139. package/latticeai/services/memory_service/stores.py +110 -0
  140. package/latticeai/services/model_runtime/__init__.py +322 -0
  141. package/latticeai/services/model_runtime/cloud.py +87 -0
  142. package/latticeai/services/model_runtime/download.py +282 -0
  143. package/latticeai/services/model_runtime/engines.py +341 -0
  144. package/latticeai/services/model_runtime/loading.py +178 -0
  145. package/latticeai/services/model_runtime/service.py +129 -0
  146. package/latticeai/services/model_runtime/state.py +131 -0
  147. package/latticeai/services/model_runtime/status.py +255 -0
  148. package/latticeai/services/product_readiness.py +15 -7
  149. package/latticeai/setup/wizard/__init__.py +126 -0
  150. package/latticeai/setup/wizard/catalog.py +172 -0
  151. package/latticeai/setup/wizard/detect.py +323 -0
  152. package/latticeai/setup/wizard/install.py +348 -0
  153. package/latticeai/setup/wizard/paths.py +168 -0
  154. package/latticeai/setup/wizard/plans.py +74 -0
  155. package/latticeai/setup/wizard/recommend.py +320 -0
  156. package/package.json +6 -2
  157. package/scripts/bump_version.py +14 -0
  158. package/scripts/capture_release_evidence.mjs +33 -21
  159. package/scripts/check_current_release_docs.mjs +1 -1
  160. package/scripts/check_i18n_namespace_coverage.mjs +41 -4
  161. package/scripts/check_max_file_lines.mjs +102 -0
  162. package/scripts/check_release_evidence_bound.mjs +30 -15
  163. package/scripts/check_screenshot_pixel_delta.py +34 -4
  164. package/scripts/check_server_i18n.mjs +2 -0
  165. package/scripts/chunking_parity_corpus.py +449 -0
  166. package/scripts/generate_agent_parity_fixtures.py +752 -0
  167. package/scripts/generate_chunking_parity_fixtures.py +259 -0
  168. package/scripts/generate_rust_parity_fixtures.py +997 -0
  169. package/scripts/lib/mock_server_fingerprint.mjs +94 -0
  170. package/scripts/release_screen_claims.json +42 -2
  171. package/src-tauri/Cargo.lock +404 -3
  172. package/src-tauri/Cargo.toml +13 -1
  173. package/src-tauri/src/backend.rs +460 -0
  174. package/src-tauri/src/folder.rs +33 -0
  175. package/src-tauri/src/main.rs +109 -399
  176. package/src-tauri/src/topology.rs +356 -0
  177. package/src-tauri/tauri.conf.json +1 -1
  178. package/static/app/asset-manifest.json +41 -37
  179. package/static/app/assets/Act-CWnxSCgN.js +1 -0
  180. package/static/app/assets/AdminConsole-BEQYU6kF.js +1 -0
  181. package/static/app/assets/{Brain-tuhI4sOC.js → Brain-DWu1BhFg.js} +2 -2
  182. package/static/app/assets/BrainHome-95Hilr9R.js +2 -0
  183. package/static/app/assets/BrainSignals-QdeqCpAF.js +1 -0
  184. package/static/app/assets/Capture-BHpCxnzb.js +1 -0
  185. package/static/app/assets/Chronicle-B4xYKoed.js +1 -0
  186. package/static/app/assets/CommandPalette-BVXnttSz.js +1 -0
  187. package/static/app/assets/Library-DgYcHome.js +1 -0
  188. package/static/app/assets/{LivingBrain-DBwhto14.js → LivingBrain-CrJLDbf7.js} +1 -1
  189. package/static/app/assets/ProductFlow-DFlScKoJ.js +1 -0
  190. package/static/app/assets/ReviewCard-Cy5f48Pj.js +3 -0
  191. package/static/app/assets/System-NF8IfhTa.js +1 -0
  192. package/static/app/assets/arrow-left-DwkSYrjR.js +1 -0
  193. package/static/app/assets/{bot-Cia42c2h.js → bot-CucuhLhm.js} +1 -1
  194. package/static/app/assets/brain-BBnSryW_.js +1 -0
  195. package/static/app/assets/{button-2j2Ijzgq.js → button-C2GUj2Ai.js} +1 -1
  196. package/static/app/assets/circle-check-CxOVPwYq.js +1 -0
  197. package/static/app/assets/{circle-pause-BEFeWpVW.js → circle-pause-CbkWzBmG.js} +1 -1
  198. package/static/app/assets/{circle-play-ujXMcHxl.js → circle-play-7lEaqHdJ.js} +1 -1
  199. package/static/app/assets/{cpu-k4awryFq.js → cpu-DAlCXlIy.js} +1 -1
  200. package/static/app/assets/{download-DFbLJ_ig.js → download-RNhuuJwh.js} +1 -1
  201. package/static/app/assets/{folder-open-7y_b6xkM.js → folder-open-CLW4odzM.js} +1 -1
  202. package/static/app/assets/{hard-drive-Bidh02Kr.js → hard-drive-NKEiDIAJ.js} +1 -1
  203. package/static/app/assets/{index-DwDl9-8Y.css → index-BLPb5lmE.css} +1 -1
  204. package/static/app/assets/index-DMurvUuR.js +10 -0
  205. package/static/app/assets/input-D2UhPC1X.js +1 -0
  206. package/static/app/assets/link-2-6amKbP_P.js +1 -0
  207. package/static/app/assets/{permissionCopy-Bpb83Hx9.js → permissionCopy-Cu9TZtdR.js} +1 -1
  208. package/static/app/assets/primitives-gPsccucr.js +1 -0
  209. package/static/app/assets/search-Cj_TKk_2.js +1 -0
  210. package/static/app/assets/{share-2-BH1M-WNi.js → share-2-Bau7KkPq.js} +1 -1
  211. package/static/app/assets/{shield-alert-BlKdBXcG.js → shield-alert-BufNYypi.js} +1 -1
  212. package/static/app/assets/{textarea-CCWbUfFB.js → textarea-BQnVWhYs.js} +1 -1
  213. package/static/app/assets/{useFocusTrap-YdHQ7pJ1.js → useFocusTrap-B3_w60si.js} +1 -1
  214. package/static/app/assets/useMutation-BHhCflT6.js +1 -0
  215. package/static/app/assets/{useQuery-CXQiwbVT.js → useQuery-rBWfI-5t.js} +1 -1
  216. package/static/app/assets/utils-V_5-wxr5.js +4 -0
  217. package/static/app/assets/workspace-K1zjYUHj.js +1 -0
  218. package/static/app/index.html +4 -4
  219. package/static/sw.js +1 -1
  220. package/lattice_brain/graph/_kg_common.py +0 -1331
  221. package/lattice_brain/graph/discovery_index.py +0 -1141
  222. package/lattice_brain/graph/retrieval.py +0 -1120
  223. package/lattice_brain/graph/retrieval_vector.py +0 -1293
  224. package/lattice_brain/ingestion.py +0 -1525
  225. package/lattice_brain/multimodal.py +0 -1258
  226. package/latticeai/core/agent.py +0 -1465
  227. package/latticeai/core/embedding_providers.py +0 -1196
  228. package/latticeai/core/file_generation.py +0 -1047
  229. package/latticeai/integrations/telegram_bot.py +0 -1390
  230. package/latticeai/models/router.py +0 -1007
  231. package/latticeai/runtime/build_phases.py +0 -1450
  232. package/latticeai/services/brain_intelligence.py +0 -1083
  233. package/latticeai/services/memory_service.py +0 -1177
  234. package/latticeai/services/model_runtime.py +0 -1281
  235. package/latticeai/setup/wizard.py +0 -1310
  236. package/static/app/assets/Act-AWf0SAKp.js +0 -1
  237. package/static/app/assets/AdminConsole-D0u8Tiyj.js +0 -1
  238. package/static/app/assets/BrainHome-Ts7G_Ila.js +0 -2
  239. package/static/app/assets/BrainSignals-jMYgQ2Ar.js +0 -1
  240. package/static/app/assets/Capture-CqOSzyPr.js +0 -1
  241. package/static/app/assets/CommandPalette-DC0Bzh-I.js +0 -1
  242. package/static/app/assets/Library-CX-bbhmK.js +0 -1
  243. package/static/app/assets/ProductFlow-BHA2cfKI.js +0 -1
  244. package/static/app/assets/ReviewCard-BUhCKRNM.js +0 -3
  245. package/static/app/assets/System-Bu2t5hn1.js +0 -1
  246. package/static/app/assets/arrow-left-Dzwa5zRb.js +0 -1
  247. package/static/app/assets/brain-DJMoqrwx.js +0 -1
  248. package/static/app/assets/index-BpYkzcVm.js +0 -10
  249. package/static/app/assets/input-DSlJJxRs.js +0 -1
  250. package/static/app/assets/primitives-BCx6TvfG.js +0 -1
  251. package/static/app/assets/search-Cgy8cCFJ.js +0 -1
  252. package/static/app/assets/utils-zqPZJxdx.js +0 -4
  253. package/static/app/assets/workspace-DXTihhfU.js +0 -1
@@ -0,0 +1,322 @@
1
+ """The bridge's primitives: who may talk to it, how it talks back, and what it
2
+ can hand over.
3
+
4
+ Four small layers that everything above depends on and that depend on nothing
5
+ above:
6
+
7
+ * **chat-id registry** — the fail-closed allowlist plus the persisted mirror
8
+ recipients (``LATTICEAI_TELEGRAM_ALLOWED_CHAT_IDS`` denies all when unset);
9
+ * **Telegram API** — the six outbound calls (message, photo, document, chat
10
+ action, callback answer, message edit) and the long-poll read;
11
+ * **network** — where this machine is reachable from a phone;
12
+ * **artifacts** — resolving agent-produced files inside the workspace root and
13
+ shipping them (or a zip of them) back to the chat.
14
+
15
+ Stubbing note: these functions read ``TOKEN``, ``CHAT_IDS_FILE``,
16
+ ``AGENT_WORKSPACE``, ``MAX_TELEGRAM_FILE_BYTES``, ``SERVER_PORT``,
17
+ ``PUBLIC_WEB_URL``, ``INVITE_CODE`` and ``atomic_write_json`` as *this* module's
18
+ globals, so a test standing in for any of them patches this module.
19
+ """
20
+
21
+ import asyncio
22
+ import base64
23
+ import json
24
+ import socket
25
+ import tempfile
26
+ import zipfile
27
+ from pathlib import Path
28
+
29
+ import httpx
30
+
31
+ from latticeai.core.io_utils import atomic_write_json
32
+ from latticeai.core.logging_safety import safe_log_text
33
+ from latticeai.core.quiet import quiet
34
+
35
+ from .config import (
36
+ AGENT_WORKSPACE,
37
+ API_URL,
38
+ CHAT_IDS_FILE,
39
+ INVITE_CODE,
40
+ MAX_TELEGRAM_FILE_BYTES,
41
+ PUBLIC_WEB_URL,
42
+ SERVER_PORT,
43
+ TOKEN,
44
+ env_value,
45
+ logger,
46
+ )
47
+
48
+ # ── Chat ID registry ─────────────────────────────────────────────────────────
49
+
50
+ def parse_allowed_chat_ids(raw: str) -> frozenset[int]:
51
+ """Parse a comma-separated Telegram chat-id allowlist."""
52
+ allowed: set[int] = set()
53
+ for value in str(raw or "").split(","):
54
+ value = value.strip()
55
+ if not value:
56
+ continue
57
+ try:
58
+ allowed.add(int(value))
59
+ except ValueError:
60
+ logger.warning(
61
+ "Invalid Telegram chat id ignored in allowlist: %r",
62
+ safe_log_text(value),
63
+ )
64
+ return frozenset(allowed)
65
+
66
+
67
+ def allowed_chat_ids() -> frozenset[int]:
68
+ """Return the configured allowlist; missing configuration denies all."""
69
+ return parse_allowed_chat_ids(env_value("LATTICEAI_TELEGRAM_ALLOWED_CHAT_IDS"))
70
+
71
+
72
+ def is_chat_allowed(chat_id) -> bool:
73
+ try:
74
+ return int(chat_id) in allowed_chat_ids()
75
+ except (TypeError, ValueError):
76
+ return False
77
+
78
+
79
+ def load_chat_ids():
80
+ try:
81
+ if CHAT_IDS_FILE.exists():
82
+ data = json.loads(CHAT_IDS_FILE.read_text(encoding="utf-8"))
83
+ return {int(cid) for cid in data.get("chat_ids", [])}
84
+ except Exception as e:
85
+ logger.error("텔레그램 채팅 목록 로드 실패: %s", safe_log_text(e))
86
+ return set()
87
+
88
+ def save_chat_ids(chat_ids):
89
+ try:
90
+ atomic_write_json(CHAT_IDS_FILE, {"chat_ids": sorted(chat_ids)})
91
+ except Exception as e:
92
+ logger.error("텔레그램 채팅 목록 저장 실패: %s", safe_log_text(e))
93
+
94
+ def register_chat_id(chat_id):
95
+ if not is_chat_allowed(chat_id):
96
+ logger.warning(
97
+ "허용되지 않은 텔레그램 채팅 등록 차단: %s",
98
+ safe_log_text(chat_id),
99
+ )
100
+ return False
101
+ chat_id = int(chat_id)
102
+ chat_ids = load_chat_ids()
103
+ if chat_id not in chat_ids:
104
+ chat_ids.add(chat_id)
105
+ save_chat_ids(chat_ids)
106
+ logger.info("텔레그램 웹 미러링 대상 등록: %s", chat_id)
107
+ return True
108
+
109
+ # ── Telegram API helpers ──────────────────────────────────────────────────────
110
+
111
+ async def send_message(client, chat_id, text, reply_markup=None):
112
+ url = f"{API_URL}/sendMessage"
113
+ try:
114
+ chunks = [text[i:i+3900] for i in range(0, len(text), 3900)] or [""]
115
+ for i, chunk in enumerate(chunks):
116
+ payload = {"chat_id": chat_id, "text": chunk}
117
+ if reply_markup and i == len(chunks) - 1:
118
+ payload["reply_markup"] = reply_markup
119
+ await client.post(url, json=payload)
120
+ except Exception as e:
121
+ logger.error("메시지 전송 실패: %s", safe_log_text(e))
122
+
123
+ async def send_photo(client, chat_id, file_path: Path, caption: str = ""):
124
+ url = f"{API_URL}/sendPhoto"
125
+ try:
126
+ # Read on a worker thread: a screenshot is megabytes, and reading it
127
+ # inline stalled the bot's poll loop (and everything else on the loop)
128
+ # for the length of the read.
129
+ blob = await asyncio.to_thread(Path(file_path).read_bytes)
130
+ res = await client.post(url, data={"chat_id": str(chat_id), "caption": caption[:1024]},
131
+ files={"photo": (file_path.name, blob)}, timeout=60.0)
132
+ if res.status_code != 200:
133
+ await send_message(client, chat_id, f"사진 전송 실패 ({res.status_code})")
134
+ except Exception as e:
135
+ logger.error("사진 전송 실패: %s", safe_log_text(e))
136
+ await send_message(client, chat_id, f"사진 전송 오류: {safe_log_text(e)}")
137
+
138
+ async def send_document(client, chat_id, file_path, caption=None, filename=None):
139
+ url = f"{API_URL}/sendDocument"
140
+ try:
141
+ blob = await asyncio.to_thread(Path(file_path).read_bytes)
142
+ res = await client.post(
143
+ url,
144
+ data={"chat_id": str(chat_id), **({"caption": caption[:1024]} if caption else {})},
145
+ files={"document": (filename or Path(file_path).name, blob)},
146
+ timeout=300.0,
147
+ )
148
+ if res.status_code != 200:
149
+ logger.error("파일 전송 실패 (%s): %s", res.status_code, safe_log_text(res.text))
150
+ except Exception as e:
151
+ logger.error("파일 전송 실패: %s", safe_log_text(e))
152
+
153
+ async def send_chat_action(client, chat_id, action="typing"):
154
+ try:
155
+ await client.post(f"{API_URL}/sendChatAction", json={"chat_id": chat_id, "action": action})
156
+ except Exception:
157
+ quiet()
158
+
159
+ async def answer_callback(client, callback_query_id, text=""):
160
+ try:
161
+ await client.post(f"{API_URL}/answerCallbackQuery",
162
+ json={"callback_query_id": callback_query_id, "text": text})
163
+ except Exception:
164
+ quiet()
165
+
166
+ async def edit_message(client, chat_id, message_id, text, reply_markup=None):
167
+ try:
168
+ payload = {"chat_id": chat_id, "message_id": message_id, "text": text}
169
+ if reply_markup:
170
+ payload["reply_markup"] = reply_markup
171
+ await client.post(f"{API_URL}/editMessageText", json=payload)
172
+ except Exception:
173
+ quiet()
174
+
175
+ # ── Network helpers ───────────────────────────────────────────────────────────
176
+
177
+ def get_lan_ip():
178
+ try:
179
+ with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
180
+ s.connect(("8.8.8.8", 80))
181
+ ip = s.getsockname()[0]
182
+ if not ip.startswith("127."):
183
+ return ip
184
+ except OSError:
185
+ quiet()
186
+ try:
187
+ hostname = socket.gethostname()
188
+ for ip in socket.gethostbyname_ex(hostname)[2]:
189
+ if not ip.startswith("127."):
190
+ return ip
191
+ except OSError:
192
+ quiet()
193
+ return "127.0.0.1"
194
+
195
+ def get_web_url():
196
+ if PUBLIC_WEB_URL:
197
+ return PUBLIC_WEB_URL.rstrip("/")
198
+ base = f"http://{get_lan_ip()}:{SERVER_PORT}/"
199
+ return f"{base}?code={INVITE_CODE}" if INVITE_CODE else base
200
+
201
+ def get_graph_url():
202
+ if PUBLIC_WEB_URL:
203
+ return f"{PUBLIC_WEB_URL.rstrip('/')}/graph"
204
+ return f"http://{get_lan_ip()}:{SERVER_PORT}/graph"
205
+
206
+ # ── Broadcast (web → telegram mirror) ────────────────────────────────────────
207
+
208
+ async def broadcast_web_chat(role, text):
209
+ if not TOKEN:
210
+ return
211
+ # Old releases registered every sender. Intersect persisted recipients
212
+ # with the current allowlist so stale files cannot keep receiving mirrors.
213
+ allowed = allowed_chat_ids()
214
+ chat_ids = load_chat_ids() & set(allowed)
215
+ if not chat_ids:
216
+ return
217
+ label = "사용자" if role == "user" else "Lattice AI"
218
+ message = f"[Web] {label}\n{text}"
219
+ async with httpx.AsyncClient() as client:
220
+ for chat_id in chat_ids:
221
+ await send_message(client, chat_id, message)
222
+
223
+ # ── Polling ───────────────────────────────────────────────────────────────────
224
+
225
+ async def get_updates(client, offset=None):
226
+ url = f"{API_URL}/getUpdates?timeout=30"
227
+ if offset:
228
+ url += f"&offset={offset}"
229
+ try:
230
+ res = await client.get(url, timeout=35)
231
+ return res.json()
232
+ except Exception:
233
+ return None
234
+
235
+ # ── File download ─────────────────────────────────────────────────────────────
236
+
237
+ async def download_telegram_file(client, file_id) -> bytes | None:
238
+ try:
239
+ res = await client.get(f"{API_URL}/getFile?file_id={file_id}")
240
+ file_path = res.json().get("result", {}).get("file_path")
241
+ if not file_path:
242
+ return None
243
+ dl = await client.get(f"https://api.telegram.org/file/bot{TOKEN}/{file_path}")
244
+ return dl.content if dl.status_code == 200 else None
245
+ except Exception as e:
246
+ logger.error("파일 다운로드 실패: %s", safe_log_text(e))
247
+ return None
248
+
249
+ async def download_as_base64(client, file_id) -> str | None:
250
+ data = await download_telegram_file(client, file_id)
251
+ return base64.b64encode(data).decode() if data else None
252
+
253
+ # ── Agent artifacts (workspace files and preview links) ──────────────────────
254
+
255
+ def resolve_workspace_file(relative_path):
256
+ target = (AGENT_WORKSPACE / relative_path).resolve()
257
+ if target != AGENT_WORKSPACE and AGENT_WORKSPACE not in target.parents:
258
+ return None
259
+ if not target.exists() or not target.is_file():
260
+ return None
261
+ if target.stat().st_size > MAX_TELEGRAM_FILE_BYTES:
262
+ return None
263
+ return target
264
+
265
+ def collect_generated_files(agent_data):
266
+ files, seen = [], set()
267
+ for step in agent_data.get("steps", []):
268
+ if step.get("action") not in {"write_file", "create_docx", "create_xlsx", "create_pptx", "create_pdf"}:
269
+ continue
270
+ path = (step.get("result") or {}).get("path") or (step.get("args") or {}).get("path")
271
+ if not path or path in seen:
272
+ continue
273
+ target = resolve_workspace_file(path)
274
+ if target:
275
+ seen.add(path)
276
+ files.append((path, target))
277
+ return files
278
+
279
+ def collect_preview_urls(agent_data):
280
+ urls, seen = [], set()
281
+ for step in agent_data.get("steps", []):
282
+ if step.get("action") != "preview_url":
283
+ continue
284
+ result = step.get("result") or {}
285
+ local_url = result.get("local_url")
286
+ if not local_url or local_url in seen:
287
+ continue
288
+ phone_url = local_url.replace("http://127.0.0.1:4825", f"http://{get_lan_ip()}:{SERVER_PORT}")
289
+ seen.add(local_url)
290
+ urls.append((result.get("path") or "preview", phone_url))
291
+ return urls
292
+
293
+ async def send_preview_links(client, chat_id, preview_urls):
294
+ if not preview_urls:
295
+ return
296
+ lines = ["미리보기 링크 (Mac과 같은 Wi-Fi 필요):"]
297
+ keyboard = []
298
+ for label, url in preview_urls:
299
+ lines.append(f"- {label}: {url}")
300
+ keyboard.append([{"text": f"{label} 열기"[:64], "url": url}])
301
+ await send_message(client, chat_id, "\n".join(lines), reply_markup={"inline_keyboard": keyboard[:8]})
302
+
303
+ async def send_generated_files(client, chat_id, generated_files):
304
+ if not generated_files:
305
+ return
306
+ if len(generated_files) == 1:
307
+ path, fpath = generated_files[0]
308
+ await send_document(client, chat_id, fpath, caption=f"생성 파일: {path}")
309
+ return
310
+ with tempfile.NamedTemporaryFile(prefix="ltcai-", suffix=".zip", delete=False) as tmp:
311
+ zip_path = Path(tmp.name)
312
+ try:
313
+ with zipfile.ZipFile(zip_path, "w", compression=zipfile.ZIP_DEFLATED) as zf:
314
+ for rel, fpath in generated_files:
315
+ zf.write(fpath, arcname=rel)
316
+ if zip_path.stat().st_size <= MAX_TELEGRAM_FILE_BYTES:
317
+ await send_document(client, chat_id, zip_path,
318
+ caption=f"생성 파일 {len(generated_files)}개", filename="ltcai-files.zip")
319
+ else:
320
+ await send_message(client, chat_id, "생성 파일이 너무 커서 전송할 수 없습니다.")
321
+ finally:
322
+ zip_path.unlink(missing_ok=True)