mirror of
https://github.com/stablyai/orca.git
synced 2026-09-21 16:02:20 +00:00
* feat(ai-vault): isolate scanning in service processes * fix(ai-vault): retire idle service processes * fix(ai-vault): discard unverified cache processes * fix(ai-vault): clear relay sidecar cancel watchdog on acknowledgement A cancelled relay call is settled before its 2s cancel watchdog is armed, so the acknowledgement path bailed out of settle() before clearing the timer. The watchdog then faulted a healthy sidecar two seconds after every aborted scan, killing whatever request had since become active. * fix(ai-vault): clear the pending restart before scheduling another recordFault overwrote this.timer, stranding a restart that dispose() could no longer cancel. * refactor(ai-vault): drop the orphaned first-prompt IPC wrapper session-first-user-prompt-handler.ts now owns this entry point and routes through the service; the copy left in the read module had no callers. * fix(ai-vault): retry a faulted cold start before surfacing it A slow first start surfaced a raw 'did not become ready' error to the caller even though the supervisor was already respawning. Requeue an unsent call once onto the scheduled respawn instead. Also stop arming the cancellation watchdog for a call the child never received: no acknowledgement is coming, so it killed a healthy service and stalled the lane. Invalidation bookkeeping and ready-waiter construction move to the state module to stay under the max-lines cap. * fix(ai-vault): give relay title reads their own lane Before this branch the relay read title files directly, concurrently with scans. Routing both through one sidecar lane put title resolution behind a list scan that may run up to 130s, so SSH tab titles could lag minutes behind. Split cache and interactive lanes in both the relay client and the sidecar entry, mirroring the desktop service. Also: clear the ready deadline on fault, so a sidecar that dies before ready cannot fault its healthy replacement five seconds later; retry an unsent call once across a respawn; and skip the cancellation watchdog for a call the sidecar never received. Restart/circuit bookkeeping moves to its own module, mirroring the desktop policy, to stay under the max-lines cap. * fix(ai-vault): degrade relay title resolution on sidecar failure listSessions already returns a host issue when the sidecar is unavailable; titles propagated the raw RPC error instead. Return no titles so callers fall back to preview text, and keep cancellation propagating. * fix(ai-vault): scrub the service child environment The children are forked with a 384 MiB heap cap and no loader, but both spawn sites handed them the full parent environment, so an exported NODE_OPTIONS silently raised the cap or --require'd code into them. Allowlist both, following the plugin worker. The desktop child keeps the eleven agent-root overrides it resolves its own roots from; the relay sidecar takes remoteHome and hostPlatform from its init message and so needs none of them. Both children share one priority module while they share this one. * fix(ai-vault): soft-disable relay vault when the service is missing A missing service threw out of the constructor, so a Vault wiring bug would abort relay startup and take every PTY on the host with it. The unsupported-platform branch three lines above already treats a Vault failure as a soft disable; do the same here. Threading the service through the two handlers instead of a field also retires the definite-assignment assertion the throw was propping up. * fix(ai-vault): drain consumed cache invalidations invalidatedPaths was re-applied in every request's finally and never drained, so once N paths had been invalidated every later request paid N evictions for the life of the process; the 4096 cap only bounded how bad that got. The re-apply exists to cover a read that overlapped the invalidation, so drain once nothing is executing. Clearing unconditionally would drop the re-apply for a request still running on the other lane. * fix(ai-vault): keep a busy child through slow invalidation acks invalidate() reused the 5s ready budget as its acknowledgement deadline and killed the child on expiry, so a delete issued during a large scan could kill a healthy process mid-scan and burn a slot toward the restart circuit. Fault only when nothing is executing. Fork IPC ordering already puts the invalidation ahead of any later request, so a busy child owes no ack here, and the 130s/15s request deadlines still catch a wedged one. The start-retry predicate moves to the state module to stay under the line cap, matching the shape the relay client already uses. * fix(ai-vault): report a failed local scan as a host issue A local-scope scan let its error escape to the renderer, which paints it over the session list. Service supervision now produces those errors, so "AI Vault service restart circuit is open." replaced the list. Route local scope through the degradation the all-hosts leg and every SSH leg already use, so it lands as a retryable host issue row instead. Same result shape either way, so no IPC or wire contract changes. * test(ai-vault): cover the relay restart circuit transitions The relay policy shipped without tests. Pin both circuit edges, the aging-out case, the forced-refresh reopen the relay has and the desktop does not, and the backoff schedule. * fix(ai-vault): keep the OpenCode roots in the service child env The scrubbed allowlist dropped XDG_DATA_HOME and OPENCODE_DB, which the child reads to locate the OpenCode store and database. The pre-PR worker thread inherited them, so a user who sets either lost every OpenCode session. * test(ai-vault): anchor the service spawn env assertion
437 lines
13 KiB
JavaScript
437 lines
13 KiB
JavaScript
import { spawn, spawnSync } from 'node:child_process'
|
|
import { createHash } from 'node:crypto'
|
|
import { copyFileSync, cpSync, existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'
|
|
import { createConnection } from 'node:net'
|
|
import { join, resolve } from 'node:path'
|
|
|
|
const projectDir = resolve(import.meta.dirname, '..', '..')
|
|
const relayBuildDir = join(projectDir, 'out', 'relay', 'win32-x64')
|
|
const SENTINEL = Buffer.from('ORCA-RELAY v0.1.0 READY\n')
|
|
const HEADER_LENGTH = 13
|
|
const REGRESSION_TIMEOUT_MS = 15_000
|
|
const NODE_PTY_PATCH_FILENAME = 'node-pty-1.1.0-console-list-agent-patch.cjs'
|
|
|
|
if (process.platform !== 'win32') {
|
|
console.log('SKIP: Windows ConPTY regression only runs on Windows.')
|
|
process.exit(0)
|
|
}
|
|
|
|
const options = parseArgs(process.argv.slice(2))
|
|
const nodePath = resolve(options.node ?? process.execPath)
|
|
const nodePtyDir = resolve(options.nodePty ?? join(projectDir, 'node_modules', 'node-pty'))
|
|
const expectFailure = options.expect === 'attach-console-failure'
|
|
|
|
for (const required of [
|
|
nodePath,
|
|
nodePtyDir,
|
|
join(relayBuildDir, 'relay.js'),
|
|
join(relayBuildDir, '.version')
|
|
]) {
|
|
if (!existsSync(required)) {
|
|
throw new Error(`Required regression input is missing: ${required}`)
|
|
}
|
|
}
|
|
|
|
const runDir = mkdtempSync(join(projectDir, '.issue-9586-relay-repro-'))
|
|
const relayPath = join(runDir, 'relay.js')
|
|
const stdoutLog = join(runDir, 'relay.log')
|
|
const stderrLog = join(runDir, 'relay.err.log')
|
|
const socketPath = `\\\\.\\pipe\\orca-issue-9586-${process.pid}-${Date.now()}`
|
|
let relayPid
|
|
|
|
try {
|
|
prepareRelayTree(runDir, nodePtyDir)
|
|
if (!options.skipRelayPatch) {
|
|
applyPackagedNodePtyPatch(nodePath, runDir)
|
|
}
|
|
relayPid = launchRelayWithoutConsole({
|
|
nodePath,
|
|
relayPath,
|
|
runDir,
|
|
socketPath,
|
|
stdoutLog,
|
|
stderrLog
|
|
})
|
|
await waitForPipe(socketPath, 5_000)
|
|
const observation = await exerciseRelayClient({
|
|
nodePath,
|
|
relayPath,
|
|
runDir,
|
|
socketPath,
|
|
shell: options.shell
|
|
})
|
|
await waitForExit(relayPid, 8_000)
|
|
|
|
const relayStdout = readIfPresent(stdoutLog)
|
|
const relayStderr = readIfPresent(stderrLog)
|
|
const attachConsoleFailed = relayStderr.includes('Error: AttachConsole failed')
|
|
const installedNodePtyDir = join(runDir, 'node_modules', 'node-pty')
|
|
const agentPath = join(installedNodePtyDir, 'lib', 'conpty_console_list_agent.js')
|
|
const nativeBindingPath = join(
|
|
installedNodePtyDir,
|
|
'prebuilds',
|
|
`${process.platform}-${process.arch}`,
|
|
'conpty.node'
|
|
)
|
|
const summary = {
|
|
node: observation.nodeVersion,
|
|
nodePty: JSON.parse(readFileSync(join(nodePtyDir, 'package.json'), 'utf8')).version,
|
|
shell: options.shell,
|
|
relayPid,
|
|
handshake: observation.handshake,
|
|
ptySpawn: observation.ptySpawn,
|
|
ptyShutdown: observation.ptyShutdown,
|
|
relayAliveAfterPtyShutdown: observation.relayAliveAfterPtyShutdown,
|
|
bridgeExit: observation.bridgeExit,
|
|
relayPatchApplied: !options.skipRelayPatch,
|
|
agentSha256: fileSha256(agentPath),
|
|
nativeBindingPresent: existsSync(nativeBindingPath),
|
|
attachConsoleFailed,
|
|
relayExitedAfterClientDisconnect: !isProcessAlive(relayPid)
|
|
}
|
|
console.log(JSON.stringify(summary, null, 2))
|
|
|
|
if (expectFailure !== attachConsoleFailed) {
|
|
throw new Error(
|
|
expectFailure
|
|
? `Expected the real console-list agent to fail AttachConsole. stderr:\n${relayStderr}`
|
|
: `The real console-list agent failed AttachConsole. stderr:\n${relayStderr}`
|
|
)
|
|
}
|
|
if (
|
|
!observation.handshake ||
|
|
!observation.ptySpawn ||
|
|
!observation.ptyShutdown ||
|
|
!observation.relayAliveAfterPtyShutdown
|
|
) {
|
|
throw new Error(
|
|
`Relay lifecycle did not complete. stdout:\n${relayStdout}\nstderr:\n${relayStderr}`
|
|
)
|
|
}
|
|
} finally {
|
|
if (relayPid && isProcessAlive(relayPid)) {
|
|
stopExactProcess(relayPid, relayPath)
|
|
}
|
|
rmSync(runDir, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 })
|
|
}
|
|
|
|
function parseArgs(args) {
|
|
const parsed = { expect: 'clean', shell: 'cmd.exe', skipRelayPatch: false }
|
|
for (let index = 0; index < args.length; index++) {
|
|
const flag = args[index]
|
|
if (flag === '--skip-relay-patch') {
|
|
parsed.skipRelayPatch = true
|
|
continue
|
|
}
|
|
const value = args[index + 1]
|
|
if (!value || !['--node', '--node-pty', '--expect', '--shell'].includes(flag)) {
|
|
throw new Error(
|
|
'Usage: node windows-ssh-attach-console-repro.mjs [--node PATH] [--node-pty DIR] [--shell PATH] [--skip-relay-patch] [--expect clean|attach-console-failure]'
|
|
)
|
|
}
|
|
if (flag === '--node') {
|
|
parsed.node = value
|
|
}
|
|
if (flag === '--node-pty') {
|
|
parsed.nodePty = value
|
|
}
|
|
if (flag === '--expect') {
|
|
parsed.expect = value
|
|
}
|
|
if (flag === '--shell') {
|
|
parsed.shell = value
|
|
}
|
|
index++
|
|
}
|
|
if (!['clean', 'attach-console-failure'].includes(parsed.expect)) {
|
|
throw new Error(`Unsupported expectation: ${parsed.expect}`)
|
|
}
|
|
return parsed
|
|
}
|
|
|
|
function prepareRelayTree(runDir, nodePtyDir) {
|
|
for (const filename of [
|
|
'relay.js',
|
|
'relay-watcher.js',
|
|
'relay-ai-vault-service.js',
|
|
'managed-hook-runtime.js',
|
|
NODE_PTY_PATCH_FILENAME,
|
|
'.version'
|
|
]) {
|
|
copyFileSync(join(relayBuildDir, filename), join(runDir, filename))
|
|
}
|
|
cpSync(nodePtyDir, join(runDir, 'node_modules', 'node-pty'), { recursive: true })
|
|
}
|
|
|
|
function applyPackagedNodePtyPatch(nodePath, runDir) {
|
|
const result = spawnSync(nodePath, [join(runDir, NODE_PTY_PATCH_FILENAME)], {
|
|
cwd: runDir,
|
|
encoding: 'utf8',
|
|
windowsHide: true
|
|
})
|
|
if (result.status !== 0) {
|
|
throw new Error(`Packaged node-pty patch failed: ${result.stderr || result.stdout}`)
|
|
}
|
|
}
|
|
|
|
function launchRelayWithoutConsole({
|
|
nodePath,
|
|
relayPath,
|
|
runDir,
|
|
socketPath,
|
|
stdoutLog,
|
|
stderrLog
|
|
}) {
|
|
const relayArgs = [
|
|
quoteWindowsArg(nodePath),
|
|
quoteWindowsArg(relayPath),
|
|
'--detached',
|
|
'--grace-time',
|
|
'5',
|
|
'--sock-path',
|
|
quoteWindowsArg(socketPath),
|
|
'--endpoint-dir',
|
|
quoteWindowsArg(join(runDir, 'endpoint')),
|
|
'--log-file',
|
|
quoteWindowsArg(stdoutLog),
|
|
`1>${quoteWindowsArg(stdoutLog)}`,
|
|
`2>${quoteWindowsArg(stderrLog)}`
|
|
].join(' ')
|
|
const commandLine = `cmd.exe /d /s /c "${relayArgs}"`
|
|
const script = [
|
|
`$result = Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{ CommandLine = ${powerShellLiteral(commandLine)}; CurrentDirectory = ${powerShellLiteral(runDir)} }`,
|
|
`if ($result.ReturnValue -ne 0) { throw "Win32_Process.Create failed with $($result.ReturnValue)" }`,
|
|
'$result.ProcessId'
|
|
].join('; ')
|
|
const launched = runPowerShell(script)
|
|
const pid = Number(launched.stdout.trim())
|
|
if (!Number.isInteger(pid) || pid <= 0) {
|
|
throw new Error(`Could not parse detached relay pid from: ${launched.stdout}`)
|
|
}
|
|
return pid
|
|
}
|
|
|
|
function exerciseRelayClient({ nodePath, relayPath, runDir, socketPath, shell }) {
|
|
return new Promise((resolvePromise, rejectPromise) => {
|
|
const bridge = spawn(nodePath, [relayPath, '--connect', '--sock-path', socketPath], {
|
|
cwd: runDir,
|
|
windowsHide: true,
|
|
stdio: ['pipe', 'pipe', 'pipe']
|
|
})
|
|
const observation = {
|
|
nodeVersion: readNodeVersion(nodePath),
|
|
handshake: false,
|
|
ptySpawn: false,
|
|
ptyShutdown: false,
|
|
relayAliveAfterPtyShutdown: false,
|
|
bridgeExit: null
|
|
}
|
|
let stderr = ''
|
|
let buffer = Buffer.alloc(0)
|
|
let sentinelRead = false
|
|
let outgoingSequence = 1
|
|
let settled = false
|
|
const timeout = setTimeout(
|
|
() => finish(new Error(`Timed out waiting for relay client lifecycle. stderr:\n${stderr}`)),
|
|
REGRESSION_TIMEOUT_MS
|
|
)
|
|
|
|
bridge.stderr.on('data', (data) => {
|
|
stderr += data.toString()
|
|
})
|
|
bridge.on('error', finish)
|
|
bridge.on('close', (code, signal) => {
|
|
observation.bridgeExit = { code, signal }
|
|
if (!settled && observation.relayAliveAfterPtyShutdown) {
|
|
finish()
|
|
} else if (!settled) {
|
|
finish(new Error(`Relay bridge closed before lifecycle completed. stderr:\n${stderr}`))
|
|
}
|
|
})
|
|
bridge.stdout.on('data', (data) => {
|
|
try {
|
|
buffer = Buffer.concat([buffer, data])
|
|
if (!sentinelRead) {
|
|
const sentinelIndex = buffer.indexOf(SENTINEL)
|
|
if (sentinelIndex === -1) {
|
|
return
|
|
}
|
|
buffer = buffer.subarray(sentinelIndex + SENTINEL.length)
|
|
sentinelRead = true
|
|
observation.handshake = true
|
|
request(1, 'pty.spawn', {
|
|
shellOverride: shell,
|
|
cwd: projectDir,
|
|
cols: 80,
|
|
rows: 24,
|
|
env: {}
|
|
})
|
|
}
|
|
for (const message of drainMessages()) {
|
|
if (message.id === 1) {
|
|
throwResponseError(message)
|
|
observation.ptySpawn = true
|
|
request(2, 'pty.shutdown', { id: message.result.id, immediate: true })
|
|
} else if (message.id === 2) {
|
|
throwResponseError(message)
|
|
observation.ptyShutdown = true
|
|
request(3, 'relay.status', {})
|
|
} else if (message.id === 3) {
|
|
throwResponseError(message)
|
|
observation.relayAliveAfterPtyShutdown = message.result.ptys.active === 0
|
|
bridge.stdin.end()
|
|
}
|
|
}
|
|
} catch (error) {
|
|
finish(error)
|
|
}
|
|
})
|
|
|
|
function request(id, method, params) {
|
|
bridge.stdin.write(encodeRequestFrame({ id, method, params }, outgoingSequence++))
|
|
}
|
|
|
|
function drainMessages() {
|
|
const messages = []
|
|
while (buffer.length >= HEADER_LENGTH) {
|
|
const type = buffer[0]
|
|
const payloadLength = buffer.readUInt32BE(9)
|
|
if (buffer.length < HEADER_LENGTH + payloadLength) {
|
|
break
|
|
}
|
|
const payload = buffer.subarray(HEADER_LENGTH, HEADER_LENGTH + payloadLength)
|
|
buffer = buffer.subarray(HEADER_LENGTH + payloadLength)
|
|
if (type === 1) {
|
|
messages.push(JSON.parse(payload.toString('utf8')))
|
|
}
|
|
}
|
|
return messages
|
|
}
|
|
|
|
function finish(error) {
|
|
if (settled) {
|
|
return
|
|
}
|
|
settled = true
|
|
clearTimeout(timeout)
|
|
if (error) {
|
|
bridge.kill()
|
|
rejectPromise(error)
|
|
} else {
|
|
resolvePromise(observation)
|
|
}
|
|
}
|
|
})
|
|
}
|
|
|
|
function waitForPipe(socketPath, timeoutMs) {
|
|
const deadline = Date.now() + timeoutMs
|
|
return new Promise((resolvePromise, rejectPromise) => {
|
|
const attempt = () => {
|
|
const socket = createConnection(socketPath)
|
|
let settled = false
|
|
const retry = () => {
|
|
if (settled) {
|
|
return
|
|
}
|
|
settled = true
|
|
socket.destroy()
|
|
if (Date.now() >= deadline) {
|
|
rejectPromise(new Error(`Detached relay did not listen on ${socketPath}`))
|
|
} else {
|
|
setTimeout(attempt, 50)
|
|
}
|
|
}
|
|
socket.once('connect', () => {
|
|
if (settled) {
|
|
return
|
|
}
|
|
settled = true
|
|
socket.destroy()
|
|
resolvePromise()
|
|
})
|
|
socket.once('error', retry)
|
|
socket.setTimeout(250, retry)
|
|
}
|
|
attempt()
|
|
})
|
|
}
|
|
|
|
function encodeRequestFrame({ id, method, params }, sequence) {
|
|
const payload = Buffer.from(JSON.stringify({ jsonrpc: '2.0', id, method, params }))
|
|
const header = Buffer.alloc(HEADER_LENGTH)
|
|
header[0] = 1
|
|
header.writeUInt32BE(sequence, 1)
|
|
header.writeUInt32BE(0, 5)
|
|
header.writeUInt32BE(payload.length, 9)
|
|
return Buffer.concat([header, payload])
|
|
}
|
|
|
|
function throwResponseError(message) {
|
|
if (message.error) {
|
|
throw new Error(`Relay RPC failed: ${message.error.message}`)
|
|
}
|
|
}
|
|
|
|
function readNodeVersion(nodePath) {
|
|
return spawnSync(nodePath, ['--version'], { encoding: 'utf8' }).stdout.trim()
|
|
}
|
|
|
|
function waitForExit(pid, timeoutMs) {
|
|
const deadline = Date.now() + timeoutMs
|
|
return new Promise((resolvePromise) => {
|
|
const poll = () => {
|
|
if (!isProcessAlive(pid) || Date.now() >= deadline) {
|
|
resolvePromise()
|
|
return
|
|
}
|
|
setTimeout(poll, 50)
|
|
}
|
|
poll()
|
|
})
|
|
}
|
|
|
|
function isProcessAlive(pid) {
|
|
const result = runPowerShell(
|
|
`if (Get-Process -Id ${pid} -ErrorAction SilentlyContinue) { 'ALIVE' }`
|
|
)
|
|
return result.stdout.includes('ALIVE')
|
|
}
|
|
|
|
function stopExactProcess(pid, relayPath) {
|
|
const script = [
|
|
`$process = Get-CimInstance Win32_Process -Filter ${powerShellLiteral(`ProcessId = ${pid}`)}`,
|
|
`if ($process -and $process.CommandLine -like ${powerShellLiteral(`*${relayPath}*`)}) { Stop-Process -Id ${pid} -Force }`
|
|
].join('; ')
|
|
runPowerShell(script)
|
|
}
|
|
|
|
function runPowerShell(script) {
|
|
const encoded = Buffer.from(script, 'utf16le').toString('base64')
|
|
const result = spawnSync(
|
|
'powershell.exe',
|
|
['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', encoded],
|
|
{ encoding: 'utf8' }
|
|
)
|
|
if (result.status !== 0) {
|
|
throw new Error(`PowerShell failed (${result.status}): ${result.stderr || result.stdout}`)
|
|
}
|
|
return result
|
|
}
|
|
|
|
function quoteWindowsArg(value) {
|
|
return `"${value.replaceAll('"', '\\"')}"`
|
|
}
|
|
|
|
function powerShellLiteral(value) {
|
|
return `'${value.replaceAll("'", "''")}'`
|
|
}
|
|
|
|
function readIfPresent(path) {
|
|
return existsSync(path) ? readFileSync(path, 'utf8') : ''
|
|
}
|
|
|
|
function fileSha256(path) {
|
|
return createHash('sha256').update(readFileSync(path)).digest('hex')
|
|
}
|