pi-information-protecter 0.11.1 → 0.12.0
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/CHANGELOG.md +7 -0
- package/README.md +21 -1
- package/dist/index.mjs +20 -15
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
# Changelog / 更新日志
|
|
2
2
|
|
|
3
|
+
## 0.12.0 — Offline rule testing without a model / 无需模型的离线规则测试
|
|
4
|
+
|
|
5
|
+
### Added / 新增
|
|
6
|
+
|
|
7
|
+
- Add `/protecter test <text>` and `/protecter test @<path>`: redact local text or a local text file (up to 256 KiB) and show the result, without sending anything to a model. It runs the same rules, the same worker and the same mapping table as a real request, so a new rule can be verified offline; the run writes an audit record and the replacements it learns stay in the session mapping. The path is read with `lstat`, so a symbolic link cannot redirect the read, and unreadable or oversized input reports `TEST_INPUT`/`TEST_SIZE` instead of a raw path or message.
|
|
8
|
+
新增 `/protecter test <文本>` 与 `/protecter test @<路径>`:对本地文本或本地文本文件(上限 256 KiB)脱敏并展示结果,全程不向模型发送内容。它与真实请求走同一套规则、同一个 worker 和同一张映射表,因此可离线验证新规则;本次运行会写入审计记录,学到的替换关系也保留在会话映射中。路径使用 `lstat` 读取,符号链接无法改变读取目标;不可读或超大输入返回 `TEST_INPUT`/`TEST_SIZE`,而不暴露路径或原始消息。
|
|
9
|
+
|
|
3
10
|
## 0.11.1 — Documented IP rules, and a README that leads with coverage / 文档内的 IP 规则,以覆盖范围开篇的 README
|
|
4
11
|
|
|
5
12
|
### Added / 新增
|
package/README.md
CHANGED
|
@@ -133,8 +133,17 @@ The reply quietly contradicts itself, looks confident, and does not change if yo
|
|
|
133
133
|
| `/protecter logs [1-100]` | Open the local audit log viewer (default 20 records) |
|
|
134
134
|
| `/protecter logs clear` | Empty this machine's audit log |
|
|
135
135
|
| `/protecter reload` | Reload Pi once it is idle |
|
|
136
|
+
| `/protecter test <text>` | Redact the text locally and show the result; nothing is sent to a model |
|
|
137
|
+
| `/protecter test @<path>` | Same, with the content of a local text file (up to 256 KiB) |
|
|
136
138
|
|
|
137
|
-
Never type a secret as a command argument.
|
|
139
|
+
Never type a secret as a command argument — `test` is the one exception, because its input never leaves this machine.
|
|
140
|
+
|
|
141
|
+
`test` runs the same rules, worker and mapping table as a real request: it writes an audit record and the replacements it learns stay in the session mapping, so later replies containing them are still restored. Use it to check a new rule offline before sending anything.
|
|
142
|
+
|
|
143
|
+
```text
|
|
144
|
+
/protecter test Call Alex Morgan at 13800138000
|
|
145
|
+
/protecter test @./demo.txt
|
|
146
|
+
```
|
|
138
147
|
|
|
139
148
|
### Context compaction
|
|
140
149
|
|
|
@@ -396,6 +405,17 @@ pi update npm:pi-information-protecter
|
|
|
396
405
|
| `/protecter logs [1-100]` | 打开本地审计日志查看器(默认 20 条) |
|
|
397
406
|
| `/protecter logs clear` | 清空本机审计日志 |
|
|
398
407
|
| `/protecter reload` | 等待空闲后重载 Pi |
|
|
408
|
+
| `/protecter test <文本>` | 在本地对文本脱敏并展示结果,不向模型发送内容 |
|
|
409
|
+
| `/protecter test @<路径>` | 同上,输入为本地文本文件内容(上限 256 KiB) |
|
|
410
|
+
|
|
411
|
+
除 `test` 外,不要在命令参数中输入敏感内容;`test` 的输入不会离开本机。
|
|
412
|
+
|
|
413
|
+
`test` 与真实请求走同一套规则、worker 和映射表:会写入审计记录,且本次学到的替换关系保留在会话映射中,后续回复中出现该替换值仍可还原。可用它在发送任何内容前离线验证新规则。
|
|
414
|
+
|
|
415
|
+
```text
|
|
416
|
+
/protecter test 联系 Alex Morgan,电话 13800138000
|
|
417
|
+
/protecter test @./demo.txt
|
|
418
|
+
```
|
|
399
419
|
|
|
400
420
|
不要把秘密作为命令参数输入。
|
|
401
421
|
|
package/dist/index.mjs
CHANGED
|
@@ -1,24 +1,29 @@
|
|
|
1
1
|
/*! SPI Protecter | MIT | see LICENSE / SPI 隐私保护插件 | MIT 许可 */
|
|
2
|
-
import{getAgentDir as wt,VERSION as St}from"@earendil-works/pi-coding-agent";import{Worker as mt}from"node:worker_threads";import{fileURLToPath as pt}from"node:url";import*as I from"node:fs";import{join as T,resolve as nt}from"node:path";import{createHash as ot,randomUUID as rt}from"node:crypto";import{Worker as it}from"node:worker_threads";import{fileURLToPath as st}from"node:url";var R="0.84.0-0.84.x, 0.85.1-0.87.x, 0.99.x, 1.2.0-1.3.x";function se(t){let e=/^(\d+)\.(\d+)\.(\d+)/.exec(t);if(!e)return!1;let[o,n,r]=e.slice(1).map(Number);return o===1?n===2||n===3:o!==0?!1:n===84?!0:n===85?r>=1:n===86||n===87||n===99}var $={INTERNAL:["Unexpected local failure","Reload; check the installed package integrity"],NOT_READY:["Protection is not initialized","Run /protecter status for the initialization error, fix it, then /reload"],UNSUPPORTED_PI:["Unsupported Pi version",`Use Pi ${R}`],GUARD_UNAVAILABLE:["Cannot cover the model calls that have no extension hook","This Pi build exposes no model runtime to wrap; use Pi "+R+" or set a trusted Pi version"],MACHINE_ID:["Machine identifier unavailable","Check local OS machine-ID access; no random fallback is used"],CONFIG_JSON:["Invalid configuration JSON","Fix JSON syntax locally, then /reload"],CONFIG_SCHEMA:["Invalid configuration structure or rule","Use version 1, a sensitiveWords array and documented fields; rule shows the 1-based index"],CONFIG_REGEX:["Invalid regex or flags","Fix the numbered rule; flags support gimsu only"],CONFIG_TARGET:["Invalid fixed replacement target","Use a non-blank string under 8192 characters without reserved __PIP_ names"],CONFIG_CONFLICT:["Conflicting rule definitions","Give the same matcher one replacement policy across all configs"],CONFIG_SIZE:["Configuration exceeds size or rule limit","Reduce configuration size or rule count; rules are never truncated"],CONFIG_IO:["Cannot access configuration","Check local permissions, ownership and free space"],CONFIG_UNSAFE:["Unsafe configuration file","Use an owned regular file without symbolic or hard links"],CONFIG_EMPTY_MATCH:["Regex matches an empty string","Require a non-empty match in the numbered rule"],CONFIG_SENSITIVE_TARGET:["Fixed target overlaps a sensitive rule","Choose a target unrelated to every sensitive matcher"],CONFIG_ALIAS_CONFLICT:["Fixed aliases overlap each other","Use distinct aliases that are not substrings of one another"],CONFIG_TIMEOUT:["Rule validation timed out","Simplify regex rules, then /reload"],MIGRATION_LOCKED:["Configuration migration lock is busy","Wait for other Pi processes; inspect a stale lock only after stopping them"],MIGRATION_CHANGED:["Configuration changed during migration","Stop concurrent edits and /reload; source files are preserved"],MIGRATION_LIMIT:["Too many configuration candidates","Consolidate old configuration files locally"],MIGRATION_IO:["Migration file operation failed","Check permissions, free space and leftover files before retrying"],PAYLOAD_JSON:["Request is not serializable JSON","Inspect the provider or another payload-modifying extension; no payload is logged"],PAYLOAD_SIZE:["Request exceeds the size limit","Reduce history or tool output size, or start a new session"],SCAN_TIMEOUT:["Redaction worker timed out","Simplify regex rules or reduce input size"],WORKER_FAILED:["Worker failed to start or exited early","Verify all dist files and the Node version; reinstall if needed"],SCAN_INTERNAL:["Unexpected scan failure","Review recent rule changes and retry with smaller input"],SCAN_NUMBER_UNSAFE:["Replacement would turn a numeric JSON value into an invalid number","Narrow the rule so it does not match inside numeric fields such as timestamps or schema limits"],SCAN_UNIQUE_FAILED:["Could not generate a unique shape-preserving replacement","The matched value is too short; match a longer value or set an explicit replacement"],SCAN_ZERO_WIDTH:["Regex produced a zero-width match","Require a non-empty match in the numbered rule"],SCAN_MATCH_LIMIT:["Too many matches in one request","Narrow overly broad rules or reduce input"],SCAN_MAPPING_LIMIT:["Mapping limit reached","Start a new session or /reload; in-memory mappings reset"],FIXED_MAPPING_CONFLICT:["One original has conflicting replacements","Use one replacement for overlapping matchers, then /reload"],FIXED_ALIAS_REUSED:["Fixed alias already maps to another original","A fixed regex represents one original per instance; use random replacement or split literal rules"],FIXED_SENSITIVE_TARGET:["Replacement contains the matched original","Choose a target without sensitive content"],FIXED_OVERLAP:["Fixed replacement partially overlaps another match","Remove the partial overlap or use random rules; rule and otherRule show both rules"],FIXED_ALIAS_CROSSING:["Regex crosses a learned fixed alias","Narrow the regex or choose a different alias"],SCAN_COMPLEXITY:["Request exceeds depth or node limits","Reduce nested data and tool schema size"],SCAN_JSON_REWRITE:["Replacement breaks embedded JSON syntax","Avoid rules spanning JSON syntax; match field values instead"],SCAN_ATTACHMENT:["Unsupported image, audio, video or file content","Remove attachments or send reviewed text only"],SCAN_KEY_COLLISION:["Replacement creates duplicate object keys","Use distinct targets or avoid matching schema keys"],RESTORE_COMPLEXITY:["Response nesting is too deep to restore","Reduce nested structures or start a new session with /new"],RESTORE_KEY_COLLISION:["Restoring produced duplicate object keys","Use more specific rules or fixed targets that cannot collide with schema keys"],COMPACT_DENIED:["Compaction refused",'Allow it when asked, or set "compaction" to "protected" in the local config'],COMPACT_FAILED:["Could not redact what Pi is about to summarize",'Retry; if it persists, set "compaction" to "off" and use /new'],COMPACT_INSTRUCTIONS:["The compaction instruction contains a protected value","Pi reads that instruction from its own state, so it cannot be redacted: run /compact without it"],CONFIG_COMPACTION:["Invalid compaction setting",'Use "ask", "protected" or "off", or an object with mode'],AUDIT_BATCH_LIMIT:["Audit batch exceeds the size limit","Reduce matched content per request"],AUDIT_FULL:["Audit log would exceed the size limit","Review records, then run /protecter logs clear or archive locally"],AUDIT_PARTIAL:["Audit log has an incomplete last line","Inspect locally or run /protecter logs clear; never upload the log"],AUDIT_LOCKED:["Audit lock stayed busy","Wait for writers; stop all Pi processes before inspecting a stale lock"],AUDIT_UNSAFE:["Unsafe audit file","Use an owned regular file without links; checks are not bypassed"],AUDIT_IO:["Audit file operation failed","Check errno, permissions and free space; no path or content is exposed"]},He={INTERNAL:["未预期的本地错误","重载并检查安装包完整性"],NOT_READY:["防护尚未初始化","查看初始化错误,修复后重载"],UNSUPPORTED_PI:["Pi 版本不受支持",`请使用 Pi ${R}`],GUARD_UNAVAILABLE:["无法覆盖没有扩展钩子的模型调用","该 Pi 构建未暴露可包装的模型运行时:请使用 Pi "+R+" 或改用可信的 Pi 版本"],MACHINE_ID:["无法获取机器标识","检查系统机器标识访问权限,不使用随机回退"],CONFIG_JSON:["配置 JSON 无效","本地修复 JSON 语法后重载"],CONFIG_SCHEMA:["配置结构或规则无效","使用版本1、敏感词数组及文档字段,rule 为规则序号"],CONFIG_REGEX:["正则或标志无效","修复指定规则,标志仅支持 gimsu"],CONFIG_TARGET:["固定替换目标无效","使用非空且少于8192字符的目标,不含保留名称"],CONFIG_CONFLICT:["规则定义冲突","为同一匹配器设置一致的替换策略"],CONFIG_SIZE:["配置超过体积或规则数上限","减少配置体积或规则数,规则不会被截断"],CONFIG_IO:["无法访问配置","检查本地权限、所有者和磁盘空间"],CONFIG_UNSAFE:["配置文件不安全","使用本人所有的普通文件,不含符号或硬链接"],CONFIG_EMPTY_MATCH:["正则匹配空字符串","修改指定规则,要求非空匹配"],CONFIG_SENSITIVE_TARGET:["固定目标与敏感规则重叠","选择与所有敏感匹配器无关的目标"],CONFIG_ALIAS_CONFLICT:["固定别名相互重叠","使用互不包含的不同别名"],CONFIG_TIMEOUT:["规则验证超时","简化正则规则后重载"],MIGRATION_LOCKED:["配置迁移锁被占用","等待其他进程,全部停止后再检查残留锁"],MIGRATION_CHANGED:["迁移期间配置发生变化","停止并发编辑后重载,源文件会保留"],MIGRATION_LIMIT:["候选配置过多","在本地整理旧配置文件"],MIGRATION_IO:["迁移文件操作失败","检查权限、空间和残留文件后重试"],PAYLOAD_JSON:["请求无法序列化为 JSON","检查提供商或其他请求改写扩展,不记录请求内容"],PAYLOAD_SIZE:["请求超过体积上限","减少历史或工具输出,或新建会话"],SCAN_TIMEOUT:["脱敏 worker 超时","简化正则规则或缩小输入"],WORKER_FAILED:["worker 启动失败或提前退出","检查 dist 文件完整性和 Node 版本,必要时重装"],SCAN_INTERNAL:["未预期的扫描错误","检查最近的规则改动并缩小输入"],SCAN_NUMBER_UNSAFE:["替换会把 JSON 数值变成无效数字","缩小规则范围,避免匹配时间戳或结构上限等数值字段"],SCAN_UNIQUE_FAILED:["无法生成唯一的同形替换值","命中内容过短或可选空间过小,请匹配更长内容或设置固定 replacement"],SCAN_ZERO_WIDTH:["正则产生零宽匹配","修改指定规则,要求非空匹配"],SCAN_MATCH_LIMIT:["单次请求匹配次数过多","缩小过宽规则或减少输入"],SCAN_MAPPING_LIMIT:["映射数量达到上限","新建会话或重载,内存映射将重置"],FIXED_MAPPING_CONFLICT:["同一原文存在冲突替换","为重叠匹配器使用同一目标后重载"],FIXED_ALIAS_REUSED:["固定别名已映射其他原文","固定正则在同一实例仅代表一种原文,改用随机替换或拆分字面规则"],FIXED_SENSITIVE_TARGET:["替换目标包含命中原文","选择不含敏感内容的目标"],FIXED_OVERLAP:["固定替换与其他匹配部分重叠","消除部分重叠或改用随机规则,rule 与 otherRule 指出两条规则"],FIXED_ALIAS_CROSSING:["正则跨越已学习的固定别名","缩小正则范围或更换别名"],SCAN_COMPLEXITY:["请求超过层级或节点上限","减少嵌套数据和工具结构体积"],SCAN_JSON_REWRITE:["替换破坏内嵌 JSON 语法","避免跨 JSON 语法的规则,改为匹配字段值"],SCAN_ATTACHMENT:["不支持图片、音频、视频或文件内容","移除附件或仅发送已审查的文本"],SCAN_KEY_COLLISION:["替换后对象键重复","使用不同目标或避免匹配结构键"],RESTORE_COMPLEXITY:["还原响应时层级过深","减少嵌套结构,或使用 /new 开始新会话"],RESTORE_KEY_COLLISION:["还原后对象键重复","使用更具体的规则或固定替换目标,避免与结构键冲突"],COMPACT_DENIED:["压缩被拒绝",'询问时选择允许,或在本地配置中将 "compaction" 设为 "protected"'],COMPACT_FAILED:["无法对 Pi 即将摘要的内容脱敏",'请重试;若持续失败,将 "compaction" 设为 "off" 并使用 /new'],COMPACT_INSTRUCTIONS:["压缩指令中包含受保护值","Pi 从自身状态读取该指令,无法脱敏:请不带该指令执行 /compact"],CONFIG_COMPACTION:["compaction 配置值无效",'请使用 "ask"、"protected"、"off",或含 mode 的对象'],AUDIT_BATCH_LIMIT:["审计批次超过上限","减少单个请求的命中内容"],AUDIT_FULL:["审计日志将超过上限","检查记录后清空日志或本地归档"],AUDIT_PARTIAL:["审计日志末行不完整","本地检查或清空日志,不要上传日志"],AUDIT_LOCKED:["审计锁持续被占用","等待写入完成,全部停止后再检查残留锁"],AUDIT_UNSAFE:["审计文件不安全","使用本人普通文件且不含链接,不会绕过检查"],AUDIT_IO:["审计文件操作失败","检查错误码、权限和磁盘空间,不暴露路径或内容"]},ae={blockedHeader:"SPI Protecter blocked this request",reasonLabel:"Reason",actionLabel:"Action",detailsLabel:"Details",statusReady:"ready",statusNotReady:"not ready",statusLine:"SPI Protecter: {state}; {rules}; {mappings}. Memory snapshot; /reload to refresh.",statusLastBlock:"Last block @ {at}:",statusNoBlock:"No recorded block in this session.",statusBarRules:"SPI Protecter · {rules}",statusBarNotReady:"SPI Protecter · not ready",emptyRules:"SPI Protecter: no rules configured; edit the local machine config, then /reload.",commandDescription:"View local SPI protection records",usage:"Usage: /protecter [logs [1-100|clear]|status|reload]. Never type secrets as arguments.",logsTuiOnly:"Open the local TUI to view protection records.",logsNone:"No readable records.",logsSelectTitle:"Protection records",logsTruncated:" (limited tail)",logsRevealTitle:"Sensitive plaintext",logsRevealBody:"Reveal locally? Never share this view.",logsPreviewTitle:"Local preview; edits are discarded",logsPreviewTruncated:"[Preview truncated]",clearTitle:"Clear the current audit log?",clearBody:"Irreversible. Only this machine's log is cleared; configuration and in-memory mappings stay. Later requests may add new records.",cleared:"Audit log cleared: {bytes}.",toolBlocked:"SPI Protecter blocked tool access to the protected configuration or audit log; edit it locally.",compactAskTitle:"Compact this conversation?",compactAskBody:`Pi builds the summarization request internally and never routes it through this extension's redaction, so letting Pi summarize as-is would send the conversation, including protected values, as plaintext.
|
|
2
|
+
import{getAgentDir as _t,VERSION as Rt}from"@earendil-works/pi-coding-agent";import{Worker as gt}from"node:worker_threads";import{fileURLToPath as ht}from"node:url";import*as I from"node:fs";import{join as D,resolve as ot}from"node:path";import{createHash as it,randomUUID as st}from"node:crypto";import{Worker as at}from"node:worker_threads";import{fileURLToPath as ct}from"node:url";var M="0.84.0-0.84.x, 0.85.1-0.87.x, 0.99.x, 1.2.0-1.3.x";function ce(t){let e=/^(\d+)\.(\d+)\.(\d+)/.exec(t);if(!e)return!1;let[r,n,o]=e.slice(1).map(Number);return r===1?n===2||n===3:r!==0?!1:n===84?!0:n===85?o>=1:n===86||n===87||n===99}var K={INTERNAL:["Unexpected local failure","Reload; check the installed package integrity"],NOT_READY:["Protection is not initialized","Run /protecter status for the initialization error, fix it, then /reload"],UNSUPPORTED_PI:["Unsupported Pi version",`Use Pi ${M}`],GUARD_UNAVAILABLE:["Cannot cover the model calls that have no extension hook","This Pi build exposes no model runtime to wrap; use Pi "+M+" or set a trusted Pi version"],MACHINE_ID:["Machine identifier unavailable","Check local OS machine-ID access; no random fallback is used"],CONFIG_JSON:["Invalid configuration JSON","Fix JSON syntax locally, then /reload"],CONFIG_SCHEMA:["Invalid configuration structure or rule","Use version 1, a sensitiveWords array and documented fields; rule shows the 1-based index"],CONFIG_REGEX:["Invalid regex or flags","Fix the numbered rule; flags support gimsu only"],CONFIG_TARGET:["Invalid fixed replacement target","Use a non-blank string under 8192 characters without reserved __PIP_ names"],CONFIG_CONFLICT:["Conflicting rule definitions","Give the same matcher one replacement policy across all configs"],CONFIG_SIZE:["Configuration exceeds size or rule limit","Reduce configuration size or rule count; rules are never truncated"],CONFIG_IO:["Cannot access configuration","Check local permissions, ownership and free space"],CONFIG_UNSAFE:["Unsafe configuration file","Use an owned regular file without symbolic or hard links"],CONFIG_EMPTY_MATCH:["Regex matches an empty string","Require a non-empty match in the numbered rule"],CONFIG_SENSITIVE_TARGET:["Fixed target overlaps a sensitive rule","Choose a target unrelated to every sensitive matcher"],CONFIG_ALIAS_CONFLICT:["Fixed aliases overlap each other","Use distinct aliases that are not substrings of one another"],CONFIG_TIMEOUT:["Rule validation timed out","Simplify regex rules, then /reload"],MIGRATION_LOCKED:["Configuration migration lock is busy","Wait for other Pi processes; inspect a stale lock only after stopping them"],MIGRATION_CHANGED:["Configuration changed during migration","Stop concurrent edits and /reload; source files are preserved"],MIGRATION_LIMIT:["Too many configuration candidates","Consolidate old configuration files locally"],MIGRATION_IO:["Migration file operation failed","Check permissions, free space and leftover files before retrying"],PAYLOAD_JSON:["Request is not serializable JSON","Inspect the provider or another payload-modifying extension; no payload is logged"],PAYLOAD_SIZE:["Request exceeds the size limit","Reduce history or tool output size, or start a new session"],SCAN_TIMEOUT:["Redaction worker timed out","Simplify regex rules or reduce input size"],WORKER_FAILED:["Worker failed to start or exited early","Verify all dist files and the Node version; reinstall if needed"],SCAN_INTERNAL:["Unexpected scan failure","Review recent rule changes and retry with smaller input"],SCAN_NUMBER_UNSAFE:["Replacement would turn a numeric JSON value into an invalid number","Narrow the rule so it does not match inside numeric fields such as timestamps or schema limits"],SCAN_UNIQUE_FAILED:["Could not generate a unique shape-preserving replacement","The matched value is too short; match a longer value or set an explicit replacement"],SCAN_ZERO_WIDTH:["Regex produced a zero-width match","Require a non-empty match in the numbered rule"],SCAN_MATCH_LIMIT:["Too many matches in one request","Narrow overly broad rules or reduce input"],SCAN_MAPPING_LIMIT:["Mapping limit reached","Start a new session or /reload; in-memory mappings reset"],FIXED_MAPPING_CONFLICT:["One original has conflicting replacements","Use one replacement for overlapping matchers, then /reload"],FIXED_ALIAS_REUSED:["Fixed alias already maps to another original","A fixed regex represents one original per instance; use random replacement or split literal rules"],FIXED_SENSITIVE_TARGET:["Replacement contains the matched original","Choose a target without sensitive content"],FIXED_OVERLAP:["Fixed replacement partially overlaps another match","Remove the partial overlap or use random rules; rule and otherRule show both rules"],FIXED_ALIAS_CROSSING:["Regex crosses a learned fixed alias","Narrow the regex or choose a different alias"],SCAN_COMPLEXITY:["Request exceeds depth or node limits","Reduce nested data and tool schema size"],SCAN_JSON_REWRITE:["Replacement breaks embedded JSON syntax","Avoid rules spanning JSON syntax; match field values instead"],SCAN_ATTACHMENT:["Unsupported image, audio, video or file content","Remove attachments or send reviewed text only"],SCAN_KEY_COLLISION:["Replacement creates duplicate object keys","Use distinct targets or avoid matching schema keys"],RESTORE_COMPLEXITY:["Response nesting is too deep to restore","Reduce nested structures or start a new session with /new"],RESTORE_KEY_COLLISION:["Restoring produced duplicate object keys","Use more specific rules or fixed targets that cannot collide with schema keys"],COMPACT_DENIED:["Compaction refused",'Allow it when asked, or set "compaction" to "protected" in the local config'],COMPACT_FAILED:["Could not redact what Pi is about to summarize",'Retry; if it persists, set "compaction" to "off" and use /new'],COMPACT_INSTRUCTIONS:["The compaction instruction contains a protected value","Pi reads that instruction from its own state, so it cannot be redacted: run /compact without it"],CONFIG_COMPACTION:["Invalid compaction setting",'Use "ask", "protected" or "off", or an object with mode'],AUDIT_BATCH_LIMIT:["Audit batch exceeds the size limit","Reduce matched content per request"],AUDIT_FULL:["Audit log would exceed the size limit","Review records, then run /protecter logs clear or archive locally"],AUDIT_PARTIAL:["Audit log has an incomplete last line","Inspect locally or run /protecter logs clear; never upload the log"],AUDIT_LOCKED:["Audit lock stayed busy","Wait for writers; stop all Pi processes before inspecting a stale lock"],AUDIT_UNSAFE:["Unsafe audit file","Use an owned regular file without links; checks are not bypassed"],AUDIT_IO:["Audit file operation failed","Check errno, permissions and free space; no path or content is exposed"],TEST_INPUT:["Cannot read the offline test input","Pass text, or @<path> pointing to a readable regular text file"],TEST_SIZE:["Offline test input exceeds the size limit","Test a smaller file or a shorter excerpt"]},Je={INTERNAL:["未预期的本地错误","重载并检查安装包完整性"],NOT_READY:["防护尚未初始化","查看初始化错误,修复后重载"],UNSUPPORTED_PI:["Pi 版本不受支持",`请使用 Pi ${M}`],GUARD_UNAVAILABLE:["无法覆盖没有扩展钩子的模型调用","该 Pi 构建未暴露可包装的模型运行时:请使用 Pi "+M+" 或改用可信的 Pi 版本"],MACHINE_ID:["无法获取机器标识","检查系统机器标识访问权限,不使用随机回退"],CONFIG_JSON:["配置 JSON 无效","本地修复 JSON 语法后重载"],CONFIG_SCHEMA:["配置结构或规则无效","使用版本1、敏感词数组及文档字段,rule 为规则序号"],CONFIG_REGEX:["正则或标志无效","修复指定规则,标志仅支持 gimsu"],CONFIG_TARGET:["固定替换目标无效","使用非空且少于8192字符的目标,不含保留名称"],CONFIG_CONFLICT:["规则定义冲突","为同一匹配器设置一致的替换策略"],CONFIG_SIZE:["配置超过体积或规则数上限","减少配置体积或规则数,规则不会被截断"],CONFIG_IO:["无法访问配置","检查本地权限、所有者和磁盘空间"],CONFIG_UNSAFE:["配置文件不安全","使用本人所有的普通文件,不含符号或硬链接"],CONFIG_EMPTY_MATCH:["正则匹配空字符串","修改指定规则,要求非空匹配"],CONFIG_SENSITIVE_TARGET:["固定目标与敏感规则重叠","选择与所有敏感匹配器无关的目标"],CONFIG_ALIAS_CONFLICT:["固定别名相互重叠","使用互不包含的不同别名"],CONFIG_TIMEOUT:["规则验证超时","简化正则规则后重载"],MIGRATION_LOCKED:["配置迁移锁被占用","等待其他进程,全部停止后再检查残留锁"],MIGRATION_CHANGED:["迁移期间配置发生变化","停止并发编辑后重载,源文件会保留"],MIGRATION_LIMIT:["候选配置过多","在本地整理旧配置文件"],MIGRATION_IO:["迁移文件操作失败","检查权限、空间和残留文件后重试"],PAYLOAD_JSON:["请求无法序列化为 JSON","检查提供商或其他请求改写扩展,不记录请求内容"],PAYLOAD_SIZE:["请求超过体积上限","减少历史或工具输出,或新建会话"],SCAN_TIMEOUT:["脱敏 worker 超时","简化正则规则或缩小输入"],WORKER_FAILED:["worker 启动失败或提前退出","检查 dist 文件完整性和 Node 版本,必要时重装"],SCAN_INTERNAL:["未预期的扫描错误","检查最近的规则改动并缩小输入"],SCAN_NUMBER_UNSAFE:["替换会把 JSON 数值变成无效数字","缩小规则范围,避免匹配时间戳或结构上限等数值字段"],SCAN_UNIQUE_FAILED:["无法生成唯一的同形替换值","命中内容过短或可选空间过小,请匹配更长内容或设置固定 replacement"],SCAN_ZERO_WIDTH:["正则产生零宽匹配","修改指定规则,要求非空匹配"],SCAN_MATCH_LIMIT:["单次请求匹配次数过多","缩小过宽规则或减少输入"],SCAN_MAPPING_LIMIT:["映射数量达到上限","新建会话或重载,内存映射将重置"],FIXED_MAPPING_CONFLICT:["同一原文存在冲突替换","为重叠匹配器使用同一目标后重载"],FIXED_ALIAS_REUSED:["固定别名已映射其他原文","固定正则在同一实例仅代表一种原文,改用随机替换或拆分字面规则"],FIXED_SENSITIVE_TARGET:["替换目标包含命中原文","选择不含敏感内容的目标"],FIXED_OVERLAP:["固定替换与其他匹配部分重叠","消除部分重叠或改用随机规则,rule 与 otherRule 指出两条规则"],FIXED_ALIAS_CROSSING:["正则跨越已学习的固定别名","缩小正则范围或更换别名"],SCAN_COMPLEXITY:["请求超过层级或节点上限","减少嵌套数据和工具结构体积"],SCAN_JSON_REWRITE:["替换破坏内嵌 JSON 语法","避免跨 JSON 语法的规则,改为匹配字段值"],SCAN_ATTACHMENT:["不支持图片、音频、视频或文件内容","移除附件或仅发送已审查的文本"],SCAN_KEY_COLLISION:["替换后对象键重复","使用不同目标或避免匹配结构键"],RESTORE_COMPLEXITY:["还原响应时层级过深","减少嵌套结构,或使用 /new 开始新会话"],RESTORE_KEY_COLLISION:["还原后对象键重复","使用更具体的规则或固定替换目标,避免与结构键冲突"],COMPACT_DENIED:["压缩被拒绝",'询问时选择允许,或在本地配置中将 "compaction" 设为 "protected"'],COMPACT_FAILED:["无法对 Pi 即将摘要的内容脱敏",'请重试;若持续失败,将 "compaction" 设为 "off" 并使用 /new'],COMPACT_INSTRUCTIONS:["压缩指令中包含受保护值","Pi 从自身状态读取该指令,无法脱敏:请不带该指令执行 /compact"],CONFIG_COMPACTION:["compaction 配置值无效",'请使用 "ask"、"protected"、"off",或含 mode 的对象'],AUDIT_BATCH_LIMIT:["审计批次超过上限","减少单个请求的命中内容"],AUDIT_FULL:["审计日志将超过上限","检查记录后清空日志或本地归档"],AUDIT_PARTIAL:["审计日志末行不完整","本地检查或清空日志,不要上传日志"],AUDIT_LOCKED:["审计锁持续被占用","等待写入完成,全部停止后再检查残留锁"],AUDIT_UNSAFE:["审计文件不安全","使用本人普通文件且不含链接,不会绕过检查"],AUDIT_IO:["审计文件操作失败","检查错误码、权限和磁盘空间,不暴露路径或内容"],TEST_INPUT:["无法读取离线测试输入","请直接传入文本,或用 @<路径> 指向可读的普通文本文件"],TEST_SIZE:["离线测试输入超出大小上限","改用更小的文件或更短的片段"]},le={blockedHeader:"SPI Protecter blocked this request",reasonLabel:"Reason",actionLabel:"Action",detailsLabel:"Details",statusReady:"ready",statusNotReady:"not ready",statusLine:"SPI Protecter: {state}; {rules}; {mappings}. Memory snapshot; /reload to refresh.",statusLastBlock:"Last block @ {at}:",statusNoBlock:"No recorded block in this session.",statusBarRules:"SPI Protecter · {rules}",statusBarNotReady:"SPI Protecter · not ready",emptyRules:"SPI Protecter: no rules configured; edit the local machine config, then /reload.",commandDescription:"View local SPI protection records",usage:"Usage: /protecter [logs [1-100|clear]|status|reload|test <text>|test @<path>]. Only `test` takes content; never type secrets as other arguments.",testPreviewTitle:"Offline redaction test; local only, edits are discarded",testRedacted:"SPI Protecter: redacted locally ({chars}); nothing was sent to a model. Replacements are now learned for this session.",testUnchanged:"SPI Protecter: no rule matched ({chars}); the text below is unchanged.",testFileLabel:"Input: local file",testTextLabel:"Input: inline text",logsTuiOnly:"Open the local TUI to view protection records.",logsNone:"No readable records.",logsSelectTitle:"Protection records",logsTruncated:" (limited tail)",logsRevealTitle:"Sensitive plaintext",logsRevealBody:"Reveal locally? Never share this view.",logsPreviewTitle:"Local preview; edits are discarded",logsPreviewTruncated:"[Preview truncated]",clearTitle:"Clear the current audit log?",clearBody:"Irreversible. Only this machine's log is cleared; configuration and in-memory mappings stay. Later requests may add new records.",cleared:"Audit log cleared: {bytes}.",toolBlocked:"SPI Protecter blocked tool access to the protected configuration or audit log; edit it locally.",compactAskTitle:"Compact this conversation?",compactAskBody:`Pi builds the summarization request internally and never routes it through this extension's redaction, so letting Pi summarize as-is would send the conversation, including protected values, as plaintext.
|
|
3
3
|
|
|
4
4
|
Allowing here does NOT do that: the conversation Pi is about to summarize is redacted first, and Pi then summarizes the redacted text with the current model. No extra model is needed. The stored summary keeps the replacements, and the model reasons about replacements, so it may describe protected values inaccurately.
|
|
5
5
|
|
|
6
|
-
This request will not be blocked if you allow it.`,compactAllowOnce:"Allow once",compactAllowAlways:"Allow for this session",compactDenyOnce:"Deny once",compactDenyAlways:"Deny for this session",compactRedacted:"SPI Protecter: redacted what Pi is about to summarize; Pi now summarizes with the current model. The stored summary keeps the replacements.",compactIgnoredKeys:"SPI Protecter: the compaction settings {keys} no longer do anything and are ignored. Pi summarizes with the session's own model; remove them from the local config.",guardInstalled:"covered",guardMissing:"NOT covered",statusCompaction:"Compaction: {mode}; Pi summarizes with the current model. Hookless model calls: {guard}.",compactAlwaysNotice:'SPI Protecter: compaction allowed for this session. Set "compaction" in the local config to make it permanent.',compactDenyNotice:"SPI Protecter: compaction refused for this session; use /new to start a new session."}
|
|
6
|
+
This request will not be blocked if you allow it.`,compactAllowOnce:"Allow once",compactAllowAlways:"Allow for this session",compactDenyOnce:"Deny once",compactDenyAlways:"Deny for this session",compactRedacted:"SPI Protecter: redacted what Pi is about to summarize; Pi now summarizes with the current model. The stored summary keeps the replacements.",compactIgnoredKeys:"SPI Protecter: the compaction settings {keys} no longer do anything and are ignored. Pi summarizes with the session's own model; remove them from the local config.",guardInstalled:"covered",guardMissing:"NOT covered",statusCompaction:"Compaction: {mode}; Pi summarizes with the current model. Hookless model calls: {guard}.",compactAlwaysNotice:'SPI Protecter: compaction allowed for this session. Set "compaction" in the local config to make it permanent.',compactDenyNotice:"SPI Protecter: compaction refused for this session; use /new to start a new session."},Ye={compactAskTitle:"是否压缩当前会话?",compactAskBody:`Pi 在内部构造摘要请求,不经过本扩展的脱敏环节,因此原样让 Pi 生成摘要会将会话内容(包括受保护的值)以明文发送。
|
|
7
7
|
|
|
8
8
|
在此处允许**不会**这样做:先对 Pi 即将摘要的内容脱敏,再由 Pi 用当前模型对脱敏后的内容生成摘要,无需额外模型。保存下来的摘要保留替换值;且模型推理的是替换值,对受保护值的描述可能不准确。
|
|
9
9
|
|
|
10
|
-
若选择允许,本次请求不会被拦截。`,compactAllowOnce:"允许一次",compactAllowAlways:"本会话内全部允许",compactDenyOnce:"拒绝一次",compactDenyAlways:"本会话内全部拒绝",compactRedacted:"SPI Protecter:已对 Pi 即将摘要的内容脱敏,现由 Pi 用当前模型生成摘要。保存下来的摘要保留替换值。",compactIgnoredKeys:"SPI Protecter:compaction 配置项 {keys} 已不再生效并被忽略。Pi 使用会话自身的模型生成摘要,请从本地配置中删除它们。",guardInstalled:"已覆盖",guardMissing:"未覆盖",statusCompaction:"压缩:{mode};由 Pi 用当前模型生成摘要。无钩子的模型调用:{guard}。",compactAlwaysNotice:'SPI Protecter:本会话内允许压缩。如需永久生效,请在本地配置中设置 "compaction"。',compactDenyNotice:"SPI Protecter:本会话内拒绝压缩;可使用 /new 开启新会话。",blockedHeader:"SPI Protecter 已阻止该请求",reasonLabel:"原因",actionLabel:"处理",detailsLabel:"详情",statusReady:"就绪",statusNotReady:"未就绪",statusLine:"SPI Protecter:{state};{rules};{mappings}。内存快照,重载后更新。",statusLastBlock:"最近一次拦截 @ {at}:",statusNoBlock:"本会话暂无拦截记录。",statusBarRules:"SPI Protecter · {rules}",statusBarNotReady:"SPI Protecter · 未就绪",emptyRules:"SPI Protecter:尚未配置规则,请编辑本地机器配置后重载。",commandDescription:"查看本地保护记录",usage:"用法:/protecter [logs [1-100|clear]|status|reload]
|
|
11
|
-
`)}var
|
|
12
|
-
`)}finally{
|
|
13
|
-
`;if(Buffer.byteLength(h)>1024*1024)throw i("CONFIG_SIZE",{bytes:Buffer.byteLength(h),limit:1024*1024});
|
|
10
|
+
若选择允许,本次请求不会被拦截。`,compactAllowOnce:"允许一次",compactAllowAlways:"本会话内全部允许",compactDenyOnce:"拒绝一次",compactDenyAlways:"本会话内全部拒绝",compactRedacted:"SPI Protecter:已对 Pi 即将摘要的内容脱敏,现由 Pi 用当前模型生成摘要。保存下来的摘要保留替换值。",compactIgnoredKeys:"SPI Protecter:compaction 配置项 {keys} 已不再生效并被忽略。Pi 使用会话自身的模型生成摘要,请从本地配置中删除它们。",guardInstalled:"已覆盖",guardMissing:"未覆盖",statusCompaction:"压缩:{mode};由 Pi 用当前模型生成摘要。无钩子的模型调用:{guard}。",compactAlwaysNotice:'SPI Protecter:本会话内允许压缩。如需永久生效,请在本地配置中设置 "compaction"。',compactDenyNotice:"SPI Protecter:本会话内拒绝压缩;可使用 /new 开启新会话。",blockedHeader:"SPI Protecter 已阻止该请求",reasonLabel:"原因",actionLabel:"处理",detailsLabel:"详情",statusReady:"就绪",statusNotReady:"未就绪",statusLine:"SPI Protecter:{state};{rules};{mappings}。内存快照,重载后更新。",statusLastBlock:"最近一次拦截 @ {at}:",statusNoBlock:"本会话暂无拦截记录。",statusBarRules:"SPI Protecter · {rules}",statusBarNotReady:"SPI Protecter · 未就绪",emptyRules:"SPI Protecter:尚未配置规则,请编辑本地机器配置后重载。",commandDescription:"查看本地保护记录",usage:"用法:/protecter [logs [1-100|clear]|status|reload|test <文本>|test @<路径>]。仅 test 接受内容,其他参数不要输入敏感内容。",testPreviewTitle:"离线脱敏测试,仅本地显示,编辑不会保存",testRedacted:"SPI Protecter:已在本地脱敏({chars}),未向任何模型发送内容。替换关系已记入本会话映射。",testUnchanged:"SPI Protecter:没有规则命中({chars}),下方文本未改动。",testFileLabel:"输入:本地文件",testTextLabel:"输入:行内文本",logsTuiOnly:"请在本地 TUI 查看保护记录。",logsNone:"暂无可读记录。",logsSelectTitle:"保护记录",logsTruncated:"(仅显示有限尾部)",logsRevealTitle:"敏感明文",logsRevealBody:"确认在本地显示?请勿分享此界面。",logsPreviewTitle:"本地预览,编辑不会保存",logsPreviewTruncated:"[预览已截断]",clearTitle:"确认清空当前审计日志?",clearBody:"不可撤销。仅清空本机日志,配置和内存映射保留;后续请求可能写入新记录。",cleared:"已清空审计日志:{bytes}。",toolBlocked:"SPI Protecter 已阻止工具访问受保护的配置或审计日志,请在本地编辑。"};function X(t=process.env){let e=t.PI_PROTECTER_LANG||t.LC_ALL||t.LC_MESSAGES||t.LANG||t.LANGUAGE||je();return/^zh\b|^zh[-_]/i.test(e.trim())?"zh":"en"}function je(){try{return new Intl.DateTimeFormat().resolvedOptions().locale}catch{return""}}var C=X();function de(){return C}function fe(t){C=t}function p(t,e={}){return((C==="zh"?Ye:le)[t]??le[t]).replace(/\{(\w+)\}/g,(n,o)=>Object.hasOwn(e,o)?String(e[o]):n)}var We={en:{rules:{one:"{n} rule",other:"{n} rules"},mappings:{one:"{n} mapping",other:"{n} mappings"},bytes:{one:"{n} byte",other:"{n} bytes"},tokens:{one:"{n} token",other:"{n} tokens"},chars:{one:"{n} character",other:"{n} characters"}},zh:{rules:{other:"规则 {n} 条"},mappings:{other:"映射 {n} 个"},bytes:{other:"{n} 字节"},tokens:{other:"{n} token"},chars:{other:"{n} 个字符"}}},ue=new Map;function _(t,e){let r=C==="zh"?"zh-CN":"en",n=ue.get(C);if(!n){try{n=new Intl.PluralRules(r)}catch{n=void 0}n&&ue.set(C,n)}let o=n?.select(e)??"other",a=We[C][t],f=a[o]??a.other,m=new Intl.NumberFormat(r).format(e);return f.replace("{n}",m)}function me(t){let r=(C==="zh"?Je[t]:K[t])??K[t]??K.INTERNAL;return{reason:r[0],action:r[1]}}var pe={INTERNAL:"internal",NOT_READY:"initialization",UNSUPPORTED_PI:"initialization",GUARD_UNAVAILABLE:"initialization",MACHINE_ID:"initialization",CONFIG_JSON:"configuration",CONFIG_SCHEMA:"configuration",CONFIG_REGEX:"configuration",CONFIG_TARGET:"configuration",CONFIG_CONFLICT:"configuration",CONFIG_SIZE:"configuration",CONFIG_IO:"configuration",CONFIG_UNSAFE:"configuration",CONFIG_EMPTY_MATCH:"configuration",CONFIG_SENSITIVE_TARGET:"configuration",CONFIG_ALIAS_CONFLICT:"configuration",CONFIG_TIMEOUT:"configuration",CONFIG_COMPACTION:"configuration",MIGRATION_LOCKED:"migration",MIGRATION_CHANGED:"migration",MIGRATION_LIMIT:"migration",MIGRATION_IO:"migration",PAYLOAD_JSON:"request",PAYLOAD_SIZE:"request",SCAN_TIMEOUT:"scan",WORKER_FAILED:"worker",SCAN_INTERNAL:"scan",SCAN_NUMBER_UNSAFE:"scan",SCAN_UNIQUE_FAILED:"scan",SCAN_ZERO_WIDTH:"scan",SCAN_MATCH_LIMIT:"scan",SCAN_MAPPING_LIMIT:"scan",FIXED_MAPPING_CONFLICT:"scan",FIXED_ALIAS_REUSED:"scan",FIXED_SENSITIVE_TARGET:"scan",FIXED_OVERLAP:"scan",FIXED_ALIAS_CROSSING:"scan",SCAN_COMPLEXITY:"scan",SCAN_JSON_REWRITE:"scan",SCAN_ATTACHMENT:"scan",SCAN_KEY_COLLISION:"scan",RESTORE_COMPLEXITY:"restore",RESTORE_KEY_COLLISION:"restore",COMPACT_DENIED:"compaction",COMPACT_FAILED:"compaction",COMPACT_INSTRUCTIONS:"compaction",AUDIT_BATCH_LIMIT:"audit",AUDIT_FULL:"audit",AUDIT_PARTIAL:"audit",AUDIT_LOCKED:"audit",AUDIT_UNSAFE:"audit",AUDIT_IO:"audit",TEST_INPUT:"test",TEST_SIZE:"test"};var ge=["rule","otherRule","node","bytes","limit","timeoutMs","status"],Ke=/^[A-Za-z][A-Za-z0-9]{0,39}$/,Xe=/^(EACCES|EPERM|ENOENT|ENOSPC|EDQUOT|EROFS|ELOOP|EISDIR|ENOTDIR|EMFILE|ENFILE|EIO|EEXIST|EBADF|EBUSY|ENOTEMPTY)$/;function qe(t,e={}){let{reason:r,action:n}=me(t),o={};for(let a of ge){let f=e[a];typeof f=="number"&&Number.isSafeInteger(f)&&f>=0&&(o[a]=f)}return typeof e.errno=="string"&&Xe.test(e.errno)&&(o.errno=e.errno),typeof e.errorName=="string"&&Ke.test(e.errorName)&&(o.errorName=e.errorName),{code:t,stage:pe[t],reason:r,action:n,...o}}function R(t){let e=de()==="zh"?":":": ",r=[...ge,"errno","errorName"].filter(n=>t[n]!==void 0).map(n=>`${n}=${t[n]}`).join(" ");return[p("blockedHeader"),`code=${t.code} stage=${t.stage}${r?` ${r}`:""}`,`${p("reasonLabel")}${e}${t.reason}`,`${p("actionLabel")}${e}${t.action}`,`${p("detailsLabel")}${e}/protecter status`].join(`
|
|
11
|
+
`)}var S=class extends Error{diagnostic;constructor(e,r={}){let n=qe(e,r);super(R(n)),this.name="ProtectionError",this.diagnostic=n}};function i(t,e={}){return new S(t,e)}function O(t,e,r={}){if(t instanceof S)return i(t.diagnostic.code,{...t.diagnostic,...r});let n=t&&typeof t=="object"&&"code"in t?t.code:void 0;return i(e,{...r,errno:typeof n=="string"?n:void 0})}function U(t,e){if(!t||typeof t!="object")return i(e);let r=t,n=typeof r.code=="string"&&Object.hasOwn(pe,r.code)?r.code:e;return i(n,r)}import{constants as P,closeSync as he,fchmodSync as Ze,fstatSync as Ve,mkdirSync as Qe,openSync as Ie,readFileSync as et,writeFileSync as tt}from"node:fs";import{dirname as nt}from"node:path";var ye=["ask","protected","off"],q=["provider","model","contextWindow","reserveTokens"];function Ne(t){return!t||typeof t!="object"?[]:q.filter(e=>Object.hasOwn(t,e))}var Z={version:1,sensitiveWords:[]},Oe="ask";function rt(t){if(typeof t=="string"){if(!ye.includes(t))throw i("CONFIG_COMPACTION");return}if(!t||typeof t!="object"||Array.isArray(t))throw i("CONFIG_COMPACTION");let e=t,r=["mode",...q];if(Object.keys(e).some(n=>!r.includes(n)))throw i("CONFIG_COMPACTION");if(e.mode!==void 0&&!ye.includes(e.mode))throw i("CONFIG_COMPACTION");for(let n of q){let o=e[n];if(o!==void 0&&typeof o!="string"&&typeof o!="number")throw i("CONFIG_COMPACTION")}}function v(t){return t===void 0?{mode:Oe}:typeof t=="string"?{mode:t}:{mode:t.mode??Oe}}function V(t){let e;try{e=JSON.parse(t)}catch{throw i("CONFIG_JSON")}let r=0;try{if(!e||e.version!==1||!Array.isArray(e.sensitiveWords)||Object.keys(e).some(o=>!["version","sensitiveWords","compaction"].includes(o)))throw i("CONFIG_SCHEMA");if(Object.hasOwn(e,"compaction")&&rt(e.compaction),e.sensitiveWords.length>1e3)throw i("CONFIG_SIZE",{limit:1e3});let n=new Map;for(let o of e.sensitiveWords){if(r++,typeof o=="string"){if(!o||o.length>8192)throw i("CONFIG_SCHEMA",{rule:r,limit:8192});let f=JSON.stringify(["literal",o]);if(n.has(f)&&n.get(f)!==void 0)throw i("CONFIG_CONFLICT",{rule:r});n.set(f,void 0);continue}if(!o||typeof o!="object")throw i("CONFIG_SCHEMA",{rule:r});if(Object.hasOwn(o,"replacement")&&(typeof o.replacement!="string"||!o.replacement.trim()||o.replacement.length>8192||o.replacement.includes("__PIP_")))throw i("CONFIG_TARGET",{rule:r,limit:8192});if(o.type==="literal"){if(Object.keys(o).some(f=>!["type","value","replacement"].includes(f))||typeof o.value!="string"||!o.value||o.value.length>8192)throw i("CONFIG_SCHEMA",{rule:r,limit:8192})}else if(o.type==="regex"){if(Object.keys(o).some(f=>!["type","pattern","flags","replacement"].includes(f))||typeof o.pattern!="string"||!o.pattern||o.pattern.length>8192||o.flags!==void 0&&(typeof o.flags!="string"||!/^[gimsu]*$/.test(o.flags)))throw i("CONFIG_REGEX",{rule:r,limit:8192});try{new RegExp(o.pattern,o.flags??"")}catch{throw i("CONFIG_REGEX",{rule:r})}}else throw i("CONFIG_SCHEMA",{rule:r});let a=o.type==="literal"?JSON.stringify(["literal",o.value]):JSON.stringify(["regex",o.pattern,[...new Set((o.flags??"")+"g")].sort().join("")]);if(n.has(a)&&n.get(a)!==o.replacement)throw i("CONFIG_CONFLICT",{rule:r});n.set(a,o.replacement)}return e}catch(n){throw n instanceof S?n:i("CONFIG_SCHEMA",{rule:r})}}function Ae(t,e=!1){let r;try{if(e){Qe(nt(t),{recursive:!0,mode:448});try{let a=Ie(t,P.O_WRONLY|P.O_CREAT|P.O_EXCL,384);try{tt(a,JSON.stringify(Z,null,2)+`
|
|
12
|
+
`)}finally{he(a)}}catch(a){if(a.code!=="EEXIST")throw O(a,"CONFIG_IO")}}r=Ie(t,P.O_RDONLY|P.O_NOFOLLOW|P.O_NONBLOCK);let n=Ve(r);if(n.size>1024*1024)throw i("CONFIG_SIZE",{bytes:n.size,limit:1024*1024});if(!n.isFile()||n.nlink!==1||process.getuid&&n.uid!==process.getuid())throw i("CONFIG_UNSAFE");process.platform!=="win32"&&Ze(r,384);let o=et(r,"utf8");if(Buffer.byteLength(o)>1024*1024)throw i("CONFIG_SIZE",{bytes:Buffer.byteLength(o),limit:1024*1024});return{config:V(o),raw:o}}catch(n){let o=n&&typeof n=="object"&&"code"in n?n.code:void 0;throw O(n,o==="ELOOP"||o==="EISDIR"||o==="ENOTDIR"?"CONFIG_UNSAFE":"CONFIG_IO")}finally{r!==void 0&&he(r)}}var ee=/^protecter(?:\.[a-f0-9]{32})?\.json$/;function lt(t){return new Promise((e,r)=>{let n=new at(ct(new URL("./validate-worker.mjs",import.meta.url)),{workerData:t,execArgv:[],resourceLimits:{maxOldGenerationSizeMb:64}}),o=!1,a=(m,d=i("WORKER_FAILED"))=>{o||(o=!0,clearTimeout(f),n.terminate(),m?e():r(d))},f=setTimeout(()=>a(!1,i("CONFIG_TIMEOUT",{timeoutMs:2e3})),2e3);n.once("message",m=>m===!0?a(!0):a(!1,U(m,"CONFIG_SCHEMA"))),n.once("error",()=>a(!1)),n.once("exit",()=>a(!1))})}function ut(t){let e=new Set,r=[];for(let d of t)for(let c of d.sensitiveWords){let l=typeof c=="string"?JSON.stringify(["literal",c,null]):c.type==="literal"?JSON.stringify(["literal",c.value,c.replacement??null]):JSON.stringify(["regex",c.pattern,[...new Set((c.flags??"")+"g")].sort().join(""),c.replacement??null]);e.has(l)||(e.add(l),r.push(c))}let n=[];for(let d of t)d.compaction!==void 0&&n.push(v(d.compaction));let a=["off","ask","protected"].find(d=>n.some(c=>c.mode===d)),f={version:1,sensitiveWords:r};a!==void 0&&(f.compaction={mode:a});let m=JSON.stringify(f);if(Buffer.byteLength(m)>1024*1024)throw i("CONFIG_SIZE",{bytes:Buffer.byteLength(m),limit:1024*1024});return V(m)}function Te(t){let e;try{e=I.lstatSync(t,{bigint:!0})}catch(r){throw O(r,"CONFIG_IO")}if(!e.isFile()||e.nlink!==1n||process.getuid&&e.uid!==BigInt(process.getuid()))throw i("CONFIG_UNSAFE");return`${e.dev}:${e.ino}:${e.size}:${e.mtimeNs}`}function Q(t,e){let r=D(t,e),n=Te(r),o=Ae(r);if(Te(r)!==n)throw i("MIGRATION_CHANGED");return{name:e,...o,identity:n,digest:it("sha256").update(o.raw).digest("hex")}}function F(t,e){let r=Q(t,e.name);if(r.identity!==e.identity||r.digest!==e.digest)throw i("MIGRATION_CHANGED")}function z(t){return I.readdirSync(t).filter(e=>ee.test(e)).sort()}function Ee(t){if(process.platform==="win32")return;let e=I.openSync(t,I.constants.O_RDONLY);try{I.fsyncSync(e)}finally{I.closeSync(e)}}async function Ce(t,e,r={}){if(!/^[a-f0-9]{32}$/.test(e))throw i("MACHINE_ID");let n=ot(t),o=`protecter.${e}.json`,a=D(n,o);I.mkdirSync(n,{recursive:!0,mode:448});let f=D(n,".protecter-migration.lock"),m=Date.now()+(r.lockTimeoutMs??5e3);for(;;)try{I.mkdirSync(f,{mode:448});break}catch(c){if(c.code!=="EEXIST")throw O(c,"MIGRATION_IO");if(Date.now()>=m)throw i("MIGRATION_LOCKED",{timeoutMs:r.lockTimeoutMs??5e3});await new Promise(l=>setTimeout(l,50))}let d;try{let c=z(n);if(c.length>64)throw i("MIGRATION_LIMIT",{limit:64});let s=[...c].sort((N,x)=>N===o?-1:x===o?1:N.localeCompare(x)).map(N=>Q(n,N)),u=ut(s.length?s.map(N=>N.config):[Z]);if(await lt([u]),s.length===1&&s[0].name===o){if(F(n,s[0]),JSON.stringify(z(n))!==JSON.stringify(c))throw i("MIGRATION_CHANGED");return{path:a,config:s[0].config,raw:s[0].raw,sourceRaws:[s[0].raw],migrated:0}}let h=JSON.stringify(u,null,2)+`
|
|
13
|
+
`;if(Buffer.byteLength(h)>1024*1024)throw i("CONFIG_SIZE",{bytes:Buffer.byteLength(h),limit:1024*1024});d=D(n,`.protecter-migration.${st()}.tmp`);let y=I.openSync(d,I.constants.O_WRONLY|I.constants.O_CREAT|I.constants.O_EXCL,384);try{I.writeFileSync(y,h),I.fsyncSync(y)}finally{I.closeSync(y)}if(r.checkpoint?.("beforeCommit",a),JSON.stringify(z(n))!==JSON.stringify(c))throw i("MIGRATION_CHANGED");for(let N of s)F(n,N);I.renameSync(d,a),d=void 0,Ee(n);let A=Q(n,o);if(A.raw!==h)throw i("MIGRATION_CHANGED");r.checkpoint?.("afterCommit",a);for(let N of s)N.name!==o&&(r.checkpoint?.("beforeDelete",D(n,N.name)),F(n,A),F(n,N),I.unlinkSync(D(n,N.name)));Ee(n);let J=[o];if(JSON.stringify(z(n))!==JSON.stringify(J))throw i("MIGRATION_CHANGED");return F(n,A),{path:a,config:u,raw:h,sourceRaws:[...new Set([...s.map(N=>N.raw),h])],migrated:s.filter(N=>N.name!==o).length}}catch(c){throw c instanceof S?c:O(c,"MIGRATION_IO")}finally{if(d)try{I.unlinkSync(d)}catch{}I.rmdirSync(f)}}import{createHash as dt}from"node:crypto";import{readFileSync as ft}from"node:fs";import{execFileSync as Se}from"node:child_process";function te(t){let e=t.trim().toLowerCase().replace(/-/g,"");if(!/^[a-f0-9]{32}$/.test(e)||/^0+$/.test(e))throw i("MACHINE_ID");return dt("sha256").update(`pi-information-protecter:v1:${e}`).digest("hex").slice(0,32)}function we(){try{if(process.platform==="linux")return te(ft("/etc/machine-id","utf8"));if(process.platform==="darwin"){let t=Se("/usr/sbin/ioreg",["-rd1","-c","IOPlatformExpertDevice"],{encoding:"utf8",timeout:5e3,maxBuffer:1048576,stdio:["ignore","pipe","pipe"]});return te(t.match(/"IOPlatformUUID"\s*=\s*"([a-fA-F0-9-]+)"/)?.[1]??"")}if(process.platform==="win32"){let t=Se("reg.exe",["query","HKLM\\SOFTWARE\\Microsoft\\Cryptography","/v","MachineGuid","/reg:64"],{encoding:"utf8",timeout:5e3,maxBuffer:65536,stdio:["ignore","pipe","pipe"]});return te(t.match(/MachineGuid\s+REG_SZ\s+([a-fA-F0-9-]+)/i)?.[1]??"")}}catch{}throw i("MACHINE_ID")}import*as g from"node:fs";import{randomUUID as mt}from"node:crypto";var _e=32*1024*1024,Re=8*1024*1024;function pt(t){let e=r=>String(r).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())} ${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}`}function ne(t,e,r=e){let n=g.openSync(t,(e?g.constants.O_RDWR|(r?g.constants.O_CREAT:0):g.constants.O_RDONLY)|g.constants.O_NOFOLLOW|g.constants.O_NONBLOCK,384);try{let o=g.fstatSync(n);if(!o.isFile()||o.nlink!==1||process.getuid&&o.uid!==process.getuid())throw i("AUDIT_UNSAFE");return process.platform!=="win32"&&g.fchmodSync(n,384),n}catch(o){throw g.closeSync(n),O(o,"AUDIT_UNSAFE")}}function B(t){let e=t&&typeof t=="object"&&"code"in t?t.code:void 0;return O(t,e==="ELOOP"||e==="EISDIR"||e==="ENOTDIR"?"AUDIT_UNSAFE":"AUDIT_IO")}async function Pe(t){let e=`${t}.lock`,r=Date.now()+2e3;for(;;)try{return g.mkdirSync(e,{mode:448}),e}catch(n){if(n.code!=="EEXIST")throw O(n,"AUDIT_IO");if(Date.now()>=r)throw i("AUDIT_LOCKED",{timeoutMs:2e3});await new Promise(o=>setTimeout(o,25))}}async function De(t){let e=await Pe(t),r;try{try{r=ne(t,!0,!1)}catch(o){if(o.code==="ENOENT")return 0;throw o}let n=g.fstatSync(r).size;return g.ftruncateSync(r,0),g.fsyncSync(r),n}catch(n){throw B(n)}finally{try{r!==void 0&&g.closeSync(r)}finally{g.rmdirSync(e)}}}async function Le(t,e,r){if(!r.length)return;let n=new Date,o=mt(),a=Buffer.from(r.map(([d,c])=>JSON.stringify({version:1,time:pt(n),timezoneOffset:-n.getTimezoneOffset(),requestId:o,provider:e||"unknown",original:c,replacement:d})).join(`
|
|
14
14
|
`)+`
|
|
15
|
-
`);if(a.length>
|
|
16
|
-
`);m=
|
|
17
|
-
`),l=f.pop()!=="",u=[],s=!1;for(let c of f.slice(-e))try{let h=JSON.parse(c);if(h.version!==1||typeof h.time!="string"||typeof h.provider!="string"||typeof h.original!="string"||typeof h.replacement!="string"||typeof h.requestId!="string"||typeof h.timezoneOffset!="number")throw new Error;u.push(h)}catch{s=!0}return{records:u,truncated:r>0||f.length>e||l||s}}catch(n){throw G(n)}finally{o!==void 0&&g.closeSync(o)}}var v=class{constructor(e,o=2e3,n=_e){this.configDir=e;this.timeoutMs=o;this.machineId=n}configDir;timeoutMs;machineId;tokens=new Map;queue=Promise.resolve();workers=new Set;closed=!1;snapshot;lastError;restorePattern;restoreSize=-1;get lastDiagnostic(){return this.lastError?{...this.lastError}:void 0}get lastDiagnosticText(){return this.lastError?w(this.lastError):void 0}async initialize(){try{if(this.closed)throw i("NOT_READY");this.snapshot=void 0;let e;try{e=this.machineId()}catch{throw i("MACHINE_ID")}let o=await Ce(this.configDir,e);if(this.closed)throw i("NOT_READY");this.snapshot=o,this.lastError=void 0}catch(e){let o=O(e,"CONFIG_IO");throw this.lastError=o.diagnostic,o}}get configPath(){return this.snapshot?.path??""}get auditPath(){return this.configPath?this.configPath.replace(/\.json$/,".jsonl"):""}auditRecords(e=20){if(!this.ready)throw this.notReady();return De(this.auditPath,e)}clearAuditRecords(){let e=this.queue.then(()=>{if(!this.ready)throw this.notReady();return Re(this.auditPath)});return this.queue=e.catch(()=>{}),e}get ruleCount(){return this.snapshot?.config.sensitiveWords.length??0}get compaction(){return F(this.snapshot?.config.compaction)}get compactionMode(){return this.compaction.mode}get rawCompaction(){return this.snapshot?.config.compaction}get ready(){return!!this.snapshot&&!this.closed}get mappingCount(){return this.tokens.size}redact(e,o="unknown"){let n=this.queue.then(()=>this.scan(e,o)).catch(r=>{let a=O(r,"INTERNAL");throw this.lastError=a.diagnostic,a});return this.queue=n.catch(()=>{}),n}notReady(){return this.lastError?i(this.lastError.code,this.lastError):i("NOT_READY")}async scan(e,o){if(!this.ready)throw this.notReady();let{config:n,sourceRaws:r}=this.snapshot,a;try{a=JSON.stringify(e)}catch{throw i("PAYLOAD_JSON")}if(!a)throw i("PAYLOAD_JSON");if(Buffer.byteLength(a)>8*1024*1024)throw i("PAYLOAD_SIZE",{bytes:Buffer.byteLength(a),limit:8*1024*1024});let d;try{d=JSON.parse(a)}catch{throw i("PAYLOAD_JSON")}let m=await new Promise((f,l)=>{let u=!1,s;try{s=new mt(pt(new URL("./scan-worker.mjs",import.meta.url)),{workerData:{payload:d,rules:n.sensitiveWords,entries:[...this.tokens],configRaws:r},execArgv:[],resourceLimits:{maxOldGenerationSizeMb:128}})}catch(y){l(O(y,"WORKER_FAILED"));return}this.workers.add(s);let c=(y,A=i("WORKER_FAILED"))=>{if(!u){if(u=!0,clearTimeout(h),this.workers.delete(s),s.terminate(),!y||this.closed){l(this.closed?i("NOT_READY"):A);return}f(y)}},h=setTimeout(()=>c(void 0,i("SCAN_TIMEOUT",{timeoutMs:this.timeoutMs})),this.timeoutMs);s.once("message",y=>{y?.failed?c(void 0,M(y.diagnostic,"SCAN_INTERNAL")):y&&Array.isArray(y.additions)&&Array.isArray(y.hits)?c(y):c()}),s.once("error",()=>c()),s.once("exit",()=>c())});if(this.closed)throw i("NOT_READY");if(await Pe(this.auditPath,o,m.hits),this.closed)throw i("NOT_READY");for(let[f,l]of m.additions)this.tokens.set(f,l);return m.payload}restoreText(e){if(!this.tokens.size)return e;if(this.restoreSize!==this.tokens.size){let o=n=>n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.restorePattern=new RegExp([...this.tokens.keys()].sort((n,r)=>r.length-n.length).map(o).join("|"),"g"),this.restoreSize=this.tokens.size}return e.replace(this.restorePattern,o=>this.tokens.get(o)??o)}restore(e,o=0){if(o>80)throw i("RESTORE_COMPLEXITY",{node:o});if(typeof e=="string")return this.restoreText(e);if(typeof e=="number"){let n=this.tokens.get(String(e));if(n===void 0)return e;let r=Number(n);return!Number.isFinite(r)||String(r)!==n?e:r}if(Array.isArray(e))return e.map(n=>this.restore(n,o+1));if(e&&typeof e=="object"){let n=Object.create(null);for(let[r,a]of Object.entries(e)){let d=this.restoreText(r);if(Object.hasOwn(n,d))throw i("RESTORE_KEY_COLLISION");n[d]=this.restore(a,o+1)}return n}return e}close(){this.closed=!0,this.snapshot=void 0,this.tokens.clear();for(let e of this.workers)e.terminate();this.workers.clear()}};import{realpathSync as gt,statSync as Le,readdirSync as ht}from"node:fs";import{homedir as It}from"node:os";import{basename as V,dirname as L,isAbsolute as yt,relative as Me,resolve as x}from"node:path";import{fileURLToPath as Ot}from"node:url";function Nt(t,e){let o=t.replace(/^@/,"");return o.startsWith("file://")&&(o=Ot(o)),(o==="~"||o.startsWith("~/"))&&(o=It()+o.slice(1)),x(e,o)}function Q(t){try{return gt(t)}catch{let e=L(t);return e===t?t:x(Q(e),Me(e,t))}}function At(t,e){let o=Me(t,e);return o===""||!o.startsWith("..")&&!yt(o)}function ke(t,e){try{let o=Le(t),n=Le(e);return o.dev===n.dev&&o.ino===n.ino}catch{return!1}}function Fe(t,e,o,n){if(!n)return!0;let r=Q(x(n));if(["bash","powershell"].includes(t)){let m=typeof e.command=="string"?e.command:"";if(/protecter(?:\.[a-f0-9]{32})?\.jsonl?|\.protecter-migration/i.test(m)||m.includes(n))return!0}let a=e.path??e.file_path??e.filePath,d=["grep","find","ls"].includes(t);if(typeof a!="string"&&!d)return!1;try{let m=Nt(typeof a=="string"?a:".",o),f=Q(m),l=/^protecter\.[a-f0-9]{32}\.jsonl(?:\.lock)?$/,u=ht(L(r)).filter(s=>l.test(s)).some(s=>ke(m,x(L(r),s)));return L(f)===L(r)&&(X.test(V(f))||l.test(V(f))||V(f).startsWith(".protecter-migration"))||f===r||ke(m,n)||u||d&&At(f,r)}catch{return!0}}function ee(t,e){t.length=0;for(let o of e)t.push(o)}function te(t){if(!Array.isArray(t))throw i("COMPACT_FAILED");return t}function be(t){if(typeof t!="string")throw i("COMPACT_FAILED");return t}async function Ge(t,e,o){let{preparation:n}=t,r=await e.redact({messages:n.messagesToSummarize,prefix:n.turnPrefixMessages,previous:n.previousSummary??null,instructions:t.customInstructions??null},o);if(!r||typeof r!="object")throw i("COMPACT_FAILED");if(typeof t.customInstructions=="string"&&r.instructions!==t.customInstructions)throw i("COMPACT_INSTRUCTIONS");let a=te(r.messages),d=te(r.prefix),m=n.previousSummary===void 0?void 0:be(r.previous);ee(n.messagesToSummarize,a),ee(n.turnPrefixMessages,d),m!==void 0&&(n.previousSummary=m)}async function ve(t,e,o){let{preparation:n}=t,r=await e.redact({entries:n.entriesToSummarize,instructions:n.customInstructions??null},o);if(!r||typeof r!="object")throw i("COMPACT_FAILED");let a=te(r.entries),d=n.customInstructions===void 0?void 0:be(r.instructions);return ee(n.entriesToSummarize,a),d===void 0?{}:{customInstructions:d}}var xe=["stream","streamSimple"],Ct=["classify","generateImages"],Ue=xe,ne=Symbol.for("pi-information-protecter.runtime-guard");function Et(t){let e=t?.runtime;if(!e||typeof e!="object")throw i("GUARD_UNAVAILABLE");let o=e;for(let n of Ue)if(typeof o[n]!="function")throw i("GUARD_UNAVAILABLE");return o}function _t(t){return!t||typeof t!="object"?!1:t.onPayload!==void 0}function ze(t,e){let o=Et(t);o[ne]?.();let n=[...Ue,...Ct.filter(a=>typeof o[a]=="function")].map(a=>[a,o[a]]);for(let[a,d]of n){let m=xe.includes(a),f=function(l,u,s){return m&&_t(s)?d.call(this,l,u,s):(async()=>d.call(this,l,await e(l,u),s))()};o[a]=f}let r=()=>{for(let[a,d]of n)o[a]=d;delete o[ne]};return Object.defineProperty(o,ne,{value:r,configurable:!0,enumerable:!1,writable:!0}),r}function Tt(t){ue(J());let e=new v(wt()),o=se(St),n=!1,r,a,d,m=u=>{let s=u?.provider;return typeof s=="string"?s:"unknown"},f=u=>{let s=w(u);return r={at:new Date().toISOString(),text:s},s};t.on("session_start",async(u,s)=>{try{if(!o)throw i("UNSUPPORTED_PI");await e.initialize(),d=ze(s.modelRegistry,(y,A)=>e.redact(A,m(y))),n=!0;let c=e.ruleCount;s.ui.setStatus("protecter",p("statusBarRules",{rules:P("rules",c)})),c===0&&s.ui.notify(p("emptyRules"),"warning");let h=ye(e.rawCompaction);h.length&&s.ui.notify(p("compactIgnoredKeys",{keys:h.join(", ")}),"warning")}catch(c){n=!1,s.ui.setStatus("protecter",p("statusBarNotReady")),s.ui.notify(f(O(c,"CONFIG_IO").diagnostic),"error")}}),t.on("before_provider_request",async(u,s)=>{try{if(!o)throw i("UNSUPPORTED_PI");let c=await e.redact(u.payload,s.model?.provider??"unknown");return n=!0,c}catch(c){n=!1;let h=f(O(c,"INTERNAL").diagnostic);try{s.abort()}catch{}try{s.ui.notify(h,"error")}catch{}return{}}}),t.on("message_end",u=>{if(u.message.role!=="assistant")return;let s=u.message;return{message:{...s,content:s.content.map(c=>c.type==="text"?{...c,text:e.restoreText(c.text)}:c.type==="thinking"?{...c,thinking:e.restoreText(c.thinking)}:c.type==="toolCall"?{...c,arguments:e.restore(c.arguments)}:c),...s.errorMessage?{errorMessage:e.restoreText(s.errorMessage)}:{}}}}),t.registerMarkdownTransformer((u,s)=>s.messageType==="user"?u:e.restoreText(u)),t.on("tool_call",(u,s)=>{if(!n)return{block:!0,reason:e.lastDiagnosticText??r?.text??w(i("NOT_READY").diagnostic)};let c=e.restore(u.input);for(let h of Object.keys(u.input))delete u.input[h];if(Object.assign(u.input,c),Fe(u.toolName,u.input,s.cwd,e.configPath))return{block:!0,reason:p("toolBlocked")}});let l=async(u,s)=>{if(!o)throw i("UNSUPPORTED_PI");if(!e.ready)throw e.lastDiagnostic?i(e.lastDiagnostic.code,e.lastDiagnostic):i("NOT_READY");let c=e.compactionMode;if(c==="off")throw i("COMPACT_DENIED");if(a==="deny")throw i("COMPACT_DENIED");if(c!=="ask"||a==="allow")return;let h=[p("compactAllowOnce"),p("compactAllowAlways"),p("compactDenyOnce"),p("compactDenyAlways")],y=await u.ui.select(`${p("compactAskTitle")}
|
|
15
|
+
`);if(a.length>Re)throw i("AUDIT_BATCH_LIMIT",{bytes:a.length,limit:Re});let f=await Pe(t),m;try{m=ne(t,!0);let d=g.fstatSync(m).size;if(d+a.length>_e)throw i("AUDIT_FULL",{bytes:d+a.length,limit:_e});if(d){let c=Buffer.alloc(1);if(g.readSync(m,c,0,1,d-1),c[0]!==10)throw i("AUDIT_PARTIAL")}try{let c=0;for(;c<a.length;){let l=g.writeSync(m,a,c,a.length-c,d+c);if(!l)throw i("AUDIT_IO");c+=l}g.fsyncSync(m)}catch(c){throw g.ftruncateSync(m,d),g.fsyncSync(m),B(c)}}catch(d){throw B(d)}finally{m!==void 0&&g.closeSync(m),g.rmdirSync(f)}}function ke(t,e=20){if(!Number.isInteger(e)||e<1||e>100)throw i("INTERNAL",{limit:100});let r;try{try{r=ne(t,!1)}catch(u){if(u.code==="ENOENT")return{records:[],truncated:!1};throw u}let n=g.fstatSync(r).size,o=Math.max(0,n-1024*1024),a=Buffer.alloc(n-o),f=g.readSync(r,a,0,a.length,o),m=a.subarray(0,f).toString("utf8");if(o){let u=m.indexOf(`
|
|
16
|
+
`);m=u<0?"":m.slice(u+1)}let d=m.split(`
|
|
17
|
+
`),c=d.pop()!=="",l=[],s=!1;for(let u of d.slice(-e))try{let h=JSON.parse(u);if(h.version!==1||typeof h.time!="string"||typeof h.provider!="string"||typeof h.original!="string"||typeof h.replacement!="string"||typeof h.requestId!="string"||typeof h.timezoneOffset!="number")throw new Error;l.push(h)}catch{s=!0}return{records:l,truncated:o>0||d.length>e||c||s}}catch(n){throw B(n)}finally{r!==void 0&&g.closeSync(r)}}var H=class{constructor(e,r=2e3,n=we){this.configDir=e;this.timeoutMs=r;this.machineId=n}configDir;timeoutMs;machineId;tokens=new Map;queue=Promise.resolve();workers=new Set;closed=!1;snapshot;lastError;restorePattern;restoreSize=-1;get lastDiagnostic(){return this.lastError?{...this.lastError}:void 0}get lastDiagnosticText(){return this.lastError?R(this.lastError):void 0}async initialize(){try{if(this.closed)throw i("NOT_READY");this.snapshot=void 0;let e;try{e=this.machineId()}catch{throw i("MACHINE_ID")}let r=await Ce(this.configDir,e);if(this.closed)throw i("NOT_READY");this.snapshot=r,this.lastError=void 0}catch(e){let r=O(e,"CONFIG_IO");throw this.lastError=r.diagnostic,r}}get configPath(){return this.snapshot?.path??""}get auditPath(){return this.configPath?this.configPath.replace(/\.json$/,".jsonl"):""}auditRecords(e=20){if(!this.ready)throw this.notReady();return ke(this.auditPath,e)}clearAuditRecords(){let e=this.queue.then(()=>{if(!this.ready)throw this.notReady();return De(this.auditPath)});return this.queue=e.catch(()=>{}),e}get ruleCount(){return this.snapshot?.config.sensitiveWords.length??0}get compaction(){return v(this.snapshot?.config.compaction)}get compactionMode(){return this.compaction.mode}get rawCompaction(){return this.snapshot?.config.compaction}get ready(){return!!this.snapshot&&!this.closed}get mappingCount(){return this.tokens.size}redact(e,r="unknown"){let n=this.queue.then(()=>this.scan(e,r)).catch(o=>{let a=O(o,"INTERNAL");throw this.lastError=a.diagnostic,a});return this.queue=n.catch(()=>{}),n}notReady(){return this.lastError?i(this.lastError.code,this.lastError):i("NOT_READY")}async scan(e,r){if(!this.ready)throw this.notReady();let{config:n,sourceRaws:o}=this.snapshot,a;try{a=JSON.stringify(e)}catch{throw i("PAYLOAD_JSON")}if(!a)throw i("PAYLOAD_JSON");if(Buffer.byteLength(a)>8*1024*1024)throw i("PAYLOAD_SIZE",{bytes:Buffer.byteLength(a),limit:8*1024*1024});let f;try{f=JSON.parse(a)}catch{throw i("PAYLOAD_JSON")}let m=await new Promise((d,c)=>{let l=!1,s;try{s=new gt(ht(new URL("./scan-worker.mjs",import.meta.url)),{workerData:{payload:f,rules:n.sensitiveWords,entries:[...this.tokens],configRaws:o},execArgv:[],resourceLimits:{maxOldGenerationSizeMb:128}})}catch(y){c(O(y,"WORKER_FAILED"));return}this.workers.add(s);let u=(y,A=i("WORKER_FAILED"))=>{if(!l){if(l=!0,clearTimeout(h),this.workers.delete(s),s.terminate(),!y||this.closed){c(this.closed?i("NOT_READY"):A);return}d(y)}},h=setTimeout(()=>u(void 0,i("SCAN_TIMEOUT",{timeoutMs:this.timeoutMs})),this.timeoutMs);s.once("message",y=>{y?.failed?u(void 0,U(y.diagnostic,"SCAN_INTERNAL")):y&&Array.isArray(y.additions)&&Array.isArray(y.hits)?u(y):u()}),s.once("error",()=>u()),s.once("exit",()=>u())});if(this.closed)throw i("NOT_READY");if(await Le(this.auditPath,r,m.hits),this.closed)throw i("NOT_READY");for(let[d,c]of m.additions)this.tokens.set(d,c);return m.payload}restoreText(e){if(!this.tokens.size)return e;if(this.restoreSize!==this.tokens.size){let r=n=>n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.restorePattern=new RegExp([...this.tokens.keys()].sort((n,o)=>o.length-n.length).map(r).join("|"),"g"),this.restoreSize=this.tokens.size}return e.replace(this.restorePattern,r=>this.tokens.get(r)??r)}restore(e,r=0){if(r>80)throw i("RESTORE_COMPLEXITY",{node:r});if(typeof e=="string")return this.restoreText(e);if(typeof e=="number"){let n=this.tokens.get(String(e));if(n===void 0)return e;let o=Number(n);return!Number.isFinite(o)||String(o)!==n?e:o}if(Array.isArray(e))return e.map(n=>this.restore(n,r+1));if(e&&typeof e=="object"){let n=Object.create(null);for(let[o,a]of Object.entries(e)){let f=this.restoreText(o);if(Object.hasOwn(n,f))throw i("RESTORE_KEY_COLLISION");n[f]=this.restore(a,r+1)}return n}return e}close(){this.closed=!0,this.snapshot=void 0,this.tokens.clear();for(let e of this.workers)e.terminate();this.workers.clear()}};import{realpathSync as It,statSync as Me,readdirSync as yt}from"node:fs";import{homedir as Ot}from"node:os";import{basename as re,dirname as b,isAbsolute as Nt,relative as be,resolve as $}from"node:path";import{fileURLToPath as At}from"node:url";function Tt(t,e){let r=t.replace(/^@/,"");return r.startsWith("file://")&&(r=At(r)),(r==="~"||r.startsWith("~/"))&&(r=Ot()+r.slice(1)),$(e,r)}function oe(t){try{return It(t)}catch{let e=b(t);return e===t?t:$(oe(e),be(e,t))}}function Et(t,e){let r=be(t,e);return r===""||!r.startsWith("..")&&!Nt(r)}function Fe(t,e){try{let r=Me(t),n=Me(e);return r.dev===n.dev&&r.ino===n.ino}catch{return!1}}function xe(t,e,r,n){if(!n)return!0;let o=oe($(n));if(["bash","powershell"].includes(t)){let m=typeof e.command=="string"?e.command:"";if(/protecter(?:\.[a-f0-9]{32})?\.jsonl?|\.protecter-migration/i.test(m)||m.includes(n))return!0}let a=e.path??e.file_path??e.filePath,f=["grep","find","ls"].includes(t);if(typeof a!="string"&&!f)return!1;try{let m=Tt(typeof a=="string"?a:".",r),d=oe(m),c=/^protecter\.[a-f0-9]{32}\.jsonl(?:\.lock)?$/,l=yt(b(o)).filter(s=>c.test(s)).some(s=>Fe(m,$(b(o),s)));return b(d)===b(o)&&(ee.test(re(d))||c.test(re(d))||re(d).startsWith(".protecter-migration"))||d===o||Fe(m,n)||l||f&&Et(d,o)}catch{return!0}}function ie(t,e){t.length=0;for(let r of e)t.push(r)}function se(t){if(!Array.isArray(t))throw i("COMPACT_FAILED");return t}function Ge(t){if(typeof t!="string")throw i("COMPACT_FAILED");return t}async function Ue(t,e,r){let{preparation:n}=t,o=await e.redact({messages:n.messagesToSummarize,prefix:n.turnPrefixMessages,previous:n.previousSummary??null,instructions:t.customInstructions??null},r);if(!o||typeof o!="object")throw i("COMPACT_FAILED");if(typeof t.customInstructions=="string"&&o.instructions!==t.customInstructions)throw i("COMPACT_INSTRUCTIONS");let a=se(o.messages),f=se(o.prefix),m=n.previousSummary===void 0?void 0:Ge(o.previous);ie(n.messagesToSummarize,a),ie(n.turnPrefixMessages,f),m!==void 0&&(n.previousSummary=m)}async function ve(t,e,r){let{preparation:n}=t,o=await e.redact({entries:n.entriesToSummarize,instructions:n.customInstructions??null},r);if(!o||typeof o!="object")throw i("COMPACT_FAILED");let a=se(o.entries),f=n.customInstructions===void 0?void 0:Ge(o.instructions);return ie(n.entriesToSummarize,a),f===void 0?{}:{customInstructions:f}}var ze=["stream","streamSimple"],Ct=["classify","generateImages"],Be=ze,ae=Symbol.for("pi-information-protecter.runtime-guard");function St(t){let e=t?.runtime;if(!e||typeof e!="object")throw i("GUARD_UNAVAILABLE");let r=e;for(let n of Be)if(typeof r[n]!="function")throw i("GUARD_UNAVAILABLE");return r}function wt(t){return!t||typeof t!="object"?!1:t.onPayload!==void 0}function He(t,e){let r=St(t);r[ae]?.();let n=[...Be,...Ct.filter(a=>typeof r[a]=="function")].map(a=>[a,r[a]]);for(let[a,f]of n){let m=ze.includes(a),d=function(c,l,s){return m&&wt(s)?f.call(this,c,l,s):(async()=>f.call(this,c,await e(c,l),s))()};r[a]=d}let o=()=>{for(let[a,f]of n)r[a]=f;delete r[ae]};return Object.defineProperty(r,ae,{value:o,configurable:!0,enumerable:!1,writable:!0}),o}import{lstat as Pt,readFile as Dt}from"node:fs/promises";import{resolve as Lt}from"node:path";var $e=256*1024;async function kt(t){let e=a=>/^(['"]).*\1$/s.test(a)?a.slice(1,-1):a,r=e(t);if(!r.startsWith("@"))return{text:r,fromFile:!1};let n=Lt(e(r.slice(1).trim())),o;try{o=await Pt(n)}catch(a){throw O(a,"TEST_INPUT")}if(!o.isFile())throw i("TEST_INPUT");if(o.size>$e)throw i("TEST_SIZE",{bytes:o.size,limit:$e});try{return{text:await Dt(n,"utf8"),fromFile:!0}}catch(a){throw O(a,"TEST_INPUT")}}function Mt(t){fe(X());let e=new H(_t()),r=ce(Rt),n=!1,o,a,f,m=l=>{let s=l?.provider;return typeof s=="string"?s:"unknown"},d=l=>{let s=R(l);return o={at:new Date().toISOString(),text:s},s};t.on("session_start",async(l,s)=>{try{if(!r)throw i("UNSUPPORTED_PI");await e.initialize(),f=He(s.modelRegistry,(y,A)=>e.redact(A,m(y))),n=!0;let u=e.ruleCount;s.ui.setStatus("protecter",p("statusBarRules",{rules:_("rules",u)})),u===0&&s.ui.notify(p("emptyRules"),"warning");let h=Ne(e.rawCompaction);h.length&&s.ui.notify(p("compactIgnoredKeys",{keys:h.join(", ")}),"warning")}catch(u){n=!1,s.ui.setStatus("protecter",p("statusBarNotReady")),s.ui.notify(d(O(u,"CONFIG_IO").diagnostic),"error")}}),t.on("before_provider_request",async(l,s)=>{try{if(!r)throw i("UNSUPPORTED_PI");let u=await e.redact(l.payload,s.model?.provider??"unknown");return n=!0,u}catch(u){n=!1;let h=d(O(u,"INTERNAL").diagnostic);try{s.abort()}catch{}try{s.ui.notify(h,"error")}catch{}return{}}}),t.on("message_end",l=>{if(l.message.role!=="assistant")return;let s=l.message;return{message:{...s,content:s.content.map(u=>u.type==="text"?{...u,text:e.restoreText(u.text)}:u.type==="thinking"?{...u,thinking:e.restoreText(u.thinking)}:u.type==="toolCall"?{...u,arguments:e.restore(u.arguments)}:u),...s.errorMessage?{errorMessage:e.restoreText(s.errorMessage)}:{}}}}),t.registerMarkdownTransformer((l,s)=>s.messageType==="user"?l:e.restoreText(l)),t.on("tool_call",(l,s)=>{if(!n)return{block:!0,reason:e.lastDiagnosticText??o?.text??R(i("NOT_READY").diagnostic)};let u=e.restore(l.input);for(let h of Object.keys(l.input))delete l.input[h];if(Object.assign(l.input,u),xe(l.toolName,l.input,s.cwd,e.configPath))return{block:!0,reason:p("toolBlocked")}});let c=async(l,s)=>{if(!r)throw i("UNSUPPORTED_PI");if(!e.ready)throw e.lastDiagnostic?i(e.lastDiagnostic.code,e.lastDiagnostic):i("NOT_READY");let u=e.compactionMode;if(u==="off")throw i("COMPACT_DENIED");if(a==="deny")throw i("COMPACT_DENIED");if(u!=="ask"||a==="allow")return;let h=[p("compactAllowOnce"),p("compactAllowAlways"),p("compactDenyOnce"),p("compactDenyAlways")],y=await l.ui.select(`${p("compactAskTitle")}
|
|
18
18
|
|
|
19
|
-
${p("compactAskBody")}`,h,{signal:s}),A=y===void 0?-1:h.indexOf(y);if(A===1?(a="allow",
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
${
|
|
23
|
-
|
|
24
|
-
${p("
|
|
19
|
+
${p("compactAskBody")}`,h,{signal:s}),A=y===void 0?-1:h.indexOf(y);if(A===1?(a="allow",l.ui.notify(p("compactAlwaysNotice"),"info")):A===3&&(a="deny",l.ui.notify(p("compactDenyNotice"),"warning")),A!==0&&A!==1)throw i("COMPACT_DENIED")};t.on("session_before_compact",async(l,s)=>{try{await c(s,l.signal),await Ue(l,e,s.model?.provider??"unknown"),s.ui.notify(p("compactRedacted"),"info");return}catch(u){return s.ui.notify(d(O(u,"COMPACT_FAILED").diagnostic),"warning"),{cancel:!0}}}),t.on("session_before_tree",async(l,s)=>{if(l.preparation.userWantsSummary)try{await c(s,l.signal);let u=await ve(l,e,s.model?.provider??"unknown");return s.ui.notify(p("compactRedacted"),"info"),u}catch(u){return s.ui.notify(d(O(u,"COMPACT_FAILED").diagnostic),"warning"),{cancel:!0}}}),t.registerCommand("protecter",{description:p("commandDescription"),handler:async(l,s)=>{let u=l.trim(),h=u.split(/\s+/).filter(Boolean),y=h[0]??"logs";if(y==="test"){let T=u.slice(y.length).trim();if(!T){s.ui.notify(p("usage"),"info");return}try{if(!e.ready)throw i("NOT_READY");let{text:w,fromFile:L}=await kt(T),E=(await e.redact({text:w},"test")).text;if(typeof E!="string")throw i("INTERNAL");let k=[p(L?"testFileLabel":"testTextLabel"),p(E===w?"testUnchanged":"testRedacted",{chars:_("chars",E.length)})].join(`
|
|
20
|
+
`);s.mode==="tui"?await s.ui.editor(p("testPreviewTitle"),`${k}
|
|
21
|
+
|
|
22
|
+
${E}`):s.ui.notify(`${k}
|
|
23
|
+
|
|
24
|
+
${E}`,"info")}catch(w){s.ui.notify(d(O(w,"TEST_INPUT").diagnostic),"error")}return}if(!["status","reload","logs"].includes(y)||y!=="logs"&&h.length>1||h.length>2||h[1]!==void 0&&h[1]!=="clear"&&!/^(?:[1-9]\d?|100)$/.test(h[1])){s.ui.notify(p("usage"),"info");return}if(y==="logs"){if(s.mode!=="tui"){s.ui.notify(p("logsTuiOnly"),"warning");return}if(h[1]==="clear"){try{if(!e.ready)throw i("NOT_READY");if(!await s.ui.confirm(p("clearTitle"),p("clearBody")))return;await s.waitForIdle();let T=await e.clearAuditRecords();n=e.ready,s.ui.notify(p("cleared",{bytes:_("bytes",T)}),"info")}catch(T){s.ui.notify(d(O(T,"AUDIT_IO").diagnostic),"error")}return}try{let{records:T,truncated:w}=e.auditRecords(Number(h[1]??20));if(!T.length){s.ui.notify(p("logsNone"),"info");return}let L=G=>JSON.stringify(G).replace(/[\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g,W=>`\\u${W.charCodeAt(0).toString(16).padStart(4,"0")}`),Y=T.map((G,W)=>`${W+1}. ${L(G.time)} | ${L(G.provider).slice(0,120)}`),E=await s.ui.select(p("logsSelectTitle")+(w?p("logsTruncated"):""),Y),k=E===void 0?-1:Y.indexOf(E);if(k<0||!await s.ui.confirm(p("logsRevealTitle"),p("logsRevealBody")))return;let j=L(T[k]);await s.ui.editor(p("logsPreviewTitle"),j.length>2e4?`${j.slice(0,2e4)}
|
|
25
|
+
${p("logsPreviewTruncated")}`:j)}catch(T){s.ui.notify(d(O(T,"AUDIT_IO").diagnostic),"error")}return}if(y==="reload"){await s.waitForIdle(),await s.reload();return}let A=e.lastDiagnosticText??o?.text,J=p("statusLine",{state:p(e.ready?"statusReady":"statusNotReady"),rules:_("rules",e.ruleCount),mappings:_("mappings",e.mappingCount)}),N=`
|
|
26
|
+
${p("statusCompaction",{mode:e.compactionMode,guard:p(f?"guardInstalled":"guardMissing")})}`,x=A?`
|
|
27
|
+
${p("statusLastBlock",{at:o?.at??""})}
|
|
28
|
+
${A}`:`
|
|
29
|
+
${p("statusNoBlock")}`;s.ui.notify(J+N+x,e.ready?"info":"error")}}),t.on("session_shutdown",()=>{f?.(),f=void 0,e.close()})}export{Mt as default};
|