ltcai 11.2.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.
- package/README.md +46 -53
- package/docs/CHANGELOG.md +61 -0
- package/docs/COMMUNITY_AND_PLUGINS.md +1 -1
- package/docs/DEVELOPMENT.md +1 -1
- package/docs/MULTI_AGENT_RUNTIME.md +1 -1
- package/docs/ONBOARDING.md +1 -1
- package/docs/OPERATIONS.md +6 -2
- package/docs/PERMISSION_MODE.md +1 -1
- package/docs/TRUST_MODEL.md +1 -1
- package/docs/WHY_LATTICE.md +1 -1
- package/docs/kg-schema.md +2 -2
- package/docs/v11.3.0_PLAN.md +202 -0
- package/docs/v11.4.0_RUST_FOUNDATION_PLAN.md +176 -0
- package/lattice_brain/__init__.py +1 -1
- package/lattice_brain/graph/_kg_common/__init__.py +287 -0
- package/lattice_brain/graph/_kg_common/extraction.py +516 -0
- package/lattice_brain/graph/_kg_common/relations.py +161 -0
- package/lattice_brain/graph/_kg_common/text.py +479 -0
- package/lattice_brain/graph/discovery_index/__init__.py +35 -0
- package/lattice_brain/graph/discovery_index/cleanup.py +182 -0
- package/lattice_brain/graph/discovery_index/extract.py +137 -0
- package/lattice_brain/graph/discovery_index/scan.py +411 -0
- package/lattice_brain/graph/discovery_index/upsert.py +495 -0
- package/lattice_brain/graph/projection/__init__.py +42 -0
- package/lattice_brain/graph/projection/curation.py +500 -0
- package/lattice_brain/graph/{projection.py → projection/v2_schema.py} +15 -477
- package/lattice_brain/graph/retrieval/__init__.py +54 -0
- package/lattice_brain/graph/retrieval/context.py +197 -0
- package/lattice_brain/graph/retrieval/graph_view.py +319 -0
- package/lattice_brain/graph/retrieval/hybrid.py +488 -0
- package/lattice_brain/graph/retrieval/maintenance.py +121 -0
- package/lattice_brain/graph/retrieval/signals.py +95 -0
- package/lattice_brain/graph/retrieval_vector/__init__.py +42 -0
- package/lattice_brain/graph/retrieval_vector/fingerprint.py +97 -0
- package/lattice_brain/graph/retrieval_vector/indexing.py +347 -0
- package/lattice_brain/graph/retrieval_vector/search.py +560 -0
- package/lattice_brain/graph/retrieval_vector/status.py +374 -0
- package/lattice_brain/ingestion/__init__.py +130 -0
- package/lattice_brain/ingestion/_contract.py +90 -0
- package/lattice_brain/ingestion/constants.py +127 -0
- package/lattice_brain/ingestion/folder_scan.py +57 -0
- package/lattice_brain/ingestion/folders.py +258 -0
- package/lattice_brain/ingestion/hashing.py +26 -0
- package/lattice_brain/ingestion/jobs_api.py +107 -0
- package/lattice_brain/ingestion/models.py +80 -0
- package/lattice_brain/ingestion/pipeline.py +486 -0
- package/lattice_brain/ingestion/quality.py +209 -0
- package/lattice_brain/ingestion/routing.py +295 -0
- package/lattice_brain/multimodal/__init__.py +164 -0
- package/lattice_brain/multimodal/audio.py +77 -0
- package/lattice_brain/multimodal/common.py +118 -0
- package/lattice_brain/multimodal/images.py +498 -0
- package/lattice_brain/multimodal/ports.py +169 -0
- package/lattice_brain/multimodal/video.py +410 -0
- package/lattice_brain/portability/__init__.py +90 -0
- package/lattice_brain/portability/_contract.py +42 -0
- package/lattice_brain/portability/backups.py +338 -0
- package/lattice_brain/portability/bundles.py +136 -0
- package/lattice_brain/portability/constants.py +93 -0
- package/lattice_brain/portability/fsops.py +138 -0
- package/lattice_brain/portability/service.py +41 -0
- package/lattice_brain/{portability.py → portability/sharing.py} +44 -677
- package/lattice_brain/runtime/__init__.py +1 -1
- package/lattice_brain/runtime/multi_agent.py +1 -1
- package/latticeai/__init__.py +1 -1
- package/latticeai/api/chronicle.py +63 -0
- package/latticeai/core/agent/__init__.py +93 -0
- package/latticeai/core/agent/_contract.py +79 -0
- package/latticeai/core/agent/context.py +57 -0
- package/latticeai/core/agent/deps.py +125 -0
- package/latticeai/core/agent/execution.py +622 -0
- package/latticeai/core/agent/planning.py +145 -0
- package/latticeai/core/agent/recovery.py +157 -0
- package/latticeai/core/agent/runtime.py +210 -0
- package/latticeai/core/agent/verification.py +231 -0
- package/latticeai/core/embedding_providers/__init__.py +151 -0
- package/latticeai/core/embedding_providers/base.py +199 -0
- package/latticeai/core/embedding_providers/captions.py +162 -0
- package/latticeai/core/embedding_providers/profiles.py +126 -0
- package/latticeai/core/embedding_providers/text.py +350 -0
- package/latticeai/core/embedding_providers/vision.py +352 -0
- package/latticeai/core/file_generation/__init__.py +115 -0
- package/latticeai/core/file_generation/bundles.py +76 -0
- package/latticeai/core/file_generation/extraction.py +154 -0
- package/latticeai/core/file_generation/inference.py +235 -0
- package/latticeai/core/file_generation/orchestration.py +152 -0
- package/latticeai/core/file_generation/prompting.py +117 -0
- package/latticeai/core/file_generation/repair.py +114 -0
- package/latticeai/core/file_generation/sanitize.py +61 -0
- package/latticeai/core/file_generation/validation.py +201 -0
- package/latticeai/core/legacy_compatibility.py +1 -1
- package/latticeai/core/marketplace.py +1 -1
- package/latticeai/core/messages.py +9 -0
- package/latticeai/core/workspace_os_constants.py +1 -1
- package/latticeai/integrations/telegram_bot/__init__.py +123 -0
- package/latticeai/integrations/telegram_bot/__main__.py +17 -0
- package/latticeai/integrations/telegram_bot/config.py +86 -0
- package/latticeai/integrations/telegram_bot/dispatch.py +311 -0
- package/latticeai/integrations/telegram_bot/flows.py +478 -0
- package/latticeai/integrations/telegram_bot/helpers.py +322 -0
- package/latticeai/integrations/telegram_bot/screens.py +394 -0
- package/latticeai/models/router/__init__.py +88 -0
- package/latticeai/models/router/_contract.py +66 -0
- package/latticeai/models/router/branding.py +56 -0
- package/latticeai/models/router/catalog.py +69 -0
- package/latticeai/models/router/documents.py +199 -0
- package/latticeai/models/router/errors.py +37 -0
- package/latticeai/models/router/generation.py +258 -0
- package/latticeai/models/router/loading.py +291 -0
- package/latticeai/models/router/local_models.py +85 -0
- package/latticeai/models/router/registry.py +147 -0
- package/latticeai/runtime/build_phases/__init__.py +82 -0
- package/latticeai/runtime/build_phases/features.py +407 -0
- package/latticeai/runtime/build_phases/foundation.py +555 -0
- package/latticeai/runtime/build_phases/web.py +492 -0
- package/latticeai/runtime/runtime_context.py +1 -0
- package/latticeai/services/architecture_readiness.py +48 -19
- package/latticeai/services/brain_intelligence/__init__.py +58 -0
- package/latticeai/services/brain_intelligence/_contract.py +71 -0
- package/latticeai/services/brain_intelligence/consistency.py +193 -0
- package/latticeai/services/brain_intelligence/constants.py +47 -0
- package/latticeai/services/brain_intelligence/digest.py +258 -0
- package/latticeai/services/brain_intelligence/health.py +331 -0
- package/latticeai/services/brain_intelligence/proposals.py +264 -0
- package/latticeai/services/brain_intelligence/sampling.py +84 -0
- package/latticeai/services/brain_intelligence/service.py +48 -0
- package/latticeai/services/chronicle.py +557 -0
- package/latticeai/services/memory_service/__init__.py +52 -0
- package/latticeai/services/memory_service/_contract.py +100 -0
- package/latticeai/services/memory_service/brief.py +431 -0
- package/latticeai/services/memory_service/constants.py +57 -0
- package/latticeai/services/memory_service/maintenance.py +138 -0
- package/latticeai/services/memory_service/manager.py +186 -0
- package/latticeai/services/memory_service/proof.py +136 -0
- package/latticeai/services/memory_service/recall.py +225 -0
- package/latticeai/services/memory_service/service.py +48 -0
- package/latticeai/services/memory_service/stores.py +110 -0
- package/latticeai/services/model_runtime/__init__.py +322 -0
- package/latticeai/services/model_runtime/cloud.py +87 -0
- package/latticeai/services/model_runtime/download.py +282 -0
- package/latticeai/services/model_runtime/engines.py +341 -0
- package/latticeai/services/model_runtime/loading.py +178 -0
- package/latticeai/services/model_runtime/service.py +129 -0
- package/latticeai/services/model_runtime/state.py +131 -0
- package/latticeai/services/model_runtime/status.py +255 -0
- package/latticeai/services/product_readiness.py +15 -7
- package/latticeai/setup/wizard/__init__.py +126 -0
- package/latticeai/setup/wizard/catalog.py +172 -0
- package/latticeai/setup/wizard/detect.py +323 -0
- package/latticeai/setup/wizard/install.py +348 -0
- package/latticeai/setup/wizard/paths.py +168 -0
- package/latticeai/setup/wizard/plans.py +74 -0
- package/latticeai/setup/wizard/recommend.py +320 -0
- package/package.json +6 -2
- package/scripts/bump_version.py +14 -0
- package/scripts/capture_release_evidence.mjs +33 -21
- package/scripts/check_current_release_docs.mjs +1 -1
- package/scripts/check_i18n_namespace_coverage.mjs +41 -4
- package/scripts/check_max_file_lines.mjs +102 -0
- package/scripts/check_release_evidence_bound.mjs +30 -15
- package/scripts/check_screenshot_pixel_delta.py +34 -4
- package/scripts/check_server_i18n.mjs +1 -0
- package/scripts/generate_rust_parity_fixtures.py +562 -0
- package/scripts/lib/mock_server_fingerprint.mjs +94 -0
- package/scripts/release_screen_claims.json +31 -2
- package/src-tauri/Cargo.lock +361 -3
- package/src-tauri/Cargo.toml +6 -1
- package/src-tauri/src/backend.rs +349 -0
- package/src-tauri/src/folder.rs +33 -0
- package/src-tauri/src/main.rs +97 -399
- package/src-tauri/tauri.conf.json +1 -1
- package/static/app/asset-manifest.json +41 -37
- package/static/app/assets/Act-yYpYnn0v.js +1 -0
- package/static/app/assets/AdminConsole-DL3Cr5pL.js +1 -0
- package/static/app/assets/{Brain-tuhI4sOC.js → Brain-C1HBN0Wf.js} +2 -2
- package/static/app/assets/BrainHome-DoXRhUUC.js +2 -0
- package/static/app/assets/BrainSignals-6yR6ir5t.js +1 -0
- package/static/app/assets/Capture-CFIRsFNE.js +1 -0
- package/static/app/assets/Chronicle-BZbEgiwN.js +1 -0
- package/static/app/assets/CommandPalette-D2pMxC2I.js +1 -0
- package/static/app/assets/Library-DwO3yZST.js +1 -0
- package/static/app/assets/{LivingBrain-DBwhto14.js → LivingBrain-Jn1GK0-S.js} +1 -1
- package/static/app/assets/ProductFlow-B-w1R4Oo.js +1 -0
- package/static/app/assets/ReviewCard-6B27X8Vg.js +3 -0
- package/static/app/assets/System-DW8F-2xL.js +1 -0
- package/static/app/assets/arrow-left-DXvKg9U6.js +1 -0
- package/static/app/assets/{bot-Cia42c2h.js → bot-IM_E_Y12.js} +1 -1
- package/static/app/assets/brain-Ci1CkWjM.js +1 -0
- package/static/app/assets/{button-2j2Ijzgq.js → button-COwyqfHM.js} +1 -1
- package/static/app/assets/circle-check-DfInj-qD.js +1 -0
- package/static/app/assets/{circle-pause-BEFeWpVW.js → circle-pause-DEM4A1Y5.js} +1 -1
- package/static/app/assets/{circle-play-ujXMcHxl.js → circle-play-C9djDuLd.js} +1 -1
- package/static/app/assets/{cpu-k4awryFq.js → cpu-DFdo1gw-.js} +1 -1
- package/static/app/assets/{download-DFbLJ_ig.js → download-SnJL6oqk.js} +1 -1
- package/static/app/assets/{folder-open-7y_b6xkM.js → folder-open-CqZeDkjE.js} +1 -1
- package/static/app/assets/{hard-drive-Bidh02Kr.js → hard-drive-j1jJXYYf.js} +1 -1
- package/static/app/assets/{index-DwDl9-8Y.css → index-BLPb5lmE.css} +1 -1
- package/static/app/assets/index-_u5iUHDr.js +10 -0
- package/static/app/assets/input-B0lPdRQZ.js +1 -0
- package/static/app/assets/link-2-CoFbooHS.js +1 -0
- package/static/app/assets/{permissionCopy-Bpb83Hx9.js → permissionCopy-BsyLxtao.js} +1 -1
- package/static/app/assets/primitives-DEbN-d6p.js +1 -0
- package/static/app/assets/search-BybIWPNd.js +1 -0
- package/static/app/assets/{share-2-BH1M-WNi.js → share-2-CVtZ_ewX.js} +1 -1
- package/static/app/assets/{shield-alert-BlKdBXcG.js → shield-alert-CBi2GNWM.js} +1 -1
- package/static/app/assets/{textarea-CCWbUfFB.js → textarea-DNMpB5ih.js} +1 -1
- package/static/app/assets/{useFocusTrap-YdHQ7pJ1.js → useFocusTrap-C83t3GXF.js} +1 -1
- package/static/app/assets/useMutation-DtbJDoyz.js +1 -0
- package/static/app/assets/{useQuery-CXQiwbVT.js → useQuery-Dcp1OChy.js} +1 -1
- package/static/app/assets/utils-BlZr7Pd4.js +4 -0
- package/static/app/assets/workspace-jJY4RuAV.js +1 -0
- package/static/app/index.html +4 -4
- package/static/sw.js +1 -1
- package/lattice_brain/graph/_kg_common.py +0 -1331
- package/lattice_brain/graph/discovery_index.py +0 -1141
- package/lattice_brain/graph/retrieval.py +0 -1120
- package/lattice_brain/graph/retrieval_vector.py +0 -1293
- package/lattice_brain/ingestion.py +0 -1525
- package/lattice_brain/multimodal.py +0 -1258
- package/latticeai/core/agent.py +0 -1465
- package/latticeai/core/embedding_providers.py +0 -1196
- package/latticeai/core/file_generation.py +0 -1047
- package/latticeai/integrations/telegram_bot.py +0 -1390
- package/latticeai/models/router.py +0 -1007
- package/latticeai/runtime/build_phases.py +0 -1450
- package/latticeai/services/brain_intelligence.py +0 -1083
- package/latticeai/services/memory_service.py +0 -1177
- package/latticeai/services/model_runtime.py +0 -1281
- package/latticeai/setup/wizard.py +0 -1310
- package/static/app/assets/Act-AWf0SAKp.js +0 -1
- package/static/app/assets/AdminConsole-D0u8Tiyj.js +0 -1
- package/static/app/assets/BrainHome-Ts7G_Ila.js +0 -2
- package/static/app/assets/BrainSignals-jMYgQ2Ar.js +0 -1
- package/static/app/assets/Capture-CqOSzyPr.js +0 -1
- package/static/app/assets/CommandPalette-DC0Bzh-I.js +0 -1
- package/static/app/assets/Library-CX-bbhmK.js +0 -1
- package/static/app/assets/ProductFlow-BHA2cfKI.js +0 -1
- package/static/app/assets/ReviewCard-BUhCKRNM.js +0 -3
- package/static/app/assets/System-Bu2t5hn1.js +0 -1
- package/static/app/assets/arrow-left-Dzwa5zRb.js +0 -1
- package/static/app/assets/brain-DJMoqrwx.js +0 -1
- package/static/app/assets/index-BpYkzcVm.js +0 -10
- package/static/app/assets/input-DSlJJxRs.js +0 -1
- package/static/app/assets/primitives-BCx6TvfG.js +0 -1
- package/static/app/assets/search-Cgy8cCFJ.js +0 -1
- package/static/app/assets/utils-zqPZJxdx.js +0 -4
- 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)
|