pi-information-protecter 0.13.0 → 0.14.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 +9 -0
- package/README.md +18 -2
- package/dist/index.mjs +19 -17
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
# Changelog / 更新日志
|
|
2
2
|
|
|
3
|
+
## 0.14.0 — Ask before passing attachments / 附件放行前先询问
|
|
4
|
+
|
|
5
|
+
### Changed / 变更
|
|
6
|
+
|
|
7
|
+
- Ask before sending opaque image, audio, video or file content (default `attachments: "ask"`). An explicit per-request choice can allow the unchanged attachment or cancel it; `"allow"` and `"deny"` configure a permanent policy. Attachment-free requests continue through normal redaction.
|
|
8
|
+
发送不透明的图片、音频、视频或文件内容前先询问(默认 `attachments: "ask"`)。用户可明确选择原样发送附件或取消请求;也可用 `"allow"` 和 `"deny"` 配置固定策略。没有附件的请求仍按原有流程脱敏。
|
|
9
|
+
- Merge attachment settings conservatively across configuration files: deny takes precedence over ask, which takes precedence over allow.
|
|
10
|
+
多份配置合并附件策略时从严处理:拒绝优先于询问,询问优先于允许。
|
|
11
|
+
|
|
3
12
|
## 0.13.0 — Capabilities, not a version allowlist / 以能力为准,而非版本白名单
|
|
4
13
|
|
|
5
14
|
### Changed / 变更
|
package/README.md
CHANGED
|
@@ -41,7 +41,7 @@ If redaction itself fails for any reason, the request is **blocked**, never sent
|
|
|
41
41
|
|
|
42
42
|
**Treat `/bug`, `/share` and `/export` as publishing plaintext.** To report a bug from a session that touched real secrets, use the local zip/export option, open it, and check the contents before sending it anywhere.
|
|
43
43
|
|
|
44
|
-
Two more limits worth knowing: only text matching your rules is protected — not paraphrases, split characters or values the model infers — and
|
|
44
|
+
Two more limits worth knowing: only text matching your rules is protected — not paraphrases, split characters or values the model infers — and attachments cannot be inspected or redacted. By default, the extension asks before sending them; allowing passes them through unchanged.
|
|
45
45
|
|
|
46
46
|
## Installation
|
|
47
47
|
|
|
@@ -149,6 +149,14 @@ Never type a secret as a command argument — `test` is the one exception, becau
|
|
|
149
149
|
/protecter test @./demo.txt
|
|
150
150
|
```
|
|
151
151
|
|
|
152
|
+
### Attachments
|
|
153
|
+
|
|
154
|
+
The default `attachments: "ask"` prompts when a request contains opaque image, audio, video or file content. Allowing sends the request unchanged, without attachment inspection or redaction; declining cancels it. Choose `"allow"` to always pass attachments through, or `"deny"` to always cancel them. Text in requests without attachments continues through normal redaction.
|
|
155
|
+
|
|
156
|
+
```json
|
|
157
|
+
{ "version": 1, "attachments": "ask", "sensitiveWords": [] }
|
|
158
|
+
```
|
|
159
|
+
|
|
152
160
|
### Context compaction
|
|
153
161
|
|
|
154
162
|
When the context fills up, Pi summarizes the conversation. That request is built inside Pi and does **not** pass through the normal hook, so this extension redacts the conversation Pi is about to summarize and lets Pi summarize it with your current model. No second model is needed, and the saved summary keeps the fake values, so no plaintext summary is written into the session file.
|
|
@@ -317,7 +325,7 @@ Pi 没有为后三者提供任何钩子,因此本扩展包装会话共享的
|
|
|
317
325
|
|
|
318
326
|
**请把 `/bug`、`/share`、`/export` 视为公开明文。** 若需要为接触过真实秘密的会话提交错误报告,请使用本地 zip/导出选项,打开它,确认内容之后再决定发给谁。
|
|
319
327
|
|
|
320
|
-
|
|
328
|
+
另外两点同样要紧:只有命中你的规则的文本会被保护——改写、片段值以及模型推断出的内容都不会;附件无法被检查或脱敏,默认在发送前询问,允许后会原样放行。
|
|
321
329
|
|
|
322
330
|
## 安装
|
|
323
331
|
|
|
@@ -427,6 +435,14 @@ pi update npm:pi-information-protecter
|
|
|
427
435
|
|
|
428
436
|
不要把秘密作为命令参数输入。
|
|
429
437
|
|
|
438
|
+
### 附件
|
|
439
|
+
|
|
440
|
+
默认 `attachments: "ask"`:请求包含不透明的图片、音频、视频或文件内容时会询问。允许后请求将未经附件检查或脱敏而原样发送;拒绝则取消请求。设为 `"allow"` 可始终放行附件,设为 `"deny"` 则始终取消。没有附件的请求仍正常脱敏。
|
|
441
|
+
|
|
442
|
+
```json
|
|
443
|
+
{ "version": 1, "attachments": "ask", "sensitiveWords": [] }
|
|
444
|
+
```
|
|
445
|
+
|
|
430
446
|
### 上下文压缩
|
|
431
447
|
|
|
432
448
|
上下文写满时,Pi 会对对话生成摘要。该请求由 Pi 内部构造,**不经过**常规钩子,因此本扩展会先对 Pi 即将摘要的对话脱敏,再由 Pi 用你当前的模型生成摘要。不需要第二个模型;保存下来的摘要保留假值,因此会话文件中不会写入明文摘要。
|
package/dist/index.mjs
CHANGED
|
@@ -1,29 +1,31 @@
|
|
|
1
1
|
/*! SPI Protecter | MIT | see LICENSE / SPI 隐私保护插件 | MIT 许可 */
|
|
2
|
-
import{getAgentDir as Gt,VERSION as Je}from"@earendil-works/pi-coding-agent";import{Worker as Tt}from"node:worker_threads";import{fileURLToPath as St}from"node:url";import*as I from"node:fs";import{join as b,resolve as pt}from"node:path";import{createHash as gt,randomUUID as ht}from"node:crypto";import{Worker as It}from"node:worker_threads";import{fileURLToPath as yt}from"node:url";var T="https://github.com/taills/pi-information-protecter/issues/new",ue="0.84.0-0.84.x, 0.85.1-0.87.x, 0.99.x, 1.2.0-1.4.x",Ze=["on","registerCommand","registerMarkdownTransformer"],Ve=["abort"],Qe=["notify","setStatus"];function K(t,e){return!t||typeof t!="object"&&typeof t!="function"?!1:typeof t[e]=="function"}function X(t,e){let r=[];for(let o of Ze)K(t,o)||r.push(`pi.${o}()`);if(e===void 0)return r;let n=e;for(let o of Ve)K(n,o)||r.push(`ctx.${o}()`);for(let o of Qe)K(n.ui,o)||r.push(`ctx.ui.${o}()`);return(!n.modelRegistry||typeof n.modelRegistry!="object")&&r.push("ctx.modelRegistry"),r}function de(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<=4:r!==0?!1:n===84?!0:n===85?o>=1:n===86||n===87||n===99}var q={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"],PI_CAPABILITY:["This Pi build is missing a capability this extension requires",`Update Pi; if the newest Pi still fails, report the listed capability at ${T}`],GUARD_UNAVAILABLE:["Cannot cover the model calls that have no extension hook","This Pi build exposes no model runtime to wrap; update Pi, or report this build at "+T],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"]},et={INTERNAL:["未预期的本地错误","重载并检查安装包完整性"],NOT_READY:["防护尚未初始化","查看初始化错误,修复后重载"],PI_CAPABILITY:["当前 Pi 构建缺少本扩展所需的能力",`请升级 Pi;若最新版 Pi 仍然失败,请将所列能力反馈至 ${T}`],GUARD_UNAVAILABLE:["无法覆盖没有扩展钩子的模型调用","该 Pi 构建未暴露可包装的模型运行时:请升级 Pi,或将该构建反馈至 "+T],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:["离线测试输入超出大小上限","改用更小的文件或更短的片段"]},fe={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",capabilityBlocked:"SPI Protecter: this Pi build does not expose {names}, so protection is off and requests are blocked instead of sent as plaintext. Report it: {url}",piNewer:"SPI Protecter: Pi {version} is newer than the suite-verified releases ({verified}). Every required hook is present, so protection is active and each request is verified; report anything that looks wrong: {url}",hookBypassed:"SPI Protecter: Pi did not run the request hook for a model call, so the runtime guard redacted it instead. Protection held, but please report it: {url}",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 et}from"@earendil-works/pi-coding-agent";import{Worker as kt}from"node:worker_threads";import{fileURLToPath as Dt}from"node:url";import*as O from"node:fs";import{join as x,resolve as At}from"node:path";import{createHash as Ot,randomUUID as wt}from"node:crypto";import{Worker as Nt}from"node:worker_threads";import{fileURLToPath as Ct}from"node:url";var _="https://github.com/taills/pi-information-protecter/issues/new",he="0.84.0-0.84.x, 0.85.1-0.87.x, 0.99.x, 1.2.0-1.4.x",nt=["on","registerCommand","registerMarkdownTransformer"],ot=["abort"],rt=["notify","setStatus"];function ee(t,e){return!t||typeof t!="object"&&typeof t!="function"?!1:typeof t[e]=="function"}function te(t,e){let o=[];for(let r of nt)ee(t,r)||o.push(`pi.${r}()`);if(e===void 0)return o;let n=e;for(let r of ot)ee(n,r)||o.push(`ctx.${r}()`);for(let r of rt)ee(n.ui,r)||o.push(`ctx.ui.${r}()`);return(!n.modelRegistry||typeof n.modelRegistry!="object")&&o.push("ctx.modelRegistry"),o}function ye(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<=4:o!==0?!1:n===84?!0:n===85?r>=1:n===86||n===87||n===99}var ne={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"],PI_CAPABILITY:["This Pi build is missing a capability this extension requires",`Update Pi; if the newest Pi still fails, report the listed capability at ${_}`],GUARD_UNAVAILABLE:["Cannot cover the model calls that have no extension hook","This Pi build exposes no model runtime to wrap; update Pi, or report this build at "+_],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'],CONFIG_ATTACHMENT:["Invalid attachment setting",'Use "ask", "allow" or "deny"'],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"]},it={INTERNAL:["未预期的本地错误","重载并检查安装包完整性"],NOT_READY:["防护尚未初始化","查看初始化错误,修复后重载"],PI_CAPABILITY:["当前 Pi 构建缺少本扩展所需的能力",`请升级 Pi;若最新版 Pi 仍然失败,请将所列能力反馈至 ${_}`],GUARD_UNAVAILABLE:["无法覆盖没有扩展钩子的模型调用","该 Pi 构建未暴露可包装的模型运行时:请升级 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 的对象'],CONFIG_ATTACHMENT:["附件配置值无效",'请使用 "ask"、"allow" 或 "deny"'],AUDIT_BATCH_LIMIT:["审计批次超过上限","减少单个请求的命中内容"],AUDIT_FULL:["审计日志将超过上限","检查记录后清空日志或本地归档"],AUDIT_PARTIAL:["审计日志末行不完整","本地检查或清空日志,不要上传日志"],AUDIT_LOCKED:["审计锁持续被占用","等待写入完成,全部停止后再检查残留锁"],AUDIT_UNSAFE:["审计文件不安全","使用本人普通文件且不含链接,不会绕过检查"],AUDIT_IO:["审计文件操作失败","检查错误码、权限和磁盘空间,不暴露路径或内容"],TEST_INPUT:["无法读取离线测试输入","请直接传入文本,或用 @<路径> 指向可读的普通文本文件"],TEST_SIZE:["离线测试输入超出大小上限","改用更小的文件或更短的片段"]},Ie={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",capabilityBlocked:"SPI Protecter: this Pi build does not expose {names}, so protection is off and requests are blocked instead of sent as plaintext. Report it: {url}",piNewer:"SPI Protecter: Pi {version} is newer than the suite-verified releases ({verified}). Every required hook is present, so protection is active and each request is verified; report anything that looks wrong: {url}",hookBypassed:"SPI Protecter: Pi did not run the request hook for a model call, so the runtime guard redacted it instead. Protection held, but please report it: {url}",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.",attachmentAskTitle:"Allow attachments?",attachmentAskBody:"This request contains image, audio, video or file content that SPI Protecter cannot inspect or redact. Allowing sends it unchanged to the provider.",attachmentAllow:"Allow this request",attachmentDeny:"Cancel request",attachmentAllowed:"SPI Protecter: attachment allowed for this request without inspection or redaction."},st={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|test <文本>|test @<路径>]。仅 test 接受内容,其他参数不要输入敏感内容。",testPreviewTitle:"离线脱敏测试,仅本地显示,编辑不会保存",testRedacted:"SPI Protecter:已在本地脱敏({chars}),未向任何模型发送内容。替换关系已记入本会话映射。",testUnchanged:"SPI Protecter:没有规则命中({chars}),下方文本未改动。",testFileLabel:"输入:本地文件",testTextLabel:"输入:行内文本",capabilityBlocked:"SPI Protecter:当前 Pi 构建未暴露 {names},因此保护未启用,请求会被拦截而不以明文发送。请反馈:{url}",piNewer:"SPI Protecter:Pi {version} 高于已经完整测试验证的版本({verified})。所需钩子均存在,保护已生效并会逐次校验;如发现异常请反馈:{url}",hookBypassed:"SPI Protecter:Pi 未对某次模型调用执行请求钩子,已由运行时闸门脱敏。保护仍然有效,但请反馈:{url}",logsTuiOnly:"请在本地 TUI 查看保护记录。",logsNone:"暂无可读记录。",logsSelectTitle:"保护记录",logsTruncated:"(仅显示有限尾部)",logsRevealTitle:"敏感明文",logsRevealBody:"确认在本地显示?请勿分享此界面。",logsPreviewTitle:"本地预览,编辑不会保存",logsPreviewTruncated:"[预览已截断]",clearTitle:"确认清空当前审计日志?",clearBody:"不可撤销。仅清空本机日志,配置和内存映射保留;后续请求可能写入新记录。",cleared:"已清空审计日志:{bytes}。",toolBlocked:"SPI Protecter 已阻止工具访问受保护的配置或审计日志,请在本地编辑。"};function
|
|
11
|
-
`)}var
|
|
12
|
-
`)}finally{
|
|
13
|
-
`;if(Buffer.byteLength(
|
|
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 开启新会话。",attachmentAskTitle:"允许发送附件?",attachmentAskBody:"此请求包含 SPI Protecter 无法检查或脱敏的图片、音频、视频或文件内容。允许后会将附件原样发送给提供商。",attachmentAllow:"允许本次请求",attachmentDeny:"取消请求",attachmentAllowed:"SPI Protecter:本次请求的附件未经检查或脱敏,将继续发送。",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:"输入:行内文本",capabilityBlocked:"SPI Protecter:当前 Pi 构建未暴露 {names},因此保护未启用,请求会被拦截而不以明文发送。请反馈:{url}",piNewer:"SPI Protecter:Pi {version} 高于已经完整测试验证的版本({verified})。所需钩子均存在,保护已生效并会逐次校验;如发现异常请反馈:{url}",hookBypassed:"SPI Protecter:Pi 未对某次模型调用执行请求钩子,已由运行时闸门脱敏。保护仍然有效,但请反馈:{url}",logsTuiOnly:"请在本地 TUI 查看保护记录。",logsNone:"暂无可读记录。",logsSelectTitle:"保护记录",logsTruncated:"(仅显示有限尾部)",logsRevealTitle:"敏感明文",logsRevealBody:"确认在本地显示?请勿分享此界面。",logsPreviewTitle:"本地预览,编辑不会保存",logsPreviewTruncated:"[预览已截断]",clearTitle:"确认清空当前审计日志?",clearBody:"不可撤销。仅清空本机日志,配置和内存映射保留;后续请求可能写入新记录。",cleared:"已清空审计日志:{bytes}。",toolBlocked:"SPI Protecter 已阻止工具访问受保护的配置或审计日志,请在本地编辑。"};function oe(t=process.env){let e=t.PI_PROTECTER_LANG||t.LC_ALL||t.LC_MESSAGES||t.LANG||t.LANGUAGE||at();return/^zh\b|^zh[-_]/i.test(e.trim())?"zh":"en"}function at(){try{return new Intl.DateTimeFormat().resolvedOptions().locale}catch{return""}}var R=oe();function Oe(){return R}function we(t){R=t}function d(t,e={}){return((R==="zh"?st:Ie)[t]??Ie[t]).replace(/\{(\w+)\}/g,(n,r)=>Object.hasOwn(e,r)?String(e[r]):n)}var ct={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} 个字符"}}},Ae=new Map;function b(t,e){let o=R==="zh"?"zh-CN":"en",n=Ae.get(R);if(!n){try{n=new Intl.PluralRules(o)}catch{n=void 0}n&&Ae.set(R,n)}let r=n?.select(e)??"other",s=ct[R][t],c=s[r]??s.other,u=new Intl.NumberFormat(o).format(e);return c.replace("{n}",u)}function Ne(t){let o=(R==="zh"?it[t]:ne[t])??ne[t]??ne.INTERNAL;return{reason:o[0],action:o[1]}}var Ce={INTERNAL:"internal",NOT_READY:"initialization",PI_CAPABILITY:"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",CONFIG_ATTACHMENT:"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 Te=["rule","otherRule","node","bytes","limit","timeoutMs","status"],lt=/^[A-Za-z][A-Za-z0-9]{0,39}$/,ut=/^(EACCES|EPERM|ENOENT|ENOSPC|EDQUOT|EROFS|ELOOP|EISDIR|ENOTDIR|EMFILE|ENFILE|EIO|EEXIST|EBADF|EBUSY|ENOTEMPTY)$/;function dt(t,e={}){let{reason:o,action:n}=Ne(t),r={};for(let s of Te){let c=e[s];typeof c=="number"&&Number.isSafeInteger(c)&&c>=0&&(r[s]=c)}return typeof e.errno=="string"&&ut.test(e.errno)&&(r.errno=e.errno),typeof e.errorName=="string"&<.test(e.errorName)&&(r.errorName=e.errorName),{code:t,stage:Ce[t],reason:o,action:n,...r}}function M(t){let e=Oe()==="zh"?":":": ",o=[...Te,"errno","errorName"].filter(n=>t[n]!==void 0).map(n=>`${n}=${t[n]}`).join(" ");return[d("blockedHeader"),`code=${t.code} stage=${t.stage}${o?` ${o}`:""}`,`${d("reasonLabel")}${e}${t.reason}`,`${d("actionLabel")}${e}${t.action}`,`${d("detailsLabel")}${e}/protecter status`].join(`
|
|
11
|
+
`)}var P=class extends Error{diagnostic;constructor(e,o={}){let n=dt(e,o);super(M(n)),this.name="ProtectionError",this.diagnostic=n}};function i(t,e={}){return new P(t,e)}function w(t,e,o={}){if(t instanceof P)return i(t.diagnostic.code,{...t.diagnostic,...o});let n=t&&typeof t=="object"&&"code"in t?t.code:void 0;return i(e,{...o,errno:typeof n=="string"?n:void 0})}function H(t,e){if(!t||typeof t!="object")return i(e);let o=t,n=typeof o.code=="string"&&Object.hasOwn(Ce,o.code)?o.code:e;return i(n,o)}import{constants as F,closeSync as Ee,fchmodSync as ft,fstatSync as mt,mkdirSync as pt,openSync as _e,readFileSync as gt,writeFileSync as ht}from"node:fs";import{dirname as yt}from"node:path";var Se=["ask","protected","off"],re=["provider","model","contextWindow","reserveTokens"];function Pe(t){return!t||typeof t!="object"?[]:re.filter(e=>Object.hasOwn(t,e))}var ie={version:1,sensitiveWords:[]},Re="ask";function It(t){if(typeof t=="string"){if(!Se.includes(t))throw i("CONFIG_COMPACTION");return}if(!t||typeof t!="object"||Array.isArray(t))throw i("CONFIG_COMPACTION");let e=t,o=["mode",...re];if(Object.keys(e).some(n=>!o.includes(n)))throw i("CONFIG_COMPACTION");if(e.mode!==void 0&&!Se.includes(e.mode))throw i("CONFIG_COMPACTION");for(let n of re){let r=e[n];if(r!==void 0&&typeof r!="string"&&typeof r!="number")throw i("CONFIG_COMPACTION")}}function $(t){return t===void 0?{mode:Re}:typeof t=="string"?{mode:t}:{mode:t.mode??Re}}function se(t){let e;try{e=JSON.parse(t)}catch{throw i("CONFIG_JSON")}let o=0;try{if(!e||e.version!==1||!Array.isArray(e.sensitiveWords)||Object.keys(e).some(r=>!["version","sensitiveWords","compaction","attachments"].includes(r)))throw i("CONFIG_SCHEMA");if(Object.hasOwn(e,"compaction")&&It(e.compaction),Object.hasOwn(e,"attachments")&&!["ask","allow","deny"].includes(e.attachments??""))throw i("CONFIG_ATTACHMENT");if(e.sensitiveWords.length>1e3)throw i("CONFIG_SIZE",{limit:1e3});let n=new Map;for(let r of e.sensitiveWords){if(o++,typeof r=="string"){if(!r||r.length>8192)throw i("CONFIG_SCHEMA",{rule:o,limit:8192});let c=JSON.stringify(["literal",r]);if(n.has(c)&&n.get(c)!==void 0)throw i("CONFIG_CONFLICT",{rule:o});n.set(c,void 0);continue}if(!r||typeof r!="object")throw i("CONFIG_SCHEMA",{rule:o});if(Object.hasOwn(r,"replacement")&&(typeof r.replacement!="string"||!r.replacement.trim()||r.replacement.length>8192||r.replacement.includes("__PIP_")))throw i("CONFIG_TARGET",{rule:o,limit:8192});if(r.type==="literal"){if(Object.keys(r).some(c=>!["type","value","replacement"].includes(c))||typeof r.value!="string"||!r.value||r.value.length>8192)throw i("CONFIG_SCHEMA",{rule:o,limit:8192})}else if(r.type==="regex"){if(Object.keys(r).some(c=>!["type","pattern","flags","replacement"].includes(c))||typeof r.pattern!="string"||!r.pattern||r.pattern.length>8192||r.flags!==void 0&&(typeof r.flags!="string"||!/^[gimsu]*$/.test(r.flags)))throw i("CONFIG_REGEX",{rule:o,limit:8192});try{new RegExp(r.pattern,r.flags??"")}catch{throw i("CONFIG_REGEX",{rule:o})}}else throw i("CONFIG_SCHEMA",{rule:o});let s=r.type==="literal"?JSON.stringify(["literal",r.value]):JSON.stringify(["regex",r.pattern,[...new Set((r.flags??"")+"g")].sort().join("")]);if(n.has(s)&&n.get(s)!==r.replacement)throw i("CONFIG_CONFLICT",{rule:o});n.set(s,r.replacement)}return e}catch(n){throw n instanceof P?n:i("CONFIG_SCHEMA",{rule:o})}}function ke(t,e=!1){let o;try{if(e){pt(yt(t),{recursive:!0,mode:448});try{let s=_e(t,F.O_WRONLY|F.O_CREAT|F.O_EXCL,384);try{ht(s,JSON.stringify(ie,null,2)+`
|
|
12
|
+
`)}finally{Ee(s)}}catch(s){if(s.code!=="EEXIST")throw w(s,"CONFIG_IO")}}o=_e(t,F.O_RDONLY|F.O_NOFOLLOW|F.O_NONBLOCK);let n=mt(o);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"&&ft(o,384);let r=gt(o,"utf8");if(Buffer.byteLength(r)>1024*1024)throw i("CONFIG_SIZE",{bytes:Buffer.byteLength(r),limit:1024*1024});return{config:se(r),raw:r}}catch(n){let r=n&&typeof n=="object"&&"code"in n?n.code:void 0;throw w(n,r==="ELOOP"||r==="EISDIR"||r==="ENOTDIR"?"CONFIG_UNSAFE":"CONFIG_IO")}finally{o!==void 0&&Ee(o)}}var ce=/^protecter(?:\.[a-f0-9]{32})?\.json$/;function Tt(t){return new Promise((e,o)=>{let n=new Nt(Ct(new URL("./validate-worker.mjs",import.meta.url)),{workerData:t,execArgv:[],resourceLimits:{maxOldGenerationSizeMb:64}}),r=!1,s=(u,m=i("WORKER_FAILED"))=>{r||(r=!0,clearTimeout(c),n.terminate(),u?e():o(m))},c=setTimeout(()=>s(!1,i("CONFIG_TIMEOUT",{timeoutMs:2e3})),2e3);n.once("message",u=>u===!0?s(!0):s(!1,H(u,"CONFIG_SCHEMA"))),n.once("error",()=>s(!1)),n.once("exit",()=>s(!1))})}function Et(t){let e=new Set,o=[];for(let l of t)for(let y of l.sensitiveWords){let I=typeof y=="string"?JSON.stringify(["literal",y,null]):y.type==="literal"?JSON.stringify(["literal",y.value,y.replacement??null]):JSON.stringify(["regex",y.pattern,[...new Set((y.flags??"")+"g")].sort().join(""),y.replacement??null]);e.has(I)||(e.add(I),o.push(y))}let n=[];for(let l of t)l.compaction!==void 0&&n.push($(l.compaction));let s=["off","ask","protected"].find(l=>n.some(y=>y.mode===l)),c={version:1,sensitiveWords:o};s!==void 0&&(c.compaction={mode:s});let u=t.map(l=>l.attachments).filter(l=>l!==void 0);u.length&&(c.attachments=["deny","ask","allow"].find(l=>u.includes(l)));let m=JSON.stringify(c);if(Buffer.byteLength(m)>1024*1024)throw i("CONFIG_SIZE",{bytes:Buffer.byteLength(m),limit:1024*1024});return se(m)}function De(t){let e;try{e=O.lstatSync(t,{bigint:!0})}catch(o){throw w(o,"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 ae(t,e){let o=x(t,e),n=De(o),r=ke(o);if(De(o)!==n)throw i("MIGRATION_CHANGED");return{name:e,...r,identity:n,digest:Ot("sha256").update(r.raw).digest("hex")}}function v(t,e){let o=ae(t,e.name);if(o.identity!==e.identity||o.digest!==e.digest)throw i("MIGRATION_CHANGED")}function j(t){return O.readdirSync(t).filter(e=>ce.test(e)).sort()}function Le(t){if(process.platform==="win32")return;let e=O.openSync(t,O.constants.O_RDONLY);try{O.fsyncSync(e)}finally{O.closeSync(e)}}async function be(t,e,o={}){if(!/^[a-f0-9]{32}$/.test(e))throw i("MACHINE_ID");let n=At(t),r=`protecter.${e}.json`,s=x(n,r);O.mkdirSync(n,{recursive:!0,mode:448});let c=x(n,".protecter-migration.lock"),u=Date.now()+(o.lockTimeoutMs??5e3);for(;;)try{O.mkdirSync(c,{mode:448});break}catch(l){if(l.code!=="EEXIST")throw w(l,"MIGRATION_IO");if(Date.now()>=u)throw i("MIGRATION_LOCKED",{timeoutMs:o.lockTimeoutMs??5e3});await new Promise(y=>setTimeout(y,50))}let m;try{let l=j(n);if(l.length>64)throw i("MIGRATION_LIMIT",{limit:64});let I=[...l].sort((p,C)=>p===r?-1:C===r?1:p.localeCompare(C)).map(p=>ae(n,p)),A=Et(I.length?I.map(p=>p.config):[ie]);if(await Tt([A]),I.length===1&&I[0].name===r){if(v(n,I[0]),JSON.stringify(j(n))!==JSON.stringify(l))throw i("MIGRATION_CHANGED");return{path:s,config:I[0].config,raw:I[0].raw,sourceRaws:[I[0].raw],migrated:0}}let N=JSON.stringify(A,null,2)+`
|
|
13
|
+
`;if(Buffer.byteLength(N)>1024*1024)throw i("CONFIG_SIZE",{bytes:Buffer.byteLength(N),limit:1024*1024});m=x(n,`.protecter-migration.${wt()}.tmp`);let f=O.openSync(m,O.constants.O_WRONLY|O.constants.O_CREAT|O.constants.O_EXCL,384);try{O.writeFileSync(f,N),O.fsyncSync(f)}finally{O.closeSync(f)}if(o.checkpoint?.("beforeCommit",s),JSON.stringify(j(n))!==JSON.stringify(l))throw i("MIGRATION_CHANGED");for(let p of I)v(n,p);O.renameSync(m,s),m=void 0,Le(n);let a=ae(n,r);if(a.raw!==N)throw i("MIGRATION_CHANGED");o.checkpoint?.("afterCommit",s);for(let p of I)p.name!==r&&(o.checkpoint?.("beforeDelete",x(n,p.name)),v(n,a),v(n,p),O.unlinkSync(x(n,p.name)));Le(n);let g=[r];if(JSON.stringify(j(n))!==JSON.stringify(g))throw i("MIGRATION_CHANGED");return v(n,a),{path:s,config:A,raw:N,sourceRaws:[...new Set([...I.map(p=>p.raw),N])],migrated:I.filter(p=>p.name!==r).length}}catch(l){throw l instanceof P?l:w(l,"MIGRATION_IO")}finally{if(m)try{O.unlinkSync(m)}catch{}O.rmdirSync(c)}}import{createHash as _t}from"node:crypto";import{readFileSync as St}from"node:fs";import{execFileSync as Me}from"node:child_process";function le(t){let e=t.trim().toLowerCase().replace(/-/g,"");if(!/^[a-f0-9]{32}$/.test(e)||/^0+$/.test(e))throw i("MACHINE_ID");return _t("sha256").update(`pi-information-protecter:v1:${e}`).digest("hex").slice(0,32)}function Fe(){try{if(process.platform==="linux")return le(St("/etc/machine-id","utf8"));if(process.platform==="darwin"){let t=Me("/usr/sbin/ioreg",["-rd1","-c","IOPlatformExpertDevice"],{encoding:"utf8",timeout:5e3,maxBuffer:1048576,stdio:["ignore","pipe","pipe"]});return le(t.match(/"IOPlatformUUID"\s*=\s*"([a-fA-F0-9-]+)"/)?.[1]??"")}if(process.platform==="win32"){let t=Me("reg.exe",["query","HKLM\\SOFTWARE\\Microsoft\\Cryptography","/v","MachineGuid","/reg:64"],{encoding:"utf8",timeout:5e3,maxBuffer:65536,stdio:["ignore","pipe","pipe"]});return le(t.match(/MachineGuid\s+REG_SZ\s+([a-fA-F0-9-]+)/i)?.[1]??"")}}catch{}throw i("MACHINE_ID")}import*as h from"node:fs";import{randomUUID as Rt}from"node:crypto";var xe=32*1024*1024,Ge=8*1024*1024;function Pt(t){let e=o=>String(o).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())} ${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}`}function ue(t,e,o=e){let n=h.openSync(t,(e?h.constants.O_RDWR|(o?h.constants.O_CREAT:0):h.constants.O_RDONLY)|h.constants.O_NOFOLLOW|h.constants.O_NONBLOCK,384);try{let r=h.fstatSync(n);if(!r.isFile()||r.nlink!==1||process.getuid&&r.uid!==process.getuid())throw i("AUDIT_UNSAFE");return process.platform!=="win32"&&h.fchmodSync(n,384),n}catch(r){throw h.closeSync(n),w(r,"AUDIT_UNSAFE")}}function Y(t){let e=t&&typeof t=="object"&&"code"in t?t.code:void 0;return w(t,e==="ELOOP"||e==="EISDIR"||e==="ENOTDIR"?"AUDIT_UNSAFE":"AUDIT_IO")}async function Ue(t){let e=`${t}.lock`,o=Date.now()+2e3;for(;;)try{return h.mkdirSync(e,{mode:448}),e}catch(n){if(n.code!=="EEXIST")throw w(n,"AUDIT_IO");if(Date.now()>=o)throw i("AUDIT_LOCKED",{timeoutMs:2e3});await new Promise(r=>setTimeout(r,25))}}async function ve(t){let e=await Ue(t),o;try{try{o=ue(t,!0,!1)}catch(r){if(r.code==="ENOENT")return 0;throw r}let n=h.fstatSync(o).size;return h.ftruncateSync(o,0),h.fsyncSync(o),n}catch(n){throw Y(n)}finally{try{o!==void 0&&h.closeSync(o)}finally{h.rmdirSync(e)}}}async function ze(t,e,o){if(!o.length)return;let n=new Date,r=Rt(),s=Buffer.from(o.map(([m,l])=>JSON.stringify({version:1,time:Pt(n),timezoneOffset:-n.getTimezoneOffset(),requestId:r,provider:e||"unknown",original:l,replacement:m})).join(`
|
|
14
14
|
`)+`
|
|
15
|
-
`);if(
|
|
16
|
-
`);
|
|
17
|
-
`),u=d.pop()!=="",A=[],g=!1;for(let O of d.slice(-e))try{let f=JSON.parse(O);if(f.version!==1||typeof f.time!="string"||typeof f.provider!="string"||typeof f.original!="string"||typeof f.replacement!="string"||typeof f.requestId!="string"||typeof f.timezoneOffset!="number")throw new Error;A.push(f)}catch{g=!0}return{records:A,truncated:o>0||d.length>e||u||g}}catch(n){throw H(n)}finally{r!==void 0&&h.closeSync(r)}}var $=class{constructor(e,r=2e3,n=Pe){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?L(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 _e(this.configDir,e);if(this.closed)throw i("NOT_READY");this.snapshot=r,this.lastError=void 0}catch(e){let r=N(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 Fe(this.auditPath,e)}clearAuditRecords(){let e=this.queue.then(()=>{if(!this.ready)throw this.notReady();return be(this.auditPath)});return this.queue=e.catch(()=>{}),e}get ruleCount(){return this.snapshot?.config.sensitiveWords.length??0}get compaction(){return z(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=N(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 c;try{c=JSON.parse(a)}catch{throw i("PAYLOAD_JSON")}let l=await new Promise((d,u)=>{let A=!1,g;try{g=new Tt(St(new URL("./scan-worker.mjs",import.meta.url)),{workerData:{payload:c,rules:n.sensitiveWords,entries:[...this.tokens],configRaws:o},execArgv:[],resourceLimits:{maxOldGenerationSizeMb:128}})}catch(s){u(N(s,"WORKER_FAILED"));return}this.workers.add(g);let O=(s,p=i("WORKER_FAILED"))=>{if(!A){if(A=!0,clearTimeout(f),this.workers.delete(g),g.terminate(),!s||this.closed){u(this.closed?i("NOT_READY"):p);return}d(s)}},f=setTimeout(()=>O(void 0,i("SCAN_TIMEOUT",{timeoutMs:this.timeoutMs})),this.timeoutMs);g.once("message",s=>{s?.failed?O(void 0,U(s.diagnostic,"SCAN_INTERNAL")):s&&Array.isArray(s.additions)&&Array.isArray(s.hits)?O(s):O()}),g.once("error",()=>O()),g.once("exit",()=>O())});if(this.closed)throw i("NOT_READY");if(await Me(this.auditPath,r,l.hits),this.closed)throw i("NOT_READY");for(let[d,u]of l.additions)this.tokens.set(d,u);return l.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 c=this.restoreText(o);if(Object.hasOwn(n,c))throw i("RESTORE_KEY_COLLISION");n[c]=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 _t,statSync as xe,readdirSync as Rt}from"node:fs";import{homedir as Pt}from"node:os";import{basename as ie,dirname as v,isAbsolute as Dt,relative as Ge,resolve as Y}from"node:path";import{fileURLToPath as Lt}from"node:url";function kt(t,e){let r=t.replace(/^@/,"");return r.startsWith("file://")&&(r=Lt(r)),(r==="~"||r.startsWith("~/"))&&(r=Pt()+r.slice(1)),Y(e,r)}function se(t){try{return _t(t)}catch{let e=v(t);return e===t?t:Y(se(e),Ge(e,t))}}function bt(t,e){let r=Ge(t,e);return r===""||!r.startsWith("..")&&!Dt(r)}function ve(t,e){try{let r=xe(t),n=xe(e);return r.dev===n.dev&&r.ino===n.ino}catch{return!1}}function Ue(t,e,r,n){if(!n)return!0;let o=se(Y(n));if(["bash","powershell"].includes(t)){let l=typeof e.command=="string"?e.command:"";if(/protecter(?:\.[a-f0-9]{32})?\.jsonl?|\.protecter-migration/i.test(l)||l.includes(n))return!0}let a=e.path??e.file_path??e.filePath,c=["grep","find","ls"].includes(t);if(typeof a!="string"&&!c)return!1;try{let l=kt(typeof a=="string"?a:".",r),d=se(l),u=/^protecter\.[a-f0-9]{32}\.jsonl(?:\.lock)?$/,A=Rt(v(o)).filter(g=>u.test(g)).some(g=>ve(l,Y(v(o),g)));return v(d)===v(o)&&(ne.test(ie(d))||u.test(ie(d))||ie(d).startsWith(".protecter-migration"))||d===o||ve(l,n)||A||c&&bt(d,o)}catch{return!0}}function ae(t,e){t.length=0;for(let r of e)t.push(r)}function ce(t){if(!Array.isArray(t))throw i("COMPACT_FAILED");return t}function ze(t){if(typeof t!="string")throw i("COMPACT_FAILED");return t}async function Be(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=ce(o.messages),c=ce(o.prefix),l=n.previousSummary===void 0?void 0:ze(o.previous);ae(n.messagesToSummarize,a),ae(n.turnPrefixMessages,c),l!==void 0&&(n.previousSummary=l)}async function He(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=ce(o.entries),c=n.customInstructions===void 0?void 0:ze(o.instructions);return ae(n.entriesToSummarize,a),c===void 0?{}:{customInstructions:c}}var $e=["stream","streamSimple"],Mt=["classify","generateImages"],Ye=$e,le=Symbol.for("pi-information-protecter.runtime-guard");function Ft(t){let e=t?.runtime;if(!e||typeof e!="object")throw i("GUARD_UNAVAILABLE");let r=e;for(let n of Ye)if(typeof r[n]!="function")throw i("GUARD_UNAVAILABLE");return r}function xt(t){return!t||typeof t!="object"?!1:t.onPayload!==void 0}function vt(t,e,r,n){if(!e||typeof e!="object")return;let o=e.onPayload;if(!n||typeof o!="function")return e;let a=o;return{...e,onPayload:async c=>{let l=n.runs(),d=await a(c);return n.runs()>l?d:(n.onBypass?.(),r(t,d===void 0?c:d))}}}function je(t,e,r){let n=Ft(t);n[le]?.();let o=[...Ye,...Mt.filter(c=>typeof n[c]=="function")].map(c=>[c,n[c]]);for(let[c,l]of o){let d=$e.includes(c),u=function(A,g,O){return d&&xt(O)?l.call(this,A,g,vt(A,O,e,r)):(async()=>l.call(this,A,await e(A,g),O))()};n[c]=u}let a=()=>{for(let[c,l]of o)n[c]=l;delete n[le]};return Object.defineProperty(n,le,{value:a,configurable:!0,enumerable:!1,writable:!0}),a}import{lstat as Ut,readFile as zt}from"node:fs/promises";import{resolve as Bt}from"node:path";var We=256*1024;async function Ht(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=Bt(e(r.slice(1).trim())),o;try{o=await Ut(n)}catch(a){throw N(a,"TEST_INPUT")}if(!o.isFile())throw i("TEST_INPUT");if(o.size>We)throw i("TEST_SIZE",{bytes:o.size,limit:We});try{return{text:await zt(n,"utf8"),fromFile:!0}}catch(a){throw N(a,"TEST_INPUT")}}function $t(t){ge(Z());let e=new $(Gt()),r=X(t),n=()=>r.length===0,o=0,a=!1,c=!1,l,d,u,A=f=>{let s=f?.provider;return typeof s=="string"?s:"unknown"},g=f=>{let s=L(f);return l={at:new Date().toISOString(),text:s},s};t.on("session_start",async(f,s)=>{try{if(r=X(t,s),!n())throw s.ui.notify(m("capabilityBlocked",{names:r.join(", "),url:T}),"error"),i("PI_CAPABILITY");await e.initialize(),u=je(s.modelRegistry,(y,E)=>e.redact(E,A(y)),{runs:()=>o,onBypass:()=>{if(!a){a=!0;try{s.ui.notify(m("hookBypassed",{url:T}),"warning")}catch{}}}}),c=!0,de(Je)||s.ui.notify(m("piNewer",{version:Je,verified:ue,url:T}),"warning");let p=e.ruleCount;s.ui.setStatus("protecter",m("statusBarRules",{rules:D("rules",p)})),p===0&&s.ui.notify(m("emptyRules"),"warning");let C=Ee(e.rawCompaction);C.length&&s.ui.notify(m("compactIgnoredKeys",{keys:C.join(", ")}),"warning")}catch(p){c=!1,s.ui.setStatus("protecter",m("statusBarNotReady")),s.ui.notify(g(N(p,"CONFIG_IO").diagnostic),"error")}}),t.on("before_provider_request",async(f,s)=>{o++;try{if(!n())throw i("PI_CAPABILITY");let p=await e.redact(f.payload,s.model?.provider??"unknown");return c=!0,p}catch(p){c=!1;let C=g(N(p,"INTERNAL").diagnostic);try{s.abort()}catch{}try{s.ui.notify(C,"error")}catch{}return{}}}),t.on("message_end",f=>{if(f.message.role!=="assistant")return;let s=f.message;return{message:{...s,content:s.content.map(p=>p.type==="text"?{...p,text:e.restoreText(p.text)}:p.type==="thinking"?{...p,thinking:e.restoreText(p.thinking)}:p.type==="toolCall"?{...p,arguments:e.restore(p.arguments)}:p),...s.errorMessage?{errorMessage:e.restoreText(s.errorMessage)}:{}}}}),t.registerMarkdownTransformer((f,s)=>s.messageType==="user"?f:e.restoreText(f)),t.on("tool_call",(f,s)=>{if(!c)return{block:!0,reason:e.lastDiagnosticText??l?.text??L(i("NOT_READY").diagnostic)};let p=e.restore(f.input);for(let C of Object.keys(f.input))delete f.input[C];if(Object.assign(f.input,p),Ue(f.toolName,f.input,s.cwd,e.configPath))return{block:!0,reason:m("toolBlocked")}});let O=async(f,s)=>{if(!n())throw i("PI_CAPABILITY");if(!e.ready)throw e.lastDiagnostic?i(e.lastDiagnostic.code,e.lastDiagnostic):i("NOT_READY");let p=e.compactionMode;if(p==="off")throw i("COMPACT_DENIED");if(d==="deny")throw i("COMPACT_DENIED");if(p!=="ask"||d==="allow")return;let C=[m("compactAllowOnce"),m("compactAllowAlways"),m("compactDenyOnce"),m("compactDenyAlways")],y=await f.ui.select(`${m("compactAskTitle")}
|
|
15
|
+
`);if(s.length>Ge)throw i("AUDIT_BATCH_LIMIT",{bytes:s.length,limit:Ge});let c=await Ue(t),u;try{u=ue(t,!0);let m=h.fstatSync(u).size;if(m+s.length>xe)throw i("AUDIT_FULL",{bytes:m+s.length,limit:xe});if(m){let l=Buffer.alloc(1);if(h.readSync(u,l,0,1,m-1),l[0]!==10)throw i("AUDIT_PARTIAL")}try{let l=0;for(;l<s.length;){let y=h.writeSync(u,s,l,s.length-l,m+l);if(!y)throw i("AUDIT_IO");l+=y}h.fsyncSync(u)}catch(l){throw h.ftruncateSync(u,m),h.fsyncSync(u),Y(l)}}catch(m){throw Y(m)}finally{u!==void 0&&h.closeSync(u),h.rmdirSync(c)}}function Be(t,e=20){if(!Number.isInteger(e)||e<1||e>100)throw i("INTERNAL",{limit:100});let o;try{try{o=ue(t,!1)}catch(A){if(A.code==="ENOENT")return{records:[],truncated:!1};throw A}let n=h.fstatSync(o).size,r=Math.max(0,n-1024*1024),s=Buffer.alloc(n-r),c=h.readSync(o,s,0,s.length,r),u=s.subarray(0,c).toString("utf8");if(r){let A=u.indexOf(`
|
|
16
|
+
`);u=A<0?"":u.slice(A+1)}let m=u.split(`
|
|
17
|
+
`),l=m.pop()!=="",y=[],I=!1;for(let A of m.slice(-e))try{let N=JSON.parse(A);if(N.version!==1||typeof N.time!="string"||typeof N.provider!="string"||typeof N.original!="string"||typeof N.replacement!="string"||typeof N.requestId!="string"||typeof N.timezoneOffset!="number")throw new Error;y.push(N)}catch{I=!0}return{records:y,truncated:r>0||m.length>e||l||I}}catch(n){throw Y(n)}finally{o!==void 0&&h.closeSync(o)}}var J=class{constructor(e,o=2e3,n=Fe){this.configDir=e;this.timeoutMs=o;this.machineId=n}configDir;timeoutMs;machineId;tokens=new Map;queue=Promise.resolve();workers=new Set;closed=!1;attachmentOptions={};snapshot;lastError;restorePattern;restoreSize=-1;get lastDiagnostic(){return this.lastError?{...this.lastError}:void 0}get lastDiagnosticText(){return this.lastError?M(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 be(this.configDir,e);if(this.closed)throw i("NOT_READY");this.snapshot=o,this.attachmentOptions.mode=o.config.attachments??"ask",this.lastError=void 0}catch(e){this.attachmentOptions.mode="deny";let o=w(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 Be(this.auditPath,e)}clearAuditRecords(){let e=this.queue.then(()=>{if(!this.ready)throw this.notReady();return ve(this.auditPath)});return this.queue=e.catch(()=>{}),e}get ruleCount(){return this.snapshot?.config.sensitiveWords.length??0}get compaction(){return $(this.snapshot?.config.compaction)}get compactionMode(){return this.compaction.mode}get attachmentMode(){return this.attachmentOptions.mode??"ask"}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 s=w(r,"INTERNAL");throw this.lastError=s.diagnostic,s});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,s;try{s=JSON.stringify(e)}catch{throw i("PAYLOAD_JSON")}if(!s)throw i("PAYLOAD_JSON");if(Buffer.byteLength(s)>8*1024*1024)throw i("PAYLOAD_SIZE",{bytes:Buffer.byteLength(s),limit:8*1024*1024});let c;try{c=JSON.parse(s)}catch{throw i("PAYLOAD_JSON")}let u=await new Promise((m,l)=>{let y=!1,I;try{I=new kt(Dt(new URL("./scan-worker.mjs",import.meta.url)),{workerData:{payload:c,rules:n.sensitiveWords,entries:[...this.tokens],configRaws:r},execArgv:[],resourceLimits:{maxOldGenerationSizeMb:128}})}catch(f){l(w(f,"WORKER_FAILED"));return}this.workers.add(I);let A=(f,a=i("WORKER_FAILED"))=>{if(!y){if(y=!0,clearTimeout(N),this.workers.delete(I),I.terminate(),!f||this.closed){l(this.closed?i("NOT_READY"):a);return}m(f)}},N=setTimeout(()=>A(void 0,i("SCAN_TIMEOUT",{timeoutMs:this.timeoutMs})),this.timeoutMs);I.once("message",f=>{f?.failed?A(void 0,H(f.diagnostic,"SCAN_INTERNAL")):f&&Array.isArray(f.additions)&&Array.isArray(f.hits)?A(f):A()}),I.once("error",()=>A()),I.once("exit",()=>A())});if(this.closed)throw i("NOT_READY");if(await ze(this.auditPath,o,u.hits),this.closed)throw i("NOT_READY");for(let[m,l]of u.additions)this.tokens.set(m,l);return u.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,s]of Object.entries(e)){let c=this.restoreText(r);if(Object.hasOwn(n,c))throw i("RESTORE_KEY_COLLISION");n[c]=this.restore(s,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 Lt,statSync as He,readdirSync as bt}from"node:fs";import{homedir as Mt}from"node:os";import{basename as de,dirname as z,isAbsolute as Ft,relative as je,resolve as W}from"node:path";import{fileURLToPath as xt}from"node:url";function Gt(t,e){let o=t.replace(/^@/,"");return o.startsWith("file://")&&(o=xt(o)),(o==="~"||o.startsWith("~/"))&&(o=Mt()+o.slice(1)),W(e,o)}function fe(t){try{return Lt(t)}catch{let e=z(t);return e===t?t:W(fe(e),je(e,t))}}function Ut(t,e){let o=je(t,e);return o===""||!o.startsWith("..")&&!Ft(o)}function $e(t,e){try{let o=He(t),n=He(e);return o.dev===n.dev&&o.ino===n.ino}catch{return!1}}function Ye(t,e,o,n){if(!n)return!0;let r=fe(W(n));if(["bash","powershell"].includes(t)){let u=typeof e.command=="string"?e.command:"";if(/protecter(?:\.[a-f0-9]{32})?\.jsonl?|\.protecter-migration/i.test(u)||u.includes(n))return!0}let s=e.path??e.file_path??e.filePath,c=["grep","find","ls"].includes(t);if(typeof s!="string"&&!c)return!1;try{let u=Gt(typeof s=="string"?s:".",o),m=fe(u),l=/^protecter\.[a-f0-9]{32}\.jsonl(?:\.lock)?$/,y=bt(z(r)).filter(I=>l.test(I)).some(I=>$e(u,W(z(r),I)));return z(m)===z(r)&&(ce.test(de(m))||l.test(de(m))||de(m).startsWith(".protecter-migration"))||m===r||$e(u,n)||y||c&&Ut(m,r)}catch{return!0}}function me(t,e){t.length=0;for(let o of e)t.push(o)}function pe(t){if(!Array.isArray(t))throw i("COMPACT_FAILED");return t}function Je(t){if(typeof t!="string")throw i("COMPACT_FAILED");return t}async function We(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 s=pe(r.messages),c=pe(r.prefix),u=n.previousSummary===void 0?void 0:Je(r.previous);me(n.messagesToSummarize,s),me(n.turnPrefixMessages,c),u!==void 0&&(n.previousSummary=u)}async function qe(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 s=pe(r.entries),c=n.customInstructions===void 0?void 0:Je(r.instructions);return me(n.entriesToSummarize,s),c===void 0?{}:{customInstructions:c}}var Ke=["stream","streamSimple"],vt=["classify","generateImages"],Xe=Ke,ge=Symbol.for("pi-information-protecter.runtime-guard");function zt(t){let e=t?.runtime;if(!e||typeof e!="object")throw i("GUARD_UNAVAILABLE");let o=e;for(let n of Xe)if(typeof o[n]!="function")throw i("GUARD_UNAVAILABLE");return o}function Bt(t){return!t||typeof t!="object"?!1:t.onPayload!==void 0}function Ht(t,e,o,n){if(!e||typeof e!="object")return;let r=e.onPayload;if(!n||typeof r!="function")return e;let s=r;return{...e,onPayload:async c=>{let u=n.runs(),m=await s(c);return n.runs()>u?m:(n.onBypass?.(),o(t,m===void 0?c:m))}}}function Ze(t,e,o){let n=zt(t);n[ge]?.();let r=[...Xe,...vt.filter(c=>typeof n[c]=="function")].map(c=>[c,n[c]]);for(let[c,u]of r){let m=Ke.includes(c),l=function(y,I,A){return m&&Bt(A)?u.call(this,y,I,Ht(y,A,e,o)):(async()=>u.call(this,y,await e(y,I),A))()};n[c]=l}let s=()=>{for(let[c,u]of r)n[c]=u;delete n[ge]};return Object.defineProperty(n,ge,{value:s,configurable:!0,enumerable:!1,writable:!0}),s}function q(t,e=0){if(e>80||!t||typeof t!="object")return!1;if(Array.isArray(t))return t.some(n=>q(n,e+1));let o=t;return Ve(o)||Object.keys(o).some(Qe)?!0:Object.values(o).some(n=>q(n,e+1))}var Ve=t=>typeof t.type=="string"&&/image|audio|video|document|(^|_)file($|_)/i.test(t.type),Qe=t=>/^(inlineData|inline_data|fileData|file_data|image_url|input_audio)$/.test(t);async function K(t,e,o=0){if(o>80)throw i("SCAN_COMPLEXITY");if(typeof t=="string")return e(t);if(Array.isArray(t))return Promise.all(t.map(n=>K(n,e,o+1)));if(t&&typeof t=="object"){let n=t;if(Ve(n))return t;let r=Object.create(null);for(let[s,c]of Object.entries(n))Qe(s)||s==="type"&&typeof c=="string"?r[s]=c:r[s]=await K(c,e,o+1);return r}return t}import{lstat as jt,readFile as Yt}from"node:fs/promises";import{resolve as Jt}from"node:path";var tt=256*1024;async function Wt(t){let e=s=>/^(['"]).*\1$/s.test(s)?s.slice(1,-1):s,o=e(t);if(!o.startsWith("@"))return{text:o,fromFile:!1};let n=Jt(e(o.slice(1).trim())),r;try{r=await jt(n)}catch(s){throw w(s,"TEST_INPUT")}if(!r.isFile())throw i("TEST_INPUT");if(r.size>tt)throw i("TEST_SIZE",{bytes:r.size,limit:tt});try{return{text:await Yt(n,"utf8"),fromFile:!0}}catch(s){throw w(s,"TEST_INPUT")}}function qt(t){we(oe());let e=new J($t()),o=te(t),n=()=>o.length===0,r=0,s=!1,c=!1,u,m,l,y,I=f=>{let a=f?.provider;return typeof a=="string"?a:"unknown"},A=f=>{let a=M(f);return u={at:new Date().toISOString(),text:a},a};t.on("session_start",async(f,a)=>{try{if(o=te(t,a),!n())throw a.ui.notify(d("capabilityBlocked",{names:o.join(", "),url:_}),"error"),i("PI_CAPABILITY");await e.initialize(),l=void 0,y=Ze(a.modelRegistry,(C,E)=>e.redact(E,I(C)),{runs:()=>r,onBypass:()=>{if(!s){s=!0;try{a.ui.notify(d("hookBypassed",{url:_}),"warning")}catch{}}}}),c=!0,ye(et)||a.ui.notify(d("piNewer",{version:et,verified:he,url:_}),"warning");let g=e.ruleCount;a.ui.setStatus("protecter",d("statusBarRules",{rules:b("rules",g)})),g===0&&a.ui.notify(d("emptyRules"),"warning");let p=Pe(e.rawCompaction);p.length&&a.ui.notify(d("compactIgnoredKeys",{keys:p.join(", ")}),"warning")}catch(g){c=!1,a.ui.setStatus("protecter",d("statusBarNotReady")),a.ui.notify(A(w(g,"CONFIG_IO").diagnostic),"error")}}),t.on("before_provider_request",async(f,a)=>{r++;try{if(!n())throw i("PI_CAPABILITY");let g=e.attachmentMode;if(q(f.payload)){let C=!1;if(g==="deny"||l==="deny")C=!1;else if(g==="allow"||l==="allow")C=!0;else if(g==="ask"&&!l){let k=[d("attachmentAllow"),d("attachmentDeny")],D=await a.ui.select(`${d("attachmentAskTitle")}
|
|
18
18
|
|
|
19
|
-
${
|
|
20
|
-
`);s.mode==="tui"?await s.ui.editor(m("testPreviewTitle"),`${F}
|
|
19
|
+
${d("attachmentAskBody")}`,k);C=D===k[0],D!==void 0&&(l=C?"allow":"deny")}if(!C)throw i("SCAN_ATTACHMENT");a.ui.notify(d("attachmentAllowed"),"warning");let E=a.model?.provider??"unknown",X=await K(f.payload,async k=>{let D=await e.redact(k,E);return typeof D=="string"?D:k});return c=!0,X}let p=await e.redact(f.payload,a.model?.provider??"unknown");return c=!0,p}catch(g){c=!1;let p=A(w(g,"INTERNAL").diagnostic);try{a.abort()}catch{}try{a.ui.notify(p,"error")}catch{}return{}}}),t.on("message_end",f=>{if(f.message.role!=="assistant")return;let a=f.message;return{message:{...a,content:a.content.map(g=>g.type==="text"?{...g,text:e.restoreText(g.text)}:g.type==="thinking"?{...g,thinking:e.restoreText(g.thinking)}:g.type==="toolCall"?{...g,arguments:e.restore(g.arguments)}:g),...a.errorMessage?{errorMessage:e.restoreText(a.errorMessage)}:{}}}}),t.registerMarkdownTransformer((f,a)=>a.messageType==="user"?f:e.restoreText(f)),t.on("tool_call",(f,a)=>{if(!c)return{block:!0,reason:e.lastDiagnosticText??u?.text??M(i("NOT_READY").diagnostic)};let g=e.restore(f.input);for(let p of Object.keys(f.input))delete f.input[p];if(Object.assign(f.input,g),Ye(f.toolName,f.input,a.cwd,e.configPath))return{block:!0,reason:d("toolBlocked")}});let N=async(f,a)=>{if(!n())throw i("PI_CAPABILITY");if(!e.ready)throw e.lastDiagnostic?i(e.lastDiagnostic.code,e.lastDiagnostic):i("NOT_READY");let g=e.compactionMode;if(g==="off")throw i("COMPACT_DENIED");if(m==="deny")throw i("COMPACT_DENIED");if(g!=="ask"||m==="allow")return;let p=[d("compactAllowOnce"),d("compactAllowAlways"),d("compactDenyOnce"),d("compactDenyAlways")],C=await f.ui.select(`${d("compactAskTitle")}
|
|
21
20
|
|
|
22
|
-
${
|
|
21
|
+
${d("compactAskBody")}`,p,{signal:a}),E=C===void 0?-1:p.indexOf(C);if(E===1?(m="allow",f.ui.notify(d("compactAlwaysNotice"),"info")):E===3&&(m="deny",f.ui.notify(d("compactDenyNotice"),"warning")),E!==0&&E!==1)throw i("COMPACT_DENIED")};t.on("session_before_compact",async(f,a)=>{try{await N(a,f.signal),await We(f,e,a.model?.provider??"unknown"),a.ui.notify(d("compactRedacted"),"info");return}catch(g){return a.ui.notify(A(w(g,"COMPACT_FAILED").diagnostic),"warning"),{cancel:!0}}}),t.on("session_before_tree",async(f,a)=>{if(f.preparation.userWantsSummary)try{await N(a,f.signal);let g=await qe(f,e,a.model?.provider??"unknown");return a.ui.notify(d("compactRedacted"),"info"),g}catch(g){return a.ui.notify(A(w(g,"COMPACT_FAILED").diagnostic),"warning"),{cancel:!0}}}),t.registerCommand("protecter",{description:d("commandDescription"),handler:async(f,a)=>{let g=f.trim(),p=g.split(/\s+/).filter(Boolean),C=p[0]??"logs";if(C==="test"){let T=g.slice(C.length).trim();if(!T){a.ui.notify(d("usage"),"info");return}try{if(!e.ready)throw i("NOT_READY");let{text:L,fromFile:G}=await Wt(T),S=(await e.redact({text:L},"test")).text;if(typeof S!="string")throw i("INTERNAL");let U=[d(G?"testFileLabel":"testTextLabel"),d(S===L?"testUnchanged":"testRedacted",{chars:b("chars",S.length)})].join(`
|
|
22
|
+
`);a.mode==="tui"?await a.ui.editor(d("testPreviewTitle"),`${U}
|
|
23
23
|
|
|
24
|
-
${S}
|
|
25
|
-
|
|
26
|
-
${
|
|
27
|
-
${
|
|
24
|
+
${S}`):a.ui.notify(`${U}
|
|
25
|
+
|
|
26
|
+
${S}`,"info")}catch(L){a.ui.notify(A(w(L,"TEST_INPUT").diagnostic),"error")}return}if(!["status","reload","logs"].includes(C)||C!=="logs"&&p.length>1||p.length>2||p[1]!==void 0&&p[1]!=="clear"&&!/^(?:[1-9]\d?|100)$/.test(p[1])){a.ui.notify(d("usage"),"info");return}if(C==="logs"){if(a.mode!=="tui"){a.ui.notify(d("logsTuiOnly"),"warning");return}if(p[1]==="clear"){try{if(!e.ready)throw i("NOT_READY");if(!await a.ui.confirm(d("clearTitle"),d("clearBody")))return;await a.waitForIdle();let T=await e.clearAuditRecords();c=e.ready,a.ui.notify(d("cleared",{bytes:b("bytes",T)}),"info")}catch(T){a.ui.notify(A(w(T,"AUDIT_IO").diagnostic),"error")}return}try{let{records:T,truncated:L}=e.auditRecords(Number(p[1]??20));if(!T.length){a.ui.notify(d("logsNone"),"info");return}let G=B=>JSON.stringify(B).replace(/[\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g,Q=>`\\u${Q.charCodeAt(0).toString(16).padStart(4,"0")}`),Z=T.map((B,Q)=>`${Q+1}. ${G(B.time)} | ${G(B.provider).slice(0,120)}`),S=await a.ui.select(d("logsSelectTitle")+(L?d("logsTruncated"):""),Z),U=S===void 0?-1:Z.indexOf(S);if(U<0||!await a.ui.confirm(d("logsRevealTitle"),d("logsRevealBody")))return;let V=G(T[U]);await a.ui.editor(d("logsPreviewTitle"),V.length>2e4?`${V.slice(0,2e4)}
|
|
27
|
+
${d("logsPreviewTruncated")}`:V)}catch(T){a.ui.notify(A(w(T,"AUDIT_IO").diagnostic),"error")}return}if(C==="reload"){await a.waitForIdle(),await a.reload();return}let E=e.lastDiagnosticText??u?.text,X=d("statusLine",{state:d(e.ready?"statusReady":"statusNotReady"),rules:b("rules",e.ruleCount),mappings:b("mappings",e.mappingCount)}),k=`
|
|
28
|
+
${d("statusCompaction",{mode:e.compactionMode,guard:d(y?"guardInstalled":"guardMissing")})}`,D=E?`
|
|
29
|
+
${d("statusLastBlock",{at:u?.at??""})}
|
|
28
30
|
${E}`:`
|
|
29
|
-
${
|
|
31
|
+
${d("statusNoBlock")}`;a.ui.notify(X+k+D,e.ready?"info":"error")}}),t.on("session_shutdown",()=>{y?.(),y=void 0,e.close()})}export{qt as default};
|