Compare commits

...

12 Commits

Author SHA1 Message Date
maksarsanjeev b8541465ec ops: Xray in the installer (mihomo fails REALITY against Xray servers), watchdog rebuilds a poisoned Telegram app 2026-11-09 00:53:46 +03:00
maksarsanjeev a4f5a89026 ops bot: task lists go out one card per task with Сделано / Перенести buttons 2026-11-09 00:47:21 +03:00
maksarsanjeev 1889439ed7 ops bot: task lists carry ✓/⏰ buttons again (tasks, today, free-text asks) 2026-11-09 00:44:13 +03:00
maksarsanjeev 977665806f Ops bot: remember the last exchanges so follow-ups have context
Each message started a fresh claude -p with only the database snapshot, so
«да, поправь» had nothing to refer to. Keep the last 6 exchanges (2 h, in
memory, shared by Telegram and BroV) and put them into the prompt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 21:54:19 +03:00
maksarsanjeev 0f4e110512 Chat: a reply stopped by BroV itself is not an error
claude catches SIGTERM and exits 143, so a reply cancelled by a new message,
a new dialog or a closed tab showed «claude: код выхода 143».

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 13:07:32 +03:00
maksarsanjeev 4f1e90ad8d Translator: take the whole copied text, keep the translation when the notch is stretched
Browsers report only part of a selection over Accessibility; when the clipboard
holds a longer text containing it, translate the clipboard. Dragging the handle
moved the home view to the chat and dropped the card; now the translation goes
into the chat (after it finishes, if still loading).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:38:47 +03:00
maksarsanjeev 46901f2b62 Net: 8 s health-check timeout, show a dead proxy only after two misses
AmneziaWG 3 tunnels idle for a while need 5+ s for the first handshake, so the
4-5 s checks marked working connections as dead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:31:03 +03:00
maksarsanjeev 3c7931d710 Net core: accept Amnezia keys that carry a plain AmneziaWG .conf
Newer Amnezia apps share vpn:// keys whose payload (same base64url + length + zlib
wrapping) is an AmneziaWG .conf ([Interface]/[Peer], AWG 3 fields) instead of the JSON
containers; the parser failed with «Expecting value: line 1 column 2». decode_key()
handles both; --check and the provider build use it. Tested with mihomo -t.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 11:19:25 +03:00
maksarsanjeev 7e5937ab3f Net core: a moment without an address is not a network change
When Wi-Fi briefly lost its address (DHCP renew), the empty snapshot became the baseline
and the same address coming back looked like a move, restarting the core for nothing.
Empty snapshots are ignored now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 02:24:12 +03:00
maksarsanjeev cd119d3b8f Net core: clean restart when the Mac changes networks, instead of a leaky rebind
Re-creating the WireGuard tunnels through a provider reload leaked every old tunnel: on
16.10 the core held 652 UDP sockets to the Amnezia servers and 677 MB, and the servers
stopped answering the handshake flood. netctl rebind is now a clean core restart (the
move drops the TCP connections anyway), and BroV calls it only when the IPv4 address of
a physical adapter actually changed, not on every path update.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 02:08:51 +03:00
maksarsanjeev f32397ea34 Net core: DNS goes into the core only on the active adapter
netctl pointed every network service at 198.18.0.2, «iPhone USB», Thunderbolt Bridge and
VPN services included; macOS then kept re-checking them and offered the iPhone's hotspot
over and over. Now only hardware services (en*) with an active link are changed, and a
service an older version changed is given its DNS back. rebind (on every network change)
also moves the DNS to a newly active adapter while capture is on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 16:22:19 +03:00
maksarsanjeev 101a3860a9 Net core: re-create WireGuard tunnels after a network change (rebind)
mihomo's WireGuard outbounds keep their UDP socket bound to the address they started on:
after moving from Planet9 to Saga the Amnezia sockets were still sending from
192.168.68.x, so every Amnezia (and client) tunnel looked dead while the AmneziaVPN app,
connecting afresh, worked. Client tunnels now live in a file provider (keys/clients.yaml,
groups select them by filter) like the Amnezia keys; netctl rebind touches both files and
reloads the providers, which re-creates the tunnels on the current address without
touching other connections. BroV calls it on every network change before re-testing.
Tested on a scratch core: groups, selection across a rebind, health check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 15:54:16 +03:00
14 changed files with 522 additions and 148 deletions
+1 -1
View File
@@ -29,7 +29,7 @@ DerivedData must stay outside ~/Documents (iCloud adds Finder attributes and cod
## Network core (globe 🌐 in the header) ## Network core (globe 🌐 in the header)
- mihomo runs as root: LaunchDaemon `local.maksar.brov.netd`, binary + config + keys + API secret in `/Library/Application Support/BroV/` (root, 0700). Nothing user-writable is read by root. - mihomo runs as root: LaunchDaemon `local.maksar.brov.netd`, binary + config + keys + API secret in `/Library/Application Support/BroV/` (root, 0700). Nothing user-writable is read by root.
- BroV never sees the config or the API secret: it talks to the narrow root helper `scripts/netcore/netctl.py` (LaunchDaemon `local.maksar.brov.netctl`, socket `/var/run/brov-netctl.sock`, only the installing user) — commands: state, select, delay, tun (on = clean core restart, refused while the AmneziaVPN app is open; also points the Mac DNS into the core), add_key, hide, unhide. - BroV never sees the config or the API secret: it talks to the narrow root helper `scripts/netcore/netctl.py` (LaunchDaemon `local.maksar.brov.netctl`, socket `/var/run/brov-netctl.sock`, only the installing user) — commands: state, select, delay, tun (on = clean core restart, refused while the AmneziaVPN app is open; also points the Mac DNS into the core), add_key, hide, unhide, refresh, rebind (the Mac changed networks: clean core restart — WireGuard tunnels stay bound to the old address, and re-creating them via a provider reload leaked sockets).
- `scripts/netcore/gen.py` builds the config (Amnezia keys → provider `keys/amnezia.yaml`, single vless:// links added in BroV → provider `vless-keys` from `keys/vless.txt`, WireGuard clients, VLESS subscription). Install/update: `sudo sh scripts/netcore/install.sh` (verifies the mihomo SHA256, migrates keys). Never commit keys, configs or the guide (`~/.brov-secrets`). - `scripts/netcore/gen.py` builds the config (Amnezia keys → provider `keys/amnezia.yaml`, single vless:// links added in BroV → provider `vless-keys` from `keys/vless.txt`, WireGuard clients, VLESS subscription). Install/update: `sudo sh scripts/netcore/install.sh` (verifies the mihomo SHA256, migrates keys). Never commit keys, configs or the guide (`~/.brov-secrets`).
- Reloading the whole core config drops every connection (including this chat); group switches and provider reloads don't. - Reloading the whole core config drops every connection (including this chat); group switches and provider reloads don't.
@@ -147,7 +147,11 @@ final class ClaudeCodeCLI {
} }
} }
p.waitUntilExit() p.waitUntilExit()
// cancel() (new message, new dialog, closed tab) drops our reference before the
// process dies; `claude` catches SIGTERM and exits 143 instead of dying on the signal.
let stoppedByUs = process !== p
if process === p { process = nil } if process === p { process = nil }
if stoppedByUs && parser.finalText == nil { throw CancellationError() }
if let error = parser.errorMessage { if let error = parser.errorMessage {
if error.localizedCaseInsensitiveContains("authenticate") || error.localizedCaseInsensitiveContains("login") { if error.localizedCaseInsensitiveContains("authenticate") || error.localizedCaseInsensitiveContains("login") {
@@ -161,6 +165,9 @@ final class ClaudeCodeCLI {
if p.terminationReason == .uncaughtSignal { throw CancellationError() } if p.terminationReason == .uncaughtSignal { throw CancellationError() }
if parser.finalText == nil, p.terminationStatus != 0 { if parser.finalText == nil, p.terminationStatus != 0 {
let stderr = String(data: err.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? "" let stderr = String(data: err.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? ""
if p.terminationStatus == 143 || p.terminationStatus == 130 {
throw ClaudeCodeCLIError.failed("Ответ прерван: процесс claude остановили снаружи. Отправь сообщение ещё раз.")
}
let last = stderr.split(separator: "\n").last.map(String.init) ?? "код выхода \(p.terminationStatus)" let last = stderr.split(separator: "\n").last.map(String.init) ?? "код выхода \(p.terminationStatus)"
throw ClaudeCodeCLIError.failed("claude: \(last)") throw ClaudeCodeCLIError.failed("claude: \(last)")
} }
@@ -449,6 +449,9 @@ struct ChatResizeHandle: View {
DragGesture(minimumDistance: 2, coordinateSpace: .global) DragGesture(minimumDistance: 2, coordinateSpace: .global)
.onChanged { g in .onChanged { g in
if startHeight == nil { if startHeight == nil {
// A translation card on the home view goes along into the chat
// instead of disappearing.
if state.translation != nil { TranslatorRun.moveToChat(state: state) }
if state.view != .prompt { if state.view != .prompt {
state.chatDetent = 0 state.chatDetent = 0
state.view = .prompt state.view = .prompt
+58 -11
View File
@@ -57,6 +57,16 @@ final class NetCore: ObservableObject {
/// Delays measured by the group test (covers the subscription nodes too). /// Delays measured by the group test (covers the subscription nodes too).
private var measured: [String: Int] = [:] private var measured: [String: Int] = [:]
/// Failed checks in a row per proxy. An AmneziaWG 3 tunnel idle for a while can miss one
/// check while its handshake warms up, so «нет ответа» is shown only after two misses.
private var misses: [String: Int] = [:]
private func record(_ name: String, _ delay: Int) {
if delay > 0 { misses[name] = 0; measured[name] = delay; return }
let n = (misses[name] ?? 0) + 1
misses[name] = n
if n >= 2 { measured[name] = 0 } // first miss: keep the previous result
}
static let clientInfo: [String: (title: String, subnet: String)] = [ static let clientInfo: [String: (title: String, subnet: String)] = [
"saga": ("Сага", "192.168.8.0/24"), "saga": ("Сага", "192.168.8.0/24"),
@@ -143,6 +153,8 @@ final class NetCore: ObservableObject {
awgNames.sort() awgNames.sort()
func lastDelay(_ name: String) -> Int? { func lastDelay(_ name: String) -> Int? {
if let d = measured[name] { return d } if let d = measured[name] { return d }
// One miss so far: the core's history already says 0, don't show it yet.
if misses[name] == 1 { return nil }
if let h = proxies[name]?["history"] as? [[String: Any]], let d = h.last?["delay"] as? Int { return d } if let h = proxies[name]?["history"] as? [[String: Any]], let d = h.last?["delay"] as? Int { return d }
return providerDelay[name] return providerDelay[name]
} }
@@ -186,17 +198,17 @@ final class NetCore: ObservableObject {
func measure() async { func measure() async {
busy = true busy = true
if let m = (await call(["cmd": "delay", "group": "ai-out"], timeout: 15))?["delays"] as? [String: Int] { if let m = (await call(["cmd": "delay", "group": "ai-out"], timeout: 15))?["delays"] as? [String: Int] {
measured = m for (k, v) in m { record(k, v) }
// Members that didn't answer are missing from the map: mark them dead. // Members that didn't answer are missing from the map: count a miss.
for e in exits where e.id != "auto" && m[e.id] == nil { measured[e.id] = 0 } for e in exits where e.id != "auto" && m[e.id] == nil { record(e.id, 0) }
} }
if let m = (await call(["cmd": "delay", "group": "amnezia"], timeout: 15))?["delays"] as? [String: Int] { if let m = (await call(["cmd": "delay", "group": "amnezia"], timeout: 15))?["delays"] as? [String: Int] {
for (k, v) in m { measured[k] = v } for (k, v) in m { record(k, v) }
for c in amneziaConns where c.id != "amnezia-auto" && m[c.id] == nil { measured[c.id] = 0 } for c in amneziaConns where c.id != "amnezia-auto" && m[c.id] == nil { record(c.id, 0) }
} }
for c in clients where c.on { for c in clients where c.on {
if let m = (await call(["cmd": "delay", "proxy": c.id], timeout: 15))?["delays"] as? [String: Int] { if let m = (await call(["cmd": "delay", "proxy": c.id], timeout: 15))?["delays"] as? [String: Int] {
for (k, v) in m { measured[k] = v } for (k, v) in m { record(k, v) }
} }
} }
await refresh() await refresh()
@@ -216,7 +228,7 @@ final class NetCore: ObservableObject {
_ = await call(["cmd": "select", "group": "\(id)-sw", "name": on ? id : off]) _ = await call(["cmd": "select", "group": "\(id)-sw", "name": on ? id : off])
SoundEngine.shared.play(on ? "pop" : "close") SoundEngine.shared.play(on ? "pop" : "close")
if on, let m = (await call(["cmd": "delay", "proxy": id], timeout: 15))?["delays"] as? [String: Int] { if on, let m = (await call(["cmd": "delay", "proxy": id], timeout: 15))?["delays"] as? [String: Int] {
for (k, v) in m { measured[k] = v } for (k, v) in m { record(k, v) }
} }
await refresh() await refresh()
} }
@@ -267,7 +279,7 @@ final class NetCore: ObservableObject {
busy = false busy = false
if r?["ok"] as? Bool == true { if r?["ok"] as? Bool == true {
lastError = nil lastError = nil
measured.removeValue(forKey: name) measured.removeValue(forKey: name); misses.removeValue(forKey: name)
SoundEngine.shared.play(cmd == "hide" ? "close" : "pop") SoundEngine.shared.play(cmd == "hide" ? "close" : "pop")
} else { } else {
lastError = "Не получилось: \(r?["error"] as? String ?? "помощник не ответил")." lastError = "Не получилось: \(r?["error"] as? String ?? "помощник не ответил")."
@@ -300,9 +312,10 @@ final class NetCore: ObservableObject {
// MARK: Network changes // MARK: Network changes
// //
// Moving between home / Saga / Planet9 Wi-Fi, waking from sleep or AmneziaVPN going on // Moving between home / Saga / Planet9 Wi-Fi, waking from sleep or AmneziaVPN going on
// and off leaves the WireGuard tunnels talking from an address that no longer exists. // and off leaves the WireGuard tunnels talking from an address that no longer exists
// Re-test everything a few seconds after the change so "auto" and "exit" re-pick at // (seen: Amnezia sockets still on 192.168.68.x after moving to Saga). A few seconds after
// once instead of at the next scheduled check. // the change the tunnels are re-created (netctl rebind), then everything is re-tested so
// "auto" and "exit" re-pick at once.
private var pathMonitor: NWPathMonitor? private var pathMonitor: NWPathMonitor?
private var recheckTask: Task<Void, Never>? private var recheckTask: Task<Void, Never>?
@@ -317,11 +330,45 @@ final class NetCore: ObservableObject {
pathMonitor = m pathMonitor = m
} }
/// IPv4 addresses of the physical adapters (en*), sorted: what "another network" means.
private var lastAddresses: String?
private static func physicalAddresses() -> String {
var out: [String] = []
var ifap: UnsafeMutablePointer<ifaddrs>?
guard getifaddrs(&ifap) == 0, let first = ifap else { return "" }
defer { freeifaddrs(ifap) }
var p: UnsafeMutablePointer<ifaddrs>? = first
while let cur = p {
let name = String(cString: cur.pointee.ifa_name)
if name.hasPrefix("en"), let sa = cur.pointee.ifa_addr, sa.pointee.sa_family == UInt8(AF_INET) {
var host = [CChar](repeating: 0, count: Int(NI_MAXHOST))
if getnameinfo(sa, socklen_t(sa.pointee.sa_len), &host, socklen_t(host.count), nil, 0, NI_NUMERICHOST) == 0 {
out.append(name + "=" + String(cString: host))
}
}
p = cur.pointee.ifa_next
}
return out.sorted().joined(separator: ",")
}
private func networkChanged() { private func networkChanged() {
recheckTask?.cancel() recheckTask?.cancel()
recheckTask = Task { recheckTask = Task {
try? await Task.sleep(for: .seconds(4)) try? await Task.sleep(for: .seconds(4))
guard !Task.isCancelled else { return } guard !Task.isCancelled else { return }
let now = Self.physicalAddresses()
// A moment without an address (DHCP renew, Wi-Fi blip) is not another network:
// only a change between two real addresses counts, else the core would restart
// when the same address comes back.
let moved = !now.isEmpty && lastAddresses != nil && now != lastAddresses
if !now.isEmpty { lastAddresses = now }
if moved {
// Another network: the WireGuard tunnels (Amnezia, clients) are still bound to
// the old address — a clean core restart re-binds them without leaking.
_ = await call(["cmd": "rebind"], timeout: 30)
try? await Task.sleep(for: .seconds(6))
}
_ = await call(["cmd": "delay", "group": "auto"], timeout: 15) _ = await call(["cmd": "delay", "group": "auto"], timeout: 15)
_ = await call(["cmd": "delay", "group": "amnezia"], timeout: 15) _ = await call(["cmd": "delay", "group": "amnezia"], timeout: 15)
_ = await call(["cmd": "delay", "group": "exit"], timeout: 15) _ = await call(["cmd": "delay", "group": "exit"], timeout: 15)
+26 -8
View File
@@ -17,6 +17,8 @@ struct TranslationResult: Equatable {
var engine: String = "" var engine: String = ""
var error: String? = nil var error: String? = nil
var loading = true var loading = true
/// The user stretched the notch while it was still translating: finish into the chat.
var toChat = false
} }
@MainActor @MainActor
@@ -42,6 +44,7 @@ enum TranslatorRun {
state.translation?.engine = engine state.translation?.engine = engine
state.translation?.loading = false state.translation?.loading = false
SoundEngine.shared.play("pop") SoundEngine.shared.play("pop")
if state.translation?.toChat == true { moveToChat(state: state) }
} catch { } catch {
guard state.translation?.source == source else { return } guard state.translation?.source == source else { return }
state.translation?.error = error.localizedDescription state.translation?.error = error.localizedDescription
@@ -50,6 +53,20 @@ enum TranslatorRun {
} }
} }
/// Moves a finished translation into a chat: the full text, room to grow (the handle
/// stretches the chat), and follow-up questions go to the same dialog.
static func moveToChat(state: AppState) {
guard let result = state.translation else { return }
if result.loading, result.error == nil { state.translation?.toChat = true; return }
state.translation = nil
guard result.error == nil else { return }
if state.tabs.count < AppState.maxTabs { state.openTab(.chat) } else { state.view = .prompt }
if let tab = state.activeTabId {
ChatTabs.shared.seed(tab, "Исходный текст:\n\(result.source)\n\nПеревод:\n\(result.text)\n\nВопросы ниже — про этот перевод.")
}
state.chatHistory.append(ChatMessage(role: .assistant, content: "**Перевод:**\n\n\(result.text)"))
}
private static func show(_ state: AppState) { private static func show(_ state: AppState) {
if state.mode != .expanded || !(state.view == .overview || state.view == .empty) { if state.mode != .expanded || !(state.view == .overview || state.view == .empty) {
NotificationCenter.default.post(name: .hookExpand, object: IslandView.overview) NotificationCenter.default.post(name: .hookExpand, object: IslandView.overview)
@@ -118,7 +135,13 @@ enum SelectionGrabber {
_ = AXIsProcessTrustedWithOptions(opts) _ = AXIsProcessTrustedWithOptions(opts)
return clipboardText() return clipboardText()
} }
if let s = axSelection(), !s.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { return s } if let s = axSelection(), !s.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
// Browsers and Electron apps often report only the visible part of a selection.
// If the user copied it, the clipboard holds the whole thing.
if let clip = clipboardText(), clip.count > s.count,
clip.contains(s.trimmingCharacters(in: .whitespacesAndNewlines)) { return clip }
return s
}
// ⌘C only when BroV isn't the key window (hotkey path); from a click in the notch // ⌘C only when BroV isn't the key window (hotkey path); from a click in the notch
// the keystroke would land in BroV itself. // the keystroke would land in BroV itself.
if NSApp.keyWindow == nil, let s = await copyViaCommandC(), !s.isEmpty { return s } if NSApp.keyWindow == nil, let s = await copyViaCommandC(), !s.isEmpty { return s }
@@ -206,7 +229,7 @@ struct TranslationCard: View {
Text(result.source).lineLimit(1).font(.system(size: 11.5)).foregroundColor(Color(hex: "#6B7079")) Text(result.source).lineLimit(1).font(.system(size: 11.5)).foregroundColor(Color(hex: "#6B7079"))
} }
} else { } else {
ScrollView(.vertical, showsIndicators: false) { ScrollView(.vertical, showsIndicators: true) {
Text(result.text) Text(result.text)
.font(.system(size: 12.5)) .font(.system(size: 12.5))
.textSelection(.enabled) .textSelection(.enabled)
@@ -219,12 +242,7 @@ struct TranslationCard: View {
SoundEngine.shared.play("blip") SoundEngine.shared.play("blip")
} }
FuncButton(symbol: "bubble.left", title: "В чат") { FuncButton(symbol: "bubble.left", title: "В чат") {
if state.tabs.count < AppState.maxTabs { state.openTab(.chat) } else { state.view = .prompt } TranslatorRun.moveToChat(state: state)
if let tab = state.activeTabId {
ChatTabs.shared.seed(tab, "Исходный текст:\n\(result.source)\n\nПеревод:\n\(result.text)\n\nВопросы ниже — про этот перевод.")
}
state.chatHistory.append(ChatMessage(role: .assistant, content: "**Перевод:**\n\n\(result.text)"))
state.translation = nil
} }
Text(result.source).lineLimit(1).font(.system(size: 10.5)).foregroundColor(Color(hex: "#5F646D")) Text(result.source).lineLimit(1).font(.system(size: 10.5)).foregroundColor(Color(hex: "#5F646D"))
} }
+91 -13
View File
@@ -31,8 +31,8 @@ CFG = {
"api_port": int(os.environ.get("API_PORT", "8787")), "api_port": int(os.environ.get("API_PORT", "8787")),
"db": os.environ.get("DB_PATH", "/var/lib/brov-ops/ops.db"), "db": os.environ.get("DB_PATH", "/var/lib/brov-ops/ops.db"),
"tz": os.environ.get("TZ_NAME", "Europe/Moscow"), "tz": os.environ.get("TZ_NAME", "Europe/Moscow"),
"claude": os.environ.get("CLAUDE_BIN", "claude"), "kimi": os.environ.get("KIMI_BIN", "kimi"),
"model": os.environ.get("CLAUDE_MODEL", "haiku"), "model": os.environ.get("KIMI_MODEL", ""),
"whisper": os.environ.get("WHISPER_MODEL", "small"), "whisper": os.environ.get("WHISPER_MODEL", "small"),
"digest_hour": int(os.environ.get("DIGEST_HOUR", "9")), "digest_hour": int(os.environ.get("DIGEST_HOUR", "9")),
"quiet_from": int(os.environ.get("QUIET_FROM", "22")), "quiet_from": int(os.environ.get("QUIET_FROM", "22")),
@@ -82,8 +82,42 @@ def owner_only(handler):
async def send_long(update: Update, text: str, **kw): async def send_long(update: Update, text: str, **kw):
for i in range(0, len(text), 3800): """Splits long text; extra kwargs (buttons) go only on the last chunk."""
await update.effective_message.reply_text(text[i:i + 3800], parse_mode=ParseMode.HTML, **kw) chunks = [text[i:i + 3800] for i in range(0, len(text), 3800)] or [""]
for i, chunk in enumerate(chunks):
last = i == len(chunks) - 1
await update.effective_message.reply_text(chunk, parse_mode=ParseMode.HTML, **(kw if last else {}))
def one_task_buttons(task_id: int) -> InlineKeyboardMarkup:
"""Buttons under a single task card — same callbacks as reminders."""
return InlineKeyboardMarkup([[
InlineKeyboardButton("✓ Сделано", callback_data=f"done:task:{task_id}"),
InlineKeyboardButton("⏰ Перенести", callback_data=f"snooze:task:{task_id}")]])
def flat_tasks(tree: list) -> list:
"""[(task, depth)] in display order."""
out = []
def walk(nodes, depth):
for n in nodes:
out.append((n, depth))
walk(n["children"], depth + 1)
walk(tree, 0)
return out
async def send_task_cards(update: Update, tree: list, limit: int = 12):
"""Every open task as its own message: task text, then Сделано / Перенести."""
tasks = flat_tasks(tree)
today = ops.today()
for t, depth in tasks[:limit]:
await update.effective_message.reply_text(fmt.task_line(t, depth, today),
parse_mode=ParseMode.HTML,
reply_markup=one_task_buttons(t["id"]))
if len(tasks) > limit:
await update.effective_message.reply_text(f"…и ещё {len(tasks) - limit}. Повтори /tasks.")
@owner_only @owner_only
@@ -97,13 +131,22 @@ async def cmd_start(update: Update, ctx):
@owner_only @owner_only
async def cmd_today(update: Update, ctx): async def cmd_today(update: Update, ctx):
await send_long(update, fmt.agenda(locked(ops.agenda))) with lock:
agenda, tree = ops.agenda(), ops.task_tree()
await send_long(update, fmt.agenda(agenda))
await send_task_cards(update, tree)
@owner_only @owner_only
async def cmd_tasks(update: Update, ctx): async def cmd_tasks(update: Update, ctx):
lines = fmt.tree(locked(ops.task_tree)) with lock:
await send_long(update, "\n".join(lines) if lines else "Открытых задач нет 👌") tree = ops.task_tree()
if not tree:
await update.effective_message.reply_text("Открытых задач нет 👌")
return
await update.effective_message.reply_text(
f"Открытые задачи ({len(flat_tasks(tree))}) — по одной, жми Сделано или Перенести:")
await send_task_cards(update, tree)
@owner_only @owner_only
@@ -132,17 +175,24 @@ def repeat_buttons(sub: dict) -> InlineKeyboardMarkup:
InlineKeyboardButton("Нет, закрыть", callback_data=f"rep:sub:{sub['id']}:0")]]) InlineKeyboardButton("Нет, закрыть", callback_data=f"rep:sub:{sub['id']}:0")]])
# Free-text asks that should end with the task list's buttons (nothing was changed, just shown).
LIST_HINTS = ("задач", "дела", "делы", "делах", "план", "список", "что там", "что горит",
"today", "tasks", "агенда")
async def think(update: Update, text: str): async def think(update: Update, text: str):
msg = await update.effective_message.reply_text("🤔 думаю…") msg = await update.effective_message.reply_text("🤔 думаю…")
paid: list = [] paid: list = []
try: try:
answer = await asyncio.to_thread(brain.handle_text, ops, text, lock, CFG["claude"], CFG["model"], paid) answer = await asyncio.to_thread(brain.handle_text, ops, text, lock, CFG["kimi"], CFG["model"], paid)
except OpsError as e: except OpsError as e:
answer = f"Не получилось: {e}" answer = f"Не получилось: {e}"
except Exception as e: # Claude timeout, CLI missing… except Exception as e: # Kimi timeout, CLI missing…
log.exception("brain") log.exception("brain")
answer = f"Ошибка: {e.__class__.__name__}" answer = f"Ошибка: {e.__class__.__name__}"
await msg.edit_text(answer[:4000]) await msg.edit_text(answer[:4000])
if "✓" not in answer and any(h in text.lower() for h in LIST_HINTS):
await send_task_cards(update, locked(ops.task_tree))
for sid in paid: # paid by text: ask «repeat?» with buttons for sid in paid: # paid by text: ask «repeat?» with buttons
s = locked(ops.sub, sid) s = locked(ops.sub, sid)
if s["paid"] and s["active"]: if s["paid"] and s["active"]:
@@ -213,6 +263,13 @@ async def on_button(update: Update, ctx):
note = "⏰ Напомню завтра" note = "⏰ Напомню завтра"
except OpsError as e: except OpsError as e:
note = f"Не получилось: {e}" note = f"Не получилось: {e}"
if action in ("done", "snooze") and kind == "task" and q.message.reply_markup:
# Task-list message (several task rows): drop the row just handled, keep the rest tappable.
# A single-row reminder keyboard is removed entirely, as before.
kb = q.message.reply_markup.inline_keyboard
if len(kb) > 1:
rows = [row for row in kb if not any(b.callback_data == f"{action}:task:{ref}" for b in row)]
markup = InlineKeyboardMarkup(rows) if rows else None
await q.answer() await q.answer()
await q.edit_message_text(q.message.text + "\n\n" + note, reply_markup=markup) await q.edit_message_text(q.message.text + "\n\n" + note, reply_markup=markup)
@@ -289,14 +346,14 @@ async def api_say(request):
if not text: if not text:
raise web.HTTPBadRequest(text="empty") raise web.HTTPBadRequest(text="empty")
try: try:
answer = await asyncio.to_thread(brain.handle_text, ops, text, lock, CFG["claude"], CFG["model"]) answer = await asyncio.to_thread(brain.handle_text, ops, text, lock, CFG["kimi"], CFG["model"])
except OpsError as e: except OpsError as e:
return ok({"ok": False, "answer": str(e)}) return ok({"ok": False, "answer": str(e)})
return ok({"ok": True, "answer": answer}) return ok({"ok": True, "answer": answer})
async def api_action(request): async def api_action(request):
"""One direct action from a BroV button (done, paid, timer…), no Claude involved.""" """One direct action from a BroV button (done, paid, timer…), no Kimi involved."""
check_auth(request) check_auth(request)
body = await request.json() body = await request.json()
if body.get("op") == "snooze": if body.get("op") == "snooze":
@@ -308,7 +365,7 @@ async def api_action(request):
async def api_delete(request): async def api_delete(request):
"""Delete by an explicit click in BroV (Claude never deletes).""" """Delete by an explicit click in BroV (Kimi never deletes)."""
check_auth(request) check_auth(request)
body = await request.json() body = await request.json()
kind, ref = str(body.get("kind")), int(body.get("id")) kind, ref = str(body.get("kind")), int(body.get("id"))
@@ -380,12 +437,15 @@ async def main():
log.warning("TELEGRAM_TOKEN not set: API only") log.warning("TELEGRAM_TOKEN not set: API only")
await asyncio.Event().wait() await asyncio.Event().wait()
proxy = CFG["proxy"] or None proxy = CFG["proxy"] or None
def build_tg() -> Application:
builder = (Application.builder().token(CFG["token"]) builder = (Application.builder().token(CFG["token"])
.request(HTTPXRequest(proxy=proxy, connect_timeout=10, read_timeout=20, write_timeout=20, .request(HTTPXRequest(proxy=proxy, connect_timeout=10, read_timeout=20, write_timeout=20,
pool_timeout=10, connection_pool_size=8)) pool_timeout=10, connection_pool_size=8))
.get_updates_request(PollRequest(proxy=proxy, connect_timeout=10, read_timeout=40, .get_updates_request(PollRequest(proxy=proxy, connect_timeout=10, read_timeout=40,
write_timeout=10, pool_timeout=10))) write_timeout=10, pool_timeout=10)))
tg = builder.build() tg = builder.build()
async def on_error(update, ctx): async def on_error(update, ctx):
log.error("handler failed", exc_info=ctx.error) log.error("handler failed", exc_info=ctx.error)
tg.add_error_handler(on_error) tg.add_error_handler(on_error)
@@ -398,12 +458,30 @@ async def main():
tg.add_handler(CallbackQueryHandler(on_button)) tg.add_handler(CallbackQueryHandler(on_button))
tg.add_handler(MessageHandler(filters.VOICE | filters.AUDIO, on_voice)) tg.add_handler(MessageHandler(filters.VOICE | filters.AUDIO, on_voice))
tg.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, on_text)) tg.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, on_text))
async with tg: return tg
# A Telegram/proxy outage must not kill the API, calendar and reminders. Every retry
# builds a FRESH Application: 06.11.2026 a proxy hiccup poisoned the shared httpx pool
# (PoolTimeout on every get_me) and reusing the same tg object looped forever — the API
# answered, the bot stayed dead for 2.5 days. If a fresh app still can't start 10 times
# (~5 minutes), exit and let systemd bring up a clean process.
fails = 0
while True:
try:
async with build_tg() as tg:
await tg.start() await tg.start()
await tg.updater.start_polling(drop_pending_updates=False, timeout=25) await tg.updater.start_polling(drop_pending_updates=False, timeout=25)
fails = 0
asyncio.create_task(reminder_loop(tg.bot)) asyncio.create_task(reminder_loop(tg.bot))
asyncio.create_task(poll_watchdog()) asyncio.create_task(poll_watchdog())
await asyncio.Event().wait() await asyncio.Event().wait()
except Exception:
fails += 1
log.exception("Telegram unavailable (attempt %d); API remains active, retrying in 30 s", fails)
if fails >= 10:
log.error("Telegram still broken after %d fresh attempts — restarting", fails)
os._exit(1)
await asyncio.sleep(30)
if __name__ == "__main__": if __name__ == "__main__":
+36 -2
View File
@@ -5,6 +5,8 @@ import json
import os import os
import subprocess import subprocess
import tempfile import tempfile
import time
from collections import deque
from .core import Ops, OpsError, client_name, ru_day from .core import Ops, OpsError, client_name, ru_day
@@ -45,6 +47,8 @@ INSTRUCTIONS = """Ты — помощник-менеджер системног
- После pay_sub добавляй repeat_sub, только если пользователь сам сказал, продлевать или нет - После pay_sub добавляй repeat_sub, только если пользователь сам сказал, продлевать или нет
(«оплатил и продлеваем», «больше не нужна»); иначе в reply спроси, повторять ли. («оплатил и продлеваем», «больше не нужна»); иначе в reply спроси, повторять ли.
- reply — 1–3 строки, без markdown-заголовков. - reply — 1–3 строки, без markdown-заголовков.
- Ниже может быть «Недавний разговор»: короткие ответы вроде «да», «поправь», «не надо»,
«перенеси на пятницу» относятся к нему. Не повторяй действия, которые там уже сделаны.
""" """
ALLOWED = {"add_task", "update_task", "complete_task", "reopen_task", "start_timer", "stop_timer", ALLOWED = {"add_task", "update_task", "complete_task", "reopen_task", "start_timer", "stop_timer",
@@ -172,14 +176,44 @@ def _only(d: dict, *keys) -> dict:
return {k: d[k] for k in keys if k in d} return {k: d[k] for k in keys if k in d}
# Recent exchanges, shared by Telegram and BroV (one owner): each `claude -p` call starts
# from scratch, so without this «да, поправь» has nothing to refer to. Memory only — a
# restart forgets the conversation, not the data.
HISTORY_TURNS = 6
HISTORY_TTL = 2 * 3600
_history: deque = deque(maxlen=HISTORY_TURNS)
def history_text(now: float | None = None) -> str:
now = time.time() if now is None else now
recent = [h for h in _history if now - h[0] <= HISTORY_TTL]
if not recent:
return ""
lines = ["Недавний разговор (старое сверху):"]
for _, said, answered in recent:
lines.append("Пользователь: " + said[:500])
lines.append("Ты: " + answered[:700])
return "\n".join(lines)
def remember(said: str, answered: str, now: float | None = None):
_history.append((time.time() if now is None else now, said.strip(), answered.strip()))
def handle_text(ops: Ops, text: str, lock, claude_bin: str = "claude", model: str = "haiku", def handle_text(ops: Ops, text: str, lock, claude_bin: str = "claude", model: str = "haiku",
paid: list | None = None) -> str: paid: list | None = None) -> str:
"""One message in, one answer out (actions taken + Claude's reply). The database lock """One message in, one answer out (actions taken + Claude's reply). The database lock
is held only while reading the state and applying the actions, not while Claude thinks.""" is held only while reading the state and applying the actions, not while Claude thinks."""
with lock: with lock:
prompt = snapshot(ops) + "\n\nСообщение пользователя:\n" + text.strip() prompt = snapshot(ops)
past = history_text()
if past:
prompt += "\n\n" + past
prompt += "\n\nСообщение пользователя:\n" + text.strip()
plan = parse_plan(ask_claude(prompt, claude_bin, model)) plan = parse_plan(ask_claude(prompt, claude_bin, model))
with lock: with lock:
lines = apply_plan(ops, plan, paid) lines = apply_plan(ops, plan, paid)
reply = str(plan.get("reply", "")).strip() reply = str(plan.get("reply", "")).strip()
return "\n".join(([reply] if reply else []) + lines) or "Готово." answer = "\n".join(([reply] if reply else []) + lines) or "Готово."
remember(text, answer)
return answer
+10
View File
@@ -55,6 +55,16 @@ def tree(nodes: list, depth: int = 0) -> list[str]:
return out return out
def task_line(t: dict, depth: int, today: date) -> str:
"""One task as a standalone card text (sent as its own message with buttons)."""
mark = "⏱" if t["running"] else ("▶️" if t["status"] == "doing" else "📌")
due = f"\nСрок: {human_day(t['due'], today)}" if t["due"] else ""
mins = f"\nУчтено: {t['minutes']} мин" if t["minutes"] else ""
client = f" [{client_name(t['client'])}]" if t["client"] else ""
indent = "└ " * depth
return f"{indent}{mark} <b>{escape(t['title'])}</b>{client}{due}{mins}"
def subs(rows: list, by_client: dict, today: date) -> str: def subs(rows: list, by_client: dict, today: date) -> str:
"""Grouped by company, each with its monthly total.""" """Grouped by company, each with its monthly total."""
if not rows: if not rows:
+2 -2
View File
@@ -1,12 +1,12 @@
[Unit] [Unit]
Description=BroV Ops proxy core (mihomo, proxy mode only: Telegram + Claude for brov-ops) Description=BroV Ops proxy core (Xray, HTTP proxy on 127.0.0.1:7890: Telegram + Kimi for brov-ops)
After=network-online.target After=network-online.target
Wants=network-online.target Wants=network-online.target
[Service] [Service]
User=brovops User=brovops
Group=brovops Group=brovops
ExecStart=/usr/local/bin/mihomo -d /etc/brov-ops/proxy -f /etc/brov-ops/proxy/config.yaml ExecStart=/opt/brov-ops/xray run -config /etc/brov-ops/proxy/xray.json
Restart=always Restart=always
RestartSec=5 RestartSec=5
NoNewPrivileges=yes NoNewPrivileges=yes
+85
View File
@@ -0,0 +1,85 @@
#!/usr/bin/env python3
"""Build /etc/brov-ops/proxy/xray.json from a nodes file of vless:// links.
Usage: gen-xray.py <nodes.txt> <out xray.json>
The nodes file holds one vless:// link per line (comments and blanks skipped).
Subscription contents are accepted too: base64 blob that decodes to vless:// lines.
Only REALITY+tcp VLESS nodes are used (that is what brov-ops' proxy runs on).
The first node becomes the outbound; extra nodes go into a round-robin balancer.
"""
import base64
import json
import sys
from urllib.parse import parse_qs, urlparse
def links(path: str) -> list[str]:
raw = open(path, encoding="utf-8").read().strip()
if "vless://" not in raw: # maybe a base64 subscription blob
try:
raw = base64.b64decode(raw).decode("utf-8")
except Exception:
pass
return [ln.strip() for ln in raw.splitlines() if ln.strip().startswith("vless://")]
def outbound(link: str, tag: str) -> dict:
u = urlparse(link)
q = {k: v[0] for k, v in parse_qs(u.query).items()}
if q.get("security") != "reality" or q.get("type", "tcp") != "tcp":
raise ValueError(f"пропускаю не-REALITY узел: {link[:40]}…")
return {
"tag": tag,
"protocol": "vless",
"settings": {"vnext": [{
"address": u.hostname,
"port": u.port or 443,
"users": [{"id": u.username, "encryption": q.get("encryption", "none"),
**({"flow": q["flow"]} if q.get("flow") else {})}],
}]},
"streamSettings": {
"network": "tcp",
"security": "reality",
"realitySettings": {
"serverName": q.get("sni", ""),
"fingerprint": q.get("fp", "chrome"),
"publicKey": q["pbk"],
"shortId": q.get("sid", ""),
},
},
}
def main() -> None:
nodes_path, out_path = sys.argv[1], sys.argv[2]
found = links(nodes_path)
if not found:
raise SystemExit("✗ в файле узлов нет ни одной vless:// ссылки")
outbounds, tags = [], []
for i, link in enumerate(found):
try:
ob = outbound(link, f"node{i}")
except (ValueError, KeyError) as e:
print(f"⚠ {e}", file=sys.stderr)
continue
outbounds.append(ob)
tags.append(ob["tag"])
if not outbounds:
raise SystemExit("✗ ни одного рабочего REALITY-узла")
cfg = {
"log": {"loglevel": "warning"},
"inbounds": [{"listen": "127.0.0.1", "port": 7890, "protocol": "http",
"settings": {"timeout": 0}}],
"outbounds": outbounds,
}
if len(tags) > 1:
cfg["routing"] = {"balancers": [{"tag": "out", "selector": tags}]}
with open(out_path, "w", encoding="utf-8") as f:
json.dump(cfg, f, indent=1, ensure_ascii=False)
f.write("\n")
print(f"✓ xray.json: {len(tags)} узл(а)")
if __name__ == "__main__":
main()
+51 -61
View File
@@ -3,8 +3,8 @@
# sudo sh ops/deploy/install.sh # sudo sh ops/deploy/install.sh
# #
# Puts the service in /opt/brov-ops (user brovops), data in /var/lib/brov-ops, settings in # Puts the service in /opt/brov-ops (user brovops), data in /var/lib/brov-ops, settings in
# /etc/brov-ops (root, 600). Telegram and Claude go through a local proxy core (mihomo in # /etc/brov-ops (root, 600). Telegram and Kimi go through a local proxy core (Xray in
# proxy mode on 127.0.0.1:7890 — only this service uses it, the VM itself is not tunnelled). # HTTP-proxy mode on 127.0.0.1:7890 — only this service uses it, the VM is not tunnelled).
# #
# Secrets on the first run: the VLESS subscription URL and the Telegram bot token are taken # Secrets on the first run: the VLESS subscription URL and the Telegram bot token are taken
# from ~/.brovops-sub and ~/.brovops-token of the user running sudo (moved into # from ~/.brovops-sub and ~/.brovops-token of the user running sudo (moved into
@@ -16,14 +16,14 @@ set -e
HERE=$(cd "$(dirname "$0")/.." && pwd) HERE=$(cd "$(dirname "$0")/.." && pwd)
ETC=/etc/brov-ops ETC=/etc/brov-ops
PROXY_DIR=$ETC/proxy PROXY_DIR=$ETC/proxy
MIHOMO_VERSION=v1.19.32 XRAY_VERSION=26.10.31
MIHOMO_GZ_SHA=8451100836c9eda194331c2babfad490b2faf30cebc1a04b0e76fd8ac2d35d10 XRAY_ZIP_SHA=e4bd9119f50ae7c41658b1abd0679ae06f98bd864a2907ff33f2f2cf7081b214
MIHOMO_BIN_SHA=3122d100e8177501776109f1a6253a694611627cf4d7c7ec82705855cf8626a8 XRAY_BIN_SHA=cc4b84d3069569f297a61f04b914f2bb37e9d202fd7b84cb50def1fc30fd40e1
PROXY=http://127.0.0.1:7890 PROXY=http://127.0.0.1:7890
echo "→ Пакеты" echo "→ Пакеты"
apt-get update -qq apt-get update -qq
apt-get install -y -qq python3-venv python3-pip ffmpeg curl ca-certificates openssl >/dev/null apt-get install -y -qq python3-venv python3-pip ffmpeg curl ca-certificates openssl unzip >/dev/null
id brovops >/dev/null 2>&1 || useradd --system --create-home --home-dir /home/brovops --shell /usr/sbin/nologin brovops id brovops >/dev/null 2>&1 || useradd --system --create-home --home-dir /home/brovops --shell /usr/sbin/nologin brovops
install -d -m 755 /opt/brov-ops install -d -m 755 /opt/brov-ops
@@ -31,13 +31,15 @@ install -d -m 750 -o brovops -g brovops /var/lib/brov-ops
install -d -m 750 -o root -g brovops $ETC install -d -m 750 -o root -g brovops $ETC
install -d -m 700 -o brovops -g brovops $PROXY_DIR install -d -m 700 -o brovops -g brovops $PROXY_DIR
echo "→ Прокси-ядро (mihomo $MIHOMO_VERSION)" echo "→ Прокси-ядро (Xray $XRAY_VERSION)"
if [ "$(sha256sum /usr/local/bin/mihomo 2>/dev/null | cut -d' ' -f1)" != "$MIHOMO_BIN_SHA" ]; then # Xray, не mihomo: 05.11.2026 mihomo не смог в REALITY handshake против Xray-сервера
# (REALITY authentication failed), а Xray-клиент ходит стабильно. Версия и суммы pinned.
if [ "$(sha256sum /opt/brov-ops/xray 2>/dev/null | cut -d' ' -f1)" != "$XRAY_BIN_SHA" ]; then
TMP=$(mktemp -d) TMP=$(mktemp -d)
curl -fsSL -o "$TMP/m.gz" "https://github.com/MetaCubeX/mihomo/releases/download/$MIHOMO_VERSION/mihomo-linux-amd64-$MIHOMO_VERSION.gz" curl -fsSL -o "$TMP/x.zip" "https://github.com/XTLS/Xray-core/releases/download/v$XRAY_VERSION/Xray-linux-64.zip"
[ "$(sha256sum "$TMP/m.gz" | cut -d' ' -f1)" = "$MIHOMO_GZ_SHA" ] || { echo "✗ архив mihomo не совпал с контрольной суммой"; exit 1; } [ "$(sha256sum "$TMP/x.zip" | cut -d' ' -f1)" = "$XRAY_ZIP_SHA" ] || { echo "✗ архив Xray не совпал с контрольной суммой"; exit 1; }
gunzip -c "$TMP/m.gz" > "$TMP/mihomo" unzip -q -o "$TMP/x.zip" -d "$TMP"
install -m 755 "$TMP/mihomo" /usr/local/bin/mihomo install -m 755 "$TMP/xray" /opt/brov-ops/xray
rm -rf "$TMP" rm -rf "$TMP"
fi fi
USER_HOME=$(getent passwd "${SUDO_USER:-root}" | cut -d: -f6) USER_HOME=$(getent passwd "${SUDO_USER:-root}" | cut -d: -f6)
@@ -54,51 +56,30 @@ ask_secret() { # prompt → stdout, input not echoed
# Server list: the subscription content as a file (~/.brovops-nodes — when the subscription # Server list: the subscription content as a file (~/.brovops-nodes — when the subscription
# page itself is blocked from here) and/or the subscription URL (~/.brovops-sub). # page itself is blocked from here) and/or the subscription URL (~/.brovops-sub).
NODES=$(take_file nodes); [ -n "$NODES" ] && printf '%s\n' "$NODES" > $PROXY_DIR/nodes.txt NODES=$(take_file nodes); [ -n "$NODES" ] && printf '%s\n' "$NODES" > $PROXY_DIR/nodes.txt
SUBURL=$(take_file sub); [ -n "$SUBURL" ] && printf '%s\n' "$SUBURL" > $PROXY_DIR/vless.sub SUBURL=$(take_file sub)
if [ -n "$SUBURL" ]; then
case "$SUBURL" in
vless://*) printf '%s\n' "$SUBURL" > $PROXY_DIR/nodes.txt ;; # a single key, not a subscription
*) printf '%s\n' "$SUBURL" > $PROXY_DIR/vless.sub ;;
esac
fi
if [ ! -s $PROXY_DIR/nodes.txt ] && [ ! -s $PROXY_DIR/vless.sub ]; then if [ ! -s $PROXY_DIR/nodes.txt ] && [ ! -s $PROXY_DIR/vless.sub ]; then
ask_secret "Ссылка подписки VLESS (ввод скрыт): " > $PROXY_DIR/vless.sub ask_secret "Ссылка подписки VLESS (ввод скрыт): " > $PROXY_DIR/vless.sub
[ -s $PROXY_DIR/vless.sub ] || { echo "✗ нет ни подписки, ни списка серверов"; exit 1; } [ -s $PROXY_DIR/vless.sub ] || { echo "✗ нет ни подписки, ни списка серверов"; exit 1; }
fi fi
PROVIDERS=""; USE="" # Xray не умеет подписки сам: скачиваем список узлов один раз при установке и генерируем
if [ -s $PROXY_DIR/nodes.txt ]; then # статичный xray.json из vless:// ссылок (REALITY). Обновление узлов — правка nodes.txt
PROVIDERS="$PROVIDERS # и повторный запуск gen-xray.py + systemctl restart brov-ops-proxy.
nodes: if [ ! -s $PROXY_DIR/nodes.txt ] && [ -s $PROXY_DIR/vless.sub ]; then
type: file curl -fsSL -m 30 -o $PROXY_DIR/nodes.txt "$(head -n1 $PROXY_DIR/vless.sub | tr -d '\r\n ')" \
path: ./nodes.txt || { echo "✗ подписка не скачалась — положи узлы файлом ~/.brovops-nodes"; exit 1; }
health-check: {enable: true, url: \"https://www.gstatic.com/generate_204\", interval: 300}"
USE="nodes"
fi fi
if [ -s $PROXY_DIR/vless.sub ]; then python3 "$HERE/deploy/gen-xray.py" $PROXY_DIR/nodes.txt $PROXY_DIR/xray.json
SUB=$(head -n1 $PROXY_DIR/vless.sub | tr -d '\r\n ')
PROVIDERS="$PROVIDERS
vless:
type: http
url: \"$SUB\"
path: ./vless.yaml
interval: 43200
proxy: DIRECT
health-check: {enable: true, url: \"https://www.gstatic.com/generate_204\", interval: 300}"
USE="${USE:+$USE, }vless"
fi
umask 077
cat > $PROXY_DIR/config.yaml <<EOF
# Generated by install.sh — proxy for brov-ops only (no TUN, nothing system-wide).
mixed-port: 7890
bind-address: 127.0.0.1
allow-lan: false
mode: rule
log-level: warning
ipv6: false
proxy-providers:$PROVIDERS
proxy-groups:
- {name: out, type: url-test, use: [$USE], url: "https://www.gstatic.com/generate_204", interval: 120, tolerance: 100}
rules:
- MATCH,out
EOF
umask 022
chown -R brovops:brovops $PROXY_DIR chown -R brovops:brovops $PROXY_DIR
chmod 600 $PROXY_DIR/* chmod 600 $PROXY_DIR/*
install -m 644 "$HERE/deploy/brov-ops-proxy.service" /etc/systemd/system/ install -m 644 "$HERE/deploy/brov-ops-proxy.service" /etc/systemd/system/
# Drop-in from the manual 05.11 hotfix and any mihomo leftovers must not override the unit.
rm -rf /etc/systemd/system/brov-ops-proxy.service.d
systemctl daemon-reload systemctl daemon-reload
systemctl enable --now brov-ops-proxy >/dev/null systemctl enable --now brov-ops-proxy >/dev/null
systemctl restart brov-ops-proxy systemctl restart brov-ops-proxy
@@ -108,24 +89,33 @@ curl -s -m 8 -o /dev/null -w " Telegram через прокси: HTTP %{http_co
echo "→ Код и Python-окружение" echo "→ Код и Python-окружение"
cp -r "$HERE/brovops" "$HERE/requirements.txt" /opt/brov-ops/ cp -r "$HERE/brovops" "$HERE/requirements.txt" /opt/brov-ops/
[ -x /opt/brov-ops/venv/bin/python ] || python3 -m venv /opt/brov-ops/venv [ -x /opt/brov-ops/venv/bin/python ] || python3 -m venv /opt/brov-ops/venv
HTTPS_PROXY=$PROXY /opt/brov-ops/venv/bin/pip install -q --upgrade pip /opt/brov-ops/venv/bin/pip install -q --upgrade pip
HTTPS_PROXY=$PROXY /opt/brov-ops/venv/bin/pip install -q -r /opt/brov-ops/requirements.txt /opt/brov-ops/venv/bin/pip install -q -r /opt/brov-ops/requirements.txt
echo "→ Claude Code" echo "→ Kimi Code"
CLAUDE=/home/brovops/.local/bin/claude KIMI=/home/brovops/.kimi-code/bin/kimi
if [ ! -x $CLAUDE ]; then if [ ! -x $KIMI ]; then
sudo -u brovops -H env HTTPS_PROXY=$PROXY HTTP_PROXY=$PROXY sh -c 'curl -fsSL https://claude.ai/install.sh | bash' >/dev/null # Kimi and PyPI are reachable directly; only Telegram requires the local proxy.
sudo -u brovops -H sh -c 'curl -fsSL https://code.kimi.com/kimi-code/install.sh | bash' >/dev/null
fi fi
[ -x $CLAUDE ] && echo " ✓ $($CLAUDE --version 2>/dev/null)" || echo " ⚠ Claude Code не установился" [ -x $KIMI ] && echo " ✓ $($KIMI --version 2>/dev/null)" || echo " ⚠ Kimi Code не установился"
echo "→ Настройки" echo "→ Настройки"
if [ ! -f $ETC/config.env ]; then if [ ! -f $ETC/config.env ]; then
# Whisper "small" needs ~1 GB on top of Claude: on a small VM take "base". # Whisper "small" needs ~1 GB on top of Kimi: on a small VM take "base".
MEM_MB=$(awk '/MemTotal/ {print int($2/1024)}' /proc/meminfo) MEM_MB=$(awk '/MemTotal/ {print int($2/1024)}' /proc/meminfo)
WHISPER=small; [ "$MEM_MB" -lt 3500 ] && WHISPER=base WHISPER=small; [ "$MEM_MB" -lt 3500 ] && WHISPER=base
sed -e "s|^API_TOKEN=.*|API_TOKEN=$(openssl rand -hex 24)|" -e "s|^CLAUDE_BIN=.*|CLAUDE_BIN=$CLAUDE|" \ sed -e "s|^API_TOKEN=.*|API_TOKEN=$(openssl rand -hex 24)|" -e "s|^KIMI_BIN=.*|KIMI_BIN=$KIMI|" \
-e "s|^WHISPER_MODEL=.*|WHISPER_MODEL=$WHISPER|" "$HERE/deploy/config.env.example" > $ETC/config.env -e "s|^WHISPER_MODEL=.*|WHISPER_MODEL=$WHISPER|" "$HERE/deploy/config.env.example" > $ETC/config.env
else
# Migrate an existing installation without touching tokens, owner or other settings.
# Old global proxy variables were for Claude; Telegram has its own TELEGRAM_PROXY.
sed -i -e "s|^CLAUDE_BIN=.*|KIMI_BIN=$KIMI|" -e "s|^CLAUDE_MODEL=.*|KIMI_MODEL=|" \
-e '/^HTTPS_PROXY=/d' -e '/^HTTP_PROXY=/d' $ETC/config.env
fi fi
grep -q "^KIMI_BIN=" $ETC/config.env || echo "KIMI_BIN=$KIMI" >> $ETC/config.env
grep -q "^KIMI_MODEL=" $ETC/config.env || echo "KIMI_MODEL=" >> $ETC/config.env
grep -q "^KIMI_PROXY=" $ETC/config.env || echo "KIMI_PROXY=" >> $ETC/config.env
if ! grep -q "^TELEGRAM_TOKEN=." $ETC/config.env; then if ! grep -q "^TELEGRAM_TOKEN=." $ETC/config.env; then
TOK=$(take_file token) TOK=$(take_file token)
[ -n "$TOK" ] || TOK=$(ask_secret "Токен бота от @BotFather (ввод скрыт): ") [ -n "$TOK" ] || TOK=$(ask_secret "Токен бота от @BotFather (ввод скрыт): ")
@@ -148,9 +138,9 @@ systemctl is-active --quiet brov-ops && echo "✓ brov-ops работает" ||
cat <<EOF cat <<EOF
Дальше (один раз): Дальше (один раз):
1. Войти в Claude под своей подпиской: 1. Войти в Kimi под своей подпиской:
sudo -u brovops -H env HTTPS_PROXY=$PROXY HTTP_PROXY=$PROXY $CLAUDE sudo -u brovops -H $KIMI login
(в нём /login, потом /exit), затем: sudo systemctl restart brov-ops Завершить device-code авторизацию, затем: sudo systemctl restart brov-ops
2. Написать боту /start — первый, кто напишет, станет владельцем. 2. Написать боту /start — первый, кто напишет, станет владельцем.
Токен для BroV (API_TOKEN): sudo grep API_TOKEN $ETC/config.env Токен для BroV (API_TOKEN): sudo grep API_TOKEN $ETC/config.env
EOF EOF
+21
View File
@@ -174,5 +174,26 @@ class Company(unittest.TestCase):
os.remove(path) os.remove(path)
class HistoryTest(unittest.TestCase):
def test_follow_up_sees_previous_exchange(self):
brain._history.clear()
o = Ops(connect(":memory:"))
seen = []
def fake(prompt, *a, **k):
seen.append(prompt)
return '{"actions":[],"reply":"Ок"}'
brain.ask_claude = fake
brain.handle_text(o, "задача посмотреть бегущий по лезвию 2033", threading.Lock())
brain.handle_text(o, "да, поправь", threading.Lock())
self.assertNotIn("Недавний разговор", seen[0])
self.assertIn("бегущий по лезвию 2033", seen[1])
self.assertLess(seen[1].index("Недавний разговор"), seen[1].index("да, поправь"))
def test_old_history_expires(self):
brain._history.clear()
brain.remember("старое", "ответ", now=0)
self.assertEqual(brain.history_text(now=brain.HISTORY_TTL + 1), "")
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()
+53 -19
View File
@@ -68,12 +68,43 @@ def mid(v, default):
return (int(m.group(1)) + int(m.group(2))) // 2 if m else int(v) return (int(m.group(1)) + int(m.group(2))) // 2 if m else int(v)
def amnezia(path, name): def decode_key(path):
"""vpn:// → (payload, description). Two formats are shared by Amnezia:
the JSON one (containers → awg → last_config) and, from newer apps, a plain AmneziaWG
.conf ([Interface] / [Peer]) under the same base64url + 4-byte length + zlib wrapping."""
key = open(path).read().strip()[len("vpn://"):] key = open(path).read().strip()[len("vpn://"):]
key += "=" * (-len(key) % 4) key += "=" * (-len(key) % 4)
j = json.loads(zlib.decompress(base64.urlsafe_b64decode(key)[4:])) text = zlib.decompress(base64.urlsafe_b64decode(key)[4:]).decode("utf-8")
awg = j["containers"][0]["awg"] if text.lstrip().startswith("["):
return conf_to_last_config(text), ""
j = json.loads(text)
cont = j["containers"][0]
if "awg" not in cont:
raise ValueError("это не AmneziaWG (контейнер %s) — пока поддерживается только AmneziaWG"
% cont.get("container"))
awg = cont["awg"]
c = awg["last_config"] if isinstance(awg["last_config"], dict) else json.loads(awg["last_config"]) c = awg["last_config"] if isinstance(awg["last_config"], dict) else json.loads(awg["last_config"])
return c, j.get("description") or ""
def conf_to_last_config(text):
"""An AmneziaWG .conf → the same field names the JSON key uses."""
p = configparser.ConfigParser()
p.optionxform = str
p.read_string(text)
i, peer = p["Interface"], p["Peer"]
host, port = peer["Endpoint"].rsplit(":", 1)
c = {k: v for k, v in i.items() if k not in ("Address", "PrivateKey", "DNS", "MTU")}
c.update({"hostName": host.strip("[]"), "port": port,
"client_ip": i["Address"].split(",")[0].split("/")[0].strip(),
"client_priv_key": i["PrivateKey"], "server_pub_key": peer["PublicKey"],
"psk_key": peer.get("PresharedKey", ""), "mtu": i.get("MTU", "1376"),
"persistent_keep_alive": peer.get("PersistentKeepalive", "25")})
return c
def amnezia(path, name):
c, _ = decode_key(path)
ver = 3 if c.get("HeaderProtectionKey") else 2 ver = 3 if c.get("HeaderProtectionKey") else 2
opt = {"version": ver, "jc": int(c["Jc"]), "jmin": int(c["Jmin"]), "jmax": int(c["Jmax"]), opt = {"version": ver, "jc": int(c["Jc"]), "jmin": int(c["Jmin"]), "jmax": int(c["Jmax"]),
"s1": int(c["S1"]), "s2": int(c["S2"])} "s1": int(c["S1"]), "s2": int(c["S2"])}
@@ -176,7 +207,12 @@ def main():
with open(os.open(prov, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "w") as f: with open(os.open(prov, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "w") as f:
f.write(y({"proxies": awg}) + "\n") f.write(y({"proxies": awg}) + "\n")
clients = {n: c for n, c in CLIENTS.items() if os.path.exists(os.path.join(SRC, c[0]))} clients = {n: c for n, c in CLIENTS.items() if os.path.exists(os.path.join(SRC, c[0]))}
proxies = [wg(n, f) for n, (f, _, _) in clients.items()] # Client tunnels live in a provider file too: after a network change BroV re-creates
# them (netctl rebind) so their WireGuard sockets bind to the new address.
client_proxies = [wg(n, f) for n, (f, _, _) in clients.items()]
with open(os.open(os.path.join(KEYS, "clients.yaml"), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "w") as f:
f.write(y({"proxies": client_proxies}) + "\n")
proxies = []
sub = open(os.path.join(SRC, "vless.sub")).read().strip() sub = open(os.path.join(SRC, "vless.sub")).read().strip()
rules = ([] if "home" in clients else [f"IP-CIDR,{HOME_NET},DIRECT,no-resolve"]) + [ rules = ([] if "home" in clients else [f"IP-CIDR,{HOME_NET},DIRECT,no-resolve"]) + [
@@ -193,21 +229,23 @@ def main():
# Fetch through the exit: the subscription host is unreachable directly from home # Fetch through the exit: the subscription host is unreachable directly from home
# (the pull failed with EOF and the node list went stale). # (the pull failed with EOF and the node list went stale).
"type": "http", "url": sub, "interval": 3600, "path": "./providers/vless.yaml", "proxy": "exit", "type": "http", "url": sub, "interval": 3600, "path": "./providers/vless.yaml", "proxy": "exit",
"health-check": {"enable": True, "url": TEST_URL, "interval": 300}} "health-check": {"enable": True, "url": TEST_URL, "interval": 300, "timeout": 8000}}
if hid["vless"]: if hid["vless"]:
# Hidden nodes stay in the subscription, the core just skips them. # Hidden nodes stay in the subscription, the core just skips them.
vless["exclude-filter"] = "^(?:" + "|".join(rx(n) for n in hid["vless"]) + ")$" vless["exclude-filter"] = "^(?:" + "|".join(rx(n) for n in hid["vless"]) + ")$"
# Single VLESS links added in BroV: a provider of their own (only when there are any — # Single VLESS links added in BroV: a provider of their own (only when there are any —
# mihomo refuses an empty provider file). # mihomo refuses an empty provider file).
extra_prov = {} extra_prov = {}
clients_prov = {"clients": {"type": "file", "path": "./keys/clients.yaml",
"health-check": {"enable": False, "url": TEST_URL}}} if clients else {}
vless_file = os.path.join(KEYS, "vless.txt") vless_file = os.path.join(KEYS, "vless.txt")
if os.path.exists(vless_file) and any(l.strip().startswith("vless://") for l in open(vless_file)): if os.path.exists(vless_file) and any(l.strip().startswith("vless://") for l in open(vless_file)):
extra_prov["vless-keys"] = {"type": "file", "path": "./keys/vless.txt", extra_prov["vless-keys"] = {"type": "file", "path": "./keys/vless.txt",
"health-check": {"enable": True, "url": TEST_URL, "interval": 300}} "health-check": {"enable": True, "url": TEST_URL, "interval": 300, "timeout": 8000}}
if hid["vless"]: if hid["vless"]:
extra_prov["vless-keys"]["exclude-filter"] = vless["exclude-filter"] extra_prov["vless-keys"]["exclude-filter"] = vless["exclude-filter"]
awg_prov = {"type": "file", "path": "./keys/amnezia.yaml", awg_prov = {"type": "file", "path": "./keys/amnezia.yaml",
"health-check": {"enable": True, "url": TEST_URL, "interval": 300}} "health-check": {"enable": True, "url": TEST_URL, "interval": 300, "timeout": 8000}}
cfg = { cfg = {
"mixed-port": 7890, "allow-lan": False, "mode": "rule", "log-level": "error", "ipv6": False, "mixed-port": 7890, "allow-lan": False, "mode": "rule", "log-level": "error", "ipv6": False,
@@ -223,30 +261,31 @@ def main():
"nameserver": ["https://1.1.1.1/dns-query#exit", "https://8.8.8.8/dns-query#exit"], "nameserver": ["https://1.1.1.1/dns-query#exit", "https://8.8.8.8/dns-query#exit"],
"direct-nameserver": ["77.88.8.8", "77.88.8.1"]}, "direct-nameserver": ["77.88.8.8", "77.88.8.1"]},
"proxies": proxies, "proxies": proxies,
"proxy-providers": {"amnezia-keys": awg_prov, "vless-cluster": vless, **extra_prov}, "proxy-providers": {"amnezia-keys": awg_prov, "vless-cluster": vless, **extra_prov, **clients_prov},
"proxy-groups": [ "proxy-groups": [
# What traffic actually uses: the exit picked in BroV while it answers, "auto" # What traffic actually uses: the exit picked in BroV while it answers, "auto"
# when it doesn't (a pinned connection that dies no longer takes the Mac offline). # when it doesn't (a pinned connection that dies no longer takes the Mac offline).
# Back to the pick as soon as it answers again. Checked every 30 s and right after # Back to the pick as soon as it answers again. Checked every 30 s and right after
# 3 failed connections. # 3 failed connections.
{"name": "exit", "type": "fallback", "proxies": ["ai-out", "auto"], {"name": "exit", "type": "fallback", "proxies": ["ai-out", "auto"],
"url": TEST_URL, "interval": 30, "timeout": 4000, "max-failed-times": 3, "lazy": False}, "url": TEST_URL, "interval": 30, "timeout": 8000, "max-failed-times": 3, "lazy": False},
# What BroV's globe panel switches: "auto", the Amnezia group, or one VLESS node. # What BroV's globe panel switches: "auto", the Amnezia group, or one VLESS node.
{"name": "ai-out", "type": "select", "proxies": ["auto", "amnezia"], "use": ["vless-cluster", *extra_prov]}, {"name": "ai-out", "type": "select", "proxies": ["auto", "amnezia"], "use": ["vless-cluster", *extra_prov]},
# Fastest alive exit among every Amnezia connection and every VLESS node; # Fastest alive exit among every Amnezia connection and every VLESS node;
# switches only when another one is 100+ ms faster. # switches only when another one is 100+ ms faster.
{"name": "auto", "type": "url-test", "use": ["amnezia-keys", "vless-cluster", *extra_prov], {"name": "auto", "type": "url-test", "use": ["amnezia-keys", "vless-cluster", *extra_prov],
"url": TEST_URL, "interval": 60, "timeout": 4000, "max-failed-times": 3, "url": TEST_URL, "interval": 60, "timeout": 8000, "max-failed-times": 3,
"tolerance": 100, "lazy": False}, "tolerance": 100, "lazy": False},
# Amnezia: "amnezia-auto" (fastest connection) or one fixed connection. # Amnezia: "amnezia-auto" (fastest connection) or one fixed connection.
{"name": "amnezia", "type": "select", "proxies": ["amnezia-auto"], "use": ["amnezia-keys"]}, {"name": "amnezia", "type": "select", "proxies": ["amnezia-auto"], "use": ["amnezia-keys"]},
{"name": "amnezia-auto", "type": "url-test", "use": ["amnezia-keys"], {"name": "amnezia-auto", "type": "url-test", "use": ["amnezia-keys"],
"url": TEST_URL, "interval": 60, "timeout": 4000, "max-failed-times": 3, "url": TEST_URL, "interval": 60, "timeout": 8000, "max-failed-times": 3,
"tolerance": 100, "lazy": False}, "tolerance": 100, "lazy": False},
] + [ ] + [
# Client networks: off (REJECT) until switched on in BroV. # Client networks: off (REJECT) until switched on in BroV.
# Client networks: first option = "off" (REJECT, or DIRECT for home). # Client networks: first option = "off" (REJECT, or DIRECT for home).
{"name": f"{n}-sw", "type": "select", "proxies": [off, n]} for n, (_, _, off) in clients.items() {"name": f"{n}-sw", "type": "select", "proxies": [off], "use": ["clients"], "filter": f"^{n}$"}
for n, (_, _, off) in clients.items()
], ],
"rules": rules, "rules": rules,
} }
@@ -263,14 +302,9 @@ def check(path):
raw = open(path).read().strip() raw = open(path).read().strip()
if not raw.startswith("vpn://"): if not raw.startswith("vpn://"):
raise ValueError("ключ должен начинаться с vpn://") raise ValueError("ключ должен начинаться с vpn://")
key = raw[len("vpn://"):] _, description = decode_key(path)
key += "=" * (-len(key) % 4)
j = json.loads(zlib.decompress(base64.urlsafe_b64decode(key)[4:]))
cont = j["containers"][0]
if "awg" not in cont:
raise ValueError("это не AmneziaWG (контейнер %s) — пока поддерживается только AmneziaWG" % cont.get("container"))
p = amnezia(path, "check") p = amnezia(path, "check")
print(json.dumps({"ok": True, "name": j.get("description") or p["server"], "server": p["server"], print(json.dumps({"ok": True, "name": description or p["server"], "server": p["server"],
"port": p["port"], "version": p["amnezia-wg-option"]["version"]}, ensure_ascii=False)) "port": p["port"], "version": p["amnezia-wg-option"]["version"]}, ensure_ascii=False))
except Exception as e: except Exception as e:
print(json.dumps({"ok": False, "error": str(e) or e.__class__.__name__}, ensure_ascii=False)) print(json.dumps({"ok": False, "error": str(e) or e.__class__.__name__}, ensure_ascii=False))
+52 -5
View File
@@ -12,6 +12,8 @@ allows exactly these operations:
tun {on} traffic capture on (fresh core start) / off; remembered tun {on} traffic capture on (fresh core start) / off; remembered
add_key {text} vpn:// Amnezia key (checked by gen.py) or a vless:// link: stored, core updated add_key {text} vpn:// Amnezia key (checked by gen.py) or a vless:// link: stored, core updated
refresh {} re-download the VLESS subscription now (new cluster nodes), no reload refresh {} re-download the VLESS subscription now (new cluster nodes), no reload
rebind {} the Mac moved to another network: clean core restart (WireGuard
tunnels bind to the new address, nothing leaks)
hide {name} take an Amnezia connection or a VLESS node out of the list and hide {name} take an Amnezia connection or a VLESS node out of the list and
out of "auto" (the key / subscription stay, nothing is deleted) out of "auto" (the key / subscription stay, nothing is deleted)
unhide {name} put it back unhide {name} put it back
@@ -84,7 +86,7 @@ def cmd_state(_):
for name, p in proxies.items(): for name, p in proxies.items():
keep[name] = {"now": p.get("now"), "all": p.get("all"), "history": (p.get("history") or [])[-1:]} keep[name] = {"now": p.get("now"), "all": p.get("all"), "history": (p.get("history") or [])[-1:]}
providers = {} providers = {}
for prov in ("vless-cluster", "vless-keys", "amnezia-keys"): for prov in ("vless-cluster", "vless-keys", "amnezia-keys", "clients"):
try: try:
lst = api("GET", "/providers/proxies/" + prov).get("proxies", []) lst = api("GET", "/providers/proxies/" + prov).get("proxies", [])
except Exception: except Exception:
@@ -106,12 +108,13 @@ def cmd_select(r):
def cmd_delay(r): def cmd_delay(r):
test = "url=" + q(TEST_URL) + "&timeout=5000" test = "url=" + q(TEST_URL) + "&timeout=8000" # AmneziaWG 3 handshakes after idle can take 5+ s
if r.get("group") in DELAY_GROUPS: if r.get("group") in DELAY_GROUPS:
return {"ok": True, "delays": api("GET", "/group/%s/delay?%s" % (q(r["group"]), test), timeout=10)} return {"ok": True, "delays": api("GET", "/group/%s/delay?%s" % (q(r["group"]), test), timeout=15)}
if r.get("proxy") in CLIENT_TUNNELS: if r.get("proxy") in CLIENT_TUNNELS:
try: try:
d = api("GET", "/proxies/%s/delay?%s" % (q(r["proxy"]), test), timeout=10).get("delay", 0) d = api("GET", "/providers/proxies/clients/%s/healthcheck?%s" % (q(r["proxy"]), test),
timeout=15).get("delay", 0)
except Exception: except Exception:
d = 0 d = 0
return {"ok": True, "delays": {r["proxy"]: d}} return {"ok": True, "delays": {r["proxy"]: d}}
@@ -135,6 +138,22 @@ def network_services():
return [l for l in out[1:] if l and not l.startswith("*")] return [l for l in out[1:] if l and not l.startswith("*")]
def active_services():
"""Hardware services that carry traffic right now: Wi-Fi or a wired adapter (en*) with
status active. Touching the others — «iPhone USB», Thunderbolt Bridge, VPN services —
made macOS re-check them and offer the iPhone's hotspot over and over."""
order = subprocess.run(["/usr/sbin/networksetup", "-listnetworkserviceorder"],
capture_output=True, text=True, timeout=10).stdout
out = []
for name, port, dev in re.findall(r"\(\d+\) (.+)\n\(Hardware Port: ([^,]*), Device: ([^)]*)\)", order):
if not re.fullmatch(r"en\d+", dev) or "iphone" in (name + port).lower():
continue
status = subprocess.run(["/sbin/ifconfig", dev], capture_output=True, text=True, timeout=5).stdout
if "status: active" in status:
out.append(name.strip())
return out
def dns_of(service): def dns_of(service):
out = subprocess.run(["/usr/sbin/networksetup", "-getdnsservers", service], out = subprocess.run(["/usr/sbin/networksetup", "-getdnsservers", service],
capture_output=True, text=True, timeout=10).stdout.splitlines() capture_output=True, text=True, timeout=10).stdout.splitlines()
@@ -153,11 +172,15 @@ def dns_to_core():
backup = json.load(f) backup = json.load(f)
except (OSError, ValueError): except (OSError, ValueError):
backup = {} backup = {}
active = set(active_services())
for svc in network_services(): for svc in network_services():
cur = dns_of(svc) cur = dns_of(svc)
if svc in active:
if cur != [CORE_DNS]: if cur != [CORE_DNS]:
backup[svc] = cur backup[svc] = cur
set_dns(svc, [CORE_DNS]) set_dns(svc, [CORE_DNS])
elif cur == [CORE_DNS]: # set by an older version: give it back
set_dns(svc, [x for x in backup.pop(svc, []) if x != CORE_DNS])
fd = os.open(DNS_BACKUP, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600) fd = os.open(DNS_BACKUP, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600)
with os.fdopen(fd, "w") as f: with os.fdopen(fd, "w") as f:
json.dump(backup, f) json.dump(backup, f)
@@ -395,6 +418,30 @@ def cmd_refresh(_):
"removed": sorted(before - set(after))} "removed": sorted(before - set(after))}
def cmd_rebind(_):
"""After the Mac moved to another network (its address changed): a clean core restart.
mihomo's WireGuard outbounds stay bound to the old address; re-creating them through a
provider reload leaked every old tunnel (16.10: 652 UDP sockets, 677 MB, the Amnezia
servers stopped answering the handshake flood). A restart leaves nothing behind, and
the move has dropped the open TCP connections anyway. TUN comes back as tun.json says;
the DNS follows the newly active adapter."""
subprocess.run(["/bin/launchctl", "kickstart", "-k", "system/" + CORE_LABEL], capture_output=True, timeout=20)
for _ in range(40):
time.sleep(0.25)
try:
api("GET", "/configs", timeout=2)
break
except Exception:
pass
try:
with open(os.path.join(CORE, "tun.json")) as f:
if json.load(f).get("on", True):
dns_to_core()
except (OSError, ValueError):
pass
return {"ok": True, "restarted": True}
def cmd_hide(r): def cmd_hide(r):
return change_hidden(r.get("name"), True) return change_hidden(r.get("name"), True)
@@ -405,7 +452,7 @@ def cmd_unhide(r):
COMMANDS = {"state": cmd_state, "select": cmd_select, "delay": cmd_delay, "tun": cmd_tun, COMMANDS = {"state": cmd_state, "select": cmd_select, "delay": cmd_delay, "tun": cmd_tun,
"add_key": cmd_add_key, "hide": cmd_hide, "unhide": cmd_unhide, "add_key": cmd_add_key, "hide": cmd_hide, "unhide": cmd_unhide,
"refresh": cmd_refresh} "refresh": cmd_refresh, "rebind": cmd_rebind}
# MARK: - Socket server # MARK: - Socket server