pi-information-protecter 0.14.1 → 0.14.2

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,12 @@
1
1
  # Changelog / 更新日志
2
2
 
3
+ ## 0.14.2 — Edit images before sending / 发送前编辑图片
4
+
5
+ ### Added / 新增
6
+
7
+ - Add an option to edit supported inline images with the operating system's default image application. The editor receives a private temporary copy; after the user saves over that file and confirms, only the saved image bytes replace the attachment in the provider request. The source attachment is unchanged, temporary files are removed, and request text still follows normal redaction. Support PNG, JPEG, WebP and GIF images up to 25 MiB.
8
+ 新增使用系统默认图片软件编辑支持的内嵌图片。编辑器打开私有临时副本;用户覆盖保存并确认后,仅将保存后的图片数据替换到提供商请求中。原附件不变,临时文件会清理,请求文本仍正常脱敏。支持不超过 25 MiB 的 PNG、JPEG、WebP 与 GIF 图片。
9
+
3
10
  ## 0.14.1 — Review attachments individually / 逐项查看并确认附件
4
11
 
5
12
  ### 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, then return to that image's menu to allow it or cancel the request. 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. 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.
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 中预览,再返回该图片的菜单选择允许或取消请求。确认仅适用于该图片的具体内容;不同图片必须分别确认。相同图片内容在本会话中会记住已确认状态,避免随历史记录重复询问。附件本身不会被检查或脱敏,但请求中的其他文本仍会正常脱敏。设为 `"allow"` 可始终放行附件,设为 `"deny"` 则始终取消。
440
+ 默认 `attachments: "ask"`:每个新附件都会单独询问。对于内嵌图片,可选“打开图片”在 TUI 中预览,或选“用系统默认软件编辑图片”打开私有临时副本。将修改覆盖保存到同一临时文件后返回菜单;只有保存后的图片副本会替换提供商请求中的附件,原附件不会被修改,编辑结束后临时文件会删除。内嵌 PNG、JPEG、WebP、GIF 图片(不超过 25 MiB)可编辑,其他图片格式仍可预览并选择放行。确认仅适用于该图片的具体内容;不同图片必须分别确认。相同图片内容在本会话中会记住已确认状态,避免随历史记录重复询问。附件本身不会被检查或脱敏,但请求中的其他文本仍会正常脱敏。设为 `"allow"` 可始终放行附件,设为 `"deny"` 则始终取消。
441
441
 
