import { isReadOnlyShellCommand, isVerificationShellCommand, isAdvisorInspectionCommand } from '../tools/bash/semantics.js'; import { toolEffectFor } from '../tools/capabilities.js'; import { getToolByName, getToolGateDetails } from '../tools/index.js'; import type { Tool, ToolCall, ToolCallContext } from '../types.js'; export function advisorSemanticsFor( call: ToolCall, context?: ToolCallContext, tool?: Tool, // 默认 false:只有顾问提醒的记账(AdvisorNudge.observeToolResult)才传 true。工作区租约判定 // (needsWorkspaceLease)必须保持严格定义不受影响——验证类命令仍可能写 // 构建产物/缓存,并发场景下让它绕开租约会重新引入竞态。 opts?: { treatVerificationAsReadOnly?: boolean }, ): { mutatesWorkspace: boolean } { const definition = tool ?? getToolByName(call.function.name); const gate = context && definition ? getToolGateDetails(definition, call.function.arguments, context) : undefined; // Only the original definition has the built-in command/action semantics. // A same-name host tool may use similar-looking arguments quite differently. if (definition && definition !== getToolByName(call.function.name)) return { mutatesWorkspace: !(gate?.isReadOnly ?? definition.isReadOnly ?? false) }; // Reuse the tool's side-effect contract, including shell/scripts, Trash and // generation tools. Shell tools refine their generic writable declaration // using the actual command; the same result is also used by the host gate. let isReadOnly = gate?.isReadOnly ?? definition?.isReadOnly ?? false; if (gate?.isReadOnly === undefined && call.function.name === 'Agent') { try { const args = JSON.parse(call.function.arguments || '{}'); isReadOnly = !args.resume_agent_id && (args.agent_type ?? 'explore') === 'explore'; } catch { isReadOnly = false; } } if (gate?.isReadOnly === undefined && (call.function.name === 'Bash' || call.function.name === 'PowerShell')) { try { const input = JSON.parse(call.function.arguments || '{}') as { command?: unknown; }; if (typeof input.command === 'string') { // 跑测试/构建/lint 只是核对现状,不该被当成"开始实施改动"而过早提醒 // "动手前先咨询"——即使它们可能写构建产物/缓存,不满足 // isReadOnlyShellCommand 的并发安全定义(见 opts 注释,那个场景仍要严格)。 isReadOnly = isReadOnlyShellCommand(input.command) || (opts?.treatVerificationAsReadOnly === true && (isAdvisorInspectionCommand(input.command) || isVerificationShellCommand(input.command))); } } catch { // Malformed input is left writable; normal tool validation reports it. isReadOnly = false; } } const mutatesWorkspace = toolEffectFor(call.function.name, isReadOnly) === 'execution'; return { mutatesWorkspace }; }