Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
@@ -1,6 +1,16 @@
|
||||
import {
|
||||
chmodSync,
|
||||
lstatSync,
|
||||
mkdirSync,
|
||||
readdirSync,
|
||||
rmSync,
|
||||
statSync,
|
||||
writeFileSync
|
||||
} from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { formatBase64PayloadByteCount } from './base64-payload-byte-count'
|
||||
import { quoteCliCommandArgument } from './shell-command-quote'
|
||||
import { writeComputerScreenshotTempFile } from './computer-screenshot-storage'
|
||||
import type {
|
||||
ComputerActionMetadata,
|
||||
ComputerActionResult,
|
||||
@@ -62,11 +72,11 @@ export function prepareComputerCliJsonResult<TResult>(
|
||||
}
|
||||
try {
|
||||
const extension = screenshot.format === 'png' ? 'png' : 'img'
|
||||
const { outputPath, expiresAt } = writeComputerScreenshotTempFile(
|
||||
response.id,
|
||||
screenshot.data,
|
||||
extension
|
||||
)
|
||||
const outputDir = computerScreenshotTempDir()
|
||||
cleanupComputerScreenshots(outputDir)
|
||||
const outputPath = join(outputDir, `${safeCliFileStem(response.id)}-screenshot.${extension}`)
|
||||
writeFileSync(outputPath, Buffer.from(screenshot.data, 'base64'), { mode: 0o600 })
|
||||
const expiresAt = new Date(Date.now() + COMPUTER_SCREENSHOT_TTL_MS).toISOString()
|
||||
return {
|
||||
...response,
|
||||
result: {
|
||||
@@ -87,6 +97,63 @@ export function prepareComputerCliJsonResult<TResult>(
|
||||
}
|
||||
}
|
||||
|
||||
const COMPUTER_SCREENSHOT_TTL_MS = 24 * 60 * 60 * 1000
|
||||
const COMPUTER_SCREENSHOT_CLEANUP_INTERVAL_MS = 60 * 60 * 1000
|
||||
const COMPUTER_SCREENSHOT_CLEANUP_MARKER = '.last-cleanup'
|
||||
|
||||
function computerScreenshotTempDir(): string {
|
||||
const outputDir =
|
||||
process.env.ORCA_COMPUTER_SCREENSHOT_TMPDIR || join(tmpdir(), 'orca-computer-use')
|
||||
mkdirSync(outputDir, { recursive: true, mode: 0o700 })
|
||||
const stat = lstatSync(outputDir)
|
||||
if (!stat.isDirectory() || stat.isSymbolicLink()) {
|
||||
throw new Error(`Unsafe computer screenshot temp path: ${outputDir}`)
|
||||
}
|
||||
if (typeof process.getuid === 'function' && stat.uid !== process.getuid()) {
|
||||
throw new Error(`Computer screenshot temp path is not owned by the current user: ${outputDir}`)
|
||||
}
|
||||
chmodSync(outputDir, 0o700)
|
||||
return outputDir
|
||||
}
|
||||
|
||||
function cleanupComputerScreenshots(outputDir: string): void {
|
||||
const now = Date.now()
|
||||
const markerPath = join(outputDir, COMPUTER_SCREENSHOT_CLEANUP_MARKER)
|
||||
try {
|
||||
// Why: agents can call computer-use CLI commands in loops; a marker keeps
|
||||
// temp cleanup from becoming a synchronous directory scan per screenshot.
|
||||
if (statSync(markerPath).mtimeMs > now - COMPUTER_SCREENSHOT_CLEANUP_INTERVAL_MS) {
|
||||
return
|
||||
}
|
||||
} catch {
|
||||
// Missing or unreadable marker means this process should attempt cleanup.
|
||||
}
|
||||
|
||||
const cutoff = now - COMPUTER_SCREENSHOT_TTL_MS
|
||||
for (const entry of readdirSync(outputDir)) {
|
||||
if (!entry.endsWith('-screenshot.png') && !entry.endsWith('-screenshot.img')) {
|
||||
continue
|
||||
}
|
||||
const path = join(outputDir, entry)
|
||||
try {
|
||||
if (statSync(path).mtimeMs < cutoff) {
|
||||
rmSync(path, { force: true })
|
||||
}
|
||||
} catch {
|
||||
// Best-effort cleanup only; formatting should not fail because a temp file raced.
|
||||
}
|
||||
}
|
||||
try {
|
||||
writeFileSync(markerPath, `${now}\n`, { mode: 0o600 })
|
||||
} catch {
|
||||
// Best-effort marker only; stale cleanup state should not hide a screenshot.
|
||||
}
|
||||
}
|
||||
|
||||
function safeCliFileStem(value: string): string {
|
||||
return value.replaceAll(/[^a-zA-Z0-9._-]/g, '_')
|
||||
}
|
||||
|
||||
export function formatListApps(result: ComputerListAppsResult): string {
|
||||
if (result.apps.length === 0) {
|
||||
return 'No apps found.'
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { existsSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { writeComputerScreenshotTempFile } from './computer-screenshot-storage'
|
||||
|
||||
const roots: string[] = []
|
||||
const originalTempDir = process.env.ORCA_COMPUTER_SCREENSHOT_TMPDIR
|
||||
|
||||
afterEach(() => {
|
||||
if (originalTempDir === undefined) {
|
||||
delete process.env.ORCA_COMPUTER_SCREENSHOT_TMPDIR
|
||||
} else {
|
||||
process.env.ORCA_COMPUTER_SCREENSHOT_TMPDIR = originalTempDir
|
||||
}
|
||||
for (const root of roots.splice(0)) {
|
||||
rmSync(root, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
describe('computer screenshot storage', () => {
|
||||
it('writes normal screenshot bytes and streams cleanup of expired captures', () => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'orca-computer-screenshot-'))
|
||||
roots.push(root)
|
||||
process.env.ORCA_COMPUTER_SCREENSHOT_TMPDIR = root
|
||||
const expiredPath = join(root, 'expired-screenshot.png')
|
||||
const unrelatedPath = join(root, 'keep.txt')
|
||||
writeFileSync(expiredPath, 'old')
|
||||
writeFileSync(unrelatedPath, 'keep')
|
||||
const expiredAt = new Date(Date.now() - 25 * 60 * 60 * 1000)
|
||||
utimesSync(expiredPath, expiredAt, expiredAt)
|
||||
|
||||
const result = writeComputerScreenshotTempFile(
|
||||
'rpc/id',
|
||||
Buffer.from('png').toString('base64'),
|
||||
'png'
|
||||
)
|
||||
|
||||
expect(result.outputPath).toBe(join(root, 'rpc_id-screenshot.png'))
|
||||
expect(existsSync(result.outputPath)).toBe(true)
|
||||
expect(existsSync(expiredPath)).toBe(false)
|
||||
expect(existsSync(unrelatedPath)).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -1,96 +0,0 @@
|
||||
import {
|
||||
chmodSync,
|
||||
lstatSync,
|
||||
mkdirSync,
|
||||
opendirSync,
|
||||
rmSync,
|
||||
statSync,
|
||||
writeFileSync
|
||||
} from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
|
||||
const COMPUTER_SCREENSHOT_TTL_MS = 24 * 60 * 60 * 1000
|
||||
const COMPUTER_SCREENSHOT_CLEANUP_INTERVAL_MS = 60 * 60 * 1000
|
||||
const COMPUTER_SCREENSHOT_CLEANUP_MARKER = '.last-cleanup'
|
||||
|
||||
export function writeComputerScreenshotTempFile(
|
||||
responseId: string,
|
||||
base64Data: string,
|
||||
extension: 'png' | 'img'
|
||||
): { outputPath: string; expiresAt: string } {
|
||||
const outputDir = computerScreenshotTempDir()
|
||||
cleanupComputerScreenshots(outputDir)
|
||||
const outputPath = join(outputDir, `${safeCliFileStem(responseId)}-screenshot.${extension}`)
|
||||
writeFileSync(outputPath, Buffer.from(base64Data, 'base64'), { mode: 0o600 })
|
||||
return {
|
||||
outputPath,
|
||||
expiresAt: new Date(Date.now() + COMPUTER_SCREENSHOT_TTL_MS).toISOString()
|
||||
}
|
||||
}
|
||||
|
||||
function computerScreenshotTempDir(): string {
|
||||
const outputDir =
|
||||
process.env.ORCA_COMPUTER_SCREENSHOT_TMPDIR || join(tmpdir(), 'orca-computer-use')
|
||||
mkdirSync(outputDir, { recursive: true, mode: 0o700 })
|
||||
const stat = lstatSync(outputDir)
|
||||
if (!stat.isDirectory() || stat.isSymbolicLink()) {
|
||||
throw new Error(`Unsafe computer screenshot temp path: ${outputDir}`)
|
||||
}
|
||||
if (typeof process.getuid === 'function' && stat.uid !== process.getuid()) {
|
||||
throw new Error(`Computer screenshot temp path is not owned by the current user: ${outputDir}`)
|
||||
}
|
||||
chmodSync(outputDir, 0o700)
|
||||
return outputDir
|
||||
}
|
||||
|
||||
function cleanupComputerScreenshots(outputDir: string): void {
|
||||
const now = Date.now()
|
||||
const markerPath = join(outputDir, COMPUTER_SCREENSHOT_CLEANUP_MARKER)
|
||||
try {
|
||||
// Why: agents can call computer-use CLI commands in loops; a marker keeps
|
||||
// temp cleanup from becoming a synchronous directory scan per screenshot.
|
||||
if (statSync(markerPath).mtimeMs > now - COMPUTER_SCREENSHOT_CLEANUP_INTERVAL_MS) {
|
||||
return
|
||||
}
|
||||
} catch {
|
||||
// Missing or unreadable marker means this process should attempt cleanup.
|
||||
}
|
||||
|
||||
const cutoff = now - COMPUTER_SCREENSHOT_TTL_MS
|
||||
const directory = opendirSync(outputDir)
|
||||
try {
|
||||
while (true) {
|
||||
const entry = directory.readSync()
|
||||
if (!entry) {
|
||||
break
|
||||
}
|
||||
if (!entry.name.endsWith('-screenshot.png') && !entry.name.endsWith('-screenshot.img')) {
|
||||
continue
|
||||
}
|
||||
const path = join(outputDir, entry.name)
|
||||
try {
|
||||
if (statSync(path).mtimeMs < cutoff) {
|
||||
rmSync(path, { force: true })
|
||||
}
|
||||
} catch {
|
||||
// Best-effort cleanup only; formatting should not fail because a temp file raced.
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
directory.closeSync()
|
||||
} catch {
|
||||
// Best-effort cleanup only.
|
||||
}
|
||||
}
|
||||
try {
|
||||
writeFileSync(markerPath, `${now}\n`, { mode: 0o600 })
|
||||
} catch {
|
||||
// Best-effort marker only; stale cleanup state should not hide a screenshot.
|
||||
}
|
||||
}
|
||||
|
||||
function safeCliFileStem(value: string): string {
|
||||
return value.replaceAll(/[^a-zA-Z0-9._-]/g, '_')
|
||||
}
|
||||
@@ -1,10 +1,9 @@
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, truncateSync, writeFileSync } from 'node:fs'
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { getDefaultPersistedState } from '../../shared/constants'
|
||||
import type { PersistedState } from '../../shared/types'
|
||||
import { ORCA_PERSISTED_STATE_MAX_BYTES } from '../../shared/persisted-state-file-bounds'
|
||||
|
||||
const {
|
||||
applyAgentStatusHooksEnabledMock,
|
||||
@@ -46,12 +45,9 @@ vi.mock('../runtime-client', () => {
|
||||
}
|
||||
}
|
||||
|
||||
class RuntimeRpcFailureError extends Error {}
|
||||
|
||||
return {
|
||||
RuntimeClient,
|
||||
RuntimeClientError,
|
||||
RuntimeRpcFailureError,
|
||||
getDefaultUserDataPath: getDefaultUserDataPathMock
|
||||
}
|
||||
})
|
||||
@@ -124,16 +120,4 @@ describe('agent hooks CLI handler', () => {
|
||||
|
||||
expect(readDataFile(userDataPath).settings.experimentalNewWorktreeCardStyle).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects an oversized sparse offline state file without replacing it', async () => {
|
||||
const dataPath = join(userDataPath, 'orca-data.json')
|
||||
writeFileSync(dataPath, '')
|
||||
truncateSync(dataPath, ORCA_PERSISTED_STATE_MAX_BYTES + 1)
|
||||
|
||||
await runAgentHooksOff(userDataPath)
|
||||
|
||||
expect(process.exitCode).toBe(1)
|
||||
expect(console.log).toHaveBeenCalledWith(expect.stringContaining('File too large'))
|
||||
expect(readFileSync(dataPath).byteLength).toBe(ORCA_PERSISTED_STATE_MAX_BYTES + 1)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { existsSync, mkdirSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'
|
||||
import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'
|
||||
import { homedir } from 'node:os'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
@@ -13,11 +13,6 @@ import {
|
||||
getManagedAgentHookStatuses
|
||||
} from '../../main/agent-hooks/managed-agent-hook-controls'
|
||||
import { getDefaultUserDataPath } from '../runtime-client'
|
||||
import {
|
||||
ORCA_PERSISTED_STATE_MAX_BYTES,
|
||||
readPersistedStateJsonFileSync,
|
||||
stringifyPrettyPersistedStateWithinLimit
|
||||
} from '../../shared/persisted-state-file-bounds'
|
||||
|
||||
type AgentHookCommandResult = {
|
||||
enabled: boolean
|
||||
@@ -39,7 +34,7 @@ function readPersistedState(dataPath: string): PersistedState {
|
||||
return getDefaultPersistedState(homedir())
|
||||
}
|
||||
try {
|
||||
const { value: parsed } = readPersistedStateJsonFileSync<unknown>(dataPath)
|
||||
const parsed = JSON.parse(readFileSync(dataPath, 'utf-8'))
|
||||
if (!isRecord(parsed)) {
|
||||
throw new Error('file does not contain a JSON object')
|
||||
}
|
||||
@@ -57,11 +52,7 @@ function writePersistedState(dataPath: string, state: PersistedState): void {
|
||||
const tmpPath = join(dirname(dataPath), `.${Date.now()}-${randomUUID()}.tmp`)
|
||||
let renamed = false
|
||||
try {
|
||||
const { serialized } = stringifyPrettyPersistedStateWithinLimit(
|
||||
state,
|
||||
ORCA_PERSISTED_STATE_MAX_BYTES - 1
|
||||
)
|
||||
writeFileSync(tmpPath, `${serialized}\n`, 'utf-8')
|
||||
writeFileSync(tmpPath, `${JSON.stringify(state, null, 2)}\n`, 'utf-8')
|
||||
renameSync(tmpPath, dataPath)
|
||||
renamed = true
|
||||
} finally {
|
||||
|
||||
@@ -2,11 +2,6 @@ import {
|
||||
computerUseHotkeyValidationMessage,
|
||||
computerUsePressKeyValidationMessage
|
||||
} from '../../shared/computer-use-key-spec'
|
||||
import { CLIPBOARD_TEXT_WRITE_MAX_BYTES } from '../../shared/clipboard-text'
|
||||
import {
|
||||
NodeReadableTextTooLargeError,
|
||||
readNodeReadableTextWithinLimit
|
||||
} from '../../shared/node-readable-text'
|
||||
import {
|
||||
getOptionalNonNegativeIntegerFlag,
|
||||
getOptionalNumberFlag,
|
||||
@@ -194,17 +189,11 @@ async function readStdin(): Promise<string> {
|
||||
if (process.stdin.isTTY) {
|
||||
throw new RuntimeClientError('invalid_argument', 'stdin payload requested but stdin is a TTY')
|
||||
}
|
||||
try {
|
||||
return await readNodeReadableTextWithinLimit(process.stdin, CLIPBOARD_TEXT_WRITE_MAX_BYTES)
|
||||
} catch (error) {
|
||||
if (error instanceof NodeReadableTextTooLargeError) {
|
||||
throw new RuntimeClientError(
|
||||
'invalid_argument',
|
||||
`stdin payload must be at most ${CLIPBOARD_TEXT_WRITE_MAX_BYTES} bytes`
|
||||
)
|
||||
}
|
||||
throw error
|
||||
const chunks: Buffer[] = []
|
||||
for await (const chunk of process.stdin) {
|
||||
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)))
|
||||
}
|
||||
return Buffer.concat(chunks).toString('utf8')
|
||||
}
|
||||
|
||||
function getOptionalPositiveNumberFlag(
|
||||
|
||||
@@ -79,25 +79,6 @@ type OrchestrationSendResult =
|
||||
| { message: { id: string }; lifecycle?: LifecycleSendRejection }
|
||||
| { messages: { id: string }[]; recipients: number }
|
||||
|
||||
type OrchestrationRetentionPage = {
|
||||
count: number
|
||||
truncated?: boolean
|
||||
total?: number
|
||||
remaining?: number
|
||||
}
|
||||
|
||||
function appendOrchestrationRetentionNotice(
|
||||
body: string,
|
||||
page: OrchestrationRetentionPage,
|
||||
noun: string
|
||||
): string {
|
||||
if (!page.truncated) {
|
||||
return body
|
||||
}
|
||||
const omitted = page.remaining ?? Math.max(0, (page.total ?? page.count) - page.count)
|
||||
return `${body}\n\nTruncated: ${omitted} additional ${noun} omitted.`
|
||||
}
|
||||
|
||||
function getOptionalStructuredMessagePayload(
|
||||
flags: Map<string, string | boolean>
|
||||
): string | undefined {
|
||||
@@ -418,8 +399,6 @@ export const ORCHESTRATION_HANDLERS: Record<string, CommandHandler> = {
|
||||
messages: MessageSummary[]
|
||||
count: number
|
||||
formatted?: string
|
||||
truncated?: boolean
|
||||
remaining?: number
|
||||
}
|
||||
let result: Awaited<ReturnType<typeof client.call<CheckResult>>>
|
||||
try {
|
||||
@@ -466,17 +445,15 @@ export const ORCHESTRATION_HANDLERS: Record<string, CommandHandler> = {
|
||||
}
|
||||
}
|
||||
printResult(result, json, (r) => {
|
||||
let body: string
|
||||
if (r.formatted) {
|
||||
body = r.formatted
|
||||
} else if (r.count === 0) {
|
||||
body = 'No messages.'
|
||||
} else {
|
||||
body = r.messages
|
||||
.map((m) => `${m.id} [${m.type ?? 'status'}] from=${m.from_handle} "${m.subject}"`)
|
||||
.join('\n')
|
||||
return r.formatted
|
||||
}
|
||||
return appendOrchestrationRetentionNotice(body, r, 'messages')
|
||||
if (r.count === 0) {
|
||||
return 'No messages.'
|
||||
}
|
||||
return r.messages
|
||||
.map((m) => `${m.id} [${m.type ?? 'status'}] from=${m.from_handle} "${m.subject}"`)
|
||||
.join('\n')
|
||||
})
|
||||
},
|
||||
|
||||
@@ -495,34 +472,31 @@ export const ORCHESTRATION_HANDLERS: Record<string, CommandHandler> = {
|
||||
const result = await client.call<{
|
||||
messages: MessageSummary[]
|
||||
count: number
|
||||
total?: number
|
||||
truncated?: boolean
|
||||
}>('orchestration.inbox', {
|
||||
limit: getOptionalPositiveIntegerFlag(flags, 'limit'),
|
||||
terminal: getOptionalStringFlag(flags, 'terminal')
|
||||
})
|
||||
printResult(result, json, (r) => {
|
||||
if (r.count === 0) {
|
||||
return 'No messages.'
|
||||
}
|
||||
// Why: default output omits body/payload for at-a-glance sweeps; --full prints them for auditing.
|
||||
const body =
|
||||
r.count === 0
|
||||
? 'No messages.'
|
||||
: r.messages
|
||||
.map((m) => {
|
||||
const head = `${m.id} ${m.from_handle} -> ${m.to_handle ?? '?'}: "${m.subject}"`
|
||||
if (!full) {
|
||||
return head
|
||||
}
|
||||
const parts = [head]
|
||||
if (m.body && m.body.length > 0) {
|
||||
parts.push(m.body)
|
||||
}
|
||||
if (m.payload) {
|
||||
parts.push(`[payload] ${m.payload}`)
|
||||
}
|
||||
return parts.join('\n')
|
||||
})
|
||||
.join(full ? '\n\n' : '\n')
|
||||
return appendOrchestrationRetentionNotice(body, r, 'messages')
|
||||
return r.messages
|
||||
.map((m) => {
|
||||
const head = `${m.id} ${m.from_handle} -> ${m.to_handle ?? '?'}: "${m.subject}"`
|
||||
if (!full) {
|
||||
return head
|
||||
}
|
||||
const parts = [head]
|
||||
if (m.body && m.body.length > 0) {
|
||||
parts.push(m.body)
|
||||
}
|
||||
if (m.payload) {
|
||||
parts.push(`[payload] ${m.payload}`)
|
||||
}
|
||||
return parts.join('\n')
|
||||
})
|
||||
.join(full ? '\n\n' : '\n')
|
||||
})
|
||||
},
|
||||
|
||||
@@ -556,8 +530,6 @@ export const ORCHESTRATION_HANDLERS: Record<string, CommandHandler> = {
|
||||
spec_truncated?: boolean
|
||||
}[]
|
||||
count: number
|
||||
total?: number
|
||||
truncated?: boolean
|
||||
}>('orchestration.taskList', {
|
||||
status: getOptionalStringFlag(flags, 'status'),
|
||||
ready: flags.has('ready') ? true : undefined,
|
||||
@@ -573,20 +545,19 @@ export const ORCHESTRATION_HANDLERS: Record<string, CommandHandler> = {
|
||||
}
|
||||
: result
|
||||
printResult(output, json, (r) => {
|
||||
const body =
|
||||
r.count === 0
|
||||
? 'No tasks.'
|
||||
: r.tasks
|
||||
.map((t) => {
|
||||
const label = t.display_name ?? t.task_title ?? t.spec
|
||||
const head = `${t.id} [${t.status}] ${label.slice(0, 60)}`
|
||||
if (t.status === 'dispatched' && t.assignee_handle) {
|
||||
return `${head} -> ${t.assignee_handle} (${t.dispatch_id ?? '?'})`
|
||||
}
|
||||
return head
|
||||
})
|
||||
.join('\n')
|
||||
return appendOrchestrationRetentionNotice(body, r, 'tasks')
|
||||
if (r.count === 0) {
|
||||
return 'No tasks.'
|
||||
}
|
||||
return r.tasks
|
||||
.map((t) => {
|
||||
const label = t.display_name ?? t.task_title ?? t.spec
|
||||
const head = `${t.id} [${t.status}] ${label.slice(0, 60)}`
|
||||
if (t.status === 'dispatched' && t.assignee_handle) {
|
||||
return `${head} -> ${t.assignee_handle} (${t.dispatch_id ?? '?'})`
|
||||
}
|
||||
return head
|
||||
})
|
||||
.join('\n')
|
||||
})
|
||||
},
|
||||
|
||||
@@ -751,18 +722,17 @@ export const ORCHESTRATION_HANDLERS: Record<string, CommandHandler> = {
|
||||
const result = await client.call<{
|
||||
gates: { id: string; task_id: string; question: string; status: string }[]
|
||||
count: number
|
||||
total?: number
|
||||
truncated?: boolean
|
||||
}>('orchestration.gateList', {
|
||||
task: getOptionalStringFlag(flags, 'task'),
|
||||
status: getOptionalStringFlag(flags, 'status')
|
||||
})
|
||||
printResult(result, json, (r) => {
|
||||
const body =
|
||||
r.gates.length === 0
|
||||
? 'No gates found.'
|
||||
: r.gates.map((g) => `${g.id} task=${g.task_id} [${g.status}] "${g.question}"`).join('\n')
|
||||
return appendOrchestrationRetentionNotice(body, r, 'gates')
|
||||
if (r.gates.length === 0) {
|
||||
return 'No gates found.'
|
||||
}
|
||||
return r.gates
|
||||
.map((g) => `${g.id} task=${g.task_id} [${g.status}] "${g.question}"`)
|
||||
.join('\n')
|
||||
})
|
||||
},
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { existsSync } from 'node:fs'
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import type { CommandHandler } from '../dispatch'
|
||||
import { RuntimeClientError } from '../runtime-client'
|
||||
@@ -18,8 +18,6 @@ import {
|
||||
runEphemeralVmRecipeStart
|
||||
} from '../../shared/ephemeral-vm-recipe-runner'
|
||||
import type { OrcaVmRecipe } from '../../shared/types'
|
||||
import { readNodeFileSyncWithinLimit } from '../../shared/node-bounded-file-reader'
|
||||
import { MAX_ORCA_YAML_BYTES } from '../../shared/orca-yaml-file-limit'
|
||||
|
||||
export const VM_HANDLERS: Record<string, CommandHandler> = {
|
||||
'vm recipe doctor': async ({ flags, cwd, json }) => {
|
||||
@@ -82,7 +80,7 @@ function doctorRecipe(repoPath: string, recipeId: string): DoctorResult {
|
||||
}
|
||||
|
||||
function readTextFile(path: string): string {
|
||||
return readNodeFileSyncWithinLimit(path, MAX_ORCA_YAML_BYTES).buffer.toString('utf8')
|
||||
return readFileSync(path, 'utf8')
|
||||
}
|
||||
|
||||
// Why: give the agent the full create/destroy output so it can self-diagnose a
|
||||
|
||||
+1
-20
@@ -1,9 +1,8 @@
|
||||
/* eslint-disable max-lines -- Why: CLI parser tests share one mocked runtime client and fixture queue; splitting this file would duplicate setup and make command coverage harder to audit. */
|
||||
import path from 'node:path'
|
||||
import { chmodSync, mkdtempSync, rmSync, truncateSync, writeFileSync, mkdirSync } from 'node:fs'
|
||||
import { chmodSync, mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { MAX_ORCA_YAML_BYTES } from '../shared/orca-yaml-file-limit'
|
||||
|
||||
const {
|
||||
callMock,
|
||||
@@ -2136,24 +2135,6 @@ describe('orca cli worktree awareness', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects an oversized sparse orca.yaml during vm recipe doctor', async () => {
|
||||
const repoPath = mkdtempSync(path.join(tmpdir(), 'orca-vm-doctor-bounds-'))
|
||||
try {
|
||||
const yamlPath = path.join(repoPath, 'orca.yaml')
|
||||
writeFileSync(yamlPath, '')
|
||||
truncateSync(yamlPath, MAX_ORCA_YAML_BYTES + 1)
|
||||
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
|
||||
|
||||
await main(['vm', 'recipe', 'doctor', 'bounded', '--repo-path', repoPath, '--json'])
|
||||
|
||||
expect(process.exitCode).toBe(1)
|
||||
expect(logSpy).toHaveBeenCalledWith(expect.stringContaining('File too large'))
|
||||
expect(callMock).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
rmSync(repoPath, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('warns when vm recipe doctor finds no cleanup hook', async () => {
|
||||
const repoPath = mkdtempSync(path.join(tmpdir(), 'orca-vm-doctor-'))
|
||||
try {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { isAbsolute, join } from 'node:path'
|
||||
import type {
|
||||
LinearIssueInclude,
|
||||
@@ -20,16 +21,6 @@ import {
|
||||
getRequiredStringFlagAllowingEmpty
|
||||
} from './flags'
|
||||
import { RuntimeClientError } from './runtime-client'
|
||||
import {
|
||||
NodeReadableTextTooLargeError,
|
||||
readNodeReadableTextWithinLimit
|
||||
} from '../shared/node-readable-text'
|
||||
import {
|
||||
NodeFileReadTooLargeError,
|
||||
readNodeFileWithinLimit
|
||||
} from '../shared/node-bounded-file-reader'
|
||||
|
||||
const LINEAR_WRITE_BODY_MAX_BYTES = LINEAR_WRITE_BODY_CAP * 4
|
||||
|
||||
const LINEAR_PRIORITY_VALUES = new Map([
|
||||
['none', 0],
|
||||
@@ -271,35 +262,14 @@ export async function readLinearBody(
|
||||
|
||||
async function readLinearBodyFile(path: string, cwd: string): Promise<string> {
|
||||
if (path !== '-') {
|
||||
try {
|
||||
const { buffer } = await readNodeFileWithinLimit(
|
||||
isAbsolute(path) ? path : join(cwd, path),
|
||||
LINEAR_WRITE_BODY_MAX_BYTES
|
||||
)
|
||||
return buffer.toString('utf8')
|
||||
} catch (error) {
|
||||
if (error instanceof NodeFileReadTooLargeError) {
|
||||
throw linearBodyTooLargeError()
|
||||
}
|
||||
throw error
|
||||
}
|
||||
return await readFile(isAbsolute(path) ? path : join(cwd, path), 'utf8')
|
||||
}
|
||||
if (process.stdin.isTTY) {
|
||||
throw new RuntimeClientError('invalid_argument', 'stdin body requested but stdin is a TTY')
|
||||
}
|
||||
try {
|
||||
return await readNodeReadableTextWithinLimit(process.stdin, LINEAR_WRITE_BODY_MAX_BYTES)
|
||||
} catch (error) {
|
||||
if (error instanceof NodeReadableTextTooLargeError) {
|
||||
throw linearBodyTooLargeError()
|
||||
}
|
||||
throw error
|
||||
const chunks: Buffer[] = []
|
||||
for await (const chunk of process.stdin) {
|
||||
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)))
|
||||
}
|
||||
}
|
||||
|
||||
function linearBodyTooLargeError(): RuntimeClientError {
|
||||
return new RuntimeClientError(
|
||||
'linear_body_too_large',
|
||||
`Linear body must be at most ${LINEAR_WRITE_BODY_CAP} characters`
|
||||
)
|
||||
return Buffer.concat(chunks).toString('utf8')
|
||||
}
|
||||
|
||||
@@ -1,77 +0,0 @@
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync, truncateSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import {
|
||||
getRuntimeMetadataPath,
|
||||
MAX_RUNTIME_METADATA_FILE_BYTES
|
||||
} from '../../shared/runtime-bootstrap'
|
||||
import {
|
||||
getServeUpdateHandoffPath,
|
||||
MAX_SERVE_UPDATE_HANDOFF_FILE_BYTES
|
||||
} from '../../shared/serve-update-handoff'
|
||||
import { readMetadata, tryReadMetadata } from './metadata'
|
||||
import {
|
||||
readServeUpdateHandoff,
|
||||
readServeUpdateHandoffSync,
|
||||
recordServeUpdateHandoffFailure
|
||||
} from './serve-update-supervisor'
|
||||
import { RuntimeClientError } from './types'
|
||||
|
||||
describe('CLI runtime control-file bounds', () => {
|
||||
const paths: string[] = []
|
||||
|
||||
afterEach(() => {
|
||||
for (const path of paths.splice(0)) {
|
||||
rmSync(path, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
function makeRoot(): string {
|
||||
const path = mkdtempSync(join(tmpdir(), 'orca-cli-control-file-bound-'))
|
||||
paths.push(path)
|
||||
return path
|
||||
}
|
||||
|
||||
it('reports oversized runtime metadata as unavailable', () => {
|
||||
const root = makeRoot()
|
||||
const metadataPath = getRuntimeMetadataPath(root)
|
||||
writeFileSync(metadataPath, '{"runtimeId":"runtime-1"}')
|
||||
truncateSync(metadataPath, MAX_RUNTIME_METADATA_FILE_BYTES + 1)
|
||||
|
||||
expect(tryReadMetadata(root)).toBeNull()
|
||||
expect(() => readMetadata(root)).toThrow(RuntimeClientError)
|
||||
})
|
||||
|
||||
it('ignores oversized serve-update handoff state in sync and async readers', async () => {
|
||||
const handoffPath = getServeUpdateHandoffPath(makeRoot())
|
||||
writeFileSync(handoffPath, '{"schemaVersion":1}')
|
||||
truncateSync(handoffPath, MAX_SERVE_UPDATE_HANDOFF_FILE_BYTES + 1)
|
||||
|
||||
expect(readServeUpdateHandoffSync(handoffPath)).toBeNull()
|
||||
await expect(readServeUpdateHandoff(handoffPath)).resolves.toBeNull()
|
||||
})
|
||||
|
||||
it('preserves the prior handoff when bounded transactional serialization fails', async () => {
|
||||
const handoffPath = getServeUpdateHandoffPath(makeRoot())
|
||||
const initial = {
|
||||
schemaVersion: 1 as const,
|
||||
phase: 'install-requested' as const,
|
||||
fromVersion: '1.0.0',
|
||||
targetVersion: '1.0.1',
|
||||
servingPid: process.pid
|
||||
}
|
||||
writeFileSync(handoffPath, JSON.stringify(initial))
|
||||
|
||||
await expect(
|
||||
recordServeUpdateHandoffFailure(
|
||||
handoffPath,
|
||||
initial,
|
||||
'x'.repeat(MAX_SERVE_UPDATE_HANDOFF_FILE_BYTES + 1)
|
||||
)
|
||||
).rejects.toThrow(`JSON output exceeds ${MAX_SERVE_UPDATE_HANDOFF_FILE_BYTES} bytes`)
|
||||
|
||||
expect(JSON.parse(readFileSync(handoffPath, 'utf8'))).toEqual(initial)
|
||||
expect(existsSync(`${handoffPath}.${process.pid}.tmp`)).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -519,33 +519,6 @@ describe('serveOrcaApp', () => {
|
||||
expect(child.unref).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('preserves recipe JSON after 100,000 one-byte fragments', async () => {
|
||||
const { child, result, stdoutSpy } = startRecipeJsonServer()
|
||||
const output = Buffer.from(`${' '.repeat(100_000)}${RECIPE_JSON}\n`)
|
||||
queueMicrotask(() => {
|
||||
for (let index = 0; index < output.byteLength; index += 1) {
|
||||
child.stdout.emit('data', output.subarray(index, index + 1))
|
||||
}
|
||||
})
|
||||
|
||||
await expect(result).resolves.toBe(0)
|
||||
expect(stdoutSpy).toHaveBeenCalledWith(`${RECIPE_JSON}\n`)
|
||||
})
|
||||
|
||||
it('kills a server that emits an oversized recipe line without a newline', async () => {
|
||||
const { child, result } = startRecipeJsonServer()
|
||||
queueMicrotask(() => {
|
||||
child.stdout.emit('data', Buffer.alloc(4 * 1024 * 1024 + 1, 0x78))
|
||||
})
|
||||
|
||||
await expect(result).rejects.toMatchObject({
|
||||
code: 'runtime_serve_failed',
|
||||
message: 'Recipe JSON output exceeded 4194304 byte line limit.'
|
||||
})
|
||||
expect(child.kill).toHaveBeenCalledWith('SIGTERM')
|
||||
expect(child.stdout.listenerCount('data')).toBe(0)
|
||||
})
|
||||
|
||||
it('rejects when the server exits without valid recipe JSON', async () => {
|
||||
const { child, result, stdoutSpy, stderrSpy } = startRecipeJsonServer()
|
||||
const secrets = ['UPPER-SECRET', 'SLASH-SECRET', 'LEGACY-SECRET', 'PRIVATE-SECRET']
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
import { spawn as spawnProcess, type SpawnOptions } from 'node:child_process'
|
||||
import { resolve } from 'node:path'
|
||||
import { StringDecoder } from 'node:string_decoder'
|
||||
import {
|
||||
SERVE_UPDATE_HANDOFF_PATH_ENV,
|
||||
getServeUpdateHandoffPath
|
||||
} from '../../shared/serve-update-handoff'
|
||||
import {
|
||||
getEphemeralVmRecipeResultConnection,
|
||||
parseEphemeralVmRecipeResult
|
||||
} from '../../shared/ephemeral-vm-recipes'
|
||||
import { getDefaultUserDataPath } from './metadata'
|
||||
import { getMacAppBundlePath } from './mac-app-update-bundle'
|
||||
import { waitForRecipeJson } from './recipe-json-output'
|
||||
import {
|
||||
readServeUpdateHandoffSync,
|
||||
resumeInterruptedServeUpdate,
|
||||
@@ -14,6 +18,8 @@ import {
|
||||
} from './serve-update-supervisor'
|
||||
import { RuntimeClientError } from './types'
|
||||
|
||||
const IGNORED_NON_RECIPE_STDOUT = '[serve] ignored non-recipe stdout'
|
||||
|
||||
export function launchOrcaApp(): void {
|
||||
const overrideCommand = process.env.ORCA_OPEN_COMMAND
|
||||
if (typeof overrideCommand === 'string' && overrideCommand.trim().length > 0) {
|
||||
@@ -159,6 +165,97 @@ export function serveOrcaApp(
|
||||
})
|
||||
}
|
||||
|
||||
function waitForRecipeJson(child: ReturnType<typeof spawnProcess>): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
let output = ''
|
||||
let settled = false
|
||||
const timeout = setTimeout(() => {
|
||||
finish(new RuntimeClientError('runtime_serve_failed', 'Timed out waiting for recipe JSON.'))
|
||||
child.kill('SIGTERM')
|
||||
}, 60000)
|
||||
const finish = (error?: Error): void => {
|
||||
if (settled) {
|
||||
return
|
||||
}
|
||||
settled = true
|
||||
clearTimeout(timeout)
|
||||
child.stdout?.off('data', onData)
|
||||
child.off('error', onError)
|
||||
child.off('close', onClose)
|
||||
if (error) {
|
||||
reject(error)
|
||||
return
|
||||
}
|
||||
child.stdout?.destroy?.()
|
||||
child.unref()
|
||||
resolve(0)
|
||||
}
|
||||
const writeIgnoredRecipeStdout = (): void => {
|
||||
// Why: non-readiness child stdout is untrusted and cannot be safely
|
||||
// redacted, including schema-valid results with arbitrary user data.
|
||||
process.stderr.write(`${IGNORED_NON_RECIPE_STDOUT}\n`)
|
||||
}
|
||||
const processRecipeOutputLine = (line: string): void => {
|
||||
const normalizedLine = line.endsWith('\r') ? line.slice(0, -1) : line
|
||||
if (!normalizedLine.trim()) {
|
||||
return
|
||||
}
|
||||
const parsed = parseEphemeralVmRecipeResult(normalizedLine)
|
||||
if (!parsed.ok) {
|
||||
writeIgnoredRecipeStdout()
|
||||
return
|
||||
}
|
||||
if (getEphemeralVmRecipeResultConnection(parsed.result).type !== 'orca-server') {
|
||||
writeIgnoredRecipeStdout()
|
||||
return
|
||||
}
|
||||
process.stdout.write(`${normalizedLine.trim()}\n`)
|
||||
finish()
|
||||
}
|
||||
const stdoutDecoder = new StringDecoder('utf8')
|
||||
const onData = (chunk: Buffer | string): void => {
|
||||
output += typeof chunk === 'string' ? chunk : stdoutDecoder.write(chunk)
|
||||
while (!settled) {
|
||||
const newlineIndex = output.indexOf('\n')
|
||||
if (newlineIndex === -1) {
|
||||
return
|
||||
}
|
||||
const line = output.slice(0, newlineIndex)
|
||||
output = output.slice(newlineIndex + 1)
|
||||
processRecipeOutputLine(line)
|
||||
}
|
||||
}
|
||||
const onError = (error: Error): void => {
|
||||
finish(error)
|
||||
}
|
||||
const onClose = (code: number | null, signal: NodeJS.Signals | null): void => {
|
||||
if (settled) {
|
||||
return
|
||||
}
|
||||
output += stdoutDecoder.end()
|
||||
if (output.trim()) {
|
||||
processRecipeOutputLine(output)
|
||||
}
|
||||
if (settled) {
|
||||
return
|
||||
}
|
||||
finish(
|
||||
new RuntimeClientError(
|
||||
'runtime_serve_failed',
|
||||
typeof code === 'number'
|
||||
? `Orca serve exited before printing valid recipe JSON with code ${code}.`
|
||||
: `Orca serve exited before printing valid recipe JSON via ${signal}.`
|
||||
)
|
||||
)
|
||||
}
|
||||
child.stdout?.on('data', onData)
|
||||
child.once('error', onError)
|
||||
// Why: `exit` can precede the final piped stdout data. `close` waits until
|
||||
// stdio closes so a last recipe chunk is not mistaken for missing output.
|
||||
child.once('close', onClose)
|
||||
})
|
||||
}
|
||||
|
||||
function getExecutableAppArgs(): string[] {
|
||||
return process.env.ORCA_APP_EXECUTABLE_NEEDS_APP_ROOT === '1' ? [resolveAppRoot()] : []
|
||||
}
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
import { mkdirSync, mkdtempSync, rmSync, truncateSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { MAC_BUNDLE_INFO_PLIST_MAX_BYTES, waitForMacBundleVersion } from './mac-app-update-bundle'
|
||||
|
||||
const roots: string[] = []
|
||||
|
||||
afterEach(() => {
|
||||
Object.defineProperty(process, 'platform', { configurable: true, value: originalPlatform })
|
||||
for (const root of roots.splice(0)) {
|
||||
rmSync(root, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
const originalPlatform = process.platform
|
||||
|
||||
describe('waitForMacBundleVersion', () => {
|
||||
it('rejects a sparse oversized Info.plist without reading its payload', async () => {
|
||||
Object.defineProperty(process, 'platform', { configurable: true, value: 'darwin' })
|
||||
const root = mkdtempSync(join(tmpdir(), 'orca-mac-bundle-bounds-'))
|
||||
roots.push(root)
|
||||
const contentsPath = join(root, 'Orca.app', 'Contents')
|
||||
const executable = join(contentsPath, 'MacOS', 'Orca')
|
||||
mkdirSync(join(contentsPath, 'MacOS'), { recursive: true })
|
||||
writeFileSync(executable, '')
|
||||
const plistPath = join(contentsPath, 'Info.plist')
|
||||
writeFileSync(plistPath, '')
|
||||
truncateSync(plistPath, MAC_BUNDLE_INFO_PLIST_MAX_BYTES + 1)
|
||||
|
||||
await expect(waitForMacBundleVersion(executable, '1.2.3', 1)).resolves.toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -1,9 +1,8 @@
|
||||
import { watch, type FSWatcher } from 'node:fs'
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { dirname, resolve } from 'node:path'
|
||||
import { readNodeFileWithinLimit } from '../../shared/node-bounded-file-reader'
|
||||
|
||||
const MAC_BUNDLE_UPDATE_TIMEOUT_MS = 120_000
|
||||
export const MAC_BUNDLE_INFO_PLIST_MAX_BYTES = 1024 * 1024
|
||||
|
||||
export function getMacAppBundlePath(executable: string): string | null {
|
||||
if (process.platform !== 'darwin') {
|
||||
@@ -79,9 +78,7 @@ export async function waitForMacBundleVersion(
|
||||
|
||||
async function readMacBundleVersion(infoPlistPath: string): Promise<string | null> {
|
||||
try {
|
||||
const plist = (
|
||||
await readNodeFileWithinLimit(infoPlistPath, MAC_BUNDLE_INFO_PLIST_MAX_BYTES)
|
||||
).buffer.toString('utf8')
|
||||
const plist = await readFile(infoPlistPath, 'utf8')
|
||||
const match = /<key>CFBundleShortVersionString<\/key>\s*<string>([^<]+)<\/string>/.exec(plist)
|
||||
return match?.[1]?.trim() || null
|
||||
} catch {
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import { homedir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { readNodeFileSyncWithinLimit } from '../../shared/node-bounded-file-reader'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import {
|
||||
findTransport,
|
||||
getRuntimeMetadataPath,
|
||||
MAX_RUNTIME_METADATA_FILE_BYTES,
|
||||
parseRuntimeMetadataJson,
|
||||
type RuntimeMetadata
|
||||
} from '../../shared/runtime-bootstrap'
|
||||
import { RuntimeClientError } from './types'
|
||||
@@ -13,11 +11,7 @@ import { RuntimeClientError } from './types'
|
||||
export function readMetadata(userDataPath: string): RuntimeMetadata {
|
||||
const metadataPath = getRuntimeMetadataPath(userDataPath)
|
||||
try {
|
||||
const metadata = parseRuntimeMetadataJson(
|
||||
readNodeFileSyncWithinLimit(metadataPath, MAX_RUNTIME_METADATA_FILE_BYTES).buffer.toString(
|
||||
'utf8'
|
||||
)
|
||||
)
|
||||
const metadata = JSON.parse(readFileSync(metadataPath, 'utf8')) as RuntimeMetadata | null
|
||||
if (!metadata || !findTransport(metadata, 'unix', 'named-pipe') || !metadata.authToken) {
|
||||
throw new RuntimeClientError(
|
||||
'runtime_unavailable',
|
||||
@@ -39,11 +33,7 @@ export function readMetadata(userDataPath: string): RuntimeMetadata {
|
||||
export function tryReadMetadata(userDataPath: string): RuntimeMetadata | null {
|
||||
const metadataPath = getRuntimeMetadataPath(userDataPath)
|
||||
try {
|
||||
return parseRuntimeMetadataJson(
|
||||
readNodeFileSyncWithinLimit(metadataPath, MAX_RUNTIME_METADATA_FILE_BYTES).buffer.toString(
|
||||
'utf8'
|
||||
)
|
||||
)
|
||||
return JSON.parse(readFileSync(metadataPath, 'utf8')) as RuntimeMetadata | null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -1,120 +0,0 @@
|
||||
import type { ChildProcess } from 'node:child_process'
|
||||
import {
|
||||
getEphemeralVmRecipeResultConnection,
|
||||
parseEphemeralVmRecipeResult
|
||||
} from '../../shared/ephemeral-vm-recipes'
|
||||
import { GrowingByteBuffer } from '../../shared/growing-byte-buffer'
|
||||
import { RuntimeClientError } from './types'
|
||||
|
||||
const IGNORED_NON_RECIPE_STDOUT = '[serve] ignored non-recipe stdout'
|
||||
const MAX_RECIPE_OUTPUT_LINE_BYTES = 4 * 1024 * 1024
|
||||
|
||||
export function waitForRecipeJson(child: ChildProcess): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const output = new GrowingByteBuffer()
|
||||
let settled = false
|
||||
const timeout = setTimeout(() => {
|
||||
finish(new RuntimeClientError('runtime_serve_failed', 'Timed out waiting for recipe JSON.'))
|
||||
child.kill('SIGTERM')
|
||||
}, 60000)
|
||||
const finish = (error?: Error): void => {
|
||||
if (settled) {
|
||||
return
|
||||
}
|
||||
settled = true
|
||||
clearTimeout(timeout)
|
||||
output.clear()
|
||||
child.stdout?.off('data', onData)
|
||||
child.off('error', onError)
|
||||
child.off('close', onClose)
|
||||
if (error) {
|
||||
reject(error)
|
||||
return
|
||||
}
|
||||
child.stdout?.destroy?.()
|
||||
child.unref()
|
||||
resolve(0)
|
||||
}
|
||||
const writeIgnoredRecipeStdout = (): void => {
|
||||
// Why: non-readiness child stdout can contain arbitrary user data.
|
||||
process.stderr.write(`${IGNORED_NON_RECIPE_STDOUT}\n`)
|
||||
}
|
||||
const processRecipeOutputLine = (line: string): void => {
|
||||
const normalizedLine = line.endsWith('\r') ? line.slice(0, -1) : line
|
||||
if (!normalizedLine.trim()) {
|
||||
return
|
||||
}
|
||||
const parsed = parseEphemeralVmRecipeResult(normalizedLine)
|
||||
if (!parsed.ok) {
|
||||
writeIgnoredRecipeStdout()
|
||||
return
|
||||
}
|
||||
if (getEphemeralVmRecipeResultConnection(parsed.result).type !== 'orca-server') {
|
||||
writeIgnoredRecipeStdout()
|
||||
return
|
||||
}
|
||||
process.stdout.write(`${normalizedLine.trim()}\n`)
|
||||
finish()
|
||||
}
|
||||
const oversizedLineError = (): RuntimeClientError =>
|
||||
new RuntimeClientError(
|
||||
'runtime_serve_failed',
|
||||
`Recipe JSON output exceeded ${MAX_RECIPE_OUTPUT_LINE_BYTES} byte line limit.`
|
||||
)
|
||||
const onData = (chunk: Buffer | string): void => {
|
||||
if (settled) {
|
||||
return
|
||||
}
|
||||
output.append(typeof chunk === 'string' ? Buffer.from(chunk) : chunk)
|
||||
while (!settled) {
|
||||
const newlineIndex = output.indexOfByte(0x0a)
|
||||
if (newlineIndex === -1) {
|
||||
break
|
||||
}
|
||||
if (newlineIndex > MAX_RECIPE_OUTPUT_LINE_BYTES) {
|
||||
finish(oversizedLineError())
|
||||
child.kill('SIGTERM')
|
||||
return
|
||||
}
|
||||
const line = output.takePrefixString(newlineIndex)
|
||||
output.discardPrefix(1)
|
||||
processRecipeOutputLine(line)
|
||||
}
|
||||
if (!settled && output.byteLength > MAX_RECIPE_OUTPUT_LINE_BYTES) {
|
||||
finish(oversizedLineError())
|
||||
child.kill('SIGTERM')
|
||||
}
|
||||
}
|
||||
const onError = (error: Error): void => {
|
||||
finish(error)
|
||||
}
|
||||
const onClose = (code: number | null, signal: NodeJS.Signals | null): void => {
|
||||
if (settled) {
|
||||
return
|
||||
}
|
||||
if (output.byteLength > MAX_RECIPE_OUTPUT_LINE_BYTES) {
|
||||
finish(oversizedLineError())
|
||||
return
|
||||
}
|
||||
const finalOutput = output.takeString()
|
||||
if (finalOutput.trim()) {
|
||||
processRecipeOutputLine(finalOutput)
|
||||
}
|
||||
if (settled) {
|
||||
return
|
||||
}
|
||||
finish(
|
||||
new RuntimeClientError(
|
||||
'runtime_serve_failed',
|
||||
typeof code === 'number'
|
||||
? `Orca serve exited before printing valid recipe JSON with code ${code}.`
|
||||
: `Orca serve exited before printing valid recipe JSON via ${signal}.`
|
||||
)
|
||||
)
|
||||
}
|
||||
child.stdout?.on('data', onData)
|
||||
child.once('error', onError)
|
||||
// Why: `close` waits for final piped stdout data that can arrive after `exit`.
|
||||
child.once('close', onClose)
|
||||
})
|
||||
}
|
||||
@@ -1,14 +1,9 @@
|
||||
import type { ChildProcess, SpawnOptions, spawn } from 'node:child_process'
|
||||
import { rename, unlink, writeFile } from 'node:fs/promises'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { readFile, rename, unlink, writeFile } from 'node:fs/promises'
|
||||
import {
|
||||
readNodeFileSyncWithinLimit,
|
||||
readNodeFileWithinLimit
|
||||
} from '../../shared/node-bounded-file-reader'
|
||||
import { stringifyJsonWithinByteLimit } from '../../shared/node-bounded-json-stringify'
|
||||
import {
|
||||
MAX_SERVE_UPDATE_HANDOFF_FILE_BYTES,
|
||||
parseServeUpdateHandoffJson,
|
||||
parseServeSupervisorMessage,
|
||||
parseServeUpdateHandoffState,
|
||||
type ServeUpdateHandoffState
|
||||
} from '../../shared/serve-update-handoff'
|
||||
import { RuntimeClientError } from './types'
|
||||
@@ -218,11 +213,7 @@ export async function readServeUpdateHandoff(
|
||||
handoffPath: string
|
||||
): Promise<ServeUpdateHandoffState | null> {
|
||||
try {
|
||||
const { buffer } = await readNodeFileWithinLimit(
|
||||
handoffPath,
|
||||
MAX_SERVE_UPDATE_HANDOFF_FILE_BYTES
|
||||
)
|
||||
return parseServeUpdateHandoffJson(buffer.toString('utf8'))
|
||||
return parseServeUpdateHandoffState(JSON.parse(await readFile(handoffPath, 'utf8')))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
@@ -230,8 +221,7 @@ export async function readServeUpdateHandoff(
|
||||
|
||||
export function readServeUpdateHandoffSync(handoffPath: string): ServeUpdateHandoffState | null {
|
||||
try {
|
||||
const { buffer } = readNodeFileSyncWithinLimit(handoffPath, MAX_SERVE_UPDATE_HANDOFF_FILE_BYTES)
|
||||
return parseServeUpdateHandoffJson(buffer.toString('utf8'))
|
||||
return parseServeUpdateHandoffState(JSON.parse(readFileSync(handoffPath, 'utf8')))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
@@ -269,12 +259,6 @@ async function writeServeUpdateHandoffState(
|
||||
state: ServeUpdateHandoffState
|
||||
): Promise<void> {
|
||||
const temporaryPath = `${handoffPath}.${process.pid}.tmp`
|
||||
try {
|
||||
const { serialized } = stringifyJsonWithinByteLimit(state, MAX_SERVE_UPDATE_HANDOFF_FILE_BYTES)
|
||||
await writeFile(temporaryPath, serialized, { mode: 0o600 })
|
||||
await rename(temporaryPath, handoffPath)
|
||||
} catch (error) {
|
||||
await unlink(temporaryPath).catch(() => undefined)
|
||||
throw error
|
||||
}
|
||||
await writeFile(temporaryPath, JSON.stringify(state), { mode: 0o600 })
|
||||
await rename(temporaryPath, handoffPath)
|
||||
}
|
||||
|
||||
@@ -2,9 +2,9 @@ import { mkdtempSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { createServer, type Socket } from 'node:net'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import type { RuntimeMetadata } from '../../shared/runtime-bootstrap'
|
||||
import { CLI_RUNTIME_JSON_STRUCTURE_LIMITS, sendRequest } from './transport'
|
||||
import { sendRequest } from './transport'
|
||||
|
||||
const servers = new Set<ReturnType<typeof createServer>>()
|
||||
const sockets = new Set<Socket>()
|
||||
@@ -114,36 +114,4 @@ describe.skipIf(process.platform === 'win32')('runtime transport', () => {
|
||||
})
|
||||
expect(Date.now() - start).toBeLessThan(5000)
|
||||
})
|
||||
|
||||
it('rejects excessive response nesting before JSON.parse', async () => {
|
||||
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-transport-'))
|
||||
const endpoint = join(userDataPath, 'runtime.sock')
|
||||
const server = createServer((socket) => {
|
||||
sockets.add(socket)
|
||||
socket.once('close', () => sockets.delete(socket))
|
||||
socket.once('data', () => {
|
||||
const depth = CLI_RUNTIME_JSON_STRUCTURE_LIMITS.nestingDepth + 1
|
||||
socket.write(`${'['.repeat(depth)}0${']'.repeat(depth)}\n`)
|
||||
})
|
||||
})
|
||||
servers.add(server)
|
||||
await new Promise<void>((resolve) => server.listen(endpoint, resolve))
|
||||
const parseSpy = vi.spyOn(JSON, 'parse')
|
||||
const metadata: RuntimeMetadata = {
|
||||
runtimeId: 'runtime-1',
|
||||
pid: 123,
|
||||
transports: [{ kind: 'unix', endpoint }],
|
||||
authToken: 'token',
|
||||
startedAt: 1
|
||||
}
|
||||
|
||||
try {
|
||||
await expect(sendRequest(metadata, 'status.get', undefined, 1000)).rejects.toMatchObject({
|
||||
code: 'invalid_runtime_response'
|
||||
})
|
||||
expect(parseSpy).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
parseSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,17 +1,9 @@
|
||||
import { createConnection } from 'node:net'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { GrowingByteBuffer } from '../../shared/growing-byte-buffer'
|
||||
import { assertJsonTextStructureWithinLimits } from '../../shared/json-text-structure-limit'
|
||||
import { findTransport, type RuntimeMetadata } from '../../shared/runtime-bootstrap'
|
||||
import { isKeepaliveFrame, RuntimeRpcEnvelopeSchema } from './envelope-schema'
|
||||
import { RuntimeClientError, type RuntimeRpcResponse } from './types'
|
||||
|
||||
const MAX_RUNTIME_RESPONSE_LINE_BYTES = 64 * 1024 * 1024
|
||||
export const CLI_RUNTIME_JSON_STRUCTURE_LIMITS = {
|
||||
structuralTokens: 1_000_000,
|
||||
nestingDepth: 128
|
||||
} as const
|
||||
|
||||
export async function sendRequest<TResult>(
|
||||
metadata: RuntimeMetadata,
|
||||
method: string,
|
||||
@@ -30,7 +22,7 @@ export async function sendRequest<TResult>(
|
||||
return
|
||||
}
|
||||
const socket = createConnection(transport.endpoint)
|
||||
const buffer = new GrowingByteBuffer()
|
||||
let buffer = ''
|
||||
let settled = false
|
||||
const requestId = randomUUID()
|
||||
|
||||
@@ -56,16 +48,15 @@ export async function sendRequest<TResult>(
|
||||
}
|
||||
settled = true
|
||||
clearTimeout(timeout)
|
||||
buffer.clear()
|
||||
socket.end()
|
||||
if (result.ok === false) {
|
||||
socket.destroy()
|
||||
reject(result.error)
|
||||
} else {
|
||||
socket.end()
|
||||
resolve(result.response)
|
||||
}
|
||||
}
|
||||
|
||||
socket.setEncoding('utf8')
|
||||
socket.once('error', () => {
|
||||
finish({
|
||||
ok: false,
|
||||
@@ -88,39 +79,24 @@ export async function sendRequest<TResult>(
|
||||
)
|
||||
})
|
||||
})
|
||||
socket.on('data', (chunk: Buffer) => {
|
||||
if (settled) {
|
||||
return
|
||||
}
|
||||
buffer.append(chunk)
|
||||
socket.on('data', (chunk) => {
|
||||
buffer += chunk
|
||||
// Why: the server may interleave `{"_keepalive":true}\n` frames with the
|
||||
// final success/failure frame to keep both idle timers alive during a
|
||||
// long-poll (see design doc §3.1). Read frames in a loop until we see a
|
||||
// terminal frame. Each keepalive refreshes the client-side timer so a
|
||||
// 10 min wait doesn't trip the 60 s default ceiling.
|
||||
let newlineIndex = buffer.indexOfByte(0x0a)
|
||||
let newlineIndex = buffer.indexOf('\n')
|
||||
while (newlineIndex !== -1 && !settled) {
|
||||
const lineBytes = newlineIndex
|
||||
if (lineBytes > MAX_RUNTIME_RESPONSE_LINE_BYTES) {
|
||||
finish({
|
||||
ok: false,
|
||||
error: new RuntimeClientError(
|
||||
'invalid_runtime_response',
|
||||
`The Orca runtime response exceeded the ${MAX_RUNTIME_RESPONSE_LINE_BYTES} byte frame limit.`
|
||||
)
|
||||
})
|
||||
return
|
||||
}
|
||||
const line = buffer.takePrefixString(lineBytes)
|
||||
buffer.discardPrefix(1)
|
||||
const line = buffer.slice(0, newlineIndex)
|
||||
buffer = buffer.slice(newlineIndex + 1)
|
||||
if (line.trim().length === 0) {
|
||||
newlineIndex = buffer.indexOfByte(0x0a)
|
||||
newlineIndex = buffer.indexOf('\n')
|
||||
continue
|
||||
}
|
||||
|
||||
let raw: unknown
|
||||
try {
|
||||
assertJsonTextStructureWithinLimits(line, CLI_RUNTIME_JSON_STRUCTURE_LIMITS)
|
||||
raw = JSON.parse(line)
|
||||
} catch {
|
||||
finish({
|
||||
@@ -139,7 +115,7 @@ export async function sendRequest<TResult>(
|
||||
// major). See §7 risk #9.
|
||||
if (isKeepaliveFrame(raw)) {
|
||||
timeout.refresh()
|
||||
newlineIndex = buffer.indexOfByte(0x0a)
|
||||
newlineIndex = buffer.indexOf('\n')
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -165,7 +141,7 @@ export async function sendRequest<TResult>(
|
||||
const frame = parsed.data
|
||||
if ('_keepalive' in frame) {
|
||||
timeout.refresh()
|
||||
newlineIndex = buffer.indexOfByte(0x0a)
|
||||
newlineIndex = buffer.indexOf('\n')
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -193,15 +169,6 @@ export async function sendRequest<TResult>(
|
||||
finish({ ok: true, response })
|
||||
return
|
||||
}
|
||||
if (buffer.byteLength > MAX_RUNTIME_RESPONSE_LINE_BYTES) {
|
||||
finish({
|
||||
ok: false,
|
||||
error: new RuntimeClientError(
|
||||
'invalid_runtime_response',
|
||||
`The Orca runtime response exceeded the ${MAX_RUNTIME_RESPONSE_LINE_BYTES} byte frame limit.`
|
||||
)
|
||||
})
|
||||
}
|
||||
})
|
||||
socket.on('connect', () => {
|
||||
socket.write(
|
||||
|
||||
Reference in New Issue
Block a user