Skip to content

Commit 8adf2ed

Browse files
committed
Add exact Agent profiles and provenance-gated draft intake
1 parent c77d20e commit 8adf2ed

26 files changed

Lines changed: 1410 additions & 380 deletions

‎Helpers/AgentCatalogMCP.swift‎

Lines changed: 219 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,219 @@
1+
import Darwin
2+
import Foundation
3+
4+
/// One native signed helper per MCP session. This executable owns both local
5+
/// connections; the model never sees a receipt capability or pairing identity.
6+
@main struct AgentCatalogMCP {
7+
static let maxFrame = 100 * 1024
8+
static let reader = "get_tts_instructions"
9+
static let receiver = "submit_explanation_draft"
10+
static let maxProofs = AgentLimits.proofCount
11+
static let pin = ProcessInfo.processInfo.environment[AgentPeerSigning.pinEnvironment]?.lowercased()
12+
static let directory = "/private/tmp/codebasic-tts-mcp-\(getuid())"
13+
14+
struct Proof {
15+
let profile: String
16+
let revision: String
17+
let bodyHash: String
18+
let token: String
19+
let expiry: ContinuousClock.Instant
20+
var key: String { profile + ":" + revision }
21+
}
22+
23+
static func main() {
24+
var initialized = false, ready = false
25+
var proofs: [Proof] = []
26+
while let input = readFrame() {
27+
if input.isEmpty { emit(error(nil, -32700, "Malformed or oversized frame")); continue }
28+
guard let frame = decode(input), frame["jsonrpc"] as? String == "2.0",
29+
let method = frame["method"] as? String else {
30+
emit(error(nil, -32600, "Invalid request")); continue
31+
}
32+
guard let id = frame["id"] else {
33+
if method == "notifications/initialized", initialized { ready = true }
34+
continue
35+
}
36+
guard id is String || id is NSNumber else { emit(error(nil, -32600, "Invalid request id")); continue }
37+
let params = frame["params"] as? [String: Any] ?? [:]
38+
switch method {
39+
case "initialize":
40+
guard !initialized else { emit(error(id, -32600, "Already initialized")); continue }
41+
initialized = true
42+
let requested = params["protocolVersion"] as? String ?? ""
43+
let version = ["2025-11-25", "2025-06-18", "2025-03-26"].contains(requested) ? requested : "2025-11-25"
44+
result(id, ["protocolVersion":version, "serverInfo":["name":"codebasic-tts-agent", "version":"2.0"],
45+
"capabilities":["tools":["listChanged":false]]])
46+
case "ping":
47+
result(id, [:])
48+
case "tools/list" where ready:
49+
result(id, ["tools": tools])
50+
case "tools/call" where ready:
51+
guard let name = params["name"] as? String, let args = params["arguments"] as? [String: Any] else {
52+
emit(error(id, -32602, "Tool name and arguments required")); continue
53+
}
54+
switch name {
55+
case reader:
56+
guard Set(args.keys) == ["profile"], let selector = args["profile"] as? String,
57+
validSelector(selector) else {
58+
tool(id, "Use an exact built-in profile ID or the ID shown by the app.", failed: true); continue
59+
}
60+
guard let reply = exchange(socket: "i.sock", ["schema_version": 2, "profile": selector]),
61+
reply["schema_version"] as? Int == 2, reply["profile"] as? String == selector,
62+
let text = reply["instructions"] as? String, AgentBytes.textValid(text),
63+
let rev = reply["revision"] as? String, UUID(uuidString: rev) != nil,
64+
let hash = reply["body_sha256"] as? String, hash == AgentBytes.hash(Data(text.utf8)),
65+
let opaque = reply["proof"] as? String, UUID(uuidString: opaque) != nil else {
66+
tool(id, "No pinned, approved instruction revision available. Local helper PID: \(getpid()).", failed: true); continue
67+
}
68+
let proof = Proof(profile: selector, revision: rev, bodyHash: hash, token: opaque,
69+
expiry: .now.advanced(by: .seconds(AgentLimits.grantSeconds)))
70+
proofs.removeAll { $0.key == proof.key || $0.expiry <= .now }
71+
proofs.append(proof)
72+
if proofs.count > maxProofs { proofs.removeFirst(proofs.count - maxProofs) }
73+
tool(id, text, extra: ["schema_version":2, "profile":selector, "revision":rev,
74+
"body_sha256":hash, "instructions":text])
75+
case receiver:
76+
let required: Set<String> = ["profile", "revision", "idempotency_key", "display_text"]
77+
let keys = Set(args.keys)
78+
guard keys == required || keys == required.union(["speech_text"]),
79+
let profile = args["profile"] as? String, let revision = args["revision"] as? String,
80+
let retry = args["idempotency_key"] as? String,
81+
(1...128).contains(retry.utf8.count), retry.range(of: "^[A-Za-z0-9._-]+$", options: .regularExpression) != nil,
82+
let display = args["display_text"] as? String, AgentBytes.textValid(display),
83+
args["speech_text"].map({ ($0 as? String).map(AgentBytes.textValid) == true }) ?? true else {
84+
tool(id, "Invalid plain-text draft arguments.", failed: true); continue
85+
}
86+
proofs.removeAll { $0.expiry <= .now }
87+
guard let proof = proofs.last(where: { $0.profile == profile && $0.revision == revision }) else {
88+
tool(id, "This helper did not receive that exact revision. Read it first or paste manually.", failed: true); continue
89+
}
90+
var request = args
91+
request["schema_version"] = 2
92+
request["body_sha256"] = proof.bodyHash
93+
request["proof"] = proof.token
94+
let status = exchange(socket: "d.sock", request)?["status"] as? String
95+
switch status {
96+
case "accepted": tool(id, "Queued in the app. Not applied or played.")
97+
case "duplicate": tool(id, "Already received. Nothing new was queued or played.")
98+
case "conflict": tool(id, "Retry key already used for different content.", failed: true)
99+
case "busy": tool(id, "Inbox is full. Nothing was queued.", failed: true)
100+
case "rate_limited": tool(id, "This grant’s receipt rate limit was reached.", failed: true)
101+
case "unproven": tool(id, "Revision proof expired, was revoked, or the profile was deleted. Read again or paste manually.", failed: true)
102+
default: tool(id, "Receipt not confirmed. Retry unchanged or paste manually. Local helper PID: \(getpid()).", failed: true)
103+
}
104+
default:
105+
emit(error(id, -32602, "Unknown tool"))
106+
}
107+
default:
108+
emit(error(id, -32601, "Method unavailable"))
109+
}
110+
}
111+
}
112+
113+
static var tools: [[String: Any]] {
114+
let string = ["type":"string"]
115+
return [["name":reader, "description":"Read one exact locally approved instruction revision.",
116+
"inputSchema":["type":"object","properties":["profile":string],"required":["profile"],"additionalProperties":false],
117+
"annotations":["readOnlyHint":true,"openWorldHint":false]],
118+
["name":receiver, "description":"Queue an editable plain-text draft for a revision received by this helper. Never plays.",
119+
"inputSchema":["type":"object", "properties":["profile":string,"revision":string,"idempotency_key":string,
120+
"display_text":string,"speech_text":string],"required":["profile","revision","idempotency_key","display_text"],
121+
"additionalProperties":false],
122+
"annotations":["readOnlyHint":false,"destructiveHint":false,"idempotentHint":true,"openWorldHint":false]]]
123+
}
124+
125+
static func validSelector(_ selector: String) -> Bool {
126+
if ["explain","continue","normalize"].contains(selector) { return true }
127+
return UUID(uuidString: selector)?.uuidString.lowercased() == selector
128+
}
129+
130+
static func decode(_ data: Data) -> [String: Any]? {
131+
guard !data.contains(0), String(data: data, encoding: .utf8) != nil else { return nil }
132+
return (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]
133+
}
134+
135+
static func readFrame() -> Data? {
136+
var data = Data(), oversized = false
137+
while true {
138+
let c = fgetc(stdin)
139+
if c == EOF { return data.isEmpty && !oversized ? nil : Data() }
140+
if c == 10 { return oversized ? Data() : data }
141+
if data.count + 1 >= maxFrame { oversized = true }
142+
if !oversized { data.append(UInt8(c)) }
143+
}
144+
}
145+
146+
static func exchange(socket endpoint: String, _ request: [String: Any]) -> [String: Any]? {
147+
guard let pin, endpoint == "i.sock" || endpoint == "d.sock" else { return nil }
148+
var st = stat()
149+
let path = directory + "/" + endpoint
150+
guard lstat(directory, &st) == 0, st.st_uid == getuid(), st.st_mode & S_IFMT == S_IFDIR, st.st_mode & 0o777 == 0o700,
151+
lstat(path, &st) == 0, st.st_uid == getuid(), st.st_mode & S_IFMT == S_IFSOCK, st.st_mode & 0o777 == 0o600,
152+
var data = try? JSONSerialization.data(withJSONObject: request, options: [.withoutEscapingSlashes]),
153+
data.count < maxFrame else { return nil }
154+
data.append(10)
155+
var addr = sockaddr_un()
156+
let wire = Array(path.utf8CString)
157+
guard wire.count <= MemoryLayout.size(ofValue: addr.sun_path) else { return nil }
158+
addr.sun_family = sa_family_t(AF_UNIX)
159+
addr.sun_len = UInt8(MemoryLayout<sockaddr_un>.size)
160+
withUnsafeMutableBytes(of: &addr.sun_path) { dst in wire.withUnsafeBytes { dst.copyBytes(from: $0) } }
161+
let fd = Darwin.socket(AF_UNIX, SOCK_STREAM, 0)
162+
guard fd >= 0 else { return nil }
163+
defer { close(fd) }
164+
var yes: Int32 = 1, timeout = timeval(tv_sec: 2, tv_usec: 0)
165+
guard setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &yes, socklen_t(MemoryLayout<Int32>.size)) == 0,
166+
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, socklen_t(MemoryLayout<timeval>.size)) == 0,
167+
setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, socklen_t(MemoryLayout<timeval>.size)) == 0 else { return nil }
168+
let connection = withUnsafePointer(to: &addr) {
169+
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) { connect(fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size)) }
170+
}
171+
guard connection == 0, AgentPeerSigning.matches(socket: fd, identifier: AgentPeerSigning.appID, leaf: pin) else { return nil }
172+
let sent = data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) -> Bool in
173+
guard let base = bytes.baseAddress else { return false }
174+
var done = 0
175+
while done < bytes.count {
176+
let n = send(fd, base.advanced(by: done), bytes.count - done, 0)
177+
if n <= 0 { return false }
178+
done += n
179+
}
180+
return true
181+
}
182+
guard sent, shutdown(fd, SHUT_WR) == 0 else { return nil }
183+
let maximum = endpoint == "i.sock" ? 52 * 1024 : 128
184+
var output = Data(), chunk = [UInt8](repeating: 0, count: 4096)
185+
let deadline = ContinuousClock.now.advanced(by: .seconds(2))
186+
var terminated = false
187+
while ContinuousClock.now < deadline {
188+
let count = chunk.withUnsafeMutableBytes { recv(fd, $0.baseAddress, $0.count, 0) }
189+
if count == 0 { return terminated ? decode(output) : nil }
190+
guard count > 0, !terminated, output.count + count <= maximum else { return nil }
191+
output.append(contentsOf: chunk.prefix(count))
192+
if let newline = output.firstIndex(of: 10) {
193+
guard newline == output.endIndex - 1 else { return nil }
194+
terminated = true
195+
}
196+
}
197+
return nil
198+
}
199+
200+
static func emit(_ envelope: [String: Any]) {
201+
if var data = try? JSONSerialization.data(withJSONObject: envelope, options: [.withoutEscapingSlashes]) {
202+
data.append(10); FileHandle.standardOutput.write(data)
203+
}
204+
}
205+
206+
static func error(_ id: Any?, _ code: Int, _ message: String) -> [String: Any] {
207+
["jsonrpc":"2.0","id":id ?? NSNull(),"error":["code":code,"message":message]]
208+
}
209+
210+
static func result(_ id: Any, _ payload: [String: Any]) {
211+
emit(["jsonrpc":"2.0","id":id,"result":payload])
212+
}
213+
214+
static func tool(_ id: Any, _ message: String, failed: Bool = false, extra: [String: Any]? = nil) {
215+
var value: [String: Any] = ["content":[["type":"text","text":message]],"isError":failed]
216+
if let extra { value["structuredContent"] = extra }
217+
result(id, value)
218+
}
219+
}

