@arach/lattices 0.1.0

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.
Files changed (64) hide show
  1. package/README.md +157 -0
  2. package/app/Lattices.app/Contents/Info.plist +24 -0
  3. package/app/Package.swift +13 -0
  4. package/app/Sources/App.swift +49 -0
  5. package/app/Sources/AppDelegate.swift +104 -0
  6. package/app/Sources/AppShellView.swift +62 -0
  7. package/app/Sources/AppTypeClassifier.swift +70 -0
  8. package/app/Sources/AppWindowShell.swift +63 -0
  9. package/app/Sources/CheatSheetHUD.swift +331 -0
  10. package/app/Sources/CommandModeState.swift +1341 -0
  11. package/app/Sources/CommandModeView.swift +1380 -0
  12. package/app/Sources/CommandModeWindow.swift +192 -0
  13. package/app/Sources/CommandPaletteView.swift +307 -0
  14. package/app/Sources/CommandPaletteWindow.swift +134 -0
  15. package/app/Sources/DaemonProtocol.swift +101 -0
  16. package/app/Sources/DaemonServer.swift +406 -0
  17. package/app/Sources/DesktopModel.swift +121 -0
  18. package/app/Sources/DesktopModelTypes.swift +71 -0
  19. package/app/Sources/DiagnosticLog.swift +253 -0
  20. package/app/Sources/EventBus.swift +29 -0
  21. package/app/Sources/HotkeyManager.swift +249 -0
  22. package/app/Sources/HotkeyStore.swift +330 -0
  23. package/app/Sources/InventoryManager.swift +35 -0
  24. package/app/Sources/InventoryPath.swift +43 -0
  25. package/app/Sources/KeyRecorderView.swift +210 -0
  26. package/app/Sources/LatticesApi.swift +915 -0
  27. package/app/Sources/MainView.swift +507 -0
  28. package/app/Sources/MainWindow.swift +70 -0
  29. package/app/Sources/OrphanRow.swift +129 -0
  30. package/app/Sources/PaletteCommand.swift +409 -0
  31. package/app/Sources/PermissionChecker.swift +115 -0
  32. package/app/Sources/Preferences.swift +48 -0
  33. package/app/Sources/ProcessModel.swift +199 -0
  34. package/app/Sources/ProcessQuery.swift +151 -0
  35. package/app/Sources/Project.swift +28 -0
  36. package/app/Sources/ProjectRow.swift +368 -0
  37. package/app/Sources/ProjectScanner.swift +121 -0
  38. package/app/Sources/ScreenMapState.swift +2397 -0
  39. package/app/Sources/ScreenMapView.swift +2817 -0
  40. package/app/Sources/ScreenMapWindowController.swift +89 -0
  41. package/app/Sources/SessionManager.swift +72 -0
  42. package/app/Sources/SettingsView.swift +641 -0
  43. package/app/Sources/SettingsWindow.swift +20 -0
  44. package/app/Sources/TabGroupRow.swift +178 -0
  45. package/app/Sources/Terminal.swift +259 -0
  46. package/app/Sources/TerminalQuery.swift +156 -0
  47. package/app/Sources/TerminalSynthesizer.swift +200 -0
  48. package/app/Sources/Theme.swift +124 -0
  49. package/app/Sources/TilePickerView.swift +209 -0
  50. package/app/Sources/TmuxModel.swift +53 -0
  51. package/app/Sources/TmuxQuery.swift +81 -0
  52. package/app/Sources/WindowTiler.swift +1752 -0
  53. package/app/Sources/WorkspaceManager.swift +434 -0
  54. package/bin/daemon-client.js +187 -0
  55. package/bin/lattices-app.js +205 -0
  56. package/bin/lattices.js +1295 -0
  57. package/docs/api.md +707 -0
  58. package/docs/app.md +250 -0
  59. package/docs/concepts.md +225 -0
  60. package/docs/config.md +234 -0
  61. package/docs/layers.md +317 -0
  62. package/docs/overview.md +74 -0
  63. package/docs/quickstart.md +82 -0
  64. package/package.json +38 -0