442
442
  ```json
443
443
  { "version": 1, "attachments": "ask", "sensitiveWords": [] }
package/dist/index.mjs CHANGED
@@ -1,31 +1,31 @@
1
1
  /*! SPI Protecter | MIT | see LICENSE / SPI 隐私保护插件 | MIT 许可 */
2
- import{getAgentDir as Jt,VERSION as nt}from"@earendil-works/pi-coding-agent";import{Worker as Lt}from"node:worker_threads";import{fileURLToPath as bt}from"node:url";import*as A from"node:fs";import{join as j,resolve as Ot}from"node:path";import{createHash as Nt,randomUUID as Ct}from"node:crypto";import{Worker as Tt}from"node:worker_threads";import{fileURLToPath as Et}from"node:url";var F="https://github.com/taills/pi-information-protecter/issues/new",Ie="0.84.0-0.84.x, 0.85.1-0.87.x, 0.99.x, 1.2.0-1.4.x",rt=["on","registerCommand","registerMarkdownTransformer"],it=["abort"],st=["notify","setStatus"];function te(t,e){return!t||typeof t!="object"&&typeof t!="function"?!1:typeof t[e]=="function"}function ne(t,e){let o=[];for(let r of rt)te(t,r)||o.push(`pi.${r}()`);if(e===void 0)return o;let n=e;for(let r of it)te(n,r)||o.push(`ctx.${r}()`);for(let r of st)te(n.ui,r)||o.push(`ctx.ui.${r}()`);return(!n.modelRegistry||typeof n.modelRegistry!="object")&&o.push("ctx.modelRegistry"),o}function Ae(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 oe={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"]},at={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:["离线测试输入超出大小上限","改用更小的文件或更短的片段"]},we={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 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.
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",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.",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 会在内部构造摘要请求,该请求不会经过本扩展的常规脱敏钩子。若直接发送,原始会话内容(包括受保护的值)可能会以明文发出。
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:"打开图片",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 re(t=process.env){let e=t.PI_PROTECTER_LANG||t.LC_ALL||t.LC_MESSAGES||t.LANG||t.LANGUAGE||lt();return/^zh\b|^zh[-_]/i.test(e.trim())?"zh":"en"}function lt(){try{return new Intl.DateTimeFormat().resolvedOptions().locale}catch{return""}}var x=re();function Ne(){return x}function Ce(t){x=t}function l(t,e={}){return((x==="zh"?ct:we)[t]??we[t]).replace(/\{(\w+)\}/g,(n,r)=>Object.hasOwn(e,r)?String(e[r]):n)}var ut={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} 个字符"}}},Oe=new Map;function z(t,e){let o=x==="zh"?"zh-CN":"en",n=Oe.get(x);if(!n){try{n=new Intl.PluralRules(o)}catch{n=void 0}n&&Oe.set(x,n)}let r=n?.select(e)??"other",s=ut[x][t],c=s[r]??s.other,u=new Intl.NumberFormat(o).format(e);return c.replace("{n}",u)}function Te(t){let o=(x==="zh"?at[t]:oe[t])??oe[t]??oe.INTERNAL;return{reason:o[0],action:o[1]}}var Ee={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 _e=["rule","otherRule","node","bytes","limit","timeoutMs","status"],dt=/^[A-Za-z][A-Za-z0-9]{0,39}$/,ft=/^(EACCES|EPERM|ENOENT|ENOSPC|EDQUOT|EROFS|ELOOP|EISDIR|ENOTDIR|EMFILE|ENFILE|EIO|EEXIST|EBADF|EBUSY|ENOTEMPTY)$/;function mt(t,e={}){let{reason:o,action:n}=Te(t),r={};for(let s of _e){let c=e[s];typeof c=="number"&&Number.isSafeInteger(c)&&c>=0&&(r[s]=c)}return typeof e.errno=="string"&&ft.test(e.errno)&&(r.errno=e.errno),typeof e.errorName=="string"&&dt.test(e.errorName)&&(r.errorName=e.errorName),{code:t,stage:Ee[t],reason:o,action:n,...r}}function H(t){let e=Ne()==="zh"?":":": ",o=[..._e,"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 G=class extends Error{diagnostic;constructor(e,o={}){let n=mt(e,o);super(H(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 W(t,e){if(!t||typeof t!="object")return i(e);let o=t,n=typeof o.code=="string"&&Object.hasOwn(Ee,o.code)?o.code:e;return i(n,o)}import{constants as $,closeSync as Se,fchmodSync as pt,fstatSync as gt,mkdirSync as ht,openSync as Re,readFileSync as yt,writeFileSync as It}from"node:fs";import{dirname as At}from"node:path";var Pe=["ask","protected","off"],ie=["provider","model","contextWindow","reserveTokens"];function De(t){return!t||typeof t!="object"?[]:ie.filter(e=>Object.hasOwn(t,e))}var se={version:1,sensitiveWords:[]},ke="ask";function wt(t){if(typeof t=="string"){if(!Pe.includes(t))throw i("CONFIG_COMPACTION");return}if(!t||typeof t!="object"||Array.isArray(t))throw i("CONFIG_COMPACTION");let e=t,o=["mode",...ie];if(Object.keys(e).some(n=>!o.includes(n)))throw i("CONFIG_COMPACTION");if(e.mode!==void 0&&!Pe.includes(e.mode))throw i("CONFIG_COMPACTION");for(let n of ie){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:ke}:typeof t=="string"?{mode:t}:{mode:t.mode??ke}}function ae(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")&&wt(e.compaction),Object.hasOwn(e,"attachments")&&!["ask","allow","deny"].includes(e.attachments??""))throw i("CONFIG_ATTACHMENT");if(e.sensitiveWords.length>1e3)throw i("CONFIG_SIZE",{limit:1e3});let n=new Map;for(let r of e.sensitiveWords){if(o++,typeof r=="string"){if(!r||r.length>8192)throw i("CONFIG_SCHEMA",{rule:o,limit:8192});let c=JSON.stringify(["literal",r]);if(n.has(c)&&n.get(c)!==void 0)throw i("CONFIG_CONFLICT",{rule:o});n.set(c,void 0);continue}if(!r||typeof r!="object")throw i("CONFIG_SCHEMA",{rule:o});if(Object.hasOwn(r,"replacement")&&(typeof r.replacement!="string"||!r.replacement.trim()||r.replacement.length>8192||r.replacement.includes("__PIP_")))throw i("CONFIG_TARGET",{rule:o,limit:8192});if(r.type==="literal"){if(Object.keys(r).some(c=>!["type","value","replacement"].includes(c))||typeof r.value!="string"||!r.value||r.value.length>8192)throw i("CONFIG_SCHEMA",{rule:o,limit:8192})}else if(r.type==="regex"){if(Object.keys(r).some(c=>!["type","pattern","flags","replacement"].includes(c))||typeof r.pattern!="string"||!r.pattern||r.pattern.length>8192||r.flags!==void 0&&(typeof r.flags!="string"||!/^[gimsu]*$/.test(r.flags)))throw i("CONFIG_REGEX",{rule:o,limit:8192});try{new RegExp(r.pattern,r.flags??"")}catch{throw i("CONFIG_REGEX",{rule:o})}}else throw i("CONFIG_SCHEMA",{rule:o});let s=r.type==="literal"?JSON.stringify(["literal",r.value]):JSON.stringify(["regex",r.pattern,[...new Set((r.flags??"")+"g")].sort().join("")]);if(n.has(s)&&n.get(s)!==r.replacement)throw i("CONFIG_CONFLICT",{rule:o});n.set(s,r.replacement)}return e}catch(n){throw n instanceof G?n:i("CONFIG_SCHEMA",{rule:o})}}function Le(t,e=!1){let o;try{if(e){ht(At(t),{recursive:!0,mode:448});try{let s=Re(t,$.O_WRONLY|$.O_CREAT|$.O_EXCL,384);try{It(s,JSON.stringify(se,null,2)+`
12
- `)}finally{Se(s)}}catch(s){if(s.code!=="EEXIST")throw w(s,"CONFIG_IO")}}o=Re(t,$.O_RDONLY|$.O_NOFOLLOW|$.O_NONBLOCK);let n=gt(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"&&pt(o,384);let r=yt(o,"utf8");if(Buffer.byteLength(r)>1024*1024)throw i("CONFIG_SIZE",{bytes:Buffer.byteLength(r),limit:1024*1024});return{config:ae(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&&Se(o)}}var le=/^protecter(?:\.[a-f0-9]{32})?\.json$/;function _t(t){return new Promise((e,o)=>{let n=new Tt(Et(new URL("./validate-worker.mjs",import.meta.url)),{workerData:t,execArgv:[],resourceLimits:{maxOldGenerationSizeMb:64}}),r=!1,s=(u,m=i("WORKER_FAILED"))=>{r||(r=!0,clearTimeout(c),n.terminate(),u?e():o(m))},c=setTimeout(()=>s(!1,i("CONFIG_TIMEOUT",{timeoutMs:2e3})),2e3);n.once("message",u=>u===!0?s(!0):s(!1,W(u,"CONFIG_SCHEMA"))),n.once("error",()=>s(!1)),n.once("exit",()=>s(!1))})}function St(t){let e=new Set,o=[];for(let d of t)for(let h of d.sensitiveWords){let y=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(y)||(e.add(y),o.push(h))}let n=[];for(let d of t)d.compaction!==void 0&&n.push(K(d.compaction));let s=["off","ask","protected"].find(d=>n.some(h=>h.mode===d)),c={version:1,sensitiveWords:o};s!==void 0&&(c.compaction={mode:s});let u=t.map(d=>d.attachments).filter(d=>d!==void 0);u.length&&(c.attachments=["deny","ask","allow"].find(d=>u.includes(d)));let m=JSON.stringify(c);if(Buffer.byteLength(m)>1024*1024)throw i("CONFIG_SIZE",{bytes:Buffer.byteLength(m),limit:1024*1024});return ae(m)}function be(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 ce(t,e){let o=j(t,e),n=be(o),r=Le(o);if(be(o)!==n)throw i("MIGRATION_CHANGED");return{name:e,...r,identity:n,digest:Nt("sha256").update(r.raw).digest("hex")}}function Y(t,e){let o=ce(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=>le.test(e)).sort()}function Me(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 Fe(t,e,o={}){if(!/^[a-f0-9]{32}$/.test(e))throw i("MACHINE_ID");let n=Ot(t),r=`protecter.${e}.json`,s=j(n,r);A.mkdirSync(n,{recursive:!0,mode:448});let c=j(n,".protecter-migration.lock"),u=Date.now()+(o.lockTimeoutMs??5e3);for(;;)try{A.mkdirSync(c,{mode:448});break}catch(d){if(d.code!=="EEXIST")throw w(d,"MIGRATION_IO");if(Date.now()>=u)throw i("MIGRATION_LOCKED",{timeoutMs:o.lockTimeoutMs??5e3});await new Promise(h=>setTimeout(h,50))}let m;try{let d=X(n);if(d.length>64)throw i("MIGRATION_LIMIT",{limit:64});let y=[...d].sort((f,O)=>f===r?-1:O===r?1:f.localeCompare(O)).map(f=>ce(n,f)),I=St(y.length?y.map(f=>f.config):[se]);if(await _t([I]),y.length===1&&y[0].name===r){if(Y(n,y[0]),JSON.stringify(X(n))!==JSON.stringify(d))throw i("MIGRATION_CHANGED");return{path:s,config:y[0].config,raw:y[0].raw,sourceRaws:[y[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});m=j(n,`.protecter-migration.${Ct()}.tmp`);let C=A.openSync(m,A.constants.O_WRONLY|A.constants.O_CREAT|A.constants.O_EXCL,384);try{A.writeFileSync(C,N),A.fsyncSync(C)}finally{A.closeSync(C)}if(o.checkpoint?.("beforeCommit",s),JSON.stringify(X(n))!==JSON.stringify(d))throw i("MIGRATION_CHANGED");for(let f of y)Y(n,f);A.renameSync(m,s),m=void 0,Me(n);let p=ce(n,r);if(p.raw!==N)throw i("MIGRATION_CHANGED");o.checkpoint?.("afterCommit",s);for(let f of y)f.name!==r&&(o.checkpoint?.("beforeDelete",j(n,f.name)),Y(n,p),Y(n,f),A.unlinkSync(j(n,f.name)));Me(n);let a=[r];if(JSON.stringify(X(n))!==JSON.stringify(a))throw i("MIGRATION_CHANGED");return Y(n,p),{path:s,config:I,raw:N,sourceRaws:[...new Set([...y.map(f=>f.raw),N])],migrated:y.filter(f=>f.name!==r).length}}catch(d){throw d instanceof G?d:w(d,"MIGRATION_IO")}finally{if(m)try{A.unlinkSync(m)}catch{}A.rmdirSync(c)}}import{createHash as Rt}from"node:crypto";import{readFileSync as Pt}from"node:fs";import{execFileSync as xe}from"node:child_process";function ue(t){let e=t.trim().toLowerCase().replace(/-/g,"");if(!/^[a-f0-9]{32}$/.test(e)||/^0+$/.test(e))throw i("MACHINE_ID");return Rt("sha256").update(`pi-information-protecter:v1:${e}`).digest("hex").slice(0,32)}function Ge(){try{if(process.platform==="linux")return ue(Pt("/etc/machine-id","utf8"));if(process.platform==="darwin"){let t=xe("/usr/sbin/ioreg",["-rd1","-c","IOPlatformExpertDevice"],{encoding:"utf8",timeout:5e3,maxBuffer:1048576,stdio:["ignore","pipe","pipe"]});return ue(t.match(/"IOPlatformUUID"\s*=\s*"([a-fA-F0-9-]+)"/)?.[1]??"")}if(process.platform==="win32"){let t=xe("reg.exe",["query","HKLM\\SOFTWARE\\Microsoft\\Cryptography","/v","MachineGuid","/reg:64"],{encoding:"utf8",timeout:5e3,maxBuffer:65536,stdio:["ignore","pipe","pipe"]});return ue(t.match(/MachineGuid\s+REG_SZ\s+([a-fA-F0-9-]+)/i)?.[1]??"")}}catch{}throw i("MACHINE_ID")}import*as g from"node:fs";import{randomUUID as kt}from"node:crypto";var ve=32*1024*1024,Ue=8*1024*1024;function Dt(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 de(t,e,o=e){let n=g.openSync(t,(e?g.constants.O_RDWR|(o?g.constants.O_CREAT:0):g.constants.O_RDONLY)|g.constants.O_NOFOLLOW|g.constants.O_NONBLOCK,384);try{let r=g.fstatSync(n);if(!r.isFile()||r.nlink!==1||process.getuid&&r.uid!==process.getuid())throw i("AUDIT_UNSAFE");return process.platform!=="win32"&&g.fchmodSync(n,384),n}catch(r){throw g.closeSync(n),w(r,"AUDIT_UNSAFE")}}function q(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 Be(t){let e=`${t}.lock`,o=Date.now()+2e3;for(;;)try{return g.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 ze(t){let e=await Be(t),o;try{try{o=de(t,!0,!1)}catch(r){if(r.code==="ENOENT")return 0;throw r}let n=g.fstatSync(o).size;return g.ftruncateSync(o,0),g.fsyncSync(o),n}catch(n){throw q(n)}finally{try{o!==void 0&&g.closeSync(o)}finally{g.rmdirSync(e)}}}async function He(t,e,o){if(!o.length)return;let n=new Date,r=kt(),s=Buffer.from(o.map(([m,d])=>JSON.stringify({version:1,time:Dt(n),timezoneOffset:-n.getTimezoneOffset(),requestId:r,provider:e||"unknown",original:d,replacement:m})).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 无法检查或脱敏此附件。请先查看,再决定是否发送。",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(`
14
14
  `)+`