‎README.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,8 @@ macOS용 TTS 앱: **텍스트 읽기, 에이전트 지시 관리, 받은 대본
6161

6262
창을 닫아도 Dock 아이콘과 실행 중인 앱은 유지됩니다. Dock에서 다시 열거나 `⌘Q`로 앱을 완전히 종료하세요.
6363

64-
**에이전트** 탭은 외부 에이전트의 **지시 조회 허용**과 **대본 받기 허용**을 따로 관리합니다.
64+
**에이전트** 탭에서 이름을 붙인 지시를 저장·편집·선택하고, 정확한 원문을 미리 보거나 복사할 수 있습니다.
65+
**지시 조회 허용**과 **대본 받기 허용**은 서명된 도우미 한 개를 대상으로 각각 따로 켭니다.
6566
허용하지 않아도 직접 입력하거나 붙여넣을 수 있습니다. 기본 지시 프로필은 코드 해설용이지만 대본 수신·편집·재생은 다른 용도에도 쓸 수 있습니다. 기존 앱 내 해설은
6667
**고급: 앱에서 직접 해설 생성…**에 남아 있습니다. 선택 텍스트 읽기 단축키와 일반 Services는 그대로입니다.
6768
자세한 연결과 검증은 [외부 에이전트 대본](docs/mcp-explanation-drafts.md)을 참고하세요.

