codex-telegram-bridge 0.9.2__tar.gz → 0.9.4__tar.gz
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.
- {codex_telegram_bridge-0.9.2/codex_telegram_bridge.egg-info → codex_telegram_bridge-0.9.4}/PKG-INFO +27 -1
- {codex_telegram_bridge-0.9.2 → codex_telegram_bridge-0.9.4}/README.md +26 -0
- codex_telegram_bridge-0.9.4/codex_conpty_attach.py +455 -0
- {codex_telegram_bridge-0.9.2 → codex_telegram_bridge-0.9.4}/codex_repl_host_windows.py +175 -2
- {codex_telegram_bridge-0.9.2 → codex_telegram_bridge-0.9.4/codex_telegram_bridge.egg-info}/PKG-INFO +27 -1
- {codex_telegram_bridge-0.9.2 → codex_telegram_bridge-0.9.4}/codex_telegram_bridge.egg-info/SOURCES.txt +2 -0
- {codex_telegram_bridge-0.9.2 → codex_telegram_bridge-0.9.4}/codex_telegram_bridge.egg-info/top_level.txt +1 -0
- {codex_telegram_bridge-0.9.2 → codex_telegram_bridge-0.9.4}/pyproject.toml +3 -2
- {codex_telegram_bridge-0.9.2 → codex_telegram_bridge-0.9.4}/tests/test_bridge.py +1 -1
- codex_telegram_bridge-0.9.4/tests/test_codex_conpty_attach.py +170 -0
- {codex_telegram_bridge-0.9.2 → codex_telegram_bridge-0.9.4}/LICENSE +0 -0
- {codex_telegram_bridge-0.9.2 → codex_telegram_bridge-0.9.4}/agent_runtime/__init__.py +0 -0
- {codex_telegram_bridge-0.9.2 → codex_telegram_bridge-0.9.4}/agent_runtime/adapters/__init__.py +0 -0
- {codex_telegram_bridge-0.9.2 → codex_telegram_bridge-0.9.4}/agent_runtime/adapters/base.py +0 -0
- {codex_telegram_bridge-0.9.2 → codex_telegram_bridge-0.9.4}/agent_runtime/adapters/codex_repl.py +0 -0
- {codex_telegram_bridge-0.9.2 → codex_telegram_bridge-0.9.4}/agent_runtime/approvals.py +0 -0
- {codex_telegram_bridge-0.9.2 → codex_telegram_bridge-0.9.4}/agent_runtime/capabilities.py +0 -0
- {codex_telegram_bridge-0.9.2 → codex_telegram_bridge-0.9.4}/agent_runtime/locks.py +0 -0
- {codex_telegram_bridge-0.9.2 → codex_telegram_bridge-0.9.4}/agent_runtime/transport.py +0 -0
- {codex_telegram_bridge-0.9.2 → codex_telegram_bridge-0.9.4}/agent_runtime/types.py +0 -0
- {codex_telegram_bridge-0.9.2 → codex_telegram_bridge-0.9.4}/bridge_setup.py +0 -0
- {codex_telegram_bridge-0.9.2 → codex_telegram_bridge-0.9.4}/bridge_watchdog.py +0 -0
- {codex_telegram_bridge-0.9.2 → codex_telegram_bridge-0.9.4}/codex_audio_transcribe.py +0 -0
- {codex_telegram_bridge-0.9.2 → codex_telegram_bridge-0.9.4}/codex_repl_bridge.py +0 -0
- {codex_telegram_bridge-0.9.2 → codex_telegram_bridge-0.9.4}/codex_telegram_bridge.egg-info/dependency_links.txt +0 -0
- {codex_telegram_bridge-0.9.2 → codex_telegram_bridge-0.9.4}/codex_telegram_bridge.egg-info/entry_points.txt +0 -0
- {codex_telegram_bridge-0.9.2 → codex_telegram_bridge-0.9.4}/codex_telegram_bridge.egg-info/requires.txt +0 -0
- {codex_telegram_bridge-0.9.2 → codex_telegram_bridge-0.9.4}/setup.cfg +0 -0
- {codex_telegram_bridge-0.9.2 → codex_telegram_bridge-0.9.4}/telegram_agent_bridge.py +0 -0
- {codex_telegram_bridge-0.9.2 → codex_telegram_bridge-0.9.4}/tests/test_agent_runtime.py +0 -0
- {codex_telegram_bridge-0.9.2 → codex_telegram_bridge-0.9.4}/tests/test_public_export.py +0 -0
- {codex_telegram_bridge-0.9.2 → codex_telegram_bridge-0.9.4}/tests/test_repl_bridge.py +0 -0
- {codex_telegram_bridge-0.9.2 → codex_telegram_bridge-0.9.4}/tests/test_repl_transport.py +0 -0
- {codex_telegram_bridge-0.9.2 → codex_telegram_bridge-0.9.4}/tests/test_setup_wizard.py +0 -0
- {codex_telegram_bridge-0.9.2 → codex_telegram_bridge-0.9.4}/tests/test_watchdog.py +0 -0
{codex_telegram_bridge-0.9.2/codex_telegram_bridge.egg-info → codex_telegram_bridge-0.9.4}/PKG-INFO
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: codex-telegram-bridge
|
|
3
|
-
Version: 0.9.
|
|
3
|
+
Version: 0.9.4
|
|
4
4
|
Summary: Control a live Codex CLI session from Telegram.
|
|
5
5
|
Author: Kang Daejong
|
|
6
6
|
License: MIT
|
|
@@ -671,6 +671,32 @@ If more than one new Codex JSONL session appears during startup, the host stops
|
|
|
671
671
|
instead of guessing. A restarted host uses a new generation and capability, so
|
|
672
672
|
an old bridge cannot redirect queued input into the new session.
|
|
673
673
|
|
|
674
|
+
### Attach window — watch and type from another terminal (Windows)
|
|
675
|
+
|
|
676
|
+
A foreground host shows its own TUI. A host that runs hidden — a scheduled task,
|
|
677
|
+
a detached launcher — shows it nowhere, and resuming the session in a second
|
|
678
|
+
terminal would only share the conversation file, not the screen: prompts sent
|
|
679
|
+
from Telegram never appear there.
|
|
680
|
+
|
|
681
|
+
The attach client subscribes to the append-only raw stream the host already tees
|
|
682
|
+
to disk and forwards your keystrokes back through the host IPC, so a single
|
|
683
|
+
window both shows the live screen and types into it:
|
|
684
|
+
|
|
685
|
+
```powershell
|
|
686
|
+
python -m codex_conpty_attach
|
|
687
|
+
```
|
|
688
|
+
|
|
689
|
+
`Ctrl+]` detaches. `Ctrl+C` is forwarded to Codex rather than closing the window.
|
|
690
|
+
`--replay 0` starts from now instead of repainting recent output, `--read-only`
|
|
691
|
+
watches without sending anything, and `--columns/--rows` match a host that was
|
|
692
|
+
started with non-default dimensions.
|
|
693
|
+
|
|
694
|
+
The client never owns the pseudoconsole — the host keeps it — so attaching and
|
|
695
|
+
detaching cannot disturb the running session. Two requirements: the host must be
|
|
696
|
+
writing the raw stream (on by default; `CODEX_CONPTY_LIVE_RAW=""` disables it),
|
|
697
|
+
and the window must be the same size as the host (`--columns 120 --rows 40` by
|
|
698
|
+
default, matching the host defaults) or redrawn lines will not line up.
|
|
699
|
+
|
|
674
700
|
Token safety rule: BotFather shows the token in Telegram, but you should copy it
|
|
675
701
|
from BotFather and paste it into the local setup wizard in your terminal. In
|
|
676
702
|
Telegram, send only `/start` or normal prompts to your bot.
|
|
@@ -644,6 +644,32 @@ If more than one new Codex JSONL session appears during startup, the host stops
|
|
|
644
644
|
instead of guessing. A restarted host uses a new generation and capability, so
|
|
645
645
|
an old bridge cannot redirect queued input into the new session.
|
|
646
646
|
|
|
647
|
+
### Attach window — watch and type from another terminal (Windows)
|
|
648
|
+
|
|
649
|
+
A foreground host shows its own TUI. A host that runs hidden — a scheduled task,
|
|
650
|
+
a detached launcher — shows it nowhere, and resuming the session in a second
|
|
651
|
+
terminal would only share the conversation file, not the screen: prompts sent
|
|
652
|
+
from Telegram never appear there.
|
|
653
|
+
|
|
654
|
+
The attach client subscribes to the append-only raw stream the host already tees
|
|
655
|
+
to disk and forwards your keystrokes back through the host IPC, so a single
|
|
656
|
+
window both shows the live screen and types into it:
|
|
657
|
+
|
|
658
|
+
```powershell
|
|
659
|
+
python -m codex_conpty_attach
|
|
660
|
+
```
|
|
661
|
+
|
|
662
|
+
`Ctrl+]` detaches. `Ctrl+C` is forwarded to Codex rather than closing the window.
|
|
663
|
+
`--replay 0` starts from now instead of repainting recent output, `--read-only`
|
|
664
|
+
watches without sending anything, and `--columns/--rows` match a host that was
|
|
665
|
+
started with non-default dimensions.
|
|
666
|
+
|
|
667
|
+
The client never owns the pseudoconsole — the host keeps it — so attaching and
|
|
668
|
+
detaching cannot disturb the running session. Two requirements: the host must be
|
|
669
|
+
writing the raw stream (on by default; `CODEX_CONPTY_LIVE_RAW=""` disables it),
|
|
670
|
+
and the window must be the same size as the host (`--columns 120 --rows 40` by
|
|
671
|
+
default, matching the host defaults) or redrawn lines will not line up.
|
|
672
|
+
|
|
647
673
|
Token safety rule: BotFather shows the token in Telegram, but you should copy it
|
|
648
674
|
from BotFather and paste it into the local setup wizard in your terminal. In
|
|
649
675
|
Telegram, send only `/start` or normal prompts to your bot.
|
|
@@ -0,0 +1,455 @@
|
|
|
1
|
+
"""codex ConPTY attach 클라이언트 — 보이고 입력도 되는 tmux 패리티 창 (T-260722-076).
|
|
2
|
+
|
|
3
|
+
왜 (요건 = tmux 패리티: 보이고 입력도 되는 터미널, 로그 표시가 아니다):
|
|
4
|
+
읽기전용 tail 뷰어는 화면을 반복 재그리기하는 스트림에서 제어열을 걷어내고 줄
|
|
5
|
+
단위로 흘린다 — 그래서 같은 자리를 고쳐 그린 조각이 아래로 쌓여 글자가 뭉갠다.
|
|
6
|
+
게다가 tail 은 입력을 못 보낸다. 표시 방식 자체가 요건 미달이었다.
|
|
7
|
+
|
|
8
|
+
이 클라이언트는 PTY 를 소유하지 않는다. 헤드리스 호스트가 계속 소유하고 여기서는
|
|
9
|
+
표시 = 호스트가 흘리는 append-only raw 파일(LiveRawSink, crb 0.9.3)을 구독해
|
|
10
|
+
제어열을 살린 채 콘솔로 그대로 흘린다(VT 패스스루).
|
|
11
|
+
입력 = 호스트 named-pipe 의 key op — 브릿지가 이미 쓰는 인증 경로 그대로.
|
|
12
|
+
둘 다 기성 경로라 호스트 모듈·site-packages 무변경이다. 두 번째 콘솔이 PTY 를
|
|
13
|
+
빼앗는 선점 문제도 성립하지 않는다.
|
|
14
|
+
|
|
15
|
+
화면 크기: 헤드리스 호스트는 자기 stdout 에 콘솔이 없어 --columns/--rows 기본값으로
|
|
16
|
+
ConPTY 를 만든다(codex_repl_host_windows.console_size 의 폴백 = 120x40). 창 크기가
|
|
17
|
+
그와 다르면 TUI 가 그린 줄이 어긋나므로 시작할 때 맞춘다.
|
|
18
|
+
|
|
19
|
+
주입 마커: 호스트는 텔레그램 주입을 raw 파일에만 한 줄 남긴다(무에코 설계 보완).
|
|
20
|
+
그 줄은 TUI 가 그린 화면이 아니므로 그대로 뿌리면 화면을 헤집는다 — 여기서 걷어낸다.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import argparse
|
|
26
|
+
import json
|
|
27
|
+
import os
|
|
28
|
+
import re
|
|
29
|
+
import secrets
|
|
30
|
+
import sys
|
|
31
|
+
import time
|
|
32
|
+
from pathlib import Path
|
|
33
|
+
|
|
34
|
+
SCHEMA = 1
|
|
35
|
+
|
|
36
|
+
# 호스트 argparse 기본값. 헤드리스라 console_size() 가 폴백해 이 값이 실제 ConPTY 크기가 된다.
|
|
37
|
+
DEFAULT_COLUMNS = 120
|
|
38
|
+
DEFAULT_ROWS = 40
|
|
39
|
+
|
|
40
|
+
# LiveRawSink.note() 가 쓰는 형식: "\r\n[YYYY-MM-DD HH:MM:SS] <text>\r\n"
|
|
41
|
+
MARKER_RE = re.compile(rb"\r\n\[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\][^\r\n]*\r\n")
|
|
42
|
+
MARKER_HEAD_TEMPLATE = "\r\n[dddd-dd-dd dd:dd:dd] "
|
|
43
|
+
MAX_CARRY = 4096
|
|
44
|
+
|
|
45
|
+
DETACH_KEY = "\x1d" # Ctrl+] — Ctrl+C 는 codex 로 넘겨야 하므로 탈출키를 따로 둔다.
|
|
46
|
+
|
|
47
|
+
# 구호스트가 프레임을 못 알아먹었을 때만 공백 폴백으로 내려간다.
|
|
48
|
+
SPACE_FALLBACK_ERRORS = {"invalid_frame", "unsupported_operation"}
|
|
49
|
+
|
|
50
|
+
# 스캔코드(getwch 가 \x00/\xe0 뒤에 주는 두 번째 문자) → 호스트 key 이름.
|
|
51
|
+
SCAN_KEYS = {
|
|
52
|
+
"H": "Up",
|
|
53
|
+
"P": "Down",
|
|
54
|
+
"K": "Left",
|
|
55
|
+
"M": "Right",
|
|
56
|
+
"G": "Home",
|
|
57
|
+
"O": "End",
|
|
58
|
+
"S": "Delete",
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
# 호스트 encode_key 가 이름으로만 받는 문자들. key 값을 strip() 하므로 공백류는 이름 필수.
|
|
62
|
+
NAMED_CHARS = {
|
|
63
|
+
"\r": "Enter",
|
|
64
|
+
"\n": "Enter",
|
|
65
|
+
"\t": "Tab",
|
|
66
|
+
"\x1b": "Escape",
|
|
67
|
+
"\x08": "Backspace",
|
|
68
|
+
"\x7f": "Backspace",
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _head_prefix_ok(rest: bytes) -> bool:
|
|
73
|
+
"""rest 가 마커 머리("\\r\\n[YYYY-MM-DD HH:MM:SS] ")의 접두사와 모순되지 않는가."""
|
|
74
|
+
|
|
75
|
+
for index, byte in enumerate(rest[: len(MARKER_HEAD_TEMPLATE)]):
|
|
76
|
+
expected = MARKER_HEAD_TEMPLATE[index]
|
|
77
|
+
char = chr(byte)
|
|
78
|
+
if expected == "d":
|
|
79
|
+
if not char.isdigit():
|
|
80
|
+
return False
|
|
81
|
+
elif char != expected:
|
|
82
|
+
return False
|
|
83
|
+
return True
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def strip_markers(data: bytes, carry: bytes = b"", max_carry: int = MAX_CARRY) -> tuple[bytes, bytes]:
|
|
87
|
+
"""주입 마커 줄을 걷어낸 (표시할 바이트, 다음 청크로 넘길 carry) 를 돌려준다.
|
|
88
|
+
|
|
89
|
+
마커가 청크 경계에서 잘릴 수 있으므로, 마커가 될 수 있는 꼬리는 carry 로 보류한다.
|
|
90
|
+
보류가 max_carry 를 넘으면 마커가 아니라고 보고 흘려보낸다(화면이 멎지 않게).
|
|
91
|
+
"""
|
|
92
|
+
|
|
93
|
+
buffer = carry + data
|
|
94
|
+
out = bytearray()
|
|
95
|
+
index = 0
|
|
96
|
+
while True:
|
|
97
|
+
start = buffer.find(b"\r\n[", index)
|
|
98
|
+
if start == -1:
|
|
99
|
+
out += buffer[index:]
|
|
100
|
+
return bytes(out), b""
|
|
101
|
+
|
|
102
|
+
match = MARKER_RE.match(buffer, start)
|
|
103
|
+
if match:
|
|
104
|
+
out += buffer[index:start]
|
|
105
|
+
index = match.end()
|
|
106
|
+
continue
|
|
107
|
+
|
|
108
|
+
rest = buffer[start:]
|
|
109
|
+
unterminated = b"\r\n" not in rest[2:]
|
|
110
|
+
if unterminated and _head_prefix_ok(rest) and len(rest) < max_carry:
|
|
111
|
+
out += buffer[index:start]
|
|
112
|
+
return bytes(out), bytes(rest)
|
|
113
|
+
|
|
114
|
+
# 마커가 아니다 — 여는 "\r\n[" 를 그대로 내보내고 그 뒤에서 다시 찾는다.
|
|
115
|
+
out += buffer[index : start + 3]
|
|
116
|
+
index = start + 3
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def map_key(char: str, scan: str = "") -> tuple[str, str]:
|
|
120
|
+
"""콘솔에서 읽은 키 → (동작, 호스트 key 이름).
|
|
121
|
+
|
|
122
|
+
동작: key(그대로 전송) / space(호스트 세대에 따라 경로가 갈림) / detach(창 닫기) / ignore.
|
|
123
|
+
"""
|
|
124
|
+
|
|
125
|
+
if scan:
|
|
126
|
+
name = SCAN_KEYS.get(scan, "")
|
|
127
|
+
return ("key", name) if name else ("ignore", "")
|
|
128
|
+
if char == DETACH_KEY:
|
|
129
|
+
return ("detach", "")
|
|
130
|
+
if char == " ":
|
|
131
|
+
# 공백은 이름으로만 보낼 수 있다 — 호스트 encode_key 가 key 값을 strip() 해서
|
|
132
|
+
# " " 는 빈 문자열이 된다. 이름 지원은 0.9.4 부터라 구호스트 폴백이 따로 있다.
|
|
133
|
+
return ("space", "space")
|
|
134
|
+
if char in NAMED_CHARS:
|
|
135
|
+
return ("key", NAMED_CHARS[char])
|
|
136
|
+
if len(char) == 1:
|
|
137
|
+
return ("key", char)
|
|
138
|
+
return ("ignore", "")
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def build_request(descriptor: dict, op: str, **fields) -> dict:
|
|
142
|
+
"""호스트가 검증하는 형식 그대로의 요청 프레임."""
|
|
143
|
+
|
|
144
|
+
request = {
|
|
145
|
+
"schema": SCHEMA,
|
|
146
|
+
"request_id": secrets.token_hex(8),
|
|
147
|
+
"generation": str(descriptor.get("generation", "")),
|
|
148
|
+
"capability": str(descriptor.get("capability", "")),
|
|
149
|
+
"op": op,
|
|
150
|
+
}
|
|
151
|
+
request.update(fields)
|
|
152
|
+
return request
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def load_descriptor(path: Path) -> dict:
|
|
156
|
+
descriptor = json.loads(path.read_text(encoding="utf-8"))
|
|
157
|
+
if descriptor.get("schema") != SCHEMA:
|
|
158
|
+
raise SystemExit(f"host descriptor schema mismatch: {descriptor.get('schema')!r}")
|
|
159
|
+
for field in ("pipe_name", "capability", "generation"):
|
|
160
|
+
if not descriptor.get(field):
|
|
161
|
+
raise SystemExit(f"host descriptor is missing {field}")
|
|
162
|
+
return descriptor
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def pipe_request(pipe_name: str, request: dict, timeout_ms: int = 1500) -> dict:
|
|
166
|
+
"""호스트 named pipe 로 한 프레임 왕복. 브릿지 _pipe_request 와 같은 계약이다.
|
|
167
|
+
|
|
168
|
+
호스트는 요청 1개마다 파이프 인스턴스를 새로 만들고 인스턴스는 1개뿐이라,
|
|
169
|
+
연결이 안 잡히는 구간만 재시도한다 — 쓰기 뒤에는 절대 재시도하지 않는다.
|
|
170
|
+
"""
|
|
171
|
+
|
|
172
|
+
import ctypes
|
|
173
|
+
|
|
174
|
+
wait_named_pipe = ctypes.windll.kernel32.WaitNamedPipeW
|
|
175
|
+
wait_named_pipe.argtypes = [ctypes.c_wchar_p, ctypes.c_uint32]
|
|
176
|
+
wait_named_pipe.restype = ctypes.c_int
|
|
177
|
+
|
|
178
|
+
encoded = (json.dumps(request, ensure_ascii=False, separators=(",", ":")) + "\n").encode("utf-8")
|
|
179
|
+
deadline = time.monotonic() + timeout_ms / 1000.0
|
|
180
|
+
|
|
181
|
+
handle = None
|
|
182
|
+
while handle is None:
|
|
183
|
+
remaining = int((deadline - time.monotonic()) * 1000)
|
|
184
|
+
if remaining <= 0:
|
|
185
|
+
raise TimeoutError("ConPTY host IPC is unavailable")
|
|
186
|
+
if not wait_named_pipe(pipe_name, remaining):
|
|
187
|
+
time.sleep(0.01)
|
|
188
|
+
continue
|
|
189
|
+
try:
|
|
190
|
+
handle = open(pipe_name, "r+b", buffering=0)
|
|
191
|
+
except OSError:
|
|
192
|
+
time.sleep(0.01)
|
|
193
|
+
|
|
194
|
+
with handle:
|
|
195
|
+
handle.write(encoded)
|
|
196
|
+
handle.flush()
|
|
197
|
+
raw = handle.readline()
|
|
198
|
+
|
|
199
|
+
response = json.loads(raw.decode("utf-8"))
|
|
200
|
+
if response.get("request_id") != request["request_id"]:
|
|
201
|
+
raise RuntimeError("ConPTY host IPC response id mismatch")
|
|
202
|
+
return response
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
class ConsoleMode:
|
|
206
|
+
"""VT 패스스루 + 원시 입력으로 콘솔을 바꾸고, 나갈 때 원상복구한다."""
|
|
207
|
+
|
|
208
|
+
ENABLE_PROCESSED_OUTPUT = 0x0001
|
|
209
|
+
ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004
|
|
210
|
+
ENABLE_PROCESSED_INPUT = 0x0001
|
|
211
|
+
ENABLE_LINE_INPUT = 0x0002
|
|
212
|
+
ENABLE_ECHO_INPUT = 0x0004
|
|
213
|
+
|
|
214
|
+
def __init__(self) -> None:
|
|
215
|
+
import ctypes
|
|
216
|
+
|
|
217
|
+
self.kernel32 = ctypes.windll.kernel32
|
|
218
|
+
self.stdout_handle = self.kernel32.GetStdHandle(-11)
|
|
219
|
+
self.stdin_handle = self.kernel32.GetStdHandle(-10)
|
|
220
|
+
self.saved_out = None
|
|
221
|
+
self.saved_in = None
|
|
222
|
+
self.saved_cp = None
|
|
223
|
+
|
|
224
|
+
def _mode(self, handle):
|
|
225
|
+
import ctypes
|
|
226
|
+
|
|
227
|
+
mode = ctypes.c_uint32()
|
|
228
|
+
if not self.kernel32.GetConsoleMode(handle, ctypes.byref(mode)):
|
|
229
|
+
return None
|
|
230
|
+
return mode.value
|
|
231
|
+
|
|
232
|
+
def __enter__(self) -> "ConsoleMode":
|
|
233
|
+
self.saved_out = self._mode(self.stdout_handle)
|
|
234
|
+
self.saved_in = self._mode(self.stdin_handle)
|
|
235
|
+
self.saved_cp = self.kernel32.GetConsoleOutputCP()
|
|
236
|
+
|
|
237
|
+
if self.saved_out is not None:
|
|
238
|
+
self.kernel32.SetConsoleMode(
|
|
239
|
+
self.stdout_handle,
|
|
240
|
+
self.saved_out | self.ENABLE_PROCESSED_OUTPUT | self.ENABLE_VIRTUAL_TERMINAL_PROCESSING,
|
|
241
|
+
)
|
|
242
|
+
if self.saved_in is not None:
|
|
243
|
+
# Ctrl+C 를 codex 로 넘겨야 하므로 콘솔이 가로채지 않게 한다.
|
|
244
|
+
self.kernel32.SetConsoleMode(
|
|
245
|
+
self.stdin_handle,
|
|
246
|
+
self.saved_in
|
|
247
|
+
& ~(self.ENABLE_PROCESSED_INPUT | self.ENABLE_LINE_INPUT | self.ENABLE_ECHO_INPUT),
|
|
248
|
+
)
|
|
249
|
+
self.kernel32.SetConsoleOutputCP(65001) # raw 는 UTF-8 이라 한글이 깨지지 않게
|
|
250
|
+
return self
|
|
251
|
+
|
|
252
|
+
def __exit__(self, *exc) -> None:
|
|
253
|
+
if self.saved_out is not None:
|
|
254
|
+
self.kernel32.SetConsoleMode(self.stdout_handle, self.saved_out)
|
|
255
|
+
if self.saved_in is not None:
|
|
256
|
+
self.kernel32.SetConsoleMode(self.stdin_handle, self.saved_in)
|
|
257
|
+
if self.saved_cp:
|
|
258
|
+
self.kernel32.SetConsoleOutputCP(self.saved_cp)
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def resize_console(columns: int, rows: int) -> str:
|
|
262
|
+
"""콘솔을 호스트 ConPTY 크기에 맞춘다. 실패해도 진행하고 사유만 돌려준다."""
|
|
263
|
+
|
|
264
|
+
try:
|
|
265
|
+
current = os.get_terminal_size()
|
|
266
|
+
except OSError:
|
|
267
|
+
current = None
|
|
268
|
+
if current and current.columns == columns and current.lines == rows:
|
|
269
|
+
return ""
|
|
270
|
+
os.system(f"mode con: cols={columns} lines={rows}")
|
|
271
|
+
try:
|
|
272
|
+
after = os.get_terminal_size()
|
|
273
|
+
except OSError:
|
|
274
|
+
return ""
|
|
275
|
+
if after.columns != columns or after.lines != rows:
|
|
276
|
+
return f"창 크기 {after.columns}x{after.lines} != 호스트 {columns}x{rows} — 창을 키우거나 글꼴을 줄이면 줄 어긋남이 사라집니다."
|
|
277
|
+
return ""
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def default_raw_path() -> Path:
|
|
281
|
+
base = os.environ.get("CODEX_CONPTY_LIVE_RAW")
|
|
282
|
+
if base:
|
|
283
|
+
return Path(base)
|
|
284
|
+
root = os.environ.get("LOCALAPPDATA") or os.environ.get("USERPROFILE") or "."
|
|
285
|
+
return Path(root) / "codex-telegram-bridge" / "conpty-live.raw"
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def default_state_path() -> Path:
|
|
289
|
+
base = os.environ.get("CRB_CONPTY_STATE_PATH")
|
|
290
|
+
if base:
|
|
291
|
+
return Path(base)
|
|
292
|
+
root = os.environ.get("LOCALAPPDATA") or os.environ.get("USERPROFILE") or "."
|
|
293
|
+
return Path(root) / "codex-telegram-bridge" / "repl-host.json"
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def send_key(descriptor: dict, name: str) -> dict:
|
|
297
|
+
return pipe_request(str(descriptor["pipe_name"]), build_request(descriptor, "key", key=name))
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def space_request(descriptor: dict, native: bool) -> dict:
|
|
301
|
+
"""공백 1칸 요청 프레임.
|
|
302
|
+
|
|
303
|
+
native = 0.9.4+ 호스트. encode_key 이름 맵에 "space" 가 있어 키 하나로 끝난다.
|
|
304
|
+
폴백 = 0.9.3 이하 호스트. 이름이 없어 key op 로는 공백을 못 보낸다. paste op 는
|
|
305
|
+
submit 프레임을 반드시 덧붙이므로, 터미널이 버리는 NUL 을 submit 으로 써서
|
|
306
|
+
화면에 영향을 남기지 않고 공백만 넣는다. 대신 프레임 간 지연을 문다.
|
|
307
|
+
"""
|
|
308
|
+
|
|
309
|
+
if native:
|
|
310
|
+
return build_request(descriptor, "key", key="space")
|
|
311
|
+
return build_request(
|
|
312
|
+
descriptor, "paste", text=" ", clear_before=False, submit_key="\x00", enter_count=1
|
|
313
|
+
)
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def space_fallback_needed(response: dict) -> bool:
|
|
317
|
+
"""구호스트라 native 공백이 거부된 것인가.
|
|
318
|
+
|
|
319
|
+
호스트가 살아 있는데 프레임을 못 알아먹은 경우에만 폴백한다. child_not_running 같은
|
|
320
|
+
다른 실패까지 폴백하면 진짜 고장을 공백 우회로 덮어버린다.
|
|
321
|
+
"""
|
|
322
|
+
|
|
323
|
+
if response.get("ok"):
|
|
324
|
+
return False
|
|
325
|
+
return str(response.get("error", "")) in SPACE_FALLBACK_ERRORS
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def send_space(descriptor: dict, native: bool) -> tuple[dict, bool]:
|
|
329
|
+
"""(응답, 앞으로도 native 를 쓸지). 한 번 거부되면 그 세션 내내 폴백을 쓴다."""
|
|
330
|
+
|
|
331
|
+
pipe_name = str(descriptor["pipe_name"])
|
|
332
|
+
response = pipe_request(pipe_name, space_request(descriptor, native))
|
|
333
|
+
if native and space_fallback_needed(response):
|
|
334
|
+
return pipe_request(pipe_name, space_request(descriptor, False)), False
|
|
335
|
+
return response, native
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def run(args: argparse.Namespace) -> int:
|
|
339
|
+
if os.name != "nt":
|
|
340
|
+
print("이 클라이언트는 Windows 에서만 동작합니다 (ConPTY 호스트가 Windows 전용).", file=sys.stderr)
|
|
341
|
+
return 2
|
|
342
|
+
|
|
343
|
+
import msvcrt
|
|
344
|
+
|
|
345
|
+
state_path = Path(args.state_path) if args.state_path else default_state_path()
|
|
346
|
+
raw_path = Path(args.raw_path) if args.raw_path else default_raw_path()
|
|
347
|
+
|
|
348
|
+
if not state_path.is_file():
|
|
349
|
+
print(f"호스트 상태 파일이 없습니다: {state_path}", file=sys.stderr)
|
|
350
|
+
return 3
|
|
351
|
+
descriptor = load_descriptor(state_path)
|
|
352
|
+
|
|
353
|
+
if not raw_path.is_file():
|
|
354
|
+
print(f"라이브 raw 파일이 없습니다: {raw_path}", file=sys.stderr)
|
|
355
|
+
print("crb 0.9.3 이상 호스트가 떠 있어야 합니다.", file=sys.stderr)
|
|
356
|
+
return 4
|
|
357
|
+
|
|
358
|
+
if not args.read_only:
|
|
359
|
+
probe = pipe_request(str(descriptor["pipe_name"]), build_request(descriptor, "verify"))
|
|
360
|
+
if not probe.get("ok"):
|
|
361
|
+
print(f"호스트 IPC 거부: {probe.get('error')}", file=sys.stderr)
|
|
362
|
+
return 5
|
|
363
|
+
if not probe.get("session_bound"):
|
|
364
|
+
print("세션이 아직 안 붙었습니다 — 봇에 프롬프트를 한 번 보낸 뒤 다시 실행하세요.", file=sys.stderr)
|
|
365
|
+
return 6
|
|
366
|
+
|
|
367
|
+
warning = "" if args.no_resize else resize_console(args.columns, args.rows)
|
|
368
|
+
|
|
369
|
+
handle = open(raw_path, "rb")
|
|
370
|
+
size = raw_path.stat().st_size
|
|
371
|
+
handle.seek(max(0, size - max(0, args.replay)))
|
|
372
|
+
|
|
373
|
+
carry = b""
|
|
374
|
+
errors: list[str] = []
|
|
375
|
+
space_native = True # 0.9.4+ 가정, 거부되면 그 세션 내내 폴백
|
|
376
|
+
out = sys.stdout.buffer
|
|
377
|
+
|
|
378
|
+
with ConsoleMode():
|
|
379
|
+
out.write(b"\x1b[2J\x1b[H") # 이전 콘솔 내용 지우고 시작
|
|
380
|
+
if warning:
|
|
381
|
+
out.write(("[attach] " + warning + "\r\n").encode("utf-8"))
|
|
382
|
+
out.write(
|
|
383
|
+
f"[attach] {raw_path.name} 구독 · 입력은 호스트로 전달 · 나가기 Ctrl+] \r\n".encode("utf-8")
|
|
384
|
+
)
|
|
385
|
+
out.flush()
|
|
386
|
+
|
|
387
|
+
try:
|
|
388
|
+
while True:
|
|
389
|
+
chunk = handle.read(65536)
|
|
390
|
+
if chunk:
|
|
391
|
+
visible, carry = strip_markers(chunk, carry)
|
|
392
|
+
if visible:
|
|
393
|
+
out.write(visible)
|
|
394
|
+
out.flush()
|
|
395
|
+
else:
|
|
396
|
+
current = raw_path.stat().st_size
|
|
397
|
+
if current < handle.tell(): # 호스트가 파일을 회전시켰다
|
|
398
|
+
handle.seek(0)
|
|
399
|
+
|
|
400
|
+
typed = False
|
|
401
|
+
while msvcrt.kbhit():
|
|
402
|
+
char = msvcrt.getwch()
|
|
403
|
+
if char in ("\x00", "\xe0"):
|
|
404
|
+
action, name = map_key("", msvcrt.getwch())
|
|
405
|
+
else:
|
|
406
|
+
action, name = map_key(char)
|
|
407
|
+
|
|
408
|
+
if action == "detach":
|
|
409
|
+
return 0
|
|
410
|
+
try:
|
|
411
|
+
if action == "key":
|
|
412
|
+
response = send_key(descriptor, name)
|
|
413
|
+
elif action == "space":
|
|
414
|
+
response, space_native = send_space(descriptor, space_native)
|
|
415
|
+
else:
|
|
416
|
+
continue
|
|
417
|
+
if not response.get("ok"):
|
|
418
|
+
errors.append(f"{action} {name!r}: {response.get('error')}")
|
|
419
|
+
typed = True
|
|
420
|
+
except (OSError, TimeoutError, RuntimeError, ValueError) as error:
|
|
421
|
+
errors.append(f"{action} {name!r}: {error}")
|
|
422
|
+
|
|
423
|
+
# 입력 직후엔 화면 갱신이 곧 오므로 잠깐 촘촘히 돈다.
|
|
424
|
+
time.sleep((args.poll_ms if not typed else 5) / 1000.0)
|
|
425
|
+
except KeyboardInterrupt:
|
|
426
|
+
return 0
|
|
427
|
+
finally:
|
|
428
|
+
handle.close()
|
|
429
|
+
out.write(b"\x1b[?1049l") # TUI 가 켰을 수 있는 대체 화면에서 빠져나온다
|
|
430
|
+
out.flush()
|
|
431
|
+
if errors:
|
|
432
|
+
print("\n[attach] 전달 실패 " + str(len(errors)) + "건:", file=sys.stderr)
|
|
433
|
+
for line in errors[-10:]:
|
|
434
|
+
print(" " + line, file=sys.stderr)
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
438
|
+
parser = argparse.ArgumentParser(description="codex ConPTY attach client (표시+입력)")
|
|
439
|
+
parser.add_argument("--state-path", default="")
|
|
440
|
+
parser.add_argument("--raw-path", default="")
|
|
441
|
+
parser.add_argument("--columns", type=int, default=DEFAULT_COLUMNS)
|
|
442
|
+
parser.add_argument("--rows", type=int, default=DEFAULT_ROWS)
|
|
443
|
+
parser.add_argument("--replay", type=int, default=65536, help="붙을 때 되감아 다시 그릴 바이트")
|
|
444
|
+
parser.add_argument("--poll-ms", type=int, default=30)
|
|
445
|
+
parser.add_argument("--no-resize", action="store_true")
|
|
446
|
+
parser.add_argument("--read-only", action="store_true", help="입력 없이 화면만")
|
|
447
|
+
return parser
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
def main(argv: list[str] | None = None) -> int:
|
|
451
|
+
return run(build_parser().parse_args(argv))
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
if __name__ == "__main__":
|
|
455
|
+
raise SystemExit(main())
|
|
@@ -67,6 +67,9 @@ def encode_key(key: str) -> bytes:
|
|
|
67
67
|
"enter": b"\r",
|
|
68
68
|
"return": b"\r",
|
|
69
69
|
"tab": b"\t",
|
|
70
|
+
# T-260722-089: 이름이 없으면 공백을 보낼 방법이 없다 — 아래 strip() 이
|
|
71
|
+
# " " 를 빈 문자열로 만들어 단일 문자 경로가 받지 못한다.
|
|
72
|
+
"space": b" ",
|
|
70
73
|
"escape": b"\x1b",
|
|
71
74
|
"esc": b"\x1b",
|
|
72
75
|
"up": b"\x1b[A",
|
|
@@ -981,6 +984,7 @@ def writer_loop(
|
|
|
981
984
|
inputs: OrderedInputQueue,
|
|
982
985
|
stop: threading.Event,
|
|
983
986
|
input_activity: dict[str, int] | None = None,
|
|
987
|
+
live: Any | None = None,
|
|
984
988
|
) -> None:
|
|
985
989
|
while not stop.is_set() and pty.alive():
|
|
986
990
|
try:
|
|
@@ -992,12 +996,171 @@ def writer_loop(
|
|
|
992
996
|
try:
|
|
993
997
|
if input_activity is not None and input_activity.get("first_ns", 0) == 0:
|
|
994
998
|
input_activity["first_ns"] = time.time_ns()
|
|
999
|
+
# 텔레그램 주입은 무에코라 콘솔에 흔적이 없다 — 라이브 파일에만 마커를 남겨
|
|
1000
|
+
# 뷰어에서 "무엇이 주입됐는지" 가 보이게 한다 (T-260722-066).
|
|
1001
|
+
if live is not None and frame.source == "ipc":
|
|
1002
|
+
live.note(f"주입 <- {summarize_injection(frame.payload)}")
|
|
995
1003
|
pty.write(frame.payload)
|
|
996
1004
|
except OSError:
|
|
997
1005
|
stop.set()
|
|
998
1006
|
return
|
|
999
1007
|
|
|
1000
1008
|
|
|
1009
|
+
DEFAULT_LIVE_RAW_MAX_BYTES = 8 * 1024 * 1024
|
|
1010
|
+
|
|
1011
|
+
|
|
1012
|
+
def default_live_raw_path() -> Path:
|
|
1013
|
+
"""호스트 state_path 와 같은 관례(LOCALAPPDATA/codex-telegram-bridge/)를 쓴다."""
|
|
1014
|
+
base = os.environ.get("LOCALAPPDATA") or str(Path.home())
|
|
1015
|
+
return Path(base) / "codex-telegram-bridge" / "conpty-live.raw"
|
|
1016
|
+
|
|
1017
|
+
|
|
1018
|
+
class LiveRawSink:
|
|
1019
|
+
"""conpty raw 출력을 stdout 과 append-only 파일에 동시에 흘리는 tee (T-260722-066).
|
|
1020
|
+
|
|
1021
|
+
발원: 사용자 실사용 증상 — PowerShell 에서 세션 접속은 되는데 텔레그램 주입
|
|
1022
|
+
프롬프트·출력이 터미널에 안 보인다. 근본원인은 버그가 아니라 가시성 설계갭으로,
|
|
1023
|
+
raw 출력이 인메모리 RawOutputBuffer 에만 남아 밖에서 볼 방법이 없었다. 파일로
|
|
1024
|
+
흘려 뷰어(codex-conpty-live-view.ps1)가 tail 할 수 있게 한다.
|
|
1025
|
+
|
|
1026
|
+
설계 제약:
|
|
1027
|
+
- 파일 IO 실패가 호스트를 죽이면 안 된다 → 1회 경고 후 stdout 전용으로 강등.
|
|
1028
|
+
- 콘솔 출력이 파일 문제로 유실되면 안 된다 → passthrough 를 먼저 쓴다.
|
|
1029
|
+
- 무한증식 금지 → 크기 상한 초과 시 <path>.1 로 1회전(총 2배 상한).
|
|
1030
|
+
- 주입 무에코 설계 유지 → note() 마커는 **파일에만** 쓴다. stdout 에 쓰면
|
|
1031
|
+
codex TUI 로 에코되어 렌더링을 깨고 무에코 계약을 위반한다.
|
|
1032
|
+
"""
|
|
1033
|
+
|
|
1034
|
+
def __init__(
|
|
1035
|
+
self,
|
|
1036
|
+
path: Path,
|
|
1037
|
+
passthrough: Any,
|
|
1038
|
+
max_bytes: int = DEFAULT_LIVE_RAW_MAX_BYTES,
|
|
1039
|
+
) -> None:
|
|
1040
|
+
self._path = path
|
|
1041
|
+
self._passthrough = passthrough
|
|
1042
|
+
self._max_bytes = max(0, int(max_bytes))
|
|
1043
|
+
self._lock = threading.Lock()
|
|
1044
|
+
self._handle: Any | None = None
|
|
1045
|
+
self._size = 0
|
|
1046
|
+
self._degraded = False
|
|
1047
|
+
self._open()
|
|
1048
|
+
|
|
1049
|
+
@property
|
|
1050
|
+
def path(self) -> Path:
|
|
1051
|
+
return self._path
|
|
1052
|
+
|
|
1053
|
+
def _open(self) -> None:
|
|
1054
|
+
try:
|
|
1055
|
+
self._path.parent.mkdir(parents=True, exist_ok=True)
|
|
1056
|
+
self._handle = open(self._path, "ab", buffering=0)
|
|
1057
|
+
self._size = self._path.stat().st_size
|
|
1058
|
+
except OSError as exc:
|
|
1059
|
+
self._degrade(f"open {self._path} failed: {exc}")
|
|
1060
|
+
|
|
1061
|
+
def _degrade(self, reason: str) -> None:
|
|
1062
|
+
if not self._degraded:
|
|
1063
|
+
self._degraded = True
|
|
1064
|
+
safe_log(f"live raw sink disabled ({reason}); stdout only")
|
|
1065
|
+
handle, self._handle = self._handle, None
|
|
1066
|
+
if handle is not None:
|
|
1067
|
+
try:
|
|
1068
|
+
handle.close()
|
|
1069
|
+
except OSError:
|
|
1070
|
+
pass
|
|
1071
|
+
|
|
1072
|
+
def _rotate_locked(self) -> None:
|
|
1073
|
+
handle, self._handle = self._handle, None
|
|
1074
|
+
if handle is not None:
|
|
1075
|
+
try:
|
|
1076
|
+
handle.close()
|
|
1077
|
+
except OSError:
|
|
1078
|
+
pass
|
|
1079
|
+
try:
|
|
1080
|
+
rotated = self._path.with_name(self._path.name + ".1")
|
|
1081
|
+
os.replace(self._path, rotated)
|
|
1082
|
+
except OSError as exc:
|
|
1083
|
+
self._degrade(f"rotate failed: {exc}")
|
|
1084
|
+
return
|
|
1085
|
+
self._open()
|
|
1086
|
+
|
|
1087
|
+
def _write_file_locked(self, data: bytes) -> None:
|
|
1088
|
+
if self._handle is None:
|
|
1089
|
+
return
|
|
1090
|
+
if self._max_bytes and self._size + len(data) > self._max_bytes:
|
|
1091
|
+
self._rotate_locked()
|
|
1092
|
+
if self._handle is None:
|
|
1093
|
+
return
|
|
1094
|
+
try:
|
|
1095
|
+
self._handle.write(data)
|
|
1096
|
+
self._size += len(data)
|
|
1097
|
+
except OSError as exc:
|
|
1098
|
+
self._degrade(f"write failed: {exc}")
|
|
1099
|
+
|
|
1100
|
+
def write(self, data: bytes) -> int:
|
|
1101
|
+
# 콘솔이 먼저다 — 파일 쪽 문제로 사람이 보는 출력을 잃지 않는다.
|
|
1102
|
+
written = self._passthrough.write(data)
|
|
1103
|
+
with self._lock:
|
|
1104
|
+
self._write_file_locked(data)
|
|
1105
|
+
return written if written is not None else len(data)
|
|
1106
|
+
|
|
1107
|
+
def flush(self) -> None:
|
|
1108
|
+
try:
|
|
1109
|
+
self._passthrough.flush()
|
|
1110
|
+
finally:
|
|
1111
|
+
with self._lock:
|
|
1112
|
+
if self._handle is not None:
|
|
1113
|
+
try:
|
|
1114
|
+
self._handle.flush()
|
|
1115
|
+
except OSError as exc:
|
|
1116
|
+
self._degrade(f"flush failed: {exc}")
|
|
1117
|
+
|
|
1118
|
+
def note(self, text: str) -> None:
|
|
1119
|
+
"""사람이 읽는 이벤트 마커 1줄 — 파일 전용(stdout 무에코 계약 유지)."""
|
|
1120
|
+
stamp = time.strftime("%Y-%m-%d %H:%M:%S")
|
|
1121
|
+
line = f"\r\n[{stamp}] {text}\r\n".encode("utf-8", "replace")
|
|
1122
|
+
with self._lock:
|
|
1123
|
+
self._write_file_locked(line)
|
|
1124
|
+
|
|
1125
|
+
def close(self) -> None:
|
|
1126
|
+
with self._lock:
|
|
1127
|
+
handle, self._handle = self._handle, None
|
|
1128
|
+
if handle is not None:
|
|
1129
|
+
try:
|
|
1130
|
+
handle.close()
|
|
1131
|
+
except OSError:
|
|
1132
|
+
pass
|
|
1133
|
+
|
|
1134
|
+
|
|
1135
|
+
def summarize_injection(payload: bytes, limit: int = 120) -> str:
|
|
1136
|
+
"""주입 페이로드를 마커용 1줄 요약으로 축약한다 (제어문자 제거·길이 컷)."""
|
|
1137
|
+
text = payload.decode("utf-8", "replace")
|
|
1138
|
+
text = re.sub(r"[\x00-\x1f\x7f]+", " ", text)
|
|
1139
|
+
text = re.sub(r"\s+", " ", text).strip()
|
|
1140
|
+
if not text:
|
|
1141
|
+
return "(제어 키 입력)"
|
|
1142
|
+
if len(text) > limit:
|
|
1143
|
+
return text[:limit] + f"… (+{len(text) - limit}자)"
|
|
1144
|
+
return text
|
|
1145
|
+
|
|
1146
|
+
|
|
1147
|
+
def build_live_raw_sink(passthrough: Any) -> LiveRawSink | None:
|
|
1148
|
+
"""env 로 경로·상한을 정한다. 경로를 빈 문자열로 두면 비활성."""
|
|
1149
|
+
configured = os.environ.get("CODEX_CONPTY_LIVE_RAW")
|
|
1150
|
+
if configured is None:
|
|
1151
|
+
target = default_live_raw_path()
|
|
1152
|
+
else:
|
|
1153
|
+
raw_path = configured.strip()
|
|
1154
|
+
if not raw_path:
|
|
1155
|
+
return None
|
|
1156
|
+
target = Path(raw_path).expanduser()
|
|
1157
|
+
try:
|
|
1158
|
+
max_bytes = int(os.environ.get("CODEX_CONPTY_LIVE_MAX_BYTES", DEFAULT_LIVE_RAW_MAX_BYTES))
|
|
1159
|
+
except ValueError:
|
|
1160
|
+
max_bytes = DEFAULT_LIVE_RAW_MAX_BYTES
|
|
1161
|
+
return LiveRawSink(target, passthrough, max_bytes)
|
|
1162
|
+
|
|
1163
|
+
|
|
1001
1164
|
def output_loop(
|
|
1002
1165
|
pty: WindowsConPty,
|
|
1003
1166
|
output: RawOutputBuffer,
|
|
@@ -1126,8 +1289,18 @@ def run_host(args: argparse.Namespace) -> int:
|
|
|
1126
1289
|
session_holder: dict[str, Path | None] = {"path": None}
|
|
1127
1290
|
input_activity: dict[str, int] = {"first_ns": 0}
|
|
1128
1291
|
|
|
1292
|
+
# raw 출력을 append-only 파일로도 흘린다 — 뷰어가 tail 해서 사용자 콘솔에 실시간
|
|
1293
|
+
# 표시할 수 있게 하는 배관 (T-260722-066). 실패해도 stdout 전용으로 계속 돈다.
|
|
1294
|
+
live_sink = build_live_raw_sink(sys.stdout.buffer)
|
|
1295
|
+
if live_sink is not None:
|
|
1296
|
+
safe_log(f"live raw sink -> {live_sink.path}")
|
|
1297
|
+
live_sink.note(f"conpty host start pid={child_pid} generation={generation[:8]}")
|
|
1298
|
+
|
|
1129
1299
|
output_thread = threading.Thread(
|
|
1130
|
-
target=output_loop,
|
|
1300
|
+
target=output_loop,
|
|
1301
|
+
args=(pty, output, stop, live_sink),
|
|
1302
|
+
daemon=True,
|
|
1303
|
+
name="conpty-output",
|
|
1131
1304
|
)
|
|
1132
1305
|
output_thread.start()
|
|
1133
1306
|
keyboard_thread = threading.Thread(
|
|
@@ -1152,7 +1325,7 @@ def run_host(args: argparse.Namespace) -> int:
|
|
|
1152
1325
|
return 3
|
|
1153
1326
|
writer_thread = threading.Thread(
|
|
1154
1327
|
target=writer_loop,
|
|
1155
|
-
args=(pty, inputs, stop, input_activity),
|
|
1328
|
+
args=(pty, inputs, stop, input_activity, live_sink),
|
|
1156
1329
|
daemon=True,
|
|
1157
1330
|
name="conpty-input",
|
|
1158
1331
|
)
|
{codex_telegram_bridge-0.9.2 → codex_telegram_bridge-0.9.4/codex_telegram_bridge.egg-info}/PKG-INFO
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: codex-telegram-bridge
|
|
3
|
-
Version: 0.9.
|
|
3
|
+
Version: 0.9.4
|
|
4
4
|
Summary: Control a live Codex CLI session from Telegram.
|
|
5
5
|
Author: Kang Daejong
|
|
6
6
|
License: MIT
|
|
@@ -671,6 +671,32 @@ If more than one new Codex JSONL session appears during startup, the host stops
|
|
|
671
671
|
instead of guessing. A restarted host uses a new generation and capability, so
|
|
672
672
|
an old bridge cannot redirect queued input into the new session.
|
|
673
673
|
|
|
674
|
+
### Attach window — watch and type from another terminal (Windows)
|
|
675
|
+
|
|
676
|
+
A foreground host shows its own TUI. A host that runs hidden — a scheduled task,
|
|
677
|
+
a detached launcher — shows it nowhere, and resuming the session in a second
|
|
678
|
+
terminal would only share the conversation file, not the screen: prompts sent
|
|
679
|
+
from Telegram never appear there.
|
|
680
|
+
|
|
681
|
+
The attach client subscribes to the append-only raw stream the host already tees
|
|
682
|
+
to disk and forwards your keystrokes back through the host IPC, so a single
|
|
683
|
+
window both shows the live screen and types into it:
|
|
684
|
+
|
|
685
|
+
```powershell
|
|
686
|
+
python -m codex_conpty_attach
|
|
687
|
+
```
|
|
688
|
+
|
|
689
|
+
`Ctrl+]` detaches. `Ctrl+C` is forwarded to Codex rather than closing the window.
|
|
690
|
+
`--replay 0` starts from now instead of repainting recent output, `--read-only`
|
|
691
|
+
watches without sending anything, and `--columns/--rows` match a host that was
|
|
692
|
+
started with non-default dimensions.
|
|
693
|
+
|
|
694
|
+
The client never owns the pseudoconsole — the host keeps it — so attaching and
|
|
695
|
+
detaching cannot disturb the running session. Two requirements: the host must be
|
|
696
|
+
writing the raw stream (on by default; `CODEX_CONPTY_LIVE_RAW=""` disables it),
|
|
697
|
+
and the window must be the same size as the host (`--columns 120 --rows 40` by
|
|
698
|
+
default, matching the host defaults) or redrawn lines will not line up.
|
|
699
|
+
|
|
674
700
|
Token safety rule: BotFather shows the token in Telegram, but you should copy it
|
|
675
701
|
from BotFather and paste it into the local setup wizard in your terminal. In
|
|
676
702
|
Telegram, send only `/start` or normal prompts to your bot.
|
|
@@ -3,6 +3,7 @@ README.md
|
|
|
3
3
|
bridge_setup.py
|
|
4
4
|
bridge_watchdog.py
|
|
5
5
|
codex_audio_transcribe.py
|
|
6
|
+
codex_conpty_attach.py
|
|
6
7
|
codex_repl_bridge.py
|
|
7
8
|
codex_repl_host_windows.py
|
|
8
9
|
pyproject.toml
|
|
@@ -24,6 +25,7 @@ codex_telegram_bridge.egg-info/requires.txt
|
|
|
24
25
|
codex_telegram_bridge.egg-info/top_level.txt
|
|
25
26
|
tests/test_agent_runtime.py
|
|
26
27
|
tests/test_bridge.py
|
|
28
|
+
tests/test_codex_conpty_attach.py
|
|
27
29
|
tests/test_public_export.py
|
|
28
30
|
tests/test_repl_bridge.py
|
|
29
31
|
tests/test_repl_transport.py
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "codex-telegram-bridge"
|
|
7
|
-
version = "0.9.
|
|
7
|
+
version = "0.9.4"
|
|
8
8
|
description = "Control a live Codex CLI session from Telegram."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.10"
|
|
@@ -50,5 +50,6 @@ py-modules = [
|
|
|
50
50
|
"telegram_agent_bridge",
|
|
51
51
|
"codex_repl_bridge",
|
|
52
52
|
"codex_repl_host_windows",
|
|
53
|
-
"codex_audio_transcribe"
|
|
53
|
+
"codex_audio_transcribe",
|
|
54
|
+
"codex_conpty_attach"
|
|
54
55
|
]
|
|
@@ -112,7 +112,7 @@ class BridgeTests(unittest.TestCase):
|
|
|
112
112
|
bridge = tab.Bridge(cfg, tab.CodexBackend(cfg), FakeTelegram())
|
|
113
113
|
|
|
114
114
|
self.assertEqual(bridge.telegram_chunks("🙂😄👋 answer"), ["answer"])
|
|
115
|
-
self.assertEqual(bridge.telegram_chunks("
|
|
115
|
+
self.assertEqual(bridge.telegram_chunks("🎉"), ["🎉"])
|
|
116
116
|
|
|
117
117
|
def test_group_chat_keeps_prefix(self):
|
|
118
118
|
with tempfile.TemporaryDirectory() as tmpdir:
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
"""T-260722-076 attach 클라이언트 단위 검증.
|
|
2
|
+
|
|
3
|
+
Windows 전용 런타임(콘솔 모드·named pipe·msvcrt)은 lazy import 라 이 테스트는
|
|
4
|
+
어느 노드에서나 돈다. 검증 대상은 화면을 망가뜨리는 두 축이다:
|
|
5
|
+
1) 주입 마커 제거 — 잘못 걷어내면 TUI 제어열까지 먹어 화면이 깨진다.
|
|
6
|
+
2) 키 매핑 — 호스트 encode_key 계약(공백은 strip 되어 거부)과 어긋나면 입력이 죽는다.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import importlib.util
|
|
12
|
+
import unittest
|
|
13
|
+
from datetime import datetime
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
# 내부 레이아웃(scripts/tests/ 옆의 scripts/windows/)과 공개 패키지 레이아웃(tests/ 옆의
|
|
17
|
+
# 저장소 루트) 양쪽에서 같은 파일이 그대로 돌아야 한다 — export 가 이 테스트를 복사해
|
|
18
|
+
# 공개 tests/ 로 싣는다(PUBLIC_TESTS.manifest 의 copy: 항목). 정본은 하나다.
|
|
19
|
+
_CANDIDATES = (
|
|
20
|
+
Path(__file__).resolve().parents[1] / "windows" / "codex_conpty_attach.py",
|
|
21
|
+
Path(__file__).resolve().parents[1] / "codex_conpty_attach.py",
|
|
22
|
+
)
|
|
23
|
+
MODULE_PATH = next((path for path in _CANDIDATES if path.is_file()), _CANDIDATES[0])
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def load_module():
|
|
27
|
+
spec = importlib.util.spec_from_file_location("codex_conpty_attach", MODULE_PATH)
|
|
28
|
+
module = importlib.util.module_from_spec(spec)
|
|
29
|
+
assert spec.loader is not None
|
|
30
|
+
spec.loader.exec_module(module)
|
|
31
|
+
return module
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
attach = load_module()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def host_marker(text: str) -> bytes:
|
|
38
|
+
"""LiveRawSink.note() 와 같은 방식으로 마커를 만든다(형식 표류 감지용)."""
|
|
39
|
+
|
|
40
|
+
stamp = datetime(2026, 7, 22, 18, 4, 38).strftime("%Y-%m-%d %H:%M:%S")
|
|
41
|
+
return f"\r\n[{stamp}] {text}\r\n".encode("utf-8")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class StripMarkersTest(unittest.TestCase):
|
|
45
|
+
def test_removes_injection_marker(self) -> None:
|
|
46
|
+
data = b"before" + host_marker("주입 <- [200~ㅎㅇ [201~") + b"after"
|
|
47
|
+
visible, carry = attach.strip_markers(data)
|
|
48
|
+
self.assertEqual(visible, b"beforeafter")
|
|
49
|
+
self.assertEqual(carry, b"")
|
|
50
|
+
|
|
51
|
+
def test_keeps_tui_escape_sequences(self) -> None:
|
|
52
|
+
data = b"\x1b[2J\x1b[H\x1b[38;5;12m> \xed\x95\x9c\xea\xb8\x80\x1b[0m\r\n"
|
|
53
|
+
visible, carry = attach.strip_markers(data)
|
|
54
|
+
self.assertEqual(visible, data)
|
|
55
|
+
self.assertEqual(carry, b"")
|
|
56
|
+
|
|
57
|
+
def test_marker_split_across_chunks(self) -> None:
|
|
58
|
+
marker = host_marker("주입 <- (제어 키 입력)")
|
|
59
|
+
first, second = marker[:12], marker[12:]
|
|
60
|
+
visible_a, carry = attach.strip_markers(b"head" + first)
|
|
61
|
+
self.assertEqual(visible_a, b"head")
|
|
62
|
+
self.assertTrue(carry)
|
|
63
|
+
visible_b, carry = attach.strip_markers(second + b"tail", carry)
|
|
64
|
+
self.assertEqual(visible_b, b"tail")
|
|
65
|
+
self.assertEqual(carry, b"")
|
|
66
|
+
|
|
67
|
+
def test_does_not_eat_ordinary_bracket_line(self) -> None:
|
|
68
|
+
data = b"\r\n[not a marker] still text\r\n"
|
|
69
|
+
visible, carry = attach.strip_markers(data)
|
|
70
|
+
self.assertEqual(visible, data)
|
|
71
|
+
self.assertEqual(carry, b"")
|
|
72
|
+
|
|
73
|
+
def test_bracketed_paste_marker_survives(self) -> None:
|
|
74
|
+
# TUI 스트림에 실제로 등장하는 bracketed paste 시작열은 마커가 아니다.
|
|
75
|
+
data = b"\r\n\x1b[200~pasted\x1b[201~"
|
|
76
|
+
visible, carry = attach.strip_markers(data)
|
|
77
|
+
self.assertEqual(visible + carry, data)
|
|
78
|
+
|
|
79
|
+
def test_carry_overflow_flushes_instead_of_stalling(self) -> None:
|
|
80
|
+
data = b"\r\n[2026-07-22 18:04:38] " + b"x" * 8192
|
|
81
|
+
visible, carry = attach.strip_markers(data, b"", max_carry=64)
|
|
82
|
+
self.assertTrue(visible)
|
|
83
|
+
self.assertEqual(len(visible) + len(carry), len(data))
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class MapKeyTest(unittest.TestCase):
|
|
87
|
+
def test_named_control_chars(self) -> None:
|
|
88
|
+
self.assertEqual(attach.map_key("\r"), ("key", "Enter"))
|
|
89
|
+
self.assertEqual(attach.map_key("\t"), ("key", "Tab"))
|
|
90
|
+
self.assertEqual(attach.map_key("\x1b"), ("key", "Escape"))
|
|
91
|
+
self.assertEqual(attach.map_key("\x08"), ("key", "Backspace"))
|
|
92
|
+
|
|
93
|
+
def test_arrow_scan_codes(self) -> None:
|
|
94
|
+
self.assertEqual(attach.map_key("", "H"), ("key", "Up"))
|
|
95
|
+
self.assertEqual(attach.map_key("", "P"), ("key", "Down"))
|
|
96
|
+
self.assertEqual(attach.map_key("", "M"), ("key", "Right"))
|
|
97
|
+
self.assertEqual(attach.map_key("", "?"), ("ignore", ""))
|
|
98
|
+
|
|
99
|
+
def test_plain_and_unicode_characters_pass_through(self) -> None:
|
|
100
|
+
self.assertEqual(attach.map_key("a"), ("key", "a"))
|
|
101
|
+
self.assertEqual(attach.map_key("가"), ("key", "가"))
|
|
102
|
+
self.assertEqual(attach.map_key("\x03"), ("key", "\x03")) # Ctrl+C 는 codex 로
|
|
103
|
+
|
|
104
|
+
def test_space_goes_through_its_own_path_by_name(self) -> None:
|
|
105
|
+
# 호스트 encode_key 는 key 를 strip() 하므로 " " 를 그대로 보내면 거부된다.
|
|
106
|
+
# 이름("space")으로 보내야 하고, 그 이름 지원은 호스트 세대를 탄다.
|
|
107
|
+
self.assertEqual(attach.map_key(" "), ("space", "space"))
|
|
108
|
+
|
|
109
|
+
def test_detach_key(self) -> None:
|
|
110
|
+
self.assertEqual(attach.map_key("\x1d"), ("detach", ""))
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class SpaceCompatibilityTest(unittest.TestCase):
|
|
114
|
+
"""공백 1칸의 호스트 세대 호환 계약.
|
|
115
|
+
|
|
116
|
+
0.9.4+ 호스트는 encode_key 이름 맵에 "space" 가 있어 키 하나로 끝나고,
|
|
117
|
+
0.9.3 이하는 그 이름을 모른다 — 그 경우에만 paste 우회로 내려가야 한다.
|
|
118
|
+
"""
|
|
119
|
+
|
|
120
|
+
descriptor = {"generation": "gen123", "capability": "cap456", "pipe_name": r"\\.\pipe\x"}
|
|
121
|
+
|
|
122
|
+
def test_native_request_is_a_named_key(self) -> None:
|
|
123
|
+
request = attach.space_request(self.descriptor, True)
|
|
124
|
+
self.assertEqual(request["op"], "key")
|
|
125
|
+
self.assertEqual(request["key"], "space")
|
|
126
|
+
|
|
127
|
+
def test_fallback_request_pastes_with_discarded_submit(self) -> None:
|
|
128
|
+
request = attach.space_request(self.descriptor, False)
|
|
129
|
+
self.assertEqual(request["op"], "paste")
|
|
130
|
+
self.assertEqual(request["text"], " ")
|
|
131
|
+
# submit 프레임은 뗄 수 없으므로 터미널이 버리는 NUL 을 쓴다 — 화면 무영향.
|
|
132
|
+
self.assertEqual(request["submit_key"], "\x00")
|
|
133
|
+
self.assertIs(request["clear_before"], False)
|
|
134
|
+
|
|
135
|
+
def test_falls_back_only_on_frame_rejection(self) -> None:
|
|
136
|
+
self.assertTrue(attach.space_fallback_needed({"ok": False, "error": "invalid_frame"}))
|
|
137
|
+
self.assertTrue(
|
|
138
|
+
attach.space_fallback_needed({"ok": False, "error": "unsupported_operation"})
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
def test_does_not_mask_real_failures_as_old_host(self) -> None:
|
|
142
|
+
# 호스트가 죽었거나 인증이 틀린 건 구호스트가 아니다 — 우회로 덮으면 진짜 고장이 숨는다.
|
|
143
|
+
for error in ("child_not_running", "unauthorized", "generation_mismatch"):
|
|
144
|
+
with self.subTest(error=error):
|
|
145
|
+
self.assertFalse(attach.space_fallback_needed({"ok": False, "error": error}))
|
|
146
|
+
|
|
147
|
+
def test_success_never_falls_back(self) -> None:
|
|
148
|
+
self.assertFalse(attach.space_fallback_needed({"ok": True, "sequence": 3}))
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
class RequestTest(unittest.TestCase):
|
|
152
|
+
descriptor = {"generation": "gen123", "capability": "cap456", "pipe_name": r"\\.\pipe\x"}
|
|
153
|
+
|
|
154
|
+
def test_request_shape_matches_host_validator(self) -> None:
|
|
155
|
+
request = attach.build_request(self.descriptor, "key", key="Enter")
|
|
156
|
+
self.assertEqual(request["schema"], attach.SCHEMA)
|
|
157
|
+
self.assertEqual(request["generation"], "gen123")
|
|
158
|
+
self.assertEqual(request["capability"], "cap456")
|
|
159
|
+
self.assertEqual(request["op"], "key")
|
|
160
|
+
self.assertEqual(request["key"], "Enter")
|
|
161
|
+
# 호스트: request_id 는 8..128 자여야 무시되지 않는다.
|
|
162
|
+
self.assertTrue(8 <= len(request["request_id"]) <= 128)
|
|
163
|
+
|
|
164
|
+
def test_request_ids_are_unique(self) -> None:
|
|
165
|
+
ids = {attach.build_request(self.descriptor, "verify")["request_id"] for _ in range(50)}
|
|
166
|
+
self.assertEqual(len(ids), 50)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
if __name__ == "__main__":
|
|
170
|
+
unittest.main()
|
|
File without changes
|
|
File without changes
|
{codex_telegram_bridge-0.9.2 → codex_telegram_bridge-0.9.4}/agent_runtime/adapters/__init__.py
RENAMED
|
File without changes
|
|
File without changes
|
{codex_telegram_bridge-0.9.2 → codex_telegram_bridge-0.9.4}/agent_runtime/adapters/codex_repl.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|