15
- `);if(s.length>Ue)throw i("AUDIT_BATCH_LIMIT",{bytes:s.length,limit:Ue});let c=await Be(t),u;try{u=de(t,!0);let m=g.fstatSync(u).size;if(m+s.length>ve)throw i("AUDIT_FULL",{bytes:m+s.length,limit:ve});if(m){let d=Buffer.alloc(1);if(g.readSync(u,d,0,1,m-1),d[0]!==10)throw i("AUDIT_PARTIAL")}try{let d=0;for(;d<s.length;){let h=g.writeSync(u,s,d,s.length-d,m+d);if(!h)throw i("AUDIT_IO");d+=h}g.fsyncSync(u)}catch(d){throw g.ftruncateSync(u,m),g.fsyncSync(u),q(d)}}catch(m){throw q(m)}finally{u!==void 0&&g.closeSync(u),g.rmdirSync(c)}}function $e(t,e=20){if(!Number.isInteger(e)||e<1||e>100)throw i("INTERNAL",{limit:100});let o;try{try{o=de(t,!1)}catch(I){if(I.code==="ENOENT")return{records:[],truncated:!1};throw I}let n=g.fstatSync(o).size,r=Math.max(0,n-1024*1024),s=Buffer.alloc(n-r),c=g.readSync(o,s,0,s.length,r),u=s.subarray(0,c).toString("utf8");if(r){let I=u.indexOf(`
16
- `);u=I<0?"":u.slice(I+1)}let m=u.split(`
17
- `),d=m.pop()!=="",h=[],y=!1;for(let I of m.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{y=!0}return{records:h,truncated:r>0||m.length>e||d||y}}catch(n){throw q(n)}finally{o!==void 0&&g.closeSync(o)}}var Z=class{constructor(e,o=2e3,n=Ge){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?H(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 Fe(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 $e(this.auditPath,e)}clearAuditRecords(){let e=this.queue.then(()=>{if(!this.ready)throw this.notReady();return ze(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 c;try{c=JSON.parse(s)}catch{throw i("PAYLOAD_JSON")}let u=await new Promise((m,d)=>{let h=!1,y;try{y=new Lt(bt(new URL("./scan-worker.mjs",import.meta.url)),{workerData:{payload:c,rules:n.sensitiveWords,entries:[...this.tokens],configRaws:r},execArgv:[],resourceLimits:{maxOldGenerationSizeMb:128}})}catch(C){d(w(C,"WORKER_FAILED"));return}this.workers.add(y);let I=(C,p=i("WORKER_FAILED"))=>{if(!h){if(h=!0,clearTimeout(N),this.workers.delete(y),y.terminate(),!C||this.closed){d(this.closed?i("NOT_READY"):p);return}m(C)}},N=setTimeout(()=>I(void 0,i("SCAN_TIMEOUT",{timeoutMs:this.timeoutMs})),this.timeoutMs);y.once("message",C=>{C?.failed?I(void 0,W(C.diagnostic,"SCAN_INTERNAL")):C&&Array.isArray(C.additions)&&Array.isArray(C.hits)?I(C):I()}),y.once("error",()=>I()),y.once("exit",()=>I())});if(this.closed)throw i("NOT_READY");if(await He(this.auditPath,o,u.hits),this.closed)throw i("NOT_READY");for(let[m,d]of u.additions)this.tokens.set(m,d);return u.payload}restoreText(e){if(!this.tokens.size)return e;if(this.restoreSize!==this.tokens.size){let o=n=>n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.restorePattern=new RegExp([...this.tokens.keys()].sort((n,r)=>r.length-n.length).map(o).join("|"),"g"),this.restoreSize=this.tokens.size}return e.replace(this.restorePattern,o=>this.tokens.get(o)??o)}restore(e,o=0){if(o>80)throw i("RESTORE_COMPLEXITY",{node:o});if(typeof e=="string")return this.restoreText(e);if(typeof e=="number"){let n=this.tokens.get(String(e));if(n===void 0)return e;let r=Number(n);return!Number.isFinite(r)||String(r)!==n?e:r}if(Array.isArray(e))return e.map(n=>this.restore(n,o+1));if(e&&typeof e=="object"){let n=Object.create(null);for(let[r,s]of Object.entries(e)){let c=this.restoreText(r);if(Object.hasOwn(n,c))throw i("RESTORE_KEY_COLLISION");n[c]=this.restore(s,o+1)}return n}return e}close(){this.closed=!0,this.snapshot=void 0,this.tokens.clear();for(let e of this.workers)e.terminate();this.workers.clear()}};import{realpathSync as Mt,statSync as je,readdirSync as Ft}from"node:fs";import{homedir as xt}from"node:os";import{basename as fe,dirname as J,isAbsolute as Gt,relative as Je,resolve as V}from"node:path";import{fileURLToPath as vt}from"node:url";function Ut(t,e){let o=t.replace(/^@/,"");return o.startsWith("file://")&&(o=vt(o)),(o==="~"||o.startsWith("~/"))&&(o=xt()+o.slice(1)),V(e,o)}function me(t){try{return Mt(t)}catch{let e=J(t);return e===t?t:V(me(e),Je(e,t))}}function Bt(t,e){let o=Je(t,e);return o===""||!o.startsWith("..")&&!Gt(o)}function Ye(t,e){try{let o=je(t),n=je(e);return o.dev===n.dev&&o.ino===n.ino}catch{return!1}}function We(t,e,o,n){if(!n)return!0;let r=me(V(n));if(["bash","powershell"].includes(t)){let u=typeof e.command=="string"?e.command:"";if(/protecter(?:\.[a-f0-9]{32})?\.jsonl?|\.protecter-migration/i.test(u)||u.includes(n))return!0}let s=e.path??e.file_path??e.filePath,c=["grep","find","ls"].includes(t);if(typeof s!="string"&&!c)return!1;try{let u=Ut(typeof s=="string"?s:".",o),m=me(u),d=/^protecter\.[a-f0-9]{32}\.jsonl(?:\.lock)?$/,h=Ft(J(r)).filter(y=>d.test(y)).some(y=>Ye(u,V(J(r),y)));return J(m)===J(r)&&(le.test(fe(m))||d.test(fe(m))||fe(m).startsWith(".protecter-migration"))||m===r||Ye(u,n)||h||c&&Bt(m,r)}catch{return!0}}function pe(t,e){t.length=0;for(let o of e)t.push(o)}function ge(t){if(!Array.isArray(t))throw i("COMPACT_FAILED");return t}function Ke(t){if(typeof t!="string")throw i("COMPACT_FAILED");return t}async function Xe(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=ge(r.messages),c=ge(r.prefix),u=n.previousSummary===void 0?void 0:Ke(r.previous);pe(n.messagesToSummarize,s),pe(n.turnPrefixMessages,c),u!==void 0&&(n.previousSummary=u)}async function qe(t,e,o){let{preparation:n}=t,r=await e.redact({entries:n.entriesToSummarize,instructions:n.customInstructions??null},o);if(!r||typeof r!="object")throw i("COMPACT_FAILED");let s=ge(r.entries),c=n.customInstructions===void 0?void 0:Ke(r.instructions);return pe(n.entriesToSummarize,s),c===void 0?{}:{customInstructions:c}}var Ze=["stream","streamSimple"],zt=["classify","generateImages"],Ve=Ze,he=Symbol.for("pi-information-protecter.runtime-guard");function Ht(t){let e=t?.runtime;if(!e||typeof e!="object")throw i("GUARD_UNAVAILABLE");let o=e;for(let n of Ve)if(typeof o[n]!="function")throw i("GUARD_UNAVAILABLE");return o}function $t(t){return!t||typeof t!="object"?!1:t.onPayload!==void 0}function jt(t,e,o,n){if(!e||typeof e!="object")return;let r=e.onPayload;if(!n||typeof r!="function")return e;let s=r;return{...e,onPayload:async c=>{let u=n.runs(),m=await s(c);return n.runs()>u?m:(n.onBypass?.(),o(t,m===void 0?c:m))}}}function Qe(t,e,o){let n=Ht(t);n[he]?.();let r=[...Ve,...zt.filter(c=>typeof n[c]=="function")].map(c=>[c,n[c]]);for(let[c,u]of r){let m=Ze.includes(c),d=function(h,y,I){return m&&$t(I)?u.call(this,h,y,jt(h,I,e,o)):(async()=>u.call(this,h,await e(h,y),I))()};n[c]=d}let s=()=>{for(let[c,u]of r)n[c]=u;delete n[he]};return Object.defineProperty(n,he,{value:s,configurable:!0,enumerable:!1,writable:!0}),s}function Q(t,e=0){if(e>80||!t||typeof t!="object")return!1;if(Array.isArray(t))return t.some(n=>Q(n,e+1));let o=t;return et(o)||Object.keys(o).some(tt)?!0:Object.values(o).some(n=>Q(n,e+1))}var Yt=t=>!!t&&typeof t=="object"&&t.type==="image"&&typeof t.data=="string",et=t=>typeof t.type=="string"&&/image|audio|video|document|(^|_)file($|_)/i.test(t.type);function ye(t,e=0){return e>80||!t||typeof t!="object"?[]:Yt(t)?[t]:(Array.isArray(t)?t:Object.values(t)).flatMap(n=>ye(n,e+1))}var tt=t=>/^(inlineData|inline_data|fileData|file_data|image_url|input_audio)$/.test(t);async function ee(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=>ee(n,e,o+1)));if(t&&typeof t=="object"){let n=t;if(et(n))return t;let r=Object.create(null);for(let[s,c]of Object.entries(n))tt(s)||s==="type"&&typeof c=="string"?r[s]=c:r[s]=await ee(c,e,o+1);return r}return t}import{Image as Wt}from"@earendil-works/pi-tui";import{lstat as Kt,readFile as Xt}from"node:fs/promises";import{createHash as qt}from"node:crypto";import{resolve as Zt}from"node:path";var ot=256*1024;async function Vt(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=Zt(e(o.slice(1).trim())),r;try{r=await Kt(n)}catch(s){throw w(s,"TEST_INPUT")}if(!r.isFile())throw i("TEST_INPUT");if(r.size>ot)throw i("TEST_SIZE",{bytes:r.size,limit:ot});try{return{text:await Xt(n,"utf8"),fromFile:!0}}catch(s){throw w(s,"TEST_INPUT")}}function Qt(t){Ce(re());let e=new Z(Jt()),o=ne(t),n=()=>o.length===0,r=0,s=!1,c=new Set,u=!1,m,d,h,y=p=>{let a=p?.provider;return typeof a=="string"?a:"unknown"},I=p=>{let a=H(p);return m={at:new Date().toISOString(),text:a},a},N=async(p,a,f)=>{await p.ui.custom((O,T,S,L)=>{let b=new Wt(a,f,{fallbackColor:R=>T.fg("dim",R)},{maxWidthCells:72,maxHeightCells:24});return{render(R){return[...b.render(R),"",T.fg("dim",l("attachmentPreviewHint"))]},handleInput(R){(R==="\x1B"||R==="\r"||R.toLowerCase()==="q")&&L(void 0)},invalidate(){b.invalidate()}}},{overlay:!0})};t.on("session_start",async(p,a)=>{try{if(o=ne(t,a),!n())throw a.ui.notify(l("capabilityBlocked",{names:o.join(", "),url:F}),"error"),i("PI_CAPABILITY");await e.initialize(),c.clear(),h=Qe(a.modelRegistry,(T,S)=>e.redact(S,y(T)),{runs:()=>r,onBypass:()=>{if(!s){s=!0;try{a.ui.notify(l("hookBypassed",{url:F}),"warning")}catch{}}}}),u=!0,Ae(nt)||a.ui.notify(l("piNewer",{version:nt,verified:Ie,url:F}),"warning");let f=e.ruleCount;a.ui.setStatus("protecter",l("statusBarRules",{rules:z("rules",f)})),f===0&&a.ui.notify(l("emptyRules"),"warning");let O=De(e.rawCompaction);O.length&&a.ui.notify(l("compactIgnoredKeys",{keys:O.join(", ")}),"warning")}catch(f){u=!1,a.ui.setStatus("protecter",l("statusBarNotReady")),a.ui.notify(I(w(f,"CONFIG_IO").diagnostic),"error")}}),t.on("before_provider_request",async(p,a)=>{r++;try{if(!n())throw i("PI_CAPABILITY");let f=e.attachmentMode;if(Q(p.payload)){if(f==="deny")throw i("SCAN_ATTACHMENT");if(f==="ask"){let L=ye(p.payload),b=new Set(c),R=new Map,E=Math.max(L.length,1);for(let k=0;k<E;k++){let _=L[k],M=_?qt("sha256").update(_.mimeType??"image/png").update("\0").update(_.data).digest("hex"):void 0,P=0;M&&(P=(R.get(M)??0)+1,R.set(M,P));let D=M?`${M}:${P}`:void 0;if(D&&b.has(D))continue;let v=_?[l("attachmentOpenImage"),l("attachmentAllow"),l("attachmentDeny")]:[l("attachmentAllow"),l("attachmentDeny")],U=!1;for(;!U;){let B=await a.ui.select(`${l("attachmentAskTitle",{index:k+1,total:E})}
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
18
 
