Skip to content

Commit bced973

Browse files
authored
Merge pull request #23 from codebasic/recovery/pre-process-features
Restore pre-process agent features dropped from the review build (#22)
2 parents 90425e9 + c21eb08 commit bced973

43 files changed

Lines changed: 4668 additions & 711 deletions

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: 406 additions & 51 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: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ macOS용 TTS 앱: **텍스트 읽기, 에이전트 지시 관리, 받은 대본
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` |

‎Resources/Info.plist‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
<key>CFBundleIconFile</key>
2020
<string>AppIcon</string>
2121
<key>LSMinimumSystemVersion</key>
22-
<string>13.0</string>
22+
<string>14.0</string>
2323

2424
<!-- macOS Services registration. NSMessage maps to the selector
2525
readSelectedText:userData:error: in ServiceProvider.swift. -->

‎Sources/App/AgentPeerSigning.swift‎

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,8 @@ import Foundation
44
import Security
55

66
enum AgentPeerSigning {
7-
static let appID = "com.seongjoo.SelectedTextTTS"
8-
static let helperID = "com.seongjoo.SelectedTextTTS.agent-helper"
9-
static let pinEnvironment = "CODEBASIC_TTS_SIGNER_SHA1"
7+
static let appID = TTSRuntime.appID
8+
static let helperID = TTSRuntime.helperID
109

1110
static func ownLeaf() -> String? {
1211
var code: SecCode?
@@ -32,11 +31,6 @@ enum AgentPeerSigning {
3231
return signedHash(code)
3332
}
3433

35-
static func matches(pid: pid_t, identifier: String, leaf: String, expectedHash: Data) -> Bool {
36-
check([kSecGuestAttributePid as String: NSNumber(value: pid)], identifier: identifier, leaf: leaf,
37-
expectedHash: expectedHash)
38-
}
39-
4034
static func matches(socket fd: Int32, identifier: String, leaf: String, expectedHash: Data? = nil) -> Bool {
4135
var uid: uid_t = 0, gid: gid_t = 0
4236
var token = audit_token_t()
@@ -48,6 +42,23 @@ enum AgentPeerSigning {
4842
identifier: identifier, leaf: leaf, expectedHash: expectedHash)
4943
}
5044

45+
/// "identifier:team" of a validly signed, team-identified running program.
46+
/// Looked up by PID, so it narrows who may reuse an approved key but is not
47+
/// by itself proof of identity; the key signature is.
48+
static func teamSignedIdentity(pid: pid_t) -> String? {
49+
var guest: SecCode?
50+
var code: SecStaticCode?
51+
var info: CFDictionary?
52+
guard SecCodeCopyGuestWithAttributes(nil, [kSecGuestAttributePid as String: pid] as CFDictionary, [], &guest) == errSecSuccess,
53+
let guest, SecCodeCheckValidity(guest, [], nil) == errSecSuccess,
54+
SecCodeCopyStaticCode(guest, [], &code) == errSecSuccess, let code,
55+
SecCodeCopySigningInformation(code, SecCSFlags(rawValue: kSecCSSigningInformation), &info) == errSecSuccess,
56+
let details = info as? [String: Any],
57+
let identifier = details[kSecCodeInfoIdentifier as String] as? String,
58+
let team = details[kSecCodeInfoTeamIdentifier as String] as? String, !team.isEmpty else { return nil }
59+
return identifier + ":" + team
60+
}
61+
5162
private static func signedHash(_ code: SecStaticCode) -> Data? {
5263
var info: CFDictionary?
5364
guard SecCodeCopySigningInformation(code, [], &info) == errSecSuccess else { return nil }

0 commit comments

Comments
 (0)