reason-format.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. /**
  2. * Localized DecisionReason formatter — produces the human-readable `reason`
  3. * strings emitted at the wire by `LocalPermissionFacade`.
  4. *
  5. * Templates are keyed by `'en' | 'zh'`. Default mode (no LLM) and auto mode
  6. * (with LLM prefix) MUST go through the same table so the two pipelines stay
  7. * in sync. When adding a new DecisionReason variant, add its template here
  8. * too — missing keys surface as a TypeScript error.
  9. */
  10. import type { UserLocaleHint } from './locale-detect.js';
  11. import type {
  12. PermissionBehavior,
  13. PermissionMode,
  14. PermissionRule,
  15. PermissionRuleSource,
  16. DecisionReason,
  17. SubcommandResult,
  18. } from './types.js';
  19. export type Lang = 'en' | 'zh';
  20. export function localeOrDefault(locale: UserLocaleHint): Lang {
  21. return locale === 'zh' ? 'zh' : 'en';
  22. }
  23. const ACTION_LABEL: Record<Lang, Record<PermissionBehavior, string>> = {
  24. en: { allow: 'Allowed', ask: 'Needs confirmation', deny: 'Blocked' },
  25. zh: { allow: '已允许', ask: '需要确认', deny: '已拒绝' },
  26. };
  27. const BEHAVIOR_LABEL: Record<Lang, Record<PermissionBehavior, string>> = {
  28. en: { allow: 'allow', ask: 'ask', deny: 'deny' },
  29. zh: { allow: '允许', ask: '询问', deny: '拒绝' },
  30. };
  31. const SOURCE_LABEL: Record<Lang, Record<PermissionRuleSource, string>> = {
  32. en: { global: 'global', agent: 'agent', session: 'session' },
  33. zh: { global: '全局', agent: 'agent', session: '会话' },
  34. };
  35. const MODE_OFF_REASON: Record<Lang, string> = {
  36. en: 'Allowed: permission mode is off; permission review was skipped.',
  37. zh: '已允许:权限模式为 off,已跳过权限审查。',
  38. };
  39. const MODE_BYPASS_REASON: Record<Lang, string> = {
  40. en: 'Allowed: permission mode is bypassPermissions and no bypass-immune safety rule matched.',
  41. zh: '已允许:权限模式为 bypassPermissions,且未命中任何强制安全规则。',
  42. };
  43. function formatMode(lang: Lang, mode: PermissionMode): string {
  44. return lang === 'zh' ? `已允许:权限模式 ${mode} 放行。` : `Allowed by permission mode: ${mode}.`;
  45. }
  46. function formatWorkingDirectoryReason(
  47. behavior: PermissionBehavior | undefined,
  48. fsPath: string,
  49. lang: Lang,
  50. ): string {
  51. if (behavior === 'allow') {
  52. return lang === 'zh'
  53. ? `已允许:文件路径在已批准的读写边界内。路径:${fsPath}`
  54. : `Allowed: filesystem path is within an approved read/write boundary. Path: ${fsPath}`;
  55. }
  56. if (behavior === 'ask') {
  57. return lang === 'zh'
  58. ? `需要确认:文件路径在工作区或允许路径之外。路径:${fsPath}`
  59. : `Needs confirmation: filesystem path is outside the workspace or configured allow paths. Path: ${fsPath}`;
  60. }
  61. return lang === 'zh'
  62. ? `已拒绝:文件路径在工作区或允许路径之外。路径:${fsPath}`
  63. : `Blocked: filesystem path is outside the workspace or configured allow paths. Path: ${fsPath}`;
  64. }
  65. function formatInternalWhitelistReason(fsPath: string, lang: Lang): string {
  66. return lang === 'zh'
  67. ? `已允许:Mavis 内部托管路径。路径:${fsPath}`
  68. : `Allowed: internal Mavis-managed path. Path: ${fsPath}`;
  69. }
  70. function formatTrustedExactWriteReason(fsPath: string, lang: Lang): string {
  71. return lang === 'zh'
  72. ? `已允许:当前 Turn 已授权写入精确路径。路径:${fsPath}`
  73. : `Allowed: the current turn allows writing the exact path. Path: ${fsPath}`;
  74. }
  75. function formatTempDirectoryReason(fsPath: string, lang: Lang): string {
  76. return lang === 'zh'
  77. ? `已允许:文件路径在临时目录内。路径:${fsPath}`
  78. : `Allowed: filesystem path is inside a temporary directory. Path: ${fsPath}`;
  79. }
  80. const SANDBOX_REASON: Record<Lang, string> = {
  81. en: 'Allowed: path is covered by the sandbox allow-list.',
  82. zh: '已允许:路径在 sandbox 允许列表内。',
  83. };
  84. function formatPathValidationReason(error: string, lang: Lang): string {
  85. return lang === 'zh'
  86. ? `已拒绝:文件路径非法。${error}`
  87. : `Blocked: invalid filesystem path. ${error}`;
  88. }
  89. function formatDangerousRemovalReason(fsPath: string, lang: Lang): string {
  90. return lang === 'zh'
  91. ? `已拒绝:危险删除目标。路径:${fsPath}`
  92. : `Blocked: dangerous removal target. Path: ${fsPath}`;
  93. }
  94. function formatRmRewriteReason(rewrittenCommand: string, lang: Lang): string {
  95. return lang === 'zh'
  96. ? `已允许:rm 命令已改写为 mavis-trash 以便恢复。原命令:${rewrittenCommand}`
  97. : `Allowed: rm command was rewritten to mavis-trash for recoverable deletion. Original command: ${rewrittenCommand}`;
  98. }
  99. const UNKNOWN_REASON: Record<Lang, string> = {
  100. en: 'Unknown reason',
  101. zh: '原因未知',
  102. };
  103. const EMPTY_BASH_REASON: Record<Lang, string> = {
  104. en: 'Allowed: empty bash command.',
  105. zh: '已允许:空的 bash 命令。',
  106. };
  107. function formatSubcommandSummary(
  108. prefix: string,
  109. command: string,
  110. detail: string,
  111. lang: Lang,
  112. ): string {
  113. return lang === 'zh'
  114. ? `${prefix}:bash 子命令 "${command}" 的判定。${detail}`
  115. : `${prefix}: bash subcommand decision for "${command}". ${detail}`;
  116. }
  117. function formatRuleDecisionReason(rule: PermissionRule, lang: Lang): string {
  118. const behavior = rule.ruleBehavior;
  119. const action = ACTION_LABEL[lang][behavior];
  120. const source = SOURCE_LABEL[lang][rule.source];
  121. const behaviorWord = BEHAVIOR_LABEL[lang][behavior];
  122. const scope = rule.ruleValue.ruleContent
  123. ? `${rule.ruleValue.toolName}(${rule.ruleValue.ruleContent})`
  124. : rule.ruleValue.toolName;
  125. return lang === 'zh'
  126. ? `${action}:命中 ${source} ${behaviorWord} 权限规则,作用域 ${scope}。`
  127. : `${action}: matched ${source} ${behaviorWord} permission rule for ${scope}.`;
  128. }
  129. function formatSafetyDecisionReason(
  130. description: string,
  131. behavior: PermissionBehavior | undefined,
  132. lang: Lang,
  133. ): string {
  134. if (
  135. /^(<system-reminder|Allowed|Blocked|Needs confirmation|Auto classifier|LLM classifier|No LLM client|⚠️|已允许|已拒绝|需要确认|⚠️ )/.test(
  136. description,
  137. )
  138. ) {
  139. return description;
  140. }
  141. if (behavior === 'allow') {
  142. return lang === 'zh' ? `已允许:${description}` : `Allowed: ${description}`;
  143. }
  144. if (behavior === 'deny') {
  145. return lang === 'zh' ? `已拒绝:${description}` : `Blocked: ${description}`;
  146. }
  147. return lang === 'zh' ? `需要确认:${description}` : `Needs confirmation: ${description}`;
  148. }
  149. function formatSubcommandDecisionReason(
  150. reasons: Map<string, SubcommandResult>,
  151. lang: Lang = 'en',
  152. ): string {
  153. if (reasons.size === 0) return EMPTY_BASH_REASON[lang];
  154. const priority: Record<PermissionBehavior, number> = { deny: 0, ask: 1, allow: 2 };
  155. const entries = [...reasons.entries()].sort(
  156. ([, a], [, b]) => priority[a.behavior] - priority[b.behavior],
  157. );
  158. const first = entries[0];
  159. if (!first) return EMPTY_BASH_REASON[lang];
  160. const [command, result] = first;
  161. const detail = formatDecisionReason(result.reason, result.behavior, lang);
  162. const prefix = ACTION_LABEL[lang][result.behavior];
  163. return formatSubcommandSummary(prefix, command, detail, lang);
  164. }
  165. /**
  166. * Render a `DecisionReason` (or bare `PermissionRule`) into a user-facing
  167. * string.
  168. */
  169. export function formatDecisionReason(
  170. reason: PermissionRule | DecisionReason,
  171. behavior?: PermissionBehavior,
  172. locale: UserLocaleHint | Lang = 'en',
  173. ): string {
  174. const lang = localeOrDefault(locale as UserLocaleHint);
  175. if ('type' in reason) {
  176. switch (reason.type) {
  177. case 'rule':
  178. return formatRuleDecisionReason(reason.rule, lang);
  179. case 'safetyCheck':
  180. return formatSafetyDecisionReason(reason.description, behavior, lang);
  181. case 'mode':
  182. if (reason.mode === 'off') {
  183. return MODE_OFF_REASON[lang];
  184. }
  185. if (reason.mode === 'bypassPermissions') {
  186. return MODE_BYPASS_REASON[lang];
  187. }
  188. return formatMode(lang, reason.mode);
  189. case 'workingDirectory':
  190. return formatWorkingDirectoryReason(behavior, reason.path, lang);
  191. case 'internalWhitelist':
  192. return formatInternalWhitelistReason(reason.path, lang);
  193. case 'trustedExactWrite':
  194. return formatTrustedExactWriteReason(reason.path, lang);
  195. case 'tempDirectory':
  196. return formatTempDirectoryReason(reason.path, lang);
  197. case 'sandbox':
  198. return SANDBOX_REASON[lang];
  199. case 'pathValidation':
  200. return formatPathValidationReason(reason.error, lang);
  201. case 'dangerousRemoval':
  202. return formatDangerousRemovalReason(reason.path, lang);
  203. case 'subcommandResults':
  204. return formatSubcommandDecisionReason(reason.reasons, lang);
  205. case 'rmRewrite':
  206. return formatRmRewriteReason(reason.rewrittenCommand, lang);
  207. case 'recoverableDeleteRewrite':
  208. return formatRmRewriteReason(reason.targets.join(' '), lang);
  209. default:
  210. return UNKNOWN_REASON[lang];
  211. }
  212. }
  213. // Bare PermissionRule.
  214. return formatRuleDecisionReason(reason, lang);
  215. }
  216. // ---------------------------------------------------------------------------
  217. // Auto-mode classifier prefixes (used by the LocalPermissionFacade
  218. // cloud-gateway branch).
  219. // ---------------------------------------------------------------------------
  220. const AUTO_CLASSIFIER_ALLOW_PREFIX: Record<Lang, string> = {
  221. en: 'Auto classifier',
  222. zh: '自动判定',
  223. };
  224. const AUTO_CLASSIFIER_BLOCK_PREFIX: Record<Lang, string> = {
  225. en: '⚠️ Blocked by auto classifier; explicit confirmation required to continue',
  226. zh: '⚠️ 自动判定已阻止,需用户显式确认才能继续',
  227. };
  228. const AUTO_CLASSIFIER_CONFIRM_PREFIX: Record<Lang, string> = {
  229. en: 'Needs confirmation',
  230. zh: '需要确认',
  231. };
  232. const AUTO_CLASSIFIER_TIMEOUT_TEMPLATE: Record<Lang, (suffix: string) => string> = {
  233. en: (suffix) => `⚠️ Auto classifier timed out${suffix}; asking user to confirm.`,
  234. zh: (suffix) => `⚠️ 自动 classifier 超时${suffix},请用户手动确认。`,
  235. };
  236. export function formatAutoClassifierReason(
  237. verdict: 'allow' | 'block' | 'confirm' | 'timeout',
  238. reasonText: string,
  239. locale: UserLocaleHint,
  240. ): string {
  241. const lang = localeOrDefault(locale);
  242. const sep = lang === 'zh' ? ':' : ': ';
  243. switch (verdict) {
  244. case 'allow':
  245. return `${AUTO_CLASSIFIER_ALLOW_PREFIX[lang]}${sep}${reasonText}`;
  246. case 'block':
  247. return `${AUTO_CLASSIFIER_BLOCK_PREFIX[lang]}${sep}${reasonText}`;
  248. case 'timeout':
  249. return AUTO_CLASSIFIER_TIMEOUT_TEMPLATE[lang](reasonText);
  250. case 'confirm':
  251. default:
  252. return `${AUTO_CLASSIFIER_CONFIRM_PREFIX[lang]}${sep}${reasonText}`;
  253. }
  254. }
  255. // ---------------------------------------------------------------------------
  256. // Blocked-tool reason — the string handed to the LLM when a tool call is
  257. // denied at `beforeToolCall`. The model reads this to decide how to recover
  258. // (try another approach / explain to the user / drop a blocked rule), so the
  259. // source is surfaced as a machine-readable tag.
  260. // ---------------------------------------------------------------------------
  261. /**
  262. * Where a tool-call denial originated. Surfaced to the LLM so it can tell a
  263. * user veto apart from a configured rule apart from a built-in safety wall.
  264. *
  265. * - `user` — the user rejected the call in the confirmation dialog
  266. * (includes auto-mode cloud `block` that was downgraded
  267. * to ask and then rejected).
  268. * - `rule` — matched a user-configured `deny` permission rule.
  269. * - `safety` — matched a built-in safety boundary (HARD final-deny,
  270. * dangerous removal, invalid path, …).
  271. * - `safety-immune` — bypass-immune safety deny (UNC / network share,
  272. * `rm -rf /`, `rm -rf ~`). Cannot be relaxed by any mode.
  273. */
  274. export type ToolDenialSource = 'user' | 'rule' | 'safety' | 'safety-immune';
  275. export interface BlockedToolReasonInput {
  276. source: ToolDenialSource;
  277. toolName: string;
  278. /**
  279. * Already-localized decision reason for non-user denials — the engine /
  280. * facade output from {@link formatDecisionReason}. Rendered as the body.
  281. */
  282. detail?: string;
  283. /**
  284. * Already-localized reason the confirmation was raised in the first place
  285. * (original safety / cloud-classifier text), carried through on a `user`
  286. * denial so the model knows what the user vetoed.
  287. */
  288. trigger?: string;
  289. }
  290. /**
  291. * Render the LLM-facing denial string. The leading `[permission:denied
  292. * source=<source>]` tag is intentionally fixed English so the model (and log
  293. * greps) can parse the origin regardless of the user's locale; the trailing
  294. * body reuses the already-localized `detail` / `trigger` text verbatim.
  295. */
  296. export function formatBlockedToolReason(input: BlockedToolReasonInput): string {
  297. const { source, toolName, detail, trigger } = input;
  298. const tag = `[permission:denied source=${source}]`;
  299. if (source === 'user') {
  300. const base = `${tag} User rejected the \`${toolName}\` call in the confirmation dialog.`;
  301. return trigger ? `${base} Trigger: ${trigger}` : base;
  302. }
  303. const body = detail && detail.trim().length > 0 ? detail : `\`${toolName}\` call was denied.`;
  304. return `${tag} ${body}`;
  305. }