@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.
- package/CONFIG.md +695 -0
- package/README.md +105 -0
- package/hooks/permission-hook.sh +285 -0
- package/package.json +69 -0
- package/scripts/fix-node-pty-helper.js +44 -0
- package/sidecar/Dockerfile +40 -0
- package/sidecar/PROTOCOL.md +691 -0
- package/sidecar/agent.js +1290 -0
- package/sidecar/package-lock.json +43 -0
- package/sidecar/package.json +17 -0
- package/src/activity-registry.js +491 -0
- package/src/anthropic-compatible-config.js +534 -0
- package/src/anthropic-compatible-session.js +579 -0
- package/src/anthropic-openai-shim.js +109 -0
- package/src/anthropic-openai-translate.js +377 -0
- package/src/auth-probes.js +296 -0
- package/src/background-shell-tracker.js +320 -0
- package/src/background-shells.js +125 -0
- package/src/base-session.js +1518 -0
- package/src/billing-budget.js +191 -0
- package/src/billing-canary-monitor.js +203 -0
- package/src/billing-class.js +149 -0
- package/src/bind-host.js +82 -0
- package/src/built-in-tools/bash-exec.js +167 -0
- package/src/built-in-tools/file-ops.js +198 -0
- package/src/built-in-tools/tool-transforms.js +179 -0
- package/src/builtin-commands.js +107 -0
- package/src/byok-compose-state-shared.js +31 -0
- package/src/byok-compose-state.js +234 -0
- package/src/byok-credentials.js +127 -0
- package/src/byok-event-translator.js +136 -0
- package/src/byok-mcp-client.js +404 -0
- package/src/byok-mcp-config.js +159 -0
- package/src/byok-mcp-fleet.js +214 -0
- package/src/byok-mcp-trust.js +175 -0
- package/src/byok-session.js +2019 -0
- package/src/byok-subagent-profiles.js +101 -0
- package/src/byok-tool-executor.js +813 -0
- package/src/byok-tools.js +271 -0
- package/src/channels/PACKAGING.md +181 -0
- package/src/channels/README.md +99 -0
- package/src/channels/chroxy-channel-server.js +248 -0
- package/src/checkpoint-manager.js +515 -0
- package/src/child-stream-guard.js +38 -0
- package/src/claude-channel-session.js +185 -0
- package/src/claude-model-catalog.js +266 -0
- package/src/claude-stream-parser.js +106 -0
- package/src/claude-tui/form-driver.js +874 -0
- package/src/claude-tui/pty-driver.js +520 -0
- package/src/claude-tui/tested-cli-version.js +22 -0
- package/src/claude-tui-attachments.js +342 -0
- package/src/claude-tui-session.js +4029 -0
- package/src/cli/config-cmd.js +34 -0
- package/src/cli/credentials-cmd.js +59 -0
- package/src/cli/deploy-cmd.js +167 -0
- package/src/cli/doctor-cmd.js +52 -0
- package/src/cli/identity-cmd.js +82 -0
- package/src/cli/init-cmd.js +209 -0
- package/src/cli/pages-cmd.js +167 -0
- package/src/cli/pair-code-cmd.js +108 -0
- package/src/cli/pair-discord-cmd.js +100 -0
- package/src/cli/providers-cmd.js +168 -0
- package/src/cli/server-cmd.js +94 -0
- package/src/cli/service-cmd.js +237 -0
- package/src/cli/session-cmd.js +143 -0
- package/src/cli/shared.js +194 -0
- package/src/cli/shell-cmd.js +130 -0
- package/src/cli/status-cmd.js +204 -0
- package/src/cli/tunnel-cmd.js +101 -0
- package/src/cli/update-cmd.js +45 -0
- package/src/cli/worktree-gc-cmd.js +195 -0
- package/src/cli-session.js +1820 -0
- package/src/cli.js +60 -0
- package/src/codex-app-server-client.js +156 -0
- package/src/codex-app-server-session.js +572 -0
- package/src/codex-session.js +604 -0
- package/src/config.js +1757 -0
- package/src/connection-info.js +42 -0
- package/src/connection-locality.js +55 -0
- package/src/content-blocks.js +42 -0
- package/src/control-room/byok-pool.js +130 -0
- package/src/control-room/constants.js +26 -0
- package/src/control-room/containers.js +258 -0
- package/src/control-room/emulators.js +279 -0
- package/src/control-room/handler-factory.js +142 -0
- package/src/control-room/host-prune.js +387 -0
- package/src/control-room/integrations.js +929 -0
- package/src/control-room/repo-runtime-config.js +239 -0
- package/src/control-room/repo-set.js +162 -0
- package/src/control-room/runners.js +479 -0
- package/src/control-room/simulators.js +223 -0
- package/src/control-room/skills-inventory.js +303 -0
- package/src/control-room/survey.js +685 -0
- package/src/control-room/wsl.js +182 -0
- package/src/conversation-scanner.js +270 -0
- package/src/conversation-scope.js +52 -0
- package/src/conversation-search.js +216 -0
- package/src/cost-budget-manager.js +190 -0
- package/src/credential-cipher.js +179 -0
- package/src/credential-store.js +786 -0
- package/src/credential-test.js +145 -0
- package/src/credentials-file.js +58 -0
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
- package/src/dashboard-next/dist/index.html +13 -0
- package/src/deepseek-credentials.js +58 -0
- package/src/deepseek-session.js +192 -0
- package/src/detect-thinking-keyword.js +67 -0
- package/src/dev-preview.js +227 -0
- package/src/devcontainer-config.js +269 -0
- package/src/device-preferences.js +267 -0
- package/src/diagnostics.js +187 -0
- package/src/diff-parser.js +157 -0
- package/src/discord-credentials.js +188 -0
- package/src/discord-pair-delivery.js +113 -0
- package/src/docker-byok-pool-stats.js +221 -0
- package/src/docker-byok-pool.js +841 -0
- package/src/docker-byok-session.js +2172 -0
- package/src/docker-image-allowlist.js +99 -0
- package/src/docker-sdk-session.js +396 -0
- package/src/docker-session.js +382 -0
- package/src/doctor-billing.js +179 -0
- package/src/doctor.js +667 -0
- package/src/duration.js +77 -0
- package/src/environment-manager.js +753 -0
- package/src/environment-statuses.js +20 -0
- package/src/environments/backends/docker.js +931 -0
- package/src/environments/backends/k8s.js +3030 -0
- package/src/environments/backends/rancher.js +326 -0
- package/src/environments/backends/types.js +332 -0
- package/src/event-ingest.js +546 -0
- package/src/event-normalizer.js +1083 -0
- package/src/external-session-registry.js +0 -0
- package/src/file-store.js +52 -0
- package/src/gemini-session.js +498 -0
- package/src/get-public-ip.js +52 -0
- package/src/git.js +15 -0
- package/src/github-webhook.js +256 -0
- package/src/handler-utils.js +663 -0
- package/src/handlers/checkpoint-handlers.js +202 -0
- package/src/handlers/control-room-handlers.js +1945 -0
- package/src/handlers/conversation-handlers.js +201 -0
- package/src/handlers/credential-handlers.js +247 -0
- package/src/handlers/evaluator-handlers.js +94 -0
- package/src/handlers/feature-handlers.js +332 -0
- package/src/handlers/file-handlers.js +142 -0
- package/src/handlers/ide-handlers.js +238 -0
- package/src/handlers/input-handlers.js +1048 -0
- package/src/handlers/pairing-handlers.js +94 -0
- package/src/handlers/repo-handlers.js +295 -0
- package/src/handlers/session-handlers.js +660 -0
- package/src/handlers/settings-handlers.js +818 -0
- package/src/handlers/skills-handlers.js +682 -0
- package/src/handlers/summarize-handlers.js +172 -0
- package/src/handlers/token-handlers.js +57 -0
- package/src/http-oversize.js +51 -0
- package/src/http-routes.js +1158 -0
- package/src/ide/search.js +268 -0
- package/src/ide/symbols.js +423 -0
- package/src/ip-utils.js +85 -0
- package/src/json-state-file.js +169 -0
- package/src/jsonl-reader.js +187 -0
- package/src/jsonl-subprocess-session.js +441 -0
- package/src/keychain.js +458 -0
- package/src/lan-ip.js +38 -0
- package/src/logger.js +388 -0
- package/src/mailbox-route.js +252 -0
- package/src/mcp-tools.js +46 -0
- package/src/message-transform.js +102 -0
- package/src/metrics.js +67 -0
- package/src/model-discovery.js +288 -0
- package/src/models.js +1426 -0
- package/src/notification-prefs.js +544 -0
- package/src/notifications/discord-billing-sink.js +323 -0
- package/src/notifications/discord-webhook-client.js +187 -0
- package/src/notifications/discord-webhook-sink.js +768 -0
- package/src/notifications/expo-push-sink.js +414 -0
- package/src/notifications/ready-body.js +177 -0
- package/src/notifications/sink-registry.js +98 -0
- package/src/notifications/sink.js +82 -0
- package/src/ollama-session.js +221 -0
- package/src/ollama-tags.js +238 -0
- package/src/openai-compatible-session.js +118 -0
- package/src/pages-store.js +255 -0
- package/src/pairing.js +836 -0
- package/src/path-hash-trust-ledger.js +311 -0
- package/src/per-session-settings.js +366 -0
- package/src/permission-audit.js +120 -0
- package/src/permission-hook.js +257 -0
- package/src/permission-manager.js +829 -0
- package/src/permission-resolver.js +144 -0
- package/src/platform.js +139 -0
- package/src/prompt-evaluator.js +386 -0
- package/src/providers.js +436 -0
- package/src/push.js +565 -0
- package/src/rate-limiter.js +433 -0
- package/src/redaction.js +206 -0
- package/src/sdk-session.js +1773 -0
- package/src/semver.js +92 -0
- package/src/server-cli/push-notification-handler.js +240 -0
- package/src/server-cli/server-orchestrator.js +168 -0
- package/src/server-cli/startup-display.js +146 -0
- package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
- package/src/server-cli-child.js +207 -0
- package/src/server-cli.js +1223 -0
- package/src/server-identity.js +383 -0
- package/src/service.js +835 -0
- package/src/session-context.js +49 -0
- package/src/session-lock.js +60 -0
- package/src/session-manager.js +3257 -0
- package/src/session-message-history.js +511 -0
- package/src/session-preset-trust.js +78 -0
- package/src/session-preset.js +458 -0
- package/src/session-state-persistence.js +307 -0
- package/src/session-timeout-manager.js +166 -0
- package/src/session-token-store.js +83 -0
- package/src/shell-approval-info.js +45 -0
- package/src/shell-approval-store.js +163 -0
- package/src/shell-audit.js +63 -0
- package/src/skills-budget.js +181 -0
- package/src/skills-content-validator.js +106 -0
- package/src/skills-frontmatter.js +422 -0
- package/src/skills-loader.js +1893 -0
- package/src/skills-manager.js +256 -0
- package/src/skills-trust.js +532 -0
- package/src/skills-usage.js +335 -0
- package/src/snapshots-store.js +345 -0
- package/src/ssrf-guard.js +130 -0
- package/src/subagent-counter.js +149 -0
- package/src/summarize-session.js +268 -0
- package/src/supervisor.js +929 -0
- package/src/test-client.js +131 -0
- package/src/token-compare.js +28 -0
- package/src/token-manager.js +220 -0
- package/src/tool-result.js +87 -0
- package/src/transcript-tasks.js +334 -0
- package/src/tunnel/base.js +294 -0
- package/src/tunnel/cloudflare.js +281 -0
- package/src/tunnel/index.js +54 -0
- package/src/tunnel-check.js +84 -0
- package/src/turn-tracker.js +0 -0
- package/src/user-shell-registry.js +218 -0
- package/src/user-shell-session.js +411 -0
- package/src/utils/check-dependencies.js +70 -0
- package/src/utils/concurrency.js +24 -0
- package/src/utils/context-window-learn.js +148 -0
- package/src/utils/error-message.js +25 -0
- package/src/utils/format-bytes.js +35 -0
- package/src/utils/preflight.js +143 -0
- package/src/utils/resolve-binary.js +91 -0
- package/src/utils/respawn-rate-limiter.js +59 -0
- package/src/utils/sleep.js +58 -0
- package/src/utils/spawn-env.js +193 -0
- package/src/utils/validation-patterns.js +23 -0
- package/src/utils/win-spawn.js +98 -0
- package/src/version-check.js +16 -0
- package/src/web-task-manager.js +383 -0
- package/src/worktree-gc.js +418 -0
- package/src/worktree-reaper.js +168 -0
- package/src/ws-auth.js +645 -0
- package/src/ws-broadcaster.js +385 -0
- package/src/ws-client-manager.js +476 -0
- package/src/ws-client-sender.js +115 -0
- package/src/ws-file-ops/browser.js +594 -0
- package/src/ws-file-ops/common.js +163 -0
- package/src/ws-file-ops/git.js +298 -0
- package/src/ws-file-ops/index.js +52 -0
- package/src/ws-file-ops/reader.js +595 -0
- package/src/ws-forwarding.js +543 -0
- package/src/ws-handler-context.js +196 -0
- package/src/ws-history.js +1251 -0
- package/src/ws-message-handlers.js +165 -0
- package/src/ws-permissions.js +676 -0
- package/src/ws-schemas.js +119 -0
- package/src/ws-server.js +2866 -0
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Android emulator survey + actions (#6137, epic #5530) — macOS/Linux hosts with
|
|
3
|
+
* the Android SDK. Sibling of `simulators.js`; feeds the same Control Room
|
|
4
|
+
* "Device runtimes" tab.
|
|
5
|
+
*
|
|
6
|
+
* Surfaces `emulator -list-avds` (installed AVDs) joined with `adb devices`
|
|
7
|
+
* (which are running) + a headline **"Ready for Maestro" verdict** — a running
|
|
8
|
+
* emulator AND Metro (:8081) AND the mock server (:9876) reachable. Boot starts
|
|
9
|
+
* an AVD (optionally headless `-no-window`); kill stops a running serial via
|
|
10
|
+
* `adb emu kill`.
|
|
11
|
+
*
|
|
12
|
+
* Degradation-first: no `emulator` binary (SDK absent) → `available: false` with
|
|
13
|
+
* a `note` and an empty list — a first-class state, never an error. Every
|
|
14
|
+
* external interaction is injectable so tests never touch the real SDK / sockets:
|
|
15
|
+
* - `_execFile(file, args, opts)` — promisified `child_process.execFile`.
|
|
16
|
+
* - `_spawn(file, args, opts)` — `child_process.spawn` (boot is detached).
|
|
17
|
+
* - `_probePort(port)` — TCP reachability probe.
|
|
18
|
+
* - `_now()` — clock.
|
|
19
|
+
*
|
|
20
|
+
* Pure parse/classify helpers are exported individually for unit tests.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import { execFile, spawn } from 'child_process'
|
|
24
|
+
import { promisify } from 'util'
|
|
25
|
+
import net from 'net'
|
|
26
|
+
import { getErrorMessage } from '../utils/error-message.js'
|
|
27
|
+
import { EXEC_TIMEOUT_MS } from './constants.js'
|
|
28
|
+
|
|
29
|
+
const execFileAsync = promisify(execFile)
|
|
30
|
+
|
|
31
|
+
const EXEC_MAX_BUFFER = 16 * 1024 * 1024
|
|
32
|
+
const EXEC_OPTS = { timeout: EXEC_TIMEOUT_MS, maxBuffer: EXEC_MAX_BUFFER }
|
|
33
|
+
|
|
34
|
+
/** Ports the Maestro pre-flight depends on (CLAUDE.md), shared with iOS. */
|
|
35
|
+
export const METRO_PORT = 8081
|
|
36
|
+
export const MOCK_SERVER_PORT = 9876
|
|
37
|
+
/** Per-port reachability probe timeout. */
|
|
38
|
+
export const PROBE_TIMEOUT_MS = 1500
|
|
39
|
+
|
|
40
|
+
/** #6137: the mutating emulator actions the Control Room can run. */
|
|
41
|
+
export const EMULATOR_ACTIONS = ['boot', 'kill']
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Parse `emulator -list-avds` stdout into a sorted, de-duped AVD-name list.
|
|
45
|
+
* The command prints one AVD name per line (plus occasional INFO/warning lines
|
|
46
|
+
* that we drop — real AVD names have no whitespace). Tolerant of empty/garbage
|
|
47
|
+
* output → `[]`. Never throws.
|
|
48
|
+
*
|
|
49
|
+
* @param {string} stdout
|
|
50
|
+
* @returns {string[]}
|
|
51
|
+
*/
|
|
52
|
+
export function parseAvdList(stdout) {
|
|
53
|
+
if (typeof stdout !== 'string') return []
|
|
54
|
+
const names = stdout
|
|
55
|
+
.split('\n')
|
|
56
|
+
.map((l) => l.trim())
|
|
57
|
+
// AVD names are a single token (no spaces); this drops "INFO | ..." noise.
|
|
58
|
+
.filter((l) => l.length > 0 && !/\s/.test(l))
|
|
59
|
+
return [...new Set(names)].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Parse `adb devices` stdout into emulator entries. Lines look like
|
|
64
|
+
* `emulator-5554\tdevice`; we keep `emulator-*` serials and map the adb state:
|
|
65
|
+
* `device` → `running` (usable), `offline` → `starting` (booting, not usable
|
|
66
|
+
* yet but already live — surfacing it stops the UI from booting a duplicate and
|
|
67
|
+
* lets `kill` target it). Other states / physical devices / the `adb` header
|
|
68
|
+
* are dropped. Deduped by serial (preferring `running`), sorted. Never throws.
|
|
69
|
+
*
|
|
70
|
+
* @param {string} stdout
|
|
71
|
+
* @returns {Array<{serial: string, state: 'running'|'starting'}>}
|
|
72
|
+
*/
|
|
73
|
+
export function parseAdbDevices(stdout) {
|
|
74
|
+
if (typeof stdout !== 'string') return []
|
|
75
|
+
const bySerial = new Map()
|
|
76
|
+
for (const line of stdout.split('\n')) {
|
|
77
|
+
const m = /^(emulator-\d+)\s+(\w+)/.exec(line.trim())
|
|
78
|
+
if (!m) continue
|
|
79
|
+
const state = m[2] === 'device' ? 'running' : m[2] === 'offline' ? 'starting' : null
|
|
80
|
+
if (!state) continue
|
|
81
|
+
const prev = bySerial.get(m[1])
|
|
82
|
+
// Prefer the usable 'running' state if a serial somehow appears twice.
|
|
83
|
+
if (!prev || (prev.state === 'starting' && state === 'running')) {
|
|
84
|
+
bySerial.set(m[1], { serial: m[1], state })
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return [...bySerial.values()].sort((a, b) => (a.serial < b.serial ? -1 : a.serial > b.serial ? 1 : 0))
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Default TCP reachability probe for 127.0.0.1:port (no data sent). */
|
|
91
|
+
function defaultProbePort(port) {
|
|
92
|
+
return new Promise((resolve) => {
|
|
93
|
+
const socket = new net.Socket()
|
|
94
|
+
let settled = false
|
|
95
|
+
const done = (ok) => {
|
|
96
|
+
if (settled) return
|
|
97
|
+
settled = true
|
|
98
|
+
socket.destroy()
|
|
99
|
+
resolve(ok)
|
|
100
|
+
}
|
|
101
|
+
socket.setTimeout(PROBE_TIMEOUT_MS)
|
|
102
|
+
socket.once('connect', () => done(true))
|
|
103
|
+
socket.once('timeout', () => done(false))
|
|
104
|
+
socket.once('error', () => done(false))
|
|
105
|
+
try {
|
|
106
|
+
socket.connect(port, '127.0.0.1')
|
|
107
|
+
} catch {
|
|
108
|
+
done(false)
|
|
109
|
+
}
|
|
110
|
+
})
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Resolve a running emulator serial's AVD name via `adb -s <serial> emu avd
|
|
115
|
+
* name` (best-effort — the first stdout line is the AVD name; on any failure
|
|
116
|
+
* returns null so the survey still lists the serial).
|
|
117
|
+
*/
|
|
118
|
+
async function resolveAvdName(serial, execFn) {
|
|
119
|
+
try {
|
|
120
|
+
const { stdout } = await execFn('adb', ['-s', serial, 'emu', 'avd', 'name'], EXEC_OPTS)
|
|
121
|
+
const first = String(stdout || '').split('\n').map((l) => l.trim()).find((l) => l.length > 0 && l !== 'OK')
|
|
122
|
+
return first || null
|
|
123
|
+
} catch {
|
|
124
|
+
return null
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Survey Android emulators + compute the "Ready for Maestro" verdict.
|
|
130
|
+
*
|
|
131
|
+
* @param {object} [opts]
|
|
132
|
+
* @param {Function} [opts._execFile]
|
|
133
|
+
* @param {(port: number) => Promise<boolean>} [opts._probePort]
|
|
134
|
+
* @param {() => Date} [opts._now]
|
|
135
|
+
* @returns {Promise<{generatedAt: string, available: boolean, note: string|null,
|
|
136
|
+
* devices: Array, readyForMaestro: {ready: boolean, runningDevice: string|null,
|
|
137
|
+
* metroReachable: boolean, mockServerReachable: boolean, reasons: string[]}}>}
|
|
138
|
+
*/
|
|
139
|
+
export async function surveyEmulators(opts = {}) {
|
|
140
|
+
const {
|
|
141
|
+
_execFile = execFileAsync,
|
|
142
|
+
_probePort = defaultProbePort,
|
|
143
|
+
_now = () => new Date(),
|
|
144
|
+
} = opts
|
|
145
|
+
const now = _now()
|
|
146
|
+
const emptyVerdict = { ready: false, runningDevice: null, metroReachable: false, mockServerReachable: false, reasons: [] }
|
|
147
|
+
const base = { generatedAt: now.toISOString(), available: false, note: null, devices: [], readyForMaestro: emptyVerdict }
|
|
148
|
+
|
|
149
|
+
let avds
|
|
150
|
+
try {
|
|
151
|
+
const { stdout } = await _execFile('emulator', ['-list-avds'], EXEC_OPTS)
|
|
152
|
+
avds = parseAvdList(stdout)
|
|
153
|
+
} catch (err) {
|
|
154
|
+
// No `emulator` binary (Android SDK absent) — first-class "absent".
|
|
155
|
+
return {
|
|
156
|
+
...base,
|
|
157
|
+
note: `Android emulators are not available on this host (${getErrorMessage(err, 'emulator -list-avds failed')}).`,
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// `adb devices` is best-effort: if adb is missing we still list AVDs (all
|
|
162
|
+
// stopped) rather than failing the whole survey. Each entry is {serial, state}
|
|
163
|
+
// where state is 'running' (usable) or 'starting' (booting / adb 'offline').
|
|
164
|
+
let adbRows = []
|
|
165
|
+
try {
|
|
166
|
+
const { stdout } = await _execFile('adb', ['devices'], EXEC_OPTS)
|
|
167
|
+
adbRows = parseAdbDevices(stdout)
|
|
168
|
+
} catch {
|
|
169
|
+
adbRows = []
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// Resolve each live serial's AVD name so we can fold it into the AVD list,
|
|
173
|
+
// carrying the adb state ('running' | 'starting').
|
|
174
|
+
const live = []
|
|
175
|
+
for (const row of adbRows) {
|
|
176
|
+
const avd = await resolveAvdName(row.serial, _execFile)
|
|
177
|
+
live.push({ serial: row.serial, avd, state: row.state })
|
|
178
|
+
}
|
|
179
|
+
const liveAvdNames = new Set(live.map((r) => r.avd).filter(Boolean))
|
|
180
|
+
|
|
181
|
+
const devices = [
|
|
182
|
+
// Live emulators first (operator's attention): running or starting, serial known.
|
|
183
|
+
...live.map((r) => ({ avd: r.avd, serial: r.serial, state: r.state })),
|
|
184
|
+
// Then installed-but-stopped AVDs: bootable, no serial yet.
|
|
185
|
+
...avds
|
|
186
|
+
.filter((name) => !liveAvdNames.has(name))
|
|
187
|
+
.map((name) => ({ avd: name, serial: null, state: 'stopped' })),
|
|
188
|
+
]
|
|
189
|
+
|
|
190
|
+
const [metroReachable, mockServerReachable] = await Promise.all([
|
|
191
|
+
_probePort(METRO_PORT).catch(() => false),
|
|
192
|
+
_probePort(MOCK_SERVER_PORT).catch(() => false),
|
|
193
|
+
])
|
|
194
|
+
|
|
195
|
+
// "Ready for Maestro" needs a FULLY running emulator — a booting ('starting')
|
|
196
|
+
// one isn't usable yet.
|
|
197
|
+
const fullyRunning = live.filter((r) => r.state === 'running')
|
|
198
|
+
const hasRunning = fullyRunning.length > 0
|
|
199
|
+
const reasons = []
|
|
200
|
+
if (!hasRunning) reasons.push('No running emulator')
|
|
201
|
+
if (!metroReachable) reasons.push(`Metro not reachable on :${METRO_PORT}`)
|
|
202
|
+
if (!mockServerReachable) reasons.push(`Mock server not reachable on :${MOCK_SERVER_PORT}`)
|
|
203
|
+
|
|
204
|
+
return {
|
|
205
|
+
generatedAt: now.toISOString(),
|
|
206
|
+
available: true,
|
|
207
|
+
note: null,
|
|
208
|
+
devices,
|
|
209
|
+
readyForMaestro: {
|
|
210
|
+
ready: hasRunning && metroReachable && mockServerReachable,
|
|
211
|
+
runningDevice: hasRunning ? (fullyRunning[0].avd || fullyRunning[0].serial) : null,
|
|
212
|
+
metroReachable,
|
|
213
|
+
mockServerReachable,
|
|
214
|
+
reasons,
|
|
215
|
+
},
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Boot an AVD or kill a running emulator. Caller (the handler) validates the
|
|
221
|
+
* target against a fresh survey and state-gates the action; this is the raw
|
|
222
|
+
* exec, mirroring `runSimulatorAction`.
|
|
223
|
+
*
|
|
224
|
+
* boot is a long-lived foreground process, so it is SPAWNED DETACHED (and
|
|
225
|
+
* unref'd). We AWAIT the child's `spawn` event (so an async spawn failure —
|
|
226
|
+
* ENOENT/EACCES — rejects here and surfaces as EMULATOR_ACTION_FAILED rather
|
|
227
|
+
* than crashing the server on an unhandled `error` event), then resolve with
|
|
228
|
+
* 'starting' — the next survey shows it as running. kill is a quick
|
|
229
|
+
* `adb emu kill` and returns 'killed'.
|
|
230
|
+
*
|
|
231
|
+
* @param {object} opts
|
|
232
|
+
* @param {'boot'|'kill'} opts.action
|
|
233
|
+
* @param {string} [opts.avd] AVD name (boot)
|
|
234
|
+
* @param {string} [opts.serial] running serial (kill)
|
|
235
|
+
* @param {boolean} [opts.headless] boot with `-no-window`
|
|
236
|
+
* @param {Function} [opts._execFile]
|
|
237
|
+
* @param {Function} [opts._spawn]
|
|
238
|
+
* @returns {Promise<'starting'|'killed'>}
|
|
239
|
+
*/
|
|
240
|
+
export async function runEmulatorAction({ action, avd, serial, headless = false, _execFile = execFileAsync, _spawn = spawn } = {}) {
|
|
241
|
+
if (!EMULATOR_ACTIONS.includes(action)) {
|
|
242
|
+
throw new Error(`Unsupported emulator action: ${action || '(none)'}`)
|
|
243
|
+
}
|
|
244
|
+
if (action === 'boot') {
|
|
245
|
+
if (typeof avd !== 'string' || !avd) throw new Error('runEmulatorAction boot requires an avd')
|
|
246
|
+
const args = ['-avd', avd]
|
|
247
|
+
if (headless) args.push('-no-window')
|
|
248
|
+
// Detached + unref so the emulator outlives this request; ignore stdio so
|
|
249
|
+
// the parent isn't held open by the child's pipes. Resolve on 'spawn',
|
|
250
|
+
// reject on 'error' — an unhandled 'error' on a ChildProcess would crash
|
|
251
|
+
// the process.
|
|
252
|
+
return await new Promise((resolve, reject) => {
|
|
253
|
+
let settled = false
|
|
254
|
+
const child = _spawn('emulator', args, { detached: true, stdio: 'ignore' })
|
|
255
|
+
const onError = (err) => {
|
|
256
|
+
if (settled) return
|
|
257
|
+
settled = true
|
|
258
|
+
reject(err instanceof Error ? err : new Error(`emulator spawn failed: ${err}`))
|
|
259
|
+
}
|
|
260
|
+
const onSpawn = () => {
|
|
261
|
+
if (settled) return
|
|
262
|
+
settled = true
|
|
263
|
+
if (typeof child.unref === 'function') child.unref()
|
|
264
|
+
resolve('starting')
|
|
265
|
+
}
|
|
266
|
+
if (child && typeof child.once === 'function') {
|
|
267
|
+
child.once('error', onError)
|
|
268
|
+
child.once('spawn', onSpawn)
|
|
269
|
+
} else {
|
|
270
|
+
// A stub child without an event emitter (defensive): treat as started.
|
|
271
|
+
onSpawn()
|
|
272
|
+
}
|
|
273
|
+
})
|
|
274
|
+
}
|
|
275
|
+
// kill
|
|
276
|
+
if (typeof serial !== 'string' || !serial) throw new Error('runEmulatorAction kill requires a serial')
|
|
277
|
+
await _execFile('adb', ['-s', serial, 'emu', 'kill'], EXEC_OPTS)
|
|
278
|
+
return 'killed'
|
|
279
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Control Room v2 — shared factories for the Host/Repo status WS handlers.
|
|
3
|
+
*
|
|
4
|
+
* The control-room handlers all share two skeletons that were copied ~11× and
|
|
5
|
+
* ~7× respectively. This module captures the *control flow* once so each handler
|
|
6
|
+
* only contributes its own snapshot shapes + survey call:
|
|
7
|
+
*
|
|
8
|
+
* - {@link makeSurveyHandler} — the async read-only survey handlers
|
|
9
|
+
* (host/runner/containers/repo-runtime/byok-pool/host-prune/simulator/
|
|
10
|
+
* emulator/wsl/integration/skills-inventory). Every one ran the same
|
|
11
|
+
* requestId-parse → host-authority gate → per-client in-flight guard →
|
|
12
|
+
* try/survey/reply → catch/log/degrade → finally/release skeleton.
|
|
13
|
+
* - {@link makeActionError} — the `*_ACTION_FAILED` `session_error` builders
|
|
14
|
+
* (integration/container/byok-pool/host-prune/simulator/emulator/wsl), which
|
|
15
|
+
* were identical apart from the `code` and the echoed correlation fields.
|
|
16
|
+
*
|
|
17
|
+
* The factories own ONLY the boilerplate; each handler's snapshot/reply shapes,
|
|
18
|
+
* survey seams, and security-sensitive ordering stay in the call site so the
|
|
19
|
+
* refactor is behaviour-preserving.
|
|
20
|
+
*/
|
|
21
|
+
import { createLogger } from '../logger.js'
|
|
22
|
+
import { getErrorMessage } from '../utils/error-message.js'
|
|
23
|
+
|
|
24
|
+
const log = createLogger('ws')
|
|
25
|
+
|
|
26
|
+
/** Parse the optional correlation id off a request, normalising to null. */
|
|
27
|
+
export function requestIdOf(msg) {
|
|
28
|
+
return typeof msg?.requestId === 'string' ? msg.requestId : null
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Build an async read-only survey handler with the shared host-authority +
|
|
33
|
+
* per-client in-flight + degraded-reply contract.
|
|
34
|
+
*
|
|
35
|
+
* Each survey supplies snapshot-shaping closures rather than control flow:
|
|
36
|
+
*
|
|
37
|
+
* @param {object} opts
|
|
38
|
+
* @param {WeakSet} opts.inFlight - per-client in-flight guard (one survey/client).
|
|
39
|
+
* @param {string} opts.logName - request type, used in the failure log line.
|
|
40
|
+
* @param {(args:{ctx:object,msg:object}) => any} [opts.prepare]
|
|
41
|
+
* Optional pre-gate computation (e.g. resolving the discovery root from
|
|
42
|
+
* config) whose result is threaded to every closure as `prep`. Runs
|
|
43
|
+
* BEFORE the authority gate — so it must read only non-sensitive config
|
|
44
|
+
* (the same ordering the hand-written handlers used). Security note: do
|
|
45
|
+
* NOT compute host-only secrets here; a session-bound client reaches the
|
|
46
|
+
* FORBIDDEN reply, so anything in `prep` may surface to it.
|
|
47
|
+
* @param {(args:{ctx,msg,requestId,prep}) => object} opts.forbidden
|
|
48
|
+
* Degraded snapshot for a session-bound (unauthorised) client.
|
|
49
|
+
* @param {(args:{ctx,msg,requestId,prep}) => object} opts.inProgress
|
|
50
|
+
* Degraded snapshot when a survey is already in flight for this client.
|
|
51
|
+
* @param {(args:{ctx,msg,requestId,prep,err}) => object} opts.failed
|
|
52
|
+
* Degraded snapshot when the survey throws.
|
|
53
|
+
* @param {(args:{ctx,msg,requestId,prep}) => Promise<object>} opts.run
|
|
54
|
+
* Runs the survey and returns the success reply (the factory sends it).
|
|
55
|
+
* @returns {(ws, client, msg, ctx) => Promise<void>}
|
|
56
|
+
*/
|
|
57
|
+
export function makeSurveyHandler({ inFlight, logName, prepare, forbidden, inProgress, failed, run }) {
|
|
58
|
+
return async function surveyHandler(ws, client, msg, ctx) {
|
|
59
|
+
const requestId = requestIdOf(msg)
|
|
60
|
+
const prep = prepare ? prepare({ ctx, msg }) : null
|
|
61
|
+
const args = { ctx, msg, requestId, prep }
|
|
62
|
+
|
|
63
|
+
// Authority gate: a host-wide survey is for host-level (unbound) clients
|
|
64
|
+
// only — a pairing-bound (share-a-session) token is scoped to one session.
|
|
65
|
+
if (client?.boundSessionId) {
|
|
66
|
+
ctx.transport.send(ws, forbidden(args))
|
|
67
|
+
return
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// In-flight guard: one survey per client at a time.
|
|
71
|
+
if (inFlight.has(client)) {
|
|
72
|
+
ctx.transport.send(ws, inProgress(args))
|
|
73
|
+
return
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
inFlight.add(client)
|
|
77
|
+
try {
|
|
78
|
+
ctx.transport.send(ws, await run(args))
|
|
79
|
+
} catch (err) {
|
|
80
|
+
log.warn(`${logName} failed: ${getErrorMessage(err, 'unknown error')}`)
|
|
81
|
+
ctx.transport.send(ws, failed({ ...args, err }))
|
|
82
|
+
} finally {
|
|
83
|
+
inFlight.delete(client)
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Build a synchronous host-survey handler for the in-memory snapshots
|
|
90
|
+
* (mailbox / external-sessions) that read only SessionManager state — no
|
|
91
|
+
* git/gh survey, so no in-flight guard. Shares the host-authority + degraded-
|
|
92
|
+
* reply contract: a session-bound client gets a schema-valid empty snapshot
|
|
93
|
+
* carrying an additive `error` so the view renders the refusal rather than
|
|
94
|
+
* spinning.
|
|
95
|
+
*
|
|
96
|
+
* @param {object} opts
|
|
97
|
+
* @param {string} opts.type - the snapshot message type.
|
|
98
|
+
* @param {object} opts.emptyFields - the snapshot's zeroed data fields
|
|
99
|
+
* (e.g. `{ registrations: [], recentEvents: [] }`); they back the
|
|
100
|
+
* FORBIDDEN reply and are overwritten by `resolve` on the success path.
|
|
101
|
+
* @param {string} opts.forbiddenMessage - the FORBIDDEN error message.
|
|
102
|
+
* @param {(ctx:object) => object} opts.resolve
|
|
103
|
+
* Returns the real data fields to spread over `emptyFields` for a
|
|
104
|
+
* host-level client.
|
|
105
|
+
* @returns {(ws, client, msg, ctx) => void}
|
|
106
|
+
*/
|
|
107
|
+
export function makeSyncHostSurvey({ type, emptyFields, forbiddenMessage, resolve }) {
|
|
108
|
+
return function syncHostSurvey(ws, client, msg, ctx) {
|
|
109
|
+
const base = { type, requestId: requestIdOf(msg), generatedAt: new Date().toISOString(), ...emptyFields }
|
|
110
|
+
if (client?.boundSessionId) {
|
|
111
|
+
ctx.transport.send(ws, { ...base, error: { code: 'FORBIDDEN', message: forbiddenMessage } })
|
|
112
|
+
return
|
|
113
|
+
}
|
|
114
|
+
ctx.transport.send(ws, { ...base, ...resolve(ctx) })
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Build a `*_ACTION_FAILED` `session_error` reply function. Mirrors how the
|
|
120
|
+
* CANCEL_ACTIVITY_FAILED session_error is built in input-handlers.js: a
|
|
121
|
+
* `session_error` envelope with a stable `code`, a `reason` discriminator, and
|
|
122
|
+
* the request's correlation fields echoed so the dashboard can clear the exact
|
|
123
|
+
* row's pending state.
|
|
124
|
+
*
|
|
125
|
+
* @param {string} code - the stable `*_ACTION_FAILED` code.
|
|
126
|
+
* @param {(msg:object) => object} correlate
|
|
127
|
+
* Returns the action-specific correlation fields to echo (e.g.
|
|
128
|
+
* `{ action, repoPath, runId }`). `requestId` is always appended.
|
|
129
|
+
* @returns {(ws, ctx, msg, reason, message) => void}
|
|
130
|
+
*/
|
|
131
|
+
export function makeActionError(code, correlate) {
|
|
132
|
+
return function actionError(ws, ctx, msg, reason, message) {
|
|
133
|
+
ctx.transport.send(ws, {
|
|
134
|
+
type: 'session_error',
|
|
135
|
+
code,
|
|
136
|
+
message,
|
|
137
|
+
reason,
|
|
138
|
+
...correlate(msg),
|
|
139
|
+
requestId: requestIdOf(msg),
|
|
140
|
+
})
|
|
141
|
+
}
|
|
142
|
+
}
|