19
- ${l("attachmentAskBody")}`,v);if(_&&B===v[0]){await N(a,_.data,_.mimeType??"image/png");continue}if(B===v[_?1:0])U=!0,D&&c.add(D);else throw i("SCAN_ATTACHMENT")}}}a.ui.notify(l("attachmentAllowed"),"warning");let T=a.model?.provider??"unknown",S=await ee(p.payload,async L=>{let b=await e.redact(L,T);return typeof b=="string"?b:L});return u=!0,S}let O=await e.redact(p.payload,a.model?.provider??"unknown");return u=!0,O}catch(f){u=!1;let O=I(w(f,"INTERNAL").diagnostic);try{a.abort()}catch{}try{a.ui.notify(O,"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(f=>f.type==="text"?{...f,text:e.restoreText(f.text)}:f.type==="thinking"?{...f,thinking:e.restoreText(f.thinking)}:f.type==="toolCall"?{...f,arguments:e.restore(f.arguments)}:f),...a.errorMessage?{errorMessage:e.restoreText(a.errorMessage)}:{}}}}),t.registerMarkdownTransformer((p,a)=>a.messageType==="user"?p:e.restoreText(p)),t.on("tool_call",(p,a)=>{if(!u)return{block:!0,reason:e.lastDiagnosticText??m?.text??H(i("NOT_READY").diagnostic)};let f=e.restore(p.input);for(let O of Object.keys(p.input))delete p.input[O];if(Object.assign(p.input,f),We(p.toolName,p.input,a.cwd,e.configPath))return{block:!0,reason:l("toolBlocked")}});let C=async(p,a)=>{if(!n())throw i("PI_CAPABILITY");if(!e.ready)throw e.lastDiagnostic?i(e.lastDiagnostic.code,e.lastDiagnostic):i("NOT_READY");let f=e.compactionMode;if(f==="off")throw i("COMPACT_DENIED");if(d==="deny")throw i("COMPACT_DENIED");if(f!=="ask"||d==="allow")return;let O=[l("compactAllowOnce"),l("compactAllowAlways"),l("compactDenyOnce"),l("compactDenyAlways")],T=await p.ui.select(`${l("compactAskTitle")}
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
20
 
