mirror of
https://github.com/stablyai/orca.git
synced 2026-11-18 11:54:46 +00:00
fix(agent-hooks): skip Orca's hook scripts outside Orca panes (#43081)
* fix(agent-hooks): skip managed hook scripts outside Orca panes Co-authored-by: Pr1p <zwq19980411@gmail.com> * test(gemini): drop type assertion in hook command test --------- Co-authored-by: Pr1p <zwq19980411@gmail.com>
This commit is contained in:
@@ -1,15 +1,20 @@
|
||||
import { quotePosixShell } from '../../../../shared/shell/launch/shell-argument-quoting'
|
||||
import { ORCA_SCRUB_SAFE_PANE_ENV } from '../../../../shared/agent-hook-listener/transport/agent-hook-scrub-safe-env'
|
||||
import {
|
||||
POSIX_HOOK_STDIN_BACKGROUND_DRAIN_COMMAND,
|
||||
POSIX_HOOK_STDIN_DRAIN_COMMAND
|
||||
} from '../scripts/hook-stdin-contract'
|
||||
|
||||
// Global hooks also fire outside Orca, where only the drain runs; the alias covers agents that scrub the key.
|
||||
// Default-form variables survive Grok prechecks.
|
||||
export const POSIX_ORCA_PANE_GUARD = `[ -n "\${ORCA_PANE_KEY-}\${${ORCA_SCRUB_SAFE_PANE_ENV}-}" ]`
|
||||
|
||||
// Missing scripts must become silent no-ops rather than fail every tool call.
|
||||
export function wrapPosixHookCommand(
|
||||
scriptPath: string,
|
||||
env: Record<string, string> = {},
|
||||
// Gate events treat silence as denial, so missing scripts may need fallback stdout.
|
||||
options: { fallbackStdout?: string; requiredEnvVar?: string; stdinMayStayOpen?: boolean } = {}
|
||||
options: { fallbackStdout?: string; skipPaneGuard?: boolean; stdinMayStayOpen?: boolean } = {}
|
||||
): string {
|
||||
// Keep arbitrary paths literal across shell metacharacters.
|
||||
const quoted = quotePosixShell(scriptPath)
|
||||
@@ -24,9 +29,8 @@ export function wrapPosixHookCommand(
|
||||
options.fallbackStdout === undefined
|
||||
? drain
|
||||
: `printf '%s\\n' ${quotePosixShell(options.fallbackStdout)}; ${drain}`
|
||||
// Default-form variables survive Grok prechecks and defer environment reads to invocation.
|
||||
const guards = [
|
||||
...(options.requiredEnvVar ? [`[ -n "\${${options.requiredEnvVar}-}" ]`] : []),
|
||||
...(options.skipPaneGuard ? [] : [POSIX_ORCA_PANE_GUARD]),
|
||||
`[ -f ${quoted} ]`,
|
||||
`[ -r ${quoted} ]`,
|
||||
`[ -x ${quoted} ]`
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
encodeWindowsPowerShellHookCommand,
|
||||
WINDOWS_POWERSHELL_HOOK_SWITCHES
|
||||
} from './windows-powershell-hook-launcher'
|
||||
import { POSIX_ORCA_PANE_GUARD } from './posix-hook-command'
|
||||
|
||||
const MANAGED_SCRIPT_BASE_NAME = /^[A-Za-z0-9_-]+$/
|
||||
const WINDOWS_GIT_BASH_RUNTIME_HOME_UNSAFE = '*\\&*|*\\^*|*\\(*|*\\)*|*\\;*|*,*|*=*|*%*|*\\!*'
|
||||
@@ -21,17 +22,19 @@ function assertManagedScriptBaseName(scriptBaseName: string): void {
|
||||
function buildPosixBranch(
|
||||
scriptBaseName: string,
|
||||
missingScriptFallback: string,
|
||||
options: { requireHome?: boolean } = {}
|
||||
options: { requireHome?: boolean; requirePane?: boolean } = {}
|
||||
): string {
|
||||
const posixScript = `"\${HOME-}/.orca/agent-hooks/${scriptBaseName}.sh"`
|
||||
const homeGuard = options.requireHome ? '[ -n "${HOME-}" ] && ' : ''
|
||||
const paneGuard = options.requirePane ? `${POSIX_ORCA_PANE_GUARD} && ` : ''
|
||||
const parentCapture =
|
||||
scriptBaseName === 'claude-hook' || scriptBaseName === 'openclaude-hook'
|
||||
? HOOK_PARENT_CAPTURE
|
||||
: ''
|
||||
return `if ${homeGuard}[ -f ${posixScript} ] && [ -r ${posixScript} ] && [ -x ${posixScript} ]; then ${parentCapture}/bin/sh ${posixScript}; else ${missingScriptFallback}; fi`
|
||||
return `if ${paneGuard}${homeGuard}[ -f ${posixScript} ] && [ -r ${posixScript} ] && [ -x ${posixScript} ]; then ${parentCapture}/bin/sh ${posixScript}; else ${missingScriptFallback}; fi`
|
||||
}
|
||||
|
||||
// Claude echoes this command after /compact and the event is rare, so it stays short and unguarded.
|
||||
export function wrapRuntimeHomePosixHookCommand(scriptBaseName: string): string {
|
||||
assertManagedScriptBaseName(scriptBaseName)
|
||||
return buildPosixBranch(scriptBaseName, POSIX_HOOK_STDIN_DRAIN_COMMAND, { requireHome: true })
|
||||
@@ -63,7 +66,9 @@ export function wrapRuntimeHomeHookCommand(
|
||||
const powershellInvocation = `${powershell} ${WINDOWS_POWERSHELL_HOOK_SWITCHES} -EncodedCommand ${encodedCommand}`
|
||||
const encodedWindowsBranch = `if [ -f ${powershell} ]; then ${powershellInvocation}; else ${windowsMissingScriptFallback}; fi`
|
||||
const windowsBranch = `if [ -f ${windowsScript} ]; then case "\${HOME-}" in ${WINDOWS_GIT_BASH_RUNTIME_HOME_UNSAFE}) ${encodedWindowsBranch} ;; *) ${windowsScript} ;; esac; else ${windowsMissingScriptFallback}; fi`
|
||||
const posixBranch = buildPosixBranch(scriptBaseName, posixMissingScriptFallback)
|
||||
const posixBranch = buildPosixBranch(scriptBaseName, posixMissingScriptFallback, {
|
||||
requirePane: true
|
||||
})
|
||||
// Shell-owned OSTYPE avoids spawning a process for each platform check.
|
||||
return `if [ -z "\${HOME-}" ]; then ${missingScriptFallback}; else case "\${OSTYPE-}" in msys*|cygwin*|win32*) ${windowsBranch} ;; *) ${posixBranch} ;; esac; fi`
|
||||
}
|
||||
|
||||
@@ -99,6 +99,8 @@ describe('writeHooksJson', () => {
|
||||
})
|
||||
})
|
||||
|
||||
const paneEnv = { ...process.env, ORCA_PANE_KEY: 'tab-1:leaf-1' }
|
||||
|
||||
describe('wrapPosixHookCommand', () => {
|
||||
it.skipIf(process.platform === 'win32')(
|
||||
'executes a script whose path contains a single quote literally',
|
||||
@@ -109,6 +111,7 @@ describe('wrapPosixHookCommand', () => {
|
||||
const result = runProcessSync({
|
||||
program: '/bin/sh',
|
||||
args: ['-c', wrapPosixHookCommand(scriptPath)],
|
||||
env: paneEnv,
|
||||
timeoutMs: 5000
|
||||
})
|
||||
expect(result.code).toBe(0)
|
||||
@@ -129,7 +132,7 @@ describe('wrapPosixHookCommand', () => {
|
||||
const result = runProcessSync({
|
||||
program: '/bin/sh',
|
||||
args: ['-c', `${command}; printf '\n%s' "$ORCA_COPILOT_HOOK_EVENT"`],
|
||||
env: { ...process.env, ORCA_COPILOT_HOOK_EVENT: 'parent-value' },
|
||||
env: { ...paneEnv, ORCA_COPILOT_HOOK_EVENT: 'parent-value' },
|
||||
timeoutMs: 5000
|
||||
})
|
||||
expect(result.code).toBe(0)
|
||||
@@ -161,7 +164,12 @@ describe('wrapPosixHookCommand', () => {
|
||||
writeFileSync(scriptPath, '#!/bin/sh\nexit 7\n', 'utf-8')
|
||||
chmodSync(scriptPath, 0o755)
|
||||
const cmd = wrapPosixHookCommand(scriptPath)
|
||||
const result = runProcessSync({ program: '/bin/sh', args: ['-c', cmd], timeoutMs: 5000 })
|
||||
const result = runProcessSync({
|
||||
program: '/bin/sh',
|
||||
args: ['-c', cmd],
|
||||
env: paneEnv,
|
||||
timeoutMs: 5000
|
||||
})
|
||||
expect(result.code).toBe(7)
|
||||
}
|
||||
)
|
||||
@@ -225,7 +233,7 @@ describe('wrapRuntimeHomeHookCommand', () => {
|
||||
program: shell,
|
||||
args: ['-c', wrapRuntimeHomeHookCommand('claude-hook')],
|
||||
env: {
|
||||
...process.env,
|
||||
...paneEnv,
|
||||
HOME: destinationHome.replaceAll('\\', '/'),
|
||||
USERPROFILE: destinationHome
|
||||
},
|
||||
|
||||
@@ -56,12 +56,7 @@ function getPosixManagedCommand(scriptPath: string, event: AntigravityEvent): st
|
||||
const command = wrapPosixHookCommand(
|
||||
scriptPath,
|
||||
{ ORCA_ANTIGRAVITY_EVENT: event.eventName },
|
||||
// Outside an Orca pane, skip the script's shell and python3 start on every agy event.
|
||||
{
|
||||
fallbackStdout: getAntigravityNoOpStdout(event.eventName),
|
||||
requiredEnvVar: 'ORCA_PANE_KEY',
|
||||
stdinMayStayOpen: true
|
||||
}
|
||||
{ fallbackStdout: getAntigravityNoOpStdout(event.eventName), stdinMayStayOpen: true }
|
||||
)
|
||||
// ACP hosts tokenize the command into argv; the shell must be the executable, not `if`.
|
||||
return `/bin/sh -c ${quotePosixShell(`${HOOK_PARENT_CAPTURE}${command}`)}`
|
||||
|
||||
@@ -190,7 +190,7 @@ describe.skipIf(process.platform === 'win32')('Antigravity POSIX hook executable
|
||||
join(home, '.orca', 'agent-hooks', 'antigravity-hook.sh'),
|
||||
`#!/bin/sh\n: > ${quotePosixShell(marker)}\n`
|
||||
)
|
||||
const { ORCA_PANE_KEY: _paneKey, ...outsideEnv } = process.env
|
||||
const { ORCA_PANE_KEY: _paneKey, ORCA_AGENT_PANE: _paneAlias, ...outsideEnv } = process.env
|
||||
const result = await invoke(command, '{"tool_name":"run_command"}', outsideEnv)
|
||||
expect(result.code).toBe(0)
|
||||
expect(result.stdout).toBe(expectedStdout)
|
||||
|
||||
@@ -54,7 +54,12 @@ function getManagedScriptPath(): string {
|
||||
function getManagedCommand(scriptPath: string): string {
|
||||
return process.platform === 'win32'
|
||||
? wrapWindowsBatchHookCommand(scriptPath)
|
||||
: wrapPosixHookCommand(scriptPath)
|
||||
: getPosixManagedCommand(scriptPath)
|
||||
}
|
||||
|
||||
// Command Code scrubs hook env; its script recovers the pane from ancestor processes.
|
||||
function getPosixManagedCommand(scriptPath: string): string {
|
||||
return wrapPosixHookCommand(scriptPath, {}, { skipPaneGuard: true })
|
||||
}
|
||||
|
||||
function buildInstalledConfig(
|
||||
@@ -180,7 +185,7 @@ export class CommandCodeHookService {
|
||||
}
|
||||
}
|
||||
|
||||
buildInstalledConfig(config, wrapPosixHookCommand(remoteScriptPath), 'command-code-hook.sh')
|
||||
buildInstalledConfig(config, getPosixManagedCommand(remoteScriptPath), 'command-code-hook.sh')
|
||||
await writeManagedScriptRemote(sftp, remoteScriptPath, buildCommandCodeManagedScript('posix'))
|
||||
await writeHooksJsonRemote(sftp, remoteConfigPath, config)
|
||||
|
||||
|
||||
@@ -22,9 +22,18 @@ export const COPILOT_EVENTS = [
|
||||
'Notification'
|
||||
] as const
|
||||
|
||||
// The script answers {} before any guard, so the skipped-script path answers the same.
|
||||
export function getPosixManagedCommand(scriptPath: string, eventName: string): string {
|
||||
return wrapPosixHookCommand(
|
||||
scriptPath,
|
||||
{ ORCA_COPILOT_HOOK_EVENT: eventName },
|
||||
{ fallbackStdout: '{}' }
|
||||
)
|
||||
}
|
||||
|
||||
export function getManagedCommand(scriptPath: string, eventName: string): string {
|
||||
if (process.platform !== 'win32') {
|
||||
return wrapPosixHookCommand(scriptPath, { ORCA_COPILOT_HOOK_EVENT: eventName })
|
||||
return getPosixManagedCommand(scriptPath, eventName)
|
||||
}
|
||||
// Arguments survive runners that ignore hook env maps and keep managed commands distinct per event.
|
||||
const direct = wrapWindowsDirectCmdHookCommand(scriptPath)
|
||||
|
||||
@@ -4,14 +4,13 @@ import {
|
||||
createManagedCommandMatcher,
|
||||
removeManagedCommands
|
||||
} from '../agent-hooks/installation/commands/managed-hook-command-matching'
|
||||
import { wrapPosixHookCommand } from '../agent-hooks/installation/commands/posix-hook-command'
|
||||
import type { HookDefinition } from '../agent-hooks/installation/configuration/hook-config-schema'
|
||||
import {
|
||||
readHooksJsonRemote,
|
||||
writeHooksJsonRemote
|
||||
} from '../agent-hooks/installation/configuration/hooks-json-remote'
|
||||
import { writeManagedScriptRemote } from '../agent-hooks/installation/scripts/managed-script-write-remote'
|
||||
import { COPILOT_EVENTS } from './copilot-managed-hook-definitions'
|
||||
import { COPILOT_EVENTS, getPosixManagedCommand } from './copilot-managed-hook-definitions'
|
||||
import { getManagedScript } from './copilot-managed-script'
|
||||
|
||||
function getRemoteManagedHookDefinition(command: string): HookDefinition {
|
||||
@@ -59,9 +58,7 @@ export async function installCopilotHooksRemote(
|
||||
const cleaned = removeManagedCommands(current, isManagedCommand)
|
||||
nextHooks[eventName] = [
|
||||
...cleaned,
|
||||
getRemoteManagedHookDefinition(
|
||||
wrapPosixHookCommand(remoteScriptPath, { ORCA_COPILOT_HOOK_EVENT: eventName })
|
||||
)
|
||||
getRemoteManagedHookDefinition(getPosixManagedCommand(remoteScriptPath, eventName))
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
@@ -74,7 +74,7 @@ describe.skipIf(process.platform === 'win32')('local Cursor hooks through login
|
||||
ORCA_AGENT_HOOK_ENDPOINT: '',
|
||||
ORCA_AGENT_HOOK_PORT: '',
|
||||
ORCA_AGENT_HOOK_TOKEN: '',
|
||||
ORCA_PANE_KEY: '',
|
||||
ORCA_PANE_KEY: 'tab-1:leaf-1',
|
||||
ORCA_TEST_EXPAND: 'expanded',
|
||||
ORCA_TEST_LITERAL: hostileLiteral,
|
||||
HOME: fixture,
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import type * as OsModule from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { GeminiHookService } from './hook-service'
|
||||
|
||||
const { homeMock } = vi.hoisted(() => ({ homeMock: vi.fn<() => string>() }))
|
||||
vi.mock('node:os', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof OsModule>()),
|
||||
homedir: homeMock
|
||||
}))
|
||||
|
||||
let home = ''
|
||||
|
||||
beforeEach(() => {
|
||||
home = mkdtempSync(join(tmpdir(), 'orca-gemini-hook-'))
|
||||
homeMock.mockReturnValue(home)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
rmSync(home, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
function installedAfterAgentCommand(): string {
|
||||
expect(new GeminiHookService().install().state).toBe('installed')
|
||||
const settings: { hooks: Record<string, { hooks: { command: string }[] }[]> } = JSON.parse(
|
||||
readFileSync(join(home, '.gemini', 'settings.json'), 'utf8')
|
||||
)
|
||||
return settings.hooks.AfterAgent[0].hooks[0].command
|
||||
}
|
||||
|
||||
function runHook(command: string, paneEnv: NodeJS.ProcessEnv) {
|
||||
const env: NodeJS.ProcessEnv = { PATH: '/usr/bin:/bin', HOME: home, ...paneEnv }
|
||||
return spawnSync('/bin/sh', ['-c', command], {
|
||||
env,
|
||||
input: '{"hook_event_name":"AfterAgent"}',
|
||||
encoding: 'utf8',
|
||||
timeout: 5000
|
||||
})
|
||||
}
|
||||
|
||||
describe.skipIf(process.platform === 'win32')('Gemini installed hook command', () => {
|
||||
it('skips the managed script outside an Orca pane and runs it inside one', () => {
|
||||
const command = installedAfterAgentCommand()
|
||||
const marker = join(home, 'script-ran')
|
||||
writeFileSync(
|
||||
join(home, '.orca', 'agent-hooks', 'gemini-hook.sh'),
|
||||
`#!/bin/sh\ncat >/dev/null\n: > '${marker}'\nprintf '{}\\n'\n`
|
||||
)
|
||||
|
||||
const outside = runHook(command, {})
|
||||
expect(outside.status).toBe(0)
|
||||
expect(outside.stdout).toBe('{}\n')
|
||||
expect(existsSync(marker)).toBe(false)
|
||||
|
||||
const inside = runHook(command, { ORCA_PANE_KEY: 'tab-1:leaf-1' })
|
||||
expect(inside.status).toBe(0)
|
||||
expect(existsSync(marker)).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -53,7 +53,12 @@ function getManagedScriptPath(): string {
|
||||
function getManagedCommand(scriptPath: string): string {
|
||||
return process.platform === 'win32'
|
||||
? wrapWindowsBatchHookCommand(scriptPath)
|
||||
: wrapPosixHookCommand(scriptPath)
|
||||
: getPosixManagedCommand(scriptPath)
|
||||
}
|
||||
|
||||
// The script answers {} before any guard, so the skipped-script path answers the same.
|
||||
function getPosixManagedCommand(scriptPath: string): string {
|
||||
return wrapPosixHookCommand(scriptPath, {}, { fallbackStdout: '{}' })
|
||||
}
|
||||
|
||||
function getManagedScript(target: 'local' | 'posix' = 'local'): string {
|
||||
@@ -221,7 +226,7 @@ export class GeminiHookService {
|
||||
}
|
||||
}
|
||||
|
||||
const command = wrapPosixHookCommand(remoteScriptPath)
|
||||
const command = getPosixManagedCommand(remoteScriptPath)
|
||||
const nextHooks = { ...config.hooks }
|
||||
const isManagedCommand = createManagedCommandMatcher('gemini-hook.sh')
|
||||
const managedEvents = new Set<string>(GEMINI_EVENTS)
|
||||
|
||||
@@ -53,11 +53,7 @@ export async function installRemoteGrokHook(
|
||||
if (!config) {
|
||||
return status(configPath, 'Could not parse remote Grok hook config')
|
||||
}
|
||||
buildInstalledGrokConfig(
|
||||
config,
|
||||
wrapPosixHookCommand(scriptPath, {}, { requiredEnvVar: 'ORCA_PANE_KEY' }),
|
||||
'grok-hook.sh'
|
||||
)
|
||||
buildInstalledGrokConfig(config, wrapPosixHookCommand(scriptPath), 'grok-hook.sh')
|
||||
await writeManagedScriptRemote(sftp, scriptPath, script)
|
||||
await writeHooksJsonRemote(sftp, configPath, config)
|
||||
return {
|
||||
|
||||
@@ -21,10 +21,9 @@ export function getGrokManagedScriptPath(): string {
|
||||
}
|
||||
|
||||
export function getGrokManagedCommand(scriptPath: string): string {
|
||||
// POSIX can gate before spawning because Orca injects ORCA_PANE_KEY only into panes it owns.
|
||||
return process.platform === 'win32'
|
||||
? wrapWindowsBatchHookCommand(scriptPath)
|
||||
: wrapPosixHookCommand(scriptPath, {}, { requiredEnvVar: 'ORCA_PANE_KEY' })
|
||||
: wrapPosixHookCommand(scriptPath)
|
||||
}
|
||||
|
||||
export function getGrokManagedScript(target: 'local' | 'posix' = 'local'): string {
|
||||
|
||||
Reference in New Issue
Block a user