diff --git a/.github/workflows/build-macos-arm-dmg.yml b/.github/workflows/build-macos-arm-dmg.yml
index 2b944c254..c277a3795 100644
--- a/.github/workflows/build-macos-arm-dmg.yml
+++ b/.github/workflows/build-macos-arm-dmg.yml
@@ -134,6 +134,11 @@ jobs:
--team-id "$APPLE_TEAM_ID" \
--password "$APPLE_APP_SPECIFIC_PASSWORD"
+ - name: Set up Go
+ uses: actions/setup-go@v5
+ with:
+ go-version: '1.23'
+
- name: Build DMG
run: ./scripts/build-dmg.sh "$VERSION"
@@ -144,6 +149,8 @@ jobs:
SPARKLE_ARCHS="$(lipo -archs .build/dmg-staging/CodeIsland.app/Contents/Frameworks/Sparkle.framework/Sparkle)"
test "$APP_ARCHS" = "arm64"
test "$HELPER_ARCHS" = "arm64"
+ FEISHU_ARCHS="$(lipo -archs .build/dmg-staging/CodeIsland.app/Contents/Helpers/feishu-bridge)"
+ test "$FEISHU_ARCHS" = "arm64"
test "$SPARKLE_ARCHS" = "arm64"
test -s .build/dmg-staging/CodeIsland.app/Contents/Resources/AppIcon.icns
test "$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIconFile' .build/dmg-staging/CodeIsland.app/Contents/Info.plist)" = "AppIcon"
diff --git a/.gitignore b/.gitignore
index 7f3578159..e1ee4fe08 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,5 +1,6 @@
# Build artifacts
.build/
+helpers/feishu-bridge/dist/
.swiftpm/
# Superpowers artifacts
diff --git a/README.md b/README.md
index 785c4e4b7..736d0cdef 100644
--- a/README.md
+++ b/README.md
@@ -310,7 +310,17 @@ Cowork runs inside Claude Desktop's sandbox, where hooks never fire, so CodeIsla
-**Settings → Behavior → Push notifications** sends approvals, questions (with numbered options), finished turns, turn errors and follow-up reminders to Bark, ntfy, DingTalk, Lark / Feishu, WeCom, Slack or Telegram — several at once, each with its own event choices and a **Send test** button that shows the service's real reply. By default a push only goes out while you're away (screen locked, screen saver, displays asleep, or no keyboard / mouse input for 5 minutes), and subagent turns are never pushed. Commands and messages go through the same credential redaction as the rest of the app. Pushes answer nothing: approve on the Mac.
+**Settings → Behavior → Push notifications** sends approvals, questions (with numbered options), finished turns, turn errors and follow-up reminders to Bark, ntfy, DingTalk, Lark / Feishu, WeCom, Slack or Telegram — several at once, each with its own event choices and a **Send test** button that shows the service's real reply. By default a push only goes out while you're away (screen locked, screen saver, displays asleep, or no keyboard / mouse input for 5 minutes), and subagent turns are never pushed. Commands and messages go through the same credential redaction as the rest of the app. Pushes answer nothing: approve on the Mac, or with Feishu remote approval below.
+
+
+
+
+
+Feishu remote approval
+
+
+
+**Settings → Behavior → Feishu remote approval** can answer a permission request from a private Feishu chat: Allow once, or Deny. It is not the one-way Feishu webhook under Push notifications, and a text reply never approves a command. Use a company self-built bot. The App Secret stays in the Keychain. Turn the long connection on here before saving the Feishu event and card subscriptions, keep the bot available only to yourself, and do not add it to a group. The card has no Always allow. A timeout, a disconnect, another account, or a second tap on the same card does not allow the command.
@@ -326,14 +336,14 @@ AI tool (Claude Code / Codex / Gemini / Cursor / …)
CodeIsland installs lightweight hooks into each tool's own config. When the tool fires an event — session start, tool call, permission request, question, stop — the bridge forwards it as JSON over a local Unix socket, and the island updates instantly. For events that wait on you, the answer travels back the same way.
-**Privacy:** events never leave your Mac unless you opt in. The only network requests CodeIsland makes are Sparkle update checks, plus — only if you turn them on — Claude plan-limit lookups (sent to `api.anthropic.com` with your own Claude Code login), webhook forwarding to the URL you configure, and pushes to the services you set up.
+**Privacy:** events never leave your Mac unless you opt in. The only network requests CodeIsland makes are Sparkle update checks, plus — only if you turn them on — Claude plan-limit lookups (sent to `api.anthropic.com` with your own Claude Code login), webhook forwarding to the URL you configure, pushes to the services you set up, and — only while Feishu remote approval is connected — an outbound long connection that sends private approval cards.
## Settings
| Page | What's there |
|------|--------------|
| **General** | Language, launch at login, display selection |
-| **Behavior** | Auto-expand (approvals and questions separately), hover delay, smart suppress, completion style, follow-up reminders, session cleanup, silence rules, auto-approve, push notifications, webhook |
+| **Behavior** | Auto-expand (approvals and questions separately), hover delay, smart suppress, completion style, follow-up reminders, session cleanup, silence rules, auto-approve, push notifications, Feishu remote approval, webhook |
| **Appearance** | Panel size, notch width, font size, reply lines, open/close speed, project name, git branch, task progress, session recap, model label, usage stats, plan limits |
| **Mascots** | Preview every character and its animations |
| **Sound** | 8-bit sounds per event, volume, quiet hours, mute while away |
diff --git a/README.zh-CN.md b/README.zh-CN.md
index ed291227b..54db5c167 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -310,7 +310,17 @@ Cowork 跑在 Claude Desktop 的沙盒里,hook 不会触发,所以 CodeIslan
-**设置 → 行为 → 推送通知** 可以把审批、提问(附编号选项)、完成、整轮出错和跟进提醒推送到 Bark、ntfy、钉钉、飞书 / Lark、企业微信、Slack 或 Telegram。可以同时启用多个通道,每个通道单独选择推送哪些事件,「发送测试」按钮会显示服务端的真实返回。默认只在你离开时推送(锁屏、屏保、显示器睡眠,或键盘鼠标 5 分钟没有操作),子 Agent 的回合不推送。命令和消息会经过和应用其他部分相同的凭据脱敏。推送只负责通知,审批仍需回到 Mac 上操作。
+**设置 → 行为 → 推送通知** 可以把审批、提问(附编号选项)、完成、整轮出错和跟进提醒推送到 Bark、ntfy、钉钉、飞书 / Lark、企业微信、Slack 或 Telegram。可以同时启用多个通道,每个通道单独选择推送哪些事件,「发送测试」按钮会显示服务端的真实返回。默认只在你离开时推送(锁屏、屏保、显示器睡眠,或键盘鼠标 5 分钟没有操作),子 Agent 的回合不推送。命令和消息会经过和应用其他部分相同的凭据脱敏。推送只负责通知。要在手机上点允许或拒绝,用下面的飞书远程审批,不要用这条 webhook。
+
+
+
+
+
+飞书远程审批
+
+
+
+**设置 → 行为 → 飞书远程审批** 可以把一条权限请求发到飞书私聊,在手机上点「允许一次」或「拒绝」。它和推送通知里的飞书 webhook 不是一回事,聊天里回复文字也不会批准命令。需要企业自建应用,App Secret 只放在钥匙串。先在这里连上长连接,再去飞书后台保存事件和卡片订阅;可用范围只留给自己,不要把机器人拉进群。卡片没有「始终允许」。超时、断线、别人的账号,或同一张卡片再点一次,都不会允许。
@@ -326,14 +336,14 @@ AI 工具(Claude Code / Codex / Gemini / Cursor / …)
CodeIsland 往每个工具自己的配置里装一个轻量 hook。工具触发事件时(会话开始、工具调用、权限请求、提问、结束),bridge 把事件以 JSON 形式经本机 Unix socket 转发过来,刘海立即更新。需要你做决定的事件,答案也沿同一条路回传。
-**隐私:** 除非你主动开启,事件不会离开你的 Mac。CodeIsland 发出的网络请求只有:Sparkle 更新检查;以及仅在你打开时才有的 Claude 套餐额度查询(用你自己的 Claude Code 登录请求 `api.anthropic.com`)、发往你所配置地址的 Webhook 转发,以及发往你所配置服务的推送。
+**隐私:** 除非你主动开启,事件不会离开你的 Mac。CodeIsland 发出的网络请求只有:Sparkle 更新检查;以及仅在你打开时才有的 Claude 套餐额度查询(用你自己的 Claude Code 登录请求 `api.anthropic.com`)、发往你所配置地址的 Webhook 转发、发往你所配置服务的推送,以及仅在打开飞书远程审批并连上时长连接时,向飞书发送的私聊审批卡片。
## 设置
| 页面 | 内容 |
|------|------|
| **通用** | 语言、开机启动、显示器选择 |
-| **行为** | 自动展开(审批与提问分开设置)、悬停展开延迟、智能抑制、完成提示方式、跟进提醒、会话清理、静默规则、自动放行、推送通知、Webhook |
+| **行为** | 自动展开(审批与提问分开设置)、悬停展开延迟、智能抑制、完成提示方式、跟进提醒、会话清理、静默规则、自动放行、推送通知、飞书远程审批、Webhook |
| **外观** | 面板尺寸、刘海宽度、字号、回复行数、展开 / 收起速度、项目名、Git 分支、任务进度、会话回顾、模型标签、用量统计、套餐额度 |
| **角色** | 预览所有像素角色和它们的动画 |
| **声音** | 按事件的 8-bit 音效、音量、静默时段、离开时自动静音 |
diff --git a/Sources/CodeIsland/AppDelegate.swift b/Sources/CodeIsland/AppDelegate.swift
index 1a79f2b4a..64d4d6ba2 100644
--- a/Sources/CodeIsland/AppDelegate.swift
+++ b/Sources/CodeIsland/AppDelegate.swift
@@ -80,6 +80,8 @@ class AppDelegate: NSObject, NSApplicationDelegate {
if isolated {
Self.log.notice("Isolated (CODEISLAND_ISOLATED=1): no hooks installed, no sessions discovered, no remote hosts connected")
} else {
+ FeishuApprovalCenter.shared.attach(appState)
+ FeishuApprovalCenter.shared.startIfConfigured()
Task.detached(priority: .userInitiated) {
if ConfigInstaller.install() {
Self.log.info("Hooks installed")
diff --git a/Sources/CodeIsland/AppState+ToolUseCache.swift b/Sources/CodeIsland/AppState+ToolUseCache.swift
index e2bf6f02b..4eaf936c6 100644
--- a/Sources/CodeIsland/AppState+ToolUseCache.swift
+++ b/Sources/CodeIsland/AppState+ToolUseCache.swift
@@ -198,6 +198,7 @@ extension AppState {
permissionQueue.removeAll { droppedIds.contains($0.id) }
for stale in dropped {
log.notice("⚠️ permission dropped, no decision reason=\(reason, privacy: .public) session=\(stale.event.sessionId ?? "nil", privacy: .public) toolUseId=\(stale.toolUseId ?? "nil", privacy: .public) tool=\(stale.event.toolName ?? "nil", privacy: .public) triggerEvent=\(triggerEvent, privacy: .public)")
+ notifyFeishuPermissionFinished(stale.id, decision: "gone")
stale.continuation.resume(returning: Self.noDecisionAnswer)
}
diff --git a/Sources/CodeIsland/AppState.swift b/Sources/CodeIsland/AppState.swift
index 3f0ffd989..75f8f70f1 100644
--- a/Sources/CodeIsland/AppState.swift
+++ b/Sources/CodeIsland/AppState.swift
@@ -2186,6 +2186,7 @@ final class AppState {
// already in progress.
let burstAlreadyInProgress = nextVisiblePermissionIndex() != nil
permissionQueue.append(request)
+ publishFeishuPermission(request)
let attention = decideAttention(.approvalQueued(firstOfBurst: !burstAlreadyInProgress), sessionId: sessionId)
pushPermissionQueued(event, sessionId: sessionId, push: attention.push)
@@ -2232,6 +2233,26 @@ final class AppState {
refreshDerivedState()
}
+ func notifyFeishuPermissionFinished(_ id: UUID, decision: String) {
+ FeishuApprovalCenter.shared.noteFinished(id: id, decision: decision)
+ }
+
+ func publishFeishuPermission(_ request: PermissionRequest) {
+ let event = request.event
+ FeishuApprovalCenter.shared.offer(
+ id: request.id,
+ source: (event.rawJSON["_source"] as? String) ?? "",
+ tool: event.toolName ?? "",
+ cwd: (event.rawJSON["cwd"] as? String) ?? "",
+ command: PushDetailSummarizer.permissionDetail(
+ toolInput: event.toolInput,
+ fallback: event.toolDescription,
+ cwd: event.rawJSON["cwd"] as? String
+ ) ?? "",
+ sessionId: event.sessionId ?? ""
+ )
+ }
+
func approvePermission(always: Bool = false, expectedSessionId: String? = nil) {
guard let index = permissionIndex(expecting: expectedSessionId) else {
if let expectedSessionId {
@@ -2239,6 +2260,19 @@ final class AppState {
}
return
}
+ approveQueuedPermission(at: index, always: always)
+ }
+
+ /// A Feishu card names one request, which may not be the card on screen.
+ /// Allow once only: remote approval never writes an always-allow rule.
+ @discardableResult
+ func approvePermission(requestId: UUID) -> Bool {
+ guard let index = permissionQueue.firstIndex(where: { $0.id == requestId }) else { return false }
+ approveQueuedPermission(at: index, always: false)
+ return true
+ }
+
+ private func approveQueuedPermission(at index: Int, always: Bool) {
let pending = permissionQueue.remove(at: index)
let sessionId = pending.event.sessionId ?? "default"
dismissedPermissionSessionIds.remove(sessionId)
@@ -2257,6 +2291,7 @@ final class AppState {
answerQueuedRequestsCoveredByAlways(sessionId: sessionId)
}
+ notifyFeishuPermissionFinished(pending.id, decision: "allow")
showNextPending()
refreshDerivedState()
}
@@ -2274,6 +2309,7 @@ final class AppState {
permissionQueue.removeAll { ids.contains($0.id) }
for request in covered {
request.continuation.resume(returning: Self.plainAllowAnswer)
+ notifyFeishuPermissionFinished(request.id, decision: "allow")
resolveMergedSubagentAfterUI(
sessionId: sessionId,
agentId: request.event.agentId,
@@ -2523,6 +2559,18 @@ final class AppState {
}
return
}
+ denyQueuedPermission(at: index)
+ }
+
+ /// See `approvePermission(requestId:)`.
+ @discardableResult
+ func denyPermission(requestId: UUID) -> Bool {
+ guard let index = permissionQueue.firstIndex(where: { $0.id == requestId }) else { return false }
+ denyQueuedPermission(at: index)
+ return true
+ }
+
+ private func denyQueuedPermission(at index: Int) {
let pending = permissionQueue.remove(at: index)
let sessionId = pending.event.sessionId ?? "default"
dismissedPermissionSessionIds.remove(sessionId)
@@ -2541,6 +2589,7 @@ final class AppState {
activeSessionId = mostActiveSessionId()
}
+ notifyFeishuPermissionFinished(pending.id, decision: "deny")
showNextPending()
refreshDerivedState()
}
@@ -3071,6 +3120,7 @@ final class AppState {
permissionQueue.removeAll { item in
guard item.event.sessionId == sessionId, matches(item.event) else { return false }
log.notice("⚠️ permission dropped, no decision reason=drainPermissions(\(reason, privacy: .public)) session=\(sessionId, privacy: .public) toolUseId=\(item.toolUseId ?? "nil", privacy: .public) tool=\(item.event.toolName ?? "nil", privacy: .public)")
+ notifyFeishuPermissionFinished(item.id, decision: "gone")
item.continuation.resume(returning: Self.noDecisionAnswer)
return true
}
@@ -3102,6 +3152,7 @@ final class AppState {
let pending = permissionQueue.remove(at: index)
sessionId = pending.event.sessionId ?? "default"
log.notice("⚠️ permission deny reason=hookGone session=\(sessionId, privacy: .public) toolUseId=\(pending.toolUseId ?? "nil", privacy: .public) tool=\(pending.event.toolName ?? "nil", privacy: .public)")
+ notifyFeishuPermissionFinished(pending.id, decision: "gone")
// Nobody reads it, but the continuation must not leak.
pending.continuation.resume(returning: Data(
#"{"hookSpecificOutput":{"hookEventName":"PermissionRequest","decision":{"behavior":"deny"}}}"#.utf8
diff --git a/Sources/CodeIsland/FeishuApprovalCenter.swift b/Sources/CodeIsland/FeishuApprovalCenter.swift
new file mode 100644
index 000000000..531a27ced
--- /dev/null
+++ b/Sources/CodeIsland/FeishuApprovalCenter.swift
@@ -0,0 +1,429 @@
+import Foundation
+import Security
+import CodeIslandCore
+
+/// Outbound Feishu long connection for Codex permission cards.
+///
+/// The helper process is the only thing that speaks to Feishu. This type
+/// decides. A card button names one request id and either allow-once or deny.
+/// Chat text, another Feishu account, a replay, or a request that is already
+/// gone never becomes an allow.
+@MainActor
+final class FeishuApprovalCenter: ObservableObject {
+ static let shared = FeishuApprovalCenter()
+
+ @Published private(set) var statusText = ""
+ @Published private(set) var isPaired = false
+ @Published private(set) var hasSecret = false
+ @Published private(set) var pairCandidateOpenID: String?
+ @Published private(set) var online = false
+
+ private weak var appState: AppState?
+ private var process: Process?
+ private var input: FileHandle?
+ private var splitter = LineSplitter()
+ private var generation = 0
+ private var restartAttempt = 0
+ private var notices: [UUID: Notice] = [:]
+ private let writer = DispatchQueue(label: "com.codeisland.feishu-approval.write")
+
+ private init() {
+ refreshIdentity()
+ if statusText.isEmpty {
+ statusText = Self.text(
+ "未连接。填写企业自建应用的 App ID 和 App Secret 后保存。",
+ "Not connected. Enter the self-built app's App ID and App Secret, then save."
+ )
+ }
+ }
+
+ func attach(_ appState: AppState) {
+ self.appState = appState
+ }
+
+ func refreshIdentity() {
+ hasSecret = FeishuSecretStore.load() != nil
+ let openID = UserDefaults.standard.string(forKey: SettingsKey.feishuApprovalOpenID) ?? ""
+ isPaired = !openID.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ }
+
+ func startIfConfigured() {
+ refreshIdentity()
+ guard UserDefaults.standard.bool(forKey: SettingsKey.feishuApprovalEnabled) else { return }
+ let appID = (UserDefaults.standard.string(forKey: SettingsKey.feishuApprovalAppID) ?? "")
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !appID.isEmpty, FeishuSecretStore.load() != nil else {
+ statusText = Self.text(
+ "已打开,但还没有可用的 App ID 和 App Secret。",
+ "Enabled, but there is no App ID and App Secret yet."
+ )
+ return
+ }
+ spawn()
+ }
+
+ func setEnabled(_ enabled: Bool) {
+ UserDefaults.standard.set(enabled, forKey: SettingsKey.feishuApprovalEnabled)
+ if enabled {
+ startIfConfigured()
+ } else {
+ stop()
+ online = false
+ statusText = Self.text(
+ "已关闭。待批的命令仍留在这台 Mac 上,不会自动允许。",
+ "Turned off. Pending commands stay on this Mac and are not allowed automatically."
+ )
+ }
+ }
+
+ func save(appID: String, secretInput: String) {
+ let trimmedID = appID.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmedID.isEmpty else {
+ statusText = Self.text("请填写 App ID。", "Enter the App ID.")
+ return
+ }
+ let typed = secretInput.trimmingCharacters(in: .whitespacesAndNewlines)
+ if !typed.isEmpty {
+ guard FeishuSecretStore.save(typed) else {
+ statusText = Self.text("钥匙串没有收下 App Secret。", "Keychain did not store the App Secret.")
+ return
+ }
+ } else if FeishuSecretStore.load() == nil {
+ statusText = Self.text(
+ "请填写 App Secret。它只写入钥匙串,不进配置文件。",
+ "Enter the App Secret. It is stored in the Keychain, not in preferences."
+ )
+ return
+ }
+ UserDefaults.standard.set(trimmedID, forKey: SettingsKey.feishuApprovalAppID)
+ UserDefaults.standard.set(true, forKey: SettingsKey.feishuApprovalEnabled)
+ hasSecret = true
+ stop()
+ spawn()
+ }
+
+ func clearSecret() {
+ FeishuSecretStore.delete()
+ hasSecret = false
+ stop()
+ statusText = Self.text("已从钥匙串删除 App Secret。", "Removed the App Secret from the Keychain.")
+ }
+
+ func armBind() {
+ guard process?.isRunning == true else {
+ statusText = Self.text("先保存凭证并连上飞书,再开始绑定。", "Save the credentials and connect before binding.")
+ return
+ }
+ send(["op": "arm_bind"])
+ statusText = Self.text(
+ "请用要绑定的飞书给机器人发一条私聊。文字不会批准命令。",
+ "Send the bot a private message from the Feishu account you want to bind. Text is never an approval."
+ )
+ }
+
+ func confirmBind() {
+ guard let openID = pairCandidateOpenID?.trimmingCharacters(in: .whitespacesAndNewlines), !openID.isEmpty else {
+ return
+ }
+ UserDefaults.standard.set(openID, forKey: SettingsKey.feishuApprovalOpenID)
+ isPaired = true
+ pairCandidateOpenID = nil
+ send(["op": "bind", "open_id": openID])
+ statusText = Self.text("已绑定。之后只有这个账号的按钮有效。", "Bound. Only this account's buttons count.")
+ flush()
+ }
+
+ func unbind() {
+ UserDefaults.standard.removeObject(forKey: SettingsKey.feishuApprovalOpenID)
+ isPaired = false
+ pairCandidateOpenID = nil
+ send(["op": "unbind"])
+ statusText = Self.text("已解除绑定。新的审批不会发到飞书。", "Unbound. New approvals are not sent to Feishu.")
+ }
+
+ func offer(
+ id: UUID,
+ source: String,
+ tool: String,
+ cwd: String,
+ command: String,
+ sessionId: String
+ ) {
+ guard UserDefaults.standard.bool(forKey: SettingsKey.feishuApprovalEnabled) else { return }
+ notices[id] = Notice(
+ source: PushMessageFormatter.clean(source, limit: 40) ?? "",
+ tool: PushMessageFormatter.clean(tool, limit: 120) ?? "",
+ cwd: PushMessageFormatter.clean(cwd, limit: 400) ?? "",
+ command: PushMessageFormatter.clean(command, limit: 1500) ?? "",
+ sessionId: PushMessageFormatter.clean(sessionId, limit: 80) ?? ""
+ )
+ flush()
+ }
+
+ func noteFinished(id: UUID, decision: String) {
+ notices.removeValue(forKey: id)
+ guard process?.isRunning == true else { return }
+ let normalized = (decision == "allow" || decision == "deny") ? decision : "gone"
+ send(["op": "resolved", "request_id": id.uuidString, "decision": normalized])
+ }
+
+ private func spawn() {
+ generation += 1
+ let token = generation
+ if process?.isRunning == true {
+ process?.terminate()
+ }
+ process = nil
+ input = nil
+ online = false
+ guard let executable = Self.helperURL() else {
+ statusText = Self.text(
+ "找不到 feishu-bridge。请安装带飞书审批 helper 的这个包。",
+ "feishu-bridge is missing. Install the build that contains the Feishu approval helper."
+ )
+ return
+ }
+ guard let secret = FeishuSecretStore.load() else {
+ statusText = Self.text("钥匙串里没有 App Secret。", "No App Secret is in the Keychain.")
+ return
+ }
+ let appID = (UserDefaults.standard.string(forKey: SettingsKey.feishuApprovalAppID) ?? "")
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !appID.isEmpty else { return }
+ let openID = UserDefaults.standard.string(forKey: SettingsKey.feishuApprovalOpenID) ?? ""
+
+ let proc = Process()
+ proc.executableURL = executable
+ let inPipe = Pipe()
+ let outPipe = Pipe()
+ let errPipe = Pipe()
+ proc.standardInput = inPipe
+ proc.standardOutput = outPipe
+ proc.standardError = errPipe
+ splitter = LineSplitter()
+ outPipe.fileHandleForReading.readabilityHandler = { [splitter] handle in
+ let data = handle.availableData
+ let lines = splitter.append(data)
+ if lines.isEmpty && !data.isEmpty { return }
+ Task { @MainActor in
+ guard self.generation == token else { return }
+ for line in lines { self.consume(line) }
+ }
+ }
+ errPipe.fileHandleForReading.readabilityHandler = { handle in
+ _ = handle.availableData
+ }
+ proc.terminationHandler = { _ in
+ Task { @MainActor in
+ guard self.generation == token else { return }
+ self.process = nil
+ self.input = nil
+ self.online = false
+ self.scheduleRestart()
+ }
+ }
+ do {
+ try proc.run()
+ } catch {
+ statusText = Self.text("飞书 helper 没有启动。", "The Feishu helper did not start.")
+ return
+ }
+ process = proc
+ input = inPipe.fileHandleForWriting
+ statusText = Self.text("正在连接飞书长连接。", "Connecting to Feishu.")
+ send([
+ "op": "configure",
+ "app_id": appID,
+ "app_secret": secret,
+ "open_id": openID.trimmingCharacters(in: .whitespacesAndNewlines),
+ ])
+ }
+
+ private func stop() {
+ generation += 1
+ online = false
+ let running = process
+ process = nil
+ input = nil
+ running?.terminate()
+ }
+
+ private func scheduleRestart() {
+ guard UserDefaults.standard.bool(forKey: SettingsKey.feishuApprovalEnabled) else { return }
+ restartAttempt += 1
+ let delay = min(30, max(2, restartAttempt * 2))
+ let token = generation
+ statusText = Self.text(
+ "飞书连接断了,\(delay) 秒后重试。断线不会自动允许。",
+ "Feishu disconnected. Retrying in \(delay)s. A disconnect does not allow anything."
+ )
+ Task { @MainActor in
+ try? await Task.sleep(nanoseconds: UInt64(delay) * 1_000_000_000)
+ guard self.generation == token, self.process == nil else { return }
+ guard UserDefaults.standard.bool(forKey: SettingsKey.feishuApprovalEnabled) else { return }
+ self.spawn()
+ }
+ }
+
+ private func flush() {
+ guard online, isPaired, process?.isRunning == true else { return }
+ for id in Array(notices.keys) {
+ guard var notice = notices[id], !notice.sent else { continue }
+ send([
+ "op": "card",
+ "request_id": id.uuidString,
+ "source": notice.source,
+ "tool": notice.tool,
+ "cwd": notice.cwd,
+ "command": notice.command,
+ "session": notice.sessionId,
+ ])
+ notice.sent = true
+ notices[id] = notice
+ }
+ }
+
+ private func consume(_ line: String) {
+ guard let data = line.data(using: .utf8),
+ let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+ let op = object["op"] as? String else { return }
+ switch op {
+ case "status":
+ let state = object["state"] as? String ?? ""
+ let detail = object["detail"] as? String ?? ""
+ online = state == "online"
+ if online { restartAttempt = 0 }
+ statusText = detail.isEmpty ? state : detail
+ if online { flush() }
+ case "pair_candidate":
+ let openID = (object["open_id"] as? String ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !openID.isEmpty, !isPaired else { return }
+ pairCandidateOpenID = openID
+ statusText = Self.text(
+ "收到私聊。确认是你的账号后点「绑定这个账号」。",
+ "A private message arrived. Confirm it is your account, then bind it."
+ )
+ case "card_action":
+ apply(object)
+ case "log":
+ if let message = object["message"] as? String, !message.isEmpty {
+ statusText = message
+ }
+ default:
+ break
+ }
+ }
+
+ private func apply(_ object: [String: Any]) {
+ let decision = object["decision"] as? String ?? ""
+ guard decision == "allow" || decision == "deny" else { return }
+ guard let rawID = object["request_id"] as? String, let id = UUID(uuidString: rawID) else { return }
+ let openID = (object["open_id"] as? String ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
+ let paired = (UserDefaults.standard.string(forKey: SettingsKey.feishuApprovalOpenID) ?? "")
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !paired.isEmpty, openID == paired else { return }
+ let applied: Bool
+ if decision == "allow" {
+ applied = appState?.approvePermission(requestId: id) ?? false
+ } else {
+ applied = appState?.denyPermission(requestId: id) ?? false
+ }
+ if !applied {
+ noteFinished(id: id, decision: "gone")
+ }
+ }
+
+ private func send(_ object: [String: Any]) {
+ guard let handle = input, process?.isRunning == true,
+ let data = try? JSONSerialization.data(withJSONObject: object) else { return }
+ var line = data
+ line.append(0x0A)
+ writer.async {
+ try? handle.write(contentsOf: line)
+ }
+ }
+
+ private static func helperURL() -> URL? {
+ let fm = FileManager.default
+ var candidates: [URL] = []
+ if let env = ProcessInfo.processInfo.environment["CODEISLAND_FEISHU_BRIDGE"], !env.isEmpty {
+ candidates.append(URL(fileURLWithPath: env))
+ }
+ candidates.append(Bundle.main.bundleURL.appendingPathComponent("Contents/Helpers/feishu-bridge"))
+ candidates.append(Bundle.main.bundleURL.deletingLastPathComponent().appendingPathComponent("feishu-bridge"))
+ return candidates.first { fm.isExecutableFile(atPath: $0.path) }
+ }
+
+ private static func text(_ zh: String, _ en: String) -> String {
+ L10n.shared.effectiveLanguage.hasPrefix("zh") ? zh : en
+ }
+}
+
+private struct Notice {
+ var source: String
+ var tool: String
+ var cwd: String
+ var command: String
+ var sessionId: String
+ var sent = false
+}
+
+private final class LineSplitter: @unchecked Sendable {
+ private var pending = Data()
+
+ func append(_ data: Data) -> [String] {
+ guard !data.isEmpty else { return [] }
+ pending.append(data)
+ var lines: [String] = []
+ while let newline = pending.firstIndex(of: 0x0A) {
+ let chunk = pending.subdata(in: pending.startIndex.. Bool {
+ delete()
+ let query: [String: Any] = [
+ kSecClass as String: kSecClassGenericPassword,
+ kSecAttrService as String: service,
+ kSecAttrAccount as String: account,
+ kSecValueData as String: Data(secret.utf8),
+ kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlock,
+ ]
+ return SecItemAdd(query as CFDictionary, nil) == errSecSuccess
+ }
+
+ static func load() -> String? {
+ let query: [String: Any] = [
+ kSecClass as String: kSecClassGenericPassword,
+ kSecAttrService as String: service,
+ kSecAttrAccount as String: account,
+ kSecReturnData as String: true,
+ kSecMatchLimit as String: kSecMatchLimitOne,
+ ]
+ var item: CFTypeRef?
+ guard SecItemCopyMatching(query as CFDictionary, &item) == errSecSuccess,
+ let data = item as? Data else { return nil }
+ let secret = String(data: data, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines)
+ return secret?.isEmpty == false ? secret : nil
+ }
+
+ static func delete() {
+ let query: [String: Any] = [
+ kSecClass as String: kSecClassGenericPassword,
+ kSecAttrService as String: service,
+ kSecAttrAccount as String: account,
+ ]
+ SecItemDelete(query as CFDictionary)
+ }
+}
diff --git a/Sources/CodeIsland/FeishuApprovalSettingsView.swift b/Sources/CodeIsland/FeishuApprovalSettingsView.swift
new file mode 100644
index 000000000..1a0f4855c
--- /dev/null
+++ b/Sources/CodeIsland/FeishuApprovalSettingsView.swift
@@ -0,0 +1,71 @@
+import SwiftUI
+
+/// Settings control for the Feishu approval long connection. The App Secret
+/// stays in the Keychain; this view only holds it until the user saves.
+struct FeishuApprovalSettingsSection: View {
+ @ObservedObject private var l10n = L10n.shared
+ @ObservedObject private var center = FeishuApprovalCenter.shared
+ @AppStorage(SettingsKey.feishuApprovalEnabled) private var enabled = SettingsDefaults.feishuApprovalEnabled
+ @AppStorage(SettingsKey.feishuApprovalAppID) private var appID = SettingsDefaults.feishuApprovalAppID
+ @State private var secret = ""
+
+ var body: some View {
+ Section(l10n["feishu_approval_title"]) {
+ Text(l10n["feishu_approval_desc"])
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ Toggle(l10n["feishu_approval_enable"], isOn: $enabled)
+ .onChange(of: enabled) { _, newValue in
+ center.setEnabled(newValue)
+ }
+ if enabled {
+ TextField(l10n["feishu_approval_app_id"], text: $appID)
+ .textFieldStyle(.roundedBorder)
+ .font(.system(size: 12, design: .monospaced))
+ .autocorrectionDisabled(true)
+ SecureField(
+ center.hasSecret ? l10n["feishu_approval_secret_saved"] : l10n["feishu_approval_secret_placeholder"],
+ text: $secret
+ )
+ .textFieldStyle(.roundedBorder)
+ .font(.system(size: 12, design: .monospaced))
+ HStack {
+ Button(l10n["feishu_approval_save"]) {
+ center.save(appID: appID, secretInput: secret)
+ secret = ""
+ }
+ if center.hasSecret {
+ Button(l10n["feishu_approval_clear_secret"]) {
+ secret = ""
+ center.clearSecret()
+ }
+ }
+ }
+ Text(center.statusText)
+ .font(.system(size: 11))
+ .foregroundStyle(.secondary)
+ .textSelection(.enabled)
+ if center.isPaired {
+ Text(l10n["feishu_approval_paired"])
+ .font(.caption)
+ HStack {
+ Button(l10n["feishu_approval_rebind"]) { center.unbind(); center.armBind() }
+ Button(l10n["feishu_approval_unbind"]) { center.unbind() }
+ }
+ } else {
+ Button(l10n["feishu_approval_arm"]) { center.armBind() }
+ if let openID = center.pairCandidateOpenID {
+ Text(String(format: l10n["feishu_approval_candidate"], openID))
+ .font(.system(size: 11, design: .monospaced))
+ .textSelection(.enabled)
+ Button(l10n["feishu_approval_bind"]) { center.confirmBind() }
+ }
+ }
+ Text(l10n["feishu_approval_note"])
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
+ }
+ .onAppear { center.refreshIdentity() }
+ }
+}
diff --git a/Sources/CodeIsland/L10n.swift b/Sources/CodeIsland/L10n.swift
index f0c519a0f..a9cddd1e6 100644
--- a/Sources/CodeIsland/L10n.swift
+++ b/Sources/CodeIsland/L10n.swift
@@ -304,6 +304,22 @@ final class L10n: ObservableObject {
"push_problem_invalidURL": "That address isn't a valid http(s) URL.",
"push_problem_ntfyTopicMismatch": "Server ends in a different topic than the Topic field. ntfy reads the last part of the address as the topic — remove it from Server, or clear Topic.",
"push_storage_note": "Tokens and secrets are kept in CodeIsland's preferences on this Mac and only sent to the service they belong to. Plain http:// works only for addresses on your local network.",
+ "feishu_approval_title": "Feishu remote approval",
+ "feishu_approval_desc": "Uses your company's self-built Feishu app and its outbound long connection. Codex command approvals arrive as a private card with only Allow once and Deny. A text reply never approves. The App Secret stays in the Keychain. This is separate from the one-way Feishu webhook in Push Notifications. In the Feishu console, enable the bot, grant only im:message.p2p_msg:readonly, im:message:send_as_bot and im:message:update, subscribe to im.message.receive_v1 and the card.action.trigger callback, and choose long connection for both. Connect here before saving that subscription. Keep the app available only to you, and do not add the bot to a group.",
+ "feishu_approval_enable": "Enable Feishu remote approval",
+ "feishu_approval_app_id": "App ID",
+ "feishu_approval_secret_saved": "App Secret saved in Keychain — leave blank to keep it",
+ "feishu_approval_secret_placeholder": "App Secret",
+ "feishu_approval_save": "Save and connect",
+ "feishu_approval_clear_secret": "Remove App Secret",
+ "feishu_approval_paired": "A Feishu account is bound. Only its buttons can answer.",
+ "feishu_approval_rebind": "Bind a different account",
+ "feishu_approval_unbind": "Unbind",
+ "feishu_approval_arm": "Start binding",
+ "feishu_approval_candidate": "Feishu account: %@",
+ "feishu_approval_bind": "Bind this account",
+ "feishu_approval_note": "Allow once approves only that command. There is no Always allow. Timeout, disconnect, another account, or tapping the same card again does not allow it.",
+
// Appearance
"preview": "Preview",
@@ -1514,6 +1530,22 @@ final class L10n: ObservableObject {
"push_problem_invalidURL": "地址不是有效的 http(s) URL。",
"push_problem_ntfyTopicMismatch": "服务器地址末尾带着一个与「主题」不同的 topic。ntfy 会把地址最后一段当作 topic——请从服务器地址中删掉它,或清空「主题」。",
"push_storage_note": "令牌和密钥保存在本机 CodeIsland 的偏好设置中,只会发送给对应的服务。明文 http:// 仅支持局域网地址。",
+ "feishu_approval_title": "飞书远程审批",
+ "feishu_approval_desc": "用企业自建应用的出站长连接,把 Codex 的命令审批发到飞书私聊。卡片只有「允许一次」和「拒绝」,聊天文字不会批准。App Secret 只进钥匙串。这和下面推送通知里的飞书 webhook 不是一回事。开放平台里开通机器人,权限只给 im:message.p2p_msg:readonly、im:message:send_as_bot、im:message:update。事件订阅 im.message.receive_v1,回调订阅 card.action.trigger,两处都选长连接。先在这里连上,再去后台保存订阅。可用范围只给你自己,不要把机器人拉进群。",
+ "feishu_approval_enable": "启用飞书远程审批",
+ "feishu_approval_app_id": "App ID",
+ "feishu_approval_secret_saved": "钥匙串里已有 App Secret,留空表示不改",
+ "feishu_approval_secret_placeholder": "App Secret",
+ "feishu_approval_save": "保存并连接",
+ "feishu_approval_clear_secret": "删除 App Secret",
+ "feishu_approval_paired": "已绑定飞书账号。只有这个账号的按钮有效。",
+ "feishu_approval_rebind": "换一个账号",
+ "feishu_approval_unbind": "解除绑定",
+ "feishu_approval_arm": "开始绑定",
+ "feishu_approval_candidate": "飞书账号:%@",
+ "feishu_approval_bind": "绑定这个账号",
+ "feishu_approval_note": "允许一次只放行这一条命令,没有始终允许。超时、断线、别人的账号、同一张卡片再点一次,都不会允许。",
+
// Appearance
"preview": "预览",
diff --git a/Sources/CodeIsland/Settings.swift b/Sources/CodeIsland/Settings.swift
index 40519cf9a..8ffb20aa6 100644
--- a/Sources/CodeIsland/Settings.swift
+++ b/Sources/CodeIsland/Settings.swift
@@ -164,6 +164,12 @@ enum SettingsKey {
static let pushAwayIdleMinutes = "pushAwayIdleMinutes"
static let pushSummaryLength = "pushSummaryLength"
static let pushChannels = "pushChannels" // JSON [PushChannelConfig]; empty = nothing configured
+
+ // Feishu long-connection approvals. The App Secret is not a default: it
+ // lives in the Keychain (FeishuSecretStore).
+ static let feishuApprovalEnabled = "feishuApprovalEnabled"
+ static let feishuApprovalAppID = "feishuApprovalAppID"
+ static let feishuApprovalOpenID = "feishuApprovalOpenID"
}
struct SettingsDefaults {
@@ -263,6 +269,9 @@ struct SettingsDefaults {
static let pushAwayIdleMinutes = 5
static let pushSummaryLength = PushMessageFormatter.defaultSummaryLimit
static let pushChannels = ""
+
+ static let feishuApprovalEnabled = false
+ static let feishuApprovalAppID = ""
}
@MainActor
@@ -349,6 +358,8 @@ class SettingsManager {
SettingsKey.pushAwayIdleMinutes: SettingsDefaults.pushAwayIdleMinutes,
SettingsKey.pushSummaryLength: SettingsDefaults.pushSummaryLength,
SettingsKey.pushChannels: SettingsDefaults.pushChannels,
+ SettingsKey.feishuApprovalEnabled: SettingsDefaults.feishuApprovalEnabled,
+ SettingsKey.feishuApprovalAppID: SettingsDefaults.feishuApprovalAppID,
])
}
diff --git a/Sources/CodeIsland/SettingsView.swift b/Sources/CodeIsland/SettingsView.swift
index 92e6e5aae..36b1935ca 100644
--- a/Sources/CodeIsland/SettingsView.swift
+++ b/Sources/CodeIsland/SettingsView.swift
@@ -674,6 +674,8 @@ private struct BehaviorPage: View {
}
}
+ FeishuApprovalSettingsSection()
+
PushNotificationsSection()
Section(l10n["sessions"]) {
diff --git a/helpers/feishu-bridge/decision_test.go b/helpers/feishu-bridge/decision_test.go
new file mode 100644
index 000000000..3e46b0051
--- /dev/null
+++ b/helpers/feishu-bridge/decision_test.go
@@ -0,0 +1,25 @@
+package main
+
+import "testing"
+
+func TestParseDecision(t *testing.T) {
+ id, decision, ok := parseDecision(map[string]any{"request_id": "abc", "decision": "allow"})
+ if !ok || id != "abc" || decision != "allow" {
+ t.Fatalf("allow: %v %v %v", id, decision, ok)
+ }
+ _, _, ok = parseDecision(map[string]any{"request_id": "abc", "decision": "deny"})
+ if !ok {
+ t.Fatal("deny should be accepted")
+ }
+ for _, decision := range []string{"yes", "always", "allow once", "", "ALLOW"} {
+ if _, _, ok := parseDecision(map[string]any{"request_id": "abc", "decision": decision}); ok {
+ t.Fatalf("accepted %q", decision)
+ }
+ }
+ if _, _, ok := parseDecision(map[string]any{"text": "同意"}); ok {
+ t.Fatal("chat-like payload must not authorize")
+ }
+ if _, _, ok := parseDecision(nil); ok {
+ t.Fatal("nil value must not authorize")
+ }
+}
diff --git a/helpers/feishu-bridge/go.mod b/helpers/feishu-bridge/go.mod
new file mode 100644
index 000000000..b9c15e916
--- /dev/null
+++ b/helpers/feishu-bridge/go.mod
@@ -0,0 +1,10 @@
+module codeisland-feishu-bridge
+
+go 1.23
+
+require github.com/larksuite/oapi-sdk-go/v3 v3.12.2
+
+require (
+ github.com/gogo/protobuf v1.3.2 // indirect
+ github.com/gorilla/websocket v1.5.0 // indirect
+)
diff --git a/helpers/feishu-bridge/go.sum b/helpers/feishu-bridge/go.sum
new file mode 100644
index 000000000..26ef7d10f
--- /dev/null
+++ b/helpers/feishu-bridge/go.sum
@@ -0,0 +1,35 @@
+github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
+github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
+github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
+github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
+github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
+github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
+github.com/larksuite/oapi-sdk-go/v3 v3.12.2 h1:YjIVkSXW3TZOL3HCdJdTKYYP3ZBIM9ql9+TVyb1XL2w=
+github.com/larksuite/oapi-sdk-go/v3 v3.12.2/go.mod h1:F1nwLfYBSKvD8mS/OFw90Gr+V4RIugPBR44m/ThA5jg=
+github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
+github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
+golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
+golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
+golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
+golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
+golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
+golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
+golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
+golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
+golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
+golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
+golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
+golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
+golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
+golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
+golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
+golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
diff --git a/helpers/feishu-bridge/main.go b/helpers/feishu-bridge/main.go
new file mode 100644
index 000000000..3555122f0
--- /dev/null
+++ b/helpers/feishu-bridge/main.go
@@ -0,0 +1,535 @@
+package main
+
+import (
+ "bufio"
+ "context"
+ "encoding/json"
+ "fmt"
+ "log"
+ "os"
+ "strings"
+ "sync"
+ "time"
+
+ lark "github.com/larksuite/oapi-sdk-go/v3"
+ larkcore "github.com/larksuite/oapi-sdk-go/v3/core"
+ "github.com/larksuite/oapi-sdk-go/v3/event/dispatcher"
+ "github.com/larksuite/oapi-sdk-go/v3/event/dispatcher/callback"
+ larkim "github.com/larksuite/oapi-sdk-go/v3/service/im/v1"
+ larkws "github.com/larksuite/oapi-sdk-go/v3/ws"
+)
+
+// feishu-bridge is a child of CodeIsland. It keeps one outbound Feishu long
+// connection and speaks newline-delimited JSON on stdin/stdout. It never
+// decides a Codex approval itself: a card click is forwarded, and only an
+// explicit allow or deny value is forwarded. Chat text is not an approval.
+func main() {
+ log.SetOutput(os.Stderr)
+ log.SetFlags(log.LstdFlags)
+ bridge := newBridge()
+ scanner := bufio.NewScanner(os.Stdin)
+ scanner.Buffer(make([]byte, 0, 64*1024), 2*1024*1024)
+ for scanner.Scan() {
+ bridge.handleLine(scanner.Bytes())
+ }
+ bridge.stop()
+}
+
+type stderrLogger struct{}
+
+func (stderrLogger) Debug(context.Context, ...interface{}) {}
+func (stderrLogger) Info(context.Context, ...interface{}) {}
+func (stderrLogger) Warn(context.Context, ...interface{}) {}
+func (stderrLogger) Error(_ context.Context, args ...interface{}) {
+ log.Println(args...)
+}
+
+type cardTrack struct {
+ messageID string
+ inflightUntil time.Time
+ done bool
+ decision string
+}
+
+type bridge struct {
+ mu sync.Mutex
+ emitMu sync.Mutex
+ appID string
+ secret string
+ openID string
+ armBind bool
+ api *lark.Client
+ cancel context.CancelFunc
+ done chan struct{}
+ cards map[string]*cardTrack
+}
+
+func newBridge() *bridge {
+ return &bridge{cards: map[string]*cardTrack{}}
+}
+
+func (b *bridge) handleLine(raw []byte) {
+ var msg map[string]any
+ if err := json.Unmarshal(raw, &msg); err != nil {
+ b.emitLog("ignored a control line that was not JSON")
+ return
+ }
+ op, _ := msg["op"].(string)
+ switch op {
+ case "configure":
+ appID, _ := msg["app_id"].(string)
+ secret, _ := msg["app_secret"].(string)
+ openID, _ := msg["open_id"].(string)
+ b.configure(strings.TrimSpace(appID), strings.TrimSpace(secret), strings.TrimSpace(openID))
+ case "arm_bind":
+ b.mu.Lock()
+ b.armBind = true
+ b.mu.Unlock()
+ b.emitStatus("online", "等待飞书私聊。文字不会批准命令。")
+ case "bind":
+ openID, _ := msg["open_id"].(string)
+ openID = strings.TrimSpace(openID)
+ b.mu.Lock()
+ b.openID = openID
+ b.armBind = false
+ b.mu.Unlock()
+ if openID != "" {
+ b.emitStatus("online", "已绑定,审批卡片会发到这个账号。")
+ }
+ case "unbind":
+ b.mu.Lock()
+ b.openID = ""
+ b.armBind = false
+ b.mu.Unlock()
+ b.emitStatus("online", "已解除绑定。新的审批不会发到飞书。")
+ case "card":
+ b.sendCard(msg)
+ case "resolved":
+ id, _ := msg["request_id"].(string)
+ decision, _ := msg["decision"].(string)
+ b.markResolved(strings.TrimSpace(id), strings.TrimSpace(decision))
+ default:
+ b.emitLog("ignored unknown control op")
+ }
+}
+
+func (b *bridge) configure(appID, secret, openID string) {
+ if appID == "" || secret == "" {
+ b.emitStatus("error", "缺少 App ID 或 App Secret。")
+ return
+ }
+ b.mu.Lock()
+ same := b.cancel != nil && b.appID == appID && b.secret == secret
+ b.openID = openID
+ b.mu.Unlock()
+ if same {
+ if openID != "" {
+ b.emitStatus("online", "已绑定,审批卡片会发到这个账号。")
+ } else {
+ b.emitStatus("online", "长连接已在。还没有绑定飞书账号。")
+ }
+ return
+ }
+ b.restart(appID, secret)
+}
+
+func (b *bridge) restart(appID, secret string) {
+ b.mu.Lock()
+ cancel := b.cancel
+ done := b.done
+ b.mu.Unlock()
+ if cancel != nil {
+ cancel()
+ }
+ if done != nil {
+ select {
+ case <-done:
+ case <-time.After(8 * time.Second):
+ b.emitLog("previous long connection did not stop within 8s")
+ }
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ finished := make(chan struct{})
+ b.mu.Lock()
+ b.cancel = cancel
+ b.done = finished
+ b.appID = appID
+ b.secret = secret
+ b.api = lark.NewClient(appID, secret,
+ lark.WithLogLevel(larkcore.LogLevelError),
+ lark.WithLogger(stderrLogger{}),
+ )
+ b.mu.Unlock()
+ go func() {
+ defer close(finished)
+ b.serve(ctx, appID, secret)
+ }()
+}
+
+func (b *bridge) stop() {
+ b.mu.Lock()
+ cancel := b.cancel
+ b.mu.Unlock()
+ if cancel != nil {
+ cancel()
+ }
+}
+
+func (b *bridge) serve(ctx context.Context, appID, secret string) {
+ b.emitStatus("connecting", "正在连接飞书长连接。")
+ handler := dispatcher.NewEventDispatcher("", "").
+ OnP2MessageReceiveV1(b.onMessage).
+ OnP2CardActionTrigger(b.onCard)
+ cli := larkws.NewClient(appID, secret,
+ larkws.WithEventHandler(handler),
+ larkws.WithLogLevel(larkcore.LogLevelError),
+ larkws.WithLogger(stderrLogger{}),
+ larkws.WithAutoReconnect(true),
+ larkws.WithOnReady(func() {
+ b.mu.Lock()
+ paired := b.openID != ""
+ b.mu.Unlock()
+ if paired {
+ b.emitStatus("online", "长连接已就绪,审批会发到已绑定的飞书。")
+ } else {
+ b.emitStatus("online", "长连接已就绪。给机器人发一条私聊后再在 Mac 上绑定。")
+ }
+ }),
+ larkws.WithOnDisconnected(func() {
+ b.emitStatus("offline", "长连接断开了,正在重连。断开期间不会自动允许。")
+ }),
+ larkws.WithOnReconnecting(func() {
+ b.emitStatus("connecting", "正在重连飞书。")
+ }),
+ larkws.WithOnReconnected(func() {
+ b.emitStatus("online", "飞书长连接已恢复。")
+ }),
+ )
+ err := cli.Start(ctx)
+ if ctx.Err() != nil {
+ return
+ }
+ if err != nil {
+ b.emitStatus("error", "长连接结束:"+err.Error())
+ }
+}
+
+func (b *bridge) onMessage(_ context.Context, event *larkim.P2MessageReceiveV1) error {
+ if event == nil || event.Event == nil || event.Event.Message == nil || event.Event.Sender == nil {
+ return nil
+ }
+ message := event.Event.Message
+ sender := event.Event.Sender
+ if message.ChatType == nil || *message.ChatType != "p2p" {
+ return nil
+ }
+ if sender.SenderType != nil && *sender.SenderType == "app" {
+ return nil
+ }
+ openID := ""
+ if sender.SenderId != nil && sender.SenderId.OpenId != nil {
+ openID = strings.TrimSpace(*sender.SenderId.OpenId)
+ }
+ if openID == "" || message.MessageId == nil {
+ return nil
+ }
+ b.mu.Lock()
+ paired := b.openID
+ arm := b.armBind
+ b.mu.Unlock()
+ switch {
+ case paired != "" && openID == paired:
+ b.reply(*message.MessageId, "审批只能点卡片上的「允许一次」或「拒绝」。文字回复不会执行命令。")
+ case paired != "" && openID != paired:
+ b.reply(*message.MessageId, "这个机器人只给已绑定的飞书账号发审批。")
+ case arm:
+ b.emit(map[string]any{"op": "pair_candidate", "open_id": openID})
+ b.reply(*message.MessageId, "已收到。请回到 Mac 的 CodeIsland 设置里点「绑定这个账号」。文字不会批准命令。")
+ default:
+ b.reply(*message.MessageId, "请先在 Mac 的 CodeIsland 设置里点「开始绑定」,再给机器人发消息。")
+ }
+ return nil
+}
+
+func (b *bridge) onCard(_ context.Context, event *callback.CardActionTriggerEvent) (*callback.CardActionTriggerResponse, error) {
+ if event == nil || event.Event == nil || event.Event.Operator == nil || event.Event.Action == nil {
+ return toast("error", "这张卡片没有有效的操作。"), nil
+ }
+ openID := strings.TrimSpace(event.Event.Operator.OpenID)
+ requestID, decision, ok := parseDecision(event.Event.Action.Value)
+ if !ok {
+ return toast("error", "只有卡片上的允许一次或拒绝才有效。"), nil
+ }
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ if b.openID == "" || openID != b.openID {
+ return toast("error", "这个飞书账号不能审批这台 Mac。"), nil
+ }
+ track := b.cards[requestID]
+ if track == nil || track.done {
+ return toast("error", "这条审批已经结束。"), nil
+ }
+ if time.Now().Before(track.inflightUntil) {
+ return toast("info", "正在让 Mac 处理,请不要重复点。"), nil
+ }
+ track.inflightUntil = time.Now().Add(20 * time.Second)
+ b.emitLocked(map[string]any{
+ "op": "card_action",
+ "request_id": requestID,
+ "decision": decision,
+ "open_id": openID,
+ })
+ return &callback.CardActionTriggerResponse{
+ Toast: toastBody("info", "已送到 Mac,等待这台电脑执行。"),
+ Card: &callback.Card{
+ Type: "raw",
+ Data: cardDocument(cardText("处理中", "已点「"+decisionLabel(decision)+"」。正在等 Mac 确认。"), "orange", false, "", ""),
+ },
+ }, nil
+}
+
+func (b *bridge) sendCard(msg map[string]any) {
+ requestID, _ := msg["request_id"].(string)
+ requestID = strings.TrimSpace(requestID)
+ if requestID == "" {
+ return
+ }
+ b.mu.Lock()
+ openID := b.openID
+ api := b.api
+ if _, exists := b.cards[requestID]; exists {
+ b.mu.Unlock()
+ return
+ }
+ b.cards[requestID] = &cardTrack{}
+ b.mu.Unlock()
+ if openID == "" || api == nil {
+ b.emitLog("card not sent; Feishu account is not bound or the connection is down")
+ return
+ }
+ body := cardTextFrom(msg)
+ content, err := json.Marshal(cardDocument(body, "orange", true, requestID, ""))
+ if err != nil {
+ b.emitLog("could not build the card")
+ return
+ }
+ req := larkim.NewCreateMessageReqBuilder().
+ ReceiveIdType(larkim.CreateMessageV1ReceiveIDTypeOpenId).
+ Body(larkim.NewCreateMessageReqBodyBuilder().
+ ReceiveId(openID).
+ MsgType(larkim.MsgTypeInteractive).
+ Content(string(content)).
+ Uuid(requestID).
+ Build()).
+ Build()
+ resp, err := api.Im.Message.Create(context.Background(), req)
+ if err != nil || resp == nil || !resp.Success() || resp.Data == nil || resp.Data.MessageId == nil {
+ detail := "send failed"
+ if err != nil {
+ detail = err.Error()
+ } else if resp != nil {
+ detail = fmt.Sprintf("code %d", resp.Code)
+ }
+ b.emitLog("card send failed: " + detail)
+ return
+ }
+ b.mu.Lock()
+ if track := b.cards[requestID]; track != nil {
+ track.messageID = *resp.Data.MessageId
+ }
+ b.mu.Unlock()
+}
+
+func (b *bridge) markResolved(requestID, decision string) {
+ if requestID == "" {
+ return
+ }
+ if decision != "allow" && decision != "deny" && decision != "gone" {
+ decision = "gone"
+ }
+ b.mu.Lock()
+ track := b.cards[requestID]
+ if track == nil {
+ b.mu.Unlock()
+ return
+ }
+ track.done = true
+ track.decision = decision
+ track.inflightUntil = time.Time{}
+ messageID := track.messageID
+ api := b.api
+ b.mu.Unlock()
+ if messageID == "" || api == nil {
+ return
+ }
+ title, template := resolvedCopy(decision)
+ content, err := json.Marshal(cardDocument(title, template, false, "", ""))
+ if err != nil {
+ return
+ }
+ req := larkim.NewPatchMessageReqBuilder().
+ MessageId(messageID).
+ Body(larkim.NewPatchMessageReqBodyBuilder().Content(string(content)).Build()).
+ Build()
+ resp, err := api.Im.Message.Patch(context.Background(), req)
+ if err != nil || resp == nil || !resp.Success() {
+ b.emitLog("card update failed")
+ }
+}
+
+func (b *bridge) reply(messageID, text string) {
+ b.mu.Lock()
+ api := b.api
+ b.mu.Unlock()
+ if api == nil || messageID == "" {
+ return
+ }
+ content, _ := json.Marshal(map[string]string{"text": text})
+ req := larkim.NewReplyMessageReqBuilder().
+ MessageId(messageID).
+ Body(larkim.NewReplyMessageReqBodyBuilder().
+ MsgType(larkim.MsgTypeText).
+ Content(string(content)).
+ Build()).
+ Build()
+ _, _ = api.Im.Message.Reply(context.Background(), req)
+}
+
+func (b *bridge) emitStatus(state, detail string) {
+ b.emit(map[string]any{"op": "status", "state": state, "detail": detail})
+}
+
+func (b *bridge) emitLog(message string) {
+ b.emit(map[string]any{"op": "log", "message": message})
+}
+
+func (b *bridge) emit(payload map[string]any) {
+ b.mu.Lock()
+ b.emitLocked(payload)
+ b.mu.Unlock()
+}
+
+func (b *bridge) emitLocked(payload map[string]any) {
+ b.emitMu.Lock()
+ defer b.emitMu.Unlock()
+ encoded, err := json.Marshal(payload)
+ if err != nil {
+ return
+ }
+ _, _ = os.Stdout.Write(append(encoded, '\n'))
+}
+
+func parseDecision(value map[string]any) (string, string, bool) {
+ if value == nil {
+ return "", "", false
+ }
+ id, _ := value["request_id"].(string)
+ decision, _ := value["decision"].(string)
+ id = strings.TrimSpace(id)
+ decision = strings.TrimSpace(decision)
+ if id == "" || (decision != "allow" && decision != "deny") {
+ return "", "", false
+ }
+ return id, decision, true
+}
+
+func decisionLabel(decision string) string {
+ if decision == "allow" {
+ return "允许一次"
+ }
+ return "拒绝"
+}
+
+func resolvedCopy(decision string) (string, string) {
+ switch decision {
+ case "allow":
+ return "已允许这一次。没有记住为始终允许。", "green"
+ case "deny":
+ return "已拒绝。命令不会执行。", "red"
+ default:
+ return "这条审批已经结束,没有从飞书执行。", "grey"
+ }
+}
+
+func cardTextFrom(msg map[string]any) string {
+ source, _ := msg["source"].(string)
+ tool, _ := msg["tool"].(string)
+ cwd, _ := msg["cwd"].(string)
+ command, _ := msg["command"].(string)
+ session, _ := msg["session"].(string)
+ var lines []string
+ if source != "" {
+ lines = append(lines, "来源:"+source)
+ }
+ if tool != "" {
+ lines = append(lines, "工具:"+tool)
+ }
+ if cwd != "" {
+ lines = append(lines, "目录:"+cwd)
+ }
+ if session != "" {
+ lines = append(lines, "会话:"+session)
+ }
+ lines = append(lines, "", clip(command, 1800))
+ return strings.TrimSpace(strings.Join(lines, "\n"))
+}
+
+func cardText(title, body string) string {
+ return title + "\n" + body
+}
+
+func cardDocument(body, template string, withButtons bool, requestID, _ string) map[string]any {
+ elements := []any{
+ map[string]any{
+ "tag": "div",
+ "text": map[string]any{"tag": "plain_text", "content": clip(body, 1800)},
+ },
+ }
+ if withButtons {
+ elements = append(elements, map[string]any{
+ "tag": "action",
+ "actions": []any{
+ button("允许一次", "primary", requestID, "allow"),
+ button("拒绝", "danger", requestID, "deny"),
+ },
+ })
+ }
+ return map[string]any{
+ "config": map[string]any{"wide_screen_mode": true},
+ "header": map[string]any{
+ "template": template,
+ "title": map[string]any{"tag": "plain_text", "content": "CodeIsland 审批"},
+ },
+ "elements": elements,
+ }
+}
+
+func button(label, kind, requestID, decision string) map[string]any {
+ return map[string]any{
+ "tag": "button",
+ "type": kind,
+ "text": map[string]any{"tag": "plain_text", "content": label},
+ "value": map[string]string{
+ "request_id": requestID,
+ "decision": decision,
+ },
+ }
+}
+
+func toast(kind, content string) *callback.CardActionTriggerResponse {
+ return &callback.CardActionTriggerResponse{Toast: toastBody(kind, content)}
+}
+
+func toastBody(kind, content string) *callback.Toast {
+ return &callback.Toast{Type: kind, Content: content}
+}
+
+func clip(value string, limit int) string {
+ value = strings.TrimSpace(value)
+ runes := []rune(value)
+ if len(runes) <= limit {
+ return value
+ }
+ return string(runes[:limit-1]) + "…"
+}
+
diff --git a/scripts/build-dmg.sh b/scripts/build-dmg.sh
index 6652a7880..37dc571c5 100755
--- a/scripts/build-dmg.sh
+++ b/scripts/build-dmg.sh
@@ -37,6 +37,7 @@ esac
echo "==> Building CodeIsland ${VERSION} (${BUILD_ARCH})"
cd "$REPO_ROOT"
+"$REPO_ROOT/scripts/build-feishu-bridge.sh" "$BUILD_ARCH"
source "$REPO_ROOT/scripts/swiftpm-release.sh"
ARM_DIR=$(swiftpm_release_build arm64)
if [ "$BUILD_ARCH" = universal ]; then
@@ -66,6 +67,17 @@ case "$BUILD_ARCH" in
esac
chmod +x "$CONTENTS_DIR/MacOS/CodeIsland" "$CONTENTS_DIR/Helpers/codeisland-bridge"
+FEISHU_DIST="$REPO_ROOT/helpers/feishu-bridge/dist"
+case "$BUILD_ARCH" in
+ universal)
+ cp "$FEISHU_DIST/feishu-bridge" "$CONTENTS_DIR/Helpers/feishu-bridge"
+ ;;
+ arm64)
+ cp "$FEISHU_DIST/feishu-bridge-arm64" "$CONTENTS_DIR/Helpers/feishu-bridge"
+ ;;
+esac
+chmod +x "$CONTENTS_DIR/Helpers/feishu-bridge"
+
# Write Info.plist (use the root Info.plist as base, update version)
CURRENT_VER=$(defaults read "$REPO_ROOT/Info.plist" CFBundleShortVersionString)
sed -e "s/${CURRENT_VER}<\/string>/${VERSION}<\/string>/g" \
diff --git a/scripts/build-feishu-bridge.sh b/scripts/build-feishu-bridge.sh
new file mode 100755
index 000000000..a8d8ff510
--- /dev/null
+++ b/scripts/build-feishu-bridge.sh
@@ -0,0 +1,42 @@
+#!/usr/bin/env bash
+# Builds the Feishu long-connection helper that CodeIsland.app supervises.
+# Usage: ./scripts/build-feishu-bridge.sh [arm64|universal]
+set -euo pipefail
+
+ARCH="${1:-arm64}"
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+SRC="$ROOT/helpers/feishu-bridge"
+OUT="$SRC/dist"
+mkdir -p "$OUT"
+
+if ! command -v go >/dev/null 2>&1; then
+ echo "ERROR: go is required to build feishu-bridge" >&2
+ exit 1
+fi
+
+build_one() {
+ local goarch="$1"
+ local dest="$2"
+ echo "==> feishu-bridge $goarch"
+ (
+ cd "$SRC"
+ CGO_ENABLED=0 GOOS=darwin GOARCH="$goarch" \
+ go build -trimpath -ldflags "-s -w" -o "$dest" .
+ )
+}
+
+case "$ARCH" in
+ arm64)
+ build_one arm64 "$OUT/feishu-bridge-arm64"
+ ;;
+ universal)
+ build_one arm64 "$OUT/feishu-bridge-arm64"
+ build_one amd64 "$OUT/feishu-bridge-amd64"
+ lipo -create "$OUT/feishu-bridge-arm64" "$OUT/feishu-bridge-amd64" \
+ -output "$OUT/feishu-bridge"
+ ;;
+ *)
+ echo "ERROR: arch must be arm64 or universal (got '$ARCH')" >&2
+ exit 1
+ ;;
+esac