@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,915 @@
1
+ import Foundation
2
+
3
+ // MARK: - Registry Types
4
+
5
+ enum Access: String, Codable {
6
+ case read, mutate
7
+ }
8
+
9
+ struct Param {
10
+ let name: String
11
+ let type: String // "string", "int", "uint32", "bool"
12
+ let required: Bool
13
+ let description: String
14
+ }
15
+
16
+ enum ReturnShape {
17
+ case array(model: String)
18
+ case object(model: String)
19
+ case ok
20
+ case custom(String)
21
+ }
22
+
23
+ struct Endpoint {
24
+ let method: String
25
+ let description: String
26
+ let access: Access
27
+ let params: [Param]
28
+ let returns: ReturnShape
29
+ let handler: (JSON?) throws -> JSON
30
+ }
31
+
32
+ struct Field {
33
+ let name: String
34
+ let type: String // "string", "int", "double", "bool", "[Model]", "Model?"
35
+ let required: Bool
36
+ let description: String
37
+ }
38
+
39
+ struct ApiModel {
40
+ let name: String
41
+ let fields: [Field]
42
+ }
43
+
44
+ // MARK: - Central Registry
45
+
46
+ final class LatticesApi {
47
+ static let shared = LatticesApi()
48
+
49
+ private(set) var endpoints: [String: Endpoint] = [:]
50
+ private(set) var models: [String: ApiModel] = [:]
51
+ private var endpointOrder: [String] = []
52
+ private var modelOrder: [String] = []
53
+
54
+ private let startTime = Date()
55
+
56
+ func register(_ endpoint: Endpoint) {
57
+ endpoints[endpoint.method] = endpoint
58
+ if !endpointOrder.contains(endpoint.method) {
59
+ endpointOrder.append(endpoint.method)
60
+ }
61
+ }
62
+
63
+ func model(_ model: ApiModel) {
64
+ models[model.name] = model
65
+ if !modelOrder.contains(model.name) {
66
+ modelOrder.append(model.name)
67
+ }
68
+ }
69
+
70
+ func dispatch(method: String, params: JSON?) throws -> JSON {
71
+ guard let endpoint = endpoints[method] else {
72
+ throw RouterError.unknownMethod(method)
73
+ }
74
+ return try endpoint.handler(params)
75
+ }
76
+
77
+ func handle(_ request: DaemonRequest) -> DaemonResponse {
78
+ do {
79
+ let result = try dispatch(method: request.method, params: request.params)
80
+ return DaemonResponse(id: request.id, result: result, error: nil)
81
+ } catch {
82
+ return DaemonResponse(id: request.id, result: nil, error: error.localizedDescription)
83
+ }
84
+ }
85
+
86
+ func schema() -> JSON {
87
+ let modelsList: [JSON] = modelOrder.compactMap { name in
88
+ guard let m = models[name] else { return nil }
89
+ return .object([
90
+ "name": .string(m.name),
91
+ "fields": .array(m.fields.map { f in
92
+ .object([
93
+ "name": .string(f.name),
94
+ "type": .string(f.type),
95
+ "required": .bool(f.required),
96
+ "description": .string(f.description)
97
+ ])
98
+ })
99
+ ])
100
+ }
101
+
102
+ let methodsList: [JSON] = endpointOrder.compactMap { name in
103
+ guard let ep = endpoints[name] else { return nil }
104
+
105
+ let returnsJson: JSON
106
+ switch ep.returns {
107
+ case .array(let model):
108
+ returnsJson = .object(["type": .string("array"), "model": .string(model)])
109
+ case .object(let model):
110
+ returnsJson = .object(["type": .string("object"), "model": .string(model)])
111
+ case .ok:
112
+ returnsJson = .object(["type": .string("ok")])
113
+ case .custom(let desc):
114
+ returnsJson = .object(["type": .string("custom"), "description": .string(desc)])
115
+ }
116
+
117
+ return .object([
118
+ "method": .string(ep.method),
119
+ "description": .string(ep.description),
120
+ "access": .string(ep.access.rawValue),
121
+ "params": .array(ep.params.map { p in
122
+ .object([
123
+ "name": .string(p.name),
124
+ "type": .string(p.type),
125
+ "required": .bool(p.required),
126
+ "description": .string(p.description)
127
+ ])
128
+ }),
129
+ "returns": returnsJson
130
+ ])
131
+ }
132
+
133
+ return .object([
134
+ "version": .string("1.0"),
135
+ "models": .array(modelsList),
136
+ "methods": .array(methodsList)
137
+ ])
138
+ }
139
+
140
+ // MARK: - Setup
141
+
142
+ static func setup() {
143
+ let api = LatticesApi.shared
144
+
145
+ // ── Models ──────────────────────────────────────────────
146
+
147
+ api.model(ApiModel(name: "Window", fields: [
148
+ Field(name: "wid", type: "int", required: true, description: "CGWindowID"),
149
+ Field(name: "app", type: "string", required: true, description: "Application name"),
150
+ Field(name: "pid", type: "int", required: true, description: "Process ID"),
151
+ Field(name: "title", type: "string", required: true, description: "Window title"),
152
+ Field(name: "frame", type: "Frame", required: true, description: "Window frame {x, y, w, h}"),
153
+ Field(name: "spaceIds", type: "[int]", required: true, description: "Space IDs the window is on"),
154
+ Field(name: "isOnScreen", type: "bool", required: true, description: "Whether window is currently visible"),
155
+ Field(name: "latticesSession", type: "string", required: false, description: "Associated lattices session name"),
156
+ ]))
157
+
158
+ api.model(ApiModel(name: "TmuxSession", fields: [
159
+ Field(name: "name", type: "string", required: true, description: "Session name"),
160
+ Field(name: "windowCount", type: "int", required: true, description: "Number of tmux windows"),
161
+ Field(name: "attached", type: "bool", required: true, description: "Whether a client is attached"),
162
+ Field(name: "panes", type: "[TmuxPane]", required: true, description: "Panes in this session"),
163
+ ]))
164
+
165
+ api.model(ApiModel(name: "TmuxPane", fields: [
166
+ Field(name: "id", type: "string", required: true, description: "Pane ID (e.g. %0)"),
167
+ Field(name: "windowIndex", type: "int", required: true, description: "Tmux window index"),
168
+ Field(name: "windowName", type: "string", required: true, description: "Tmux window name"),
169
+ Field(name: "title", type: "string", required: true, description: "Pane title"),
170
+ Field(name: "currentCommand", type: "string", required: true, description: "Currently running command"),
171
+ Field(name: "pid", type: "int", required: true, description: "Process ID of the pane"),
172
+ Field(name: "isActive", type: "bool", required: true, description: "Whether this pane is active"),
173
+ Field(name: "children", type: "[PaneChild]", required: false, description: "Interesting child processes in this pane"),
174
+ ]))
175
+
176
+ api.model(ApiModel(name: "Project", fields: [
177
+ Field(name: "path", type: "string", required: true, description: "Absolute path to project"),
178
+ Field(name: "name", type: "string", required: true, description: "Project display name"),
179
+ Field(name: "sessionName", type: "string", required: true, description: "Tmux session name"),
180
+ Field(name: "isRunning", type: "bool", required: true, description: "Whether the session is active"),
181
+ Field(name: "hasConfig", type: "bool", required: true, description: "Whether .lattices.json exists"),
182
+ Field(name: "paneCount", type: "int", required: true, description: "Number of configured panes"),
183
+ Field(name: "paneNames", type: "[string]", required: true, description: "Names of configured panes"),
184
+ Field(name: "devCommand", type: "string", required: false, description: "Dev command if detected"),
185
+ Field(name: "packageManager", type: "string", required: false, description: "Detected package manager"),
186
+ ]))
187
+
188
+ api.model(ApiModel(name: "Display", fields: [
189
+ Field(name: "displayIndex", type: "int", required: true, description: "Display index"),
190
+ Field(name: "displayId", type: "string", required: true, description: "Display identifier"),
191
+ Field(name: "currentSpaceId", type: "int", required: true, description: "Currently active space ID"),
192
+ Field(name: "spaces", type: "[Space]", required: true, description: "Spaces on this display"),
193
+ ]))
194
+
195
+ api.model(ApiModel(name: "Space", fields: [
196
+ Field(name: "id", type: "int", required: true, description: "Space ID"),
197
+ Field(name: "index", type: "int", required: true, description: "Space index"),
198
+ Field(name: "display", type: "int", required: true, description: "Display index"),
199
+ Field(name: "isCurrent", type: "bool", required: true, description: "Whether this is the active space"),
200
+ ]))
201
+
202
+ api.model(ApiModel(name: "Layer", fields: [
203
+ Field(name: "id", type: "string", required: true, description: "Layer identifier"),
204
+ Field(name: "label", type: "string", required: true, description: "Layer display label"),
205
+ Field(name: "index", type: "int", required: true, description: "Layer index"),
206
+ Field(name: "projectCount", type: "int", required: true, description: "Number of projects in layer"),
207
+ ]))
208
+
209
+ api.model(ApiModel(name: "Process", fields: [
210
+ Field(name: "pid", type: "int", required: true, description: "Process ID"),
211
+ Field(name: "ppid", type: "int", required: true, description: "Parent process ID"),
212
+ Field(name: "command", type: "string", required: true, description: "Command basename (e.g. node, claude)"),
213
+ Field(name: "args", type: "string", required: true, description: "Full command line"),
214
+ Field(name: "cwd", type: "string", required: false, description: "Working directory"),
215
+ Field(name: "tty", type: "string", required: true, description: "Controlling TTY"),
216
+ Field(name: "tmuxSession", type: "string", required: false, description: "Linked tmux session name"),
217
+ Field(name: "tmuxPaneId", type: "string", required: false, description: "Linked tmux pane ID"),
218
+ Field(name: "windowId", type: "int", required: false, description: "Linked macOS window ID"),
219
+ ]))
220
+
221
+ api.model(ApiModel(name: "PaneChild", fields: [
222
+ Field(name: "pid", type: "int", required: true, description: "Process ID"),
223
+ Field(name: "command", type: "string", required: true, description: "Command basename"),
224
+ Field(name: "args", type: "string", required: true, description: "Full command line"),
225
+ Field(name: "cwd", type: "string", required: false, description: "Working directory"),
226
+ ]))
227
+
228
+ api.model(ApiModel(name: "TerminalInstance", fields: [
229
+ Field(name: "tty", type: "string", required: true, description: "Controlling TTY (universal join key)"),
230
+ Field(name: "app", type: "string", required: false, description: "Terminal emulator name (iTerm2, Terminal, etc.)"),
231
+ Field(name: "windowIndex", type: "int", required: false, description: "Terminal window index"),
232
+ Field(name: "tabIndex", type: "int", required: false, description: "Tab index within the window"),
233
+ Field(name: "isActiveTab", type: "bool", required: true, description: "Whether this is the selected tab"),
234
+ Field(name: "tabTitle", type: "string", required: false, description: "Tab title from the terminal emulator"),
235
+ Field(name: "terminalSessionId", type: "string", required: false, description: "Terminal-specific session ID (iTerm2 unique ID)"),
236
+ Field(name: "processes", type: "[Process]", required: true, description: "Interesting processes on this TTY"),
237
+ Field(name: "shellPid", type: "int", required: false, description: "Root shell PID for this TTY"),
238
+ Field(name: "cwd", type: "string", required: false, description: "Working directory (from deepest interesting process)"),
239
+ Field(name: "tmuxSession", type: "string", required: false, description: "Linked tmux session name"),
240
+ Field(name: "tmuxPaneId", type: "string", required: false, description: "Linked tmux pane ID"),
241
+ Field(name: "windowId", type: "int", required: false, description: "Linked macOS window ID (CGWindowID)"),
242
+ Field(name: "windowTitle", type: "string", required: false, description: "macOS window title"),
243
+ Field(name: "hasClaude", type: "bool", required: true, description: "Whether a claude process is running on this TTY"),
244
+ Field(name: "displayName", type: "string", required: true, description: "Best display name (session > tab title > tty)"),
245
+ ]))
246
+
247
+ api.model(ApiModel(name: "DaemonStatus", fields: [
248
+ Field(name: "uptime", type: "double", required: true, description: "Seconds since daemon started"),
249
+ Field(name: "clientCount", type: "int", required: true, description: "Connected WebSocket clients"),
250
+ Field(name: "version", type: "string", required: true, description: "Daemon version"),
251
+ Field(name: "windowCount", type: "int", required: true, description: "Tracked window count"),
252
+ Field(name: "tmuxSessionCount", type: "int", required: true, description: "Active tmux session count"),
253
+ ]))
254
+
255
+ // ── Endpoints: Read ─────────────────────────────────────
256
+
257
+ api.register(Endpoint(
258
+ method: "windows.list",
259
+ description: "List all windows known to the system",
260
+ access: .read,
261
+ params: [],
262
+ returns: .array(model: "Window"),
263
+ handler: { _ in
264
+ let entries = DesktopModel.shared.allWindows()
265
+ return .array(entries.map { Encoders.window($0) })
266
+ }
267
+ ))
268
+
269
+ api.register(Endpoint(
270
+ method: "windows.get",
271
+ description: "Get a single window by ID",
272
+ access: .read,
273
+ params: [Param(name: "wid", type: "uint32", required: true, description: "Window ID")],
274
+ returns: .object(model: "Window"),
275
+ handler: { params in
276
+ guard let wid = params?["wid"]?.uint32Value else {
277
+ throw RouterError.missingParam("wid")
278
+ }
279
+ guard let entry = DesktopModel.shared.windows[wid] else {
280
+ throw RouterError.notFound("window \(wid)")
281
+ }
282
+ return Encoders.window(entry)
283
+ }
284
+ ))
285
+
286
+ api.register(Endpoint(
287
+ method: "tmux.sessions",
288
+ description: "List all tmux sessions with child process enrichment",
289
+ access: .read,
290
+ params: [],
291
+ returns: .array(model: "TmuxSession"),
292
+ handler: { _ in
293
+ let sessions = TmuxModel.shared.sessions
294
+ return .array(sessions.map { Encoders.enrichedSession($0) })
295
+ }
296
+ ))
297
+
298
+ api.register(Endpoint(
299
+ method: "tmux.inventory",
300
+ description: "Get full tmux inventory including orphaned sessions",
301
+ access: .read,
302
+ params: [],
303
+ returns: .custom("Object with 'all' and 'orphans' arrays of TmuxSession"),
304
+ handler: { _ in
305
+ let inv = InventoryManager.shared
306
+ return .object([
307
+ "all": .array(inv.allSessions.map { Encoders.session($0) }),
308
+ "orphans": .array(inv.orphans.map { Encoders.session($0) })
309
+ ])
310
+ }
311
+ ))
312
+
313
+ api.register(Endpoint(
314
+ method: "projects.list",
315
+ description: "List all discovered projects",
316
+ access: .read,
317
+ params: [],
318
+ returns: .array(model: "Project"),
319
+ handler: { _ in
320
+ let projects = ProjectScanner.shared.projects
321
+ return .array(projects.map { Encoders.project($0) })
322
+ }
323
+ ))
324
+
325
+ api.register(Endpoint(
326
+ method: "spaces.list",
327
+ description: "List all displays and their spaces",
328
+ access: .read,
329
+ params: [],
330
+ returns: .array(model: "Display"),
331
+ handler: { _ in
332
+ let displays = WindowTiler.getDisplaySpaces()
333
+ return .array(displays.map { display in
334
+ .object([
335
+ "displayIndex": .int(display.displayIndex),
336
+ "displayId": .string(display.displayId),
337
+ "currentSpaceId": .int(display.currentSpaceId),
338
+ "spaces": .array(display.spaces.map { space in
339
+ .object([
340
+ "id": .int(space.id),
341
+ "index": .int(space.index),
342
+ "display": .int(space.display),
343
+ "isCurrent": .bool(space.isCurrent)
344
+ ])
345
+ })
346
+ ])
347
+ })
348
+ }
349
+ ))
350
+
351
+ api.register(Endpoint(
352
+ method: "layers.list",
353
+ description: "List all workspace layers and the active index",
354
+ access: .read,
355
+ params: [],
356
+ returns: .custom("Object with 'layers' array of Layer and 'active' index"),
357
+ handler: { _ in
358
+ let wm = WorkspaceManager.shared
359
+ guard let config = wm.config, let layers = config.layers else {
360
+ return .object([
361
+ "layers": .array([]),
362
+ "active": .int(0)
363
+ ])
364
+ }
365
+ return .object([
366
+ "layers": .array(layers.enumerated().map { i, layer in
367
+ .object([
368
+ "id": .string(layer.id),
369
+ "label": .string(layer.label),
370
+ "index": .int(i),
371
+ "projectCount": .int(layer.projects.count)
372
+ ])
373
+ }),
374
+ "active": .int(wm.activeLayerIndex)
375
+ ])
376
+ }
377
+ ))
378
+
379
+ api.register(Endpoint(
380
+ method: "daemon.status",
381
+ description: "Get daemon status including uptime and counts",
382
+ access: .read,
383
+ params: [],
384
+ returns: .object(model: "DaemonStatus"),
385
+ handler: { _ in
386
+ let uptime = Date().timeIntervalSince(api.startTime)
387
+ return .object([
388
+ "uptime": .double(uptime),
389
+ "clientCount": .int(DaemonServer.shared.clientCount),
390
+ "version": .string("1.0.0"),
391
+ "windowCount": .int(DesktopModel.shared.windows.count),
392
+ "tmuxSessionCount": .int(TmuxModel.shared.sessions.count)
393
+ ])
394
+ }
395
+ ))
396
+
397
+ api.register(Endpoint(
398
+ method: "processes.list",
399
+ description: "List interesting developer processes with tmux/window linkage",
400
+ access: .read,
401
+ params: [Param(name: "command", type: "string", required: false, description: "Filter by command name (e.g. claude)")],
402
+ returns: .array(model: "Process"),
403
+ handler: { params in
404
+ let pm = ProcessModel.shared
405
+ var enriched = pm.enrichedProcesses()
406
+ if let cmd = params?["command"]?.stringValue {
407
+ enriched = enriched.filter { $0.process.comm == cmd }
408
+ }
409
+ return .array(enriched.map { Encoders.process($0) })
410
+ }
411
+ ))
412
+
413
+ api.register(Endpoint(
414
+ method: "processes.tree",
415
+ description: "Get all descendant processes of a given PID",
416
+ access: .read,
417
+ params: [Param(name: "pid", type: "int", required: true, description: "Parent process ID")],
418
+ returns: .array(model: "Process"),
419
+ handler: { params in
420
+ guard let pid = params?["pid"]?.intValue else {
421
+ throw RouterError.missingParam("pid")
422
+ }
423
+ let pm = ProcessModel.shared
424
+ let descendants = pm.descendants(of: pid)
425
+ return .array(descendants.map { entry in
426
+ let enrichment = pm.enrich(entry)
427
+ return Encoders.process(enrichment)
428
+ })
429
+ }
430
+ ))
431
+
432
+ api.register(Endpoint(
433
+ method: "terminals.list",
434
+ description: "List all synthesized terminal instances (unified TTY view)",
435
+ access: .read,
436
+ params: [
437
+ Param(name: "refresh", type: "bool", required: false, description: "Force-refresh terminal tab cache before synthesizing"),
438
+ ],
439
+ returns: .array(model: "TerminalInstance"),
440
+ handler: { params in
441
+ let pm = ProcessModel.shared
442
+ if params?["refresh"]?.boolValue == true {
443
+ pm.refreshTerminalTabs()
444
+ }
445
+ let instances = pm.synthesizeTerminals()
446
+ return .array(instances.map { Encoders.terminalInstance($0) })
447
+ }
448
+ ))
449
+
450
+ api.register(Endpoint(
451
+ method: "terminals.search",
452
+ description: "Search terminal instances by command, cwd, app, session, or hasClaude",
453
+ access: .read,
454
+ params: [
455
+ Param(name: "command", type: "string", required: false, description: "Filter by command name substring"),
456
+ Param(name: "cwd", type: "string", required: false, description: "Filter by working directory substring"),
457
+ Param(name: "app", type: "string", required: false, description: "Filter by terminal app name"),
458
+ Param(name: "session", type: "string", required: false, description: "Filter by tmux session name"),
459
+ Param(name: "hasClaude", type: "bool", required: false, description: "Filter to only Claude-running TTYs"),
460
+ ],
461
+ returns: .array(model: "TerminalInstance"),
462
+ handler: { params in
463
+ var instances = ProcessModel.shared.synthesizeTerminals()
464
+
465
+ if let cmd = params?["command"]?.stringValue {
466
+ instances = instances.filter { inst in
467
+ inst.processes.contains { $0.comm.contains(cmd) || $0.args.contains(cmd) }
468
+ }
469
+ }
470
+ if let cwd = params?["cwd"]?.stringValue {
471
+ instances = instances.filter { inst in
472
+ inst.cwd?.contains(cwd) == true
473
+ }
474
+ }
475
+ if let app = params?["app"]?.stringValue {
476
+ instances = instances.filter { $0.app?.rawValue == app }
477
+ }
478
+ if let session = params?["session"]?.stringValue {
479
+ instances = instances.filter { $0.tmuxSession == session }
480
+ }
481
+ if let hasClaude = params?["hasClaude"]?.boolValue {
482
+ instances = instances.filter { $0.hasClaude == hasClaude }
483
+ }
484
+
485
+ return .array(instances.map { Encoders.terminalInstance($0) })
486
+ }
487
+ ))
488
+
489
+ // ── Endpoints: Mutations ────────────────────────────────
490
+
491
+ api.register(Endpoint(
492
+ method: "window.tile",
493
+ description: "Tile a session's terminal window to a position",
494
+ access: .mutate,
495
+ params: [
496
+ Param(name: "session", type: "string", required: true, description: "Tmux session name"),
497
+ Param(name: "position", type: "string", required: true,
498
+ description: "Tile position (\(TilePosition.allCases.map(\.rawValue).joined(separator: ", ")))"),
499
+ ],
500
+ returns: .ok,
501
+ handler: { params in
502
+ guard let session = params?["session"]?.stringValue else {
503
+ throw RouterError.missingParam("session")
504
+ }
505
+ guard let posStr = params?["position"]?.stringValue,
506
+ let position = TilePosition(rawValue: posStr) else {
507
+ throw RouterError.missingParam("position (valid: \(TilePosition.allCases.map(\.rawValue).joined(separator: ", ")))")
508
+ }
509
+ let terminal = Preferences.shared.terminal
510
+ DispatchQueue.main.async {
511
+ WindowTiler.tile(session: session, terminal: terminal, to: position)
512
+ }
513
+ return .object(["ok": .bool(true)])
514
+ }
515
+ ))
516
+
517
+ api.register(Endpoint(
518
+ method: "window.focus",
519
+ description: "Focus a window by wid or session name",
520
+ access: .mutate,
521
+ params: [
522
+ Param(name: "wid", type: "uint32", required: false, description: "Window ID (takes priority)"),
523
+ Param(name: "session", type: "string", required: false, description: "Tmux session name (fallback)"),
524
+ ],
525
+ returns: .ok,
526
+ handler: { params in
527
+ if let wid = params?["wid"]?.uint32Value {
528
+ guard let entry = DesktopModel.shared.windows[wid] else {
529
+ throw RouterError.notFound("window \(wid)")
530
+ }
531
+ DispatchQueue.main.async {
532
+ WindowTiler.focusWindow(wid: wid, pid: entry.pid)
533
+ }
534
+ return .object(["ok": .bool(true), "wid": .int(Int(wid)), "app": .string(entry.app)])
535
+ }
536
+ guard let session = params?["session"]?.stringValue else {
537
+ throw RouterError.missingParam("session or wid")
538
+ }
539
+ let terminal = Preferences.shared.terminal
540
+ DispatchQueue.main.async {
541
+ WindowTiler.navigateToWindow(session: session, terminal: terminal)
542
+ }
543
+ return .object(["ok": .bool(true)])
544
+ }
545
+ ))
546
+
547
+ api.register(Endpoint(
548
+ method: "window.move",
549
+ description: "Move a session's window to a different space",
550
+ access: .mutate,
551
+ params: [
552
+ Param(name: "session", type: "string", required: true, description: "Tmux session name"),
553
+ Param(name: "spaceId", type: "int", required: true, description: "Target space ID"),
554
+ ],
555
+ returns: .ok,
556
+ handler: { params in
557
+ guard let session = params?["session"]?.stringValue else {
558
+ throw RouterError.missingParam("session")
559
+ }
560
+ guard let spaceId = params?["spaceId"]?.intValue else {
561
+ throw RouterError.missingParam("spaceId")
562
+ }
563
+ let terminal = Preferences.shared.terminal
564
+ DispatchQueue.main.async {
565
+ _ = WindowTiler.moveWindowToSpace(session: session, terminal: terminal, spaceId: spaceId)
566
+ }
567
+ return .object(["ok": .bool(true)])
568
+ }
569
+ ))
570
+
571
+ api.register(Endpoint(
572
+ method: "session.launch",
573
+ description: "Launch a project's tmux session",
574
+ access: .mutate,
575
+ params: [Param(name: "path", type: "string", required: true, description: "Absolute project path")],
576
+ returns: .ok,
577
+ handler: { params in
578
+ guard let path = params?["path"]?.stringValue else {
579
+ throw RouterError.missingParam("path")
580
+ }
581
+ guard let project = ProjectScanner.shared.projects.first(where: { $0.path == path }) else {
582
+ throw RouterError.notFound("project at \(path)")
583
+ }
584
+ DispatchQueue.main.async {
585
+ SessionManager.launch(project: project)
586
+ }
587
+ return .object(["ok": .bool(true)])
588
+ }
589
+ ))
590
+
591
+ api.register(Endpoint(
592
+ method: "session.kill",
593
+ description: "Kill a tmux session by name",
594
+ access: .mutate,
595
+ params: [Param(name: "name", type: "string", required: true, description: "Session name")],
596
+ returns: .ok,
597
+ handler: { params in
598
+ guard let name = params?["name"]?.stringValue else {
599
+ throw RouterError.missingParam("name")
600
+ }
601
+ SessionManager.killByName(name)
602
+ return .object(["ok": .bool(true)])
603
+ }
604
+ ))
605
+
606
+ api.register(Endpoint(
607
+ method: "session.detach",
608
+ description: "Detach all clients from a tmux session",
609
+ access: .mutate,
610
+ params: [Param(name: "name", type: "string", required: true, description: "Session name")],
611
+ returns: .ok,
612
+ handler: { params in
613
+ guard let name = params?["name"]?.stringValue else {
614
+ throw RouterError.missingParam("name")
615
+ }
616
+ SessionManager.detachByName(name)
617
+ return .object(["ok": .bool(true)])
618
+ }
619
+ ))
620
+
621
+ api.register(Endpoint(
622
+ method: "session.sync",
623
+ description: "Sync a project's tmux session panes to match config",
624
+ access: .mutate,
625
+ params: [Param(name: "path", type: "string", required: true, description: "Absolute project path")],
626
+ returns: .ok,
627
+ handler: { params in
628
+ guard let path = params?["path"]?.stringValue else {
629
+ throw RouterError.missingParam("path")
630
+ }
631
+ guard let project = ProjectScanner.shared.projects.first(where: { $0.path == path }) else {
632
+ throw RouterError.notFound("project at \(path)")
633
+ }
634
+ SessionManager.sync(project: project)
635
+ return .object(["ok": .bool(true)])
636
+ }
637
+ ))
638
+
639
+ api.register(Endpoint(
640
+ method: "session.restart",
641
+ description: "Restart a project session or specific pane",
642
+ access: .mutate,
643
+ params: [
644
+ Param(name: "path", type: "string", required: true, description: "Absolute project path"),
645
+ Param(name: "pane", type: "string", required: false, description: "Specific pane name to restart"),
646
+ ],
647
+ returns: .ok,
648
+ handler: { params in
649
+ guard let path = params?["path"]?.stringValue else {
650
+ throw RouterError.missingParam("path")
651
+ }
652
+ guard let project = ProjectScanner.shared.projects.first(where: { $0.path == path }) else {
653
+ throw RouterError.notFound("project at \(path)")
654
+ }
655
+ let paneName = params?["pane"]?.stringValue
656
+ SessionManager.restart(project: project, paneName: paneName)
657
+ return .object(["ok": .bool(true)])
658
+ }
659
+ ))
660
+
661
+ api.register(Endpoint(
662
+ method: "layer.switch",
663
+ description: "Switch to a workspace layer by index",
664
+ access: .mutate,
665
+ params: [Param(name: "index", type: "int", required: true, description: "Layer index")],
666
+ returns: .ok,
667
+ handler: { params in
668
+ guard let index = params?["index"]?.intValue else {
669
+ throw RouterError.missingParam("index")
670
+ }
671
+ DispatchQueue.main.async {
672
+ WorkspaceManager.shared.tileLayer(index: index, launch: true)
673
+ EventBus.shared.post(.layerSwitched(index: index))
674
+ }
675
+ return .object(["ok": .bool(true)])
676
+ }
677
+ ))
678
+
679
+ api.register(Endpoint(
680
+ method: "group.launch",
681
+ description: "Launch all sessions in a project group",
682
+ access: .mutate,
683
+ params: [Param(name: "id", type: "string", required: true, description: "Group identifier")],
684
+ returns: .ok,
685
+ handler: { params in
686
+ guard let groupId = params?["id"]?.stringValue else {
687
+ throw RouterError.missingParam("id")
688
+ }
689
+ guard let group = WorkspaceManager.shared.group(byId: groupId) else {
690
+ throw RouterError.notFound("group \(groupId)")
691
+ }
692
+ DispatchQueue.main.async {
693
+ WorkspaceManager.shared.launchGroup(group)
694
+ }
695
+ return .object(["ok": .bool(true)])
696
+ }
697
+ ))
698
+
699
+ api.register(Endpoint(
700
+ method: "group.kill",
701
+ description: "Kill all sessions in a project group",
702
+ access: .mutate,
703
+ params: [Param(name: "id", type: "string", required: true, description: "Group identifier")],
704
+ returns: .ok,
705
+ handler: { params in
706
+ guard let groupId = params?["id"]?.stringValue else {
707
+ throw RouterError.missingParam("id")
708
+ }
709
+ guard let group = WorkspaceManager.shared.group(byId: groupId) else {
710
+ throw RouterError.notFound("group \(groupId)")
711
+ }
712
+ WorkspaceManager.shared.killGroup(group)
713
+ return .object(["ok": .bool(true)])
714
+ }
715
+ ))
716
+
717
+ api.register(Endpoint(
718
+ method: "projects.scan",
719
+ description: "Trigger a rescan of project directories",
720
+ access: .mutate,
721
+ params: [],
722
+ returns: .ok,
723
+ handler: { _ in
724
+ DispatchQueue.main.async {
725
+ ProjectScanner.shared.scan()
726
+ }
727
+ return .object(["ok": .bool(true)])
728
+ }
729
+ ))
730
+
731
+ api.register(Endpoint(
732
+ method: "layout.distribute",
733
+ description: "Distribute visible windows evenly across the screen",
734
+ access: .mutate,
735
+ params: [],
736
+ returns: .ok,
737
+ handler: { _ in
738
+ DispatchQueue.main.async {
739
+ WindowTiler.distributeVisible()
740
+ }
741
+ return .object(["ok": .bool(true)])
742
+ }
743
+ ))
744
+
745
+ // ── Meta endpoint ───────────────────────────────────────
746
+
747
+ api.register(Endpoint(
748
+ method: "api.schema",
749
+ description: "Get the full API schema including all methods and models",
750
+ access: .read,
751
+ params: [],
752
+ returns: .custom("Full API schema with version, models, and methods"),
753
+ handler: { _ in
754
+ api.schema()
755
+ }
756
+ ))
757
+ }
758
+ }
759
+
760
+ // MARK: - Encoders
761
+
762
+ enum Encoders {
763
+ static func window(_ w: WindowEntry) -> JSON {
764
+ var obj: [String: JSON] = [
765
+ "wid": .int(Int(w.wid)),
766
+ "app": .string(w.app),
767
+ "pid": .int(Int(w.pid)),
768
+ "title": .string(w.title),
769
+ "frame": .object([
770
+ "x": .double(w.frame.x),
771
+ "y": .double(w.frame.y),
772
+ "w": .double(w.frame.w),
773
+ "h": .double(w.frame.h)
774
+ ]),
775
+ "spaceIds": .array(w.spaceIds.map { .int($0) }),
776
+ "isOnScreen": .bool(w.isOnScreen)
777
+ ]
778
+ if let session = w.latticesSession {
779
+ obj["latticesSession"] = .string(session)
780
+ }
781
+ return .object(obj)
782
+ }
783
+
784
+ static func session(_ s: TmuxSession) -> JSON {
785
+ .object([
786
+ "name": .string(s.name),
787
+ "windowCount": .int(s.windowCount),
788
+ "attached": .bool(s.attached),
789
+ "panes": .array(s.panes.map { pane in
790
+ .object([
791
+ "id": .string(pane.id),
792
+ "windowIndex": .int(pane.windowIndex),
793
+ "windowName": .string(pane.windowName),
794
+ "title": .string(pane.title),
795
+ "currentCommand": .string(pane.currentCommand),
796
+ "pid": .int(pane.pid),
797
+ "isActive": .bool(pane.isActive)
798
+ ])
799
+ })
800
+ ])
801
+ }
802
+
803
+ static func process(_ e: ProcessModel.Enrichment) -> JSON {
804
+ var obj: [String: JSON] = [
805
+ "pid": .int(e.process.pid),
806
+ "ppid": .int(e.process.ppid),
807
+ "command": .string(e.process.comm),
808
+ "args": .string(e.process.args),
809
+ "tty": .string(e.process.tty),
810
+ ]
811
+ if let cwd = e.process.cwd { obj["cwd"] = .string(cwd) }
812
+ if let s = e.tmuxSession { obj["tmuxSession"] = .string(s) }
813
+ if let p = e.tmuxPaneId { obj["tmuxPaneId"] = .string(p) }
814
+ if let w = e.windowId { obj["windowId"] = .int(Int(w)) }
815
+ return .object(obj)
816
+ }
817
+
818
+ static func paneChild(_ entry: ProcessEntry) -> JSON {
819
+ var obj: [String: JSON] = [
820
+ "pid": .int(entry.pid),
821
+ "command": .string(entry.comm),
822
+ "args": .string(entry.args),
823
+ ]
824
+ if let cwd = entry.cwd { obj["cwd"] = .string(cwd) }
825
+ return .object(obj)
826
+ }
827
+
828
+ static func terminalInstance(_ inst: TerminalInstance) -> JSON {
829
+ var obj: [String: JSON] = [
830
+ "tty": .string(inst.tty),
831
+ "isActiveTab": .bool(inst.isActiveTab),
832
+ "hasClaude": .bool(inst.hasClaude),
833
+ "displayName": .string(inst.displayName),
834
+ "processes": .array(inst.processes.map { entry in
835
+ var p: [String: JSON] = [
836
+ "pid": .int(entry.pid),
837
+ "ppid": .int(entry.ppid),
838
+ "command": .string(entry.comm),
839
+ "args": .string(entry.args),
840
+ "tty": .string(entry.tty),
841
+ ]
842
+ if let cwd = entry.cwd { p["cwd"] = .string(cwd) }
843
+ return .object(p)
844
+ }),
845
+ ]
846
+ if let app = inst.app { obj["app"] = .string(app.rawValue) }
847
+ if let wi = inst.windowIndex { obj["windowIndex"] = .int(wi) }
848
+ if let ti = inst.tabIndex { obj["tabIndex"] = .int(ti) }
849
+ if let title = inst.tabTitle { obj["tabTitle"] = .string(title) }
850
+ if let sid = inst.terminalSessionId { obj["terminalSessionId"] = .string(sid) }
851
+ if let pid = inst.shellPid { obj["shellPid"] = .int(pid) }
852
+ if let cwd = inst.cwd { obj["cwd"] = .string(cwd) }
853
+ if let s = inst.tmuxSession { obj["tmuxSession"] = .string(s) }
854
+ if let p = inst.tmuxPaneId { obj["tmuxPaneId"] = .string(p) }
855
+ if let w = inst.windowId { obj["windowId"] = .int(Int(w)) }
856
+ if let t = inst.windowTitle { obj["windowTitle"] = .string(t) }
857
+ return .object(obj)
858
+ }
859
+
860
+ static func enrichedSession(_ s: TmuxSession) -> JSON {
861
+ let pm = ProcessModel.shared
862
+ return .object([
863
+ "name": .string(s.name),
864
+ "windowCount": .int(s.windowCount),
865
+ "attached": .bool(s.attached),
866
+ "panes": .array(s.panes.map { pane in
867
+ let children = pm.interestingDescendants(of: pane.pid)
868
+ var obj: [String: JSON] = [
869
+ "id": .string(pane.id),
870
+ "windowIndex": .int(pane.windowIndex),
871
+ "windowName": .string(pane.windowName),
872
+ "title": .string(pane.title),
873
+ "currentCommand": .string(pane.currentCommand),
874
+ "pid": .int(pane.pid),
875
+ "isActive": .bool(pane.isActive),
876
+ ]
877
+ if !children.isEmpty {
878
+ obj["children"] = .array(children.map { Encoders.paneChild($0) })
879
+ }
880
+ return .object(obj)
881
+ })
882
+ ])
883
+ }
884
+
885
+ static func project(_ p: Project) -> JSON {
886
+ var obj: [String: JSON] = [
887
+ "path": .string(p.path),
888
+ "name": .string(p.name),
889
+ "sessionName": .string(p.sessionName),
890
+ "isRunning": .bool(p.isRunning),
891
+ "hasConfig": .bool(p.hasConfig),
892
+ "paneCount": .int(p.paneCount),
893
+ "paneNames": .array(p.paneNames.map { .string($0) })
894
+ ]
895
+ if let cmd = p.devCommand { obj["devCommand"] = .string(cmd) }
896
+ if let pm = p.packageManager { obj["packageManager"] = .string(pm) }
897
+ return .object(obj)
898
+ }
899
+ }
900
+
901
+ // MARK: - Errors
902
+
903
+ enum RouterError: LocalizedError {
904
+ case unknownMethod(String)
905
+ case missingParam(String)
906
+ case notFound(String)
907
+
908
+ var errorDescription: String? {
909
+ switch self {
910
+ case .unknownMethod(let m): return "Unknown method: \(m)"
911
+ case .missingParam(let p): return "Missing parameter: \(p)"
912
+ case .notFound(let what): return "Not found: \(what)"
913
+ }
914
+ }
915
+ }