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,328 @@
|
|
|
1
|
+
import Cocoa
|
|
2
|
+
import Darwin
|
|
3
|
+
|
|
4
|
+
struct MenuBarInstanceIdentity: Equatable {
|
|
5
|
+
let processIdentifier: pid_t
|
|
6
|
+
let packageVersion: String?
|
|
7
|
+
let buildVersion: String?
|
|
8
|
+
let startedAt: Date?
|
|
9
|
+
|
|
10
|
+
init(
|
|
11
|
+
processIdentifier: pid_t,
|
|
12
|
+
packageVersion: String?,
|
|
13
|
+
buildVersion: String?,
|
|
14
|
+
startedAt: Date? = nil
|
|
15
|
+
) {
|
|
16
|
+
self.processIdentifier = processIdentifier
|
|
17
|
+
self.packageVersion = packageVersion
|
|
18
|
+
self.buildVersion = buildVersion
|
|
19
|
+
self.startedAt = startedAt
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
enum MenuBarInstanceArbitration: Equatable {
|
|
24
|
+
case keepCandidate(terminate: [pid_t])
|
|
25
|
+
case exitCandidate(winner: pid_t, terminate: [pid_t])
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
enum MenuBarInstanceAcquisition: Equatable {
|
|
29
|
+
case acquired
|
|
30
|
+
case lostArbitration(winner: pid_t)
|
|
31
|
+
case degraded
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
struct MenuBarRuntimeState: Codable, Equatable {
|
|
35
|
+
let schema: String
|
|
36
|
+
let pid: Int32
|
|
37
|
+
let package_version: String
|
|
38
|
+
let build_version: String
|
|
39
|
+
let bundle_identifier: String
|
|
40
|
+
let executable_path: String
|
|
41
|
+
let started_at: String?
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
final class SingletonInstanceGuard {
|
|
45
|
+
private let bundleIdentifier: String
|
|
46
|
+
private let packageVersion: String
|
|
47
|
+
private let buildVersion: String
|
|
48
|
+
private let stateURL: URL
|
|
49
|
+
private let lockURL: URL
|
|
50
|
+
private let currentPID: pid_t
|
|
51
|
+
private let startedAt: Date
|
|
52
|
+
|
|
53
|
+
init(
|
|
54
|
+
bundleIdentifier: String,
|
|
55
|
+
packageVersion: String,
|
|
56
|
+
buildVersion: String,
|
|
57
|
+
buildStampPath: String,
|
|
58
|
+
currentPID: pid_t = getpid(),
|
|
59
|
+
startedAt: Date = Date()
|
|
60
|
+
) {
|
|
61
|
+
self.bundleIdentifier = bundleIdentifier
|
|
62
|
+
self.packageVersion = packageVersion
|
|
63
|
+
self.buildVersion = buildVersion
|
|
64
|
+
self.currentPID = currentPID
|
|
65
|
+
self.startedAt = startedAt
|
|
66
|
+
let installDirectory = URL(fileURLWithPath: buildStampPath).deletingLastPathComponent()
|
|
67
|
+
self.stateURL = installDirectory.appendingPathComponent("runtime-state.json")
|
|
68
|
+
self.lockURL = installDirectory.appendingPathComponent("singleton.lock")
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/// Only `.lostArbitration` requires the caller to exit before constructing app UI.
|
|
72
|
+
/// Degraded acquisition preserves availability after a bounded warning path.
|
|
73
|
+
/// A short-lived filesystem lock serializes simultaneous launchd/manual/Doctor starts.
|
|
74
|
+
func acquire() -> MenuBarInstanceAcquisition {
|
|
75
|
+
// The holder may spend up to five seconds in terminate-and-readback.
|
|
76
|
+
// Wait beyond that bounded critical section before degrading so a
|
|
77
|
+
// normal contender is still arbitrated after the holder releases.
|
|
78
|
+
guard let lockDescriptor = acquireLock(timeout: 6.0) else {
|
|
79
|
+
fputs("SKS Menu Bar singleton: lock unavailable; continuing in degraded mode.\n", stderr)
|
|
80
|
+
return .degraded
|
|
81
|
+
}
|
|
82
|
+
defer {
|
|
83
|
+
flock(lockDescriptor, LOCK_UN)
|
|
84
|
+
close(lockDescriptor)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
let candidate = MenuBarInstanceIdentity(
|
|
88
|
+
processIdentifier: currentPID,
|
|
89
|
+
packageVersion: packageVersion,
|
|
90
|
+
buildVersion: buildVersion,
|
|
91
|
+
startedAt: startedAt
|
|
92
|
+
)
|
|
93
|
+
let applications = NSRunningApplication.runningApplications(withBundleIdentifier: bundleIdentifier)
|
|
94
|
+
.filter { $0.processIdentifier != currentPID && !$0.isTerminated }
|
|
95
|
+
let recordedState = runtimeState()
|
|
96
|
+
let identities = applications.map { application in
|
|
97
|
+
Self.identity(
|
|
98
|
+
processIdentifier: application.processIdentifier,
|
|
99
|
+
runtimeState: recordedState,
|
|
100
|
+
expectedBundleIdentifier: bundleIdentifier
|
|
101
|
+
)
|
|
102
|
+
}
|
|
103
|
+
switch Self.arbitrate(candidate: candidate, running: identities) {
|
|
104
|
+
case let .exitCandidate(winner, processes):
|
|
105
|
+
let targets = applications.filter { processes.contains($0.processIdentifier) }
|
|
106
|
+
if !terminateAndReadBack(targets) {
|
|
107
|
+
fputs("SKS Menu Bar singleton: a losing instance did not terminate within the bounded wait.\n", stderr)
|
|
108
|
+
}
|
|
109
|
+
fputs("SKS Menu Bar singleton: process \(winner) already owns the newer or equal instance.\n", stderr)
|
|
110
|
+
return .lostArbitration(winner: winner)
|
|
111
|
+
case let .keepCandidate(processes):
|
|
112
|
+
let targets = applications.filter { processes.contains($0.processIdentifier) }
|
|
113
|
+
var degraded = false
|
|
114
|
+
if !terminateAndReadBack(targets) {
|
|
115
|
+
fputs("SKS Menu Bar singleton: an older instance did not terminate within the bounded wait.\n", stderr)
|
|
116
|
+
degraded = true
|
|
117
|
+
}
|
|
118
|
+
if !writeRuntimeState() { degraded = true }
|
|
119
|
+
return degraded ? .degraded : .acquired
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
func releaseRuntimeStateIfOwned() {
|
|
124
|
+
guard let data = try? Data(contentsOf: stateURL),
|
|
125
|
+
let state = try? JSONDecoder().decode(MenuBarRuntimeState.self, from: data),
|
|
126
|
+
state.pid == currentPID else { return }
|
|
127
|
+
try? FileManager.default.removeItem(at: stateURL)
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
static func arbitrate(
|
|
131
|
+
candidate: MenuBarInstanceIdentity,
|
|
132
|
+
running: [MenuBarInstanceIdentity]
|
|
133
|
+
) -> MenuBarInstanceArbitration {
|
|
134
|
+
let unique = Dictionary(grouping: running, by: \.processIdentifier)
|
|
135
|
+
.compactMap { $0.value.first }
|
|
136
|
+
guard let incumbent = preferredIncumbent(from: unique) else {
|
|
137
|
+
return .keepCandidate(terminate: [])
|
|
138
|
+
}
|
|
139
|
+
guard candidateOutranksIncumbent(candidate, incumbent) else {
|
|
140
|
+
return .exitCandidate(
|
|
141
|
+
winner: incumbent.processIdentifier,
|
|
142
|
+
terminate: unique
|
|
143
|
+
.filter { $0.processIdentifier != incumbent.processIdentifier }
|
|
144
|
+
.map(\.processIdentifier)
|
|
145
|
+
.sorted()
|
|
146
|
+
)
|
|
147
|
+
}
|
|
148
|
+
return .keepCandidate(terminate: unique.map(\.processIdentifier).sorted())
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
static func compareVersions(_ lhs: String, _ rhs: String) -> ComparisonResult {
|
|
152
|
+
let left = parsedVersion(lhs)
|
|
153
|
+
let right = parsedVersion(rhs)
|
|
154
|
+
let width = max(left.core.count, right.core.count)
|
|
155
|
+
for index in 0..<width {
|
|
156
|
+
let a = index < left.core.count ? left.core[index] : 0
|
|
157
|
+
let b = index < right.core.count ? right.core[index] : 0
|
|
158
|
+
if a != b { return a < b ? .orderedAscending : .orderedDescending }
|
|
159
|
+
}
|
|
160
|
+
if left.prerelease.isEmpty != right.prerelease.isEmpty {
|
|
161
|
+
return left.prerelease.isEmpty ? .orderedDescending : .orderedAscending
|
|
162
|
+
}
|
|
163
|
+
for index in 0..<max(left.prerelease.count, right.prerelease.count) {
|
|
164
|
+
if index >= left.prerelease.count { return .orderedAscending }
|
|
165
|
+
if index >= right.prerelease.count { return .orderedDescending }
|
|
166
|
+
let a = left.prerelease[index]
|
|
167
|
+
let b = right.prerelease[index]
|
|
168
|
+
if a == b { continue }
|
|
169
|
+
if let an = Int(a), let bn = Int(b) {
|
|
170
|
+
return an < bn ? .orderedAscending : .orderedDescending
|
|
171
|
+
}
|
|
172
|
+
if Int(a) != nil { return .orderedAscending }
|
|
173
|
+
if Int(b) != nil { return .orderedDescending }
|
|
174
|
+
return a.localizedStandardCompare(b)
|
|
175
|
+
}
|
|
176
|
+
return .orderedSame
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
private static func candidateOutranksIncumbent(
|
|
180
|
+
_ candidate: MenuBarInstanceIdentity,
|
|
181
|
+
_ incumbent: MenuBarInstanceIdentity
|
|
182
|
+
) -> Bool {
|
|
183
|
+
let versionOrder = compareIdentityVersions(candidate, incumbent)
|
|
184
|
+
if versionOrder != .orderedSame { return versionOrder == .orderedDescending }
|
|
185
|
+
// An incumbent without a recorded start must be kept: its age cannot safely be inferred.
|
|
186
|
+
guard let incumbentStart = incumbent.startedAt else {
|
|
187
|
+
return candidate.startedAt == nil && candidate.processIdentifier < incumbent.processIdentifier
|
|
188
|
+
}
|
|
189
|
+
guard let candidateStart = candidate.startedAt else { return false }
|
|
190
|
+
if candidateStart != incumbentStart { return candidateStart < incumbentStart }
|
|
191
|
+
return candidate.processIdentifier < incumbent.processIdentifier
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
private static func preferredIncumbent(
|
|
195
|
+
from running: [MenuBarInstanceIdentity]
|
|
196
|
+
) -> MenuBarInstanceIdentity? {
|
|
197
|
+
running.sorted { lhs, rhs in
|
|
198
|
+
let versionOrder = compareIdentityVersions(lhs, rhs)
|
|
199
|
+
if versionOrder != .orderedSame { return versionOrder == .orderedDescending }
|
|
200
|
+
switch (lhs.startedAt, rhs.startedAt) {
|
|
201
|
+
case (nil, .some): return true
|
|
202
|
+
case (.some, nil): return false
|
|
203
|
+
case let (.some(left), .some(right)) where left != right: return left < right
|
|
204
|
+
default: return lhs.processIdentifier < rhs.processIdentifier
|
|
205
|
+
}
|
|
206
|
+
}.first
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
private static func compareIdentityVersions(
|
|
210
|
+
_ lhs: MenuBarInstanceIdentity,
|
|
211
|
+
_ rhs: MenuBarInstanceIdentity
|
|
212
|
+
) -> ComparisonResult {
|
|
213
|
+
switch (lhs.packageVersion, rhs.packageVersion) {
|
|
214
|
+
case (nil, nil): return .orderedSame
|
|
215
|
+
case (.some, nil): return .orderedDescending
|
|
216
|
+
case (nil, .some): return .orderedAscending
|
|
217
|
+
case let (.some(leftPackage), .some(rightPackage)):
|
|
218
|
+
let packageOrder = compareVersions(leftPackage, rightPackage)
|
|
219
|
+
if packageOrder != .orderedSame { return packageOrder }
|
|
220
|
+
return compareVersions(
|
|
221
|
+
lhs.buildVersion ?? leftPackage,
|
|
222
|
+
rhs.buildVersion ?? rightPackage
|
|
223
|
+
)
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
private static func parsedVersion(_ raw: String) -> (core: [Int], prerelease: [String]) {
|
|
228
|
+
let withoutMetadata = raw.split(separator: "+", maxSplits: 1).first.map(String.init) ?? raw
|
|
229
|
+
let pieces = withoutMetadata.split(separator: "-", maxSplits: 1, omittingEmptySubsequences: false)
|
|
230
|
+
let core = pieces[0].split(separator: ".", omittingEmptySubsequences: false).map { Int($0) ?? 0 }
|
|
231
|
+
let prerelease = pieces.count > 1 ? pieces[1].split(separator: ".").map(String.init) : []
|
|
232
|
+
return (core.isEmpty ? [0] : core, prerelease)
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
static func identity(
|
|
236
|
+
processIdentifier: pid_t,
|
|
237
|
+
runtimeState: MenuBarRuntimeState?,
|
|
238
|
+
expectedBundleIdentifier: String
|
|
239
|
+
) -> MenuBarInstanceIdentity {
|
|
240
|
+
guard let state = runtimeState,
|
|
241
|
+
state.pid == processIdentifier,
|
|
242
|
+
state.bundle_identifier == expectedBundleIdentifier else {
|
|
243
|
+
return MenuBarInstanceIdentity(
|
|
244
|
+
processIdentifier: processIdentifier,
|
|
245
|
+
packageVersion: nil,
|
|
246
|
+
buildVersion: nil
|
|
247
|
+
)
|
|
248
|
+
}
|
|
249
|
+
return MenuBarInstanceIdentity(
|
|
250
|
+
processIdentifier: processIdentifier,
|
|
251
|
+
packageVersion: state.package_version,
|
|
252
|
+
buildVersion: state.build_version,
|
|
253
|
+
startedAt: parseStartTime(state.started_at)
|
|
254
|
+
)
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
private static func parseStartTime(_ raw: String?) -> Date? {
|
|
258
|
+
guard let raw else { return nil }
|
|
259
|
+
let formatter = ISO8601DateFormatter()
|
|
260
|
+
if let parsed = formatter.date(from: raw) { return parsed }
|
|
261
|
+
formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
|
|
262
|
+
return formatter.date(from: raw)
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
private func terminateAndReadBack(_ applications: [NSRunningApplication]) -> Bool {
|
|
266
|
+
guard !applications.isEmpty else { return true }
|
|
267
|
+
for application in applications { _ = application.terminate() }
|
|
268
|
+
if waitUntilTerminated(applications, timeout: 2.0) { return true }
|
|
269
|
+
for application in applications where !application.isTerminated { _ = application.forceTerminate() }
|
|
270
|
+
return waitUntilTerminated(applications, timeout: 3.0)
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
private func waitUntilTerminated(_ applications: [NSRunningApplication], timeout: TimeInterval) -> Bool {
|
|
274
|
+
let deadline = Date().addingTimeInterval(timeout)
|
|
275
|
+
while Date() < deadline {
|
|
276
|
+
if applications.allSatisfy(\.isTerminated) { return true }
|
|
277
|
+
RunLoop.current.run(until: Date().addingTimeInterval(0.05))
|
|
278
|
+
}
|
|
279
|
+
return applications.allSatisfy(\.isTerminated)
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
private func acquireLock(timeout: TimeInterval) -> Int32? {
|
|
283
|
+
do {
|
|
284
|
+
try FileManager.default.createDirectory(
|
|
285
|
+
at: lockURL.deletingLastPathComponent(),
|
|
286
|
+
withIntermediateDirectories: true,
|
|
287
|
+
attributes: [.posixPermissions: 0o700]
|
|
288
|
+
)
|
|
289
|
+
} catch {
|
|
290
|
+
return nil
|
|
291
|
+
}
|
|
292
|
+
let descriptor = open(lockURL.path, O_CREAT | O_RDWR | O_CLOEXEC, S_IRUSR | S_IWUSR)
|
|
293
|
+
guard descriptor >= 0 else { return nil }
|
|
294
|
+
let deadline = Date().addingTimeInterval(timeout)
|
|
295
|
+
repeat {
|
|
296
|
+
if flock(descriptor, LOCK_EX | LOCK_NB) == 0 { return descriptor }
|
|
297
|
+
usleep(50_000)
|
|
298
|
+
} while Date() < deadline
|
|
299
|
+
close(descriptor)
|
|
300
|
+
return nil
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
private func runtimeState() -> MenuBarRuntimeState? {
|
|
304
|
+
guard let data = try? Data(contentsOf: stateURL) else { return nil }
|
|
305
|
+
return try? JSONDecoder().decode(MenuBarRuntimeState.self, from: data)
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
private func writeRuntimeState() -> Bool {
|
|
309
|
+
let state = MenuBarRuntimeState(
|
|
310
|
+
schema: "sks.menubar-runtime-state.v1",
|
|
311
|
+
pid: currentPID,
|
|
312
|
+
package_version: packageVersion,
|
|
313
|
+
build_version: buildVersion,
|
|
314
|
+
bundle_identifier: bundleIdentifier,
|
|
315
|
+
executable_path: Bundle.main.executableURL?.standardizedFileURL.path ?? CommandLine.arguments[0],
|
|
316
|
+
started_at: ISO8601DateFormatter().string(from: startedAt)
|
|
317
|
+
)
|
|
318
|
+
do {
|
|
319
|
+
let data = try JSONEncoder().encode(state)
|
|
320
|
+
try data.write(to: stateURL, options: .atomic)
|
|
321
|
+
try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: stateURL.path)
|
|
322
|
+
return true
|
|
323
|
+
} catch {
|
|
324
|
+
fputs("SKS Menu Bar singleton: failed to write runtime identity.\n", stderr)
|
|
325
|
+
return false
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
}
|
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
struct TelegramStoredConfirmation: Sendable, Equatable {
|
|
4
|
+
let request: TelegramTypedCommandRequest
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
protocol TelegramAccessStoring: Sendable {
|
|
8
|
+
func loadToken() throws -> String?
|
|
9
|
+
func consumePairing(code: String, chatID: Int64, senderID: Int64, chatType: String) throws -> Bool
|
|
10
|
+
func isAuthorized(chatID: Int64, senderID: Int64) throws -> Bool
|
|
11
|
+
func authorizedCount() throws -> Int
|
|
12
|
+
func issueConfirmation(
|
|
13
|
+
chatID: Int64,
|
|
14
|
+
senderID: Int64,
|
|
15
|
+
request: TelegramTypedCommandRequest,
|
|
16
|
+
expiresAt: Date
|
|
17
|
+
) throws -> String
|
|
18
|
+
func consumeConfirmation(nonce: String, chatID: Int64, senderID: Int64) throws -> TelegramStoredConfirmation?
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
final class TelegramPrivateFileStore: TelegramAccessStoring, @unchecked Sendable {
|
|
22
|
+
static let stateSchema = "sks.telegram-state.v1"
|
|
23
|
+
static let pairingSchema = "sks.telegram-pairing.v1"
|
|
24
|
+
static let tokenEnvironmentNames = ["TELEGRAM_BOT_TOKEN", "SKS_TELEGRAM_BOT_TOKEN"]
|
|
25
|
+
|
|
26
|
+
private struct PairingState {
|
|
27
|
+
let schema: String
|
|
28
|
+
let code: String
|
|
29
|
+
let expiresAt: String
|
|
30
|
+
var used: Bool
|
|
31
|
+
var raw: [String: Any]
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
private struct AuthorizedChat {
|
|
35
|
+
let chatID: Int64
|
|
36
|
+
let senderID: Int64
|
|
37
|
+
let pairedAt: String
|
|
38
|
+
var raw: [String: Any]
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
private struct ConfirmationState {
|
|
42
|
+
let nonce: String
|
|
43
|
+
let chatID: Int64
|
|
44
|
+
let senderID: Int64
|
|
45
|
+
let command: String
|
|
46
|
+
let inputJSON: String
|
|
47
|
+
let expiresAt: String
|
|
48
|
+
var raw: [String: Any]
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
private struct State {
|
|
52
|
+
let schema: String
|
|
53
|
+
var pairing: PairingState?
|
|
54
|
+
var chats: [AuthorizedChat]
|
|
55
|
+
var confirmations: [ConfirmationState]
|
|
56
|
+
var raw: [String: Any]
|
|
57
|
+
|
|
58
|
+
init(
|
|
59
|
+
schema: String = TelegramPrivateFileStore.stateSchema,
|
|
60
|
+
pairing: PairingState? = nil,
|
|
61
|
+
chats: [AuthorizedChat] = [],
|
|
62
|
+
confirmations: [ConfirmationState] = [],
|
|
63
|
+
raw: [String: Any] = [:]
|
|
64
|
+
) {
|
|
65
|
+
self.schema = schema
|
|
66
|
+
self.pairing = pairing
|
|
67
|
+
self.chats = chats
|
|
68
|
+
self.confirmations = confirmations
|
|
69
|
+
self.raw = raw
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
private let environment: [String: String]
|
|
74
|
+
private let files: TelegramPrivateFileSupport
|
|
75
|
+
private let now: @Sendable () -> Date
|
|
76
|
+
|
|
77
|
+
init(
|
|
78
|
+
homeDirectory: URL? = nil,
|
|
79
|
+
environment: [String: String] = ProcessInfo.processInfo.environment,
|
|
80
|
+
now: @escaping @Sendable () -> Date = { Date() }
|
|
81
|
+
) {
|
|
82
|
+
self.environment = environment
|
|
83
|
+
self.files = TelegramPrivateFileSupport(homeDirectory: homeDirectory, environment: environment)
|
|
84
|
+
self.now = now
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
func loadToken() throws -> String? {
|
|
88
|
+
for name in Self.tokenEnvironmentNames {
|
|
89
|
+
let value = (environment[name] ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
|
|
90
|
+
if !value.isEmpty { return try validatedToken(value) }
|
|
91
|
+
}
|
|
92
|
+
guard let data = try files.readTokenData() else { return nil }
|
|
93
|
+
guard let value = String(data: data, encoding: .utf8) else {
|
|
94
|
+
throw TelegramPrivateFileError.invalidStoredValue
|
|
95
|
+
}
|
|
96
|
+
return try validatedToken(value.trimmingCharacters(in: .whitespacesAndNewlines))
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
func consumePairing(code: String, chatID: Int64, senderID: Int64, chatType: String) throws -> Bool {
|
|
100
|
+
guard chatType == "private" else { return false }
|
|
101
|
+
return try files.withStateTransaction {
|
|
102
|
+
var state = try loadStateUnlocked()
|
|
103
|
+
guard var pairing = state.pairing,
|
|
104
|
+
pairing.code == code,
|
|
105
|
+
!pairing.used,
|
|
106
|
+
let expiration = parseTelegramDate(pairing.expiresAt),
|
|
107
|
+
expiration > now() else { return false }
|
|
108
|
+
pairing.used = true
|
|
109
|
+
state.pairing = pairing
|
|
110
|
+
state.chats.removeAll { $0.chatID == chatID }
|
|
111
|
+
state.chats.append(AuthorizedChat(
|
|
112
|
+
chatID: chatID,
|
|
113
|
+
senderID: senderID,
|
|
114
|
+
pairedAt: telegramPrivateStoreDate(now()),
|
|
115
|
+
raw: [:]
|
|
116
|
+
))
|
|
117
|
+
try writeStateUnlocked(state)
|
|
118
|
+
return true
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
func isAuthorized(chatID: Int64, senderID: Int64) throws -> Bool {
|
|
123
|
+
try files.withStateTransaction {
|
|
124
|
+
try loadStateUnlocked().chats.contains { $0.chatID == chatID && $0.senderID == senderID }
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
func authorizedCount() throws -> Int {
|
|
129
|
+
try files.withStateTransaction { try loadStateUnlocked().chats.count }
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
func issueConfirmation(
|
|
133
|
+
chatID: Int64,
|
|
134
|
+
senderID: Int64,
|
|
135
|
+
request: TelegramTypedCommandRequest,
|
|
136
|
+
expiresAt: Date
|
|
137
|
+
) throws -> String {
|
|
138
|
+
try files.withStateTransaction {
|
|
139
|
+
var state = try loadStateUnlocked()
|
|
140
|
+
removeExpiredConfirmations(from: &state)
|
|
141
|
+
guard state.confirmations.count < 64 else {
|
|
142
|
+
throw TelegramPrivateFileError.tooManyConfirmations
|
|
143
|
+
}
|
|
144
|
+
let nonce = UUID().uuidString.replacingOccurrences(of: "-", with: "")
|
|
145
|
+
state.confirmations.append(ConfirmationState(
|
|
146
|
+
nonce: nonce,
|
|
147
|
+
chatID: chatID,
|
|
148
|
+
senderID: senderID,
|
|
149
|
+
command: request.name,
|
|
150
|
+
inputJSON: request.inputJSON,
|
|
151
|
+
expiresAt: telegramPrivateStoreDate(expiresAt),
|
|
152
|
+
raw: [:]
|
|
153
|
+
))
|
|
154
|
+
try writeStateUnlocked(state)
|
|
155
|
+
return nonce
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
func consumeConfirmation(nonce: String, chatID: Int64, senderID: Int64) throws -> TelegramStoredConfirmation? {
|
|
160
|
+
try files.withStateTransaction {
|
|
161
|
+
var state = try loadStateUnlocked()
|
|
162
|
+
let countBeforeExpiration = state.confirmations.count
|
|
163
|
+
removeExpiredConfirmations(from: &state)
|
|
164
|
+
guard let index = state.confirmations.firstIndex(where: {
|
|
165
|
+
$0.nonce == nonce && $0.chatID == chatID && $0.senderID == senderID
|
|
166
|
+
}) else {
|
|
167
|
+
if state.confirmations.count != countBeforeExpiration { try writeStateUnlocked(state) }
|
|
168
|
+
return nil
|
|
169
|
+
}
|
|
170
|
+
let confirmation = state.confirmations.remove(at: index)
|
|
171
|
+
try writeStateUnlocked(state)
|
|
172
|
+
return TelegramStoredConfirmation(request: TelegramTypedCommandRequest(
|
|
173
|
+
name: confirmation.command,
|
|
174
|
+
inputJSON: confirmation.inputJSON
|
|
175
|
+
))
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
private func validatedToken(_ value: String) throws -> String {
|
|
180
|
+
guard value.range(
|
|
181
|
+
of: #"^\d{5,20}:[A-Za-z0-9_-]{20,128}$"#,
|
|
182
|
+
options: .regularExpression
|
|
183
|
+
) != nil else { throw TelegramPrivateFileError.invalidStoredValue }
|
|
184
|
+
return value
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
private func removeExpiredConfirmations(from state: inout State) {
|
|
188
|
+
let current = now()
|
|
189
|
+
state.confirmations.removeAll {
|
|
190
|
+
guard let expiration = parseTelegramDate($0.expiresAt) else { return true }
|
|
191
|
+
return expiration <= current
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
private func loadStateUnlocked() throws -> State {
|
|
196
|
+
guard let data = try files.readStateData() else { return State() }
|
|
197
|
+
guard let root = try JSONSerialization.jsonObject(with: data) as? [String: Any],
|
|
198
|
+
root["schema"] as? String == Self.stateSchema,
|
|
199
|
+
root.keys.contains("pairing"),
|
|
200
|
+
let chatRows = root["chats"] as? [[String: Any]],
|
|
201
|
+
let confirmationRows = root["confirmations"] as? [[String: Any]] else {
|
|
202
|
+
throw TelegramPrivateFileError.invalidStoredValue
|
|
203
|
+
}
|
|
204
|
+
let pairing: PairingState?
|
|
205
|
+
if root["pairing"] is NSNull {
|
|
206
|
+
pairing = nil
|
|
207
|
+
} else if let row = root["pairing"] as? [String: Any] {
|
|
208
|
+
pairing = try decodePairing(row)
|
|
209
|
+
} else {
|
|
210
|
+
throw TelegramPrivateFileError.invalidStoredValue
|
|
211
|
+
}
|
|
212
|
+
let chats = try chatRows.map(decodeChat)
|
|
213
|
+
let confirmations = try confirmationRows.map(decodeConfirmation)
|
|
214
|
+
return State(
|
|
215
|
+
pairing: pairing,
|
|
216
|
+
chats: chats,
|
|
217
|
+
confirmations: confirmations,
|
|
218
|
+
raw: root
|
|
219
|
+
)
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
private func writeStateUnlocked(_ state: State) throws {
|
|
223
|
+
var root = state.raw
|
|
224
|
+
root["schema"] = Self.stateSchema
|
|
225
|
+
root["pairing"] = state.pairing.map(encodePairing) ?? NSNull()
|
|
226
|
+
root["chats"] = state.chats.map(encodeChat)
|
|
227
|
+
root["confirmations"] = state.confirmations.map(encodeConfirmation)
|
|
228
|
+
guard JSONSerialization.isValidJSONObject(root) else {
|
|
229
|
+
throw TelegramPrivateFileError.invalidStoredValue
|
|
230
|
+
}
|
|
231
|
+
var data = try JSONSerialization.data(withJSONObject: root, options: [.sortedKeys])
|
|
232
|
+
data.append(0x0A)
|
|
233
|
+
try files.writeStateData(data)
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
private func decodePairing(_ row: [String: Any]) throws -> PairingState {
|
|
237
|
+
guard let schema = row["schema"] as? String, schema == Self.pairingSchema,
|
|
238
|
+
let code = row["code"] as? String,
|
|
239
|
+
let expiresAt = row["expires_at"] as? String,
|
|
240
|
+
let used = row["used"] as? Bool else {
|
|
241
|
+
throw TelegramPrivateFileError.invalidStoredValue
|
|
242
|
+
}
|
|
243
|
+
return PairingState(schema: schema, code: code, expiresAt: expiresAt, used: used, raw: row)
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
private func decodeChat(_ row: [String: Any]) throws -> AuthorizedChat {
|
|
247
|
+
guard let chatID = telegramInt64(row["chat_id"]),
|
|
248
|
+
let senderID = telegramInt64(row["sender_id"]),
|
|
249
|
+
let pairedAt = row["paired_at"] as? String else {
|
|
250
|
+
throw TelegramPrivateFileError.invalidStoredValue
|
|
251
|
+
}
|
|
252
|
+
return AuthorizedChat(chatID: chatID, senderID: senderID, pairedAt: pairedAt, raw: row)
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
private func decodeConfirmation(_ row: [String: Any]) throws -> ConfirmationState {
|
|
256
|
+
guard let nonce = row["nonce"] as? String,
|
|
257
|
+
let chatID = telegramInt64(row["chat_id"]),
|
|
258
|
+
let senderID = telegramInt64(row["sender_id"]),
|
|
259
|
+
let command = row["command"] as? String,
|
|
260
|
+
let inputJSON = row["input_json"] as? String,
|
|
261
|
+
let expiresAt = row["expires_at"] as? String else {
|
|
262
|
+
throw TelegramPrivateFileError.invalidStoredValue
|
|
263
|
+
}
|
|
264
|
+
return ConfirmationState(
|
|
265
|
+
nonce: nonce,
|
|
266
|
+
chatID: chatID,
|
|
267
|
+
senderID: senderID,
|
|
268
|
+
command: command,
|
|
269
|
+
inputJSON: inputJSON,
|
|
270
|
+
expiresAt: expiresAt,
|
|
271
|
+
raw: row
|
|
272
|
+
)
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
private func encodePairing(_ pairing: PairingState) -> [String: Any] {
|
|
276
|
+
var row = pairing.raw
|
|
277
|
+
row["schema"] = Self.pairingSchema
|
|
278
|
+
row["code"] = pairing.code
|
|
279
|
+
row["expires_at"] = pairing.expiresAt
|
|
280
|
+
row["used"] = pairing.used
|
|
281
|
+
return row
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
private func encodeChat(_ chat: AuthorizedChat) -> [String: Any] {
|
|
285
|
+
var row = chat.raw
|
|
286
|
+
row["chat_id"] = chat.chatID
|
|
287
|
+
row["sender_id"] = chat.senderID
|
|
288
|
+
row["paired_at"] = chat.pairedAt
|
|
289
|
+
return row
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
private func encodeConfirmation(_ confirmation: ConfirmationState) -> [String: Any] {
|
|
293
|
+
var row = confirmation.raw
|
|
294
|
+
row["nonce"] = confirmation.nonce
|
|
295
|
+
row["chat_id"] = confirmation.chatID
|
|
296
|
+
row["sender_id"] = confirmation.senderID
|
|
297
|
+
row["command"] = confirmation.command
|
|
298
|
+
row["input_json"] = confirmation.inputJSON
|
|
299
|
+
row["expires_at"] = confirmation.expiresAt
|
|
300
|
+
return row
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
private func telegramInt64(_ value: Any?) -> Int64? {
|
|
305
|
+
guard let number = value as? NSNumber,
|
|
306
|
+
CFGetTypeID(number) != CFBooleanGetTypeID() else { return nil }
|
|
307
|
+
return Int64(number.stringValue)
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
private func parseTelegramDate(_ value: String) -> Date? {
|
|
311
|
+
let fractional = ISO8601DateFormatter()
|
|
312
|
+
fractional.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
|
|
313
|
+
return fractional.date(from: value) ?? ISO8601DateFormatter().date(from: value)
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
private func telegramPrivateStoreDate(_ date: Date) -> String {
|
|
317
|
+
let formatter = ISO8601DateFormatter()
|
|
318
|
+
formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
|
|
319
|
+
return formatter.string(from: date)
|
|
320
|
+
}
|