/** * ============================================================ * src/cli/memoryAccess.ts —— CLI 入口的「本机记忆权限」判定(单一出处) * ------------------------------------------------------------ * **为什么单独一个模块**:这是一条信任边界,不该以内联三元的形式散落在 print.ts 和 * streamJson.ts 各写一份。分层约定是—— * * 内核(loop.ts) :默认 `denied`,永不自己推断,只认宿主显式声明; * 宿主(本模块) :把「这次调用算不算本机主人」这个**产品判断**收敛在一处; * 入口(print/streamJson):只负责把结论透传,不再自证身份。 * * 在此之前两个入口都硬编码 `access:'local-owner'`,与 types.ts::memoryAccess 写下的 * 不变量(「远程、社交和子 Agent 必须为 denied」)直接冲突。 * * **判定规则**:本机非交互 `-p` 入口默认 read-only;显式 local-owner/read-write * 才允许修改。远程或不可信宿主必须显式传 denied。 * ============================================================ */ import { normalizeArgs } from './args.js'; export type MemoryAccess = 'read-write' | 'read-only' | 'denied'; const FLAG = '--memory-access'; /** * 从 argv 里取显式声明。声明存在但缺值或值非法时抛出可操作错误,不能静默降级: * 对权限参数而言,拼写错误与明确拒绝不是同一件事。 * * `--memory-access=x` 与 `--memory-access x` 两种写法等价——`=` 形式由 `normalizeArgs` * 统一展开(本函数一度自己认过一次 `=`,那是只保住这一个标志的补丁:`--cwd=` / * `--session=` 照样静默失败,所以已下沉到 args.ts 的解析层)。 */ function explicitAccess(args: string[]): MemoryAccess | undefined { const normalized = normalizeArgs(args); for (let index = 0; index < normalized.length; index += 1) { if (normalized[index] !== FLAG) continue; const value = normalized[index + 1]; if (value === 'local-owner' || value === 'read-write') return 'read-write'; if (value === 'read-only' || value === 'denied') return value; throw new Error( `${FLAG} 只接受 local-owner、read-write、read-only 或 denied,收到:${value && !value.startsWith('-') ? value : '缺少值'}`, ); } return undefined; } export function resolveMemoryAccess( _outputFormat: 'text' | 'json' | 'stream-json', args: string[], ): MemoryAccess { return explicitAccess(args) ?? 'read-only'; }