-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
2094 lines (1831 loc) · 97.5 KB
/
Copy pathbot.py
File metadata and controls
2094 lines (1831 loc) · 97.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
=============================================================================
Telegram → Gemini CLI ACP Bridge Bot
=============================================================================
Architecture Overview:
┌──────────────┐ Telegram API ┌────────────────┐ JSON-RPC 2.0 ┌─────────────────┐
│ Telegram │ ◄──────────────► │ bot.py │ ◄──────────────► │ gemini --acp │
│ User │ (python- │ (this file) │ (stdio pipe) │ (subprocess) │
└──────────────┘ telegram-bot) └────────────────┘ └─────────────────┘
Communication with gemini-cli --acp:
• Transport: subprocess stdin/stdout (newline-delimited JSON)
• Protocol: JSON-RPC 2.0
• Handshake:
1. Send → {"jsonrpc":"2.0","id":1,"method":"initialize","params":{...}}
2. Recv ← {"jsonrpc":"2.0","id":1,"result":{...}}
3. Send → {"jsonrpc":"2.0","id":2,"method":"session/new","params":{}}
4. Recv ← {"jsonrpc":"2.0","id":2,"result":{"sessionId":"..."}}
• Per message:
5. Send → {"jsonrpc":"2.0","id":N,"method":"prompt",
"params":{"sessionId":"...","prompt":[{"type":"text","text":"..."}]}}
6. Recv ← (possibly multiple notification chunks, then a result with id=N)
Environment variables (from .env):
TELEGRAM_BOT_TOKEN - Bot token from @BotFather
GEMINI_CLI_PATH - Path to gemini executable (default: "gemini")
GEMINI_WORKING_DIR - Working directory for the subprocess (default: cwd)
ACP_TIMEOUT - Seconds to wait for a full response (default: 120)
=============================================================================
"""
import asyncio
import contextlib
import datetime
import json
import logging
import os
import shlex
import sys
import time
from pathlib import Path
from typing import Optional
from dotenv import load_dotenv
# ─────────────────────────────────────────────────────────────────────────────
# FIX: On Windows the default stdout/stderr encoding is cp1252, which can't
# handle emoji/unicode characters (…, →, etc.) that bot.py logs. Reconfigure
# BOTH stdout AND stderr to UTF-8 with errors='replace' so those chars are
# rendered instead of crashing the StreamHandler with UnicodeEncodeError.
# NOTE: stderr must also be reconfigured because Python's logging module writes
# its own internal errors ("--- Logging error ---") to sys.stderr, and NSSM
# captures stderr to gelegram_stderr.log which defaults to cp1252.
# ─────────────────────────────────────────────────────────────────────────────
if sys.platform == "win32":
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
if hasattr(sys.stderr, "reconfigure"):
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
from telegram import Update, BotCommand
from telegram.ext import (
Application,
CommandHandler,
ContextTypes,
MessageHandler,
filters,
)
# ─────────────────────────────────────────────────────────────────────────────
# Logging setup – keep it clean and timestamped
# ─────────────────────────────────────────────────────────────────────────────
logging.basicConfig(
format="%(asctime)s | %(levelname)-8s | %(name)s | %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
level=logging.INFO,
handlers=[
logging.StreamHandler(sys.stdout),
logging.FileHandler("bot.log", encoding="utf-8"),
],
)
logger = logging.getLogger("gelegram")
# ── Dedicated tool-call audit logger ─────────────────────────────────────────
# All gemini-cli tool invocations (shell commands, file writes, etc.) are
# written here so you have a clean audit trail separate from bot/gateway logs.
# Format: timestamp | method | params JSON
_tools_file_handler = logging.FileHandler("tools.log", encoding="utf-8")
_tools_file_handler.setFormatter(
logging.Formatter(
fmt="%(asctime)s | %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
)
tools_logger = logging.getLogger("gelegram.tools")
tools_logger.setLevel(logging.INFO)
tools_logger.addHandler(_tools_file_handler)
tools_logger.propagate = False # keep tools.log clean; don't double-write to bot.log
# Silence overly verbose libraries
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("telegram").setLevel(logging.WARNING)
# ─────────────────────────────────────────────────────────────────────────────
# Load environment
# ─────────────────────────────────────────────────────────────────────────────
load_dotenv()
TELEGRAM_BOT_TOKEN: str = os.getenv("TELEGRAM_BOT_TOKEN", "")
GEMINI_CLI_PATH: str = os.getenv("GEMINI_CLI_PATH", "gemini")
GEMINI_WORKING_DIR: str = os.getenv("GEMINI_WORKING_DIR", str(Path.cwd()))
ACP_TIMEOUT: int = int(os.getenv("ACP_TIMEOUT", "120"))
BOT_PASSWORD: str = os.getenv("BOT_PASSWORD", "")
# NOTE: Token validation is intentionally deferred to main() so that
# importing this module (e.g. from chat.py) does NOT trigger sys.exit.
# Ensure the working directory exists (create it if missing)
_work_dir = Path(GEMINI_WORKING_DIR)
if not _work_dir.is_absolute():
_work_dir = Path.cwd() / _work_dir
GEMINI_WORKING_DIR = str(_work_dir)
if not _work_dir.exists():
logger.warning("GEMINI_WORKING_DIR '%s' does not exist – creating it.", GEMINI_WORKING_DIR)
_work_dir.mkdir(parents=True, exist_ok=True)
# ── Shared Constants for Tool Call Updates ──────────────────────────────────
# Emoji map keyed on the "kind" field of tool_call events
KIND_EMOJI: dict[str, str] = {
"read": "📖",
"write": "✏️",
"search": "🔍",
"shell": "⚡",
"think": "🧠",
"exec": "⚡",
"fetch": "🌐",
"list": "📂",
}
# update_types that are internal noise — never surface to user
SILENT_TYPES: set[str] = {
"tool_call_update", # completion events (we show starts only)
"agent_thought_chunk", # internal chain-of-thought
"available_commands_update", # startup handshake
"agent_message_chunk", # handled by on_chunk below
}
# ── Lightweight Cross-Process Lock for cron.json ─────────────────────────────
# Creates a temporary lock directory atomically, working across both Windows
# and Unix without external dependencies (since os.mkdir is atomic).
@contextlib.contextmanager
def cron_lock(timeout: float = 5.0):
lock_path = Path(GEMINI_WORKING_DIR) / "cron.json.lock"
start_time = time.time()
acquired = False
while time.time() - start_time < timeout:
try:
os.mkdir(lock_path)
acquired = True
break
except FileExistsError:
time.sleep(0.05)
except OSError:
break
try:
yield acquired
finally:
if acquired:
try:
os.rmdir(lock_path)
except Exception:
pass
# Scaffold workspace if it's new (creates GEMINI.md, directory structure, starter skills)
# This replaces the old primitive bootstrap that only copied BOOTSTRAP_GEMINI.txt → GEMINI.md.
# Now it creates the full agentic MD system: directories, operational .md files,
# and the memory-agent skill. Identity files (SOUL.md, IDENTITY.md, USER.md, MEMORY.md)
# are NOT created here — the agent creates them interactively during Bootstrap Mode.
from workspace_init import init_workspace
init_workspace(_work_dir)
# Detect if this is a fresh workspace that needs the agent to run bootstrap.
# SOUL.md is created by the agent during interactive Bootstrap Mode — its absence
# means the agent hasn't been configured yet and we need to send a primer prompt
# after the ACP handshake so Gemini reads GEMINI.md automatically.
_NEEDS_BOOTSTRAP = not (_work_dir / "SOUL.md").exists()
if _NEEDS_BOOTSTRAP:
logger.info("Fresh workspace detected (no SOUL.md) — bootstrap primer will be sent on first session.")
# ─────────────────────────────────────────────────────────────────────────────
# ACP Client — manages one persistent gemini --acp subprocess
# ─────────────────────────────────────────────────────────────────────────────
class GeminiACPClient:
"""
Manages the lifecycle of a `gemini --acp` subprocess and provides an
async interface to send prompts and receive responses via JSON-RPC 2.0.
The subprocess is started lazily on the first call to `send_prompt()`.
If the subprocess crashes, it is automatically restarted before the
next call.
Thread-safety: All public methods are coroutines and must be awaited
from the same async event loop. An asyncio.Lock serialises concurrent
Telegram messages so that JSON-RPC IDs are never interleaved.
"""
def __init__(self) -> None:
self._process: Optional[asyncio.subprocess.Process] = None
self._session_id: Optional[str] = None
self._req_id: int = 0 # monotonically increasing JSON-RPC id
self._lock: asyncio.Lock = asyncio.Lock()
self._drain_task: Optional[asyncio.Task] = None # Reference to drain stderr task to prevent GC
self._initialized: bool = False
self._transcript_file: Optional[Path] = None
self._active_req_id: Optional[int] = None
self.private_mode: bool = False
# Bootstrap primer: when the workspace is fresh (no SOUL.md), we send
# an automatic first prompt after the ACP handshake telling Gemini to
# read GEMINI.md and enter Bootstrap Mode. The primer response is cached
# and prepended to the first real user response.
self._bootstrap_response: Optional[str] = None
self._bootstrap_sent: bool = False
# ── Streaming / tool-status callbacks ────────────────────────────────
# Set by send_prompt() before each call; cleared after. Allows the
# Telegram handler to receive live chunk updates and tool notifications
# without tightly coupling GeminiACPClient to Telegram internals.
self._on_chunk: Optional[object] = None # async callable(str)
self._on_tool_call: Optional[object] = None # async callable(method, params)
# ── Private helpers ──────────────────────────────────────────────────────
def _next_id(self) -> int:
"""Return the next unique JSON-RPC request id."""
self._req_id += 1
return self._req_id
async def _send(self, payload: dict) -> None:
"""
Serialize `payload` as a single newline-terminated JSON line and
write it to the subprocess stdin.
ACP uses newline-delimited JSON (NDJSON) over stdio: every message
is one JSON object followed by exactly one newline character `\n`.
"""
if self._process is None or self._process.stdin is None:
raise RuntimeError("ACP process is not running")
line = json.dumps(payload, separators=(",", ":")) + "\n"
logger.debug(">> ACP: %s", line.rstrip())
self._process.stdin.write(line.encode("utf-8"))
await self._process.stdin.drain()
async def _recv_message(self, timeout: float = ACP_TIMEOUT) -> dict:
"""
Read one complete JSON-RPC message from the subprocess stdout.
Because gemini --acp may emit notification messages (progress
updates that have no `id`) before the final response, we loop
until we either see a message that has an `id` field or until
the timeout is reached. Notifications are logged but discarded
here; callers use _recv_response() which handles this properly.
"""
if self._process is None or self._process.stdout is None:
raise RuntimeError("ACP process stdout is not available")
deadline = asyncio.get_event_loop().time() + timeout
while True:
remaining = deadline - asyncio.get_event_loop().time()
if remaining <= 0:
raise asyncio.TimeoutError("Timed out waiting for ACP response")
# asyncio.wait_for will cancel the read after `remaining` seconds
raw_line = await asyncio.wait_for(
self._process.stdout.readline(), timeout=remaining
)
if not raw_line:
raise EOFError("ACP subprocess closed stdout unexpectedly")
line_str = raw_line.decode("utf-8", errors="replace").strip()
if not line_str:
continue # skip blank lines
logger.debug("<< ACP: %s", line_str)
try:
msg = json.loads(line_str)
except json.JSONDecodeError as exc:
logger.warning("ACP sent non-JSON line (ignoring): %s | err: %s", line_str, exc)
continue
return msg
async def _recv_response(self, req_id: int, timeout: float = ACP_TIMEOUT) -> dict:
"""
Consume ACP messages until we receive the response that matches
`req_id`. Notifications (messages without an `id`) are accumulated
as side-channel data and their text fragments are returned so callers
can stream them to Telegram if desired.
Callbacks (set on self before calling):
self._on_chunk(text: str) – called for each new streamed chunk
self._on_tool_call(method, params) – called when a tool is auto-approved
Returns the matched JSON-RPC *result* or raises on *error*.
"""
deadline = asyncio.get_event_loop().time() + timeout
accumulated_text: list[str] = []
while True:
remaining = deadline - asyncio.get_event_loop().time()
if remaining <= 0:
raise asyncio.TimeoutError(
f"Timed out waiting for response to request {req_id}"
)
msg = await self._recv_message(timeout=remaining)
# ── Notification (no id) ──────────────────────────────────────
if "id" not in msg:
method = msg.get("method", "")
params = msg.get("params", {})
# ── session/update: all tool + agent activity arrives here ────
# In YOLO (-y) mode, gemini-cli NEVER sends session/request_permission
# to the client — it auto-approves all tools internally.
# Instead, all activity (text chunks AND tool invocations) arrives
# as session/update notifications with different "sessionUpdate" values.
# We must inspect every update type here, not just agent_message_chunk.
#
# Known sessionUpdate values (discovered from live traffic):
# agent_message_chunk – streamed text fragment
# tool_call_start – tool invocation starting
# tool_call_complete – tool invocation finished
# tool_use – generic tool use event (some CLI versions)
# (any other value) – unknown, log it anyway for discovery
if method == "session/update" and isinstance(params, dict):
update = params.get("update", {})
update_type = update.get("sessionUpdate", "")
if update_type == "agent_message_chunk":
# ── Text streaming chunk ──────────────────────────────
chunk = update.get("content", {}).get("text", "")
if chunk:
accumulated_text.append(chunk)
logger.debug("ACP chunk: %r", chunk)
# ── Feature: live chunk streaming callback ────────
# Fire the on_chunk callback so handle_message can
# edit a placeholder Telegram message in real-time.
# Errors are suppressed so a Telegram API hiccup
# never disrupts the core ACP response loop.
if self._on_chunk is not None:
try:
await self._on_chunk("".join(accumulated_text))
except Exception as _cb_err:
logger.debug("on_chunk callback error (non-fatal): %s", _cb_err)
else:
# ── Non-chunk update: tool invocation or unknown event ─
# In YOLO mode these are the ONLY signals we get for tool
# calls. Log everything to tools.log for the audit trail
# and fire the Telegram tool-status callback.
logger.info("ACP session/update [%s]: %s", update_type, str(update)[:300])
try:
tools_logger.info(
"sessionUpdate=%-35s update=%s",
update_type,
json.dumps(update, separators=(",", ":"), ensure_ascii=False)[:2000],
)
except Exception:
pass # never let logging break the response loop
# ── Feature: tool-status push to Telegram ─────────────
if self._on_tool_call is not None and update_type:
try:
await self._on_tool_call(update_type, update)
except Exception as _cb_err:
logger.debug("on_tool_call callback error (non-fatal): %s", _cb_err)
elif method and method != "session/update":
# ── Any other notification method (log for discovery) ─────
logger.info("ACP notification [%s]: %s", method, str(params)[:300])
try:
tools_logger.info(
"notification=%-40s params=%s",
method,
json.dumps(params, separators=(",", ":"), ensure_ascii=False)[:2000],
)
except Exception:
pass
continue
# ── Server→client REQUEST (has BOTH 'id' AND 'method') ───────────
# gemini-cli sends tool-confirmation requests to the client as
# JSON-RPC requests (not responses), identifiable by the presence
# of a 'method' field. These MUST be checked BEFORE the id==req_id
# check below, because the server may reuse an id that collides with
# our pending prompt request id.
#
# Confirmed approval schema (from live logs):
# result: { "outcome": { "optionId": "<one of the offered options>" } }
# Options offered for session/request_permission:
# proceed_always – allow for entire session
# proceed_once – allow just this once
# cancel – reject
if "method" in msg:
server_req_id = msg.get("id")
server_method = msg.get("method", "")
params = msg.get("params", {})
# Pick the most permissive option offered
options = params.get("options", [])
option_ids = [o.get("optionId", "") for o in options]
chosen = next(
(o for o in ("proceed_always", "proceed_once") if o in option_ids),
option_ids[0] if option_ids else "proceed_always",
)
logger.info(
"Auto-approving server request: method=%s id=%s option=%s",
server_method, server_req_id, chosen,
)
# ── Feature: tool-call audit log ─────────────────────────────
# Write every auto-approved tool invocation to tools.log with
# full params so you have a clean audit trail.
try:
tools_logger.info(
"method=%-40s params=%s",
server_method,
json.dumps(params, separators=(",", ":"), ensure_ascii=False)[:2000],
)
except Exception:
pass # never let logging break the approval flow
# ── Feature: tool-status push to Telegram ─────────────────────
# If a callback is registered, notify the user which tool is
# being invoked. Errors are suppressed (non-fatal).
if self._on_tool_call is not None:
try:
await self._on_tool_call(server_method, params)
except Exception as _cb_err:
logger.debug("on_tool_call callback error (non-fatal): %s", _cb_err)
# Confirmed schema from live logs:
# result.outcome.outcome = "selected" | "cancelled" (discriminator)
# result.outcome.optionId = the chosen optionId string
await self._send({
"jsonrpc": "2.0",
"id": server_req_id,
"result": {
"outcome": {
"outcome": "selected", # discriminator value
"optionId": chosen,
},
},
})
continue
# ── Response for our request ──────────────────────────────────────
# Only pure responses (have 'id', no 'method') reach here.
if msg.get("id") == req_id:
if "error" in msg:
err = msg["error"]
raise RuntimeError(
f"ACP error {err.get('code')}: {err.get('message')}"
)
result = msg.get("result", {})
# Attach any accumulated notification text so callers can use it
if accumulated_text:
result["_notification_text"] = "".join(accumulated_text)
return result
# ── Stale response from a previous request ────────────────────────
logger.debug(
"Ignoring stale response for id %s (waiting for %s)",
msg.get("id"), req_id,
)
# ── ACP Handshake ────────────────────────────────────────────────────────
async def _initialize(self) -> None:
"""
Perform the ACP handshake (2 steps, confirmed by live protocol test):
1. initialize – negotiate protocol version & capabilities
Response includes authMethods (metadata only, ignore)
2. session/new – create a session; REQUIRED params:
cwd (str) working directory
mcpServers (list) MCP servers (can be empty)
NOTE: gemini-cli does NOT support an 'initialized' notification
(-32601 Method not found). Skip it entirely.
Auth is handled automatically from OS-cached credentials.
"""
logger.info("Performing ACP handshake …")
# ── Step 1: initialize ────────────────────────────────────────────
init_id = self._next_id()
await self._send({
"jsonrpc": "2.0",
"id": init_id,
"method": "initialize",
"params": {
"protocolVersion": 1,
"clientInfo": {
"name": "gelegram-telegram-bot",
"version": "1.0.0",
},
"clientCapabilities": {},
},
})
init_result = await self._recv_response(init_id, timeout=90)
# authMethods in the response is metadata only — it lists what auth
# providers are configured on the server. No auth/select call needed;
# no 'initialized' notification needed (gemini-cli returns -32601 for it).
# gemini-cli uses OS-cached credentials (oauth-personal) automatically.
logger.info(
"ACP initialized (version=%s, auth=%s)",
init_result.get("protocolVersion"),
[m.get("id") for m in init_result.get("authMethods", [])],
)
# ── Step 2: create a session ──────────────────────────────────────
# session/new REQUIRES two params (confirmed from gemini-cli source):
# cwd – working directory string (passed to the agent)
# mcpServers – list of MCP servers to connect to (can be empty)
sess_id = self._next_id()
await self._send({
"jsonrpc": "2.0",
"id": sess_id,
"method": "session/new",
"params": {
"cwd": GEMINI_WORKING_DIR,
"mcpServers": [], # no MCP tool servers needed for basic chat
# Trust the working directory so -y (YOLO) mode is not overridden.
# Without this gemini-cli prints:
# "Approval mode overridden to 'default' because the current
# folder is not trusted."
"trustedFolders": [GEMINI_WORKING_DIR],
},
})
sess_result = await self._recv_response(sess_id, timeout=90)
self._session_id = sess_result.get("sessionId") or sess_result.get("id")
logger.info("ACP session created: %s", self._session_id)
# ── Setup Transcript File ─────────────────────────────────────────
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
transcripts_dir = Path(GEMINI_WORKING_DIR) / "transcripts"
transcripts_dir.mkdir(parents=True, exist_ok=True)
self._transcript_file = transcripts_dir / f"session_{timestamp}.txt"
logger.info("Transcript file created: %s", self._transcript_file)
self._initialized = True
# ── Bootstrap Primer ──────────────────────────────────────────────
# On a fresh workspace (no SOUL.md), automatically send a primer
# prompt that tells Gemini to read GEMINI.md and enter Bootstrap Mode.
# This ensures the agent's first interaction with the user already
# has its bootstrap context loaded, instead of giving a generic greeting.
# NOTE: We do a live filesystem check here (not the module-level
# _NEEDS_BOOTSTRAP flag) so that after /reset, if SOUL.md was created
# during a previous session, we don't re-trigger bootstrap.
needs_bootstrap_now = not (_work_dir / "SOUL.md").exists()
if needs_bootstrap_now and not self._bootstrap_sent:
logger.info("Sending bootstrap primer prompt to Gemini …")
primer_id = self._next_id()
await self._send({
"jsonrpc": "2.0",
"id": primer_id,
"method": "session/prompt",
"params": {
"sessionId": self._session_id,
"prompt": [
{
"type": "text",
"text": (
"[SYSTEM] This is an automated bootstrap trigger. "
"Read GEMINI.md in this workspace immediately and follow "
"the instructions under 'First-Run Initialization (Bootstrap Mode)'. "
"SOUL.md does not exist yet — you are in Bootstrap Mode. "
"Greet the user and begin the identity configuration questions "
"as specified in GEMINI.md. Do NOT skip any steps."
),
}
],
},
})
try:
result = await self._recv_response(primer_id, timeout=60)
# Extract and cache the bootstrap response text
primer_text = ""
if "_notification_text" in result and result["_notification_text"].strip():
primer_text = result["_notification_text"].strip()
elif "text" in result and result["text"]:
primer_text = str(result["text"]).strip()
if primer_text:
self._bootstrap_response = primer_text
logger.info("Bootstrap primer response cached (%d chars)", len(primer_text))
else:
logger.warning("Bootstrap primer returned empty response: %s", result)
except Exception as e:
logger.error("Bootstrap primer failed (non-fatal): %s", e)
self._bootstrap_sent = True
# ── Process lifecycle ────────────────────────────────────────────────────
async def _start_process(self) -> None:
"""
Launch `gemini --acp` as an async subprocess.
IMPORTANT (Windows 11):
• asyncio.subprocess requires the ProactorEventLoop on Windows,
which is the default since Python 3.8+.
• .cmd files (npm-installed tools on Windows) cannot be exec'd
directly – they need `cmd /c <file>` to be interpreted by the shell.
• We capture stderr separately so stray diagnostic text from
gemini-cli cannot corrupt the JSON-RPC stream on stdout.
MSA (Microsoft Account / email sign-in) FIX:
• When the Windows service runs under a Microsoft-account user,
the service token may carry a broken or missing USERPROFILE /
APPDATA environment, causing gemini-cli to fail locating
~/.gemini credentials and throwing a login error.
• We build an explicit env dict that inherits the current env but
overrides HOME / USERPROFILE / APPDATA with the real values so
gemini-cli always finds its credential files.
"""
cli = GEMINI_CLI_PATH
# ── Build corrected environment for the gemini subprocess ────────────
# Inherit the full current environment first, then patch the broken
# profile variables that are commonly wrong in MSA service contexts.
subprocess_env = dict(os.environ)
if sys.platform == "win32":
# Detect the real user profile path.
# Priority: USERPROFILE env > registry ProfileList > fallback.
real_profile = subprocess_env.get("USERPROFILE", "")
# System / LocalSystem paths are NOT a valid user profile.
# When we see one, try to resolve the correct path.
_system_profiles = {
r"C:\Windows\system32\config\systemprofile",
r"C:\Windows\SysWOW64\config\systemprofile",
r"C:\Windows\ServiceProfiles\LocalService",
r"C:\Windows\ServiceProfiles\NetworkService",
}
if not real_profile or real_profile in _system_profiles:
# Attempt 1: read from service_userprofile.txt written by
# install_service.ps1 at install time.
profile_hint_file = Path(__file__).resolve().parent / "service_userprofile.txt"
if profile_hint_file.exists():
try:
real_profile = profile_hint_file.read_text(encoding="utf-8").strip()
logger.info(
"MSA fix: loaded USERPROFILE from service_userprofile.txt: %s",
real_profile,
)
except Exception as e:
logger.warning("MSA fix: could not read service_userprofile.txt: %s", e)
if not real_profile or real_profile in _system_profiles:
# Attempt 2: derive from USERNAME env var (works for local accounts)
username = subprocess_env.get("USERNAME", "")
if username and username.lower() not in ("system", "local service", "network service"):
candidate = rf"C:\Users\{username}"
if Path(candidate).is_dir():
real_profile = candidate
logger.info(
"MSA fix: derived USERPROFILE from USERNAME: %s", real_profile
)
if real_profile and real_profile not in _system_profiles:
# Patch all profile-derived env vars so gemini-cli finds ~/.gemini
subprocess_env["USERPROFILE"] = real_profile
subprocess_env["HOME"] = real_profile # used by Node.js / git
subprocess_env["APPDATA"] = str(Path(real_profile) / "AppData" / "Roaming")
subprocess_env["LOCALAPPDATA"] = str(Path(real_profile) / "AppData" / "Local")
logger.info(
"MSA fix: set USERPROFILE=%s APPDATA=%s",
subprocess_env["USERPROFILE"],
subprocess_env["APPDATA"],
)
else:
logger.warning(
"MSA fix: could not determine real USERPROFILE "
"(current value=%r) – gemini auth may fail.",
real_profile,
)
# Windows: .cmd and .bat scripts require the cmd.exe interpreter.
# asyncio.create_subprocess_exec bypasses the shell, so we must
# prefix with cmd /c explicitly.
if sys.platform == "win32" and cli.lower().endswith((".cmd", ".bat")):
exec_args = ["cmd", "/c", cli, "--acp", "-y"]
else:
exec_args = [cli, "--acp", "-y"]
# -y → YOLO mode: auto-approve all tool actions (file edits, shell
# commands, etc.) without prompting the user.
logger.info(
"Starting ACP subprocess: %s (cwd=%s)",
" ".join(exec_args),
GEMINI_WORKING_DIR,
)
self._process = await asyncio.create_subprocess_exec(
*exec_args,
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE, # capture stderr separately
cwd=GEMINI_WORKING_DIR,
env=subprocess_env, # explicitly corrected environment
)
logger.info("ACP subprocess started (pid=%s)", self._process.pid)
# Consume stderr asynchronously so it doesn't fill the OS pipe buffer
# BUG FIX: Store a strong reference to the task so it doesn't get garbage collected mid-execution
self._drain_task = asyncio.create_task(self._drain_stderr(), name="drain-stderr")
async def _drain_stderr(self) -> None:
"""Read and log gemini-cli stderr at WARNING level so it shows in console."""
if self._process is None or self._process.stderr is None:
return
ignore_keywords = [
"conpty_console_list_agent.js",
"getConsoleProcessList",
"Error: AttachConsole failed",
"at Object.<anonymous>",
"at Module._compile",
"at Object..js",
"at Module.load",
"at Module._load",
"at wrapModuleLoad",
"at Module.executeUserEntryPoint",
"at node:internal",
"Node.js v2"
]
while True:
line = await self._process.stderr.readline()
if not line:
break
line_str = line.decode("utf-8", errors="replace").rstrip()
if not line_str:
continue
if any(kw in line_str for kw in ignore_keywords) or line_str.strip() == "^" or line_str.strip() == "var consoleProcessList = getConsoleProcessList(shellPid);":
continue
# Log at WARNING so it's always visible — gemini-cli writes useful
# diagnostics (auth errors, startup failures) to stderr
logger.warning("[gemini-stderr] %s", line_str)
def _is_alive(self) -> bool:
"""Return True if the subprocess is running."""
return self._process is not None and self._process.returncode is None
async def _ensure_running(self) -> None:
"""
Guarantee the subprocess is alive and the ACP handshake has been
completed. If the process is dead (crashed, never started), it is
restarted and re-initialised transparently.
IMPORTANT: Any asyncio.TimeoutError raised by _initialize() (the
ACP handshake, which uses its own 90-second timeouts) is wrapped
into a RuntimeError here. This prevents it from being caught by
the Telegram handler's `except asyncio.TimeoutError` block, which
is reserved exclusively for prompt-level 30-minute timeouts and
would otherwise log a misleading "30 mins passed" error message
on the very first message after a bot restart or cold start.
"""
if not self._is_alive():
logger.info("ACP process is not running – starting …")
self._initialized = False
self._session_id = None
await self._start_process()
try:
await self._initialize()
except asyncio.TimeoutError as exc:
raise RuntimeError(
f"ACP handshake timed out during startup – gemini-cli took too long to "
f"respond. This is a startup failure, not a 30-minute prompt timeout. "
f"Original error: {exc}"
) from exc
elif not self._initialized:
try:
await self._initialize()
except asyncio.TimeoutError as exc:
raise RuntimeError(
f"ACP handshake timed out during re-initialization – gemini-cli took "
f"too long to respond. Original error: {exc}"
) from exc
async def stop(self) -> None:
"""Gracefully terminate the gemini-cli subprocess."""
if self._process is not None and self._is_alive():
logger.info("Terminating ACP subprocess (pid=%s) …", self._process.pid)
try:
self._process.terminate()
await asyncio.wait_for(self._process.wait(), timeout=5)
except asyncio.TimeoutError:
self._process.kill()
logger.info("ACP subprocess terminated.")
self._process = None
self._initialized = False
self._session_id = None
self._active_req_id = None
self.private_mode = False
self._bootstrap_response = None
# Re-check SOUL.md on next session start — if the user completed
# bootstrap before resetting, we don't want to re-trigger it.
self._bootstrap_sent = False
# BUG FIX: Clean up the background stderr drain task properly
if self._drain_task:
self._drain_task.cancel()
try:
await self._drain_task
except asyncio.CancelledError:
pass
except Exception as e:
logger.warning("Error awaiting stderr drain task cleanup: %s", e)
self._drain_task = None
async def cancel_active_request(self) -> bool:
"""Attempt to cancel the currently running request gracefully without killing the process."""
if not self._is_alive() or self._active_req_id is None:
return False
logger.info("Sending cancel request for req_id=%s", self._active_req_id)
# JSON-RPC standard cancellation notification
await self._send({
"jsonrpc": "2.0",
"method": "$/cancelRequest",
"params": {
"id": self._active_req_id
}
})
return True
# ── Public API ───────────────────────────────────────────────────────────
async def send_prompt(
self,
text: str,
user_name: str = "user",
on_timeout_callback=None,
on_chunk=None,
on_tool_call=None,
) -> str:
"""
Send `text` to gemini-cli and return the full text response.
This method is serialised by an asyncio.Lock so that concurrent
Telegram messages do not interleave JSON-RPC ids on the stdio stream.
If a bootstrap primer response was cached (from a fresh workspace),
it is returned instead of sending a new prompt — this ensures the
user sees the bootstrap greeting on their very first message.
Raises:
RuntimeError – ACP protocol error returned by gemini-cli
asyncio.TimeoutError – No response within ACP_TIMEOUT seconds
Exception – Subprocess crashed or other unexpected error
"""
async with self._lock:
# ── Register per-call streaming / tool callbacks ───────────────
# These are stored on self so _recv_response (which has no direct
# reference to the caller) can invoke them without coupling.
# They are always cleared in the finally block below.
self._on_chunk = on_chunk
self._on_tool_call = on_tool_call
try:
return await self._send_prompt_inner(
text, user_name, on_timeout_callback
)
except Exception as e:
# BUG FIX: Restart the subprocess on timeout or communication failure to prevent channel desync
logger.error("Error during prompt communication: %s. Force-stopping ACP subprocess to prevent desync.", e)
try:
await self.stop()
except Exception as stop_err:
logger.error("Failed to stop ACP subprocess on error: %s", stop_err)
raise
finally:
# Always clear callbacks so they don't leak to the next call
self._on_chunk = None
self._on_tool_call = None
async def _send_prompt_inner(
self,
text: str,
user_name: str = "user",
on_timeout_callback=None,
) -> str:
"""
Internal implementation of send_prompt, called after callbacks are
registered. Must be called while self._lock is already held by the
caller (send_prompt acquires and holds it for the full call).
"""
# Restart process if it crashed since the last call
await self._ensure_running()
# ── Bootstrap primer intercept ────────────────────────────────────
# If we cached a bootstrap primer response, return it for the
# user's very first message so they see the identity setup
# questions immediately. The primer already primed the Gemini
# session context, so subsequent messages flow normally.
# BUG FIX: Avoid consuming bootstrap response on system warm-up calls (user_name == "system")
if self._bootstrap_response is not None and user_name != "system":
cached = self._bootstrap_response
self._bootstrap_response = None # consume once
logger.info("Returning cached bootstrap primer response to user")
# Still log the user message + bootstrap response to transcript
if self._transcript_file and not self.private_mode:
time_str = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(self._transcript_file, "a", encoding="utf-8") as f:
f.write(f"{time_str} : {user_name} : {text}\n")
f.write(f"{time_str} : gemini : {cached}\n")
# Forward the user's actual text to Gemini so the agent has
# it in its context for the next turn (non-blocking fire-and-forget
# would be complex here — instead we send it and use the response
# ONLY if the bootstrap response was empty for some reason).
prompt_id = self._next_id()
self._active_req_id = prompt_id
await self._send({
"jsonrpc": "2.0",
"id": prompt_id,
"method": "session/prompt",
"params": {
"sessionId": self._session_id,
"prompt": [
{"type": "text", "text": text}
],
},
})
try:
followup = await self._recv_response(prompt_id, timeout=ACP_TIMEOUT)
# Extract followup text in case bootstrap primer + user text
# triggers additional relevant output
followup_text = ""
if "_notification_text" in followup and followup["_notification_text"].strip():
followup_text = followup["_notification_text"].strip()
elif "text" in followup and followup["text"]:
followup_text = str(followup["text"]).strip()
if followup_text:
# Combine: show bootstrap greeting + any followup
cached = cached + "\n\n" + followup_text
logger.info("Appended followup response (%d chars)", len(followup_text))
except Exception as e:
logger.warning("Followup after bootstrap primer failed (non-fatal): %s", e)
finally:
self._active_req_id = None
return cached
# Log user message to transcript
if self._transcript_file and not self.private_mode:
time_str = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(self._transcript_file, "a", encoding="utf-8") as f:
f.write(f"{time_str} : {user_name} : {text}\n")
prompt_id = self._next_id()
self._active_req_id = prompt_id
await self._send({
"jsonrpc": "2.0",
"id": prompt_id,
"method": "session/prompt", # confirmed method name in gemini-cli ACP
"params": {
"sessionId": self._session_id,
"prompt": [
{"type": "text", "text": text}
],
},
})
try:
result = await self._recv_response(prompt_id, timeout=ACP_TIMEOUT)
except asyncio.TimeoutError:
if on_timeout_callback:
try:
await on_timeout_callback()
except Exception as e:
logger.error("Error in on_timeout_callback: %s", e)
# Continue waiting with a generous 30-minute timeout for heavy tasks
result = await self._recv_response(prompt_id, timeout=1800)
finally:
self._active_req_id = None