@chroxy/server 0.10.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 (275) hide show
  1. package/CONFIG.md +695 -0
  2. package/README.md +105 -0
  3. package/hooks/permission-hook.sh +285 -0
  4. package/package.json +69 -0
  5. package/scripts/fix-node-pty-helper.js +44 -0
  6. package/sidecar/Dockerfile +40 -0
  7. package/sidecar/PROTOCOL.md +691 -0
  8. package/sidecar/agent.js +1290 -0
  9. package/sidecar/package-lock.json +43 -0
  10. package/sidecar/package.json +17 -0
  11. package/src/activity-registry.js +491 -0
  12. package/src/anthropic-compatible-config.js +534 -0
  13. package/src/anthropic-compatible-session.js +579 -0
  14. package/src/anthropic-openai-shim.js +109 -0
  15. package/src/anthropic-openai-translate.js +377 -0
  16. package/src/auth-probes.js +296 -0
  17. package/src/background-shell-tracker.js +320 -0
  18. package/src/background-shells.js +125 -0
  19. package/src/base-session.js +1518 -0
  20. package/src/billing-budget.js +191 -0
  21. package/src/billing-canary-monitor.js +203 -0
  22. package/src/billing-class.js +149 -0
  23. package/src/bind-host.js +82 -0
  24. package/src/built-in-tools/bash-exec.js +167 -0
  25. package/src/built-in-tools/file-ops.js +198 -0
  26. package/src/built-in-tools/tool-transforms.js +179 -0
  27. package/src/builtin-commands.js +107 -0
  28. package/src/byok-compose-state-shared.js +31 -0
  29. package/src/byok-compose-state.js +234 -0
  30. package/src/byok-credentials.js +127 -0
  31. package/src/byok-event-translator.js +136 -0
  32. package/src/byok-mcp-client.js +404 -0
  33. package/src/byok-mcp-config.js +159 -0
  34. package/src/byok-mcp-fleet.js +214 -0
  35. package/src/byok-mcp-trust.js +175 -0
  36. package/src/byok-session.js +2019 -0
  37. package/src/byok-subagent-profiles.js +101 -0
  38. package/src/byok-tool-executor.js +813 -0
  39. package/src/byok-tools.js +271 -0
  40. package/src/channels/PACKAGING.md +181 -0
  41. package/src/channels/README.md +99 -0
  42. package/src/channels/chroxy-channel-server.js +248 -0
  43. package/src/checkpoint-manager.js +515 -0
  44. package/src/child-stream-guard.js +38 -0
  45. package/src/claude-channel-session.js +185 -0
  46. package/src/claude-model-catalog.js +266 -0
  47. package/src/claude-stream-parser.js +106 -0
  48. package/src/claude-tui/form-driver.js +874 -0
  49. package/src/claude-tui/pty-driver.js +520 -0
  50. package/src/claude-tui/tested-cli-version.js +22 -0
  51. package/src/claude-tui-attachments.js +342 -0
  52. package/src/claude-tui-session.js +4029 -0
  53. package/src/cli/config-cmd.js +34 -0
  54. package/src/cli/credentials-cmd.js +59 -0
  55. package/src/cli/deploy-cmd.js +167 -0
  56. package/src/cli/doctor-cmd.js +52 -0
  57. package/src/cli/identity-cmd.js +82 -0
  58. package/src/cli/init-cmd.js +209 -0
  59. package/src/cli/pages-cmd.js +167 -0
  60. package/src/cli/pair-code-cmd.js +108 -0
  61. package/src/cli/pair-discord-cmd.js +100 -0
  62. package/src/cli/providers-cmd.js +168 -0
  63. package/src/cli/server-cmd.js +94 -0
  64. package/src/cli/service-cmd.js +237 -0
  65. package/src/cli/session-cmd.js +143 -0
  66. package/src/cli/shared.js +194 -0
  67. package/src/cli/shell-cmd.js +130 -0
  68. package/src/cli/status-cmd.js +204 -0
  69. package/src/cli/tunnel-cmd.js +101 -0
  70. package/src/cli/update-cmd.js +45 -0
  71. package/src/cli/worktree-gc-cmd.js +195 -0
  72. package/src/cli-session.js +1820 -0
  73. package/src/cli.js +60 -0
  74. package/src/codex-app-server-client.js +156 -0
  75. package/src/codex-app-server-session.js +572 -0
  76. package/src/codex-session.js +604 -0
  77. package/src/config.js +1757 -0
  78. package/src/connection-info.js +42 -0
  79. package/src/connection-locality.js +55 -0
  80. package/src/content-blocks.js +42 -0
  81. package/src/control-room/byok-pool.js +130 -0
  82. package/src/control-room/constants.js +26 -0
  83. package/src/control-room/containers.js +258 -0
  84. package/src/control-room/emulators.js +279 -0
  85. package/src/control-room/handler-factory.js +142 -0
  86. package/src/control-room/host-prune.js +387 -0
  87. package/src/control-room/integrations.js +929 -0
  88. package/src/control-room/repo-runtime-config.js +239 -0
  89. package/src/control-room/repo-set.js +162 -0
  90. package/src/control-room/runners.js +479 -0
  91. package/src/control-room/simulators.js +223 -0
  92. package/src/control-room/skills-inventory.js +303 -0
  93. package/src/control-room/survey.js +685 -0
  94. package/src/control-room/wsl.js +182 -0
  95. package/src/conversation-scanner.js +270 -0
  96. package/src/conversation-scope.js +52 -0
  97. package/src/conversation-search.js +216 -0
  98. package/src/cost-budget-manager.js +190 -0
  99. package/src/credential-cipher.js +179 -0
  100. package/src/credential-store.js +786 -0
  101. package/src/credential-test.js +145 -0
  102. package/src/credentials-file.js +58 -0
  103. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
  104. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
  105. package/src/dashboard-next/dist/index.html +13 -0
  106. package/src/deepseek-credentials.js +58 -0
  107. package/src/deepseek-session.js +192 -0
  108. package/src/detect-thinking-keyword.js +67 -0
  109. package/src/dev-preview.js +227 -0
  110. package/src/devcontainer-config.js +269 -0
  111. package/src/device-preferences.js +267 -0
  112. package/src/diagnostics.js +187 -0
  113. package/src/diff-parser.js +157 -0
  114. package/src/discord-credentials.js +188 -0
  115. package/src/discord-pair-delivery.js +113 -0
  116. package/src/docker-byok-pool-stats.js +221 -0
  117. package/src/docker-byok-pool.js +841 -0
  118. package/src/docker-byok-session.js +2172 -0
  119. package/src/docker-image-allowlist.js +99 -0
  120. package/src/docker-sdk-session.js +396 -0
  121. package/src/docker-session.js +382 -0
  122. package/src/doctor-billing.js +179 -0
  123. package/src/doctor.js +667 -0
  124. package/src/duration.js +77 -0
  125. package/src/environment-manager.js +753 -0
  126. package/src/environment-statuses.js +20 -0
  127. package/src/environments/backends/docker.js +931 -0
  128. package/src/environments/backends/k8s.js +3030 -0
  129. package/src/environments/backends/rancher.js +326 -0
  130. package/src/environments/backends/types.js +332 -0
  131. package/src/event-ingest.js +546 -0
  132. package/src/event-normalizer.js +1083 -0
  133. package/src/external-session-registry.js +0 -0
  134. package/src/file-store.js +52 -0
  135. package/src/gemini-session.js +498 -0
  136. package/src/get-public-ip.js +52 -0
  137. package/src/git.js +15 -0
  138. package/src/github-webhook.js +256 -0
  139. package/src/handler-utils.js +663 -0
  140. package/src/handlers/checkpoint-handlers.js +202 -0
  141. package/src/handlers/control-room-handlers.js +1945 -0
  142. package/src/handlers/conversation-handlers.js +201 -0
  143. package/src/handlers/credential-handlers.js +247 -0
  144. package/src/handlers/evaluator-handlers.js +94 -0
  145. package/src/handlers/feature-handlers.js +332 -0
  146. package/src/handlers/file-handlers.js +142 -0
  147. package/src/handlers/ide-handlers.js +238 -0
  148. package/src/handlers/input-handlers.js +1048 -0
  149. package/src/handlers/pairing-handlers.js +94 -0
  150. package/src/handlers/repo-handlers.js +295 -0
  151. package/src/handlers/session-handlers.js +660 -0
  152. package/src/handlers/settings-handlers.js +818 -0
  153. package/src/handlers/skills-handlers.js +682 -0
  154. package/src/handlers/summarize-handlers.js +172 -0
  155. package/src/handlers/token-handlers.js +57 -0
  156. package/src/http-oversize.js +51 -0
  157. package/src/http-routes.js +1158 -0
  158. package/src/ide/search.js +268 -0
  159. package/src/ide/symbols.js +423 -0
  160. package/src/ip-utils.js +85 -0
  161. package/src/json-state-file.js +169 -0
  162. package/src/jsonl-reader.js +187 -0
  163. package/src/jsonl-subprocess-session.js +441 -0
  164. package/src/keychain.js +458 -0
  165. package/src/lan-ip.js +38 -0
  166. package/src/logger.js +388 -0
  167. package/src/mailbox-route.js +252 -0
  168. package/src/mcp-tools.js +46 -0
  169. package/src/message-transform.js +102 -0
  170. package/src/metrics.js +67 -0
  171. package/src/model-discovery.js +288 -0
  172. package/src/models.js +1426 -0
  173. package/src/notification-prefs.js +544 -0
  174. package/src/notifications/discord-billing-sink.js +323 -0
  175. package/src/notifications/discord-webhook-client.js +187 -0
  176. package/src/notifications/discord-webhook-sink.js +768 -0
  177. package/src/notifications/expo-push-sink.js +414 -0
  178. package/src/notifications/ready-body.js +177 -0
  179. package/src/notifications/sink-registry.js +98 -0
  180. package/src/notifications/sink.js +82 -0
  181. package/src/ollama-session.js +221 -0
  182. package/src/ollama-tags.js +238 -0
  183. package/src/openai-compatible-session.js +118 -0
  184. package/src/pages-store.js +255 -0
  185. package/src/pairing.js +836 -0
  186. package/src/path-hash-trust-ledger.js +311 -0
  187. package/src/per-session-settings.js +366 -0
  188. package/src/permission-audit.js +120 -0
  189. package/src/permission-hook.js +257 -0
  190. package/src/permission-manager.js +829 -0
  191. package/src/permission-resolver.js +144 -0
  192. package/src/platform.js +139 -0
  193. package/src/prompt-evaluator.js +386 -0
  194. package/src/providers.js +436 -0
  195. package/src/push.js +565 -0
  196. package/src/rate-limiter.js +433 -0
  197. package/src/redaction.js +206 -0
  198. package/src/sdk-session.js +1773 -0
  199. package/src/semver.js +92 -0
  200. package/src/server-cli/push-notification-handler.js +240 -0
  201. package/src/server-cli/server-orchestrator.js +168 -0
  202. package/src/server-cli/startup-display.js +146 -0
  203. package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
  204. package/src/server-cli-child.js +207 -0
  205. package/src/server-cli.js +1223 -0
  206. package/src/server-identity.js +383 -0
  207. package/src/service.js +835 -0
  208. package/src/session-context.js +49 -0
  209. package/src/session-lock.js +60 -0
  210. package/src/session-manager.js +3257 -0
  211. package/src/session-message-history.js +511 -0
  212. package/src/session-preset-trust.js +78 -0
  213. package/src/session-preset.js +458 -0
  214. package/src/session-state-persistence.js +307 -0
  215. package/src/session-timeout-manager.js +166 -0
  216. package/src/session-token-store.js +83 -0
  217. package/src/shell-approval-info.js +45 -0
  218. package/src/shell-approval-store.js +163 -0
  219. package/src/shell-audit.js +63 -0
  220. package/src/skills-budget.js +181 -0
  221. package/src/skills-content-validator.js +106 -0
  222. package/src/skills-frontmatter.js +422 -0
  223. package/src/skills-loader.js +1893 -0
  224. package/src/skills-manager.js +256 -0
  225. package/src/skills-trust.js +532 -0
  226. package/src/skills-usage.js +335 -0
  227. package/src/snapshots-store.js +345 -0
  228. package/src/ssrf-guard.js +130 -0
  229. package/src/subagent-counter.js +149 -0
  230. package/src/summarize-session.js +268 -0
  231. package/src/supervisor.js +929 -0
  232. package/src/test-client.js +131 -0
  233. package/src/token-compare.js +28 -0
  234. package/src/token-manager.js +220 -0
  235. package/src/tool-result.js +87 -0
  236. package/src/transcript-tasks.js +334 -0
  237. package/src/tunnel/base.js +294 -0
  238. package/src/tunnel/cloudflare.js +281 -0
  239. package/src/tunnel/index.js +54 -0
  240. package/src/tunnel-check.js +84 -0
  241. package/src/turn-tracker.js +0 -0
  242. package/src/user-shell-registry.js +218 -0
  243. package/src/user-shell-session.js +411 -0
  244. package/src/utils/check-dependencies.js +70 -0
  245. package/src/utils/concurrency.js +24 -0
  246. package/src/utils/context-window-learn.js +148 -0
  247. package/src/utils/error-message.js +25 -0
  248. package/src/utils/format-bytes.js +35 -0
  249. package/src/utils/preflight.js +143 -0
  250. package/src/utils/resolve-binary.js +91 -0
  251. package/src/utils/respawn-rate-limiter.js +59 -0
  252. package/src/utils/sleep.js +58 -0
  253. package/src/utils/spawn-env.js +193 -0
  254. package/src/utils/validation-patterns.js +23 -0
  255. package/src/utils/win-spawn.js +98 -0
  256. package/src/version-check.js +16 -0
  257. package/src/web-task-manager.js +383 -0
  258. package/src/worktree-gc.js +418 -0
  259. package/src/worktree-reaper.js +168 -0
  260. package/src/ws-auth.js +645 -0
  261. package/src/ws-broadcaster.js +385 -0
  262. package/src/ws-client-manager.js +476 -0
  263. package/src/ws-client-sender.js +115 -0
  264. package/src/ws-file-ops/browser.js +594 -0
  265. package/src/ws-file-ops/common.js +163 -0
  266. package/src/ws-file-ops/git.js +298 -0
  267. package/src/ws-file-ops/index.js +52 -0
  268. package/src/ws-file-ops/reader.js +595 -0
  269. package/src/ws-forwarding.js +543 -0
  270. package/src/ws-handler-context.js +196 -0
  271. package/src/ws-history.js +1251 -0
  272. package/src/ws-message-handlers.js +165 -0
  273. package/src/ws-permissions.js +676 -0
  274. package/src/ws-schemas.js +119 -0
  275. package/src/ws-server.js +2866 -0
