Skip to content

Commit b3ebef2

Browse files
authored
Merge pull request #36 from codebasic/integration/issue-31
Bring agent app approval (#13) and Agent-tab auto connect (#31) into the promotion candidate (#4)
2 parents b286b69 + 28ae9e8 commit b3ebef2

67 files changed

Lines changed: 11099 additions & 263 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎Helpers/AgentCatalogMCP.swift‎

Lines changed: 756 additions & 0 deletions
Large diffs are not rendered by default.

‎Helpers/tts_mcp_client.py‎

Lines changed: 221 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,221 @@
1+
#!/usr/bin/env python3
2+
"""Send drafts to Codebasic TTS through its signed MCP helper, over pipes.
3+
4+
A pseudo-terminal must not sit between an agent and the helper: its line
5+
discipline cuts long lines and swallows bytes, so a long Korean script never
6+
arrives whole and no reply comes back. This client talks to the helper over
7+
plain pipes, one complete UTF-8 JSON-RPC frame per request, and reports every
8+
send as exactly one of:
9+
10+
confirmed the app answered this request: accepted, or duplicate
11+
rejected the app, the helper or this client refused it; nothing was opened
12+
unconfirmed no matching answer arrived; whether it was received is unknown
13+
14+
An unconfirmed send is never repeated automatically. `retry()` repeats it once
15+
on the same connection, with the same key and bytes and a new request id.
16+
Diagnostics hold states and byte counts only, never the draft text.
17+
18+
tts_mcp_client.py --helper PATH status
19+
tts_mcp_client.py --helper PATH guide
20+
tts_mcp_client.py --helper PATH send --key K --display-file F [--speech-file F] [--title T]
21+
"""
22+
import argparse
23+
import json
24+
import os
25+
import select
26+
import subprocess
27+
import sys
28+
import time
29+
30+
TEXT_LIMIT = 8192 # UTF-8 bytes per text field, agreed with the app
31+
FRAME_LIMIT = 100 * 1024 # UTF-8 bytes of one whole request frame, newline included
32+
CONFIRMED = {"accepted", "duplicate"}
33+
34+
35+
class Session:
36+
"""One live helper process. Keep it open across turns; closing it is harmless."""
37+
38+
def __init__(self, helper, client=None, name="tts-mcp-client", launcher=None, **popen):
39+
command = list(launcher or []) + [helper] + (["--client", client] if client else [])
40+
# Binary pipes: no terminal, no echo, no line-length limit, no translation.
41+
self.proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
42+
stderr=subprocess.DEVNULL, bufsize=0, **popen)
43+
self.next_id = 0
44+
self.buffer = b""
45+
self.limits = {"text_bytes": TEXT_LIMIT, "frame_bytes": FRAME_LIMIT}
46+
self.last = None
47+
reply = self._request("initialize", {"protocolVersion": "2025-11-25", "capabilities": {},
48+
"clientInfo": {"name": name, "version": "1"}})[1]
49+
if reply is None or "result" not in reply:
50+
raise RuntimeError("helper did not initialize")
51+
self.server = reply["result"]["serverInfo"]["name"]
52+
self._write(self._frame({"jsonrpc": "2.0", "method": "notifications/initialized"}))
53+
54+
@staticmethod
55+
def _frame(message):
56+
# json.dumps escapes every newline inside strings; the only raw LF ends the frame.
57+
return json.dumps(message, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + b"\n"
58+
59+
def _write(self, frame):
60+
view = memoryview(frame)
61+
while view: # a short write is continued on this connection only
62+
view = view[os.write(self.proc.stdin.fileno(), view):]
63+
64+
def _read(self, request_id, timeout):
65+
deadline = time.monotonic() + timeout
66+
while True:
67+
while b"\n" in self.buffer:
68+
line, self.buffer = self.buffer.split(b"\n", 1)
69+
try:
70+
message = json.loads(line)
71+
except ValueError:
72+
continue
73+
if message.get("id") == request_id:
74+
return message
75+
remaining = deadline - time.monotonic()
76+
if remaining <= 0 or not select.select([self.proc.stdout], [], [], remaining)[0]:
77+
return None
78+
chunk = os.read(self.proc.stdout.fileno(), 65536)
79+
if not chunk:
80+
return None
81+
self.buffer += chunk
82+
83+
def _request(self, method, params, timeout=8.0, discard_reply=False):
84+
self.next_id += 1
85+
frame = self._frame({"jsonrpc": "2.0", "id": self.next_id, "method": method, "params": params})
86+
if len(frame) > self.limits["frame_bytes"]:
87+
return len(frame), {"local": "frame_too_large"}
88+
try:
89+
self._write(frame)
90+
except OSError:
91+
return len(frame), None
92+
reply = self._read(self.next_id, timeout)
93+
return len(frame), (None if discard_reply else reply)
94+
95+
def call(self, tool, arguments=None, **options):
96+
size, reply = self._request("tools/call", {"name": tool, "arguments": arguments or {}}, **options)
97+
return size, reply
98+
99+
def status(self):
100+
reply = self.call("tts_agent_status")[1]
101+
content = (reply or {}).get("result", {}).get("structuredContent", {})
102+
self.limits.update(content.get("limits", {}))
103+
return content.get("status", "unconfirmed")
104+
105+
def read_instruction(self):
106+
"""Returns the selected saved instruction (profile, revision, instructions) or None."""
107+
reply = self.call("get_tts_instructions")[1]
108+
result = (reply or {}).get("result", {})
109+
return None if result.get("isError", True) else result.get("structuredContent")
110+
111+
def guide(self):
112+
"""The submission format as the helper describes it: fields, limits, examples, results."""
113+
reply = self.call("get_tts_submission_guide")[1]
114+
return (reply or {}).get("result", {}).get("structuredContent")
115+
116+
def send(self, key, display, speech=None, profile=None, revision=None,
117+
local_checks=True, discard_reply=False, timeout=8.0, title=None):
118+
"""One draft, one frame. `discard_reply` drops the answer, as a lost reply would.
119+
`title` names the draft in the app's list only; it is never part of the text."""
120+
arguments = {"idempotency_key": key, "display_text": display}
121+
if title is not None:
122+
arguments["title"] = title
123+
if speech is not None:
124+
arguments["speech_text"] = speech
125+
tool = "submit_tts_draft"
126+
if profile is not None:
127+
arguments.update(profile=profile, revision=revision)
128+
tool = "submit_explanation_draft"
129+
sizes = {name: len(arguments[name].encode("utf-8")) for name in ("display_text", "speech_text") if name in arguments}
130+
report = {"key": key, "display_bytes": sizes["display_text"], "speech_bytes": sizes.get("speech_text", 0)}
131+
self.last = (tool, arguments, report)
132+
if local_checks:
133+
for name, size in sizes.items():
134+
if size > self.limits["text_bytes"]:
135+
return {**report, "outcome": "rejected", "status": "too_large", "by": "client",
136+
"field": name, "limit_bytes": self.limits["text_bytes"]}
137+
return self._finish(tool, arguments, dict(report), discard_reply, timeout)
138+
139+
def retry(self, timeout=8.0):
140+
"""Repeat the last send once: same connection, same key and bytes, new request id."""
141+
tool, arguments, report = self.last
142+
return self._finish(tool, arguments, dict(report), False, timeout)
143+
144+
def _finish(self, tool, arguments, report, discard_reply, timeout):
145+
size, reply = self.call(tool, arguments, timeout=timeout, discard_reply=discard_reply)
146+
report.update(frame_bytes=size, request_id=self.next_id)
147+
if reply is not None and reply.get("local"):
148+
return {**report, "outcome": "rejected", "status": "frame_too_large", "by": "client",
149+
"limit_bytes": self.limits["frame_bytes"]}
150+
if reply is None or "result" not in reply:
151+
return {**report, "outcome": "unconfirmed", "status": "unconfirmed"}
152+
result = reply["result"]
153+
status = (result.get("structuredContent") or {}).get("status", "invalid" if result.get("isError") else "unconfirmed")
154+
report["status"] = status
155+
for extra in ("field", "bytes", "limit_bytes"):
156+
if extra in (result.get("structuredContent") or {}):
157+
report[extra] = result["structuredContent"][extra]
158+
if status in CONFIRMED and not result.get("isError"):
159+
report["outcome"] = "confirmed"
160+
elif status == "unconfirmed":
161+
report["outcome"] = "unconfirmed"
162+
else:
163+
report["outcome"] = "rejected"
164+
return report
165+
166+
def close(self, kill=False):
167+
if self.proc.poll() is None:
168+
if kill:
169+
self.proc.kill()
170+
else:
171+
self.proc.stdin.close()
172+
try:
173+
self.proc.wait(timeout=3)
174+
except subprocess.TimeoutExpired:
175+
self.proc.kill()
176+
self.proc.wait(timeout=3)
177+
for stream in (self.proc.stdin, self.proc.stdout):
178+
if stream and not stream.closed:
179+
stream.close()
180+
181+
182+
def main():
183+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
184+
parser.add_argument("--helper", required=True, help="path to the app's bundled CodebasicAgentMCP")
185+
parser.add_argument("--client", help="name of this client's key slot (default: this program's MCP name)")
186+
commands = parser.add_subparsers(dest="command", required=True)
187+
commands.add_parser("status")
188+
commands.add_parser("guide")
189+
send = commands.add_parser("send")
190+
send.add_argument("--key", required=True)
191+
send.add_argument("--display-file", required=True)
192+
send.add_argument("--speech-file")
193+
send.add_argument("--title", help="name shown in the app's draft list only")
194+
options = parser.parse_args()
195+
session = Session(options.helper, options.client)
196+
try:
197+
if options.command == "guide":
198+
print(json.dumps(session.guide(), ensure_ascii=False, indent=2))
199+
return 0
200+
state = session.status()
201+
if options.command == "status":
202+
print(json.dumps({"status": state, "limits": session.limits}))
203+
return 0
204+
with open(options.display_file, "rb") as handle:
205+
display = handle.read().decode("utf-8")
206+
speech = None
207+
if options.speech_file:
208+
with open(options.speech_file, "rb") as handle:
209+
speech = handle.read().decode("utf-8")
210+
instruction = session.read_instruction() if state == "ready" else None
211+
report = session.send(options.key, display, speech, title=options.title,
212+
profile=instruction and instruction["profile"],
213+
revision=instruction and instruction["revision"])
214+
print(json.dumps({**report, "connection": state}))
215+
return 0 if report["outcome"] == "confirmed" else 2 if report["outcome"] == "rejected" else 3
216+
finally:
217+
session.close()
218+
219+
220+
if __name__ == "__main__":
221+
sys.exit(main())

‎README.md‎

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -10,22 +10,22 @@
1010
<a href="LICENSE"><img alt="License: MIT" src="https://img.shields.io/badge/License-MIT-yellow.svg" valign="middle"></a>
1111
</p>
1212

13-
macOS용 TTS 앱: **텍스트를 선택하고 단축키 한 번으로 AI 음성 읽기 + LLM 코드 해설**까지.
13+
macOS용 TTS 앱: **텍스트 읽기, 에이전트 지시 관리, 받은 대본 편집·재생**.
1414

1515
**개발 소스: v0.2.1 (빌드 3)** · [변경 기록](CHANGELOG.md). 최신 공개 다운로드는 **v0.1.0**이며, v0.2.1 앱 패키지는 아직 발행하지 않았습니다.
1616

1717
> 💖 **Codebasic TTS는 무료·오픈소스입니다.** 앱이 유용하다면 후원으로 개발을 응원해 주세요
1818
> → [**GitHub Sponsors로 후원하기**](https://github.com/sponsors/codebasic) (금액·주기 자유)
1919
2020
- 아무 앱에서 텍스트 선택 → **⌃⌥⌘R** (또는 우클릭 → Services → "Codebasic TTS") → 곧바로 음성 재생
21-
- 코드 선택 → **⌃⌥⌘E** → 연결된 LLM이 코드를 해설하고, 그 해설을 음성으로 읽어줌
21+
- **에이전트** 탭에서 지시문을 관리하고 외부 에이전트가 돌려준 대본을 편집한 뒤 명시적으로 재생
2222
- ElevenLabs(클라우드)와 로컬 Qwen3-TTS(MLX, 음성 클론) 중 선택해서 사용
2323
- 문장 단위 스트리밍 재생, 문장별 음성 캐싱으로 반복 재생 즉시 반응
2424
- TTS 스크립트를 다듬어주는 LLM 스크립트 편집기 + 용어집(glossary) 내장
2525

2626
| | |
2727
|---|---|
28-
| 플랫폼 | macOS 13.0+ (Apple Silicon 최적화, Intel 미검증) |
28+
| 플랫폼 | macOS 14.0+ (Apple Silicon 최적화, Intel 미검증) |
2929
| 요구사항 | 릴리스 앱은 Xcode 불필요. 기존 플랜 연결은 Codex CLI 또는 Antigravity CLI, 로컬 음성은 Qwen3-TTS 서버 필요 |
3030
| 라이선스 | MIT |
3131
| 다운로드 | [Releases](../../releases/latest) 에서 `Codebasic-TTS.app.zip` |
@@ -55,9 +55,17 @@ macOS용 TTS 앱: **텍스트를 선택하고 단축키 한 번으로 AI 음성
5555
| 동작 | 방법 |
5656
|---|---|
5757
| 선택 텍스트 읽기 | ⌃⌥⌘R 또는 우클릭 → Services → "Codebasic TTS" |
58-
| 선택 코드 해설 후 읽기 | ⌃⌥⌘E 또는 Services → "Codebasic TTS: 코드 해설" |
59-
| 일시정지 / 정지 | 재생 HUD 또는 메뉴 막대 아이콘 메뉴 |
60-
| 스크립트 편집 · 해설 보기 | 메뉴 막대 아이콘 클릭 → 관리 창 |
58+
| 외부 에이전트가 작성한 대본 읽기 | 에이전트 탭 → 붙여넣기 또는 대본 받기 → 검토 → 그대로 재생 |
59+
| 일시정지 / 정지 | 재생 HUD에서 일시정지·중지 / 앱 메뉴에서 재생 중지 |
60+
| 스크립트 편집 · 받은 대본 보기 | Dock 아이콘 클릭 → 관리 창 |
61+
62+
창을 닫아도 Dock 아이콘과 실행 중인 앱은 유지됩니다. Dock에서 다시 열거나 `⌘Q`로 앱을 완전히 종료하세요.
63+
64+
**에이전트** 탭에서 이름을 붙인 지시를 저장·편집·선택하고, 정확한 원문을 미리 보거나 복사할 수 있습니다.
65+
**지시 조회 허용**과 **대본 받기 허용**은 서명된 도우미 한 개를 대상으로 각각 따로 켭니다.
66+
허용하지 않아도 직접 입력하거나 붙여넣을 수 있습니다. 기본 지시 프로필은 코드 해설용이지만 대본 수신·편집·재생은 다른 용도에도 쓸 수 있습니다. 기존 앱 내 해설은
67+
**고급: 앱에서 직접 해설 생성…**에 남아 있습니다. 선택 텍스트 읽기 단축키와 일반 Services는 그대로입니다.
68+
자세한 연결과 검증은 [외부 에이전트 대본](docs/mcp-explanation-drafts.md)을 참고하세요.
6169

6270
## 설정
6371

@@ -69,7 +77,7 @@ macOS용 TTS 앱: **텍스트를 선택하고 단축키 한 번으로 AI 음성
6977
| **AI 서비스** | 해설·대본 생성에 사용할 공급자, 연결 방식, 기본 모델 |
7078
| **대본·발음** | 대본 다듬기, 발음 사전 |
7179
| **재생·자막** | 재생 자막, 음성 캐시, 긴 대본의 합성 분할 기준 |
72-
| **단축키** | 선택 텍스트 읽기·해설 단축키 안내, 손쉬운 사용 권한 확인 |
80+
| **단축키** | 선택 텍스트 읽기 단축키 안내, 손쉬운 사용 권한 확인 |
7381

7482
일반 설정은 자동 저장됩니다. API 키 입력과 AI 서비스 추가·편집은
7583
**저장 및 연결 확인**을 눌러 반영합니다. 서비스 편집 중 **취소**하면 저장 전 변경은
@@ -95,7 +103,7 @@ ElevenLabs는 연결 확인 후 **보이스**와 **합성 모델**을 선택합
95103
2. API 키를 입력하거나, 지원되는 공급자는 **연결 방식 → 기존 플랜**을 선택합니다.
96104
3. **저장 및 연결 확인**으로 서비스를 저장하고 모델을 조회합니다.
97105
4. 필요하면 **조회한 모델에서 선택**으로 기본 모델을 지정하고 다시 저장합니다.
98-
실제 사용할 모델은 TTS·해설 화면에서도 선택할 수 있습니다.
106+
실제 사용할 모델은 TTS 및 에이전트 탭의 고급 해설에서도 선택할 수 있습니다.
99107

100108
| 공급자 프리셋 | 연결 방식 | 준비물 |
101109
|---|---|---|
@@ -138,7 +146,7 @@ Google 플랜 연결은 Gemini CLI가 아닌 **Antigravity CLI**를 사용합니
138146

139147
### 이미지와 모델 선택
140148

141-
해설 화면에서는 **해설 모델**과 **비전 모델**을 각각 선택할 수 있습니다.
149+
에이전트 탭의 고급 해설에서는 **해설 모델**과 **비전 모델**을 각각 선택할 수 있습니다.
142150

143151
- **OpenAI 기존 플랜**: 이미지 입력을 지원합니다. 이미지 처리가 가능한 모델을 선택하세요.
144152
- **Google 기존 플랜**: 현재 Antigravity CLI의 자동화 입력은 **텍스트 전용**이므로
@@ -281,9 +289,9 @@ Sidecar/tts -m 4bit # 양자화 선택 (4bit|5bit|6bit|8bit|bf16)
281289
```
282290
Codebasic-TTS/
283291
├── build.sh # swiftc 빌드 + 번들 조립 + Launch Services 등록
284-
├── Resources/Info.plist # LSUIElement + NSServices 정의
292+
├── Resources/Info.plist # Dock 앱 정보 및 NSServices 정의
285293
├── Sources/
286-
│ ├── App/ # 진입점, 메뉴 막대, 전역 단축키, 엔드포인트/시크릿
294+
│ ├── App/ # 진입점, 앱 메뉴, 전역 단축키, 엔드포인트/시크릿
287295
│ ├── Service/ServiceProvider.swift # NSServices 핸들러 (read/explain)
288296
│ ├── Core/ # 문장 분할, 캐시, 큐 재생, 원문 정규화
289297
│ ├── TTS/ # TTSBackend 프로토콜 + ElevenLabs/로컬 Qwen3 백엔드

‎Resources/Info.plist‎

Lines changed: 1 addition & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,7 @@
1919
<key>CFBundleIconFile</key>
2020
<string>AppIcon</string>
2121
<key>LSMinimumSystemVersion</key>
22-
<string>13.0</string>
23-
24-
<!-- Start as a focus-safe agent; MainWindow flips to a Dock app (.regular)
25-
while its window is open. Keeps background Services playback from
26-
stealing focus. -->
27-
<key>LSUIElement</key>
28-
<true/>
22+
<string>14.0</string>
2923

3024
<!-- macOS Services registration. NSMessage maps to the selector
3125
readSelectedText:userData:error: in ServiceProvider.swift. -->
@@ -49,26 +43,6 @@
4943
<key>NSRequiredContext</key>
5044
<dict/>
5145
</dict>
52-
<!-- Second entry: explain selected code, then read the commentary aloud.
53-
NSMessage maps to explainSelectedText:userData:error: in
54-
ServiceProvider.swift. -->
55-
<dict>
56-
<key>NSMenuItem</key>
57-
<dict>
58-
<key>default</key>
59-
<string>Codebasic TTS: 코드 해설</string>
60-
</dict>
61-
<key>NSMessage</key>
62-
<string>explainSelectedText</string>
63-
<key>NSPortName</key>
64-
<string>SelectedTextTTS</string>
65-
<key>NSSendTypes</key>
66-
<array>
67-
<string>public.utf8-plain-text</string>
68-
</array>
69-
<key>NSRequiredContext</key>
70-
<dict/>
71-
</dict>
7246
</array>
7347
</dict>
7448
</plist>

0 commit comments

Comments
 (0)