sneakoscope 8.0.2 → 8.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +47 -23
- package/config/skills-hash-ledger.v1.json +1 -1
- package/crates/sks-core/Cargo.lock +1 -1
- package/crates/sks-core/Cargo.toml +1 -1
- package/dist/bin/fast-inline.js +55 -13
- package/dist/bin/sks-dispatch.js +1 -1
- package/dist/cli/command-manifest-lite.js +4 -0
- package/dist/cli/command-registry.js +4 -0
- package/dist/cli/install-helpers-codex-lb-chain.js +187 -0
- package/dist/cli/install-helpers-codex-lb-config.js +74 -8
- package/dist/cli/install-helpers.js +89 -44
- package/dist/commands/codex-lb.js +117 -19
- package/dist/commands/doctor.js +697 -37
- package/dist/config/skills-manifest.json +3 -2
- package/dist/core/agents/agent-runner-codex-exec.js +5 -3
- package/dist/core/codex/codex-config-guard.js +238 -52
- package/dist/core/codex-adapter.js +5 -3
- package/dist/core/codex-app/menubar/constants.js +10 -1
- package/dist/core/codex-app/menubar/global-install.js +288 -0
- package/dist/core/codex-app/menubar/installer.js +79 -14
- package/dist/core/codex-app/menubar/launch-agent.js +267 -45
- package/dist/core/codex-app/menubar/paths.js +3 -0
- package/dist/core/codex-app/menubar/rollback.js +55 -7
- package/dist/core/codex-app/menubar/status.js +75 -4
- package/dist/core/codex-control/codex-0139-image-path-real-probe.js +3 -1
- package/dist/core/codex-control/codex-0139-web-search-probe.js +3 -1
- package/dist/core/codex-control/codex-app-server-runtime-env.js +13 -4
- package/dist/core/codex-control/codex-app-server-v2-client.js +3 -3
- package/dist/core/codex-exec-output-schema.js +4 -1
- package/dist/core/codex-lb/codex-lb-env.js +63 -72
- package/dist/core/codex-lb/codex-lb-setup.js +15 -2
- package/dist/core/codex-lb/desktop-center-credentials.js +517 -58
- package/dist/core/codex-lb/desktop-controller.js +153 -24
- package/dist/core/codex-lb/routing-truth.js +327 -0
- package/dist/core/codex-native/core-skill-manifest.js +1 -1
- package/dist/core/commands/basic-cli.js +7 -1
- package/dist/core/commands/qa-loop-command.js +3 -1
- package/dist/core/commands/telegram-command.js +241 -0
- package/dist/core/config-adopt/config-adopt-command.js +35 -0
- package/dist/core/config-adopt/config-adopt.js +346 -0
- package/dist/core/config-adopt/index.js +3 -0
- package/dist/core/doctor/command-alias-cleanup.js +4 -1
- package/dist/core/doctor/current-project-guidance-nested.js +37 -6
- package/dist/core/doctor/current-project-guidance.js +11 -6
- package/dist/core/doctor/doctor-readiness-matrix.js +14 -0
- package/dist/core/doctor/retired-managed-residue-private.js +1 -1
- package/dist/core/doctor/sks-menubar-doctor.js +4 -0
- package/dist/core/feature-fixtures.js +8 -0
- package/dist/core/hooks-runtime/hook-context.js +9 -0
- package/dist/core/hooks-runtime/managed-skill-admission.js +54 -4
- package/dist/core/hooks-runtime/official-subagent-lifecycle.js +69 -1
- package/dist/core/hooks-runtime/subagent-skill-availability-contract.js +2 -2
- package/dist/core/hooks-runtime/subagent-skill-availability-evidence.js +3 -3
- package/dist/core/hooks-runtime/subagent-skill-availability-guards.js +43 -5
- package/dist/core/hooks-runtime/subagent-skill-availability.js +64 -30
- package/dist/core/hooks-runtime/subagent-stop-hook.js +15 -2
- package/dist/core/hooks-runtime.js +148 -4
- package/dist/core/imagegen/imagegen-capability.js +46 -0
- package/dist/core/imagegen/require-imagegen.js +2 -2
- package/dist/core/init/skills.js +17 -3
- package/dist/core/install/installed-package-smoke.js +8 -2
- package/dist/core/naruto/hardware-capacity-probe.js +9 -3
- package/dist/core/naruto/naruto-concurrency-governor.js +68 -24
- package/dist/core/perf/import-graph-budget.js +0 -1
- package/dist/core/product-design-app-server.js +13 -1
- package/dist/core/release/package-size-budget.js +2 -2
- package/dist/core/release/release-pack-receipt.js +1 -2
- package/dist/core/routes/dollar-manifest-lite.js +1 -1
- package/dist/core/routes.js +1 -1
- package/dist/core/security/private-credential-file.js +209 -0
- package/dist/core/subagents/agent-catalog.js +17 -32
- package/dist/core/subagents/naruto-help-contract.js +5 -5
- package/dist/core/subagents/official-subagent-config.js +16 -6
- package/dist/core/subagents/official-subagent-preparation.js +34 -15
- package/dist/core/subagents/official-subagent-prompt.js +4 -4
- package/dist/core/subagents/official-subagent-runner.js +27 -4
- package/dist/core/subagents/thread-budget.js +19 -12
- package/dist/core/subagents/wave-lifecycle.js +18 -6
- package/dist/core/telegram/access.js +54 -0
- package/dist/core/telegram/client.js +144 -0
- package/dist/core/telegram/confirmation.js +37 -0
- package/dist/core/telegram/doctor.js +151 -0
- package/dist/core/telegram/index.js +9 -0
- package/dist/core/telegram/keychain.js +265 -0
- package/dist/core/telegram/liveness.js +109 -0
- package/dist/core/telegram/poller.js +90 -0
- package/dist/core/telegram/redaction.js +15 -0
- package/dist/core/telegram/types.js +1 -0
- package/dist/core/update/update-diagnostics.js +52 -0
- package/dist/core/update/update-migration-state.js +5 -1
- package/dist/core/update/update-operation.js +2 -1
- package/dist/core/update/update-stage-diagnostics.js +38 -0
- package/dist/core/update/update-status.js +2 -9
- package/dist/core/update-check.js +147 -31
- package/dist/core/version.js +1 -1
- package/dist/core/zellij/zellij-launcher.js +23 -4
- package/dist/native/sks-menubar/Sources/AppDelegate.swift +13 -0
- package/dist/native/sks-menubar/Sources/AppIdentity.swift +7 -0
- package/dist/native/sks-menubar/Sources/OperationCoordinator.swift +3 -2
- package/dist/native/sks-menubar/Sources/ProvidersConnectTest.swift +115 -0
- package/dist/native/sks-menubar/Sources/ProvidersFastMode.swift +17 -0
- package/dist/native/sks-menubar/Sources/ProvidersRoutingTruth.swift +190 -0
- package/dist/native/sks-menubar/Sources/ProvidersViewController.swift +100 -59
- package/dist/native/sks-menubar/Sources/SingletonInstanceGuard.swift +328 -0
- package/dist/native/sks-menubar/Sources/TelegramPrivateFileStore.swift +320 -0
- package/dist/native/sks-menubar/Sources/TelegramPrivateFileSupport.swift +303 -0
- package/dist/native/sks-menubar/Sources/TelegramProcessGateway.swift +238 -0
- package/dist/native/sks-menubar/Sources/TelegramRuntimeSupport.swift +56 -0
- package/dist/native/sks-menubar/Sources/TelegramSupport.swift +56 -0
- package/dist/native/sks-menubar/Sources/TelegramTransport.swift +474 -0
- package/dist/native/sks-menubar/Sources/main.swift +15 -1
- package/dist/native/sks-menubar/Tests/OperationCoordinatorTests.swift +4 -3
- package/dist/native/sks-menubar/Tests/ProvidersViewControllerTests.swift +129 -0
- package/dist/native/sks-menubar/Tests/SingletonInstanceGuardTests.swift +183 -0
- package/dist/native/sks-menubar/Tests/TelegramRuntimeSmokeTests.swift +267 -0
- package/dist/native/sks-menubar/Tests/TelegramRuntimeTests.swift +222 -0
- package/dist/scripts/codex-lb-fast-mode-truth-check.js +1 -1
- package/dist/scripts/codex-lb-fast-ui-preservation-check.js +1 -1
- package/dist/scripts/current-command-surface-check.js +2 -4
- package/dist/scripts/official-subagent-workflow-check.js +1 -1
- package/dist/scripts/packlist-performance-check.js +1 -2
- package/package.json +1 -1
|
@@ -0,0 +1,474 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
struct TelegramNativeUser: Codable, Sendable {
|
|
4
|
+
let id: Int64
|
|
5
|
+
let is_bot: Bool
|
|
6
|
+
let first_name: String
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
struct TelegramNativeChat: Codable, Sendable {
|
|
10
|
+
let id: Int64
|
|
11
|
+
let type: String
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
struct TelegramNativeMessage: Codable, Sendable {
|
|
15
|
+
let message_id: Int64
|
|
16
|
+
let date: Int64
|
|
17
|
+
let chat: TelegramNativeChat
|
|
18
|
+
let from: TelegramNativeUser?
|
|
19
|
+
let text: String?
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
struct TelegramNativeUpdate: Codable, Sendable {
|
|
23
|
+
let update_id: Int64
|
|
24
|
+
let message: TelegramNativeMessage?
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
protocol TelegramBotAPI: Sendable {
|
|
28
|
+
func getMe(token: String) async throws -> TelegramNativeUser
|
|
29
|
+
func getUpdates(token: String, offset: Int64, timeoutSeconds: Int) async throws -> [TelegramNativeUpdate]
|
|
30
|
+
func sendMessage(token: String, chatID: Int64, text: String) async throws
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
enum TelegramTransportError: Error, Equatable {
|
|
34
|
+
case invalidToken
|
|
35
|
+
case invalidResponse
|
|
36
|
+
case responseTooLarge
|
|
37
|
+
case auditUnavailable
|
|
38
|
+
case apiFailure(Int?, String)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
final class TelegramHTTPSBotAPI: TelegramBotAPI, @unchecked Sendable {
|
|
42
|
+
private struct ResponseEnvelope<T: Decodable>: Decodable {
|
|
43
|
+
let ok: Bool
|
|
44
|
+
let result: T?
|
|
45
|
+
let error_code: Int?
|
|
46
|
+
let description: String?
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
private let session: URLSession
|
|
50
|
+
private let baseURL: URL
|
|
51
|
+
private let maximumResponseBytes = 2 * 1024 * 1024
|
|
52
|
+
|
|
53
|
+
init(baseURL: URL = URL(string: "https://api.telegram.org")!, session: URLSession? = nil) {
|
|
54
|
+
self.baseURL = baseURL
|
|
55
|
+
if let session {
|
|
56
|
+
self.session = session
|
|
57
|
+
} else {
|
|
58
|
+
let configuration = URLSessionConfiguration.ephemeral
|
|
59
|
+
configuration.httpShouldSetCookies = false
|
|
60
|
+
configuration.urlCache = nil
|
|
61
|
+
configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
|
|
62
|
+
self.session = URLSession(configuration: configuration, delegate: TelegramNoRedirectDelegate(), delegateQueue: nil)
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
func getMe(token: String) async throws -> TelegramNativeUser {
|
|
67
|
+
try await call(token: token, method: "getMe", body: [:], timeout: 20)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
func getUpdates(token: String, offset: Int64, timeoutSeconds: Int) async throws -> [TelegramNativeUpdate] {
|
|
71
|
+
let timeout = max(1, min(timeoutSeconds, 50))
|
|
72
|
+
return try await call(token: token, method: "getUpdates", body: [
|
|
73
|
+
"offset": offset,
|
|
74
|
+
"timeout": timeout,
|
|
75
|
+
"allowed_updates": ["message"]
|
|
76
|
+
], timeout: TimeInterval(timeout + 10))
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
func sendMessage(token: String, chatID: Int64, text: String) async throws {
|
|
80
|
+
let bounded = String(text.prefix(4_000))
|
|
81
|
+
guard !bounded.isEmpty else { return }
|
|
82
|
+
let _: TelegramNativeMessage = try await call(token: token, method: "sendMessage", body: [
|
|
83
|
+
"chat_id": chatID,
|
|
84
|
+
"text": bounded
|
|
85
|
+
], timeout: 20)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
private func call<T: Decodable>(
|
|
89
|
+
token: String,
|
|
90
|
+
method: String,
|
|
91
|
+
body: [String: Any],
|
|
92
|
+
timeout: TimeInterval
|
|
93
|
+
) async throws -> T {
|
|
94
|
+
guard token.range(of: #"^\d+:[A-Za-z0-9_-]+$"#, options: .regularExpression) != nil else {
|
|
95
|
+
throw TelegramTransportError.invalidToken
|
|
96
|
+
}
|
|
97
|
+
guard baseURL.scheme == "https",
|
|
98
|
+
let endpoint = URL(string: "bot\(token)/\(method)", relativeTo: baseURL)?.absoluteURL else {
|
|
99
|
+
throw TelegramTransportError.invalidResponse
|
|
100
|
+
}
|
|
101
|
+
var request = URLRequest(url: endpoint, timeoutInterval: timeout)
|
|
102
|
+
request.httpMethod = "POST"
|
|
103
|
+
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
|
|
104
|
+
request.httpBody = try JSONSerialization.data(withJSONObject: body)
|
|
105
|
+
let (data, response) = try await session.data(for: request)
|
|
106
|
+
guard data.count <= maximumResponseBytes,
|
|
107
|
+
let http = response as? HTTPURLResponse else {
|
|
108
|
+
throw data.count > maximumResponseBytes ? TelegramTransportError.responseTooLarge : TelegramTransportError.invalidResponse
|
|
109
|
+
}
|
|
110
|
+
let envelope: ResponseEnvelope<T>
|
|
111
|
+
do { envelope = try JSONDecoder().decode(ResponseEnvelope<T>.self, from: data) }
|
|
112
|
+
catch { throw TelegramTransportError.invalidResponse }
|
|
113
|
+
guard http.statusCode >= 200, http.statusCode < 300, envelope.ok, let result = envelope.result else {
|
|
114
|
+
throw TelegramTransportError.apiFailure(envelope.error_code ?? http.statusCode, telegramPublicError(envelope.description, secret: token))
|
|
115
|
+
}
|
|
116
|
+
return result
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
private final class TelegramNoRedirectDelegate: NSObject, URLSessionTaskDelegate, @unchecked Sendable {
|
|
121
|
+
func urlSession(
|
|
122
|
+
_ session: URLSession,
|
|
123
|
+
task: URLSessionTask,
|
|
124
|
+
willPerformHTTPRedirection response: HTTPURLResponse,
|
|
125
|
+
newRequest request: URLRequest,
|
|
126
|
+
completionHandler: @escaping (URLRequest?) -> Void
|
|
127
|
+
) {
|
|
128
|
+
completionHandler(nil)
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
struct TelegramTypedCommandRequest: Sendable, Equatable {
|
|
133
|
+
let name: String
|
|
134
|
+
let inputJSON: String
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
struct TelegramTypedCommandDecision: Sendable, Equatable {
|
|
138
|
+
let allowed: Bool
|
|
139
|
+
let confirmationRequired: Bool
|
|
140
|
+
let publicError: String?
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/// The AppDelegate adapter must delegate these calls to the TypeScript
|
|
144
|
+
/// createTelegramCommandDispatcher boundary. It must execute argv directly;
|
|
145
|
+
/// no shell command string is accepted by this protocol.
|
|
146
|
+
protocol TelegramTypedCommandGateway: Sendable {
|
|
147
|
+
func prepare(_ request: TelegramTypedCommandRequest) async -> TelegramTypedCommandDecision
|
|
148
|
+
func execute(_ request: TelegramTypedCommandRequest) async throws -> String
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
struct TelegramNativeAuditEvent: Sendable, Equatable {
|
|
152
|
+
let actor: String
|
|
153
|
+
let action: String
|
|
154
|
+
let command: String?
|
|
155
|
+
let outcome: String
|
|
156
|
+
let detail: String?
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
struct TelegramPollerReceipt: Codable, Sendable, Equatable {
|
|
160
|
+
let schema: String
|
|
161
|
+
let running: Bool
|
|
162
|
+
let offset: Int64
|
|
163
|
+
let consecutive_failures: Int
|
|
164
|
+
let last_poll_at: String?
|
|
165
|
+
let last_success_at: String?
|
|
166
|
+
let last_update_at: String?
|
|
167
|
+
let last_error: String?
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
struct TelegramLivenessReceipt: Codable, Sendable, Equatable {
|
|
171
|
+
let schema: String
|
|
172
|
+
let generation: String
|
|
173
|
+
let pid: Int32
|
|
174
|
+
let running: Bool
|
|
175
|
+
let token_configured: Bool
|
|
176
|
+
let bot_identity_valid: Bool
|
|
177
|
+
let getme_checked_at: String?
|
|
178
|
+
let getme_latency_ms: Int?
|
|
179
|
+
let paired_chat_count: Int
|
|
180
|
+
let started_at: String
|
|
181
|
+
let heartbeat_at: String
|
|
182
|
+
let stale_after_seconds: Int
|
|
183
|
+
let audit_healthy: Bool?
|
|
184
|
+
let audit_last_error: String?
|
|
185
|
+
let poller: TelegramPollerReceipt
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
actor TelegramMenuBarRuntime {
|
|
189
|
+
private let api: TelegramBotAPI
|
|
190
|
+
private let access: TelegramAccessStoring
|
|
191
|
+
private let gateway: TelegramTypedCommandGateway
|
|
192
|
+
private let writer: TelegramLivenessWriter
|
|
193
|
+
private let auditSink: @Sendable (TelegramNativeAuditEvent) throws -> Void
|
|
194
|
+
private var pollTask: Task<Void, Never>?
|
|
195
|
+
private var starting = false
|
|
196
|
+
private var token: String?
|
|
197
|
+
private var botIdentityValid = false
|
|
198
|
+
private var getMeCheckedAt: String?
|
|
199
|
+
private var getMeLatencyMilliseconds: Int?
|
|
200
|
+
private var generation = UUID().uuidString
|
|
201
|
+
private var startedAt = telegramISODate()
|
|
202
|
+
private var offset: Int64 = 0
|
|
203
|
+
private var failures = 0
|
|
204
|
+
private var lastPollAt: String?
|
|
205
|
+
private var lastSuccessAt: String?
|
|
206
|
+
private var lastUpdateAt: String?
|
|
207
|
+
private var lastError: String?
|
|
208
|
+
private var auditHealthy = true
|
|
209
|
+
private var auditLastError: String?
|
|
210
|
+
|
|
211
|
+
init(
|
|
212
|
+
api: TelegramBotAPI = TelegramHTTPSBotAPI(),
|
|
213
|
+
access: TelegramAccessStoring = TelegramPrivateFileStore(),
|
|
214
|
+
gateway: TelegramTypedCommandGateway,
|
|
215
|
+
receiptURL: URL,
|
|
216
|
+
audit: @escaping @Sendable (TelegramNativeAuditEvent) throws -> Void
|
|
217
|
+
) {
|
|
218
|
+
self.api = api
|
|
219
|
+
self.access = access
|
|
220
|
+
self.gateway = gateway
|
|
221
|
+
self.writer = TelegramLivenessWriter(url: receiptURL)
|
|
222
|
+
self.auditSink = audit
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
@discardableResult
|
|
226
|
+
func start() async throws -> TelegramLivenessReceipt {
|
|
227
|
+
if pollTask != nil || starting { throw TelegramTransportError.apiFailure(nil, "telegram_poller_already_running") }
|
|
228
|
+
starting = true
|
|
229
|
+
defer { starting = false }
|
|
230
|
+
let loadedToken = try access.loadToken()
|
|
231
|
+
guard let loadedToken, !loadedToken.isEmpty else {
|
|
232
|
+
token = nil
|
|
233
|
+
botIdentityValid = false
|
|
234
|
+
let receipt = snapshot(running: false)
|
|
235
|
+
try? writer.write(receipt)
|
|
236
|
+
throw TelegramTransportError.invalidToken
|
|
237
|
+
}
|
|
238
|
+
token = loadedToken
|
|
239
|
+
do { try await validateIdentity(token: loadedToken) }
|
|
240
|
+
catch {
|
|
241
|
+
try? writer.write(snapshot(running: false))
|
|
242
|
+
throw error
|
|
243
|
+
}
|
|
244
|
+
auditHealthy = true
|
|
245
|
+
auditLastError = nil
|
|
246
|
+
guard recordAudit(TelegramNativeAuditEvent(
|
|
247
|
+
actor: "system", action: "poller_start", command: nil,
|
|
248
|
+
outcome: "allowed", detail: nil
|
|
249
|
+
)) else {
|
|
250
|
+
try? writer.write(snapshot(running: false))
|
|
251
|
+
throw TelegramTransportError.auditUnavailable
|
|
252
|
+
}
|
|
253
|
+
generation = UUID().uuidString
|
|
254
|
+
startedAt = telegramISODate()
|
|
255
|
+
offset = max(0, writer.read()?.poller.offset ?? 0)
|
|
256
|
+
failures = 0
|
|
257
|
+
lastError = nil
|
|
258
|
+
let pollGeneration = generation
|
|
259
|
+
pollTask = Task { [weak self] in await self?.pollLoop(token: loadedToken, generation: pollGeneration) }
|
|
260
|
+
let receipt = snapshot(running: true)
|
|
261
|
+
try writer.write(receipt)
|
|
262
|
+
return receipt
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
func stop() {
|
|
266
|
+
pollTask?.cancel()
|
|
267
|
+
pollTask = nil
|
|
268
|
+
_ = recordAudit(TelegramNativeAuditEvent(
|
|
269
|
+
actor: "system", action: "poller_stop", command: nil,
|
|
270
|
+
outcome: "allowed", detail: nil
|
|
271
|
+
))
|
|
272
|
+
try? writer.write(snapshot(running: false))
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
func restart() async throws -> TelegramLivenessReceipt {
|
|
276
|
+
stop()
|
|
277
|
+
return try await start()
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
func liveness() -> TelegramLivenessReceipt { snapshot(running: pollTask != nil) }
|
|
281
|
+
|
|
282
|
+
private func pollLoop(token: String, generation pollGeneration: String) async {
|
|
283
|
+
defer {
|
|
284
|
+
if generation == pollGeneration {
|
|
285
|
+
pollTask = nil
|
|
286
|
+
try? writer.write(snapshot(running: false))
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
while !Task.isCancelled {
|
|
290
|
+
lastPollAt = telegramISODate()
|
|
291
|
+
try? writer.write(snapshot(running: true))
|
|
292
|
+
do {
|
|
293
|
+
if shouldRefreshIdentity() { try await validateIdentity(token: token) }
|
|
294
|
+
let updates = try await api.getUpdates(token: token, offset: offset, timeoutSeconds: 30)
|
|
295
|
+
for update in updates.sorted(by: { $0.update_id < $1.update_id }) where update.update_id >= offset {
|
|
296
|
+
guard !Task.isCancelled else { return }
|
|
297
|
+
// Persist the claim before any typed command can cause an
|
|
298
|
+
// external effect. This makes restart behavior at-most-once.
|
|
299
|
+
offset = update.update_id + 1
|
|
300
|
+
lastUpdateAt = telegramISODate()
|
|
301
|
+
try writer.write(snapshot(running: true))
|
|
302
|
+
await handle(update: update, token: token)
|
|
303
|
+
if !auditHealthy { return }
|
|
304
|
+
}
|
|
305
|
+
failures = 0
|
|
306
|
+
lastSuccessAt = telegramISODate()
|
|
307
|
+
lastError = nil
|
|
308
|
+
try? writer.write(snapshot(running: true))
|
|
309
|
+
} catch is CancellationError {
|
|
310
|
+
return
|
|
311
|
+
} catch {
|
|
312
|
+
failures += 1
|
|
313
|
+
lastError = telegramPublicError(String(describing: error))
|
|
314
|
+
try? writer.write(snapshot(running: true))
|
|
315
|
+
let exponent = min(max(failures - 1, 0), 6)
|
|
316
|
+
let delayMilliseconds = min(30_000, 500 * (1 << exponent))
|
|
317
|
+
try? await Task.sleep(nanoseconds: UInt64(delayMilliseconds) * 1_000_000)
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
private func handle(update: TelegramNativeUpdate, token: String) async {
|
|
323
|
+
guard let message = update.message, let sender = message.from, let text = message.text else { return }
|
|
324
|
+
guard auditHealthy else { return }
|
|
325
|
+
let actor = telegramRedactedActor(chatID: message.chat.id, senderID: sender.id)
|
|
326
|
+
let authorized = (try? access.isAuthorized(chatID: message.chat.id, senderID: sender.id)) == true
|
|
327
|
+
if !authorized {
|
|
328
|
+
let code = telegramPairingCode(text: text, chatType: message.chat.type)
|
|
329
|
+
if code == nil {
|
|
330
|
+
_ = recordAudit(TelegramNativeAuditEvent(
|
|
331
|
+
actor: actor, action: "unauthorized_chat", command: nil,
|
|
332
|
+
outcome: "denied", detail: nil
|
|
333
|
+
))
|
|
334
|
+
return
|
|
335
|
+
}
|
|
336
|
+
guard recordAudit(TelegramNativeAuditEvent(
|
|
337
|
+
actor: actor, action: "pair_attempt", command: nil,
|
|
338
|
+
outcome: "allowed", detail: nil
|
|
339
|
+
)) else { return }
|
|
340
|
+
let paired = code.flatMap { try? access.consumePairing(code: $0, chatID: message.chat.id, senderID: sender.id, chatType: message.chat.type) } == true
|
|
341
|
+
guard recordAudit(TelegramNativeAuditEvent(
|
|
342
|
+
actor: actor, action: paired ? "pair" : "unauthorized_chat", command: nil,
|
|
343
|
+
outcome: paired ? "allowed" : "denied", detail: nil
|
|
344
|
+
)) else { return }
|
|
345
|
+
if paired { await send(token: token, chatID: message.chat.id, text: "SKS Telegram control paired.", actor: actor) }
|
|
346
|
+
return
|
|
347
|
+
}
|
|
348
|
+
if let nonce = telegramConfirmationNonce(text) {
|
|
349
|
+
guard let pending = try? access.consumeConfirmation(
|
|
350
|
+
nonce: nonce,
|
|
351
|
+
chatID: message.chat.id,
|
|
352
|
+
senderID: sender.id
|
|
353
|
+
) else {
|
|
354
|
+
guard recordAudit(TelegramNativeAuditEvent(actor: actor, action: "confirm", command: nil, outcome: "denied", detail: "invalid_or_expired_nonce")) else { return }
|
|
355
|
+
await send(token: token, chatID: message.chat.id, text: "Confirmation is invalid or expired.", actor: actor)
|
|
356
|
+
return
|
|
357
|
+
}
|
|
358
|
+
guard recordAudit(TelegramNativeAuditEvent(actor: actor, action: "confirm", command: pending.request.name, outcome: "confirmed", detail: nil)) else { return }
|
|
359
|
+
await execute(pending.request, token: token, chatID: message.chat.id, actor: actor, outcome: "confirmed")
|
|
360
|
+
return
|
|
361
|
+
}
|
|
362
|
+
guard let request = telegramCommandRequest(text) else {
|
|
363
|
+
_ = recordAudit(TelegramNativeAuditEvent(actor: actor, action: "invalid_command", command: nil, outcome: "denied", detail: nil))
|
|
364
|
+
return
|
|
365
|
+
}
|
|
366
|
+
let decision = await gateway.prepare(request)
|
|
367
|
+
guard decision.allowed else {
|
|
368
|
+
let denial = telegramPublicError(decision.publicError)
|
|
369
|
+
guard recordAudit(TelegramNativeAuditEvent(actor: actor, action: "execute", command: request.name, outcome: "denied", detail: denial)) else { return }
|
|
370
|
+
await send(token: token, chatID: message.chat.id, text: "Command denied: \(denial)", actor: actor)
|
|
371
|
+
return
|
|
372
|
+
}
|
|
373
|
+
if decision.confirmationRequired {
|
|
374
|
+
let expiration = Date().addingTimeInterval(120)
|
|
375
|
+
guard let nonce = try? access.issueConfirmation(
|
|
376
|
+
chatID: message.chat.id,
|
|
377
|
+
senderID: sender.id,
|
|
378
|
+
request: request,
|
|
379
|
+
expiresAt: expiration
|
|
380
|
+
) else {
|
|
381
|
+
_ = recordAudit(TelegramNativeAuditEvent(actor: actor, action: "confirmation_issued", command: request.name, outcome: "failed", detail: "confirmation_state_unavailable"))
|
|
382
|
+
return
|
|
383
|
+
}
|
|
384
|
+
guard recordAudit(TelegramNativeAuditEvent(actor: actor, action: "confirmation_issued", command: request.name, outcome: "allowed", detail: nil)) else { return }
|
|
385
|
+
await send(token: token, chatID: message.chat.id, text: "Confirm once with /confirm \(nonce) before \(telegramISODate(expiration)).", actor: actor)
|
|
386
|
+
return
|
|
387
|
+
}
|
|
388
|
+
await execute(request, token: token, chatID: message.chat.id, actor: actor, outcome: "allowed")
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
private func execute(_ request: TelegramTypedCommandRequest, token: String, chatID: Int64, actor: String, outcome: String) async {
|
|
392
|
+
guard recordAudit(TelegramNativeAuditEvent(
|
|
393
|
+
actor: actor, action: "execute_started", command: request.name,
|
|
394
|
+
outcome: outcome, detail: nil
|
|
395
|
+
)) else { return }
|
|
396
|
+
do {
|
|
397
|
+
let result = try await gateway.execute(request)
|
|
398
|
+
guard recordAudit(TelegramNativeAuditEvent(actor: actor, action: "execute", command: request.name, outcome: outcome, detail: nil)) else { return }
|
|
399
|
+
await send(token: token, chatID: chatID, text: String(result.prefix(4_000)), actor: actor)
|
|
400
|
+
} catch {
|
|
401
|
+
let detail = telegramPublicError(String(describing: error))
|
|
402
|
+
guard recordAudit(TelegramNativeAuditEvent(actor: actor, action: "execute", command: request.name, outcome: "failed", detail: detail)) else { return }
|
|
403
|
+
await send(token: token, chatID: chatID, text: "Command failed: \(detail)", actor: actor)
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
private func send(token: String, chatID: Int64, text: String, actor: String) async {
|
|
408
|
+
do { try await api.sendMessage(token: token, chatID: chatID, text: text) }
|
|
409
|
+
catch {
|
|
410
|
+
_ = recordAudit(TelegramNativeAuditEvent(actor: actor, action: "reply", command: nil, outcome: "failed", detail: telegramPublicError(String(describing: error))))
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
@discardableResult
|
|
415
|
+
private func recordAudit(_ event: TelegramNativeAuditEvent) -> Bool {
|
|
416
|
+
guard auditHealthy else { return false }
|
|
417
|
+
do {
|
|
418
|
+
try auditSink(event)
|
|
419
|
+
return true
|
|
420
|
+
} catch {
|
|
421
|
+
auditHealthy = false
|
|
422
|
+
auditLastError = "telegram_audit_unavailable"
|
|
423
|
+
lastError = "telegram_audit_unavailable"
|
|
424
|
+
try? writer.write(snapshot(running: false))
|
|
425
|
+
return false
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
private func shouldRefreshIdentity() -> Bool {
|
|
430
|
+
guard let checked = getMeCheckedAt.flatMap({ ISO8601DateFormatter().date(from: $0) }) else { return true }
|
|
431
|
+
return Date().timeIntervalSince(checked) >= 5 * 60
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
private func validateIdentity(token: String) async throws {
|
|
435
|
+
let started = Date()
|
|
436
|
+
do {
|
|
437
|
+
let identity = try await api.getMe(token: token)
|
|
438
|
+
getMeCheckedAt = telegramISODate()
|
|
439
|
+
getMeLatencyMilliseconds = max(0, Int(Date().timeIntervalSince(started) * 1_000))
|
|
440
|
+
botIdentityValid = identity.is_bot
|
|
441
|
+
guard identity.is_bot else { throw TelegramTransportError.invalidResponse }
|
|
442
|
+
} catch {
|
|
443
|
+
getMeCheckedAt = telegramISODate()
|
|
444
|
+
getMeLatencyMilliseconds = max(0, Int(Date().timeIntervalSince(started) * 1_000))
|
|
445
|
+
botIdentityValid = false
|
|
446
|
+
throw error
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
private func snapshot(running: Bool) -> TelegramLivenessReceipt {
|
|
451
|
+
TelegramLivenessReceipt(
|
|
452
|
+
schema: "sks.telegram-liveness.v1",
|
|
453
|
+
generation: generation,
|
|
454
|
+
pid: ProcessInfo.processInfo.processIdentifier,
|
|
455
|
+
running: running,
|
|
456
|
+
token_configured: token != nil,
|
|
457
|
+
bot_identity_valid: botIdentityValid,
|
|
458
|
+
getme_checked_at: getMeCheckedAt,
|
|
459
|
+
getme_latency_ms: getMeLatencyMilliseconds,
|
|
460
|
+
paired_chat_count: (try? access.authorizedCount()) ?? 0,
|
|
461
|
+
started_at: startedAt,
|
|
462
|
+
heartbeat_at: telegramISODate(),
|
|
463
|
+
stale_after_seconds: 120,
|
|
464
|
+
audit_healthy: auditHealthy,
|
|
465
|
+
audit_last_error: auditLastError,
|
|
466
|
+
poller: TelegramPollerReceipt(
|
|
467
|
+
schema: "sks.telegram-poller-state.v1", running: running, offset: offset,
|
|
468
|
+
consecutive_failures: failures, last_poll_at: lastPollAt,
|
|
469
|
+
last_success_at: lastSuccessAt, last_update_at: lastUpdateAt,
|
|
470
|
+
last_error: lastError
|
|
471
|
+
)
|
|
472
|
+
)
|
|
473
|
+
}
|
|
474
|
+
}
|
|
@@ -25,6 +25,20 @@ enum AppRuntime {
|
|
|
25
25
|
}
|
|
26
26
|
|
|
27
27
|
let application = NSApplication.shared
|
|
28
|
-
let
|
|
28
|
+
let singletonGuard = SingletonInstanceGuard(
|
|
29
|
+
bundleIdentifier: AppIdentity.bundleIdentifier,
|
|
30
|
+
packageVersion: AppRuntime.packageVersion,
|
|
31
|
+
buildVersion: AppIdentity.buildVersion,
|
|
32
|
+
buildStampPath: AppRuntime.buildStampPath
|
|
33
|
+
)
|
|
34
|
+
switch singletonGuard.acquire() {
|
|
35
|
+
case .acquired:
|
|
36
|
+
break
|
|
37
|
+
case .lostArbitration:
|
|
38
|
+
exit(EXIT_SUCCESS)
|
|
39
|
+
case .degraded:
|
|
40
|
+
break
|
|
41
|
+
}
|
|
42
|
+
let applicationDelegate = AppDelegate(singletonGuard: singletonGuard)
|
|
29
43
|
application.delegate = applicationDelegate
|
|
30
44
|
application.run()
|
|
@@ -3,7 +3,7 @@ import Foundation
|
|
|
3
3
|
import XCTest
|
|
4
4
|
|
|
5
5
|
final class OperationCoordinatorTests: XCTestCase {
|
|
6
|
-
func
|
|
6
|
+
func testCompletedSeventeenStageUpdateReceiptIsAcceptedAndReleasesMutationGuard() throws {
|
|
7
7
|
let directory = FileManager.default.temporaryDirectory
|
|
8
8
|
.appendingPathComponent("sks-operation-coordinator-\(UUID().uuidString)", isDirectory: true)
|
|
9
9
|
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
|
@@ -53,11 +53,12 @@ final class OperationCoordinatorTests: XCTestCase {
|
|
|
53
53
|
try data.write(to: receiptURL, options: .atomic)
|
|
54
54
|
try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: receiptURL.path)
|
|
55
55
|
|
|
56
|
-
XCTAssertEqual(OperationCoordinator.updateStageOrder.count,
|
|
56
|
+
XCTAssertEqual(OperationCoordinator.updateStageOrder.count, 17)
|
|
57
57
|
XCTAssertTrue(OperationCoordinator.updateStageOrder.contains("update_finalize_doctor"))
|
|
58
|
+
XCTAssertTrue(OperationCoordinator.updateStageOrder.contains("menubar_version_probe"))
|
|
58
59
|
|
|
59
60
|
let loaded = try XCTUnwrap(coordinator.latestUpdateReceipt())
|
|
60
|
-
XCTAssertEqual(loaded.stages.count,
|
|
61
|
+
XCTAssertEqual(loaded.stages.count, 17)
|
|
61
62
|
XCTAssertEqual(loaded.registry, registry)
|
|
62
63
|
XCTAssertTrue(OperationCoordinator.receiptMatchesLaunchedUpdate(loaded, operation: operation))
|
|
63
64
|
XCTAssertNil(
|
|
@@ -138,5 +138,134 @@ final class ProvidersViewControllerTests: XCTestCase {
|
|
|
138
138
|
XCTAssertFalse(snapshot.legacyCodexLbSelected)
|
|
139
139
|
XCTAssertTrue(snapshot.chatgptOauthPresent)
|
|
140
140
|
}
|
|
141
|
+
|
|
142
|
+
func testCodexLbIsActiveOnlyFromSelectedMeasuredFreshSuccessfulTruth() {
|
|
143
|
+
let status: [String: Any] = [
|
|
144
|
+
"routing_truth": [
|
|
145
|
+
"schema": "sks.codex-lb-routing-truth.v1",
|
|
146
|
+
"ok": true,
|
|
147
|
+
"status": "verified",
|
|
148
|
+
"selected": true,
|
|
149
|
+
"measured": true,
|
|
150
|
+
"fresh": true,
|
|
151
|
+
"configured_host": "lb.example.test",
|
|
152
|
+
"actual_host": "lb.example.test",
|
|
153
|
+
"auth_transport": "authorization-bearer",
|
|
154
|
+
"auth_outcome": "accepted",
|
|
155
|
+
"http_status": 200,
|
|
156
|
+
"measured_at": "2026-08-01T00:00:00.000Z",
|
|
157
|
+
"latency_ms": 21,
|
|
158
|
+
"blockers": []
|
|
159
|
+
]
|
|
160
|
+
]
|
|
161
|
+
let route = ProviderRoutingTruth.measuredRoute(from: status)
|
|
162
|
+
XCTAssertEqual(route?.state, .active)
|
|
163
|
+
XCTAssertTrue(route?.active == true)
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
func testSelectedFailedAndStaleRoutesRemainVisibleButNeverActive() {
|
|
167
|
+
var failedTruth: [String: Any] = [
|
|
168
|
+
"schema": "sks.codex-lb-routing-truth.v1",
|
|
169
|
+
"ok": false,
|
|
170
|
+
"status": "auth_rejected",
|
|
171
|
+
"selected": true,
|
|
172
|
+
"measured": true,
|
|
173
|
+
"fresh": true,
|
|
174
|
+
"auth_outcome": "rejected",
|
|
175
|
+
"http_status": 401,
|
|
176
|
+
"measured_at": "2026-08-01T00:00:00.000Z",
|
|
177
|
+
"blockers": ["codex_lb_auth_rejected"]
|
|
178
|
+
]
|
|
179
|
+
let failed = ProviderRoutingTruth.measuredRoute(from: ["routing_truth": failedTruth])
|
|
180
|
+
XCTAssertEqual(failed?.state, .degraded)
|
|
181
|
+
XCTAssertFalse(failed?.active == true)
|
|
182
|
+
XCTAssertEqual(failed?.blockers, ["codex_lb_auth_rejected"])
|
|
183
|
+
|
|
184
|
+
failedTruth["status"] = "stale"
|
|
185
|
+
failedTruth["fresh"] = false
|
|
186
|
+
failedTruth["blockers"] = ["codex_lb_routing_truth_stale"]
|
|
187
|
+
let stale = ProviderRoutingTruth.measuredRoute(from: ["routing_truth": failedTruth])
|
|
188
|
+
XCTAssertEqual(stale?.state, .unverified)
|
|
189
|
+
XCTAssertFalse(stale?.active == true)
|
|
190
|
+
XCTAssertEqual(stale?.blockers, ["codex_lb_routing_truth_stale"])
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
func testConnectTestRequiresExactStructuredLiveResponseEvidence() {
|
|
194
|
+
let proof = connectTestFixture()
|
|
195
|
+
let parsed = CodexLbConnectTestTruth.success(from: proof)
|
|
196
|
+
XCTAssertEqual(parsed?.model, "gpt-5.6-luna")
|
|
197
|
+
XCTAssertEqual(parsed?.latencyMs, 42)
|
|
198
|
+
XCTAssertEqual(parsed?.responseId, "resp_fixture")
|
|
199
|
+
XCTAssertEqual(parsed?.inputTokens, 7)
|
|
200
|
+
XCTAssertEqual(parsed?.outputTokens, 4)
|
|
201
|
+
XCTAssertEqual(parsed?.totalTokens, 11)
|
|
202
|
+
XCTAssertEqual(parsed?.httpStatus, 200)
|
|
203
|
+
XCTAssertEqual(CodexLbConnectTestTruth.validationFailure(from: proof), "none")
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
func testConnectTestRejectsMerelyOkTrueOrWrongSchema() {
|
|
207
|
+
XCTAssertNil(CodexLbConnectTestTruth.success(from: ["ok": true]))
|
|
208
|
+
XCTAssertEqual(
|
|
209
|
+
CodexLbConnectTestTruth.validationFailure(from: ["ok": true]),
|
|
210
|
+
"unexpected or missing schema"
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
var wrongSchema = connectTestFixture()
|
|
214
|
+
wrongSchema["schema"] = "sks.codex-lb-health.v1"
|
|
215
|
+
XCTAssertNil(CodexLbConnectTestTruth.success(from: wrongSchema))
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
func testConnectTestRejectsEmptyReplyAndMalformedTokenUsage() {
|
|
219
|
+
var emptyReply = connectTestFixture()
|
|
220
|
+
emptyReply["result"] = " \n "
|
|
221
|
+
XCTAssertNil(CodexLbConnectTestTruth.success(from: emptyReply))
|
|
222
|
+
XCTAssertEqual(CodexLbConnectTestTruth.validationFailure(from: emptyReply), "returned reply is empty")
|
|
223
|
+
|
|
224
|
+
var inconsistentUsage = connectTestFixture()
|
|
225
|
+
inconsistentUsage["usage"] = ["input_tokens": 7, "output_tokens": 4, "total_tokens": 12]
|
|
226
|
+
XCTAssertNil(CodexLbConnectTestTruth.success(from: inconsistentUsage))
|
|
227
|
+
XCTAssertEqual(CodexLbConnectTestTruth.validationFailure(from: inconsistentUsage), "token usage evidence is invalid")
|
|
228
|
+
|
|
229
|
+
var booleanLatency = connectTestFixture()
|
|
230
|
+
booleanLatency["latency_ms"] = true
|
|
231
|
+
XCTAssertNil(CodexLbConnectTestTruth.success(from: booleanLatency))
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
func testConnectTestRejectsUnboundedRequestAndBoundsRenderedReply() {
|
|
235
|
+
var unbounded = connectTestFixture()
|
|
236
|
+
unbounded["usage"] = [
|
|
237
|
+
"input_tokens": 7,
|
|
238
|
+
"output_tokens": CodexLbConnectTestTruth.maximumAcceptedOutputTokens + 1,
|
|
239
|
+
"total_tokens": CodexLbConnectTestTruth.maximumAcceptedOutputTokens + 8
|
|
240
|
+
]
|
|
241
|
+
XCTAssertNil(CodexLbConnectTestTruth.success(from: unbounded))
|
|
242
|
+
XCTAssertEqual(CodexLbConnectTestTruth.validationFailure(from: unbounded), "low-token request evidence is invalid")
|
|
243
|
+
|
|
244
|
+
var longReply = connectTestFixture()
|
|
245
|
+
longReply["result"] = String(repeating: "answer ", count: 80)
|
|
246
|
+
longReply["result_truncated"] = true
|
|
247
|
+
let parsed = CodexLbConnectTestTruth.success(from: longReply)
|
|
248
|
+
XCTAssertNotNil(parsed)
|
|
249
|
+
XCTAssertLessThanOrEqual(parsed?.reply.count ?? .max, CodexLbConnectTestTruth.maximumRenderedReplyCharacters + 1)
|
|
250
|
+
XCTAssertTrue(parsed?.renderedSummary.contains("gpt-5.6-luna") == true)
|
|
251
|
+
XCTAssertTrue(parsed?.renderedSummary.contains("42 ms") == true)
|
|
252
|
+
XCTAssertTrue(parsed?.renderedSummary.contains("7 in / 4 out / 11 total") == true)
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
private func connectTestFixture() -> [String: Any] {
|
|
256
|
+
[
|
|
257
|
+
"schema": "sks.codex-lb-connect-test.v1",
|
|
258
|
+
"ok": true,
|
|
259
|
+
"status": "connected",
|
|
260
|
+
"model": "gpt-5.6-luna",
|
|
261
|
+
"latency_ms": 42,
|
|
262
|
+
"response_id": "resp_fixture",
|
|
263
|
+
"result": "Connected through Codex LB.",
|
|
264
|
+
"result_truncated": false,
|
|
265
|
+
"http_status": 200,
|
|
266
|
+
"usage": ["input_tokens": 7, "output_tokens": 4, "total_tokens": 11],
|
|
267
|
+
"blockers": []
|
|
268
|
+
]
|
|
269
|
+
}
|
|
141
270
|
}
|
|
142
271
|
#endif
|