@@ -0,0 +1,479 @@
1
+ /**
2
+ * Control Room — self-hosted runner survey (#5253).
3
+ *
4
+ * Sibling to the Host/Repo Status survey (survey.js). Where that one classifies
5
+ * git repos, this one classifies the GitHub Actions **self-hosted runners**
6
+ * installed on the host: it scans a runner-install root (default
7
+ * `~/github-runners`), parses each install's `.runner` (repo URL + agent name)
8
+ * and `.service` (service label), probes the platform service manager
9
+ * (launchd on macOS, systemd on Linux) for the runner's running/PID/last-exit
10
+ * state, and — when enabled — enriches each with GitHub's view
11
+ * (`gh api .../actions/runners`: online/offline, busy, labels, os). Runners are
12
+ * grouped by the GitHub target (repo or org) they register against.
13
+ *
14
+ * The result conforms to `ServerRunnerStatusSnapshotSchema` from
15
+ * `@chroxy/protocol` (minus the `type` field, which the WS handler adds), the
16
+ * same contract shape the host survey follows.
17
+ *
18
+ * Every external interaction is injectable so tests never touch real fs / exec
19
+ * / the user's home dir:
20
+ * - `_readdir(dir, { withFileTypes: true })` — async, resolves Dirent-likes.
21
+ * - `_readFile(path, enc)` — async, resolves a string (rejects when absent).
22
+ * - `_execFile(file, args, opts)` — async, resolves `{ stdout, stderr }`
23
+ * (the promisified `child_process.execFile` shape). Rejections tolerated.
24
+ * - `_now()` — returns a `Date` (defaults to `new Date()`).
25
+ *
26
+ * Service probing dispatches on the per-install service manager parsed from each
27
+ * install's `.service` file (`launchd` vs `systemd`), not on `process.platform`,
28
+ * so no platform seam is needed — the `_execFile` seam already isolates the
29
+ * exec calls from the host.
30
+ *
31
+ * Pure parse/classify helpers are exported individually so the bulk of the
32
+ * logic is unit-tested without any orchestration.
33
+ */
34
+
35
+ import { execFile } from 'child_process'
36
+ import { promisify } from 'util'
37
+ import { readFile, readdir } from 'fs/promises'
38
+ import { join, basename } from 'path'
39
+ import { homedir } from 'os'
40
+ import { DEFAULT_CONCURRENCY, EXEC_TIMEOUT_MS } from './constants.js'
41
+
42
+ const execFileAsync = promisify(execFile)
43
+
44
+ /** Default runner-install root scanned for `.runner` installs. */
45
+ export const DEFAULT_RUNNER_ROOT = join(homedir(), 'github-runners')
46
+
47
+ /** Modest output cap for probe subprocesses (runner JSON is small). */
48
+ const EXEC_MAX_BUFFER = 8 * 1024 * 1024
49
+ /** Shared exec options for every probe. */
50
+ const EXEC_OPTS = { timeout: EXEC_TIMEOUT_MS, maxBuffer: EXEC_MAX_BUFFER }
51
+
52
+ /**
53
+ * Parse a runner install's `.runner` config (JSON). The file GitHub writes is
54
+ * UTF-8 with a BOM, which `JSON.parse` rejects — strip a leading BOM first.
55
+ *
56
+ * @param {string|null} text - raw `.runner` contents, or null when absent.
57
+ * @returns {{ agentName: string|null, gitHubUrl: string|null }|null} parsed
58
+ * identity, or null when the file is absent / unparseable / not an object.
59
+ */
60
+ export function parseRunnerConfig(text) {
61
+ if (text === null || text === undefined) return null
62
+ let parsed
63
+ try {
64
+ parsed = JSON.parse(String(text).replace(/^/, ''))
65
+ } catch {
66
+ return null
67
+ }
68
+ if (!parsed || typeof parsed !== 'object') return null
69
+ const agentName = typeof parsed.agentName === 'string' && parsed.agentName.length > 0 ? parsed.agentName : null
70
+ const gitHubUrl = typeof parsed.gitHubUrl === 'string' && parsed.gitHubUrl.length > 0 ? parsed.gitHubUrl : null
71
+ return { agentName, gitHubUrl }
72
+ }
73
+
74
+ /**
75
+ * Resolve a runner install's `.service` file into a service-manager identity.
76
+ *
77
+ * On macOS the runner writes the absolute path of its LaunchAgent plist
78
+ * (`.../actions.runner.<owner>-<repo>.<name>.plist`); the launchd label is that
79
+ * basename minus `.plist`. On Linux it writes the systemd unit name
80
+ * (`actions.runner.<owner>-<repo>.<name>.service`). A missing/empty file means
81
+ * the runner was configured but never installed as a service.
82
+ *
83
+ * @param {string|null} text - raw `.service` contents, or null when absent.
84
+ * @returns {{ manager: 'launchd'|'systemd'|'none', label: string|null }}
85
+ */
86
+ export function parseServiceIdentity(text) {
87
+ if (text === null || text === undefined) return { manager: 'none', label: null }
88
+ const trimmed = String(text).trim()
89
+ if (trimmed.length === 0) return { manager: 'none', label: null }
90
+ const base = basename(trimmed)
91
+ if (base.endsWith('.plist')) {
92
+ return { manager: 'launchd', label: base.slice(0, -'.plist'.length) }
93
+ }
94
+ if (base.endsWith('.service')) {
95
+ // systemd unit name (drop a trailing `.service` so we hold the bare unit
96
+ // stem; systemctl accepts either form).
97
+ return { manager: 'systemd', label: base.slice(0, -'.service'.length) }
98
+ }
99
+ // A bare label with no recognised extension — assume launchd (the common
100
+ // macOS case where `.service` somehow held only the label).
101
+ return { manager: 'launchd', label: base }
102
+ }
103
+
104
+ /**
105
+ * Parse `launchctl list <label>` output into a service state.
106
+ *
107
+ * The output is a plist-ish dict with lines like `\t"PID" = 1778;` and
108
+ * `\t"LastExitStatus" = 0;`. A present `PID` means the job is running; its
109
+ * absence means the job is loaded-but-stopped. `LastExitStatus` carries the
110
+ * most recent exit code (the crash signal when a stopped job exited non-zero).
111
+ *
112
+ * @param {string} stdout - raw `launchctl list <label>` output.
113
+ * @returns {{ running: boolean, pid: number|null, lastExitCode: number|null }}
114
+ */
115
+ export function parseLaunchctlList(stdout) {
116
+ const text = String(stdout == null ? '' : stdout)
117
+ const pidM = /"PID"\s*=\s*(\d+)\s*;/.exec(text)
118
+ const exitM = /"LastExitStatus"\s*=\s*(-?\d+)\s*;/.exec(text)
119
+ const pid = pidM ? Number(pidM[1]) : null
120
+ const lastExitCode = exitM ? Number(exitM[1]) : null
121
+ return { running: pid !== null && pid > 0, pid: pid !== null && pid > 0 ? pid : null, lastExitCode }
122
+ }
123
+
124
+ /**
125
+ * Parse `systemctl show <unit> --property=ActiveState,MainPID,ExecMainStatus`
126
+ * output (a `Key=Value` block) into a service state. `ActiveState=active` means
127
+ * running; `MainPID` is the worker pid (0 when not running); `ExecMainStatus`
128
+ * is the last exit code.
129
+ *
130
+ * @param {string} stdout
131
+ * @returns {{ running: boolean, pid: number|null, lastExitCode: number|null }}
132
+ */
133
+ export function parseSystemctlShow(stdout) {
134
+ const props = {}
135
+ for (const raw of String(stdout == null ? '' : stdout).split('\n')) {
136
+ const line = raw.replace(/\r$/, '')
137
+ const eq = line.indexOf('=')
138
+ if (eq <= 0) continue
139
+ props[line.slice(0, eq)] = line.slice(eq + 1)
140
+ }
141
+ const running = props.ActiveState === 'active'
142
+ const pidNum = Number(props.MainPID)
143
+ const pid = Number.isInteger(pidNum) && pidNum > 0 ? pidNum : null
144
+ const exitNum = Number(props.ExecMainStatus)
145
+ const lastExitCode = props.ExecMainStatus !== undefined && Number.isFinite(exitNum) ? exitNum : null
146
+ return { running, pid: running ? pid : null, lastExitCode }
147
+ }
148
+
149
+ /**
150
+ * Probe a runner's service-manager state, tolerating any failure (an unloaded
151
+ * service makes the probe command exit non-zero → treated as not-running).
152
+ *
153
+ * @param {Function} execFn - promisified execFile seam.
154
+ * @param {{ manager: string, label: string|null }} service
155
+ * @returns {Promise<{ running: boolean, pid: number|null, lastExitCode: number|null }>}
156
+ */
157
+ export async function probeService(execFn, service) {
158
+ const stopped = { running: false, pid: null, lastExitCode: null }
159
+ if (!service || !service.label) return stopped
160
+ try {
161
+ if (service.manager === 'launchd') {
162
+ const { stdout } = await execFn('launchctl', ['list', service.label], EXEC_OPTS)
163
+ return parseLaunchctlList(stdout)
164
+ }
165
+ if (service.manager === 'systemd') {
166
+ const { stdout } = await execFn('systemctl', [
167
+ 'show', service.label,
168
+ '--property=ActiveState', '--property=MainPID', '--property=ExecMainStatus',
169
+ ], EXEC_OPTS)
170
+ return parseSystemctlShow(stdout)
171
+ }
172
+ return stopped
173
+ } catch {
174
+ // Probe failed (service not loaded / manager unavailable) → not running.
175
+ return stopped
176
+ }
177
+ }
178
+
179
+ /**
180
+ * Parse a runner install's `gitHubUrl` into an owner/repo target.
181
+ *
182
+ * Handles repo URLs (`https://github.com/<owner>/<repo>`), org URLs
183
+ * (`https://github.com/<org>` or `https://github.com/orgs/<org>`), with or
184
+ * without a trailing slash or `.git`. Returns `repo: null` for an org target.
185
+ * Returns nulls for anything that doesn't look like a GitHub URL.
186
+ *
187
+ * @param {string|null} url
188
+ * @returns {{ owner: string|null, repo: string|null }}
189
+ */
190
+ export function parseGithubTarget(url) {
191
+ if (!url || typeof url !== 'string') return { owner: null, repo: null }
192
+ const m = /^https?:\/\/github\.com\/(.+?)\/?$/.exec(url.trim())
193
+ if (!m) return { owner: null, repo: null }
194
+ const segs = m[1].split('/').filter(Boolean)
195
+ if (segs.length === 0) return { owner: null, repo: null }
196
+ // `orgs/<org>` → org target.
197
+ if (segs[0] === 'orgs' && segs[1]) return { owner: segs[1], repo: null }
198
+ if (segs.length === 1) return { owner: segs[0], repo: null } // bare org
199
+ const repo = segs[1].replace(/\.git$/, '')
200
+ return { owner: segs[0], repo }
201
+ }
202
+
203
+ /**
204
+ * Build the GitHub runner-settings deep link for a target, or null when the
205
+ * owner is unknown. Repo targets point at the repo's runner settings; org
206
+ * targets at the org's. Shape is locked to what `RepoRunnersSchema.runnersUrl`
207
+ * accepts (it's rendered as an `<a href>`).
208
+ *
209
+ * @param {{ owner: string|null, repo: string|null }} target
210
+ * @returns {string|null}
211
+ */
212
+ export function buildRunnersUrl({ owner, repo }) {
213
+ if (!owner) return null
214
+ if (repo) return `https://github.com/${owner}/${repo}/settings/actions/runners`
215
+ return `https://github.com/organizations/${owner}/settings/actions/runners`
216
+ }
217
+
218
+ /**
219
+ * The `gh api` path that lists a target's self-hosted runners.
220
+ *
221
+ * @param {{ owner: string|null, repo: string|null }} target
222
+ * @returns {string|null}
223
+ */
224
+ export function ghRunnersApiPath({ owner, repo }) {
225
+ if (!owner) return null
226
+ return repo ? `repos/${owner}/${repo}/actions/runners` : `orgs/${owner}/actions/runners`
227
+ }
228
+
229
+ /**
230
+ * Parse `gh api .../actions/runners` JSON into a name→view map. Each value is
231
+ * GitHub's view of a runner: `{ status, busy, os, labels }`. Returns an empty
232
+ * Map on any failure (null/unparseable/unexpected shape) so the caller simply
233
+ * finds no match and leaves the GitHub fields null.
234
+ *
235
+ * @param {string|null} json
236
+ * @returns {Map<string, { status: string|null, busy: boolean|null, os: string|null, labels: string[] }>}
237
+ */
238
+ export function parseGhRunners(json) {
239
+ const out = new Map()
240
+ if (json === null || json === undefined) return out
241
+ let parsed
242
+ try {
243
+ parsed = JSON.parse(json)
244
+ } catch {
245
+ return out
246
+ }
247
+ const list = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.runners) ? parsed.runners : null
248
+ if (!list) return out
249
+ for (const r of list) {
250
+ if (!r || typeof r !== 'object' || typeof r.name !== 'string') continue
251
+ const status = r.status === 'online' || r.status === 'offline' ? r.status : null
252
+ const busy = typeof r.busy === 'boolean' ? r.busy : null
253
+ const os = typeof r.os === 'string' ? r.os : null
254
+ const labels = Array.isArray(r.labels)
255
+ ? r.labels.map(l => (typeof l === 'string' ? l : l && typeof l.name === 'string' ? l.name : null)).filter(Boolean)
256
+ : []
257
+ out.set(r.name, { status, busy, os, labels })
258
+ }
259
+ return out
260
+ }
261
+
262
+ /**
263
+ * Classify a runner into a verdict from its local service state and GitHub's
264
+ * view. See `RunnerVerdictSchema` for the bucket definitions.
265
+ *
266
+ * - no service registered → 'unregistered'
267
+ * - not running + GitHub online → 'offline' (mismatch)
268
+ * - not running (no GitHub view / offline) → 'stopped'
269
+ * - running + GitHub online + busy → 'busy'
270
+ * - running + GitHub online + not busy → 'idle'
271
+ * - running + GitHub view unavailable → 'idle' (locally healthy)
272
+ * - running + GitHub offline → 'offline' (mismatch)
273
+ *
274
+ * @param {{ manager: string, running: boolean }} service
275
+ * @param {{ status: string|null, busy: boolean|null }|null} github
276
+ * @returns {'busy'|'idle'|'offline'|'stopped'|'unregistered'}
277
+ */
278
+ export function classifyRunner(service, github) {
279
+ if (!service || service.manager === 'none' || !service.label) return 'unregistered'
280
+ const status = github ? github.status : null
281
+ if (!service.running) {
282
+ // GitHub still reporting the runner online while the local service is down
283
+ // is the inverse mismatch — surface it as 'offline', not a plain 'stopped'.
284
+ return status === 'online' ? 'offline' : 'stopped'
285
+ }
286
+ if (status === 'offline') return 'offline'
287
+ if (status === 'online') return github && github.busy ? 'busy' : 'idle'
288
+ // Running locally with no GitHub view → trust the local healthy state.
289
+ return 'idle'
290
+ }
291
+
292
+ /**
293
+ * Scan the runner root for install directories, reading each one's `.runner`
294
+ * and `.service` files. Returns one descriptor per VALID install (one whose
295
+ * `.runner` parsed and carried a gitHubUrl). Tolerates a missing root / unread
296
+ * entries.
297
+ *
298
+ * @param {object} ctx - { readdirFn, readFn, root }
299
+ * @returns {Promise<Array<{ dir: string, config: object, service: object }>>}
300
+ */
301
+ async function discoverInstalls(ctx) {
302
+ const { readdirFn, readFn, root } = ctx
303
+ let entries
304
+ try {
305
+ entries = await readdirFn(root, { withFileTypes: true })
306
+ } catch {
307
+ return []
308
+ }
309
+ const dirs = (Array.isArray(entries) ? entries : [])
310
+ .filter(e => e && typeof e.isDirectory === 'function' && e.isDirectory())
311
+ .map(e => join(root, e.name))
312
+
313
+ const installs = []
314
+ for (const dir of dirs) {
315
+ let runnerText = null
316
+ try {
317
+ runnerText = await readFn(join(dir, '.runner'), 'utf8')
318
+ } catch {
319
+ continue // not a runner install
320
+ }
321
+ const config = parseRunnerConfig(runnerText)
322
+ if (!config || !config.gitHubUrl) continue // need a target to group under
323
+
324
+ let serviceText = null
325
+ try {
326
+ serviceText = await readFn(join(dir, '.service'), 'utf8')
327
+ } catch {
328
+ serviceText = null
329
+ }
330
+ installs.push({ dir, config, service: parseServiceIdentity(serviceText) })
331
+ }
332
+ return installs
333
+ }
334
+
335
+ /**
336
+ * Run `tasks` with a concurrency cap, preserving order. (Same helper shape as
337
+ * survey.js — kept local so the modules stay independent.)
338
+ */
339
+ async function mapWithCap(tasks, cap) {
340
+ const results = new Array(tasks.length)
341
+ let cursor = 0
342
+ const limit = Math.max(1, Math.min(cap, tasks.length || 1))
343
+ async function worker() {
344
+ while (cursor < tasks.length) {
345
+ const i = cursor++
346
+ results[i] = await tasks[i]()
347
+ }
348
+ }
349
+ const workers = []
350
+ for (let i = 0; i < limit; i++) workers.push(worker())
351
+ await Promise.all(workers)
352
+ return results
353
+ }
354
+
355
+ /** Tally per-verdict + total counts across the grouped runners. */
356
+ function summarize(repos) {
357
+ const summary = { total: 0, busy: 0, idle: 0, offline: 0, stopped: 0, unregistered: 0 }
358
+ for (const group of repos) {
359
+ for (const r of group.runners) {
360
+ summary.total++
361
+ if (r.verdict in summary) summary[r.verdict]++
362
+ }
363
+ }
364
+ return summary
365
+ }
366
+
367
+ /**
368
+ * Survey the host's self-hosted runners and produce a
369
+ * `runner_status_snapshot`-shaped result (minus the `type` field).
370
+ *
371
+ * @param {object} [opts]
372
+ * @param {string} [opts.root] - runner-install root (default ~/github-runners).
373
+ * @param {boolean} [opts.includeGithub=true] - whether to enrich via `gh`.
374
+ * @param {number} [opts.concurrency]
375
+ * @param {Function} [opts._readdir] - async readdir seam.
376
+ * @param {Function} [opts._readFile] - async readFile seam.
377
+ * @param {Function} [opts._execFile] - promisified execFile seam.
378
+ * @param {Function} [opts._now] - returns a `Date`.
379
+ * @returns {Promise<{ generatedAt: string, root: string, summary: object, repos: object[] }>}
380
+ */
381
+ export async function surveyRunners(opts = {}) {
382
+ const {
383
+ root = DEFAULT_RUNNER_ROOT,
384
+ includeGithub = true,
385
+ concurrency = DEFAULT_CONCURRENCY,
386
+ _readdir = readdir,
387
+ _readFile = readFile,
388
+ _execFile = execFileAsync,
389
+ _now = () => new Date(),
390
+ } = opts
391
+
392
+ const now = _now()
393
+ const installs = await discoverInstalls({ readdirFn: _readdir, readFn: _readFile, root })
394
+
395
+ // Group installs by their GitHub target (owner/repo), preserving first-seen
396
+ // order so the table is stable.
397
+ const groups = new Map() // key -> { name, owner, repo, githubUrl, runnersUrl, installs: [] }
398
+ for (const inst of installs) {
399
+ const target = parseGithubTarget(inst.config.gitHubUrl)
400
+ const key = `${target.owner || '?'}/${target.repo || ''}`
401
+ if (!groups.has(key)) {
402
+ const name = target.repo || (target.owner ? `org:${target.owner}` : inst.config.gitHubUrl)
403
+ groups.set(key, {
404
+ name,
405
+ owner: target.owner,
406
+ repo: target.repo,
407
+ githubUrl: inst.config.gitHubUrl,
408
+ runnersUrl: buildRunnersUrl(target),
409
+ target,
410
+ installs: [],
411
+ })
412
+ }
413
+ groups.get(key).installs.push(inst)
414
+ }
415
+
416
+ const groupList = [...groups.values()]
417
+
418
+ // One survey task per group: probe each install's service (concurrently) and
419
+ // optionally make a single `gh` call for the group's GitHub view.
420
+ const tasks = groupList.map(group => async () => {
421
+ const ghPromise = includeGithub
422
+ ? (async () => {
423
+ const path = ghRunnersApiPath(group.target)
424
+ if (!path) return new Map()
425
+ try {
426
+ const { stdout } = await _execFile('gh', ['api', path], EXEC_OPTS)
427
+ return parseGhRunners(typeof stdout === 'string' ? stdout : '')
428
+ } catch {
429
+ return new Map()
430
+ }
431
+ })()
432
+ : Promise.resolve(new Map())
433
+
434
+ const [serviceStates, ghMap] = await Promise.all([
435
+ Promise.all(group.installs.map(inst => probeService(_execFile, inst.service))),
436
+ ghPromise,
437
+ ])
438
+
439
+ const runners = group.installs.map((inst, i) => {
440
+ const svc = serviceStates[i]
441
+ const service = {
442
+ manager: inst.service.manager,
443
+ label: inst.service.label,
444
+ running: svc.running,
445
+ pid: svc.pid,
446
+ lastExitCode: svc.lastExitCode,
447
+ }
448
+ const gh = inst.config.agentName ? ghMap.get(inst.config.agentName) || null : null
449
+ return {
450
+ name: inst.config.agentName || basename(inst.dir),
451
+ dir: inst.dir,
452
+ verdict: classifyRunner(service, gh),
453
+ service,
454
+ githubStatus: gh ? gh.status : null,
455
+ busy: gh ? gh.busy : null,
456
+ os: gh ? gh.os : null,
457
+ labels: gh ? gh.labels : [],
458
+ }
459
+ })
460
+
461
+ return {
462
+ name: group.name,
463
+ owner: group.owner,
464
+ repo: group.repo,
465
+ githubUrl: group.githubUrl,
466
+ runnersUrl: group.runnersUrl,
467
+ runners,
468
+ }
469
+ })
470
+
471
+ const repos = await mapWithCap(tasks, concurrency)
472
+
473
+ return {
474
+ generatedAt: now.toISOString(),
475
+ root,
476
+ summary: summarize(repos),
477
+ repos,
478
+ }
479
+ }
@@ -0,0 +1,223 @@
1
+ /**
2
+ * iOS simulator survey (#6136, epic #5530) — READ-ONLY (macOS hosts).
3
+ *
4
+ * Surfaces `xcrun simctl list devices --json` in the Control Room: each
5
+ * simulator's name / udid / state (Booted/Shutdown) / runtime / device type, plus
6
+ * a headline **"Ready for Maestro" verdict** — a booted simulator AND Metro
7
+ * (:8081) reachable AND the mock server (:9876) reachable — turning the manual
8
+ * Maestro pre-flight (CLAUDE.md "UI Verification with Maestro") into one glance.
9
+ *
10
+ * Degradation-first: off macOS / no `xcrun` → `available: false` with a `note`
11
+ * and an empty device list — a first-class state, never an error. Every external
12
+ * interaction is injectable so tests never touch real simctl / sockets:
13
+ * - `_execFile(file, args, opts)` — promisified `child_process.execFile`.
14
+ * - `_probePort(port)` — resolves true if a TCP connect to 127.0.0.1:port works.
15
+ * - `_now()` — clock.
16
+ *
17
+ * Pure parse/classify helpers are exported individually for unit tests.
18
+ */
19
+
20
+ import { execFile } from 'child_process'
21
+ import { promisify } from 'util'
22
+ import net from 'net'
23
+ import { getErrorMessage } from '../utils/error-message.js'
24
+ import { EXEC_TIMEOUT_MS } from './constants.js'
25
+
26
+ const execFileAsync = promisify(execFile)
27
+
28
+ const EXEC_MAX_BUFFER = 16 * 1024 * 1024
29
+ const EXEC_OPTS = { timeout: EXEC_TIMEOUT_MS, maxBuffer: EXEC_MAX_BUFFER }
30
+
31
+ /** Ports the Maestro pre-flight depends on (CLAUDE.md). */
32
+ export const METRO_PORT = 8081
33
+ export const MOCK_SERVER_PORT = 9876
34
+ /** Per-port reachability probe timeout. */
35
+ export const PROBE_TIMEOUT_MS = 1500
36
+
37
+ /**
38
+ * Friendly runtime name from a simctl runtime key, e.g.
39
+ * `com.apple.CoreSimulator.SimRuntime.iOS-26-1` → `iOS 26.1`. A key whose tail
40
+ * doesn't match the `OS-major[-minor[-patch]]` shape falls back to that raw tail
41
+ * (e.g. `iOS-26-1-2` → `iOS-26-1-2`); a non-string falls back to `'unknown'`.
42
+ * Never throws.
43
+ *
44
+ * @param {string} key
45
+ * @returns {string}
46
+ */
47
+ export function friendlyRuntime(key) {
48
+ if (typeof key !== 'string' || !key) return 'unknown'
49
+ const tail = key.split('.SimRuntime.').pop() || key
50
+ // "iOS-26-1" → "iOS 26.1"; "watchOS-11-0" → "watchOS 11.0".
51
+ const m = /^([A-Za-z]+)-(\d+)(?:-(\d+))?(?:-(\d+))?$/.exec(tail)
52
+ if (!m) return tail
53
+ const os = m[1]
54
+ const ver = [m[2], m[3], m[4]].filter((p) => p !== undefined).join('.')
55
+ return `${os} ${ver}`
56
+ }
57
+
58
+ /**
59
+ * Friendly device-type name, e.g.
60
+ * `com.apple.CoreSimulator.SimDeviceType.iPhone-16-Pro` → `iPhone 16 Pro`.
61
+ *
62
+ * @param {string} id
63
+ * @returns {string|null}
64
+ */
65
+ export function friendlyDeviceType(id) {
66
+ if (typeof id !== 'string' || !id) return null
67
+ const tail = id.split('.SimDeviceType.').pop() || id
68
+ return tail.replace(/-/g, ' ')
69
+ }
70
+
71
+ /**
72
+ * Parse `xcrun simctl list devices --json` output into a flat device list. The
73
+ * raw shape is `{ devices: { "<runtime key>": [ { udid, name, state,
74
+ * isAvailable, deviceTypeIdentifier } ] } }`. Unavailable devices (runtime not
75
+ * installed) are dropped. Tolerant of malformed JSON / missing fields — returns
76
+ * `[]` rather than throwing.
77
+ *
78
+ * @param {string} stdout
79
+ * @returns {Array<{udid: string, name: string, state: string, runtime: string, deviceType: string|null, isAvailable: boolean}>}
80
+ */
81
+ export function parseSimctlDevices(stdout) {
82
+ let parsed
83
+ try {
84
+ parsed = JSON.parse(stdout)
85
+ } catch {
86
+ return []
87
+ }
88
+ const byRuntime = parsed && typeof parsed === 'object' ? parsed.devices : null
89
+ if (!byRuntime || typeof byRuntime !== 'object') return []
90
+ const out = []
91
+ for (const [runtimeKey, list] of Object.entries(byRuntime)) {
92
+ if (!Array.isArray(list)) continue
93
+ for (const d of list) {
94
+ if (!d || typeof d.udid !== 'string') continue
95
+ if (d.isAvailable === false) continue
96
+ out.push({
97
+ udid: d.udid,
98
+ name: typeof d.name === 'string' ? d.name : d.udid,
99
+ state: typeof d.state === 'string' ? d.state : 'Unknown',
100
+ runtime: friendlyRuntime(runtimeKey),
101
+ deviceType: friendlyDeviceType(d.deviceTypeIdentifier),
102
+ isAvailable: d.isAvailable !== false,
103
+ })
104
+ }
105
+ }
106
+ // Booted first (operator's attention), then by name for stable output.
107
+ out.sort((a, b) => {
108
+ const ab = a.state === 'Booted' ? 0 : 1
109
+ const bb = b.state === 'Booted' ? 0 : 1
110
+ if (ab !== bb) return ab - bb
111
+ return a.name < b.name ? -1 : a.name > b.name ? 1 : 0
112
+ })
113
+ return out
114
+ }
115
+
116
+ /** #6136 slice 2: the mutating simulator actions the Control Room can run. */
117
+ export const SIMULATOR_ACTIONS = ['boot', 'shutdown']
118
+
119
+ /**
120
+ * Boot or shut down a single iOS simulator via `xcrun simctl <action> <udid>`.
121
+ * Caller (the handler) is responsible for validating `udid` against a fresh
122
+ * survey and state-gating the action — this is the raw exec, mirroring
123
+ * `runHostPrune` in host-prune.js. Returns the device's expected new state.
124
+ *
125
+ * @param {object} opts
126
+ * @param {'boot'|'shutdown'} opts.action
127
+ * @param {string} opts.udid
128
+ * @param {Function} [opts._execFile]
129
+ * @returns {Promise<'Booted'|'Shutdown'>}
130
+ */
131
+ export async function runSimulatorAction({ action, udid, _execFile = execFileAsync } = {}) {
132
+ if (!SIMULATOR_ACTIONS.includes(action)) {
133
+ throw new Error(`Unsupported simulator action: ${action || '(none)'}`)
134
+ }
135
+ if (typeof udid !== 'string' || !udid) {
136
+ throw new Error('runSimulatorAction requires a udid')
137
+ }
138
+ await _execFile('xcrun', ['simctl', action, udid], EXEC_OPTS)
139
+ return action === 'boot' ? 'Booted' : 'Shutdown'
140
+ }
141
+
142
+ /** Default TCP reachability probe for 127.0.0.1:port (no data sent). */
143
+ function defaultProbePort(port) {
144
+ return new Promise((resolve) => {
145
+ const socket = new net.Socket()
146
+ let settled = false
147
+ const done = (ok) => {
148
+ if (settled) return
149
+ settled = true
150
+ socket.destroy()
151
+ resolve(ok)
152
+ }
153
+ socket.setTimeout(PROBE_TIMEOUT_MS)
154
+ socket.once('connect', () => done(true))
155
+ socket.once('timeout', () => done(false))
156
+ socket.once('error', () => done(false))
157
+ try {
158
+ socket.connect(port, '127.0.0.1')
159
+ } catch {
160
+ done(false)
161
+ }
162
+ })
163
+ }
164
+
165
+ /**
166
+ * Survey iOS simulators + compute the "Ready for Maestro" verdict.
167
+ *
168
+ * @param {object} [opts]
169
+ * @param {Function} [opts._execFile]
170
+ * @param {(port: number) => Promise<boolean>} [opts._probePort]
171
+ * @param {() => Date} [opts._now]
172
+ * @returns {Promise<{generatedAt: string, available: boolean, note: string|null,
173
+ * devices: Array, readyForMaestro: {ready: boolean, bootedSimulator: string|null,
174
+ * metroReachable: boolean, mockServerReachable: boolean, reasons: string[]}}>}
175
+ */
176
+ export async function surveySimulators(opts = {}) {
177
+ const {
178
+ _execFile = execFileAsync,
179
+ _probePort = defaultProbePort,
180
+ _now = () => new Date(),
181
+ } = opts
182
+ const now = _now()
183
+ const emptyVerdict = { ready: false, bootedSimulator: null, metroReachable: false, mockServerReachable: false, reasons: [] }
184
+ const base = { generatedAt: now.toISOString(), available: false, note: null, devices: [], readyForMaestro: emptyVerdict }
185
+
186
+ let devices
187
+ try {
188
+ const { stdout } = await _execFile('xcrun', ['simctl', 'list', 'devices', '--json'], EXEC_OPTS)
189
+ devices = parseSimctlDevices(stdout)
190
+ } catch (err) {
191
+ // No xcrun (not macOS / no Xcode) or simctl failed — first-class "absent".
192
+ return {
193
+ ...base,
194
+ note: `iOS simulators are not available on this host (${getErrorMessage(err, 'xcrun simctl failed')}).`,
195
+ }
196
+ }
197
+
198
+ const booted = devices.find((d) => d.state === 'Booted') || null
199
+ // Probe Metro + mock-server concurrently (independent ports).
200
+ const [metroReachable, mockServerReachable] = await Promise.all([
201
+ _probePort(METRO_PORT).catch(() => false),
202
+ _probePort(MOCK_SERVER_PORT).catch(() => false),
203
+ ])
204
+
205
+ const reasons = []
206
+ if (!booted) reasons.push('No booted simulator')
207
+ if (!metroReachable) reasons.push(`Metro not reachable on :${METRO_PORT}`)
208
+ if (!mockServerReachable) reasons.push(`Mock server not reachable on :${MOCK_SERVER_PORT}`)
209
+
210
+ return {
211
+ generatedAt: now.toISOString(),
212
+ available: true,
213
+ note: null,
214
+ devices,
215
+ readyForMaestro: {
216
+ ready: Boolean(booted) && metroReachable && mockServerReachable,
217
+ bootedSimulator: booted ? booted.name : null,
218
+ metroReachable,
219
+ mockServerReachable,
220
+ reasons,
221
+ },
222
+ }
223
+ }