开源 企业版 高校版 私有云 模力方舟 AI 队友
代码拉取完成,页面将自动刷新
加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
已有帐号? 立即登录
文件
main
分支 (5)
标签 (3)
main
feature/v6
test/test-most-core-func
version/i18n/zh-cn
feature/prod
v3
v2
v1
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
项目仓库所选许可证以仓库主分支所使用许可证为准
main
分支 (5)
标签 (3)
main
feature/v6
test/test-most-core-func
version/i18n/zh-cn
feature/prod
v3
v2
v1
克隆/下载
克隆/下载
提示
下载代码请复制以下命令到终端执行
为确保你提交的代码身份被 Gitee 正确识别,请执行以下命令完成配置
初次使用 SSH 协议进行代码克隆、推送等操作时,需按下述提示完成 SSH 配置
1 生成 RSA 密钥
2 获取 RSA 公钥内容,并配置到 SSH公钥
在 Gitee 上使用 SVN,请访问 使用指南
使用 HTTPS 协议时,命令行会出现如下账号密码验证步骤。基于安全考虑,Gitee 建议 配置并使用私人令牌 替代登录密码进行克隆、推送等操作
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # 私人令牌
main
分支 (5)
标签 (3)
main
feature/v6
test/test-most-core-func
version/i18n/zh-cn
feature/prod
v3
v2
v1
claude-code
/
src
/
utils
/
Shell.ts
claude-code
/
src
/
utils
/
Shell.ts
Shell.ts 16.53 KB
一键复制 编辑 原始数据 按行查看 历史
claude-code-best 提交于 2026年03月31日 19:22 +08:00 . feat: build
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
import { execFileSync, spawn } from 'child_process'
import { constants as fsConstants, readFileSync, unlinkSync } from 'fs'
import { type FileHandle, mkdir, open, realpath } from 'fs/promises'
import memoize from 'lodash-es/memoize.js'
import { isAbsolute, resolve } from 'path'
import { join as posixJoin } from 'path/posix'
import { logEvent } from 'src/services/analytics/index.js'
import {
getOriginalCwd,
getSessionId,
setCwdState,
} from '../bootstrap/state.js'
import { generateTaskId } from '../Task.js'
import { pwd } from './cwd.js'
import { logForDebugging } from './debug.js'
import { errorMessage, isENOENT } from './errors.js'
import { getFsImplementation } from './fsOperations.js'
import { logError } from './log.js'
import {
createAbortedCommand,
createFailedCommand,
type ShellCommand,
wrapSpawn,
} from './ShellCommand.js'
import { getTaskOutputDir } from './task/diskOutput.js'
import { TaskOutput } from './task/TaskOutput.js'
import { which } from './which.js'
export type { ExecResult } from './ShellCommand.js'
import { accessSync } from 'fs'
import { onCwdChangedForHooks } from './hooks/fileChangedWatcher.js'
import { getClaudeTempDirName } from './permissions/filesystem.js'
import { getPlatform } from './platform.js'
import { SandboxManager } from './sandbox/sandbox-adapter.js'
import { invalidateSessionEnvCache } from './sessionEnvironment.js'
import { createBashShellProvider } from './shell/bashProvider.js'
import { getCachedPowerShellPath } from './shell/powershellDetection.js'
import { createPowerShellProvider } from './shell/powershellProvider.js'
import type { ShellProvider, ShellType } from './shell/shellProvider.js'
import { subprocessEnv } from './subprocessEnv.js'
import { posixPathToWindowsPath } from './windowsPaths.js'
const DEFAULT_TIMEOUT = 30 * 60 * 1000 // 30 minutes
export type ShellConfig = {
provider: ShellProvider
}
function isExecutable(shellPath: string): boolean {
try {
accessSync(shellPath, fsConstants.X_OK)
return true
} catch (_err) {
// Fallback for Nix and other environments where X_OK check might fail
try {
// Try to execute the shell with --version, which should exit quickly
// Use execFileSync to avoid shell injection vulnerabilities
execFileSync(shellPath, ['--version'], {
timeout: 1000,
stdio: 'ignore',
})
return true
} catch {
return false
}
}
}
/**
* Determines the best available shell to use.
*/
export async function findSuitableShell(): Promise<string> {
// Check for explicit shell override first
const shellOverride = process.env.CLAUDE_CODE_SHELL
if (shellOverride) {
// Validate it's a supported shell type
const isSupported =
shellOverride.includes('bash') || shellOverride.includes('zsh')
if (isSupported && isExecutable(shellOverride)) {
logForDebugging(`Using shell override: ${shellOverride}`)
return shellOverride
} else {
// Note, if we ever want to add support for new shells here we'll need to update or Bash tool parsing to account for this
logForDebugging(
`CLAUDE_CODE_SHELL="${shellOverride}" is not a valid bash/zsh path, falling back to detection`,
)
}
}
// Check user's preferred shell from environment
const env_shell = process.env.SHELL
// Only consider SHELL if it's bash or zsh
const isEnvShellSupported =
env_shell && (env_shell.includes('bash') || env_shell.includes('zsh'))
const preferBash = env_shell?.includes('bash')
// Try to locate shells using which (uses Bun.which when available)
const [zshPath, bashPath] = await Promise.all([which('zsh'), which('bash')])
// Populate shell paths from which results and fallback locations
const shellPaths = ['/bin', '/usr/bin', '/usr/local/bin', '/opt/homebrew/bin']
// Order shells based on user preference
const shellOrder = preferBash ? ['bash', 'zsh'] : ['zsh', 'bash']
const supportedShells = shellOrder.flatMap(shell =>
shellPaths.map(path => `${path}/${shell}`),
)
// Add discovered paths to the beginning of our search list
// Put the user's preferred shell type first
if (preferBash) {
if (bashPath) supportedShells.unshift(bashPath)
if (zshPath) supportedShells.push(zshPath)
} else {
if (zshPath) supportedShells.unshift(zshPath)
if (bashPath) supportedShells.push(bashPath)
}
// Always prioritize SHELL env variable if it's a supported shell type
if (isEnvShellSupported && isExecutable(env_shell)) {
supportedShells.unshift(env_shell)
}
const shellPath = supportedShells.find(shell => shell && isExecutable(shell))
// If no valid shell found, throw a helpful error
if (!shellPath) {
const errorMsg =
'No suitable shell found. Claude CLI requires a Posix shell environment. ' +
'Please ensure you have a valid shell installed and the SHELL environment variable set.'
logError(new Error(errorMsg))
throw new Error(errorMsg)
}
return shellPath
}
async function getShellConfigImpl(): Promise<ShellConfig> {
const binShell = await findSuitableShell()
const provider = await createBashShellProvider(binShell)
return { provider }
}
// Memoize the entire shell config so it only happens once per session
export const getShellConfig = memoize(getShellConfigImpl)
export const getPsProvider = memoize(async (): Promise<ShellProvider> => {
const psPath = await getCachedPowerShellPath()
if (!psPath) {
throw new Error('PowerShell is not available')
}
return createPowerShellProvider(psPath)
})
const resolveProvider: Record<ShellType, () => Promise<ShellProvider>> = {
bash: async () => (await getShellConfig()).provider,
powershell: getPsProvider,
}
export type ExecOptions = {
timeout?: number
onProgress?: (
lastLines: string,
allLines: string,
totalLines: number,
totalBytes: number,
isIncomplete: boolean,
) => void
preventCwdChanges?: boolean
shouldUseSandbox?: boolean
shouldAutoBackground?: boolean
/** When provided, stdout is piped (not sent to file) and this callback fires on each data chunk. */
onStdout?: (data: string) => void
}
/**
* Execute a shell command using the environment snapshot
* Creates a new shell process for each command execution
*/
export async function exec(
command: string,
abortSignal: AbortSignal,
shellType: ShellType,
options?: ExecOptions,
): Promise<ShellCommand> {
const {
timeout,
onProgress,
preventCwdChanges,
shouldUseSandbox,
shouldAutoBackground,
onStdout,
} = options ?? {}
const commandTimeout = timeout || DEFAULT_TIMEOUT
const provider = await resolveProvider[shellType]()
const id = Math.floor(Math.random() * 0x10000)
.toString(16)
.padStart(4, '0')
// Sandbox temp directory - use per-user directory name to prevent multi-user permission conflicts
const sandboxTmpDir = posixJoin(
process.env.CLAUDE_CODE_TMPDIR || '/tmp',
getClaudeTempDirName(),
)
const { commandString: builtCommand, cwdFilePath } =
await provider.buildExecCommand(command, {
id,
sandboxTmpDir: shouldUseSandbox ? sandboxTmpDir : undefined,
useSandbox: shouldUseSandbox ?? false,
})
let commandString = builtCommand
let cwd = pwd()
// Recover if the current working directory no longer exists on disk.
// This can happen when a command deletes its own CWD (e.g., temp dir cleanup).
try {
await realpath(cwd)
} catch {
const fallback = getOriginalCwd()
logForDebugging(
`Shell CWD "${cwd}" no longer exists, recovering to "${fallback}"`,
)
try {
await realpath(fallback)
setCwdState(fallback)
cwd = fallback
} catch {
return createFailedCommand(
`Working directory "${cwd}" no longer exists. Please restart Claude from an existing directory.`,
)
}
}
// If already aborted, don't spawn the process at all
if (abortSignal.aborted) {
return createAbortedCommand()
}
const binShell = provider.shellPath
// Sandboxed PowerShell: wrapWithSandbox hardcodes `<binShell> -c '<cmd>'` —
// using pwsh there would lose -NoProfile -NonInteractive (profile load
// inside sandbox → delays, stray output, may hang on prompts). Instead:
// • powershellProvider.buildExecCommand (useSandbox) pre-wraps as
// `pwsh -NoProfile -NonInteractive -EncodedCommand <base64>` — base64
// survives the runtime's shellquote.quote() layer
// • pass /bin/sh as the sandbox's inner shell to exec that invocation
// • outer spawn is also /bin/sh -c to parse the runtime's POSIX output
// /bin/sh exists on every platform where sandbox is supported.
const isSandboxedPowerShell = shouldUseSandbox && shellType === 'powershell'
const sandboxBinShell = isSandboxedPowerShell ? '/bin/sh' : binShell
if (shouldUseSandbox) {
commandString = await SandboxManager.wrapWithSandbox(
commandString,
sandboxBinShell,
undefined,
abortSignal,
)
// Create sandbox temp directory for sandboxed processes with secure permissions
try {
const fs = getFsImplementation()
await fs.mkdir(sandboxTmpDir, { mode: 0o700 })
} catch (error) {
logForDebugging(`Failed to create ${sandboxTmpDir} directory: ${error}`)
}
}
const spawnBinary = isSandboxedPowerShell ? '/bin/sh' : binShell
const shellArgs = isSandboxedPowerShell
? ['-c', commandString]
: provider.getSpawnArgs(commandString)
const envOverrides = await provider.getEnvironmentOverrides(command)
// When onStdout is provided, use pipe mode: stdout flows through
// StreamWrapper → TaskOutput in-memory buffer instead of a file fd.
// This lets callers receive real-time stdout callbacks.
const usePipeMode = !!onStdout
const taskId = generateTaskId('local_bash')
const taskOutput = new TaskOutput(taskId, onProgress ?? null, !usePipeMode)
await mkdir(getTaskOutputDir(), { recursive: true })
// In file mode, both stdout and stderr go to the same file fd.
// On POSIX, O_APPEND makes each write atomic (seek-to-end + write), so
// stdout and stderr are interleaved chronologically without tearing.
// On Windows, 'a' mode strips FILE_WRITE_DATA (only grants FILE_APPEND_DATA)
// via libuv's fs__open. MSYS2/Cygwin probes inherited handles with
// NtQueryInformationFile(FileAccessInformation) and treats handles without
// FILE_WRITE_DATA as read-only, silently discarding all output. Using 'w'
// grants FILE_GENERIC_WRITE. Atomicity is preserved because duplicated
// handles share the same FILE_OBJECT with FILE_SYNCHRONOUS_IO_NONALERT,
// which serializes all I/O through a single kernel lock.
// SECURITY: O_NOFOLLOW prevents symlink-following attacks from the sandbox.
// On Windows, use string flags — numeric flags can produce EINVAL through libuv.
let outputHandle: FileHandle | undefined
if (!usePipeMode) {
const O_NOFOLLOW = fsConstants.O_NOFOLLOW ?? 0
outputHandle = await open(
taskOutput.path,
process.platform === 'win32'
? 'w'
: fsConstants.O_WRONLY |
fsConstants.O_CREAT |
fsConstants.O_APPEND |
O_NOFOLLOW,
)
}
try {
const childProcess = spawn(spawnBinary, shellArgs, {
env: {
...subprocessEnv(),
SHELL: shellType === 'bash' ? binShell : undefined,
GIT_EDITOR: 'true',
CLAUDECODE: '1',
...envOverrides,
...(process.env.USER_TYPE === 'ant'
? {
CLAUDE_CODE_SESSION_ID: getSessionId(),
}
: {}),
},
cwd,
stdio: usePipeMode
? ['pipe', 'pipe', 'pipe']
: ['pipe', outputHandle?.fd, outputHandle?.fd],
// Don't pass the signal - we'll handle termination ourselves with tree-kill
detached: provider.detached,
// Prevent visible console window on Windows (no-op on other platforms)
windowsHide: true,
})
const shellCommand = wrapSpawn(
childProcess,
abortSignal,
commandTimeout,
taskOutput,
shouldAutoBackground,
)
// Close our copy of the fd — the child has its own dup.
// Must happen after wrapSpawn attaches 'error' listener, since the await
// yields and the child's ENOENT 'error' event can fire in that window.
// Wrapped in its own try/catch so a close failure (e.g. EIO) doesn't fall
// through to the spawn-failure catch block, which would orphan the child.
if (outputHandle !== undefined) {
try {
await outputHandle.close()
} catch {
// fd may already be closed by the child; safe to ignore
}
}
// In pipe mode, attach the caller's callbacks alongside StreamWrapper.
// Both listeners receive the same data chunks (Node.js ReadableStream supports
// multiple 'data' listeners). StreamWrapper feeds TaskOutput for persistence;
// these callbacks give the caller real-time access.
if (childProcess.stdout && onStdout) {
childProcess.stdout.on('data', (chunk: string | Buffer) => {
onStdout(typeof chunk === 'string' ? chunk : chunk.toString())
})
}
// Attach cleanup to the command result
// NOTE: readFileSync/unlinkSync are intentional here — these must complete
// synchronously within the .then() microtask so that callers who
// `await shellCommand.result` see the updated cwd immediately after.
// Using async readFile would introduce a microtask boundary, causing
// a race where cwd hasn't been updated yet when the caller continues.
// On Windows, cwdFilePath is a POSIX path (for bash's `pwd -P >| $path`),
// but Node.js needs a native Windows path for readFileSync/unlinkSync.
// Similarly, `pwd -P` outputs a POSIX path that must be converted before setCwd.
const nativeCwdFilePath =
getPlatform() === 'windows'
? posixPathToWindowsPath(cwdFilePath)
: cwdFilePath
void shellCommand.result.then(async result => {
// On Linux, bwrap creates 0-byte mount-point files on the host to deny
// writes to non-existent paths (.bashrc, HEAD, etc.). These persist after
// bwrap exits as ghost dotfiles in cwd. Cleanup is synchronous and a no-op
// on macOS. Keep before any await so callers awaiting .result see a clean
// working tree in the same microtask.
if (shouldUseSandbox) {
SandboxManager.cleanupAfterCommand()
}
// Only foreground tasks update the cwd
if (result && !preventCwdChanges && !result.backgroundTaskId) {
try {
let newCwd = readFileSync(nativeCwdFilePath, {
encoding: 'utf8',
}).trim()
if (getPlatform() === 'windows') {
newCwd = posixPathToWindowsPath(newCwd)
}
// cwd is NFC-normalized (setCwdState); newCwd from `pwd -P` may be
// NFD on macOS APFS. Normalize before comparing so Unicode paths
// don't false-positive as "changed" on every command.
if (newCwd.normalize('NFC') !== cwd) {
setCwd(newCwd, cwd)
invalidateSessionEnvCache()
void onCwdChangedForHooks(cwd, newCwd)
}
} catch {
logEvent('tengu_shell_set_cwd', { success: false })
}
}
// Clean up the temp file used for cwd tracking
try {
unlinkSync(nativeCwdFilePath)
} catch {
// File may not exist if command failed before pwd -P ran
}
})
return shellCommand
} catch (error) {
// Close the fd if spawn failed (child never got its dup)
if (outputHandle !== undefined) {
try {
await outputHandle.close()
} catch {
// May already be closed
}
}
taskOutput.clear()
logForDebugging(`Shell exec error: ${errorMessage(error)}`)
return createAbortedCommand(undefined, {
code: 126, // Standard Unix code for execution errors
stderr: errorMessage(error),
})
}
}
/**
* Set the current working directory
*/
export function setCwd(path: string, relativeTo?: string): void {
const resolved = isAbsolute(path)
? path
: resolve(relativeTo || getFsImplementation().cwd(), path)
// Resolve symlinks to match the behavior of pwd -P.
// realpathSync throws ENOENT if the path doesn't exist - convert to a
// friendlier error message instead of a separate existsSync pre-check (TOCTOU).
let physicalPath: string
try {
physicalPath = getFsImplementation().realpathSync(resolved)
} catch (e) {
if (isENOENT(e)) {
throw new Error(`Path "${resolved}" does not exist`)
}
throw e
}
setCwdState(physicalPath)
if (process.env.NODE_ENV !== 'test') {
try {
logEvent('tengu_shell_set_cwd', {
success: true,
})
} catch (_error) {
// Ignore logging errors to prevent test failures
}
}
}
Loading...
举报
举报成功
我们将于2个工作日内通过站内信反馈结果给你!
请认真填写举报原因,尽可能描述详细。
请选择举报类型
取消
发送
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

简介

取消

发行版

暂无发行版

贡献者

全部

近期动态

不能加载更多了
编辑仓库简介
简介内容
主页
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/jbcode/claude-code.git
git@gitee.com:jbcode/claude-code.git
jbcode
claude-code
claude-code
main
点此查找更多帮助

搜索帮助

评论
仓库举报
回到顶部
登录提示
该操作需登录 Gitee 帐号,请先登录后再操作。
立即登录
没有帐号,去注册

AltStyle によって変換されたページ (->オリジナル) /