pi-verdict 0.5.0 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -13
- package/README.zh-CN.md +20 -13
- package/extensions/auto-mode.ts +79 -18
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
- Built-in danger rules and your own allow/deny rules settle the clear cases first, at zero latency
|
|
13
13
|
- Everything else goes to a model classifier that sees the conversation context
|
|
14
14
|
- Any uncertainty or failure fails closed; nothing ever runs silently
|
|
15
|
+
- Self-protection: the gate guards itself against snooping and tampering
|
|
15
16
|
|
|
16
17
|
## The problem
|
|
17
18
|
|
|
@@ -23,10 +24,15 @@ pi-verdict adds the missing gate: a model decides whether each call should run,
|
|
|
23
24
|
|
|
24
25
|
**verdict is an adjudication, not a switch.** Most classifiers in this space output a binary allow/block. Three states matter: `ask` routes genuinely ambiguous actions to a human (and degrades to `deny` in non-interactive sessions), so "not sure" never silently becomes "go ahead".
|
|
25
26
|
|
|
27
|
+
## Screenshots
|
|
28
|
+
|
|
29
|
+

|
|
30
|
+

|
|
31
|
+
|
|
26
32
|
## Quick start
|
|
27
33
|
|
|
28
34
|
```bash
|
|
29
|
-
# install from npm
|
|
35
|
+
# install from npm:
|
|
30
36
|
pi install npm:pi-verdict
|
|
31
37
|
|
|
32
38
|
# or directly from git — try it once
|
|
@@ -62,15 +68,15 @@ pi --extension ./extensions/auto-mode.ts
|
|
|
62
68
|
```
|
|
63
69
|
|
|
64
70
|
- `allow`/`deny` are JS regex arrays; **`deny` wins over `allow`**, both beat the classifier
|
|
65
|
-
-
|
|
66
|
-
|
|
71
|
+
- `denyPaths` are plain paths (not regexes) you declare **protected**: any tool call touching them — file tools via their path, bash via path tokens extracted from the command string — triggers a **terminal ask** you adjudicate (non-interactive sessions degrade to deny). Not affected by `builtinDenyFloor: false`.
|
|
72
|
+
The classifier only ever learns that protected paths *exist*; the paths themselves never leave your machine, and a matched path shows **only** in the local confirm dialog.
|
|
67
73
|
- `builtinDenyFloor: false` turns the built-in danger/path floor off entirely (risk accepted by you; the classifier and your rules remain — the self-protection layer below always stays on)
|
|
68
74
|
- `classifierModel: "provider/model-id"` sets the classifier model (e.g. a fast flash-class model); precedence is flag > env > config > session model (self-reflection); an invalid value falls back to the session model with a one-time warning
|
|
69
|
-
- the spec accepts pi's native `--model` thinking suffix: `"zai/glm-5.3-flash:low"` sets classifier thinking to effort low (default without suffix: thinking explicitly off
|
|
70
|
-
- `toggleShortcut` rebinds the master-switch toggle key (
|
|
71
|
-
- first run generates a template at `~/.pi/agent/config/pi-verdict.json` (honors `PI_CODING_AGENT_DIR`)
|
|
75
|
+
- the spec accepts pi's native `--model` thinking suffix: `"zai/glm-5.3-flash:low"` sets classifier thinking to effort low (default without suffix: thinking explicitly off)
|
|
76
|
+
- `toggleShortcut` rebinds the master-switch toggle key (`null` or empty disables it, not persisted)
|
|
77
|
+
- first run generates a template at `~/.pi/agent/config/pi-verdict.json` (honors `PI_CODING_AGENT_DIR`)
|
|
72
78
|
|
|
73
|
-
**Why no built-in allowlist?** Bypass testing of the rule layer ([writeup](research/rule-layer-security-audit.md)) showed that allowlist
|
|
79
|
+
**Why no built-in allowlist?** Bypass testing of the rule layer ([writeup](research/rule-layer-security-audit.md)) showed that allowlist robustness is very limited. The built-in layer only makes **deny** claims (the sound direction); allow claims are yours.
|
|
74
80
|
|
|
75
81
|
### Self-protection (the gate guards itself — [ADR-0001](docs/adr/0001-self-protection-layer.md))
|
|
76
82
|
|
|
@@ -116,10 +122,12 @@ tool_call
|
|
|
116
122
|
│
|
|
117
123
|
├─ 1. Rule layer (deterministic, zero latency)
|
|
118
124
|
│ ├─ built-in deny floor: bash danger regexes (full-string) +
|
|
119
|
-
│ │ path sensitivity S0–S5 (secrets/system/.git meta → deny
|
|
125
|
+
│ │ path sensitivity S0–S5 (secrets/system/.git meta → deny;
|
|
126
|
+
│ │ dual-form matching — lexical + realpath, symlink aliases resolve)
|
|
120
127
|
│ ├─ your rules: user deny beats user allow (regex, see below)
|
|
121
128
|
│ ├─ denyPaths (ADR-0002): user-declared protected paths, tool-owned
|
|
122
|
-
│ │ normalization (~, $HOME, relative, .., symlink
|
|
129
|
+
│ │ normalization (~, $HOME, relative, .., symlink, case on
|
|
130
|
+
│ │ macOS/Windows) → terminal ask,
|
|
123
131
|
│ │ before user allow; classifier sees an existence hint only
|
|
124
132
|
│ └─ no built-in allowlist — every "always allow" claim is yours to make
|
|
125
133
|
│
|
|
@@ -142,7 +150,7 @@ tool_call
|
|
|
142
150
|
replays a double-key LRU(128) to measure would-be hit rate
|
|
143
151
|
```
|
|
144
152
|
|
|
145
|
-
**fail-closed**: classifier exception / timeout (
|
|
153
|
+
**fail-closed**: classifier exception / timeout (25s) / contract violation → deny. Never silently allow.
|
|
146
154
|
|
|
147
155
|
## Evidence-driven, not vibes-driven
|
|
148
156
|
|
|
@@ -158,9 +166,9 @@ Design decisions here are settled by measurement, and the lab notes ship with th
|
|
|
158
166
|
|
|
159
167
|
## Status & limitations
|
|
160
168
|
|
|
161
|
-
Prototype quality — usable, not hardened:
|
|
162
|
-
|
|
163
169
|
- no built-in allowlist by design (see the [bypass writeup](research/rule-layer-security-audit.md)); with an empty `allow` config most commands go to the classifier — point `--auto-mode-model` at a fast model if per-call latency matters
|
|
170
|
+
- the path sensitivity floor applies to file tools only: bash command strings are matched by the danger regexes alone, so e.g. `cat ~/.ssh/id_rsa` goes to the classifier rather than the deterministic S0 deny (the file-tool spelling `read ~/.ssh/id_rsa` does deny)
|
|
171
|
+
- on Windows the built-in floor covers bash-shaped patterns only — PowerShell-native dangerous commands (`Remove-Item -Recurse -Force`, `Invoke-Expression`, `Set-ExecutionPolicy`, …) rely on the classifier (fail-closed)
|
|
164
172
|
- AGENTS.md is not passed to the classifier as downweighted intent evidence (Claude Code does this)
|
|
165
173
|
- parallel gray-zone calls are adjudicated serially
|
|
166
174
|
- self-reflection means the session model adjudicates — point `--auto-mode-model` at a lighter model if verdict latency/cost matters (open question tracked in the issue tracker)
|
|
@@ -179,7 +187,7 @@ The name: the three-state **verdict** is the core concept. The UX keeps `/automo
|
|
|
179
187
|
```bash
|
|
180
188
|
bun install
|
|
181
189
|
bun run typecheck
|
|
182
|
-
bun test #
|
|
190
|
+
bun test # offline stub tests: self-protection, tamper detection, deny floor, user rules, denyPaths, bypass regression, classifier retry, shadow cache, commands, toggle shortcut
|
|
183
191
|
```
|
|
184
192
|
|
|
185
193
|
Issue tracker and decision records live in the GitHub issues ("map" issue #1 indexes them).
|
package/README.zh-CN.md
CHANGED
|
@@ -6,12 +6,13 @@
|
|
|
6
6
|
[](https://www.npmjs.com/package/pi-verdict)
|
|
7
7
|
[](https://pi.dev)
|
|
8
8
|
|
|
9
|
-
**pi-verdict 是 [pi](https://pi.dev) 的 Claude Code
|
|
9
|
+
**pi-verdict 是 [pi](https://pi.dev) 的 Claude Code 风格的 Auto mode 式的极简权限门禁:每次工具调用执行前先过检查——放行、拦截,或先问你。**
|
|
10
10
|
|
|
11
11
|
- 只有几百行的极简代码
|
|
12
12
|
- 内置危险规则与你的 allow/deny 规则以零延迟先行裁决明确情形
|
|
13
13
|
- 其余交给携带会话上下文的模型分类器
|
|
14
14
|
- 任何不确定或失败一律 fail-closed, 绝不静默放行
|
|
15
|
+
- 自我保护: 防止被窥探和篡改
|
|
15
16
|
|
|
16
17
|
## 问题
|
|
17
18
|
|
|
@@ -23,10 +24,15 @@ pi-verdict 补上这道缺失的门禁, 由模型基于上下文和你的意图
|
|
|
23
24
|
|
|
24
25
|
**verdict 是裁决,不是开关。** 本品类的分类器大多只输出二值 allow/block。三态有意义的地方在:`ask` 把真正含糊的动作转交人类确认(非交互会话中降级为 `deny`),「不确定」永远不会静默变成「放行」。
|
|
25
26
|
|
|
27
|
+
## 截图
|
|
28
|
+
|
|
29
|
+

|
|
30
|
+

|
|
31
|
+
|
|
26
32
|
## 快速开始
|
|
27
33
|
|
|
28
34
|
```bash
|
|
29
|
-
# 从 npm
|
|
35
|
+
# 从 npm 安装:
|
|
30
36
|
pi install npm:pi-verdict
|
|
31
37
|
|
|
32
38
|
# 或直接从源码 —— 试用一次
|
|
@@ -62,15 +68,15 @@ pi --extension ./extensions/auto-mode.ts
|
|
|
62
68
|
```
|
|
63
69
|
|
|
64
70
|
- `allow`/`deny` 为 JS 正则数组;**`deny` 优先于 `allow`**,两者都优先于分类器
|
|
65
|
-
-
|
|
66
|
-
|
|
71
|
+
- `denyPaths` 是你声明**受保护**的普通路径列表(非正则):任何触碰它们的工具调用——文件类工具取其路径、bash 从命令串提取路径 token——触发**终局 ask**,由你裁决(非交互会话降级 deny)。不受 `builtinDenyFloor: false` 影响
|
|
72
|
+
分类器只被告知受保护路径**存在**,路径明文永不出本机, 命中的路径**只**出现在本地确认弹窗。
|
|
67
73
|
- `builtinDenyFloor: false` 可整体关闭内置危险/路径拦截(风险自担;分类器与你的规则仍在——下方自保护层永远开启)
|
|
68
74
|
- `classifierModel: "provider/model-id"` 指定分类器模型(如轻量 flash 类);优先级 flag > env > config > 自省;无效值回退会话模型并一次性警告
|
|
69
|
-
- spec 支持 pi 原生 `--model` 思考级别后缀:`"zai/glm-5.3-flash:low"` 将分类器思考设为 effort low(无后缀缺省 =
|
|
70
|
-
- `toggleShortcut` 重绑主开关快捷键(
|
|
71
|
-
- 首次运行自动生成模板 `~/.pi/agent/config/pi-verdict.json`(尊重 `PI_CODING_AGENT_DIR`)
|
|
75
|
+
- spec 支持 pi 原生 `--model` 思考级别后缀:`"zai/glm-5.3-flash:low"` 将分类器思考设为 effort low(无后缀缺省 = 显式关思考)
|
|
76
|
+
- `toggleShortcut` 重绑主开关快捷键(`null` 或空串禁用, 非持久化)
|
|
77
|
+
- 首次运行自动生成模板 `~/.pi/agent/config/pi-verdict.json`(尊重 `PI_CODING_AGENT_DIR`)
|
|
72
78
|
|
|
73
|
-
**为什么没有内置白名单?**对规则层的绕过测试(见 [`research/rule-layer-security-audit.md`](research/rule-layer-security-audit.md))
|
|
79
|
+
**为什么没有内置白名单?**对规则层的绕过测试(见 [`research/rule-layer-security-audit.md`](research/rule-layer-security-audit.md))证明白名单的健壮性非常有限。因此内置层只做 **deny** 声明(方向健全),allow 声明归你。
|
|
74
80
|
|
|
75
81
|
### 自保护(门禁守护自身——[ADR-0001](docs/adr/0001-self-protection-layer.md))
|
|
76
82
|
|
|
@@ -116,9 +122,10 @@ tool_call
|
|
|
116
122
|
│
|
|
117
123
|
├─ 1. 规则层(确定性,零延迟)
|
|
118
124
|
│ ├─ 内置 deny floor:bash 危险正则(完整命令串)+ 路径敏感度 S0–S5
|
|
125
|
+
│ │ (双形匹配 —— 词法 + realpath,符号链接别名会被解析)
|
|
119
126
|
│ ├─ 用户规则:deny 优先于 allow(正则,见下)
|
|
120
127
|
│ ├─ denyPaths(ADR-0002):用户声明的受保护路径,工具负责归一化
|
|
121
|
-
│ │ (~、$HOME、相对、..、symlink)→ 终局 ask,先于用户 allow;
|
|
128
|
+
│ │ (~、$HOME、相对、..、symlink、macOS/Windows 大小写)→ 终局 ask,先于用户 allow;
|
|
122
129
|
│ │ 分类器只见存在性话术
|
|
123
130
|
│ └─ 无内置白名单 —— 「永远放行」的声明由你自己做
|
|
124
131
|
│
|
|
@@ -140,7 +147,7 @@ tool_call
|
|
|
140
147
|
回放双键 LRU(128)测量 would-be 命中率
|
|
141
148
|
```
|
|
142
149
|
|
|
143
|
-
**fail-closed**:分类器异常 / 超时(
|
|
150
|
+
**fail-closed**:分类器异常 / 超时(25s)/ 输出违反契约 → 拦截,绝不静默放行。
|
|
144
151
|
|
|
145
152
|
## 证据驱动,不靠直觉
|
|
146
153
|
|
|
@@ -156,9 +163,9 @@ tool_call
|
|
|
156
163
|
|
|
157
164
|
## 状态与限制
|
|
158
165
|
|
|
159
|
-
原型质量 —— 可用,未硬化:
|
|
160
|
-
|
|
161
166
|
- 设计上无内置白名单(见[绕过测试](research/rule-layer-security-audit.md)与[用户规则](#用户规则configpi-verdictjson));allow 配置为空时大多数命令进分类器 —— 延迟敏感可 `--auto-mode-model` 指向轻量模型
|
|
167
|
+
- 路径敏感度 floor 只作用于文件类工具:bash 命令串仅匹配危险正则——`cat ~/.ssh/id_rsa` 走分类器而非确定性 S0 拦截(文件工具拼写 `read ~/.ssh/id_rsa` 会拦截)
|
|
168
|
+
- Windows 下内置 floor 仅覆盖 bash 形态模式——PowerShell 原生危险命令(`Remove-Item -Recurse -Force`、`Invoke-Expression`、`Set-ExecutionPolicy` 等)依赖分类器兜底(fail-closed)
|
|
162
169
|
- AGENTS.md 未作为降权意图证据传入分类器(Claude Code 有此设计)
|
|
163
170
|
- 并行灰区调用串行裁决
|
|
164
171
|
- 自省意味着会话模型亲自裁决 —— 若延迟/成本敏感,用 `--auto-mode-model` 指向轻量模型(开放问题见 issue tracker)
|
|
@@ -177,7 +184,7 @@ tool_call
|
|
|
177
184
|
```bash
|
|
178
185
|
bun install
|
|
179
186
|
bun run typecheck
|
|
180
|
-
bun test #
|
|
187
|
+
bun test # 离线桩测试:自保护 / 变更检测 / deny floor / 用户规则 / denyPaths / 绕过回归 / 分类器重试 / 影子缓存 / 命令 / toggle 快捷键
|
|
181
188
|
```
|
|
182
189
|
|
|
183
190
|
Issue tracker 与决策记录在 GitHub issues(「地图」issue #1 为索引)。
|
package/extensions/auto-mode.ts
CHANGED
|
@@ -207,7 +207,7 @@ function userConfigPath(): string {
|
|
|
207
207
|
}
|
|
208
208
|
|
|
209
209
|
const USER_CONFIG_TEMPLATE = `${JSON.stringify({
|
|
210
|
-
_hint: "pi-verdict user rules. allow/deny are JS regex arrays; deny wins over allow. Match target: bash = full command string, file tools = absolute path. denyPaths is a list of protected path prefixes (plain paths, not regexes; the tool owns normalization — ~, $HOME, relative, .. and symlink forms all resolve — and any access attempt, including from bash command strings, asks for your confirmation, degrading to deny in non-interactive sessions; priority: after your deny rules, before your allow rules; never sent to the classifier). builtinDenyFloor=false disables the built-in danger/path floor (at your own risk; the self-protection layer always stays on and cannot be turned off by any config). classifierModel persistently sets the classifier model (provider/id, e.g. zai/glm-5.3-flash; accepts a pi-native thinking suffix, e.g. zai/glm-5.3-flash:low; empty = self-reflection, inherit session model). toggleShortcut sets the master-switch toggle key (pi key combo, e.g. ctrl+shift+a; null or empty disables the shortcut). This file is part of the permission gate itself: pi-verdict denies any agent-side modification of it — edit it manually outside pi. Changes apply to new sessions.",
|
|
210
|
+
_hint: "pi-verdict user rules. allow/deny are JS regex arrays; deny wins over allow. Match target: bash = full command string, file tools = absolute path. denyPaths is a list of protected path prefixes (plain paths, not regexes; the tool owns normalization — ~, $HOME, relative, .. and symlink forms all resolve, case folds on macOS/Windows — and any access attempt, including from bash command strings, asks for your confirmation, degrading to deny in non-interactive sessions; priority: after your deny rules, before your allow rules; never sent to the classifier). builtinDenyFloor=false disables the built-in danger/path floor (at your own risk; the self-protection layer always stays on and cannot be turned off by any config). classifierModel persistently sets the classifier model (provider/id, e.g. zai/glm-5.3-flash; accepts a pi-native thinking suffix, e.g. zai/glm-5.3-flash:low; empty = self-reflection, inherit session model). toggleShortcut sets the master-switch toggle key (pi key combo, e.g. ctrl+shift+a; null or empty disables the shortcut). This file is part of the permission gate itself: pi-verdict denies any agent-side modification of it — edit it manually outside pi. Changes apply to new sessions.",
|
|
211
211
|
allow: ["^ls\\b"],
|
|
212
212
|
deny: [],
|
|
213
213
|
denyPaths: [],
|
|
@@ -277,21 +277,57 @@ function expandHome(p: string): string {
|
|
|
277
277
|
return p.startsWith("~") ? path.join(os.homedir(), p.slice(1)) : p;
|
|
278
278
|
}
|
|
279
279
|
|
|
280
|
+
// All S-rules match case-insensitively (#21): on case-insensitive filesystems
|
|
281
|
+
// (default macOS APFS, Windows) case variants name the same file — realpath
|
|
282
|
+
// normalization covers existing targets, /i covers the lexical forms of
|
|
283
|
+
// nonexistent ones; on linux the uppercase spelling usually does not exist and
|
|
284
|
+
// the occasional false positive fails toward deny (safe direction).
|
|
280
285
|
const S0_SECRET = [
|
|
281
|
-
/\.ssh(\/|$)
|
|
282
|
-
/(^|\/)id_rsa
|
|
286
|
+
/\.ssh(\/|$)/i, /\.aws(\/|$)/i, /\.gnupg(\/|$)/i, /(^|\/)\.env(\.|$)/i, /credentials?(\.|\/|$)/i,
|
|
287
|
+
/(^|\/)id_rsa/i, /\.pem$/i, /_history$/i, /\.config\/gh(\/|$)/i, /\.pi\/agent\/auth\.json$/i,
|
|
283
288
|
// V8(安全审计):常见明文凭证文件补全
|
|
284
|
-
/(^|\/)\.netrc
|
|
285
|
-
/\.kube(\/|$)
|
|
289
|
+
/(^|\/)\.netrc$/i, /(^|\/)\.npmrc$/i, /(^|\/)\.pypirc$/i, /(^|\/)\.envrc$/i, /(^|\/)\.vault-token$/i,
|
|
290
|
+
/\.kube(\/|$)/i, /\.docker\/config\.json$/i, /\.gem\/credentials$/i,
|
|
286
291
|
];
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
const
|
|
292
|
+
// /private prefixes: macOS firmlinks — /etc, /var are really /private/etc,
|
|
293
|
+
// /private/var, and realpath'd toolchain output uses the real spelling (#21)
|
|
294
|
+
const S1_SYSTEM = [/^\/etc(\/|$)/i, /^\/private\/(etc|var)(\/|$)/i, /^\/usr(\/|$)/i, /^\/var(\/|$)/i, /^\/System(\/|$)/i, /(^|\/)authorized_keys$/i];
|
|
295
|
+
const S2_USER_RC = [/\.(bashrc|zshrc|profile|bash_profile|gitconfig)$/i, /crontab/i, /Library\/LaunchAgents(\/|$)/i, /\.config\/systemd(\/|$)/i];
|
|
296
|
+
const S3_GIT_META = [/(^|\/)\.git\/(hooks|config|modules)(\/|$)/i, /(^|\/)\.gitmodules$/i];
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* All canonical forms of a path for rule matching: the lexical absolute plus,
|
|
300
|
+
* whenever an existing ancestor can be resolved, the form rebuilt from that
|
|
301
|
+
* ancestor's realpath. Read and write targets may both not exist yet — walking
|
|
302
|
+
* up to the nearest existing ancestor means a symlink alias exposes its real
|
|
303
|
+
* form even when the final segments do not exist (#20).
|
|
304
|
+
*/
|
|
305
|
+
function targetForms(abs: string): string[] {
|
|
306
|
+
const out = new Set<string>([abs]);
|
|
307
|
+
let dir = abs;
|
|
308
|
+
const tail: string[] = [];
|
|
309
|
+
for (;;) {
|
|
310
|
+
try {
|
|
311
|
+
const real = fs.realpathSync(dir);
|
|
312
|
+
out.add(path.join(real, ...tail));
|
|
313
|
+
return [...out];
|
|
314
|
+
} catch {
|
|
315
|
+
const parent = path.dirname(dir);
|
|
316
|
+
if (parent === dir) return [...out];
|
|
317
|
+
tail.unshift(path.basename(dir));
|
|
318
|
+
dir = parent;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
}
|
|
290
322
|
|
|
291
323
|
/** read 类工具:S0 读取即高危(deny),其余读取放行。isWrite: write/edit 走完整分级 */
|
|
292
324
|
function classifyPath(toolName: string, rawPath: string, cwd: string, isWrite: boolean, floorOn: boolean): RuleResult {
|
|
293
325
|
const abs = path.resolve(cwd, expandHome(rawPath));
|
|
294
|
-
|
|
326
|
+
// Dual-form matching (#20): rules test every canonical form of the target —
|
|
327
|
+
// a project-local symlink aliasing ~/.ssh or a .git/hooks dir must not pass
|
|
328
|
+
// the floor on its lexical spelling alone.
|
|
329
|
+
const forms = targetForms(abs);
|
|
330
|
+
const hit = (rules: RegExp[]) => forms.some((f) => rules.some((r) => r.test(f)));
|
|
295
331
|
// floor 关闭时:内置 deny 一律降级 gray(永不升格 allow);非 deny 分支(allow/gray)保持
|
|
296
332
|
const D = floorOn
|
|
297
333
|
? (reason: string): RuleResult => ({ verdict: "deny", reason })
|
|
@@ -305,7 +341,12 @@ function classifyPath(toolName: string, rawPath: string, cwd: string, isWrite: b
|
|
|
305
341
|
if (hit(S1_SYSTEM)) return D(`write to system directory: ${rawPath}`);
|
|
306
342
|
if (hit(S3_GIT_META)) return D(`write to .git metadata (executable code entry point): ${rawPath}` );
|
|
307
343
|
if (hit(S2_USER_RC)) return { verdict: "gray", reason: `write to user config/persistence entry point: ${rawPath}` };
|
|
308
|
-
|
|
344
|
+
// In-cwd write allowance (#20): every canonical form must sit inside the cwd
|
|
345
|
+
// (in either its lexical or real form) — a lexical prefix hit whose real
|
|
346
|
+
// form escapes the project (symlink alias) grades as an outside-cwd write.
|
|
347
|
+
const cwdBases = new Set([cwd, tryRealpath(cwd)]);
|
|
348
|
+
const inCwd = (f: string) => [...cwdBases].some((b) => f === b || f.startsWith(b + path.sep));
|
|
349
|
+
if (forms.every(inCwd)) return { verdict: "allow" };
|
|
309
350
|
return { verdict: "gray", reason: `write outside project directory (CWD): ${rawPath}` };
|
|
310
351
|
}
|
|
311
352
|
|
|
@@ -362,6 +403,14 @@ function userRuleTarget(toolName: string, input: Record<string, unknown>, cwd: s
|
|
|
362
403
|
const BASH_PATH_TOKENS =
|
|
363
404
|
/(?:~|\$HOME)(?:\/[\w.@*-]+)*|\/(?:[\w.@*-]+\/)*[\w.@*-]*|\.{1,2}(?:\/[\w.@*-]+)+|[\w.-]+(?:\/[\w.-]+)+/g;
|
|
364
405
|
|
|
406
|
+
/** Case-insensitive filesystems (default macOS APFS, Windows) compare path strings
|
|
407
|
+
* case-folded; realpath already normalizes case whenever it resolves, this covers
|
|
408
|
+
* the lexical-only forms of nonexistent targets (#21). Linux stays case-sensitive. */
|
|
409
|
+
const CASE_INSENSITIVE_FS = process.platform === "darwin" || process.platform === "win32";
|
|
410
|
+
const fold = (s: string): string => (CASE_INSENSITIVE_FS ? s.toLowerCase() : s);
|
|
411
|
+
const pathEquals = (a: string, b: string): boolean => fold(a) === fold(b);
|
|
412
|
+
const pathStartsWith = (child: string, base: string): boolean => fold(child).startsWith(fold(base) + path.sep);
|
|
413
|
+
|
|
365
414
|
/** Normalized forms of one path (lexical + realpath when it exists) for denyPaths comparison */
|
|
366
415
|
function denyPathForms(raw: string, cwd: string): string[] {
|
|
367
416
|
if (!raw) return [];
|
|
@@ -393,7 +442,7 @@ function hitDenyPaths(toolName: string, input: Record<string, unknown>, cwd: str
|
|
|
393
442
|
for (const candidate of denyPathCandidates(toolName, input)) {
|
|
394
443
|
for (const c of denyPathForms(candidate, cwd)) {
|
|
395
444
|
for (const b of bases) {
|
|
396
|
-
if (c
|
|
445
|
+
if (pathEquals(c, b) || pathStartsWith(c, b)) return b;
|
|
397
446
|
}
|
|
398
447
|
}
|
|
399
448
|
}
|
|
@@ -511,10 +560,12 @@ export function buildProtectedSet(agentDir: string, ownFile: string | null): Pro
|
|
|
511
560
|
return { exact: [...exact], prefixes: [...prefixes], bashPatterns, watchBases };
|
|
512
561
|
}
|
|
513
562
|
|
|
514
|
-
/**
|
|
563
|
+
/** Does the resolved write path hit the protected set (realpath guards against
|
|
564
|
+
* symlink bypass; nonexistent targets rebuild their real form from the
|
|
565
|
+
* nearest existing ancestor, #20) */
|
|
515
566
|
export function isProtectedWritePath(rawPath: string, cwd: string, prot: ProtectedSet): boolean {
|
|
516
567
|
if (!rawPath) return false;
|
|
517
|
-
for (const c of
|
|
568
|
+
for (const c of targetForms(path.resolve(cwd, expandHome(rawPath)))) {
|
|
518
569
|
if (prot.exact.includes(c)) return true;
|
|
519
570
|
for (const p of prot.prefixes) {
|
|
520
571
|
if (c === p || c.startsWith(p + path.sep)) return true;
|
|
@@ -659,13 +710,23 @@ function sanitize(text: string): string {
|
|
|
659
710
|
if (cleaned.length <= MAX_ENTRY_CHARS) return cleaned;
|
|
660
711
|
const head = Math.floor(MAX_ENTRY_CHARS * 0.6);
|
|
661
712
|
const tail = MAX_ENTRY_CHARS - head;
|
|
662
|
-
return `${cleaned.slice(0, head)}
|
|
713
|
+
return `${cleaned.slice(0, head)}…[truncated]…${cleaned.slice(-tail)}`;
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
/** Transcript line body: sanitized (zero-width stripped, length-capped) with
|
|
717
|
+
* line breaks escaped in place — the transcript is line-structured ("User: …" /
|
|
718
|
+
* "tool: …"), and an embedded line break in a path, command, or message could
|
|
719
|
+
* otherwise forge a structural line (#22). Covers \n, \r\n, lone \r and the
|
|
720
|
+
* Unicode separators U+2028/U+2029/U+0085, which models may render as breaks.
|
|
721
|
+
* Content is preserved, only the line structure is defended. */
|
|
722
|
+
function transcriptSafe(text: string): string {
|
|
723
|
+
return sanitize(text).replace(/[\r\n\u2028\u2029\u0085]/g, "\\n");
|
|
663
724
|
}
|
|
664
725
|
|
|
665
726
|
function toolCallLine(name: string, args: Record<string, unknown>): string {
|
|
666
|
-
if (typeof args.command === "string") return `${name}: ${
|
|
667
|
-
if (typeof args.path === "string") return `${name}: ${args.path}`;
|
|
668
|
-
return `${name}: ${
|
|
727
|
+
if (typeof args.command === "string") return `${name}: ${transcriptSafe(args.command)}`;
|
|
728
|
+
if (typeof args.path === "string") return `${name}: ${transcriptSafe(args.path)}`;
|
|
729
|
+
return `${name}: ${transcriptSafe(JSON.stringify(args))}`;
|
|
669
730
|
}
|
|
670
731
|
|
|
671
732
|
/**
|
|
@@ -681,7 +742,7 @@ function collectTranscriptParts(ctx: ExtensionContext): { userLines: string[]; t
|
|
|
681
742
|
const msg = entry.message;
|
|
682
743
|
if (msg.role === "user") {
|
|
683
744
|
const text = typeof msg.content === "string" ? msg.content : msg.content.filter((b) => b.type === "text").map((b) => b.text).join("\n");
|
|
684
|
-
if (text.trim()) userLines.push(`User: ${
|
|
745
|
+
if (text.trim()) userLines.push(`User: ${transcriptSafe(text)}`);
|
|
685
746
|
} else if (msg.role === "assistant") {
|
|
686
747
|
for (const block of msg.content) {
|
|
687
748
|
if (block.type === "toolCall") toolLines.push(toolCallLine(block.name, block.arguments as Record<string, unknown>));
|