@aliwey/bmo 2.0.9 → 2.1.1
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/bin/bmo.js +12 -0
- package/config/__pycache__/settings.cpython-313.pyc +0 -0
- package/config/settings.py +1 -0
- package/core/__pycache__/bmo_engine.cpython-313.pyc +0 -0
- package/core/__pycache__/bot_client.cpython-313.pyc +0 -0
- package/core/bmo_engine.py +2 -1
- package/core/bot_client.py +2 -2
- package/memory.md +14 -29
- package/package.json +1 -1
- package/scripts/bmo_init.js +46 -4
- package/scripts/postinstall.js +13 -11
- package/storage/__pycache__/sqlite_storage.cpython-313.pyc +0 -0
- package/storage/sqlite_storage.py +64 -13
package/bin/bmo.js
CHANGED
|
@@ -209,6 +209,18 @@ Data lives in: ${BMO_HOME_DISPLAY}
|
|
|
209
209
|
process.on('SIGTERM', () => { cleanup(); process.exit(0); });
|
|
210
210
|
}
|
|
211
211
|
|
|
212
|
+
// Copy generic memory.md template if it does not exist
|
|
213
|
+
const packageMemoryPath = path.join(PKG_DIR, 'memory.md');
|
|
214
|
+
const userMemoryPath = path.join(BMO_HOME, 'data', 'memory.md');
|
|
215
|
+
if (fs.existsSync(packageMemoryPath) && !fs.existsSync(userMemoryPath)) {
|
|
216
|
+
try {
|
|
217
|
+
fs.mkdirSync(path.dirname(userMemoryPath), { recursive: true });
|
|
218
|
+
fs.copyFileSync(packageMemoryPath, userMemoryPath);
|
|
219
|
+
} catch (e) {
|
|
220
|
+
console.error(`Warning: Failed to copy memory.md template: ${e.message}`);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
212
224
|
// Launch BMO Python CLI — exactly like running `python cli.py`
|
|
213
225
|
const python = getPython();
|
|
214
226
|
const cliScript = path.join(PKG_DIR, 'cli.py');
|
|
Binary file
|
package/config/settings.py
CHANGED
|
@@ -78,6 +78,7 @@ SESSIONS_FILE = DATA_DIR / "sessions.jsonl"
|
|
|
78
78
|
USER_MEMORY_FILE = DATA_DIR / "user_memory.json"
|
|
79
79
|
ACTIVE_SESSIONS_FILE = DATA_DIR / "active_sessions.json"
|
|
80
80
|
DATABASE_FILE = DATA_DIR / "bot.db"
|
|
81
|
+
MEMORY_FILE = DATA_DIR / "memory.md"
|
|
81
82
|
|
|
82
83
|
MAX_HISTORY_PER_CHAT = 500
|
|
83
84
|
MAX_CONTEXT_LENGTH = 32000
|
|
Binary file
|
|
Binary file
|
package/core/bmo_engine.py
CHANGED
|
@@ -12,7 +12,7 @@ from uuid import uuid4
|
|
|
12
12
|
from datetime import datetime
|
|
13
13
|
from typing import Optional, List, Dict, AsyncGenerator
|
|
14
14
|
|
|
15
|
-
from config.settings import OPENCODE_BASE_URL, BFP_RELAY_URL, BFP_TRANSPORT_PORT, BFP_A2A_PORT
|
|
15
|
+
from config.settings import OPENCODE_BASE_URL, BFP_RELAY_URL, BFP_TRANSPORT_PORT, BFP_A2A_PORT, OWNER_ID, ALLOWED_USER_IDS
|
|
16
16
|
from core.bot_client import OpenCodeBotClient
|
|
17
17
|
from core.worker_manager import WorkerManager
|
|
18
18
|
from models.chat_models import ChatSession, ChatMessage
|
|
@@ -38,6 +38,7 @@ class BMOEngine:
|
|
|
38
38
|
self.storage = SQLiteStorage(db_path=db_path)
|
|
39
39
|
else:
|
|
40
40
|
self.storage = get_storage()
|
|
41
|
+
self.storage.sync_session_groups(OWNER_ID, ALLOWED_USER_IDS)
|
|
41
42
|
self.client = OpenCodeBotClient()
|
|
42
43
|
self.worker_manager = WorkerManager(backend=worker_backend)
|
|
43
44
|
self.client.set_worker_manager(self.worker_manager)
|
package/core/bot_client.py
CHANGED
|
@@ -14,7 +14,7 @@ from typing import Optional, Callable
|
|
|
14
14
|
|
|
15
15
|
from core.worker_manager import WorkerManager
|
|
16
16
|
|
|
17
|
-
from config.settings import OPENCODE_BASE_URL, OPENCODE_TIMEOUT, OPENCODE_POLL_INTERVAL, OPENCODE_POLL_TIMEOUT
|
|
17
|
+
from config.settings import OPENCODE_BASE_URL, OPENCODE_TIMEOUT, OPENCODE_POLL_INTERVAL, OPENCODE_POLL_TIMEOUT, MEMORY_FILE
|
|
18
18
|
|
|
19
19
|
logger = logging.getLogger(__name__)
|
|
20
20
|
|
|
@@ -46,7 +46,7 @@ class OpenCodeBotClient:
|
|
|
46
46
|
self._memory_cache_time: float = 0
|
|
47
47
|
self._agents_cache: Optional[list] = None
|
|
48
48
|
self._agents_cache_time: float = 0
|
|
49
|
-
self._memory_path =
|
|
49
|
+
self._memory_path = str(MEMORY_FILE)
|
|
50
50
|
self._worker: Optional[WorkerManager] = None
|
|
51
51
|
|
|
52
52
|
def set_worker_manager(self, worker: WorkerManager):
|
package/memory.md
CHANGED
|
@@ -1,43 +1,28 @@
|
|
|
1
1
|
# BMO Core Profile
|
|
2
2
|
|
|
3
|
+
This file contains the essential identity and core preferences of the USER and BMO.
|
|
4
|
+
Detailed technical experiences are stored separately in the Knowledge Vault (`data/experience/`).
|
|
5
|
+
|
|
3
6
|
## User Profile
|
|
4
7
|
|
|
5
|
-
- Name:
|
|
6
|
-
- Role:
|
|
7
|
-
- Preference:
|
|
8
|
+
- Name: [Enter Name]
|
|
9
|
+
- Role: [Enter Role]
|
|
10
|
+
- Preference: [Enter Preference]
|
|
11
|
+
- Arch: BMO is PORTABLE — each person runs their own instance on their device.
|
|
12
|
+
The Telegram bot lives on the owner's device. The owner uses both CLI and Telegram
|
|
13
|
+
to talk to their BMO. Other ALLOWED_USER_IDS can be added to connect via Telegram.
|
|
14
|
+
Session sync is between CLI ↔ Telegram on the SAME device for the SAME user(s).
|
|
15
|
+
ALLOWED_USER_IDS + OWNER_ID form a session group — they share one global active session.
|
|
16
|
+
Users outside the group get isolated sessions.
|
|
8
17
|
|
|
9
18
|
## Learned Preferences
|
|
10
19
|
|
|
11
|
-
- Language: English
|
|
12
|
-
- Communication: Concise
|
|
13
|
-
- Telegram Format: **Markdown** (integrated with CLI markdown output) — Telegram wire format uses MarkdownV2 parse mode, converted from standard markdown at send-time
|
|
14
|
-
- Project: BMO Telegram Bot (OpenCode Ecosystem).
|
|
20
|
+
- Language: English
|
|
21
|
+
- Communication: Concise and professional.
|
|
15
22
|
|
|
16
23
|
## Knowledge Index
|
|
17
24
|
|
|
18
25
|
This index summarizes technical achievements stored in `data/experience/`. BMO should read these files to reuse past solutions.
|
|
19
26
|
|
|
20
|
-
- **bmo_rebranding.md**: Full identity migration from NOVA to BMO (Core, Handlers, Web UI).
|
|
21
|
-
- **auto_summarization.md**: Implementation of idle-triggered session summaries with database persistence.
|
|
22
|
-
- **file_archival_system.md**: Session-linked file detection, copy, and indexing logic.
|
|
23
|
-
- **excel_inventory_automation.md**: Creation of multi-sheet Excel workbooks with cross-references for store management.
|
|
24
|
-
- **inline_menu_sessions.md**: Inline keyboard menu system with session history pagination and loading.
|
|
25
|
-
- **model_switching.md**: Model change with full session continuity — clears OpenCode session ID, creates fresh backend, injects SQLite history as context.
|
|
26
|
-
- **auto_title_summary.md**: Auto-summary now generates both summary + title after inactivity; new user guidance in system prompt to explain keyboard buttons.
|
|
27
|
-
- **webchat_public_default.md**: Webchat is always public — start server + cloudflared tunnel automatically. Never localhost-only unless user explicitly requests it. Full workflow: start_web_task → tunnel_webchat → wait 15s → check_task_status → send URL.
|
|
28
|
-
- **background_task_registry.md**: Full background task management system with JSON registry, MCP tools (start_web_task, list_background_tasks, check_task_status, stop_background_task, tunnel_webchat), auto-cleanup of dead processes, port conflict detection, and centralized logging. Prevents all bot freezing from servers/tunnels.
|
|
29
|
-
- **soft_new_session.md**: `/new` rewritten with Claude Code-style soft-reset — wipes model context via `delete_messages` but preserves `opencode_session_id` for warm system-prompt cache. Inherits provider/model/agent/mode from old session. Fixes 60s+ first-token latency on every `/new`.
|
|
30
|
-
- **cli_hang_timeout.md**: Fixed 20-min CLI hang — lowered `OPENCODE_TIMEOUT` 1200→120, wrapped `_do_send` POST in `asyncio.wait_for`, installed real OS-level `signal.SIGINT` handler in `cli.py` so Ctrl+C cancels the active streaming task even inside `rich.Live` + `prompt_toolkit.patch_stdout(raw=True)`.
|
|
31
|
-
- **cli_worker_kill.md**: Full worker-subprocess Ctrl+C fix — added `cancel_current()` to both `AsyncSubprocessWorker` and `MultiprocessWorker` + `WorkerManager` facade, SIGINT handler now kills the subprocess via `asyncio.run_coroutine_threadsafe(worker.cancel_current(), loop)` BEFORE cancelling the asyncio task (shielded futures would otherwise block propagation). `ensure_worker` checks `is_alive` so cancelled workers respawn on next request. Timeouts set to 900s (15 min) for reasoning-heavy tasks.
|
|
32
|
-
- **name_correction.md**: Fixed stale `Aliwi` → `Aliwey` in both profile files (`memory.md` + `data/memory.md`); reminder that the profile lives in two synced locations.
|
|
33
|
-
- **cli_exit_unclosed_transport.md**: Fixed `/exit` dumping 4 `ValueError: I/O operation on closed pipe` warnings. CLI disabled worker (`client._worker = None`) but `ensure_worker()` still spawned a stranded subprocess. Three-layer fix: skip worker start when client disables it + properly close pipe transports in `shutdown()` + post-loop cleanup in `cli.py`.
|
|
34
|
-
- **telegram_markdown_integration.md**: User preference flip — Telegram now uses Markdown (MarkdownV2 on the wire) integrated with CLI markdown output. Old HTML parser path must be replaced by a `to_markdown_v2()` converter + chunker. `_clean_telegram_html` is obsolete.
|
|
35
|
-
- **portable_distribution.md**: Made BMO distributable — each user runs their own instance. Configurable `OWNER_ID`, generic memory.md templates, path-agnostic build script, setup wizard with owner ID prompt, stripped all personal/dev artifacts, port 4800 default.
|
|
36
|
-
- **cli_spinner_inplace_update.md**: Fixed thinking-counter leaving a vertical trail of past values on screen. `rich.Console.print(..., end="")` does NOT honor `\r` — switched the tick update to `sys.stdout.write + flush` with manual ANSI dim codes, and clear the partial line on completion.
|
|
37
|
-
- **bfp_protocol.md**: BFP (BMO Friendship Protocol) — DID-based identity, A2A-compatible Agent Cards, WebSocket transport, relay discovery, and enterprise A2A bridge. BMO is the reference implementation.
|
|
38
|
-
- **bfp_integration_fix.md**: Fixed 3 critical bugs from parallel subagent isolation: A2A bridge sync/async mismatch calling `send_message()` with wrong args, `bfp.delegate` returning fake stubs. Extracted shared `core/bfp_tasks.py` module used by both transport and A2A bridge. 13 passing tests.
|
|
39
|
-
- **bfp_user_facing.md**: Discovery module (`bfp_discovery.py`), relay WS connector (`bfp_connector.py`), relay WS DID mapping + peer forwarding, CLI `/bfp status/find/delegate/talk` commands, `BFP_RELAY_URL` env var. Relay WS forwarding architecture: `send` action creates pending future, forwards to target's WS, awaits `relay_response`, returns result. All 20 BFP tests pass.
|
|
40
|
-
- **bfp_websocket_http_graceful.md**: Fixed `InvalidUpgrade: Keep-Alive` traceback when HTTP requests hit the BFP WebSocket port 8765. Added `_process_request` callback to `ws_serve()` that returns a 426 "Upgrade Required" response for non-WebSocket connections instead of letting the library crash.
|
|
41
|
-
|
|
42
27
|
---
|
|
43
28
|
*BMO: Always update this index after adding a new file to the vault.*
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aliwey/bmo",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.1.1",
|
|
4
4
|
"description": "BMO — AI coding assistant with Telegram, CLI & Web sync. One command, all frontends.",
|
|
5
5
|
"keywords": ["ai", "coding-assistant", "telegram-bot", "cli", "opencode", "bfp"],
|
|
6
6
|
"homepage": "https://github.com/aliwey/bmo",
|
package/scripts/bmo_init.js
CHANGED
|
@@ -13,6 +13,7 @@ const os = require('os');
|
|
|
13
13
|
|
|
14
14
|
const BMO_HOME = process.env.BMO_HOME || path.join(os.homedir(), '.bmo');
|
|
15
15
|
const ENV_PATH = path.join(BMO_HOME, '.env');
|
|
16
|
+
const PKG_DIR = path.join(__dirname, '..');
|
|
16
17
|
|
|
17
18
|
function mkdirp(p) { fs.mkdirSync(p, { recursive: true }); }
|
|
18
19
|
|
|
@@ -26,9 +27,9 @@ function ask(rl, question, defaultValue) {
|
|
|
26
27
|
}
|
|
27
28
|
|
|
28
29
|
(async () => {
|
|
29
|
-
console.log('\n
|
|
30
|
+
console.log('\n╭───────────────────────────────────────────╮');
|
|
30
31
|
console.log('│ BMO Setup Wizard │');
|
|
31
|
-
console.log('
|
|
32
|
+
console.log('╰───────────────────────────────────────────╯\n');
|
|
32
33
|
|
|
33
34
|
// Load existing .env values as defaults
|
|
34
35
|
let existing = {};
|
|
@@ -38,7 +39,24 @@ function ask(rl, question, defaultValue) {
|
|
|
38
39
|
const m = line.match(/^([^#=]+)=(.*)$/);
|
|
39
40
|
if (m) existing[m[1].trim()] = m[2].trim();
|
|
40
41
|
}
|
|
41
|
-
console.log(`
|
|
42
|
+
console.log(` [Info] Existing config found at ${ENV_PATH} — press Enter to keep values.\n`);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Load existing memory.md values if available
|
|
46
|
+
let existing_name = '';
|
|
47
|
+
let existing_role = '';
|
|
48
|
+
let existing_preference = '';
|
|
49
|
+
const userMemoryPath = path.join(BMO_HOME, 'data', 'memory.md');
|
|
50
|
+
if (fs.existsSync(userMemoryPath)) {
|
|
51
|
+
try {
|
|
52
|
+
const memoryContent = fs.readFileSync(userMemoryPath, 'utf8');
|
|
53
|
+
const nameMatch = memoryContent.match(/-\s*Name:\s*(.*)/i);
|
|
54
|
+
const roleMatch = memoryContent.match(/-\s*Role:\s*(.*)/i);
|
|
55
|
+
const prefMatch = memoryContent.match(/-\s*Preference:\s*(.*)/i);
|
|
56
|
+
if (nameMatch && nameMatch[1].trim() !== '[Enter Name]') existing_name = nameMatch[1].trim();
|
|
57
|
+
if (roleMatch && roleMatch[1].trim() !== '[Enter Role]') existing_role = roleMatch[1].trim();
|
|
58
|
+
if (prefMatch && prefMatch[1].trim() !== '[Enter Preference]') existing_preference = prefMatch[1].trim();
|
|
59
|
+
} catch (e) {}
|
|
42
60
|
}
|
|
43
61
|
|
|
44
62
|
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
@@ -73,6 +91,13 @@ function ask(rl, question, defaultValue) {
|
|
|
73
91
|
existing.BFP_REGISTRY_URL || 'https://bfp-registry.aliwey.workers.dev'
|
|
74
92
|
);
|
|
75
93
|
|
|
94
|
+
// ── User Profile ──────────────────────────────────────────────────────────────
|
|
95
|
+
console.log('\n── User Profile ─────────────────────────────────────');
|
|
96
|
+
console.log(' Provide details to personalize your BMO companion.');
|
|
97
|
+
const userName = await ask(rl, 'Your Name', existing_name || 'Developer');
|
|
98
|
+
const userRole = await ask(rl, 'Your Knowledge / Background Description', existing_role || 'Python/Web Developer');
|
|
99
|
+
const userPref = await ask(rl, 'What should BMO do / Where should BMO focus', existing_preference || 'Assist with software development, debugging, and task automation');
|
|
100
|
+
|
|
76
101
|
rl.close();
|
|
77
102
|
|
|
78
103
|
// ── Write .env ────────────────────────────────────────────────────────────────
|
|
@@ -106,8 +131,25 @@ function ask(rl, question, defaultValue) {
|
|
|
106
131
|
|
|
107
132
|
fs.writeFileSync(ENV_PATH, envContent, 'utf8');
|
|
108
133
|
|
|
134
|
+
// ── Update memory.md ──────────────────────────────────────────────────────────
|
|
135
|
+
const packageMemoryPath = path.join(PKG_DIR, 'memory.md');
|
|
136
|
+
|
|
137
|
+
let memoryContent = '';
|
|
138
|
+
if (fs.existsSync(userMemoryPath)) {
|
|
139
|
+
memoryContent = fs.readFileSync(userMemoryPath, 'utf8');
|
|
140
|
+
} else if (fs.existsSync(packageMemoryPath)) {
|
|
141
|
+
memoryContent = fs.readFileSync(packageMemoryPath, 'utf8');
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
if (memoryContent) {
|
|
145
|
+
memoryContent = memoryContent.replace(/-\s*Name:\s*[^\r\n]*/i, `- Name: ${userName}`);
|
|
146
|
+
memoryContent = memoryContent.replace(/-\s*Role:\s*[^\r\n]*/i, `- Role: ${userRole}`);
|
|
147
|
+
memoryContent = memoryContent.replace(/-\s*Preference:\s*[^\r\n]*/i, `- Preference: ${userPref}`);
|
|
148
|
+
fs.writeFileSync(userMemoryPath, memoryContent, 'utf8');
|
|
149
|
+
}
|
|
150
|
+
|
|
109
151
|
console.log('\n╭───────────────────────────────────────────────────╮');
|
|
110
|
-
console.log(
|
|
152
|
+
console.log('│' + ` [OK] Config saved to ${ENV_PATH}`.padEnd(51) + '│');
|
|
111
153
|
console.log('│ │');
|
|
112
154
|
console.log('│ Run: bmo ← start BMO │');
|
|
113
155
|
console.log('│ bmo relay ← go online for BFP discovery │');
|
package/scripts/postinstall.js
CHANGED
|
@@ -53,9 +53,9 @@ const CF_URLS = {
|
|
|
53
53
|
// ── Helpers ──────────────────────────────────────────────────────────────────
|
|
54
54
|
|
|
55
55
|
const step = (n, msg) => console.log(`\n[${n}/5] ${msg}`);
|
|
56
|
-
const ok = msg => console.log(`
|
|
57
|
-
const warn = msg => console.log(`
|
|
58
|
-
const err = msg => console.error(`
|
|
56
|
+
const ok = msg => console.log(` [OK] ${msg}`);
|
|
57
|
+
const warn = msg => console.log(` [Warning] ${msg}`);
|
|
58
|
+
const err = msg => console.error(` [Error] ${msg}`);
|
|
59
59
|
|
|
60
60
|
function mkdirp(p) { fs.mkdirSync(p, { recursive: true }); }
|
|
61
61
|
|
|
@@ -250,16 +250,18 @@ function installWebchatDeps() {
|
|
|
250
250
|
await installCloudflared();
|
|
251
251
|
installWebchatDeps();
|
|
252
252
|
|
|
253
|
-
console.log('\n
|
|
254
|
-
console.log('│
|
|
255
|
-
console.log('│
|
|
256
|
-
console.log('│
|
|
257
|
-
console.log('│ bmo init
|
|
258
|
-
console.log('│
|
|
259
|
-
console.log('
|
|
253
|
+
console.log('\n╭───────────────────────────────────────────────────╮');
|
|
254
|
+
console.log('│ [OK] BMO installed successfully! │');
|
|
255
|
+
console.log('│ │');
|
|
256
|
+
console.log('│ IMPORTANT: You must run the setup wizard first: │');
|
|
257
|
+
console.log('│ bmo --init │');
|
|
258
|
+
console.log('│ │');
|
|
259
|
+
console.log('│ Then start BMO: │');
|
|
260
|
+
console.log('│ bmo │');
|
|
261
|
+
console.log('╰───────────────────────────────────────────────────╯\n');
|
|
260
262
|
} catch (e) {
|
|
261
263
|
err(`Installation failed: ${e.message}`);
|
|
262
|
-
console.log('\nRun `bmo init` to retry configuration, or check the docs.');
|
|
264
|
+
console.log('\nRun `bmo --init` to retry configuration, or check the docs.');
|
|
263
265
|
process.exit(1);
|
|
264
266
|
}
|
|
265
267
|
})();
|
|
Binary file
|
|
@@ -117,6 +117,11 @@ class SQLiteStorage:
|
|
|
117
117
|
created_at REAL NOT NULL,
|
|
118
118
|
UNIQUE(user_id, scope)
|
|
119
119
|
);
|
|
120
|
+
|
|
121
|
+
CREATE TABLE IF NOT EXISTS session_groups (
|
|
122
|
+
chat_id INTEGER PRIMARY KEY,
|
|
123
|
+
group_id INTEGER NOT NULL
|
|
124
|
+
);
|
|
120
125
|
""")
|
|
121
126
|
conn.commit()
|
|
122
127
|
|
|
@@ -254,6 +259,22 @@ class SQLiteStorage:
|
|
|
254
259
|
except Exception as e:
|
|
255
260
|
print(f"_fix_active_sessions error: {e}")
|
|
256
261
|
|
|
262
|
+
# ── Session Groups ─────────────────────────────────────────────────────
|
|
263
|
+
|
|
264
|
+
def sync_session_groups(self, owner_id: int, allowed_ids: set[int]):
|
|
265
|
+
"""Populate session_groups table from OWNER_ID + ALLOWED_USER_IDS config."""
|
|
266
|
+
if not owner_id and not allowed_ids:
|
|
267
|
+
return
|
|
268
|
+
group_id = owner_id or next(iter(allowed_ids))
|
|
269
|
+
ids_to_map = {owner_id} if owner_id else set()
|
|
270
|
+
ids_to_map.update(allowed_ids)
|
|
271
|
+
for cid in ids_to_map:
|
|
272
|
+
self._exec(
|
|
273
|
+
"INSERT OR REPLACE INTO session_groups (chat_id, group_id) VALUES (?, ?)",
|
|
274
|
+
(cid, group_id),
|
|
275
|
+
)
|
|
276
|
+
self._conn().commit()
|
|
277
|
+
|
|
257
278
|
# ── Session CRUD ──────────────────────────────────────────────────────
|
|
258
279
|
|
|
259
280
|
def save_session(self, session: ChatSession) -> bool:
|
|
@@ -292,16 +313,17 @@ class SQLiteStorage:
|
|
|
292
313
|
),
|
|
293
314
|
)
|
|
294
315
|
|
|
295
|
-
# Only set active session pointer if none exists yet for this
|
|
316
|
+
# Only set active session pointer if none exists yet for this group.
|
|
296
317
|
# This prevents save_session from overwriting a manual session switch.
|
|
318
|
+
group_id = self._resolve_group(session.chat_id)
|
|
297
319
|
existing_active = self._fetchone(
|
|
298
320
|
"SELECT session_id FROM active_sessions WHERE chat_id = ?",
|
|
299
|
-
(
|
|
321
|
+
(group_id,),
|
|
300
322
|
)
|
|
301
323
|
if not existing_active:
|
|
302
324
|
self._exec(
|
|
303
325
|
"INSERT OR REPLACE INTO active_sessions (chat_id, session_id) VALUES (?, ?)",
|
|
304
|
-
(
|
|
326
|
+
(group_id, session.session_id),
|
|
305
327
|
)
|
|
306
328
|
|
|
307
329
|
self._conn().commit()
|
|
@@ -312,9 +334,10 @@ class SQLiteStorage:
|
|
|
312
334
|
|
|
313
335
|
def load_session(self, chat_id: int) -> Optional[ChatSession]:
|
|
314
336
|
try:
|
|
337
|
+
group_id = self._resolve_group(chat_id)
|
|
315
338
|
active = self._fetchone(
|
|
316
339
|
"SELECT session_id FROM active_sessions WHERE chat_id = ?",
|
|
317
|
-
(
|
|
340
|
+
(group_id,),
|
|
318
341
|
)
|
|
319
342
|
session_id = active["session_id"] if active else None
|
|
320
343
|
|
|
@@ -326,14 +349,19 @@ class SQLiteStorage:
|
|
|
326
349
|
return self._row_to_session(row)
|
|
327
350
|
|
|
328
351
|
candidates = self._fetchall(
|
|
329
|
-
"SELECT
|
|
330
|
-
(
|
|
352
|
+
"SELECT s.* FROM sessions s JOIN session_groups sg ON s.chat_id = sg.chat_id WHERE sg.group_id = ? ORDER BY s.updated_at DESC LIMIT 1",
|
|
353
|
+
(group_id,),
|
|
331
354
|
)
|
|
355
|
+
if not candidates:
|
|
356
|
+
candidates = self._fetchall(
|
|
357
|
+
"SELECT * FROM sessions WHERE chat_id = ? ORDER BY updated_at DESC LIMIT 1",
|
|
358
|
+
(chat_id,),
|
|
359
|
+
)
|
|
332
360
|
if candidates:
|
|
333
361
|
row = candidates[0]
|
|
334
362
|
self._exec(
|
|
335
363
|
"INSERT OR REPLACE INTO active_sessions (chat_id, session_id) VALUES (?, ?)",
|
|
336
|
-
(
|
|
364
|
+
(group_id, dict(row)["id"]),
|
|
337
365
|
)
|
|
338
366
|
self._conn().commit()
|
|
339
367
|
return self._row_to_session(row)
|
|
@@ -346,9 +374,10 @@ class SQLiteStorage:
|
|
|
346
374
|
def set_active_session(self, chat_id: int, session_id: str) -> bool:
|
|
347
375
|
"""Explicitly switch the active session pointer for a chat."""
|
|
348
376
|
try:
|
|
377
|
+
group_id = self._resolve_group(chat_id)
|
|
349
378
|
self._exec(
|
|
350
379
|
"INSERT OR REPLACE INTO active_sessions (chat_id, session_id) VALUES (?, ?)",
|
|
351
|
-
(
|
|
380
|
+
(group_id, session_id),
|
|
352
381
|
)
|
|
353
382
|
self._conn().commit()
|
|
354
383
|
return True
|
|
@@ -358,9 +387,10 @@ class SQLiteStorage:
|
|
|
358
387
|
|
|
359
388
|
def delete_session(self, chat_id: int) -> bool:
|
|
360
389
|
try:
|
|
390
|
+
group_id = self._resolve_group(chat_id)
|
|
361
391
|
active = self._fetchone(
|
|
362
392
|
"SELECT session_id FROM active_sessions WHERE chat_id = ?",
|
|
363
|
-
(
|
|
393
|
+
(group_id,),
|
|
364
394
|
)
|
|
365
395
|
if active:
|
|
366
396
|
self._exec("DELETE FROM messages WHERE session_id = ?", (active["session_id"],))
|
|
@@ -375,9 +405,10 @@ class SQLiteStorage:
|
|
|
375
405
|
def add_message(self, chat_id: int, sender: str, content: str, interface: str = 'telegram') -> bool:
|
|
376
406
|
"""Insert a single message directly into DB without rewriting the whole session."""
|
|
377
407
|
try:
|
|
408
|
+
group_id = self._resolve_group(chat_id)
|
|
378
409
|
active = self._fetchone(
|
|
379
410
|
"SELECT session_id FROM active_sessions WHERE chat_id = ?",
|
|
380
|
-
(
|
|
411
|
+
(group_id,),
|
|
381
412
|
)
|
|
382
413
|
if not active:
|
|
383
414
|
return False
|
|
@@ -415,14 +446,26 @@ class SQLiteStorage:
|
|
|
415
446
|
return [dict(r) for r in reversed(rows)]
|
|
416
447
|
|
|
417
448
|
def list_chat_sessions(self, chat_id: int) -> List[dict]:
|
|
449
|
+
group_id = self._resolve_group(chat_id)
|
|
418
450
|
rows = self._fetchall(
|
|
419
451
|
"""SELECT id, title, summary,
|
|
420
452
|
(SELECT COUNT(*) FROM messages WHERE session_id = sessions.id) as msg_count,
|
|
421
453
|
updated_at,
|
|
422
454
|
(SELECT session_id FROM active_sessions WHERE chat_id = ?) as active_id
|
|
423
|
-
FROM sessions
|
|
424
|
-
|
|
455
|
+
FROM sessions
|
|
456
|
+
WHERE chat_id IN (SELECT chat_id FROM session_groups WHERE group_id = ?)
|
|
457
|
+
ORDER BY updated_at DESC""",
|
|
458
|
+
(group_id, group_id),
|
|
425
459
|
)
|
|
460
|
+
if not rows:
|
|
461
|
+
rows = self._fetchall(
|
|
462
|
+
"""SELECT id, title, summary,
|
|
463
|
+
(SELECT COUNT(*) FROM messages WHERE session_id = sessions.id) as msg_count,
|
|
464
|
+
updated_at,
|
|
465
|
+
(SELECT session_id FROM active_sessions WHERE chat_id = ?) as active_id
|
|
466
|
+
FROM sessions WHERE chat_id = ? ORDER BY updated_at DESC""",
|
|
467
|
+
(group_id, chat_id),
|
|
468
|
+
)
|
|
426
469
|
return [
|
|
427
470
|
{
|
|
428
471
|
"session_id": r["id"],
|
|
@@ -441,9 +484,10 @@ class SQLiteStorage:
|
|
|
441
484
|
)
|
|
442
485
|
if not exists:
|
|
443
486
|
return False
|
|
487
|
+
group_id = self._resolve_group(chat_id)
|
|
444
488
|
self._exec(
|
|
445
489
|
"INSERT OR REPLACE INTO active_sessions (chat_id, session_id) VALUES (?, ?)",
|
|
446
|
-
(
|
|
490
|
+
(group_id, session_id),
|
|
447
491
|
)
|
|
448
492
|
self._conn().commit()
|
|
449
493
|
return True
|
|
@@ -546,6 +590,13 @@ class SQLiteStorage:
|
|
|
546
590
|
session_id=row_dict["id"],
|
|
547
591
|
)
|
|
548
592
|
|
|
593
|
+
def _resolve_group(self, chat_id: int) -> int:
|
|
594
|
+
"""Return the group_id for a chat_id, or chat_id itself if not in a group."""
|
|
595
|
+
row = self._fetchone(
|
|
596
|
+
"SELECT group_id FROM session_groups WHERE chat_id = ?", (chat_id,)
|
|
597
|
+
)
|
|
598
|
+
return row["group_id"] if row else chat_id
|
|
599
|
+
|
|
549
600
|
def get_stats(self) -> dict:
|
|
550
601
|
"""Returns global statistics for the admin."""
|
|
551
602
|
user_count = self._fetchone("SELECT COUNT(DISTINCT chat_id) FROM sessions")[0]
|