@arach/lattices 0.2.1 → 0.6.1

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 (143) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +144 -69
  3. package/apps/mac/Info.plist +43 -0
  4. package/apps/mac/Lattices.app/Contents/Info.plist +43 -0
  5. package/apps/mac/Lattices.app/Contents/MacOS/Lattices +0 -0
  6. package/apps/mac/Lattices.app/Contents/Resources/AppIcon.icns +0 -0
  7. package/apps/mac/Lattices.app/Contents/Resources/docs/assistant-knowledge.md +130 -0
  8. package/apps/mac/Lattices.app/Contents/Resources/tap.wav +0 -0
  9. package/apps/mac/Lattices.app/Contents/_CodeSignature/CodeResources +150 -0
  10. package/apps/mac/Lattices.entitlements +21 -0
  11. package/apps/mac/Resources/Pets/assistant-spark/pet.json +62 -0
  12. package/apps/mac/Resources/Pets/assistant-spark/spritesheet.webp +0 -0
  13. package/apps/mac/Resources/Pets/scout-ranger/pet.json +6 -0
  14. package/apps/mac/Resources/Pets/scout-ranger/spritesheet.webp +0 -0
  15. package/apps/mac/Resources/tap.wav +0 -0
  16. package/assets/AppIcon.icns +0 -0
  17. package/bin/assistant-intelligence.ts +912 -0
  18. package/bin/cli/capture.ts +252 -0
  19. package/bin/cli/daemon.ts +22 -0
  20. package/bin/cli/helpers.ts +105 -0
  21. package/bin/cli/layer.ts +178 -0
  22. package/bin/cli/runs.ts +43 -0
  23. package/bin/cli/search.ts +141 -0
  24. package/bin/cli/session.ts +32 -0
  25. package/bin/client.ts +17 -0
  26. package/bin/cua.ts +26 -0
  27. package/bin/{daemon-client.js → daemon-client.ts} +49 -30
  28. package/bin/handsoff-infer.ts +96 -0
  29. package/bin/handsoff-worker.ts +531 -0
  30. package/bin/infer.ts +424 -0
  31. package/bin/keychain.ts +75 -0
  32. package/bin/lattices-app.ts +655 -0
  33. package/bin/lattices-build +125 -0
  34. package/bin/lattices-build-env.ts +77 -0
  35. package/bin/lattices-dev +362 -0
  36. package/bin/lattices.ts +3260 -0
  37. package/bin/project-twin.ts +645 -0
  38. package/docs/agent-execution-plan.md +562 -0
  39. package/docs/agent-layer-guide.md +207 -0
  40. package/docs/agents.md +233 -0
  41. package/docs/ai-chat-ux-review.md +416 -0
  42. package/docs/api.md +1041 -47
  43. package/docs/app.md +96 -13
  44. package/docs/assistant-knowledge.md +130 -0
  45. package/docs/companion-deck.md +209 -0
  46. package/docs/component-extraction-roadmap.md +392 -0
  47. package/docs/concepts.md +13 -12
  48. package/docs/config.md +83 -10
  49. package/docs/gesture-customization-proposal.md +520 -0
  50. package/docs/handsoff-test-scenarios.md +84 -0
  51. package/docs/hyperspace-grid-snappiness.md +210 -0
  52. package/docs/layers.md +176 -28
  53. package/docs/mouse-gestures.md +244 -0
  54. package/docs/ocr.md +21 -9
  55. package/docs/overview.md +42 -23
  56. package/docs/presentation-execution-review.md +491 -0
  57. package/docs/prompts/hands-off-system.md +382 -0
  58. package/docs/prompts/hands-off-turn.md +30 -0
  59. package/docs/prompts/voice-advisor.md +31 -0
  60. package/docs/prompts/voice-fallback.md +23 -0
  61. package/docs/proposals/LAT-001-gesture-visual-customization.md +522 -0
  62. package/docs/proposals/LAT-002-shared-overlay-canvas.md +353 -0
  63. package/docs/proposals/LAT-003-menu-bar-controller-architecture.md +291 -0
  64. package/docs/proposals/LAT-004-interactive-overlay-actors.md +534 -0
  65. package/docs/proposals/LAT-005-action-runtime-product-spine.md +914 -0
  66. package/docs/proposals/LAT-006-followup-gaps.md +103 -0
  67. package/docs/proposals/LAT-006-runs-and-capture-in-lattices.md +566 -0
  68. package/docs/proposals/LAT-007-unified-app-shell.md +128 -0
  69. package/docs/quickstart.md +8 -12
  70. package/docs/reference/dewey.config.ts +74 -0
  71. package/docs/reference/install-agent.md +79 -0
  72. package/docs/release.md +172 -0
  73. package/docs/repo-structure.md +100 -0
  74. package/docs/terminal-kit.md +87 -0
  75. package/docs/tiling-reference.md +224 -0
  76. package/docs/twins.md +138 -0
  77. package/docs/voice-command-protocol.md +278 -0
  78. package/docs/voice-error-model.md +73 -0
  79. package/docs/voice.md +221 -0
  80. package/package.json +69 -16
  81. package/packages/npm/sdk/cua.d.mts +1 -0
  82. package/packages/npm/sdk/cua.d.ts +188 -0
  83. package/packages/npm/sdk/cua.mjs +376 -0
  84. package/app/Lattices.app/Contents/Info.plist +0 -24
  85. package/app/Package.swift +0 -13
  86. package/app/Sources/ActionRow.swift +0 -61
  87. package/app/Sources/App.swift +0 -10
  88. package/app/Sources/AppDelegate.swift +0 -234
  89. package/app/Sources/AppShellView.swift +0 -62
  90. package/app/Sources/AppTypeClassifier.swift +0 -70
  91. package/app/Sources/AppWindowShell.swift +0 -63
  92. package/app/Sources/CheatSheetHUD.swift +0 -332
  93. package/app/Sources/CommandModeState.swift +0 -1362
  94. package/app/Sources/CommandModeView.swift +0 -1405
  95. package/app/Sources/CommandModeWindow.swift +0 -192
  96. package/app/Sources/CommandPaletteView.swift +0 -307
  97. package/app/Sources/CommandPaletteWindow.swift +0 -134
  98. package/app/Sources/DaemonProtocol.swift +0 -101
  99. package/app/Sources/DaemonServer.swift +0 -414
  100. package/app/Sources/DesktopModel.swift +0 -121
  101. package/app/Sources/DesktopModelTypes.swift +0 -71
  102. package/app/Sources/DiagnosticLog.swift +0 -271
  103. package/app/Sources/EventBus.swift +0 -30
  104. package/app/Sources/HotkeyManager.swift +0 -250
  105. package/app/Sources/HotkeyStore.swift +0 -338
  106. package/app/Sources/InventoryManager.swift +0 -35
  107. package/app/Sources/InventoryPath.swift +0 -43
  108. package/app/Sources/KeyRecorderView.swift +0 -210
  109. package/app/Sources/LatticesApi.swift +0 -1125
  110. package/app/Sources/MainView.swift +0 -467
  111. package/app/Sources/MainWindow.swift +0 -83
  112. package/app/Sources/OcrModel.swift +0 -309
  113. package/app/Sources/OcrStore.swift +0 -295
  114. package/app/Sources/OmniSearchState.swift +0 -283
  115. package/app/Sources/OmniSearchView.swift +0 -288
  116. package/app/Sources/OmniSearchWindow.swift +0 -105
  117. package/app/Sources/OrphanRow.swift +0 -129
  118. package/app/Sources/PaletteCommand.swift +0 -419
  119. package/app/Sources/PermissionChecker.swift +0 -125
  120. package/app/Sources/Preferences.swift +0 -92
  121. package/app/Sources/ProcessModel.swift +0 -199
  122. package/app/Sources/ProcessQuery.swift +0 -151
  123. package/app/Sources/Project.swift +0 -28
  124. package/app/Sources/ProjectRow.swift +0 -368
  125. package/app/Sources/ProjectScanner.swift +0 -121
  126. package/app/Sources/ScreenMapState.swift +0 -2387
  127. package/app/Sources/ScreenMapView.swift +0 -2820
  128. package/app/Sources/ScreenMapWindowController.swift +0 -89
  129. package/app/Sources/SessionManager.swift +0 -72
  130. package/app/Sources/SettingsView.swift +0 -1053
  131. package/app/Sources/SettingsWindow.swift +0 -20
  132. package/app/Sources/TabGroupRow.swift +0 -178
  133. package/app/Sources/Terminal.swift +0 -259
  134. package/app/Sources/TerminalQuery.swift +0 -156
  135. package/app/Sources/TerminalSynthesizer.swift +0 -200
  136. package/app/Sources/Theme.swift +0 -163
  137. package/app/Sources/TilePickerView.swift +0 -209
  138. package/app/Sources/TmuxModel.swift +0 -53
  139. package/app/Sources/TmuxQuery.swift +0 -81
  140. package/app/Sources/WindowTiler.swift +0 -1755
  141. package/app/Sources/WorkspaceManager.swift +0 -434
  142. package/bin/lattices-app.js +0 -221
  143. package/bin/lattices.js +0 -1418