21
- ${l("compactAskBody")}`,O,{signal:a}),S=T===void 0?-1:O.indexOf(T);if(S===1?(d="allow",p.ui.notify(l("compactAlwaysNotice"),"info")):S===3&&(d="deny",p.ui.notify(l("compactDenyNotice"),"warning")),S!==0&&S!==1)throw i("COMPACT_DENIED")};t.on("session_before_compact",async(p,a)=>{try{await C(a,p.signal),await Xe(p,e,a.model?.provider??"unknown"),a.ui.notify(l("compactRedacted"),"info");return}catch(f){return a.ui.notify(I(w(f,"COMPACT_FAILED").diagnostic),"warning"),{cancel:!0}}}),t.on("session_before_tree",async(p,a)=>{if(p.preparation.userWantsSummary)try{await C(a,p.signal);let f=await qe(p,e,a.model?.provider??"unknown");return a.ui.notify(l("compactRedacted"),"info"),f}catch(f){return a.ui.notify(I(w(f,"COMPACT_FAILED").diagnostic),"warning"),{cancel:!0}}}),t.registerCommand("protecter",{description:l("commandDescription"),handler:async(p,a)=>{let f=p.trim(),O=f.split(/\s+/).filter(Boolean),T=O[0]??"logs";if(T==="test"){let E=f.slice(T.length).trim();if(!E){a.ui.notify(l("usage"),"info");return}try{if(!e.ready)throw i("NOT_READY");let{text:k,fromFile:_}=await Vt(E),P=(await e.redact({text:k},"test")).text;if(typeof P!="string")throw i("INTERNAL");let D=[l(_?"testFileLabel":"testTextLabel"),l(P===k?"testUnchanged":"testRedacted",{chars:z("chars",P.length)})].join(`
22
- `);a.mode==="tui"?await a.ui.editor(l("testPreviewTitle"),`${D}
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
23
 