‎Sources/App/AgentPeerSigning.swift‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import CryptoKit
2+
import Darwin
3+
import Foundation
4+
import Security
5+
6+
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"
10+
11+
static func ownLeaf() -> String? {
12+
var code: SecCode?
13+
var staticCode: SecStaticCode?
14+
var info: CFDictionary?
15+
guard SecCodeCopySelf([], &code) == errSecSuccess, let code,
16+
SecCodeCopyStaticCode(code, [], &staticCode) == errSecSuccess, let staticCode,
17+
SecCodeCopySigningInformation(staticCode, SecCSFlags(rawValue: kSecCSSigningInformation), &info) == errSecSuccess,
18+
let certificates = (info as? [String: Any])?[kSecCodeInfoCertificates as String] as? [SecCertificate],
19+
let certificate = certificates.first else { return nil }
20+
return Insecure.SHA1.hash(data: SecCertificateCopyData(certificate) as Data)
21+
.map { String(format: "%02x", $0) }.joined()
22+
}
23+
24+
static func bundledHelperHash() -> Data? {
25+
signedHash(at: Bundle.main.bundleURL.appendingPathComponent("Contents/Helpers/CodebasicAgentMCP"))
26+
}
27+
28+
static func signedHash(at url: URL) -> Data? {
29+
var code: SecStaticCode?
30+
guard SecStaticCodeCreateWithPath(url as CFURL, [], &code) == errSecSuccess, let code else { return nil }
31+
return signedHash(code)
32+
}
33+
34+
static func matches(pid: pid_t, identifier: String, leaf: String, expectedHash: Data) -> Bool {
35+
check([kSecGuestAttributePid as String: NSNumber(value: pid)], identifier: identifier, leaf: leaf,
36+
expectedHash: expectedHash)
37+
}
38+
39+
static func matches(socket fd: Int32, identifier: String, leaf: String, expectedHash: Data? = nil) -> Bool {
40+
var uid: uid_t = 0, gid: gid_t = 0
41+
var token = audit_token_t()
42+
var count = socklen_t(MemoryLayout<audit_token_t>.size)
43+
guard getpeereid(fd, &uid, &gid) == 0, uid == geteuid(),
44+
getsockopt(fd, SOL_LOCAL, LOCAL_PEERTOKEN, &token, &count) == 0,
45+
count == MemoryLayout<audit_token_t>.size else { return false }
46+
return check([kSecGuestAttributeAudit as String: Data(bytes: &token, count: Int(count))],
47+
identifier: identifier, leaf: leaf, expectedHash: expectedHash)
48+
}
49+
50+
private static func signedHash(_ code: SecStaticCode) -> Data? {
51+
var info: CFDictionary?
52+
guard SecCodeCopySigningInformation(code, [], &info) == errSecSuccess else { return nil }
53+
return (info as? [String: Any])?[kSecCodeInfoUnique as String] as? Data
54+
}
55+
56+
private static func check(_ attributes: [String: Any], identifier: String, leaf: String, expectedHash: Data?) -> Bool {
57+
guard identifier == appID || identifier == helperID,
58+
leaf.utf8.count == 40, leaf.utf8.allSatisfy({ (48...57).contains($0) || (97...102).contains($0) }) else {
59+
return false
60+
}
61+
let expression = "identifier \"\(identifier)\" and certificate leaf = H\"\(leaf)\""
62+
var requirement: SecRequirement?
63+
var guest: SecCode?
64+
guard SecRequirementCreateWithString(expression as CFString, [], &requirement) == errSecSuccess,
65+
let requirement,
66+
SecCodeCopyGuestWithAttributes(nil, attributes as CFDictionary, [], &guest) == errSecSuccess,
67+
let guest else { return false }
68+
guard SecCodeCheckValidity(guest, [], requirement) == errSecSuccess else { return false }
69+
guard let expectedHash else { return true }
70+
var code: SecStaticCode?
71+
guard SecCodeCopyStaticCode(guest, [], &code) == errSecSuccess, let code else { return false }
72+
return signedHash(code) == expectedHash
73+
}
74+
}

0 commit comments

Comments
 (0)