pi-information-protecter 0.14.2 → 0.15.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 CHANGED
@@ -1,5 +1,28 @@
1
1
  # Changelog / 更新日志
2
2
 
3
+ ## 0.15.0 — Attachment paths and explicit rule conflicts / 附件路径与明确的规则冲突
4
+
5
+ ### Added / 新增
6
+
7
+ - Show the attachment's local file path in the consent menu when it is known. Pi's image content carries no path, so images read by a tool (for example `read`) are mapped back to the path in that tool call; directly pasted or attached images are reported as having no path.
8
+ 在附件确认菜单中展示已知的本地文件路径。Pi 的图片内容不含路径,因此由工具(如 `read`)读取的图片会按该工具调用中的路径反查;直接粘贴或附加的图片会如实提示无路径。
9
+ - Once an attachment from a known path is allowed, later attachments from the same path are allowed for the rest of the session without asking. Edited images do not approve their path, so the unedited original is never sent silently later.
10
+ 已知路径的附件一经允许,本会话内同一路径的后续附件直接放行,不再询问。编辑过的图片不会记住其路径,避免之后静默发送未编辑的原图。
11
+ - Blocks that name rules (such as `FIXED_OVERLAP`) now list the exact configuration entries for `rule` and `otherRule` in the local notification and `/protecter status`. These entries are never included in tool-call block reasons visible to the model.
12
+ 指明规则的拦截(如 `FIXED_OVERLAP`)现在会在本地通知和 `/protecter status` 中列出 `rule` 与 `otherRule` 对应的完整配置条目;这些条目绝不会出现在模型可见的工具调用拦截原因中。
13
+
14
+ ### Fixed / 修复
15
+
16
+ - Recognize inline images in Anthropic (`source.type: "base64"`) and OpenAI (`data:` URL in `image_url`) request formats, so they can be previewed and edited instead of only allowed or cancelled. Edited bytes are written back in the same provider format; remote image URLs remain opaque.
17
+ 识别 Anthropic(`source.type: "base64"`)和 OpenAI(`image_url` 中的 `data:` URL)请求格式的内嵌图片,使其可预览和编辑,而不再只能放行或取消。编辑后的数据按原提供商格式写回;远程图片 URL 仍按不透明附件处理。
18
+
19
+ ## 0.14.3 — Use Pi-provided UI packages / 使用 Pi 宿主提供的界面包
20
+
21
+ ### Fixed / 修复
22
+
23
+ - Declare `@earendil-works/pi-tui` as a host-provided peer dependency (`*`) instead of installing a duplicate runtime copy. This prevents extension-loader warnings and duplicate TUI modules.
24
+ 将 `@earendil-works/pi-tui` 声明为 Pi 宿主提供的 peer 依赖(`*`),不再安装重复的运行时副本,避免扩展加载器警告和重复 TUI 模块。
25
+
3
26
  ## 0.14.2 — Edit images before sending / 发送前编辑图片
4
27
 
5
28
  ### Added / 新增
package/README.md CHANGED
@@ -151,7 +151,7 @@ Never type a secret as a command argument — `test` is the one exception, becau
151
151
 
152
152
  ### Attachments
153
153
 
154
- The default `attachments: "ask"` prompts separately for each new attachment. For inline images, choose **Open image** to preview it in the TUI, or **Edit image in default app** to open a private temporary copy with the operating system's image app. Save edits over that same temporary file and return to the menu; only the saved image copy is substituted into the provider request, and the original attachment is not changed. Temporary files are removed after editing. Editing is available for inline PNG, JPEG, WebP and GIF images up to 25 MiB; other image types can still be previewed and allowed. Approval applies only to that image's exact content; a different image requires its own confirmation. The same confirmed image content is remembered for the current session so it is not repeatedly prompted from conversation history. Attachments are never inspected or redacted, while other text in the request still goes through normal redaction. Choose `"allow"` to always pass attachments through, or `"deny"` to always cancel them.
154
+ The default `attachments: "ask"` prompts separately for each new attachment. For inline images, choose **Open image** to preview it in the TUI, or **Edit image in default app** to open a private temporary copy with the operating system's image app. Save edits over that same temporary file and return to the menu; only the saved image copy is substituted into the provider request, and the original attachment is not changed. Temporary files are removed after editing. Editing is available for inline PNG, JPEG, WebP and GIF images up to 25 MiB; other image types can still be previewed and allowed. Inline images in Pi, Gemini, Anthropic (base64 source) and OpenAI (data URL) request formats can be previewed; remote image URLs and non-image files can only be allowed or cancelled. The prompt shows the attachment's local file path when one is known — for images read by a tool such as `read`, the path from that tool call; images pasted or attached directly carry no path in Pi, so the prompt says so. Approval applies only to that image's exact content; a different image requires its own confirmation, except that once a known path is allowed, later attachments from the same path are allowed for the rest of the session without asking. Edited images never approve their path, so the unedited original is not sent silently later. The same confirmed image content is remembered for the current session so it is not repeatedly prompted from conversation history. Attachments are never inspected or redacted, while other text in the request still goes through normal redaction. Choose `"allow"` to always pass attachments through, or `"deny"` to always cancel them.
155
155
 
156
156
  ```json
157
157
  { "version": 1, "attachments": "ask", "sensitiveWords": [] }
@@ -437,7 +437,7 @@ pi update npm:pi-information-protecter
437
437
 
438
438
  ### 附件
439
439
 
440
- 默认 `attachments: "ask"`:每个新附件都会单独询问。对于内嵌图片,可选“打开图片”在 TUI 中预览,或选“用系统默认软件编辑图片”打开私有临时副本。将修改覆盖保存到同一临时文件后返回菜单;只有保存后的图片副本会替换提供商请求中的附件,原附件不会被修改,编辑结束后临时文件会删除。内嵌 PNG、JPEG、WebP、GIF 图片(不超过 25 MiB)可编辑,其他图片格式仍可预览并选择放行。确认仅适用于该图片的具体内容;不同图片必须分别确认。相同图片内容在本会话中会记住已确认状态,避免随历史记录重复询问。附件本身不会被检查或脱敏,但请求中的其他文本仍会正常脱敏。设为 `"allow"` 可始终放行附件,设为 `"deny"` 则始终取消。
440
+ 默认 `attachments: "ask"`:每个新附件都会单独询问。对于内嵌图片,可选“打开图片”在 TUI 中预览,或选“用系统默认软件编辑图片”打开私有临时副本。将修改覆盖保存到同一临时文件后返回菜单;只有保存后的图片副本会替换提供商请求中的附件,原附件不会被修改,编辑结束后临时文件会删除。内嵌 PNG、JPEG、WebP、GIF 图片(不超过 25 MiB)可编辑,其他图片格式仍可预览并选择放行。Pi、Gemini、Anthropic(base64 source)和 OpenAI(data URL)请求格式中的内嵌图片均可预览;远程图片 URL 与非图片文件只能放行或取消。若已知附件的本地路径,确认菜单会展示该路径——对于由 `read` 等工具读取的图片,取自该工具调用的路径;直接粘贴或附加的图片在 Pi 中不携带路径,菜单会如实说明。确认仅适用于该图片的具体内容;不同图片必须分别确认,但已知路径一经允许,本会话内来自同一路径的后续附件将直接放行,不再询问。编辑过的图片不会记住其路径,避免之后静默发送未编辑的原图。相同图片内容在本会话中会记住已确认状态,避免随历史记录重复询问。附件本身不会被检查或脱敏,但请求中的其他文本仍会正常脱敏。设为 `"allow"` 可始终放行附件,设为 `"deny"` 则始终取消。
441
441
 
442
442
  ```json
443
443
  { "version": 1, "attachments": "ask", "sensitiveWords": [] }
package/dist/index.mjs CHANGED
@@ -1,31 +1,38 @@
1
1
  /*! SPI Protecter | MIT | see LICENSE / SPI 隐私保护插件 | MIT 许可 */