@@ -1,1125 +0,0 @@
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: "OcrResult", fields: [
248
- Field(name: "wid", type: "int", required: true, description: "Window ID"),
249
- Field(name: "app", type: "string", required: true, description: "Application name"),
250
- Field(name: "title", type: "string", required: true, description: "Window title"),
251
- Field(name: "frame", type: "Frame", required: true, description: "Window frame"),
252
- Field(name: "fullText", type: "string", required: true, description: "All recognized text"),
253
- Field(name: "blocks", type: "[OcrBlock]", required: true, description: "Individual text blocks with position/confidence"),
254
- Field(name: "timestamp", type: "double", required: true, description: "Scan timestamp (Unix)"),
255
- ]))
256
-
257
- api.model(ApiModel(name: "OcrBlock", fields: [
258
- Field(name: "text", type: "string", required: true, description: "Recognized text"),
259
- Field(name: "confidence", type: "double", required: true, description: "Recognition confidence 0-1"),
260
- Field(name: "x", type: "double", required: true, description: "Normalized bounding box x"),
261
- Field(name: "y", type: "double", required: true, description: "Normalized bounding box y"),
262
- Field(name: "w", type: "double", required: true, description: "Normalized bounding box width"),
263
- Field(name: "h", type: "double", required: true, description: "Normalized bounding box height"),
264
- ]))
265
-
266
- api.model(ApiModel(name: "OcrSearchResult", fields: [
267
- Field(name: "id", type: "int", required: true, description: "Database row ID"),
268
- Field(name: "wid", type: "int", required: true, description: "Window ID"),
269
- Field(name: "app", type: "string", required: true, description: "Application name"),
270
- Field(name: "title", type: "string", required: true, description: "Window title"),
271
- Field(name: "frame", type: "Frame", required: true, description: "Window frame at scan time"),
272
- Field(name: "fullText", type: "string", required: true, description: "Full recognized text"),
273
- Field(name: "snippet", type: "string", required: true, description: "Highlighted snippet (FTS5)"),
274
- Field(name: "timestamp", type: "double", required: true, description: "Scan timestamp (Unix)"),
275
- ]))
276
-
277
- api.model(ApiModel(name: "DaemonStatus", fields: [
278
- Field(name: "uptime", type: "double", required: true, description: "Seconds since daemon started"),
279
- Field(name: "clientCount", type: "int", required: true, description: "Connected WebSocket clients"),
280
- Field(name: "version", type: "string", required: true, description: "Daemon version"),
281
- Field(name: "windowCount", type: "int", required: true, description: "Tracked window count"),
282
- Field(name: "tmuxSessionCount", type: "int", required: true, description: "Active tmux session count"),
283
- ]))
284
-
285
- // ── Endpoints: Read ─────────────────────────────────────
286
-
287
- api.register(Endpoint(
288
- method: "windows.list",
289
- description: "List all windows known to the system",
290
- access: .read,
291
- params: [],
292
- returns: .array(model: "Window"),
293
- handler: { _ in
294
- let entries = DesktopModel.shared.allWindows()
295
- return .array(entries.map { Encoders.window($0) })
296
- }
297
- ))
298
-
299
- api.register(Endpoint(
300
- method: "windows.get",
301
- description: "Get a single window by ID",
302
- access: .read,
303
- params: [Param(name: "wid", type: "uint32", required: true, description: "Window ID")],
304
- returns: .object(model: "Window"),
305
- handler: { params in
306
- guard let wid = params?["wid"]?.uint32Value else {
307
- throw RouterError.missingParam("wid")
308
- }
309
- guard let entry = DesktopModel.shared.windows[wid] else {
310
- throw RouterError.notFound("window \(wid)")
311
- }
312
- return Encoders.window(entry)
313
- }
314
- ))
315
-
316
- api.register(Endpoint(
317
- method: "windows.search",
318
- description: "Search windows by title, app, and OCR content",
319
- access: .read,
320
- params: [
321
- Param(name: "query", type: "string", required: true, description: "Search text"),
322
- Param(name: "ocr", type: "bool", required: false, description: "Include OCR content (default true)"),
323
- Param(name: "limit", type: "int", required: false, description: "Max results (default 50)"),
324
- ],
325
- returns: .array(model: "Window"),
326
- handler: { params in
327
- guard let query = params?["query"]?.stringValue?.lowercased(), !query.isEmpty else {
328
- throw RouterError.missingParam("query")
329
- }
330
- let includeOcr = params?["ocr"]?.boolValue ?? true
331
- let limit = params?["limit"]?.intValue ?? 50
332
- let ocrResults = OcrModel.shared.results
333
-
334
- var matches: [JSON] = []
335
- for entry in DesktopModel.shared.allWindows() {
336
- let matchesApp = entry.app.lowercased().contains(query)
337
- let matchesTitle = entry.title.lowercased().contains(query)
338
- let matchesSession = entry.latticesSession?.lowercased().contains(query) ?? false
339
- let ocrText = includeOcr ? ocrResults[entry.wid]?.fullText : nil
340
- let matchesOcrContent = ocrText?.lowercased().contains(query) ?? false
341
-
342
- if matchesApp || matchesTitle || matchesSession || matchesOcrContent {
343
- var obj = Encoders.window(entry)
344
- if matchesOcrContent, let text = ocrText,
345
- let range = text.lowercased().range(of: query) {
346
- // Extract snippet around match
347
- let half = max(0, (80 - text.distance(from: range.lowerBound, to: range.upperBound)) / 2)
348
- let start = text.index(range.lowerBound, offsetBy: -half, limitedBy: text.startIndex) ?? text.startIndex
349
- let end = text.index(range.upperBound, offsetBy: half, limitedBy: text.endIndex) ?? text.endIndex
350
- var snippet = String(text[start..<end])
351
- .replacingOccurrences(of: "\n", with: " ")
352
- .trimmingCharacters(in: .whitespaces)
353
- if start > text.startIndex { snippet = "…" + snippet }
354
- if end < text.endIndex { snippet += "…" }
355
- if case .object(var dict) = obj {
356
- dict["ocrSnippet"] = .string(snippet)
357
- dict["matchSource"] = .string("ocr")
358
- obj = .object(dict)
359
- }
360
- } else if case .object(var dict) = obj {
361
- let source = matchesTitle ? "title" : matchesApp ? "app" : "session"
362
- dict["matchSource"] = .string(source)
363
- obj = .object(dict)
364
- }
365
- matches.append(obj)
366
- if matches.count >= limit { break }
367
- }
368
- }
369
- return .array(matches)
370
- }
371
- ))
372
-
373
- api.register(Endpoint(
374
- method: "tmux.sessions",
375
- description: "List all tmux sessions with child process enrichment",
376
- access: .read,
377
- params: [],
378
- returns: .array(model: "TmuxSession"),
379
- handler: { _ in
380
- let sessions = TmuxModel.shared.sessions
381
- return .array(sessions.map { Encoders.enrichedSession($0) })
382
- }
383
- ))
384
-
385
- api.register(Endpoint(
386
- method: "tmux.inventory",
387
- description: "Get full tmux inventory including orphaned sessions",
388
- access: .read,
389
- params: [],
390
- returns: .custom("Object with 'all' and 'orphans' arrays of TmuxSession"),
391
- handler: { _ in
392
- let inv = InventoryManager.shared
393
- return .object([
394
- "all": .array(inv.allSessions.map { Encoders.session($0) }),
395
- "orphans": .array(inv.orphans.map { Encoders.session($0) })
396
- ])
397
- }
398
- ))
399
-
400
- api.register(Endpoint(
401
- method: "projects.list",
402
- description: "List all discovered projects",
403
- access: .read,
404
- params: [],
405
- returns: .array(model: "Project"),
406
- handler: { _ in
407
- let projects = ProjectScanner.shared.projects
408
- return .array(projects.map { Encoders.project($0) })
409
- }
410
- ))
411
-
412
- api.register(Endpoint(
413
- method: "spaces.list",
414
- description: "List all displays and their spaces",
415
- access: .read,
416
- params: [],
417
- returns: .array(model: "Display"),
418
- handler: { _ in
419
- let displays = WindowTiler.getDisplaySpaces()
420
- return .array(displays.map { display in
421
- .object([
422
- "displayIndex": .int(display.displayIndex),
423
- "displayId": .string(display.displayId),
424
- "currentSpaceId": .int(display.currentSpaceId),
425
- "spaces": .array(display.spaces.map { space in
426
- .object([
427
- "id": .int(space.id),
428
- "index": .int(space.index),
429
- "display": .int(space.display),
430
- "isCurrent": .bool(space.isCurrent)
431
- ])
432
- })
433
- ])
434
- })
435
- }
436
- ))
437
-
438
- api.register(Endpoint(
439
- method: "layers.list",
440
- description: "List all workspace layers and the active index",
441
- access: .read,
442
- params: [],
443
- returns: .custom("Object with 'layers' array of Layer and 'active' index"),
444
- handler: { _ in
445
- let wm = WorkspaceManager.shared
446
- guard let config = wm.config, let layers = config.layers else {
447
- return .object([
448
- "layers": .array([]),
449
- "active": .int(0)
450
- ])
451
- }
452
- return .object([
453
- "layers": .array(layers.enumerated().map { i, layer in
454
- .object([
455
- "id": .string(layer.id),
456
- "label": .string(layer.label),
457
- "index": .int(i),
458
- "projectCount": .int(layer.projects.count)
459
- ])
460
- }),
461
- "active": .int(wm.activeLayerIndex)
462
- ])
463
- }
464
- ))
465
-
466
- api.register(Endpoint(
467
- method: "daemon.status",
468
- description: "Get daemon status including uptime and counts",
469
- access: .read,
470
- params: [],
471
- returns: .object(model: "DaemonStatus"),
472
- handler: { _ in
473
- let uptime = Date().timeIntervalSince(api.startTime)
474
- return .object([
475
- "uptime": .double(uptime),
476
- "clientCount": .int(DaemonServer.shared.clientCount),
477
- "version": .string("1.0.0"),
478
- "windowCount": .int(DesktopModel.shared.windows.count),
479
- "tmuxSessionCount": .int(TmuxModel.shared.sessions.count)
480
- ])
481
- }
482
- ))
483
-
484
- api.register(Endpoint(
485
- method: "processes.list",
486
- description: "List interesting developer processes with tmux/window linkage",
487
- access: .read,
488
- params: [Param(name: "command", type: "string", required: false, description: "Filter by command name (e.g. claude)")],
489
- returns: .array(model: "Process"),
490
- handler: { params in
491
- let pm = ProcessModel.shared
492
- var enriched = pm.enrichedProcesses()
493
- if let cmd = params?["command"]?.stringValue {
494
- enriched = enriched.filter { $0.process.comm == cmd }
495
- }
496
- return .array(enriched.map { Encoders.process($0) })
497
- }
498
- ))
499
-
500
- api.register(Endpoint(
501
- method: "processes.tree",
502
- description: "Get all descendant processes of a given PID",
503
- access: .read,
504
- params: [Param(name: "pid", type: "int", required: true, description: "Parent process ID")],
505
- returns: .array(model: "Process"),
506
- handler: { params in
507
- guard let pid = params?["pid"]?.intValue else {
508
- throw RouterError.missingParam("pid")
509
- }
510
- let pm = ProcessModel.shared
511
- let descendants = pm.descendants(of: pid)
512
- return .array(descendants.map { entry in
513
- let enrichment = pm.enrich(entry)
514
- return Encoders.process(enrichment)
515
- })
516
- }
517
- ))
518
-
519
- api.register(Endpoint(
520
- method: "terminals.list",
521
- description: "List all synthesized terminal instances (unified TTY view)",
522
- access: .read,
523
- params: [
524
- Param(name: "refresh", type: "bool", required: false, description: "Force-refresh terminal tab cache before synthesizing"),
525
- ],
526
- returns: .array(model: "TerminalInstance"),
527
- handler: { params in
528
- let pm = ProcessModel.shared
529
- if params?["refresh"]?.boolValue == true {
530
- pm.refreshTerminalTabs()
531
- }
532
- let instances = pm.synthesizeTerminals()
533
- return .array(instances.map { Encoders.terminalInstance($0) })
534
- }
535
- ))
536
-
537
- api.register(Endpoint(
538
- method: "terminals.search",
539
- description: "Search terminal instances by command, cwd, app, session, or hasClaude",
540
- access: .read,
541
- params: [
542
- Param(name: "command", type: "string", required: false, description: "Filter by command name substring"),
543
- Param(name: "cwd", type: "string", required: false, description: "Filter by working directory substring"),
544
- Param(name: "app", type: "string", required: false, description: "Filter by terminal app name"),
545
- Param(name: "session", type: "string", required: false, description: "Filter by tmux session name"),
546
- Param(name: "hasClaude", type: "bool", required: false, description: "Filter to only Claude-running TTYs"),
547
- ],
548
- returns: .array(model: "TerminalInstance"),
549
- handler: { params in
550
- var instances = ProcessModel.shared.synthesizeTerminals()
551
-
552
- if let cmd = params?["command"]?.stringValue {
553
- instances = instances.filter { inst in
554
- inst.processes.contains { $0.comm.contains(cmd) || $0.args.contains(cmd) }
555
- }
556
- }
557
- if let cwd = params?["cwd"]?.stringValue {
558
- instances = instances.filter { inst in
559
- inst.cwd?.contains(cwd) == true
560
- }
561
- }
562
- if let app = params?["app"]?.stringValue {
563
- instances = instances.filter { $0.app?.rawValue == app }
564
- }
565
- if let session = params?["session"]?.stringValue {
566
- instances = instances.filter { $0.tmuxSession == session }
567
- }
568
- if let hasClaude = params?["hasClaude"]?.boolValue {
569
- instances = instances.filter { $0.hasClaude == hasClaude }
570
- }
571
-
572
- return .array(instances.map { Encoders.terminalInstance($0) })
573
- }
574
- ))
575
-
576
- // ── Endpoints: OCR ─────────────────────────────────────
577
-
578
- api.register(Endpoint(
579
- method: "ocr.snapshot",
580
- description: "Get the latest OCR scan results for all on-screen windows",
581
- access: .read,
582
- params: [],
583
- returns: .array(model: "OcrResult"),
584
- handler: { _ in
585
- let results = OcrModel.shared.results
586
- return .array(results.values.map { Encoders.ocrResult($0) })
587
- }
588
- ))
589
-
590
- api.register(Endpoint(
591
- method: "ocr.search",
592
- description: "Search OCR text across all windows (queries persistent SQLite FTS5 index by default)",
593
- access: .read,
594
- params: [
595
- Param(name: "query", type: "string", required: true, description: "Search text (FTS5 query syntax)"),
596
- Param(name: "app", type: "string", required: false, description: "Filter by app name"),
597
- Param(name: "limit", type: "int", required: false, description: "Max results (default 50)"),
598
- Param(name: "live", type: "bool", required: false, description: "Search in-memory snapshot instead of history (default false)"),
599
- ],
600
- returns: .array(model: "OcrSearchResult"),
601
- handler: { params in
602
- guard let query = params?["query"]?.stringValue else {
603
- throw RouterError.missingParam("query")
604
- }
605
- let app = params?["app"]?.stringValue
606
- let limit = params?["limit"]?.intValue ?? 50
607
- let live = params?["live"]?.boolValue ?? false
608
-
609
- if live {
610
- // In-memory snapshot search (original behavior)
611
- var results = Array(OcrModel.shared.results.values)
612
- let q = query.lowercased()
613
- results = results.filter { $0.fullText.lowercased().contains(q) }
614
- if let app { results = results.filter { $0.app == app } }
615
- return .array(results.prefix(limit).map { Encoders.ocrResult($0) })
616
- }
617
-
618
- // Persistent FTS5 search
619
- let results = OcrStore.shared.search(query: query, app: app, limit: limit)
620
- return .array(results.map { Encoders.ocrSearchResult($0) })
621
- }
622
- ))
623
-
624
- api.register(Endpoint(
625
- method: "ocr.history",
626
- description: "Get OCR content timeline for a specific window",
627
- access: .read,
628
- params: [
629
- Param(name: "wid", type: "uint32", required: true, description: "Window ID"),
630
- Param(name: "limit", type: "int", required: false, description: "Max results (default 50)"),
631
- ],
632
- returns: .array(model: "OcrSearchResult"),
633
- handler: { params in
634
- guard let wid = params?["wid"]?.uint32Value else {
635
- throw RouterError.missingParam("wid")
636
- }
637
- let limit = params?["limit"]?.intValue ?? 50
638
- let results = OcrStore.shared.history(wid: wid, limit: limit)
639
- return .array(results.map { Encoders.ocrSearchResult($0) })
640
- }
641
- ))
642
-
643
- api.register(Endpoint(
644
- method: "ocr.scan",
645
- description: "Trigger an immediate OCR scan",
646
- access: .mutate,
647
- params: [],
648
- returns: .ok,
649
- handler: { _ in
650
- OcrModel.shared.scan()
651
- return .object(["ok": .bool(true)])
652
- }
653
- ))
654
-
655
- // ── Endpoints: Mutations ────────────────────────────────
656
-
657
- api.register(Endpoint(
658
- method: "window.tile",
659
- description: "Tile a session's terminal window to a position",
660
- access: .mutate,
661
- params: [
662
- Param(name: "session", type: "string", required: true, description: "Tmux session name"),
663
- Param(name: "position", type: "string", required: true,
664
- description: "Tile position (\(TilePosition.allCases.map(\.rawValue).joined(separator: ", ")))"),
665
- ],
666
- returns: .ok,
667
- handler: { params in
668
- guard let session = params?["session"]?.stringValue else {
669
- throw RouterError.missingParam("session")
670
- }
671
- guard let posStr = params?["position"]?.stringValue,
672
- let position = TilePosition(rawValue: posStr) else {
673
- throw RouterError.missingParam("position (valid: \(TilePosition.allCases.map(\.rawValue).joined(separator: ", ")))")
674
- }
675
- let terminal = Preferences.shared.terminal
676
- DispatchQueue.main.async {
677
- WindowTiler.tile(session: session, terminal: terminal, to: position)
678
- }
679
- return .object(["ok": .bool(true)])
680
- }
681
- ))
682
-
683
- api.register(Endpoint(
684
- method: "window.focus",
685
- description: "Focus a window by wid or session name",
686
- access: .mutate,
687
- params: [
688
- Param(name: "wid", type: "uint32", required: false, description: "Window ID (takes priority)"),
689
- Param(name: "session", type: "string", required: false, description: "Tmux session name (fallback)"),
690
- ],
691
- returns: .ok,
692
- handler: { params in
693
- if let wid = params?["wid"]?.uint32Value {
694
- guard let entry = DesktopModel.shared.windows[wid] else {
695
- throw RouterError.notFound("window \(wid)")
696
- }
697
- DispatchQueue.main.async {
698
- WindowTiler.focusWindow(wid: wid, pid: entry.pid)
699
- }
700
- return .object(["ok": .bool(true), "wid": .int(Int(wid)), "app": .string(entry.app)])
701
- }
702
- guard let session = params?["session"]?.stringValue else {
703
- throw RouterError.missingParam("session or wid")
704
- }
705
- let terminal = Preferences.shared.terminal
706
- DispatchQueue.main.async {
707
- WindowTiler.navigateToWindow(session: session, terminal: terminal)
708
- }
709
- return .object(["ok": .bool(true)])
710
- }
711
- ))
712
-
713
- api.register(Endpoint(
714
- method: "window.move",
715
- description: "Move a session's window to a different space",
716
- access: .mutate,
717
- params: [
718
- Param(name: "session", type: "string", required: true, description: "Tmux session name"),
719
- Param(name: "spaceId", type: "int", required: true, description: "Target space ID"),
720
- ],
721
- returns: .ok,
722
- handler: { params in
723
- guard let session = params?["session"]?.stringValue else {
724
- throw RouterError.missingParam("session")
725
- }
726
- guard let spaceId = params?["spaceId"]?.intValue else {
727
- throw RouterError.missingParam("spaceId")
728
- }
729
- let terminal = Preferences.shared.terminal
730
- DispatchQueue.main.async {
731
- _ = WindowTiler.moveWindowToSpace(session: session, terminal: terminal, spaceId: spaceId)
732
- }
733
- return .object(["ok": .bool(true)])
734
- }
735
- ))
736
-
737
- api.register(Endpoint(
738
- method: "session.launch",
739
- description: "Launch a project's tmux session",
740
- access: .mutate,
741
- params: [Param(name: "path", type: "string", required: true, description: "Absolute project path")],
742
- returns: .ok,
743
- handler: { params in
744
- guard let path = params?["path"]?.stringValue else {
745
- throw RouterError.missingParam("path")
746
- }
747
- guard let project = ProjectScanner.shared.projects.first(where: { $0.path == path }) else {
748
- throw RouterError.notFound("project at \(path)")
749
- }
750
- DispatchQueue.main.async {
751
- SessionManager.launch(project: project)
752
- }
753
- return .object(["ok": .bool(true)])
754
- }
755
- ))
756
-
757
- api.register(Endpoint(
758
- method: "session.kill",
759
- description: "Kill a tmux session by name",
760
- access: .mutate,
761
- params: [Param(name: "name", type: "string", required: true, description: "Session name")],
762
- returns: .ok,
763
- handler: { params in
764
- guard let name = params?["name"]?.stringValue else {
765
- throw RouterError.missingParam("name")
766
- }
767
- SessionManager.killByName(name)
768
- return .object(["ok": .bool(true)])
769
- }
770
- ))
771
-
772
- api.register(Endpoint(
773
- method: "session.detach",
774
- description: "Detach all clients from a tmux session",
775
- access: .mutate,
776
- params: [Param(name: "name", type: "string", required: true, description: "Session name")],
777
- returns: .ok,
778
- handler: { params in
779
- guard let name = params?["name"]?.stringValue else {
780
- throw RouterError.missingParam("name")
781
- }
782
- SessionManager.detachByName(name)
783
- return .object(["ok": .bool(true)])
784
- }
785
- ))
786
-
787
- api.register(Endpoint(
788
- method: "session.sync",
789
- description: "Sync a project's tmux session panes to match config",
790
- access: .mutate,
791
- params: [Param(name: "path", type: "string", required: true, description: "Absolute project path")],
792
- returns: .ok,
793
- handler: { params in
794
- guard let path = params?["path"]?.stringValue else {
795
- throw RouterError.missingParam("path")
796
- }
797
- guard let project = ProjectScanner.shared.projects.first(where: { $0.path == path }) else {
798
- throw RouterError.notFound("project at \(path)")
799
- }
800
- SessionManager.sync(project: project)
801
- return .object(["ok": .bool(true)])
802
- }
803
- ))
804
-
805
- api.register(Endpoint(
806
- method: "session.restart",
807
- description: "Restart a project session or specific pane",
808
- access: .mutate,
809
- params: [
810
- Param(name: "path", type: "string", required: true, description: "Absolute project path"),
811
- Param(name: "pane", type: "string", required: false, description: "Specific pane name to restart"),
812
- ],
813
- returns: .ok,
814
- handler: { params in
815
- guard let path = params?["path"]?.stringValue else {
816
- throw RouterError.missingParam("path")
817
- }
818
- guard let project = ProjectScanner.shared.projects.first(where: { $0.path == path }) else {
819
- throw RouterError.notFound("project at \(path)")
820
- }
821
- let paneName = params?["pane"]?.stringValue
822
- SessionManager.restart(project: project, paneName: paneName)
823
- return .object(["ok": .bool(true)])
824
- }
825
- ))
826
-
827
- api.register(Endpoint(
828
- method: "layer.switch",
829
- description: "Switch to a workspace layer by index",
830
- access: .mutate,
831
- params: [Param(name: "index", type: "int", required: true, description: "Layer index")],
832
- returns: .ok,
833
- handler: { params in
834
- guard let index = params?["index"]?.intValue else {
835
- throw RouterError.missingParam("index")
836
- }
837
- DispatchQueue.main.async {
838
- WorkspaceManager.shared.tileLayer(index: index, launch: true)
839
- EventBus.shared.post(.layerSwitched(index: index))
840
- }
841
- return .object(["ok": .bool(true)])
842
- }
843
- ))
844
-
845
- api.register(Endpoint(
846
- method: "group.launch",
847
- description: "Launch all sessions in a project group",
848
- access: .mutate,
849
- params: [Param(name: "id", type: "string", required: true, description: "Group identifier")],
850
- returns: .ok,
851
- handler: { params in
852
- guard let groupId = params?["id"]?.stringValue else {
853
- throw RouterError.missingParam("id")
854
- }
855
- guard let group = WorkspaceManager.shared.group(byId: groupId) else {
856
- throw RouterError.notFound("group \(groupId)")
857
- }
858
- DispatchQueue.main.async {
859
- WorkspaceManager.shared.launchGroup(group)
860
- }
861
- return .object(["ok": .bool(true)])
862
- }
863
- ))
864
-
865
- api.register(Endpoint(
866
- method: "group.kill",
867
- description: "Kill all sessions in a project group",
868
- access: .mutate,
869
- params: [Param(name: "id", type: "string", required: true, description: "Group identifier")],
870
- returns: .ok,
871
- handler: { params in
872
- guard let groupId = params?["id"]?.stringValue else {
873
- throw RouterError.missingParam("id")
874
- }
875
- guard let group = WorkspaceManager.shared.group(byId: groupId) else {
876
- throw RouterError.notFound("group \(groupId)")
877
- }
878
- WorkspaceManager.shared.killGroup(group)
879
- return .object(["ok": .bool(true)])
880
- }
881
- ))
882
-
883
- api.register(Endpoint(
884
- method: "projects.scan",
885
- description: "Trigger a rescan of project directories",
886
- access: .mutate,
887
- params: [],
888
- returns: .ok,
889
- handler: { _ in
890
- DispatchQueue.main.async {
891
- ProjectScanner.shared.scan()
892
- }
893
- return .object(["ok": .bool(true)])
894
- }
895
- ))
896
-
897
- api.register(Endpoint(
898
- method: "layout.distribute",
899
- description: "Distribute visible windows evenly across the screen",
900
- access: .mutate,
901
- params: [],
902
- returns: .ok,
903
- handler: { _ in
904
- DispatchQueue.main.async {
905
- WindowTiler.distributeVisible()
906
- }
907
- return .object(["ok": .bool(true)])
908
- }
909
- ))
910
-
911
- // ── Meta endpoint ───────────────────────────────────────
912
-
913
- api.register(Endpoint(
914
- method: "api.schema",
915
- description: "Get the full API schema including all methods and models",
916
- access: .read,
917
- params: [],
918
- returns: .custom("Full API schema with version, models, and methods"),
919
- handler: { _ in
920
- api.schema()
921
- }
922
- ))
923
- }
924
- }
925
-
926
- // MARK: - Encoders
927
-
928
- enum Encoders {
929
- static func window(_ w: WindowEntry) -> JSON {
930
- var obj: [String: JSON] = [
931
- "wid": .int(Int(w.wid)),
932
- "app": .string(w.app),
933
- "pid": .int(Int(w.pid)),
934
- "title": .string(w.title),
935
- "frame": .object([
936
- "x": .double(w.frame.x),
937
- "y": .double(w.frame.y),
938
- "w": .double(w.frame.w),
939
- "h": .double(w.frame.h)
940
- ]),
941
- "spaceIds": .array(w.spaceIds.map { .int($0) }),
942
- "isOnScreen": .bool(w.isOnScreen)
943
- ]
944
- if let session = w.latticesSession {
945
- obj["latticesSession"] = .string(session)
946
- }
947
- return .object(obj)
948
- }
949
-
950
- static func session(_ s: TmuxSession) -> JSON {
951
- .object([
952
- "name": .string(s.name),
953
- "windowCount": .int(s.windowCount),
954
- "attached": .bool(s.attached),
955
- "panes": .array(s.panes.map { pane in
956
- .object([
957
- "id": .string(pane.id),
958
- "windowIndex": .int(pane.windowIndex),
959
- "windowName": .string(pane.windowName),
960
- "title": .string(pane.title),
961
- "currentCommand": .string(pane.currentCommand),
962
- "pid": .int(pane.pid),
963
- "isActive": .bool(pane.isActive)
964
- ])
965
- })
966
- ])
967
- }
968
-
969
- static func process(_ e: ProcessModel.Enrichment) -> JSON {
970
- var obj: [String: JSON] = [
971
- "pid": .int(e.process.pid),
972
- "ppid": .int(e.process.ppid),
973
- "command": .string(e.process.comm),
974
- "args": .string(e.process.args),
975
- "tty": .string(e.process.tty),
976
- ]
977
- if let cwd = e.process.cwd { obj["cwd"] = .string(cwd) }
978
- if let s = e.tmuxSession { obj["tmuxSession"] = .string(s) }
979
- if let p = e.tmuxPaneId { obj["tmuxPaneId"] = .string(p) }
980
- if let w = e.windowId { obj["windowId"] = .int(Int(w)) }
981
- return .object(obj)
982
- }
983
-
984
- static func paneChild(_ entry: ProcessEntry) -> JSON {
985
- var obj: [String: JSON] = [
986
- "pid": .int(entry.pid),
987
- "command": .string(entry.comm),
988
- "args": .string(entry.args),
989
- ]
990
- if let cwd = entry.cwd { obj["cwd"] = .string(cwd) }
991
- return .object(obj)
992
- }
993
-
994
- static func terminalInstance(_ inst: TerminalInstance) -> JSON {
995
- var obj: [String: JSON] = [
996
- "tty": .string(inst.tty),
997
- "isActiveTab": .bool(inst.isActiveTab),
998
- "hasClaude": .bool(inst.hasClaude),
999
- "displayName": .string(inst.displayName),
1000
- "processes": .array(inst.processes.map { entry in
1001
- var p: [String: JSON] = [
1002
- "pid": .int(entry.pid),
1003
- "ppid": .int(entry.ppid),
1004
- "command": .string(entry.comm),
1005
- "args": .string(entry.args),
1006
- "tty": .string(entry.tty),
1007
- ]
1008
- if let cwd = entry.cwd { p["cwd"] = .string(cwd) }
1009
- return .object(p)
1010
- }),
1011
- ]
1012
- if let app = inst.app { obj["app"] = .string(app.rawValue) }
1013
- if let wi = inst.windowIndex { obj["windowIndex"] = .int(wi) }
1014
- if let ti = inst.tabIndex { obj["tabIndex"] = .int(ti) }
1015
- if let title = inst.tabTitle { obj["tabTitle"] = .string(title) }
1016
- if let sid = inst.terminalSessionId { obj["terminalSessionId"] = .string(sid) }
1017
- if let pid = inst.shellPid { obj["shellPid"] = .int(pid) }
1018
- if let cwd = inst.cwd { obj["cwd"] = .string(cwd) }
1019
- if let s = inst.tmuxSession { obj["tmuxSession"] = .string(s) }
1020
- if let p = inst.tmuxPaneId { obj["tmuxPaneId"] = .string(p) }
1021
- if let w = inst.windowId { obj["windowId"] = .int(Int(w)) }
1022
- if let t = inst.windowTitle { obj["windowTitle"] = .string(t) }
1023
- return .object(obj)
1024
- }
1025
-
1026
- static func ocrResult(_ r: OcrWindowResult) -> JSON {
1027
- .object([
1028
- "wid": .int(Int(r.wid)),
1029
- "app": .string(r.app),
1030
- "title": .string(r.title),
1031
- "frame": .object([
1032
- "x": .double(r.frame.x),
1033
- "y": .double(r.frame.y),
1034
- "w": .double(r.frame.w),
1035
- "h": .double(r.frame.h)
1036
- ]),
1037
- "fullText": .string(r.fullText),
1038
- "blocks": .array(r.texts.map { block in
1039
- .object([
1040
- "text": .string(block.text),
1041
- "confidence": .double(Double(block.confidence)),
1042
- "x": .double(block.boundingBox.origin.x),
1043
- "y": .double(block.boundingBox.origin.y),
1044
- "w": .double(block.boundingBox.size.width),
1045
- "h": .double(block.boundingBox.size.height)
1046
- ])
1047
- }),
1048
- "timestamp": .double(r.timestamp.timeIntervalSince1970)
1049
- ])
1050
- }
1051
-
1052
- static func ocrSearchResult(_ r: OcrSearchResult) -> JSON {
1053
- .object([
1054
- "id": .int(Int(r.id)),
1055
- "wid": .int(Int(r.wid)),
1056
- "app": .string(r.app),
1057
- "title": .string(r.title),
1058
- "frame": .object([
1059
- "x": .double(r.frame.x),
1060
- "y": .double(r.frame.y),
1061
- "w": .double(r.frame.w),
1062
- "h": .double(r.frame.h)
1063
- ]),
1064
- "fullText": .string(r.fullText),
1065
- "snippet": .string(r.snippet),
1066
- "timestamp": .double(r.timestamp.timeIntervalSince1970)
1067
- ])
1068
- }
1069
-
1070
- static func enrichedSession(_ s: TmuxSession) -> JSON {
1071
- let pm = ProcessModel.shared
1072
- return .object([
1073
- "name": .string(s.name),
1074
- "windowCount": .int(s.windowCount),
1075
- "attached": .bool(s.attached),
1076
- "panes": .array(s.panes.map { pane in
1077
- let children = pm.interestingDescendants(of: pane.pid)
1078
- var obj: [String: JSON] = [
1079
- "id": .string(pane.id),
1080
- "windowIndex": .int(pane.windowIndex),
1081
- "windowName": .string(pane.windowName),
1082
- "title": .string(pane.title),
1083
- "currentCommand": .string(pane.currentCommand),
1084
- "pid": .int(pane.pid),
1085
- "isActive": .bool(pane.isActive),
1086
- ]
1087
- if !children.isEmpty {
1088
- obj["children"] = .array(children.map { Encoders.paneChild($0) })
1089
- }
1090
- return .object(obj)
1091
- })
1092
- ])
1093
- }
1094
-
1095
- static func project(_ p: Project) -> JSON {
1096
- var obj: [String: JSON] = [
1097
- "path": .string(p.path),
1098
- "name": .string(p.name),
1099
- "sessionName": .string(p.sessionName),
1100
- "isRunning": .bool(p.isRunning),
1101
- "hasConfig": .bool(p.hasConfig),
1102
- "paneCount": .int(p.paneCount),
1103
- "paneNames": .array(p.paneNames.map { .string($0) })
1104
- ]
1105
- if let cmd = p.devCommand { obj["devCommand"] = .string(cmd) }
1106
- if let pm = p.packageManager { obj["packageManager"] = .string(pm) }
1107
- return .object(obj)
1108
- }
1109
- }
1110
-
1111
- // MARK: - Errors
1112
-
1113
- enum RouterError: LocalizedError {
1114
- case unknownMethod(String)
1115
- case missingParam(String)
1116
- case notFound(String)
1117
-
1118
- var errorDescription: String? {
1119
- switch self {
1120
- case .unknownMethod(let m): return "Unknown method: \(m)"
1121
- case .missingParam(let p): return "Missing parameter: \(p)"
1122
- case .notFound(let what): return "Not found: \(what)"
1123
- }
1124
- }
1125
- }