@@ -0,0 +1,434 @@
1
+ import AppKit
2
+ import CryptoKit
3
+ import Foundation
4
+
5
+ // MARK: - Data Model
6
+
7
+ struct TabGroupTab: Codable {
8
+ let path: String
9
+ let label: String?
10
+ }
11
+
12
+ struct TabGroup: Codable, Identifiable {
13
+ let id: String
14
+ let label: String
15
+ let tabs: [TabGroupTab]
16
+ }
17
+
18
+ struct LayerProject: Codable {
19
+ let path: String?
20
+ let group: String?
21
+ let tile: String?
22
+ let display: Int?
23
+ }
24
+
25
+ struct Layer: Codable, Identifiable {
26
+ let id: String
27
+ let label: String
28
+ let projects: [LayerProject]
29
+ }
30
+
31
+ struct WorkspaceConfig: Codable {
32
+ let name: String
33
+ let groups: [TabGroup]?
34
+ let layers: [Layer]?
35
+ }
36
+
37
+ // MARK: - Grid Presets & Named Layouts
38
+
39
+ struct GridPreset: Codable {
40
+ let x: CGFloat
41
+ let y: CGFloat
42
+ let w: CGFloat
43
+ let h: CGFloat
44
+
45
+ var fractions: (CGFloat, CGFloat, CGFloat, CGFloat) { (x, y, w, h) }
46
+ }
47
+
48
+ struct LayoutWindowSpec: Codable {
49
+ let app: String
50
+ let tile: String // TilePosition name or preset name
51
+ let display: Int? // spatial display number (1-based), nil = current
52
+ let title: String? // optional title match for disambiguation
53
+ }
54
+
55
+ struct LayoutConfig: Codable {
56
+ let windows: [LayoutWindowSpec]
57
+ }
58
+
59
+ struct GridFile: Codable {
60
+ let presets: [String: GridPreset]?
61
+ let layouts: [String: LayoutConfig]?
62
+ }
63
+
64
+ // MARK: - Manager
65
+
66
+ class WorkspaceManager: ObservableObject {
67
+ static let shared = WorkspaceManager()
68
+
69
+ @Published var config: WorkspaceConfig?
70
+ @Published var activeLayerIndex: Int = 0
71
+ @Published var isSwitching: Bool = false
72
+ @Published var gridPresets: [String: GridPreset] = [:]
73
+ @Published var gridLayouts: [String: LayoutConfig] = [:]
74
+
75
+ private let configPath: String
76
+ private let gridConfigPath: String
77
+ private let tmuxPath = "/opt/homebrew/bin/tmux"
78
+ private let activeLayerKey = "lattices.activeLayerIndex"
79
+
80
+ init() {
81
+ let home = FileManager.default.homeDirectoryForCurrentUser.path
82
+ self.configPath = (home as NSString).appendingPathComponent(".lattices/workspace.json")
83
+ self.gridConfigPath = (home as NSString).appendingPathComponent(".lattices/grid.json")
84
+ self.activeLayerIndex = UserDefaults.standard.integer(forKey: activeLayerKey)
85
+ loadConfig()
86
+ loadGridConfig()
87
+ }
88
+
89
+ var activeLayer: Layer? {
90
+ guard let config, let layers = config.layers, activeLayerIndex < layers.count else { return nil }
91
+ return layers[activeLayerIndex]
92
+ }
93
+
94
+ // MARK: - Config I/O
95
+
96
+ func loadConfig() {
97
+ guard FileManager.default.fileExists(atPath: configPath),
98
+ let data = FileManager.default.contents(atPath: configPath) else {
99
+ config = nil
100
+ return
101
+ }
102
+ do {
103
+ config = try JSONDecoder().decode(WorkspaceConfig.self, from: data)
104
+ // Clamp saved index
105
+ if let config, let layers = config.layers, activeLayerIndex >= layers.count {
106
+ activeLayerIndex = 0
107
+ }
108
+ } catch {
109
+ DiagnosticLog.shared.error("WorkspaceManager: failed to decode workspace.json — \(error.localizedDescription)")
110
+ config = nil
111
+ }
112
+ }
113
+
114
+ func reloadConfig() {
115
+ loadConfig()
116
+ loadGridConfig()
117
+ }
118
+
119
+ // MARK: - Grid Config I/O
120
+
121
+ func loadGridConfig() {
122
+ var presets: [String: GridPreset] = [:]
123
+ var layouts: [String: LayoutConfig] = [:]
124
+
125
+ // Load global ~/.lattices/grid.json
126
+ if FileManager.default.fileExists(atPath: gridConfigPath),
127
+ let data = FileManager.default.contents(atPath: gridConfigPath) {
128
+ do {
129
+ let gridFile = try JSONDecoder().decode(GridFile.self, from: data)
130
+ if let p = gridFile.presets { presets.merge(p) { _, new in new } }
131
+ if let l = gridFile.layouts { layouts.merge(l) { _, new in new } }
132
+ } catch {
133
+ DiagnosticLog.shared.error("WorkspaceManager: failed to decode grid.json — \(error.localizedDescription)")
134
+ }
135
+ }
136
+
137
+ // Merge per-project .lattices.json "grid" section on top
138
+ let projectGridPath = ".lattices.json"
139
+ if FileManager.default.fileExists(atPath: projectGridPath),
140
+ let data = FileManager.default.contents(atPath: projectGridPath) {
141
+ do {
142
+ if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
143
+ let gridDict = json["grid"] {
144
+ let gridData = try JSONSerialization.data(withJSONObject: gridDict)
145
+ let gridFile = try JSONDecoder().decode(GridFile.self, from: gridData)
146
+ if let p = gridFile.presets { presets.merge(p) { _, new in new } }
147
+ if let l = gridFile.layouts { layouts.merge(l) { _, new in new } }
148
+ }
149
+ } catch {
150
+ DiagnosticLog.shared.error("WorkspaceManager: failed to decode .lattices.json grid — \(error.localizedDescription)")
151
+ }
152
+ }
153
+
154
+ self.gridPresets = presets
155
+ self.gridLayouts = layouts
156
+ }
157
+
158
+ /// Resolve a tile string to fractions: check user presets first, then built-in TilePosition
159
+ func resolveTileFractions(_ tile: String) -> (CGFloat, CGFloat, CGFloat, CGFloat)? {
160
+ if let preset = gridPresets[tile] {
161
+ return preset.fractions
162
+ }
163
+ if let position = TilePosition(rawValue: tile) {
164
+ return position.rect
165
+ }
166
+ return nil
167
+ }
168
+
169
+ // MARK: - Tab Groups
170
+
171
+ func group(byId id: String) -> TabGroup? {
172
+ config?.groups?.first(where: { $0.id == id })
173
+ }
174
+
175
+ func isGroupRunning(_ group: TabGroup) -> Bool {
176
+ group.tabs.contains { tab in
177
+ let name = Self.sessionName(for: tab.path)
178
+ return shell([tmuxPath, "has-session", "-t", name]) == 0
179
+ }
180
+ }
181
+
182
+ /// Count how many tabs in the group have running sessions
183
+ func runningTabCount(_ group: TabGroup) -> Int {
184
+ group.tabs.filter { tab in
185
+ let name = Self.sessionName(for: tab.path)
186
+ return shell([tmuxPath, "has-session", "-t", name]) == 0
187
+ }.count
188
+ }
189
+
190
+ /// Launch a group by opening each tab as a separate iTerm/Terminal tab
191
+ func launchGroup(_ group: TabGroup) {
192
+ let terminal = Preferences.shared.terminal
193
+ for (i, tab) in group.tabs.enumerated() {
194
+ let label = tab.label ?? (tab.path as NSString).lastPathComponent
195
+ DispatchQueue.main.asyncAfter(deadline: .now() + Double(i) * 0.4) {
196
+ if i == 0 {
197
+ terminal.launch(command: "/opt/homebrew/bin/lattices", in: tab.path)
198
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
199
+ terminal.nameTab(label)
200
+ }
201
+ } else {
202
+ terminal.launchTab(command: "/opt/homebrew/bin/lattices", in: tab.path, tabName: label)
203
+ }
204
+ }
205
+ }
206
+ }
207
+
208
+ /// Kill all individual tab sessions for a group
209
+ func killGroup(_ group: TabGroup) {
210
+ for tab in group.tabs {
211
+ let name = Self.sessionName(for: tab.path)
212
+ let task = Process()
213
+ task.executableURL = URL(fileURLWithPath: tmuxPath)
214
+ task.arguments = ["kill-session", "-t", name]
215
+ task.standardOutput = FileHandle.nullDevice
216
+ task.standardError = FileHandle.nullDevice
217
+ try? task.run()
218
+ task.waitUntilExit()
219
+ }
220
+ }
221
+
222
+ /// Focus a specific tab's session in the terminal
223
+ func focusTab(group: TabGroup, tabIndex: Int) {
224
+ guard tabIndex >= 0, tabIndex < group.tabs.count else { return }
225
+ let tab = group.tabs[tabIndex]
226
+ let sessionName = Self.sessionName(for: tab.path)
227
+ let terminal = Preferences.shared.terminal
228
+ terminal.focusOrAttach(session: sessionName)
229
+ }
230
+
231
+ /// Run a command and return exit code
232
+ private func shell(_ args: [String]) -> Int32 {
233
+ let task = Process()
234
+ task.executableURL = URL(fileURLWithPath: args[0])
235
+ task.arguments = Array(args.dropFirst())
236
+ task.standardOutput = FileHandle.nullDevice
237
+ task.standardError = FileHandle.nullDevice
238
+ try? task.run()
239
+ task.waitUntilExit()
240
+ return task.terminationStatus
241
+ }
242
+
243
+ // MARK: - Display Helper
244
+
245
+ /// Resolve a display index to an NSScreen (falls back to first screen)
246
+ private func screen(for displayIndex: Int?) -> NSScreen? {
247
+ let screens = NSScreen.screens
248
+ guard !screens.isEmpty else { return nil }
249
+ let idx = displayIndex ?? 0
250
+ return idx < screens.count ? screens[idx] : screens[0]
251
+ }
252
+
253
+ // MARK: - Window Lookup
254
+
255
+ /// Find a tracked window for a session name (instant — uses DesktopModel cache)
256
+ private func windowForSession(_ sessionName: String) -> WindowEntry? {
257
+ DesktopModel.shared.windowForSession(sessionName)
258
+ }
259
+
260
+ /// Resolve a session name to a tile target: (wid, pid, frame).
261
+ /// Returns nil if the window isn't tracked or has no tile position.
262
+ private func batchTarget(session: String, position: TilePosition, screen: NSScreen) -> (wid: UInt32, pid: Int32, frame: CGRect)? {
263
+ guard let entry = windowForSession(session) else { return nil }
264
+ let frame = WindowTiler.tileFrame(for: position, on: screen)
265
+ return (entry.wid, entry.pid, frame)
266
+ }
267
+
268
+ // MARK: - Tiling
269
+
270
+ /// Re-tile the current layer without switching (for "tile all")
271
+ func retileCurrentLayer() {
272
+ tileLayer(index: activeLayerIndex, launch: false, force: true)
273
+ }
274
+
275
+ /// Count running projects+groups in a layer
276
+ func layerRunningCount(index: Int) -> (running: Int, total: Int) {
277
+ guard let config, let layers = config.layers, index < layers.count else { return (0, 0) }
278
+ let layer = layers[index]
279
+ let scanner = ProjectScanner.shared
280
+ var running = 0
281
+ let total = layer.projects.count
282
+
283
+ for lp in layer.projects {
284
+ if let groupId = lp.group, let group = group(byId: groupId) {
285
+ if isGroupRunning(group) { running += 1 }
286
+ } else if let path = lp.path {
287
+ let project = scanner.projects.first(where: { $0.path == path })
288
+ if project?.isRunning == true { running += 1 }
289
+ }
290
+ }
291
+ return (running, total)
292
+ }
293
+
294
+ // MARK: - Unified Layer Tiling
295
+
296
+ /// Unified entry point for arranging a layer's windows.
297
+ ///
298
+ /// | launch | force | Behavior |
299
+ /// |--------|-------|----------|
300
+ /// | false | false | Tile running projects only (focus) |
301
+ /// | true | false | Launch stopped + tile all, skip if same layer |
302
+ /// | true | true | Re-launch current layer |
303
+ /// | false | true | Re-tile current layer |
304
+ func tileLayer(index: Int, launch: Bool = false, force: Bool = false) {
305
+ guard let config, let layers = config.layers, index < layers.count else { return }
306
+ if launch && !force && index == activeLayerIndex { return }
307
+
308
+ let diag = DiagnosticLog.shared
309
+ let label = launch ? "tileLayer(launch)" : "tileLayer(focus)"
310
+ let overall = diag.startTimed("\(label) \(activeLayerIndex)→\(index)")
311
+
312
+ isSwitching = true
313
+ let terminal = Preferences.shared.terminal
314
+ let scanner = ProjectScanner.shared
315
+ let targetLayer = layers[index]
316
+
317
+ // Phase 1: classify each project
318
+ var batchMoves: [(wid: UInt32, pid: Int32, frame: CGRect)] = []
319
+ var fallbacks: [(session: String, position: TilePosition, screen: NSScreen)] = []
320
+ var launchQueue: [(session: String, position: TilePosition?, screen: NSScreen, launchAction: () -> Void)] = []
321
+
322
+ for lp in targetLayer.projects {
323
+ guard let lpScreen = screen(for: lp.display) else { continue }
324
+
325
+ if let groupId = lp.group, let grp = group(byId: groupId) {
326
+ let firstTabSession = grp.tabs.first.map { Self.sessionName(for: $0.path) } ?? ""
327
+ let position = lp.tile.flatMap { TilePosition(rawValue: $0) }
328
+ let groupRunning = isGroupRunning(grp)
329
+
330
+ if groupRunning, let pos = position,
331
+ let target = batchTarget(session: firstTabSession, position: pos, screen: lpScreen) {
332
+ batchMoves.append(target)
333
+ } else if !groupRunning && launch {
334
+ diag.info(" launch group: \(grp.label)")
335
+ launchQueue.append((firstTabSession, position, lpScreen, { [weak self] in
336
+ self?.launchGroup(grp)
337
+ }))
338
+ } else if groupRunning, let pos = position {
339
+ // Running but not in DesktopModel — fallback
340
+ fallbacks.append((firstTabSession, pos, lpScreen))
341
+ } else if !groupRunning {
342
+ diag.info(" skip (not running): \(grp.label)")
343
+ }
344
+ continue
345
+ }
346
+
347
+ guard let path = lp.path else { continue }
348
+ let sessionName = Self.sessionName(for: path)
349
+ let project = scanner.projects.first(where: { $0.path == path })
350
+ let position = lp.tile.flatMap { TilePosition(rawValue: $0) }
351
+ let isRunning = project?.isRunning == true
352
+
353
+ if isRunning {
354
+ if let pos = position,
355
+ let target = batchTarget(session: sessionName, position: pos, screen: lpScreen) {
356
+ batchMoves.append(target)
357
+ } else if let pos = position {
358
+ fallbacks.append((sessionName, pos, lpScreen))
359
+ }
360
+ } else if launch {
361
+ if let project {
362
+ let t = diag.startTimed("launch: \(project.name)")
363
+ SessionManager.launch(project: project)
364
+ diag.finish(t)
365
+ } else {
366
+ diag.info(" launch (direct): \(sessionName)")
367
+ terminal.launch(command: "/opt/homebrew/bin/lattices", in: path)
368
+ }
369
+ launchQueue.append((sessionName, position, lpScreen, {}))
370
+ } else {
371
+ diag.info(" skip (not running): \(sessionName)")
372
+ }
373
+ }
374
+
375
+ // Phase 2: batch tile all tracked windows
376
+ if !batchMoves.isEmpty {
377
+ let t = diag.startTimed("batch tile \(batchMoves.count) windows")
378
+ WindowTiler.batchMoveAndRaiseWindows(batchMoves)
379
+ diag.finish(t)
380
+ }
381
+
382
+ // Phase 3: fallback for running-but-untracked windows
383
+ for (i, fb) in fallbacks.enumerated() {
384
+ let delay = Double(i) * 0.15 + 0.1
385
+ DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
386
+ diag.info(" tile fallback: \(fb.session) → \(fb.position.rawValue)")
387
+ WindowTiler.navigateToWindow(session: fb.session, terminal: terminal)
388
+ WindowTiler.tile(session: fb.session, terminal: terminal, to: fb.position, on: fb.screen)
389
+ }
390
+ }
391
+
392
+ // Phase 4: staggered tile for newly-launched windows
393
+ for (i, item) in launchQueue.enumerated() {
394
+ let delay = Double(i) * 0.15 + 0.2
395
+ DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
396
+ item.launchAction()
397
+ if let pos = item.position {
398
+ let t = diag.startTimed("tile launched: \(item.session) → \(pos.rawValue)")
399
+ WindowTiler.tile(session: item.session, terminal: terminal, to: pos, on: item.screen)
400
+ diag.finish(t)
401
+ }
402
+ }
403
+ }
404
+
405
+ activeLayerIndex = index
406
+ UserDefaults.standard.set(index, forKey: activeLayerKey)
407
+
408
+ let maxDelay = max(
409
+ fallbacks.isEmpty ? 0.0 : Double(fallbacks.count) * 0.15 + 0.3,
410
+ launchQueue.isEmpty ? 0.0 : Double(launchQueue.count) * 0.15 + 0.5
411
+ )
412
+ let cleanupDelay = max(0.2, maxDelay)
413
+ DispatchQueue.main.asyncAfter(deadline: .now() + cleanupDelay) {
414
+ scanner.refreshStatus()
415
+ self.isSwitching = false
416
+ diag.finish(overall)
417
+ }
418
+ }
419
+
420
+ // MARK: - Session Name Helper
421
+
422
+ /// Replicates Project.sessionName logic from a bare path
423
+ static func sessionName(for path: String) -> String {
424
+ let name = (path as NSString).lastPathComponent
425
+ let base = name.replacingOccurrences(
426
+ of: "[^a-zA-Z0-9_-]",
427
+ with: "-",
428
+ options: .regularExpression
429
+ )
430
+ let hash = SHA256.hash(data: Data(path.utf8))
431
+ let short = hash.prefix(3).map { String(format: "%02x", $0) }.joined()
432
+ return "\(base)-\(short)"
433
+ }
434
+ }
@@ -0,0 +1,187 @@
1
+ // Lightweight WebSocket client for lattices daemon (ws://127.0.0.1:9399)
2
+ // Uses Node `net` module with manual HTTP upgrade + minimal WS framing.
3
+ // Zero npm dependencies. Requires Node >= 18.
4
+
5
+ import { createConnection } from "node:net";
6
+ import { randomBytes } from "node:crypto";
7
+
8
+ const DAEMON_HOST = "127.0.0.1";
9
+ const DAEMON_PORT = 9399;
10
+
11
+ /**
12
+ * Send a JSON-RPC-style request to the daemon and return the response.
13
+ * @param {string} method
14
+ * @param {object} [params]
15
+ * @param {number} [timeoutMs=3000]
16
+ * @returns {Promise<object>} The result field from the response
17
+ */
18
+ export async function daemonCall(method, params, timeoutMs = 3000) {
19
+ const id = randomBytes(4).toString("hex");
20
+ const request = JSON.stringify({ id, method, params: params ?? null });
21
+
22
+ return new Promise((resolve, reject) => {
23
+ const socket = createConnection({ host: DAEMON_HOST, port: DAEMON_PORT });
24
+ let settled = false;
25
+ let buffer = Buffer.alloc(0);
26
+ let upgraded = false;
27
+
28
+ const timer = setTimeout(() => {
29
+ if (!settled) {
30
+ settled = true;
31
+ socket.destroy();
32
+ reject(new Error("Daemon request timed out"));
33
+ }
34
+ }, timeoutMs);
35
+
36
+ const cleanup = () => {
37
+ clearTimeout(timer);
38
+ socket.destroy();
39
+ };
40
+
41
+ socket.on("error", (err) => {
42
+ if (!settled) {
43
+ settled = true;
44
+ cleanup();
45
+ reject(err);
46
+ }
47
+ });
48
+
49
+ socket.on("connect", () => {
50
+ // Send HTTP upgrade request
51
+ const key = randomBytes(16).toString("base64");
52
+ const upgrade = [
53
+ `GET / HTTP/1.1`,
54
+ `Host: ${DAEMON_HOST}:${DAEMON_PORT}`,
55
+ `Upgrade: websocket`,
56
+ `Connection: Upgrade`,
57
+ `Sec-WebSocket-Key: ${key}`,
58
+ `Sec-WebSocket-Version: 13`,
59
+ ``,
60
+ ``,
61
+ ].join("\r\n");
62
+ socket.write(upgrade);
63
+ });
64
+
65
+ socket.on("data", (chunk) => {
66
+ buffer = Buffer.concat([buffer, chunk]);
67
+
68
+ if (!upgraded) {
69
+ const headerEnd = buffer.indexOf("\r\n\r\n");
70
+ if (headerEnd === -1) return;
71
+ const header = buffer.subarray(0, headerEnd).toString();
72
+ if (!header.includes("101")) {
73
+ settled = true;
74
+ cleanup();
75
+ reject(new Error("WebSocket upgrade failed"));
76
+ return;
77
+ }
78
+ upgraded = true;
79
+ buffer = buffer.subarray(headerEnd + 4);
80
+
81
+ // Send the request as a masked WebSocket text frame
82
+ sendFrame(socket, request);
83
+ }
84
+
85
+ // Try to parse a WebSocket frame from the buffer
86
+ const result = parseFrame(buffer);
87
+ if (result) {
88
+ buffer = result.rest;
89
+ if (!settled) {
90
+ settled = true;
91
+ cleanup();
92
+ try {
93
+ const parsed = JSON.parse(result.payload);
94
+ if (parsed.error) {
95
+ reject(new Error(parsed.error));
96
+ } else {
97
+ resolve(parsed.result);
98
+ }
99
+ } catch (e) {
100
+ reject(new Error("Invalid JSON response from daemon"));
101
+ }
102
+ }
103
+ }
104
+ });
105
+ });
106
+ }
107
+
108
+ /**
109
+ * Check if the daemon is reachable.
110
+ * @returns {Promise<boolean>}
111
+ */
112
+ export async function isDaemonRunning() {
113
+ try {
114
+ await daemonCall("daemon.status", null, 1000);
115
+ return true;
116
+ } catch {
117
+ return false;
118
+ }
119
+ }
120
+
121
+ // MARK: - WebSocket framing helpers
122
+
123
+ function sendFrame(socket, text) {
124
+ const payload = Buffer.from(text, "utf8");
125
+ const mask = randomBytes(4);
126
+ const len = payload.length;
127
+
128
+ let header;
129
+ if (len < 126) {
130
+ header = Buffer.alloc(2);
131
+ header[0] = 0x81; // FIN + text opcode
132
+ header[1] = 0x80 | len; // masked + length
133
+ } else if (len < 65536) {
134
+ header = Buffer.alloc(4);
135
+ header[0] = 0x81;
136
+ header[1] = 0x80 | 126;
137
+ header.writeUInt16BE(len, 2);
138
+ } else {
139
+ header = Buffer.alloc(10);
140
+ header[0] = 0x81;
141
+ header[1] = 0x80 | 127;
142
+ header.writeBigUInt64BE(BigInt(len), 2);
143
+ }
144
+
145
+ // Mask payload
146
+ const masked = Buffer.alloc(payload.length);
147
+ for (let i = 0; i < payload.length; i++) {
148
+ masked[i] = payload[i] ^ mask[i % 4];
149
+ }
150
+
151
+ socket.write(Buffer.concat([header, mask, masked]));
152
+ }
153
+
154
+ function parseFrame(buf) {
155
+ if (buf.length < 2) return null;
156
+
157
+ const masked = (buf[1] & 0x80) !== 0;
158
+ let payloadLen = buf[1] & 0x7f;
159
+ let offset = 2;
160
+
161
+ if (payloadLen === 126) {
162
+ if (buf.length < 4) return null;
163
+ payloadLen = buf.readUInt16BE(2);
164
+ offset = 4;
165
+ } else if (payloadLen === 127) {
166
+ if (buf.length < 10) return null;
167
+ payloadLen = Number(buf.readBigUInt64BE(2));
168
+ offset = 10;
169
+ }
170
+
171
+ if (masked) offset += 4;
172
+ if (buf.length < offset + payloadLen) return null;
173
+
174
+ let payload = buf.subarray(offset, offset + payloadLen);
175
+ if (masked) {
176
+ const maskKey = buf.subarray(offset - 4, offset);
177
+ payload = Buffer.alloc(payloadLen);
178
+ for (let i = 0; i < payloadLen; i++) {
179
+ payload[i] = buf[offset + i] ^ maskKey[i % 4];
180
+ }
181
+ }
182
+
183
+ return {
184
+ payload: payload.toString("utf8"),
185
+ rest: buf.subarray(offset + payloadLen),
186
+ };
187
+ }