2
- import{getAgentDir as hn,VERSION as It}from"@earendil-works/pi-coding-agent";import{Worker as Kt}from"node:worker_threads";import{fileURLToPath as Xt}from"node:url";import*as A from"node:fs";import{join as j,resolve as Gt}from"node:path";import{createHash as Ut,randomUUID as Bt}from"node:crypto";import{Worker as Ht}from"node:worker_threads";import{fileURLToPath as zt}from"node:url";var L="https://github.com/taills/pi-information-protecter/issues/new",ke="0.84.0-0.84.x, 0.85.1-0.87.x, 0.99.x, 1.2.0-1.4.x",Tt=["on","registerCommand","registerMarkdownTransformer"],Ot=["abort"],Nt=["notify","setStatus"];function ae(t,e){return!t||typeof t!="object"&&typeof t!="function"?!1:typeof t[e]=="function"}function ce(t,e){let o=[];for(let r of Tt)ae(t,r)||o.push(`pi.${r}()`);if(e===void 0)return o;let n=e;for(let r of Ot)ae(n,r)||o.push(`ctx.${r}()`);for(let r of Nt)ae(n.ui,r)||o.push(`ctx.ui.${r}()`);return(!n.modelRegistry||typeof n.modelRegistry!="object")&&o.push("ctx.modelRegistry"),o}function De(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 le={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 ${L}`],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 "+L],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"]},Et={INTERNAL:["未预期的本地错误","重载并检查安装包完整性"],NOT_READY:["防护尚未初始化","查看初始化错误,修复后重载"],PI_CAPABILITY:["当前 Pi 构建缺少本扩展所需的能力",`请升级 Pi;若最新版 Pi 仍然失败,请将所列能力反馈至 ${L}`],GUARD_UNAVAILABLE:["无法覆盖没有扩展钩子的模型调用","该 Pi 构建未暴露可包装的模型运行时:请升级 Pi,或将该构建反馈至 "+L],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:["离线测试输入超出大小上限","改用更小的文件或更短的片段"]},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",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 its summary request internally, outside this extension's normal redaction hook. If sent as-is, the conversation—including protected values—could be sent in plaintext.
2
+ import{getAgentDir as kn,VERSION as Pt}from"@earendil-works/pi-coding-agent";import{Worker as ln}from"node:worker_threads";import{fileURLToPath as dn}from"node:url";import*as w from"node:fs";import{join as q,resolve as Vt}from"node:path";import{createHash as Zt,randomUUID as Qt}from"node:crypto";import{Worker as en}from"node:worker_threads";import{fileURLToPath as tn}from"node:url";var F="https://github.com/taills/pi-information-protecter/issues/new",xe="0.84.0-0.84.x, 0.85.1-0.87.x, 0.99.x, 1.2.0-1.4.x",Mt=["on","registerCommand","registerMarkdownTransformer"],Ft=["abort"],xt=["notify","setStatus"];function me(t,e){return!t||typeof t!="object"&&typeof t!="function"?!1:typeof t[e]=="function"}function pe(t,e){let o=[];for(let r of Mt)me(t,r)||o.push(`pi.${r}()`);if(e===void 0)return o;let n=e;for(let r of Ft)me(n,r)||o.push(`ctx.${r}()`);for(let r of xt)me(n.ui,r)||o.push(`ctx.ui.${r}()`);return(!n.modelRegistry||typeof n.modelRegistry!="object")&&o.push("ctx.modelRegistry"),o}function ve(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 ge={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 ${F}`],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 "+F],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"]},vt={INTERNAL:["未预期的本地错误","重载并检查安装包完整性"],NOT_READY:["防护尚未初始化","查看初始化错误,修复后重载"],PI_CAPABILITY:["当前 Pi 构建缺少本扩展所需的能力",`请升级 Pi;若最新版 Pi 仍然失败,请将所列能力反馈至 ${F}`],GUARD_UNAVAILABLE:["无法覆盖没有扩展钩子的模型调用","该 Pi 构建未暴露可包装的模型运行时:请升级 Pi,或将该构建反馈至 "+F],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:["离线测试输入超出大小上限","改用更小的文件或更短的片段"]},Ge={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 its summary request internally, outside this extension's normal redaction hook. If sent as-is, the conversation—including protected values—could be sent in plaintext.
3
3
 
4
4
  If you allow compaction, this extension will redact the content first. Pi will then summarize the redacted content with the current model; no additional model is needed. The summary will retain the replacement values, so the model may not describe protected information accurately.
5
5
 
6
- Allowing compaction does not bypass redaction. It allows this compaction to proceed.`,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:"Review attachment {index} of {total}",attachmentAskBody:"This attachment cannot be inspected or redacted by SPI Protecter. Review it before deciding whether to send it.",attachmentOpenImage:"Open image",attachmentEditImage:"Edit image in default app",attachmentEditWait:"The app receives a private temporary copy. Save your edits over that same file, then return here; only the saved image will be sent.",attachmentEditDone:"Done editing",attachmentAllow:"Allow this attachment",attachmentDeny:"Cancel request",attachmentAllowed:"SPI Protecter: reviewed attachment allowed; its contents are not redacted.",attachmentPreviewTitle:"Attachment preview",attachmentPreviewHint:"Press Esc or Enter to return to the attachment decision."},Ct={compactAskTitle:"是否压缩当前会话?",compactAskBody:`Pi 会在内部构造摘要请求,该请求不会经过本扩展的常规脱敏钩子。若直接发送,原始会话内容(包括受保护的值)可能会以明文发出。
6
+ Allowing compaction does not bypass redaction. It allows this compaction to proceed.`,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:"Review attachment {index} of {total}",attachmentAskBody:"This attachment cannot be inspected or redacted by SPI Protecter. Review it before deciding whether to send it.",attachmentPathLabel:"Local file path",diagnosticRuleEntries:"Matched configuration entries:",attachmentPathUnavailable:"Not provided by Pi; locate the original in the conversation or file picker",attachmentOpenImage:"Open image",attachmentEditImage:"Edit image in default app",attachmentEditWait:"The app receives a private temporary copy. Save your edits over that same file, then return here; only the saved image will be sent.",attachmentEditDone:"Done editing",attachmentAllow:"Allow this attachment",attachmentDeny:"Cancel request",attachmentAllowed:"SPI Protecter: reviewed attachment allowed; its contents are not redacted.",attachmentPreviewTitle:"Attachment preview",attachmentPreviewHint:"Press Esc or Enter to return to the attachment decision."},Gt={compactAskTitle:"是否压缩当前会话?",compactAskBody:`Pi 会在内部构造摘要请求,该请求不会经过本扩展的常规脱敏钩子。若直接发送,原始会话内容(包括受保护的值)可能会以明文发出。
7
7
 
8
8
  选择允许后,本扩展会先对待压缩内容脱敏,再由 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 开启新会话。",attachmentAskTitle:"查看附件({index}/{total})",attachmentAskBody:"SPI Protecter 无法检查或脱敏此附件。请先查看,再决定是否发送。",attachmentOpenImage:"打开图片",attachmentEditImage:"用系统默认软件编辑图片",attachmentEditWait:"打开的软件收到的是私有临时副本。请将修改覆盖保存到同一文件,再返回此处;最终只会发送保存后的图片。",attachmentEditDone:"编辑完成",attachmentAllow:"允许发送此附件",attachmentDeny:"取消本次请求",attachmentAllowed:"SPI Protecter:已确认放行此附件;附件内容未经脱敏。",attachmentPreviewTitle:"附件预览",attachmentPreviewHint:"按 Esc 或 Enter 返回附件确认菜单。",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 de(t=process.env){let e=t.PI_PROTECTER_LANG||t.LC_ALL||t.LC_MESSAGES||t.LANG||t.LANGUAGE||St();return/^zh\b|^zh[-_]/i.test(e.trim())?"zh":"en"}function St(){try{return new Intl.DateTimeFormat().resolvedOptions().locale}catch{return""}}var v=de();function Me(){return v}function Fe(t){v=t}function u(t,e={}){return((v==="zh"?Ct:Le)[t]??Le[t]).replace(/\{(\w+)\}/g,(n,r)=>Object.hasOwn(e,r)?String(e[r]):n)}var _t={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} 个字符"}}},be=new Map;function H(t,e){let o=v==="zh"?"zh-CN":"en",n=be.get(v);if(!n){try{n=new Intl.PluralRules(o)}catch{n=void 0}n&&be.set(v,n)}let r=n?.select(e)??"other",s=_t[v][t],a=s[r]??s.other,d=new Intl.NumberFormat(o).format(e);return a.replace("{n}",d)}function xe(t){let o=(v==="zh"?Et[t]:le[t])??le[t]??le.INTERNAL;return{reason:o[0],action:o[1]}}var ve={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 Ge=["rule","otherRule","node","bytes","limit","timeoutMs","status"],Rt=/^[A-Za-z][A-Za-z0-9]{0,39}$/,Pt=/^(EACCES|EPERM|ENOENT|ENOSPC|EDQUOT|EROFS|ELOOP|EISDIR|ENOTDIR|EMFILE|ENFILE|EIO|EEXIST|EBADF|EBUSY|ENOTEMPTY)$/;function kt(t,e={}){let{reason:o,action:n}=xe(t),r={};for(let s of Ge){let a=e[s];typeof a=="number"&&Number.isSafeInteger(a)&&a>=0&&(r[s]=a)}return typeof e.errno=="string"&&Pt.test(e.errno)&&(r.errno=e.errno),typeof e.errorName=="string"&&Rt.test(e.errorName)&&(r.errorName=e.errorName),{code:t,stage:ve[t],reason:o,action:n,...r}}function z(t){let e=Me()==="zh"?":":": ",o=[...Ge,"errno","errorName"].filter(n=>t[n]!==void 0).map(n=>`${n}=${t[n]}`).join(" ");return[u("blockedHeader"),`code=${t.code} stage=${t.stage}${o?` ${o}`:""}`,`${u("reasonLabel")}${e}${t.reason}`,`${u("actionLabel")}${e}${t.action}`,`${u("detailsLabel")}${e}/protecter status`].join(`
11
- `)}var G=class extends Error{diagnostic;constructor(e,o={}){let n=kt(e,o);super(z(n)),this.name="ProtectionError",this.diagnostic=n}};function i(t,e={}){return new G(t,e)}function w(t,e,o={}){if(t instanceof G)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 q(t,e){if(!t||typeof t!="object")return i(e);let o=t,n=typeof o.code=="string"&&Object.hasOwn(ve,o.code)?o.code:e;return i(n,o)}import{constants as $,closeSync as Ue,fchmodSync as Dt,fstatSync as Lt,mkdirSync as bt,openSync as Be,readFileSync as Mt,writeFileSync as Ft}from"node:fs";import{dirname as xt}from"node:path";var He=["ask","protected","off"],ue=["provider","model","contextWindow","reserveTokens"];function $e(t){return!t||typeof t!="object"?[]:ue.filter(e=>Object.hasOwn(t,e))}var fe={version:1,sensitiveWords:[]},ze="ask";function vt(t){if(typeof t=="string"){if(!He.includes(t))throw i("CONFIG_COMPACTION");return}if(!t||typeof t!="object"||Array.isArray(t))throw i("CONFIG_COMPACTION");let e=t,o=["mode",...ue];if(Object.keys(e).some(n=>!o.includes(n)))throw i("CONFIG_COMPACTION");if(e.mode!==void 0&&!He.includes(e.mode))throw i("CONFIG_COMPACTION");for(let n of ue){let r=e[n];if(r!==void 0&&typeof r!="string"&&typeof r!="number")throw i("CONFIG_COMPACTION")}}function K(t){return t===void 0?{mode:ze}:typeof t=="string"?{mode:t}:{mode:t.mode??ze}}function me(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")&&vt(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 a=JSON.stringify(["literal",r]);if(n.has(a)&&n.get(a)!==void 0)throw i("CONFIG_CONFLICT",{rule:o});n.set(a,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(a=>!["type","value","replacement"].includes(a))||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(a=>!["type","pattern","flags","replacement"].includes(a))||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 G?n:i("CONFIG_SCHEMA",{rule:o})}}function je(t,e=!1){let o;try{if(e){bt(xt(t),{recursive:!0,mode:448});try{let s=Be(t,$.O_WRONLY|$.O_CREAT|$.O_EXCL,384);try{Ft(s,JSON.stringify(fe,null,2)+`
12
- `)}finally{Ue(s)}}catch(s){if(s.code!=="EEXIST")throw w(s,"CONFIG_IO")}}o=Be(t,$.O_RDONLY|$.O_NOFOLLOW|$.O_NONBLOCK);let n=Lt(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"&&Dt(o,384);let r=Mt(o,"utf8");if(Buffer.byteLength(r)>1024*1024)throw i("CONFIG_SIZE",{bytes:Buffer.byteLength(r),limit:1024*1024});return{config:me(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&&Ue(o)}}var ge=/^protecter(?:\.[a-f0-9]{32})?\.json$/;function $t(t){return new Promise((e,o)=>{let n=new Ht(zt(new URL("./validate-worker.mjs",import.meta.url)),{workerData:t,execArgv:[],resourceLimits:{maxOldGenerationSizeMb:64}}),r=!1,s=(d,l=i("WORKER_FAILED"))=>{r||(r=!0,clearTimeout(a),n.terminate(),d?e():o(l))},a=setTimeout(()=>s(!1,i("CONFIG_TIMEOUT",{timeoutMs:2e3})),2e3);n.once("message",d=>d===!0?s(!0):s(!1,q(d,"CONFIG_SCHEMA"))),n.once("error",()=>s(!1)),n.once("exit",()=>s(!1))})}function jt(t){let e=new Set,o=[];for(let f of t)for(let g of f.sensitiveWords){let h=typeof g=="string"?JSON.stringify(["literal",g,null]):g.type==="literal"?JSON.stringify(["literal",g.value,g.replacement??null]):JSON.stringify(["regex",g.pattern,[...new Set((g.flags??"")+"g")].sort().join(""),g.replacement??null]);e.has(h)||(e.add(h),o.push(g))}let n=[];for(let f of t)f.compaction!==void 0&&n.push(K(f.compaction));let s=["off","ask","protected"].find(f=>n.some(g=>g.mode===f)),a={version:1,sensitiveWords:o};s!==void 0&&(a.compaction={mode:s});let d=t.map(f=>f.attachments).filter(f=>f!==void 0);d.length&&(a.attachments=["deny","ask","allow"].find(f=>d.includes(f)));let l=JSON.stringify(a);if(Buffer.byteLength(l)>1024*1024)throw i("CONFIG_SIZE",{bytes:Buffer.byteLength(l),limit:1024*1024});return me(l)}function Ye(t){let e;try{e=A.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 pe(t,e){let o=j(t,e),n=Ye(o),r=je(o);if(Ye(o)!==n)throw i("MIGRATION_CHANGED");return{name:e,...r,identity:n,digest:Ut("sha256").update(r.raw).digest("hex")}}function W(t,e){let o=pe(t,e.name);if(o.identity!==e.identity||o.digest!==e.digest)throw i("MIGRATION_CHANGED")}function X(t){return A.readdirSync(t).filter(e=>ge.test(e)).sort()}function We(t){if(process.platform==="win32")return;let e=A.openSync(t,A.constants.O_RDONLY);try{A.fsyncSync(e)}finally{A.closeSync(e)}}async function Je(t,e,o={}){if(!/^[a-f0-9]{32}$/.test(e))throw i("MACHINE_ID");let n=Gt(t),r=`protecter.${e}.json`,s=j(n,r);A.mkdirSync(n,{recursive:!0,mode:448});let a=j(n,".protecter-migration.lock"),d=Date.now()+(o.lockTimeoutMs??5e3);for(;;)try{A.mkdirSync(a,{mode:448});break}catch(f){if(f.code!=="EEXIST")throw w(f,"MIGRATION_IO");if(Date.now()>=d)throw i("MIGRATION_LOCKED",{timeoutMs:o.lockTimeoutMs??5e3});await new Promise(g=>setTimeout(g,50))}let l;try{let f=X(n);if(f.length>64)throw i("MIGRATION_LIMIT",{limit:64});let h=[...f].sort((m,T)=>m===r?-1:T===r?1:m.localeCompare(T)).map(m=>pe(n,m)),I=jt(h.length?h.map(m=>m.config):[fe]);if(await $t([I]),h.length===1&&h[0].name===r){if(W(n,h[0]),JSON.stringify(X(n))!==JSON.stringify(f))throw i("MIGRATION_CHANGED");return{path:s,config:h[0].config,raw:h[0].raw,sourceRaws:[h[0].raw],migrated:0}}let N=JSON.stringify(I,null,2)+`
13
- `;if(Buffer.byteLength(N)>1024*1024)throw i("CONFIG_SIZE",{bytes:Buffer.byteLength(N),limit:1024*1024});l=j(n,`.protecter-migration.${Bt()}.tmp`);let E=A.openSync(l,A.constants.O_WRONLY|A.constants.O_CREAT|A.constants.O_EXCL,384);try{A.writeFileSync(E,N),A.fsyncSync(E)}finally{A.closeSync(E)}if(o.checkpoint?.("beforeCommit",s),JSON.stringify(X(n))!==JSON.stringify(f))throw i("MIGRATION_CHANGED");for(let m of h)W(n,m);A.renameSync(l,s),l=void 0,We(n);let p=pe(n,r);if(p.raw!==N)throw i("MIGRATION_CHANGED");o.checkpoint?.("afterCommit",s);for(let m of h)m.name!==r&&(o.checkpoint?.("beforeDelete",j(n,m.name)),W(n,p),W(n,m),A.unlinkSync(j(n,m.name)));We(n);let c=[r];if(JSON.stringify(X(n))!==JSON.stringify(c))throw i("MIGRATION_CHANGED");return W(n,p),{path:s,config:I,raw:N,sourceRaws:[...new Set([...h.map(m=>m.raw),N])],migrated:h.filter(m=>m.name!==r).length}}catch(f){throw f instanceof G?f:w(f,"MIGRATION_IO")}finally{if(l)try{A.unlinkSync(l)}catch{}A.rmdirSync(a)}}import{createHash as Yt}from"node:crypto";import{readFileSync as Wt}from"node:fs";import{execFileSync as qe}from"node:child_process";function he(t){let e=t.trim().toLowerCase().replace(/-/g,"");if(!/^[a-f0-9]{32}$/.test(e)||/^0+$/.test(e))throw i("MACHINE_ID");return Yt("sha256").update(`pi-information-protecter:v1:${e}`).digest("hex").slice(0,32)}function Ke(){try{if(process.platform==="linux")return he(Wt("/etc/machine-id","utf8"));if(process.platform==="darwin"){let t=qe("/usr/sbin/ioreg",["-rd1","-c","IOPlatformExpertDevice"],{encoding:"utf8",timeout:5e3,maxBuffer:1048576,stdio:["ignore","pipe","pipe"]});return he(t.match(/"IOPlatformUUID"\s*=\s*"([a-fA-F0-9-]+)"/)?.[1]??"")}if(process.platform==="win32"){let t=qe("reg.exe",["query","HKLM\\SOFTWARE\\Microsoft\\Cryptography","/v","MachineGuid","/reg:64"],{encoding:"utf8",timeout:5e3,maxBuffer:65536,stdio:["ignore","pipe","pipe"]});return he(t.match(/MachineGuid\s+REG_SZ\s+([a-fA-F0-9-]+)/i)?.[1]??"")}}catch{}throw i("MACHINE_ID")}import*as y from"node:fs";import{randomUUID as Jt}from"node:crypto";var Xe=32*1024*1024,Ze=8*1024*1024;function qt(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 ye(t,e,o=e){let n=y.openSync(t,(e?y.constants.O_RDWR|(o?y.constants.O_CREAT:0):y.constants.O_RDONLY)|y.constants.O_NOFOLLOW|y.constants.O_NONBLOCK,384);try{let r=y.fstatSync(n);if(!r.isFile()||r.nlink!==1||process.getuid&&r.uid!==process.getuid())throw i("AUDIT_UNSAFE");return process.platform!=="win32"&&y.fchmodSync(n,384),n}catch(r){throw y.closeSync(n),w(r,"AUDIT_UNSAFE")}}function Z(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 Ve(t){let e=`${t}.lock`,o=Date.now()+2e3;for(;;)try{return y.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 Qe(t){let e=await Ve(t),o;try{try{o=ye(t,!0,!1)}catch(r){if(r.code==="ENOENT")return 0;throw r}let n=y.fstatSync(o).size;return y.ftruncateSync(o,0),y.fsyncSync(o),n}catch(n){throw Z(n)}finally{try{o!==void 0&&y.closeSync(o)}finally{y.rmdirSync(e)}}}async function et(t,e,o){if(!o.length)return;let n=new Date,r=Jt(),s=Buffer.from(o.map(([l,f])=>JSON.stringify({version:1,time:qt(n),timezoneOffset:-n.getTimezoneOffset(),requestId:r,provider:e||"unknown",original:f,replacement:l})).join(`
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:"查看附件({index}/{total})",attachmentAskBody:"SPI Protecter 无法检查或脱敏此附件。请先查看,再决定是否发送。",attachmentPathLabel:"本地文件路径",diagnosticRuleEntries:"涉及的配置条目内容:",attachmentPathUnavailable:"Pi 未提供本地路径;请在会话记录或文件选择器中定位原文件",attachmentOpenImage:"打开图片",attachmentEditImage:"用系统默认软件编辑图片",attachmentEditWait:"打开的软件收到的是私有临时副本。请将修改覆盖保存到同一文件,再返回此处;最终只会发送保存后的图片。",attachmentEditDone:"编辑完成",attachmentAllow:"允许发送此附件",attachmentDeny:"取消本次请求",attachmentAllowed:"SPI Protecter:已确认放行此附件;附件内容未经脱敏。",attachmentPreviewTitle:"附件预览",attachmentPreviewHint:"按 Esc 或 Enter 返回附件确认菜单。",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 he(t=process.env){let e=t.PI_PROTECTER_LANG||t.LC_ALL||t.LC_MESSAGES||t.LANG||t.LANGUAGE||Ut();return/^zh\b|^zh[-_]/i.test(e.trim())?"zh":"en"}function Ut(){try{return new Intl.DateTimeFormat().resolvedOptions().locale}catch{return""}}var B=he();function Be(){return B}function ze(t){B=t}function l(t,e={}){return((B==="zh"?Gt:Ge)[t]??Ge[t]).replace(/\{(\w+)\}/g,(n,r)=>Object.hasOwn(e,r)?String(e[r]):n)}var Bt={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 W(t,e){let o=B==="zh"?"zh-CN":"en",n=Ue.get(B);if(!n){try{n=new Intl.PluralRules(o)}catch{n=void 0}n&&Ue.set(B,n)}let r=n?.select(e)??"other",i=Bt[B][t],c=i[r]??i.other,d=new Intl.NumberFormat(o).format(e);return c.replace("{n}",d)}function He(t){let o=(B==="zh"?vt[t]:ge[t])??ge[t]??ge.INTERNAL;return{reason:o[0],action:o[1]}}var $e={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 je=["rule","otherRule","node","bytes","limit","timeoutMs","status"],zt=/^[A-Za-z][A-Za-z0-9]{0,39}$/,Ht=/^(EACCES|EPERM|ENOENT|ENOSPC|EDQUOT|EROFS|ELOOP|EISDIR|ENOTDIR|EMFILE|ENFILE|EIO|EEXIST|EBADF|EBUSY|ENOTEMPTY)$/;function $t(t,e={}){let{reason:o,action:n}=He(t),r={};for(let i of je){let c=e[i];typeof c=="number"&&Number.isSafeInteger(c)&&c>=0&&(r[i]=c)}return typeof e.errno=="string"&&Ht.test(e.errno)&&(r.errno=e.errno),typeof e.errorName=="string"&&zt.test(e.errorName)&&(r.errorName=e.errorName),{code:t,stage:$e[t],reason:o,action:n,...r}}function $(t){let e=Be()==="zh"?":":": ",o=[...je,"errno","errorName"].filter(n=>t[n]!==void 0).map(n=>`${n}=${t[n]}`).join(" ");return[l("blockedHeader"),`code=${t.code} stage=${t.stage}${o?` ${o}`:""}`,`${l("reasonLabel")}${e}${t.reason}`,`${l("actionLabel")}${e}${t.action}`,`${l("detailsLabel")}${e}/protecter status`].join(`
11
+ `)}var z=class extends Error{diagnostic;constructor(e,o={}){let n=$t(e,o);super($(n)),this.name="ProtectionError",this.diagnostic=n}};function s(t,e={}){return new z(t,e)}function O(t,e,o={}){if(t instanceof z)return s(t.diagnostic.code,{...t.diagnostic,...o});let n=t&&typeof t=="object"&&"code"in t?t.code:void 0;return s(e,{...o,errno:typeof n=="string"?n:void 0})}function te(t,e){if(!t||typeof t!="object")return s(e);let o=t,n=typeof o.code=="string"&&Object.hasOwn($e,o.code)?o.code:e;return s(n,o)}import{constants as J,closeSync as Ye,fchmodSync as jt,fstatSync as Yt,mkdirSync as Wt,openSync as We,readFileSync as Jt,writeFileSync as qt}from"node:fs";import{dirname as Kt}from"node:path";var Je=["ask","protected","off"],ye=["provider","model","contextWindow","reserveTokens"];function Ke(t){return!t||typeof t!="object"?[]:ye.filter(e=>Object.hasOwn(t,e))}var Ie={version:1,sensitiveWords:[]},qe="ask";function Xt(t){if(typeof t=="string"){if(!Je.includes(t))throw s("CONFIG_COMPACTION");return}if(!t||typeof t!="object"||Array.isArray(t))throw s("CONFIG_COMPACTION");let e=t,o=["mode",...ye];if(Object.keys(e).some(n=>!o.includes(n)))throw s("CONFIG_COMPACTION");if(e.mode!==void 0&&!Je.includes(e.mode))throw s("CONFIG_COMPACTION");for(let n of ye){let r=e[n];if(r!==void 0&&typeof r!="string"&&typeof r!="number")throw s("CONFIG_COMPACTION")}}function ne(t){return t===void 0?{mode:qe}:typeof t=="string"?{mode:t}:{mode:t.mode??qe}}function we(t){let e;try{e=JSON.parse(t)}catch{throw s("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 s("CONFIG_SCHEMA");if(Object.hasOwn(e,"compaction")&&Xt(e.compaction),Object.hasOwn(e,"attachments")&&!["ask","allow","deny"].includes(e.attachments??""))throw s("CONFIG_ATTACHMENT");if(e.sensitiveWords.length>1e3)throw s("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 s("CONFIG_SCHEMA",{rule:o,limit:8192});let c=JSON.stringify(["literal",r]);if(n.has(c)&&n.get(c)!==void 0)throw s("CONFIG_CONFLICT",{rule:o});n.set(c,void 0);continue}if(!r||typeof r!="object")throw s("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 s("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 s("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 s("CONFIG_REGEX",{rule:o,limit:8192});try{new RegExp(r.pattern,r.flags??"")}catch{throw s("CONFIG_REGEX",{rule:o})}}else throw s("CONFIG_SCHEMA",{rule:o});let i=r.type==="literal"?JSON.stringify(["literal",r.value]):JSON.stringify(["regex",r.pattern,[...new Set((r.flags??"")+"g")].sort().join("")]);if(n.has(i)&&n.get(i)!==r.replacement)throw s("CONFIG_CONFLICT",{rule:o});n.set(i,r.replacement)}return e}catch(n){throw n instanceof z?n:s("CONFIG_SCHEMA",{rule:o})}}function Xe(t,e=!1){let o;try{if(e){Wt(Kt(t),{recursive:!0,mode:448});try{let i=We(t,J.O_WRONLY|J.O_CREAT|J.O_EXCL,384);try{qt(i,JSON.stringify(Ie,null,2)+`
12
+ `)}finally{Ye(i)}}catch(i){if(i.code!=="EEXIST")throw O(i,"CONFIG_IO")}}o=We(t,J.O_RDONLY|J.O_NOFOLLOW|J.O_NONBLOCK);let n=Yt(o);if(n.size>1024*1024)throw s("CONFIG_SIZE",{bytes:n.size,limit:1024*1024});if(!n.isFile()||n.nlink!==1||process.getuid&&n.uid!==process.getuid())throw s("CONFIG_UNSAFE");process.platform!=="win32"&&jt(o,384);let r=Jt(o,"utf8");if(Buffer.byteLength(r)>1024*1024)throw s("CONFIG_SIZE",{bytes:Buffer.byteLength(r),limit:1024*1024});return{config:we(r),raw:r}}catch(n){let r=n&&typeof n=="object"&&"code"in n?n.code:void 0;throw O(n,r==="ELOOP"||r==="EISDIR"||r==="ENOTDIR"?"CONFIG_UNSAFE":"CONFIG_IO")}finally{o!==void 0&&Ye(o)}}var Te=/^protecter(?:\.[a-f0-9]{32})?\.json$/;function nn(t){return new Promise((e,o)=>{let n=new en(tn(new URL("./validate-worker.mjs",import.meta.url)),{workerData:t,execArgv:[],resourceLimits:{maxOldGenerationSizeMb:64}}),r=!1,i=(d,u=s("WORKER_FAILED"))=>{r||(r=!0,clearTimeout(c),n.terminate(),d?e():o(u))},c=setTimeout(()=>i(!1,s("CONFIG_TIMEOUT",{timeoutMs:2e3})),2e3);n.once("message",d=>d===!0?i(!0):i(!1,te(d,"CONFIG_SCHEMA"))),n.once("error",()=>i(!1)),n.once("exit",()=>i(!1))})}function on(t){let e=new Set,o=[];for(let f of t)for(let h of f.sensitiveWords){let g=typeof h=="string"?JSON.stringify(["literal",h,null]):h.type==="literal"?JSON.stringify(["literal",h.value,h.replacement??null]):JSON.stringify(["regex",h.pattern,[...new Set((h.flags??"")+"g")].sort().join(""),h.replacement??null]);e.has(g)||(e.add(g),o.push(h))}let n=[];for(let f of t)f.compaction!==void 0&&n.push(ne(f.compaction));let i=["off","ask","protected"].find(f=>n.some(h=>h.mode===f)),c={version:1,sensitiveWords:o};i!==void 0&&(c.compaction={mode:i});let d=t.map(f=>f.attachments).filter(f=>f!==void 0);d.length&&(c.attachments=["deny","ask","allow"].find(f=>d.includes(f)));let u=JSON.stringify(c);if(Buffer.byteLength(u)>1024*1024)throw s("CONFIG_SIZE",{bytes:Buffer.byteLength(u),limit:1024*1024});return we(u)}function Ve(t){let e;try{e=w.lstatSync(t,{bigint:!0})}catch(o){throw O(o,"CONFIG_IO")}if(!e.isFile()||e.nlink!==1n||process.getuid&&e.uid!==BigInt(process.getuid()))throw s("CONFIG_UNSAFE");return`${e.dev}:${e.ino}:${e.size}:${e.mtimeNs}`}function Ae(t,e){let o=q(t,e),n=Ve(o),r=Xe(o);if(Ve(o)!==n)throw s("MIGRATION_CHANGED");return{name:e,...r,identity:n,digest:Zt("sha256").update(r.raw).digest("hex")}}function Z(t,e){let o=Ae(t,e.name);if(o.identity!==e.identity||o.digest!==e.digest)throw s("MIGRATION_CHANGED")}function oe(t){return w.readdirSync(t).filter(e=>Te.test(e)).sort()}function Ze(t){if(process.platform==="win32")return;let e=w.openSync(t,w.constants.O_RDONLY);try{w.fsyncSync(e)}finally{w.closeSync(e)}}async function Qe(t,e,o={}){if(!/^[a-f0-9]{32}$/.test(e))throw s("MACHINE_ID");let n=Vt(t),r=`protecter.${e}.json`,i=q(n,r);w.mkdirSync(n,{recursive:!0,mode:448});let c=q(n,".protecter-migration.lock"),d=Date.now()+(o.lockTimeoutMs??5e3);for(;;)try{w.mkdirSync(c,{mode:448});break}catch(f){if(f.code!=="EEXIST")throw O(f,"MIGRATION_IO");if(Date.now()>=d)throw s("MIGRATION_LOCKED",{timeoutMs:o.lockTimeoutMs??5e3});await new Promise(h=>setTimeout(h,50))}let u;try{let f=oe(n);if(f.length>64)throw s("MIGRATION_LIMIT",{limit:64});let g=[...f].sort((E,K)=>E===r?-1:K===r?1:E.localeCompare(K)).map(E=>Ae(n,E)),I=on(g.length?g.map(E=>E.config):[Ie]);if(await nn([I]),g.length===1&&g[0].name===r){if(Z(n,g[0]),JSON.stringify(oe(n))!==JSON.stringify(f))throw s("MIGRATION_CHANGED");return{path:i,config:g[0].config,raw:g[0].raw,sourceRaws:[g[0].raw],migrated:0}}let N=JSON.stringify(I,null,2)+`
13
+ `;if(Buffer.byteLength(N)>1024*1024)throw s("CONFIG_SIZE",{bytes:Buffer.byteLength(N),limit:1024*1024});u=q(n,`.protecter-migration.${Qt()}.tmp`);let _=w.openSync(u,w.constants.O_WRONLY|w.constants.O_CREAT|w.constants.O_EXCL,384);try{w.writeFileSync(_,N),w.fsyncSync(_)}finally{w.closeSync(_)}if(o.checkpoint?.("beforeCommit",i),JSON.stringify(oe(n))!==JSON.stringify(f))throw s("MIGRATION_CHANGED");for(let E of g)Z(n,E);w.renameSync(u,i),u=void 0,Ze(n);let x=Ae(n,r);if(x.raw!==N)throw s("MIGRATION_CHANGED");o.checkpoint?.("afterCommit",i);for(let E of g)E.name!==r&&(o.checkpoint?.("beforeDelete",q(n,E.name)),Z(n,x),Z(n,E),w.unlinkSync(q(n,E.name)));Ze(n);let D=[r];if(JSON.stringify(oe(n))!==JSON.stringify(D))throw s("MIGRATION_CHANGED");return Z(n,x),{path:i,config:I,raw:N,sourceRaws:[...new Set([...g.map(E=>E.raw),N])],migrated:g.filter(E=>E.name!==r).length}}catch(f){throw f instanceof z?f:O(f,"MIGRATION_IO")}finally{if(u)try{w.unlinkSync(u)}catch{}w.rmdirSync(c)}}import{createHash as rn}from"node:crypto";import{readFileSync as sn}from"node:fs";import{execFileSync as et}from"node:child_process";function Oe(t){let e=t.trim().toLowerCase().replace(/-/g,"");if(!/^[a-f0-9]{32}$/.test(e)||/^0+$/.test(e))throw s("MACHINE_ID");return rn("sha256").update(`pi-information-protecter:v1:${e}`).digest("hex").slice(0,32)}function tt(){try{if(process.platform==="linux")return Oe(sn("/etc/machine-id","utf8"));if(process.platform==="darwin"){let t=et("/usr/sbin/ioreg",["-rd1","-c","IOPlatformExpertDevice"],{encoding:"utf8",timeout:5e3,maxBuffer:1048576,stdio:["ignore","pipe","pipe"]});return Oe(t.match(/"IOPlatformUUID"\s*=\s*"([a-fA-F0-9-]+)"/)?.[1]??"")}if(process.platform==="win32"){let t=et("reg.exe",["query","HKLM\\SOFTWARE\\Microsoft\\Cryptography","/v","MachineGuid","/reg:64"],{encoding:"utf8",timeout:5e3,maxBuffer:65536,stdio:["ignore","pipe","pipe"]});return Oe(t.match(/MachineGuid\s+REG_SZ\s+([a-fA-F0-9-]+)/i)?.[1]??"")}}catch{}throw s("MACHINE_ID")}import*as y from"node:fs";import{randomUUID as an}from"node:crypto";var nt=32*1024*1024,ot=8*1024*1024;function cn(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 Ne(t,e,o=e){let n=y.openSync(t,(e?y.constants.O_RDWR|(o?y.constants.O_CREAT:0):y.constants.O_RDONLY)|y.constants.O_NOFOLLOW|y.constants.O_NONBLOCK,384);try{let r=y.fstatSync(n);if(!r.isFile()||r.nlink!==1||process.getuid&&r.uid!==process.getuid())throw s("AUDIT_UNSAFE");return process.platform!=="win32"&&y.fchmodSync(n,384),n}catch(r){throw y.closeSync(n),O(r,"AUDIT_UNSAFE")}}function re(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 rt(t){let e=`${t}.lock`,o=Date.now()+2e3;for(;;)try{return y.mkdirSync(e,{mode:448}),e}catch(n){if(n.code!=="EEXIST")throw O(n,"AUDIT_IO");if(Date.now()>=o)throw s("AUDIT_LOCKED",{timeoutMs:2e3});await new Promise(r=>setTimeout(r,25))}}async function it(t){let e=await rt(t),o;try{try{o=Ne(t,!0,!1)}catch(r){if(r.code==="ENOENT")return 0;throw r}let n=y.fstatSync(o).size;return y.ftruncateSync(o,0),y.fsyncSync(o),n}catch(n){throw re(n)}finally{try{o!==void 0&&y.closeSync(o)}finally{y.rmdirSync(e)}}}async function st(t,e,o){if(!o.length)return;let n=new Date,r=an(),i=Buffer.from(o.map(([u,f])=>JSON.stringify({version:1,time:cn(n),timezoneOffset:-n.getTimezoneOffset(),requestId:r,provider:e||"unknown",original:f,replacement:u})).join(`
14
14
  `)+`
15
- `);if(s.length>Ze)throw i("AUDIT_BATCH_LIMIT",{bytes:s.length,limit:Ze});let a=await Ve(t),d;try{d=ye(t,!0);let l=y.fstatSync(d).size;if(l+s.length>Xe)throw i("AUDIT_FULL",{bytes:l+s.length,limit:Xe});if(l){let f=Buffer.alloc(1);if(y.readSync(d,f,0,1,l-1),f[0]!==10)throw i("AUDIT_PARTIAL")}try{let f=0;for(;f<s.length;){let g=y.writeSync(d,s,f,s.length-f,l+f);if(!g)throw i("AUDIT_IO");f+=g}y.fsyncSync(d)}catch(f){throw y.ftruncateSync(d,l),y.fsyncSync(d),Z(f)}}catch(l){throw Z(l)}finally{d!==void 0&&y.closeSync(d),y.rmdirSync(a)}}function tt(t,e=20){if(!Number.isInteger(e)||e<1||e>100)throw i("INTERNAL",{limit:100});let o;try{try{o=ye(t,!1)}catch(I){if(I.code==="ENOENT")return{records:[],truncated:!1};throw I}let n=y.fstatSync(o).size,r=Math.max(0,n-1024*1024),s=Buffer.alloc(n-r),a=y.readSync(o,s,0,s.length,r),d=s.subarray(0,a).toString("utf8");if(r){let I=d.indexOf(`
16
- `);d=I<0?"":d.slice(I+1)}let l=d.split(`
17
- `),f=l.pop()!=="",g=[],h=!1;for(let I of l.slice(-e))try{let N=JSON.parse(I);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;g.push(N)}catch{h=!0}return{records:g,truncated:r>0||l.length>e||f||h}}catch(n){throw Z(n)}finally{o!==void 0&&y.closeSync(o)}}var V=class{constructor(e,o=2e3,n=Ke){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?z(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 Je(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 tt(this.auditPath,e)}clearAuditRecords(){let e=this.queue.then(()=>{if(!this.ready)throw this.notReady();return Qe(this.auditPath)});return this.queue=e.catch(()=>{}),e}get ruleCount(){return this.snapshot?.config.sensitiveWords.length??0}get compaction(){return K(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 a;try{a=JSON.parse(s)}catch{throw i("PAYLOAD_JSON")}let d=await new Promise((l,f)=>{let g=!1,h;try{h=new Kt(Xt(new URL("./scan-worker.mjs",import.meta.url)),{workerData:{payload:a,rules:n.sensitiveWords,entries:[...this.tokens],configRaws:r},execArgv:[],resourceLimits:{maxOldGenerationSizeMb:128}})}catch(E){f(w(E,"WORKER_FAILED"));return}this.workers.add(h);let I=(E,p=i("WORKER_FAILED"))=>{if(!g){if(g=!0,clearTimeout(N),this.workers.delete(h),h.terminate(),!E||this.closed){f(this.closed?i("NOT_READY"):p);return}l(E)}},N=setTimeout(()=>I(void 0,i("SCAN_TIMEOUT",{timeoutMs:this.timeoutMs})),this.timeoutMs);h.once("message",E=>{E?.failed?I(void 0,q(E.diagnostic,"SCAN_INTERNAL")):E&&Array.isArray(E.additions)&&Array.isArray(E.hits)?I(E):I()}),h.once("error",()=>I()),h.once("exit",()=>I())});if(this.closed)throw i("NOT_READY");if(await et(this.auditPath,o,d.hits),this.closed)throw i("NOT_READY");for(let[l,f]of d.additions)this.tokens.set(l,f);return d.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 a=this.restoreText(r);if(Object.hasOwn(n,a))throw i("RESTORE_KEY_COLLISION");n[a]=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 Zt,statSync as nt,readdirSync as Vt}from"node:fs";import{homedir as Qt}from"node:os";import{basename as Ie,dirname as J,isAbsolute as en,relative as ot,resolve as Q}from"node:path";import{fileURLToPath as tn}from"node:url";function nn(t,e){let o=t.replace(/^@/,"");return o.startsWith("file://")&&(o=tn(o)),(o==="~"||o.startsWith("~/"))&&(o=Qt()+o.slice(1)),Q(e,o)}function Ae(t){try{return Zt(t)}catch{let e=J(t);return e===t?t:Q(Ae(e),ot(e,t))}}function rn(t,e){let o=ot(t,e);return o===""||!o.startsWith("..")&&!en(o)}function rt(t,e){try{let o=nt(t),n=nt(e);return o.dev===n.dev&&o.ino===n.ino}catch{return!1}}function it(t,e,o,n){if(!n)return!0;let r=Ae(Q(n));if(["bash","powershell"].includes(t)){let d=typeof e.command=="string"?e.command:"";if(/protecter(?:\.[a-f0-9]{32})?\.jsonl?|\.protecter-migration/i.test(d)||d.includes(n))return!0}let s=e.path??e.file_path??e.filePath,a=["grep","find","ls"].includes(t);if(typeof s!="string"&&!a)return!1;try{let d=nn(typeof s=="string"?s:".",o),l=Ae(d),f=/^protecter\.[a-f0-9]{32}\.jsonl(?:\.lock)?$/,g=Vt(J(r)).filter(h=>f.test(h)).some(h=>rt(d,Q(J(r),h)));return J(l)===J(r)&&(ge.test(Ie(l))||f.test(Ie(l))||Ie(l).startsWith(".protecter-migration"))||l===r||rt(d,n)||g||a&&rn(l,r)}catch{return!0}}function we(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 st(t){if(typeof t!="string")throw i("COMPACT_FAILED");return t}async function at(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=Te(r.messages),a=Te(r.prefix),d=n.previousSummary===void 0?void 0:st(r.previous);we(n.messagesToSummarize,s),we(n.turnPrefixMessages,a),d!==void 0&&(n.previousSummary=d)}async function ct(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=Te(r.entries),a=n.customInstructions===void 0?void 0:st(r.instructions);return we(n.entriesToSummarize,s),a===void 0?{}:{customInstructions:a}}var lt=["stream","streamSimple"],on=["classify","generateImages"],dt=lt,Oe=Symbol.for("pi-information-protecter.runtime-guard");function sn(t){let e=t?.runtime;if(!e||typeof e!="object")throw i("GUARD_UNAVAILABLE");let o=e;for(let n of dt)if(typeof o[n]!="function")throw i("GUARD_UNAVAILABLE");return o}function an(t){return!t||typeof t!="object"?!1:t.onPayload!==void 0}function cn(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 a=>{let d=n.runs(),l=await s(a);return n.runs()>d?l:(n.onBypass?.(),o(t,l===void 0?a:l))}}}function ut(t,e,o){let n=sn(t);n[Oe]?.();let r=[...dt,...on.filter(a=>typeof n[a]=="function")].map(a=>[a,n[a]]);for(let[a,d]of r){let l=lt.includes(a),f=function(g,h,I){return l&&an(I)?d.call(this,g,h,cn(g,I,e,o)):(async()=>d.call(this,g,await e(g,h),I))()};n[a]=f}let s=()=>{for(let[a,d]of r)n[a]=d;delete n[Oe]};return Object.defineProperty(n,Oe,{value:s,configurable:!0,enumerable:!1,writable:!0}),s}function ee(t,e=0){if(e>80||!t||typeof t!="object")return!1;if(Array.isArray(t))return t.some(n=>ee(n,e+1));let o=t;return re(o)||Object.keys(o).some(oe)?!0:Object.values(o).some(n=>ee(n,e+1))}var te=t=>{if(!t||typeof t!="object")return!1;let e=t;return typeof e.data=="string"&&(e.type==="image"||typeof e.mimeType=="string"&&e.mimeType.startsWith("image/"))},re=t=>typeof t.type=="string"&&/image|audio|video|document|(^|_)file($|_)/i.test(t.type);function Ne(t,e=0){if(e>80||!t||typeof t!="object")return[];if(te(t))return[t];let o=t;if(!Array.isArray(t)&&re(o))return[void 0];let n=[],r=Array.isArray(t)?Array.from(t.entries()):Object.entries(o);for(let[s,a]of r)typeof s=="string"&&oe(s)?te(a)?n.push(a):n.push(void 0):n.push(...Ne(a,e+1));return n}function ft(t,e){let o=0,n=(r,s)=>{if(s>80||!r||typeof r!="object")return r;if(te(r)){let l=e[o++];return l?{...r,data:l.data,mimeType:l.mimeType??r.mimeType}:r}let a=r;if(!Array.isArray(r)&&re(a))return r;if(Array.isArray(r))return r.map(l=>n(l,s+1));let d=Object.create(null);for(let[l,f]of Object.entries(a))d[l]=oe(l)&&!te(f)?f:n(f,s+1);return d};return n(t,0)}var oe=t=>/^(inlineData|inline_data|fileData|file_data|image_url|input_audio)$/.test(t);async function ne(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=>ne(n,e,o+1)));if(t&&typeof t=="object"){let n=t;if(re(n))return t;let r=Object.create(null);for(let[s,a]of Object.entries(n))oe(s)||s==="type"&&typeof a=="string"?r[s]=a:r[s]=await ne(a,e,o+1);return r}return t}import{constants as mt}from"node:fs";import{spawn as ln}from"node:child_process";import{lstat as dn,mkdtemp as un,open as fn,rm as mn,writeFile as pn}from"node:fs/promises";import{tmpdir as gn}from"node:os";import{join as pt}from"node:path";var Ee={"image/png":{extension:".png",mimeType:"image/png"},"image/jpeg":{extension:".jpg",mimeType:"image/jpeg"},"image/webp":{extension:".webp",mimeType:"image/webp"},"image/gif":{extension:".gif",mimeType:"image/gif"}},ie=25*1024*1024;function gt(t){let e=t.mimeType??"image/png";return!Ee[e]||t.data.length>Math.ceil(ie*4/3)+4?!1:Ce(Buffer.from(t.data,"base64"))===e}async function ht(t){let e="";if(process.platform==="darwin"?e="open":process.platform==="win32"?e="explorer.exe":process.platform==="linux"&&(e="xdg-open"),!e)throw i("SCAN_ATTACHMENT");let o=[t];await new Promise((n,r)=>{let s=ln(e,o,{detached:!0,stdio:"ignore"});s.once("error",r),s.once("spawn",()=>{s.unref(),n()})})}function Ce(t){if(t.length>=8&&t.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])))return"image/png";if(t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255)return"image/jpeg";if(t.length>=6&&(t.toString("ascii",0,6)==="GIF87a"||t.toString("ascii",0,6)==="GIF89a"))return"image/gif";if(t.length>=12&&t.toString("ascii",0,4)==="RIFF"&&t.toString("ascii",8,12)==="WEBP")return"image/webp"}async function yt(t,e){let o=t.mimeType??"image/png",n=Ee[o];if(!n)throw i("SCAN_ATTACHMENT");let r=Buffer.from(t.data,"base64"),s=r.toString("base64").replace(/=+$/,"");if(!r.length||r.length>ie||s!==t.data.replace(/=+$/,"")||Ce(r)!==o)throw i("SCAN_ATTACHMENT");let a=await un(pt(gn(),"pi-protecter-image-")),d=pt(a,`attachment${n.extension}`);try{await pn(d,r,{mode:384,flag:"wx"}),await e(d);let l=await dn(d);if(!l.isFile()||l.isSymbolicLink()||l.nlink!==1||l.size<=0||l.size>ie)throw i("SCAN_ATTACHMENT");let f=await fn(d,mt.O_RDONLY|(mt.O_NOFOLLOW??0)),g;try{let I=await f.stat();if(!I.isFile()||I.nlink!==1||I.size<=0||I.size>ie)throw i("SCAN_ATTACHMENT");g=await f.readFile()}finally{await f.close()}let h=Ce(g);if(!h||!Ee[h]||g.equals(r))throw i("SCAN_ATTACHMENT");return{data:g.toString("base64"),mimeType:h}}finally{await mn(a,{recursive:!0,force:!0})}}import{Image as yn}from"@earendil-works/pi-tui";import{lstat as In,readFile as An}from"node:fs/promises";import{createHash as wn}from"node:crypto";import{resolve as Tn}from"node:path";var At=256*1024;async function On(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=Tn(e(o.slice(1).trim())),r;try{r=await In(n)}catch(s){throw w(s,"TEST_INPUT")}if(!r.isFile())throw i("TEST_INPUT");if(r.size>At)throw i("TEST_SIZE",{bytes:r.size,limit:At});try{return{text:await An(n,"utf8"),fromFile:!0}}catch(s){throw w(s,"TEST_INPUT")}}function Nn(t){Fe(de());let e=new V(hn()),o=ce(t),n=()=>o.length===0,r=0,s=!1,a=new Set,d=!1,l,f,g,h=p=>{let c=p?.provider;return typeof c=="string"?c:"unknown"},I=p=>{let c=z(p);return l={at:new Date().toISOString(),text:c},c},N=async(p,c,m)=>{await p.ui.custom((T,C,R,Y)=>{let P=new yn(c,m,{fallbackColor:S=>C.fg("dim",S)},{maxWidthCells:72,maxHeightCells:24});return{render(S){return[...P.render(S),"",C.fg("dim",u("attachmentPreviewHint"))]},handleInput(S){(S==="\x1B"||S==="\r"||S.toLowerCase()==="q")&&Y(void 0)},invalidate(){P.invalidate()}}},{overlay:!0})};t.on("session_start",async(p,c)=>{try{if(o=ce(t,c),!n())throw c.ui.notify(u("capabilityBlocked",{names:o.join(", "),url:L}),"error"),i("PI_CAPABILITY");await e.initialize(),a.clear(),g=ut(c.modelRegistry,(C,R)=>e.redact(R,h(C)),{runs:()=>r,onBypass:()=>{if(!s){s=!0;try{c.ui.notify(u("hookBypassed",{url:L}),"warning")}catch{}}}}),d=!0,De(It)||c.ui.notify(u("piNewer",{version:It,verified:ke,url:L}),"warning");let m=e.ruleCount;c.ui.setStatus("protecter",u("statusBarRules",{rules:H("rules",m)})),m===0&&c.ui.notify(u("emptyRules"),"warning");let T=$e(e.rawCompaction);T.length&&c.ui.notify(u("compactIgnoredKeys",{keys:T.join(", ")}),"warning")}catch(m){d=!1,c.ui.setStatus("protecter",u("statusBarNotReady")),c.ui.notify(I(w(m,"CONFIG_IO").diagnostic),"error")}}),t.on("before_provider_request",async(p,c)=>{r++;try{if(!n())throw i("PI_CAPABILITY");let m=e.attachmentMode;if(ee(p.payload)){if(m==="deny")throw i("SCAN_ATTACHMENT");let C=p.payload;if(m==="ask"){let P=Ne(p.payload),S=[],_=new Set(a),k=new Map,U=0;for(let b=0;b<P.length;b++){let O=P[b],M=O?U++:-1,D=O?wn("sha256").update(O.mimeType??"image/png").update("\0").update(O.data).digest("hex"):void 0,F=0;D&&(F=(k.get(D)??0)+1,k.set(D,F));let x=D?`${D}:${F}`:void 0;if(x&&_.has(x)){S[M]=void 0;continue}let Se=O!==void 0&&gt(O),B;O?(B=[u("attachmentOpenImage")],Se&&B.push(u("attachmentEditImage")),B.push(u("attachmentAllow"),u("attachmentDeny"))):B=[u("attachmentAllow"),u("attachmentDeny")];let _e=!1,Re=!1;for(;!_e;){let se=await c.ui.select(`${u("attachmentAskTitle",{index:b+1,total:P.length})}
18
-
19
- ${u("attachmentAskBody")}`,B);if(O&&se===B[0]){await N(c,O.data,O.mimeType??"image/png");continue}if(O&&Se&&se===u("attachmentEditImage")){let Pe=await yt(O,async wt=>{if(await ht(wt),await c.ui.select(u("attachmentEditWait"),[u("attachmentEditDone"),u("attachmentDeny")])!==u("attachmentEditDone"))throw i("SCAN_ATTACHMENT")});O={type:"image",...Pe},S[M]=Pe,Re=!0,await N(c,O.data,O.mimeType??"image/png");continue}if(se===u("attachmentAllow"))_e=!0,x&&!Re&&a.add(x);else throw i("SCAN_ATTACHMENT")}}C=ft(p.payload,S)}c.ui.notify(u("attachmentAllowed"),"warning");let R=c.model?.provider??"unknown",Y=await ne(C,async P=>{let S=await e.redact(P,R);return typeof S=="string"?S:P});return d=!0,Y}let T=await e.redact(p.payload,c.model?.provider??"unknown");return d=!0,T}catch(m){d=!1;let T=I(w(m,"INTERNAL").diagnostic);try{c.abort()}catch{}try{c.ui.notify(T,"error")}catch{}return{}}}),t.on("message_end",p=>{if(p.message.role!=="assistant")return;let c=p.message;return{message:{...c,content:c.content.map(m=>m.type==="text"?{...m,text:e.restoreText(m.text)}:m.type==="thinking"?{...m,thinking:e.restoreText(m.thinking)}:m.type==="toolCall"?{...m,arguments:e.restore(m.arguments)}:m),...c.errorMessage?{errorMessage:e.restoreText(c.errorMessage)}:{}}}}),t.registerMarkdownTransformer((p,c)=>c.messageType==="user"?p:e.restoreText(p)),t.on("tool_call",(p,c)=>{if(!d)return{block:!0,reason:e.lastDiagnosticText??l?.text??z(i("NOT_READY").diagnostic)};let m=e.restore(p.input);for(let T of Object.keys(p.input))delete p.input[T];if(Object.assign(p.input,m),it(p.toolName,p.input,c.cwd,e.configPath))return{block:!0,reason:u("toolBlocked")}});let E=async(p,c)=>{if(!n())throw i("PI_CAPABILITY");if(!e.ready)throw e.lastDiagnostic?i(e.lastDiagnostic.code,e.lastDiagnostic):i("NOT_READY");let m=e.compactionMode;if(m==="off")throw i("COMPACT_DENIED");if(f==="deny")throw i("COMPACT_DENIED");if(m!=="ask"||f==="allow")return;let T=[u("compactAllowOnce"),u("compactAllowAlways"),u("compactDenyOnce"),u("compactDenyAlways")],C=await p.ui.select(`${u("compactAskTitle")}
20
-
21
- ${u("compactAskBody")}`,T,{signal:c}),R=C===void 0?-1:T.indexOf(C);if(R===1?(f="allow",p.ui.notify(u("compactAlwaysNotice"),"info")):R===3&&(f="deny",p.ui.notify(u("compactDenyNotice"),"warning")),R!==0&&R!==1)throw i("COMPACT_DENIED")};t.on("session_before_compact",async(p,c)=>{try{await E(c,p.signal),await at(p,e,c.model?.provider??"unknown"),c.ui.notify(u("compactRedacted"),"info");return}catch(m){return c.ui.notify(I(w(m,"COMPACT_FAILED").diagnostic),"warning"),{cancel:!0}}}),t.on("session_before_tree",async(p,c)=>{if(p.preparation.userWantsSummary)try{await E(c,p.signal);let m=await ct(p,e,c.model?.provider??"unknown");return c.ui.notify(u("compactRedacted"),"info"),m}catch(m){return c.ui.notify(I(w(m,"COMPACT_FAILED").diagnostic),"warning"),{cancel:!0}}}),t.registerCommand("protecter",{description:u("commandDescription"),handler:async(p,c)=>{let m=p.trim(),T=m.split(/\s+/).filter(Boolean),C=T[0]??"logs";if(C==="test"){let _=m.slice(C.length).trim();if(!_){c.ui.notify(u("usage"),"info");return}try{if(!e.ready)throw i("NOT_READY");let{text:k,fromFile:U}=await On(_),O=(await e.redact({text:k},"test")).text;if(typeof O!="string")throw i("INTERNAL");let M=[u(U?"testFileLabel":"testTextLabel"),u(O===k?"testUnchanged":"testRedacted",{chars:H("chars",O.length)})].join(`
22
- `);c.mode==="tui"?await c.ui.editor(u("testPreviewTitle"),`${M}
23
-
24
- ${O}`):c.ui.notify(`${M}
25
-
26
- ${O}`,"info")}catch(k){c.ui.notify(I(w(k,"TEST_INPUT").diagnostic),"error")}return}if(!["status","reload","logs"].includes(C)||C!=="logs"&&T.length>1||T.length>2||T[1]!==void 0&&T[1]!=="clear"&&!/^(?:[1-9]\d?|100)$/.test(T[1])){c.ui.notify(u("usage"),"info");return}if(C==="logs"){if(c.mode!=="tui"){c.ui.notify(u("logsTuiOnly"),"warning");return}if(T[1]==="clear"){try{if(!e.ready)throw i("NOT_READY");if(!await c.ui.confirm(u("clearTitle"),u("clearBody")))return;await c.waitForIdle();let _=await e.clearAuditRecords();d=e.ready,c.ui.notify(u("cleared",{bytes:H("bytes",_)}),"info")}catch(_){c.ui.notify(I(w(_,"AUDIT_IO").diagnostic),"error")}return}try{let{records:_,truncated:k}=e.auditRecords(Number(T[1]??20));if(!_.length){c.ui.notify(u("logsNone"),"info");return}let U=F=>JSON.stringify(F).replace(/[\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g,x=>`\\u${x.charCodeAt(0).toString(16).padStart(4,"0")}`),b=_.map((F,x)=>`${x+1}. ${U(F.time)} | ${U(F.provider).slice(0,120)}`),O=await c.ui.select(u("logsSelectTitle")+(k?u("logsTruncated"):""),b),M=O===void 0?-1:b.indexOf(O);if(M<0||!await c.ui.confirm(u("logsRevealTitle"),u("logsRevealBody")))return;let D=U(_[M]);await c.ui.editor(u("logsPreviewTitle"),D.length>2e4?`${D.slice(0,2e4)}
27
- ${u("logsPreviewTruncated")}`:D)}catch(_){c.ui.notify(I(w(_,"AUDIT_IO").diagnostic),"error")}return}if(C==="reload"){await c.waitForIdle(),await c.reload();return}let R=e.lastDiagnosticText??l?.text,Y=u("statusLine",{state:u(e.ready?"statusReady":"statusNotReady"),rules:H("rules",e.ruleCount),mappings:H("mappings",e.mappingCount)}),P=`
28
- ${u("statusCompaction",{mode:e.compactionMode,guard:u(g?"guardInstalled":"guardMissing")})}`,S=R?`
29
- ${u("statusLastBlock",{at:l?.at??""})}
30
- ${R}`:`
31
- ${u("statusNoBlock")}`;c.ui.notify(Y+P+S,e.ready?"info":"error")}}),t.on("session_shutdown",()=>{g?.(),g=void 0,e.close()})}export{Nn as default};
15
+ `);if(i.length>ot)throw s("AUDIT_BATCH_LIMIT",{bytes:i.length,limit:ot});let c=await rt(t),d;try{d=Ne(t,!0);let u=y.fstatSync(d).size;if(u+i.length>nt)throw s("AUDIT_FULL",{bytes:u+i.length,limit:nt});if(u){let f=Buffer.alloc(1);if(y.readSync(d,f,0,1,u-1),f[0]!==10)throw s("AUDIT_PARTIAL")}try{let f=0;for(;f<i.length;){let h=y.writeSync(d,i,f,i.length-f,u+f);if(!h)throw s("AUDIT_IO");f+=h}y.fsyncSync(d)}catch(f){throw y.ftruncateSync(d,u),y.fsyncSync(d),re(f)}}catch(u){throw re(u)}finally{d!==void 0&&y.closeSync(d),y.rmdirSync(c)}}function at(t,e=20){if(!Number.isInteger(e)||e<1||e>100)throw s("INTERNAL",{limit:100});let o;try{try{o=Ne(t,!1)}catch(I){if(I.code==="ENOENT")return{records:[],truncated:!1};throw I}let n=y.fstatSync(o).size,r=Math.max(0,n-1024*1024),i=Buffer.alloc(n-r),c=y.readSync(o,i,0,i.length,r),d=i.subarray(0,c).toString("utf8");if(r){let I=d.indexOf(`
16
+ `);d=I<0?"":d.slice(I+1)}let u=d.split(`
17
+ `),f=u.pop()!=="",h=[],g=!1;for(let I of u.slice(-e))try{let N=JSON.parse(I);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;h.push(N)}catch{g=!0}return{records:h,truncated:r>0||u.length>e||f||g}}catch(n){throw re(n)}finally{o!==void 0&&y.closeSync(o)}}var ie=class{constructor(e,o=2e3,n=tt){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?$(this.lastError):void 0}async initialize(){try{if(this.closed)throw s("NOT_READY");this.snapshot=void 0;let e;try{e=this.machineId()}catch{throw s("MACHINE_ID")}let o=await Qe(this.configDir,e);if(this.closed)throw s("NOT_READY");this.snapshot=o,this.attachmentOptions.mode=o.config.attachments??"ask",this.lastError=void 0}catch(e){this.attachmentOptions.mode="deny";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 at(this.auditPath,e)}clearAuditRecords(){let e=this.queue.then(()=>{if(!this.ready)throw this.notReady();return it(this.auditPath)});return this.queue=e.catch(()=>{}),e}get ruleCount(){return this.snapshot?.config.sensitiveWords.length??0}ruleAt(e){if(!(!Number.isSafeInteger(e)||e<1))return this.snapshot?.config.sensitiveWords[e-1]}get compaction(){return ne(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 i=O(r,"INTERNAL");throw this.lastError=i.diagnostic,i});return this.queue=n.catch(()=>{}),n}notReady(){return this.lastError?s(this.lastError.code,this.lastError):s("NOT_READY")}async scan(e,o){if(!this.ready)throw this.notReady();let{config:n,sourceRaws:r}=this.snapshot,i;try{i=JSON.stringify(e)}catch{throw s("PAYLOAD_JSON")}if(!i)throw s("PAYLOAD_JSON");if(Buffer.byteLength(i)>8*1024*1024)throw s("PAYLOAD_SIZE",{bytes:Buffer.byteLength(i),limit:8*1024*1024});let c;try{c=JSON.parse(i)}catch{throw s("PAYLOAD_JSON")}let d=await new Promise((u,f)=>{let h=!1,g;try{g=new ln(dn(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(O(_,"WORKER_FAILED"));return}this.workers.add(g);let I=(_,x=s("WORKER_FAILED"))=>{if(!h){if(h=!0,clearTimeout(N),this.workers.delete(g),g.terminate(),!_||this.closed){f(this.closed?s("NOT_READY"):x);return}u(_)}},N=setTimeout(()=>I(void 0,s("SCAN_TIMEOUT",{timeoutMs:this.timeoutMs})),this.timeoutMs);g.once("message",_=>{_?.failed?I(void 0,te(_.diagnostic,"SCAN_INTERNAL")):_&&Array.isArray(_.additions)&&Array.isArray(_.hits)?I(_):I()}),g.once("error",()=>I()),g.once("exit",()=>I())});if(this.closed)throw s("NOT_READY");if(await st(this.auditPath,o,d.hits),this.closed)throw s("NOT_READY");for(let[u,f]of d.additions)this.tokens.set(u,f);return d.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 s("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,i]of Object.entries(e)){let c=this.restoreText(r);if(Object.hasOwn(n,c))throw s("RESTORE_KEY_COLLISION");n[c]=this.restore(i,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 un,statSync as ct,readdirSync as fn}from"node:fs";import{homedir as mn}from"node:os";import{basename as Ee,dirname as Q,isAbsolute as pn,relative as dt,resolve as se}from"node:path";import{fileURLToPath as gn}from"node:url";function hn(t,e){let o=t.replace(/^@/,"");return o.startsWith("file://")&&(o=gn(o)),(o==="~"||o.startsWith("~/"))&&(o=mn()+o.slice(1)),se(e,o)}function Ce(t){try{return un(t)}catch{let e=Q(t);return e===t?t:se(Ce(e),dt(e,t))}}function yn(t,e){let o=dt(t,e);return o===""||!o.startsWith("..")&&!pn(o)}function lt(t,e){try{let o=ct(t),n=ct(e);return o.dev===n.dev&&o.ino===n.ino}catch{return!1}}function ut(t,e,o,n){if(!n)return!0;let r=Ce(se(n));if(["bash","powershell"].includes(t)){let d=typeof e.command=="string"?e.command:"";if(/protecter(?:\.[a-f0-9]{32})?\.jsonl?|\.protecter-migration/i.test(d)||d.includes(n))return!0}let i=e.path??e.file_path??e.filePath,c=["grep","find","ls"].includes(t);if(typeof i!="string"&&!c)return!1;try{let d=hn(typeof i=="string"?i:".",o),u=Ce(d),f=/^protecter\.[a-f0-9]{32}\.jsonl(?:\.lock)?$/,h=fn(Q(r)).filter(g=>f.test(g)).some(g=>lt(d,se(Q(r),g)));return Q(u)===Q(r)&&(Te.test(Ee(u))||f.test(Ee(u))||Ee(u).startsWith(".protecter-migration"))||u===r||lt(d,n)||h||c&&yn(u,r)}catch{return!0}}function _e(t,e){t.length=0;for(let o of e)t.push(o)}function Se(t){if(!Array.isArray(t))throw s("COMPACT_FAILED");return t}function ft(t){if(typeof t!="string")throw s("COMPACT_FAILED");return t}async function mt(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 s("COMPACT_FAILED");if(typeof t.customInstructions=="string"&&r.instructions!==t.customInstructions)throw s("COMPACT_INSTRUCTIONS");let i=Se(r.messages),c=Se(r.prefix),d=n.previousSummary===void 0?void 0:ft(r.previous);_e(n.messagesToSummarize,i),_e(n.turnPrefixMessages,c),d!==void 0&&(n.previousSummary=d)}async function pt(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 s("COMPACT_FAILED");let i=Se(r.entries),c=n.customInstructions===void 0?void 0:ft(r.instructions);return _e(n.entriesToSummarize,i),c===void 0?{}:{customInstructions:c}}var gt=["stream","streamSimple"],In=["classify","generateImages"],ht=gt,Re=Symbol.for("pi-information-protecter.runtime-guard");function wn(t){let e=t?.runtime;if(!e||typeof e!="object")throw s("GUARD_UNAVAILABLE");let o=e;for(let n of ht)if(typeof o[n]!="function")throw s("GUARD_UNAVAILABLE");return o}function An(t){return!t||typeof t!="object"?!1:t.onPayload!==void 0}function Tn(t,e,o,n){if(!e||typeof e!="object")return;let r=e.onPayload;if(!n||typeof r!="function")return e;let i=r;return{...e,onPayload:async c=>{let d=n.runs(),u=await i(c);return n.runs()>d?u:(n.onBypass?.(),o(t,u===void 0?c:u))}}}function yt(t,e,o){let n=wn(t);n[Re]?.();let r=[...ht,...In.filter(c=>typeof n[c]=="function")].map(c=>[c,n[c]]);for(let[c,d]of r){let u=gt.includes(c),f=function(h,g,I){return u&&An(I)?d.call(this,h,g,Tn(h,I,e,o)):(async()=>d.call(this,h,await e(h,g),I))()};n[c]=f}let i=()=>{for(let[c,d]of r)n[c]=d;delete n[Re]};return Object.defineProperty(n,Re,{value:i,configurable:!0,enumerable:!1,writable:!0}),i}function ce(t,e=0){if(e>80||!t||typeof t!="object")return!1;if(Array.isArray(t))return t.some(n=>ce(n,e+1));let o=t;return Pe(o)||Object.keys(o).some(ke)?!0:Object.values(o).some(n=>ce(n,e+1))}var On=/^data:(image\/[a-z0-9.+-]+);base64,([a-z0-9+/=\s]*)$/i;function It(t){if(typeof t!="string")return;let e=On.exec(t);return e?{type:"image",mimeType:e[1].toLowerCase(),data:e[2].replace(/\s+/g,"")}:void 0}var wt=(t,e)=>`data:${t.mimeType??e??"image/png"};base64,${t.data}`;function At(t){let e=typeof t.mimeType=="string"?t.mimeType:typeof t.mime_type=="string"?t.mime_type:void 0;if(typeof t.data=="string"&&(t.type==="image"||e?.startsWith("image/"))){let r=typeof t.mimeType=="string"||typeof t.mime_type!="string"?"mimeType":"mime_type";return{image:{type:"image",data:t.data,mimeType:e},write:i=>({...t,data:i.data,[r]:i.mimeType??e})}}let o=t.source;if(t.type==="image"&&o&&typeof o=="object"&&o.type==="base64"&&typeof o.data=="string"){let r=typeof o.media_type=="string"?o.media_type:void 0;return{image:{type:"image",data:o.data,mimeType:r},write:i=>({...t,source:{...o,data:i.data,media_type:i.mimeType??r}})}}let n=t.image_url;if(n&&typeof n=="object"){let r=It(n.url);if(r)return{image:r,write:i=>({...t,image_url:{...n,url:wt(i,r.mimeType)}})}}if(typeof t.image_url=="string"){let r=It(t.image_url);if(r)return{image:r,write:i=>({...t,image_url:wt(i,r.mimeType)})}}}var Pe=t=>typeof t.type=="string"&&/image|audio|video|document|(^|_)file($|_)/i.test(t.type);function ee(t,e,o=0){if(o>80||!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(c=>ee(c,e,o+1));let n=t,r=At(n);if(r)return e({image:r.image,path:ae(n)},r)??t;if(Pe(n))return e({path:ae(n)})??t;let i=Object.create(null);for(let[c,d]of Object.entries(n))if(ke(c)){let u=d&&typeof d=="object"&&!Array.isArray(d)?d:void 0,f=u?At(u):void 0;i[c]=e({image:f?.image,path:u?ae(u):void 0},f)??d}else i[c]=ee(d,e,o+1);return i}function Tt(t){let e=[];return ee(t,o=>{e.push(o.path)}),e}function ae(t){for(let e of["filePath","file_path","path"]){let o=t[e];if(typeof o=="string"&&o.trim())return o}for(let e of["source","file","metadata"]){let o=t[e];if(o&&typeof o=="object"){let n=ae(o);if(n)return n}}}function Ot(t){let e=[];return ee(t,o=>{e.push(o.image)}),e}function Nt(t,e){let o=0;return ee(t,(n,r)=>{if(!n.image||!r)return;let i=e[o++];return i?r.write(i):void 0})}var ke=t=>/^(inlineData|inline_data|fileData|file_data|image_url|input_audio)$/.test(t);async function le(t,e,o=0){if(o>80)throw s("SCAN_COMPLEXITY");if(typeof t=="string")return e(t);if(Array.isArray(t))return Promise.all(t.map(n=>le(n,e,o+1)));if(t&&typeof t=="object"){let n=t;if(Pe(n))return t;let r=Object.create(null);for(let[i,c]of Object.entries(n))ke(i)||i==="type"&&typeof c=="string"?r[i]=c:r[i]=await le(c,e,o+1);return r}return t}import{constants as Et}from"node:fs";import{spawn as Nn}from"node:child_process";import{lstat as En,mkdtemp as Cn,open as _n,rm as Sn,writeFile as Rn}from"node:fs/promises";import{tmpdir as Pn}from"node:os";import{join as Ct}from"node:path";var De={"image/png":{extension:".png",mimeType:"image/png"},"image/jpeg":{extension:".jpg",mimeType:"image/jpeg"},"image/webp":{extension:".webp",mimeType:"image/webp"},"image/gif":{extension:".gif",mimeType:"image/gif"}},de=25*1024*1024;function _t(t){let e=t.mimeType??"image/png";return!De[e]||t.data.length>Math.ceil(de*4/3)+4?!1:be(Buffer.from(t.data,"base64"))===e}async function St(t){let e="";if(process.platform==="darwin"?e="open":process.platform==="win32"?e="explorer.exe":process.platform==="linux"&&(e="xdg-open"),!e)throw s("SCAN_ATTACHMENT");let o=[t];await new Promise((n,r)=>{let i=Nn(e,o,{detached:!0,stdio:"ignore"});i.once("error",r),i.once("spawn",()=>{i.unref(),n()})})}function be(t){if(t.length>=8&&t.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])))return"image/png";if(t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255)return"image/jpeg";if(t.length>=6&&(t.toString("ascii",0,6)==="GIF87a"||t.toString("ascii",0,6)==="GIF89a"))return"image/gif";if(t.length>=12&&t.toString("ascii",0,4)==="RIFF"&&t.toString("ascii",8,12)==="WEBP")return"image/webp"}async function Rt(t,e){let o=t.mimeType??"image/png",n=De[o];if(!n)throw s("SCAN_ATTACHMENT");let r=Buffer.from(t.data,"base64"),i=r.toString("base64").replace(/=+$/,"");if(!r.length||r.length>de||i!==t.data.replace(/=+$/,"")||be(r)!==o)throw s("SCAN_ATTACHMENT");let c=await Cn(Ct(Pn(),"pi-protecter-image-")),d=Ct(c,`attachment${n.extension}`);try{await Rn(d,r,{mode:384,flag:"wx"}),await e(d);let u=await En(d);if(!u.isFile()||u.isSymbolicLink()||u.nlink!==1||u.size<=0||u.size>de)throw s("SCAN_ATTACHMENT");let f=await _n(d,Et.O_RDONLY|(Et.O_NOFOLLOW??0)),h;try{let I=await f.stat();if(!I.isFile()||I.nlink!==1||I.size<=0||I.size>de)throw s("SCAN_ATTACHMENT");h=await f.readFile()}finally{await f.close()}let g=be(h);if(!g||!De[g]||h.equals(r))throw s("SCAN_ATTACHMENT");return{data:h.toString("base64"),mimeType:g}}finally{await Sn(c,{recursive:!0,force:!0})}}import{Image as Dn}from"@earendil-works/pi-tui";import{lstat as bn,readFile as Ln}from"node:fs/promises";import{createHash as kt}from"node:crypto";import{resolve as bt}from"node:path";var Dt=256*1024;async function Mn(t){let e=i=>/^(['"]).*\1$/s.test(i)?i.slice(1,-1):i,o=e(t);if(!o.startsWith("@"))return{text:o,fromFile:!1};let n=bt(e(o.slice(1).trim())),r;try{r=await bn(n)}catch(i){throw O(i,"TEST_INPUT")}if(!r.isFile())throw s("TEST_INPUT");if(r.size>Dt)throw s("TEST_SIZE",{bytes:r.size,limit:Dt});try{return{text:await Ln(n,"utf8"),fromFile:!0}}catch(i){throw O(i,"TEST_INPUT")}}function Fn(t){ze(he());let e=new ie(kn()),o=pe(t),n=()=>o.length===0,r=0,i=!1,c=new Set,d=new Set,u=new Map,f=p=>kt("sha256").update(p).digest("hex"),h=!1,g,I,N,_=p=>{let a=p?.provider;return typeof a=="string"?a:"unknown"},x=p=>{let a=[...new Set([p.rule,p.otherRule])].filter(m=>m!==void 0).flatMap(m=>{let A=e.ruleAt(m);return A===void 0?[]:[`#${m} ${JSON.stringify(A)}`]});return a.length?`${l("diagnosticRuleEntries")}
18
+ ${a.join(`
19
+ `)}`:void 0},D=p=>{let a=$(p),m=x(p);return g={at:new Date().toISOString(),text:a,local:m},m?`${a}
20
+ ${m}`:a},E=async(p,a,m)=>{await p.ui.custom((A,C,S,j)=>{let k=new Dn(a,m,{fallbackColor:R=>C.fg("dim",R)},{maxWidthCells:72,maxHeightCells:24});return{render(R){return[...k.render(R),"",C.fg("dim",l("attachmentPreviewHint"))]},handleInput(R){(R==="\x1B"||R==="\r"||R.toLowerCase()==="q")&&j(void 0)},invalidate(){k.invalidate()}}},{overlay:!0})};t.on("session_start",async(p,a)=>{try{if(o=pe(t,a),!n())throw a.ui.notify(l("capabilityBlocked",{names:o.join(", "),url:F}),"error"),s("PI_CAPABILITY");await e.initialize(),c.clear(),d.clear(),u.clear(),N=yt(a.modelRegistry,(C,S)=>e.redact(S,_(C)),{runs:()=>r,onBypass:()=>{if(!i){i=!0;try{a.ui.notify(l("hookBypassed",{url:F}),"warning")}catch{}}}}),h=!0,ve(Pt)||a.ui.notify(l("piNewer",{version:Pt,verified:xe,url:F}),"warning");let m=e.ruleCount;a.ui.setStatus("protecter",l("statusBarRules",{rules:W("rules",m)})),m===0&&a.ui.notify(l("emptyRules"),"warning");let A=Ke(e.rawCompaction);A.length&&a.ui.notify(l("compactIgnoredKeys",{keys:A.join(", ")}),"warning")}catch(m){h=!1,a.ui.setStatus("protecter",l("statusBarNotReady")),a.ui.notify(D(O(m,"CONFIG_IO").diagnostic),"error")}}),t.on("before_provider_request",async(p,a)=>{r++;try{if(!n())throw s("PI_CAPABILITY");let m=e.attachmentMode;if(ce(p.payload)){if(m==="deny")throw s("SCAN_ATTACHMENT");let C=p.payload;if(m==="ask"){let k=Ot(p.payload),R=Tt(p.payload),X=[],P=new Set(c),b=new Map,H=0;for(let L=0;L<k.length;L++){let T=k[L],v=T?H++:-1,M=T?kt("sha256").update(T.mimeType??"image/png").update("\0").update(T.data).digest("hex"):void 0,G=0;M&&(G=(b.get(M)??0)+1,b.set(M,G));let U=M?`${M}:${G}`:void 0,V=R[L]??(T?u.get(f(T.data)):void 0);if(V&&d.has(V)||U&&P.has(U)){X[v]=void 0;continue}let Le=T!==void 0&&_t(T),Y;T?(Y=[l("attachmentOpenImage")],Le&&Y.push(l("attachmentEditImage")),Y.push(l("attachmentAllow"),l("attachmentDeny"))):Y=[l("attachmentAllow"),l("attachmentDeny")];let Me=!1,ue=!1;for(;!Me;){let fe=await a.ui.select(`${l("attachmentAskTitle",{index:L+1,total:k.length})}
21
+
22
+ ${l("attachmentAskBody")}
23
+
24
+ ${l("attachmentPathLabel")}: ${V??l("attachmentPathUnavailable")}`,Y);if(T&&fe===Y[0]){await E(a,T.data,T.mimeType??"image/png");continue}if(T&&Le&&fe===l("attachmentEditImage")){let Fe=await Rt(T,async Lt=>{if(await St(Lt),await a.ui.select(l("attachmentEditWait"),[l("attachmentEditDone"),l("attachmentDeny")])!==l("attachmentEditDone"))throw s("SCAN_ATTACHMENT")});T={type:"image",...Fe},X[v]=Fe,ue=!0,await E(a,T.data,T.mimeType??"image/png");continue}if(fe===l("attachmentAllow"))Me=!0,V&&!ue&&d.add(V),U&&!ue&&c.add(U);else throw s("SCAN_ATTACHMENT")}}C=Nt(p.payload,X)}a.ui.notify(l("attachmentAllowed"),"warning");let S=a.model?.provider??"unknown",j=await le(C,async k=>{let R=await e.redact(k,S);return typeof R=="string"?R:k});return h=!0,j}let A=await e.redact(p.payload,a.model?.provider??"unknown");return h=!0,A}catch(m){h=!1;let A=D(O(m,"INTERNAL").diagnostic);try{a.abort()}catch{}try{a.ui.notify(A,"error")}catch{}return{}}}),t.on("message_end",p=>{if(p.message.role!=="assistant")return;let a=p.message;return{message:{...a,content:a.content.map(m=>m.type==="text"?{...m,text:e.restoreText(m.text)}:m.type==="thinking"?{...m,thinking:e.restoreText(m.thinking)}:m.type==="toolCall"?{...m,arguments:e.restore(m.arguments)}:m),...a.errorMessage?{errorMessage:e.restoreText(a.errorMessage)}:{}}}}),t.registerMarkdownTransformer((p,a)=>a.messageType==="user"?p:e.restoreText(p)),t.on("tool_result",(p,a)=>{try{let m=p.input,A=m.path??m.file_path??m.filePath;if(typeof A!="string"||!A.trim())return;let C=bt(a.cwd,A.replace(/^@/,""));for(let S of p.content)S.type==="image"&&u.set(f(S.data),C)}catch{}}),t.on("tool_call",(p,a)=>{if(!h)return{block:!0,reason:e.lastDiagnosticText??g?.text??$(s("NOT_READY").diagnostic)};let m=e.restore(p.input);for(let A of Object.keys(p.input))delete p.input[A];if(Object.assign(p.input,m),ut(p.toolName,p.input,a.cwd,e.configPath))return{block:!0,reason:l("toolBlocked")}});let K=async(p,a)=>{if(!n())throw s("PI_CAPABILITY");if(!e.ready)throw e.lastDiagnostic?s(e.lastDiagnostic.code,e.lastDiagnostic):s("NOT_READY");let m=e.compactionMode;if(m==="off")throw s("COMPACT_DENIED");if(I==="deny")throw s("COMPACT_DENIED");if(m!=="ask"||I==="allow")return;let A=[l("compactAllowOnce"),l("compactAllowAlways"),l("compactDenyOnce"),l("compactDenyAlways")],C=await p.ui.select(`${l("compactAskTitle")}
25
+
26
+ ${l("compactAskBody")}`,A,{signal:a}),S=C===void 0?-1:A.indexOf(C);if(S===1?(I="allow",p.ui.notify(l("compactAlwaysNotice"),"info")):S===3&&(I="deny",p.ui.notify(l("compactDenyNotice"),"warning")),S!==0&&S!==1)throw s("COMPACT_DENIED")};t.on("session_before_compact",async(p,a)=>{try{await K(a,p.signal),await mt(p,e,a.model?.provider??"unknown"),a.ui.notify(l("compactRedacted"),"info");return}catch(m){return a.ui.notify(D(O(m,"COMPACT_FAILED").diagnostic),"warning"),{cancel:!0}}}),t.on("session_before_tree",async(p,a)=>{if(p.preparation.userWantsSummary)try{await K(a,p.signal);let m=await pt(p,e,a.model?.provider??"unknown");return a.ui.notify(l("compactRedacted"),"info"),m}catch(m){return a.ui.notify(D(O(m,"COMPACT_FAILED").diagnostic),"warning"),{cancel:!0}}}),t.registerCommand("protecter",{description:l("commandDescription"),handler:async(p,a)=>{let m=p.trim(),A=m.split(/\s+/).filter(Boolean),C=A[0]??"logs";if(C==="test"){let P=m.slice(C.length).trim();if(!P){a.ui.notify(l("usage"),"info");return}try{if(!e.ready)throw s("NOT_READY");let{text:b,fromFile:H}=await Mn(P),T=(await e.redact({text:b},"test")).text;if(typeof T!="string")throw s("INTERNAL");let v=[l(H?"testFileLabel":"testTextLabel"),l(T===b?"testUnchanged":"testRedacted",{chars:W("chars",T.length)})].join(`
27
+ `);a.mode==="tui"?await a.ui.editor(l("testPreviewTitle"),`${v}
28
+
29
+ ${T}`):a.ui.notify(`${v}
30
+
31
+ ${T}`,"info")}catch(b){a.ui.notify(D(O(b,"TEST_INPUT").diagnostic),"error")}return}if(!["status","reload","logs"].includes(C)||C!=="logs"&&A.length>1||A.length>2||A[1]!==void 0&&A[1]!=="clear"&&!/^(?:[1-9]\d?|100)$/.test(A[1])){a.ui.notify(l("usage"),"info");return}if(C==="logs"){if(a.mode!=="tui"){a.ui.notify(l("logsTuiOnly"),"warning");return}if(A[1]==="clear"){try{if(!e.ready)throw s("NOT_READY");if(!await a.ui.confirm(l("clearTitle"),l("clearBody")))return;await a.waitForIdle();let P=await e.clearAuditRecords();h=e.ready,a.ui.notify(l("cleared",{bytes:W("bytes",P)}),"info")}catch(P){a.ui.notify(D(O(P,"AUDIT_IO").diagnostic),"error")}return}try{let{records:P,truncated:b}=e.auditRecords(Number(A[1]??20));if(!P.length){a.ui.notify(l("logsNone"),"info");return}let H=G=>JSON.stringify(G).replace(/[\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g,U=>`\\u${U.charCodeAt(0).toString(16).padStart(4,"0")}`),L=P.map((G,U)=>`${U+1}. ${H(G.time)} | ${H(G.provider).slice(0,120)}`),T=await a.ui.select(l("logsSelectTitle")+(b?l("logsTruncated"):""),L),v=T===void 0?-1:L.indexOf(T);if(v<0||!await a.ui.confirm(l("logsRevealTitle"),l("logsRevealBody")))return;let M=H(P[v]);await a.ui.editor(l("logsPreviewTitle"),M.length>2e4?`${M.slice(0,2e4)}
32
+ ${l("logsPreviewTruncated")}`:M)}catch(P){a.ui.notify(D(O(P,"AUDIT_IO").diagnostic),"error")}return}if(C==="reload"){await a.waitForIdle(),await a.reload();return}let S=e.lastDiagnostic,j=S?[$(S),x(S)].filter(Boolean).join(`
33
+ `):g?[g.text,g.local].filter(Boolean).join(`
34
+ `):void 0,k=l("statusLine",{state:l(e.ready?"statusReady":"statusNotReady"),rules:W("rules",e.ruleCount),mappings:W("mappings",e.mappingCount)}),R=`
35
+ ${l("statusCompaction",{mode:e.compactionMode,guard:l(N?"guardInstalled":"guardMissing")})}`,X=j?`
36
+ ${l("statusLastBlock",{at:g?.at??""})}
37
+ ${j}`:`
38
+ ${l("statusNoBlock")}`;a.ui.notify(k+R+X,e.ready?"info":"error")}}),t.on("session_shutdown",()=>{N?.(),N=void 0,e.close()})}export{Fn as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-information-protecter",
3
- "version": "0.14.2",
3
+ "version": "0.15.0",
4
4
  "description": "Sensitive Personal Information (SPI) Protecter — local reversible privacy redaction for Pi",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -40,7 +40,8 @@
40
40
  "node": ">=22"
41
41
  },
42
42
  "peerDependencies": {
43
- "@earendil-works/pi-coding-agent": ">=0.84.0 <0.85.0 || >=0.85.1 <1.0.0 || >=1.2.0"
43
+ "@earendil-works/pi-coding-agent": ">=0.84.0 <0.85.0 || >=0.85.1 <1.0.0 || >=1.2.0",
44
+ "@earendil-works/pi-tui": "*"
44
45
  },
45
46
  "devDependencies": {
46
47
  "@earendil-works/pi-coding-agent": "1.4.0",
@@ -57,8 +58,5 @@
57
58
  "check": "npm run typecheck && npm test",
58
59
  "prepublishOnly": "npm run check",
59
60
  "prepack": "npm run build"
60
- },
61
- "dependencies": {
62
- "@earendil-works/pi-tui": "1.4.0"
63
61
  }
64
62
  }