24
- ${P}`):a.ui.notify(`${D}
24
+ ${O}`):c.ui.notify(`${M}
25
25
 
26
- ${P}`,"info")}catch(k){a.ui.notify(I(w(k,"TEST_INPUT").diagnostic),"error")}return}if(!["status","reload","logs"].includes(T)||T!=="logs"&&O.length>1||O.length>2||O[1]!==void 0&&O[1]!=="clear"&&!/^(?:[1-9]\d?|100)$/.test(O[1])){a.ui.notify(l("usage"),"info");return}if(T==="logs"){if(a.mode!=="tui"){a.ui.notify(l("logsTuiOnly"),"warning");return}if(O[1]==="clear"){try{if(!e.ready)throw i("NOT_READY");if(!await a.ui.confirm(l("clearTitle"),l("clearBody")))return;await a.waitForIdle();let E=await e.clearAuditRecords();u=e.ready,a.ui.notify(l("cleared",{bytes:z("bytes",E)}),"info")}catch(E){a.ui.notify(I(w(E,"AUDIT_IO").diagnostic),"error")}return}try{let{records:E,truncated:k}=e.auditRecords(Number(O[1]??20));if(!E.length){a.ui.notify(l("logsNone"),"info");return}let _=U=>JSON.stringify(U).replace(/[\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g,B=>`\\u${B.charCodeAt(0).toString(16).padStart(4,"0")}`),M=E.map((U,B)=>`${B+1}. ${_(U.time)} | ${_(U.provider).slice(0,120)}`),P=await a.ui.select(l("logsSelectTitle")+(k?l("logsTruncated"):""),M),D=P===void 0?-1:M.indexOf(P);if(D<0||!await a.ui.confirm(l("logsRevealTitle"),l("logsRevealBody")))return;let v=_(E[D]);await a.ui.editor(l("logsPreviewTitle"),v.length>2e4?`${v.slice(0,2e4)}
27
- ${l("logsPreviewTruncated")}`:v)}catch(E){a.ui.notify(I(w(E,"AUDIT_IO").diagnostic),"error")}return}if(T==="reload"){await a.waitForIdle(),await a.reload();return}let S=e.lastDiagnosticText??m?.text,L=l("statusLine",{state:l(e.ready?"statusReady":"statusNotReady"),rules:z("rules",e.ruleCount),mappings:z("mappings",e.mappingCount)}),b=`
28
- ${l("statusCompaction",{mode:e.compactionMode,guard:l(h?"guardInstalled":"guardMissing")})}`,R=S?`
29
- ${l("statusLastBlock",{at:m?.at??""})}
30
- ${S}`:`
31
- ${l("statusNoBlock")}`;a.ui.notify(L+b+R,e.ready?"info":"error")}}),t.on("session_shutdown",()=>{h?.(),h=void 0,e.close()})}export{Qt as default};
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};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-information-protecter",
3
- "version": "0.14.1",
3
+ "version": "0.14.2",
4
4
  "description": "Sensitive Personal Information (SPI) Protecter — local reversible privacy redaction for Pi",
5
5
  "type": "module",
6
6
  "license": "MIT",