pi-information-protecter 0.8.2 → 0.8.3

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,14 @@
1
1
  # Changelog / 更新日志
2
2
 
3
+ ## 0.8.3 — Summarize through the model registry / 经由模型注册表生成摘要
4
+
5
+ ### Fixed / 修复
6
+
7
+ - Route summarization through `modelRegistry.streamSimple`, falling back to `complete` before Pi 0.86. Passing no stream function made the summarizer issue a bare provider call with only the resolved key, bypassing Pi's request preparation, which is what refreshes OAuth tokens and applies provider base URLs. Compaction therefore failed with `COMPACT_FAILED` on providers that need either.
8
+ 摘要改为经由 `modelRegistry.streamSimple` 发起,Pi 0.86 之前回退到 `complete`。此前不传流函数会导致摘要仅用已解析的密钥发起裸请求,绕过 Pi 的请求准备(OAuth 令牌刷新与 provider 地址由其处理),因此在需要二者的提供商上压缩以 `COMPACT_FAILED` 失败。
9
+ - Add a regression asserting a stream function is always passed, that `streamSimple` is preferred and that `complete` is used when it is absent.
10
+ 新增回归,断言始终传入流函数、优先使用 `streamSimple`、缺失时使用 `complete`。
11
+
3
12
  ## 0.8.2 — Compaction diagnostics say what happened / 压缩诊断如实说明原因
4
13
 
5
14
  ### Fixed / 修复
package/dist/index.mjs CHANGED
@@ -1,23 +1,23 @@
1
1
  /*! SPI Protecter | MIT | see LICENSE / SPI 隐私保护插件 | MIT 许可 */
2
- import{getAgentDir as ut,VERSION as dt}from"@earendil-works/pi-coding-agent";import{Worker as Qe}from"node:worker_threads";import{fileURLToPath as et}from"node:url";import*as p from"node:fs";import{join as T,resolve as He}from"node:path";import{createHash as $e,randomUUID as Je}from"node:crypto";import{Worker as We}from"node:worker_threads";import{fileURLToPath as Ye}from"node:url";var z="0.84.0-0.84.x, 0.85.1-0.87.x";function Q(o){let e=/^(\d+)\.(\d+)\.(\d+)/.exec(o);if(!e)return!1;let[r,t,n]=e.slice(1).map(Number);return r!==0?!1:t===84?!0:t===85?n>=1:t===86||t===87}var B={INTERNAL:["Unexpected local failure","Reload; check the installed package integrity"],NOT_READY:["Protection is not initialized","Run /protecter status for the initialization error, fix it, then /reload"],UNSUPPORTED_PI:["Unsupported Pi version",`Use Pi ${z}`],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_UNAVAILABLE:["No model or credentials available to summarize","Select a model and sign in to its provider, then retry"],COMPACT_FAILED:["Could not summarize the redacted conversation",'Retry; if it persists, set "compaction" to "off" and use /new'],CONFIG_COMPACTION:["Invalid compaction setting",'Use "ask", "protected" or "off"'],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"]},De={INTERNAL:["未预期的本地错误","重载并检查安装包完整性"],NOT_READY:["防护尚未初始化","查看初始化错误,修复后重载"],UNSUPPORTED_PI:["Pi 版本不受支持",`请使用 Pi ${z}`],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_UNAVAILABLE:["没有可用于生成摘要的模型或凭证","选择模型并登录对应提供商后重试"],COMPACT_FAILED:["无法对脱敏后的会话生成摘要",'请重试;若持续失败,将 "compaction" 设为 "off" 并使用 /new'],CONFIG_COMPACTION:["compaction 配置值无效",'请使用 "ask"、"protected" 或 "off"'],AUDIT_BATCH_LIMIT:["审计批次超过上限","减少单个请求的命中内容"],AUDIT_FULL:["审计日志将超过上限","检查记录后清空日志或本地归档"],AUDIT_PARTIAL:["审计日志末行不完整","本地检查或清空日志,不要上传日志"],AUDIT_LOCKED:["审计锁持续被占用","等待写入完成,全部停止后再检查残留锁"],AUDIT_UNSAFE:["审计文件不安全","使用本人普通文件且不含链接,不会绕过检查"],AUDIT_IO:["审计文件操作失败","检查错误码、权限和磁盘空间,不暴露路径或内容"]},ee={blockedHeader:"SPI Protecter blocked this request",reasonLabel:"Reason",actionLabel:"Action",detailsLabel:"Details",statusReady:"ready",statusNotReady:"not ready",statusLine:"SPI Protecter: {state}; {rules}; {mappings}. Memory snapshot; /reload to refresh.",statusLastBlock:"Last block @ {at}:",statusNoBlock:"No recorded block in this session.",statusBarRules:"SPI Protecter · {rules}",statusBarNotReady:"SPI Protecter · not ready",emptyRules:"SPI Protecter: no rules configured; edit the local machine config, then /reload.",commandDescription:"View local SPI protection records",usage:"Usage: /protecter [logs [1-100|clear]|status|reload]. Never type secrets as arguments.",logsTuiOnly:"Open the local TUI to view protection records.",logsNone:"No readable records.",logsSelectTitle:"Protection records",logsTruncated:" (limited tail)",logsRevealTitle:"Sensitive plaintext",logsRevealBody:"Reveal locally? Never share this view.",logsPreviewTitle:"Local preview; edits are discarded",logsPreviewTruncated:"[Preview truncated]",clearTitle:"Clear the current audit log?",clearBody:"Irreversible. Only this machine's log is cleared; configuration and in-memory mappings stay. Later requests may add new records.",cleared:"Audit log cleared: {bytes}.",toolBlocked:"SPI Protecter blocked tool access to the protected configuration or audit log; edit it locally.",compactAskTitle:"Compact this conversation?",compactAskBody:`Pi builds the summarization request internally and never routes it through this extension's redaction, so allowing Pi to summarize directly would send the conversation, including protected values, as plaintext.
2
+ import{getAgentDir as dt,VERSION as ft}from"@earendil-works/pi-coding-agent";import{Worker as et}from"node:worker_threads";import{fileURLToPath as tt}from"node:url";import*as g from"node:fs";import{join as T,resolve as $e}from"node:path";import{createHash as Je,randomUUID as We}from"node:crypto";import{Worker as Ye}from"node:worker_threads";import{fileURLToPath as Ke}from"node:url";var z="0.84.0-0.84.x, 0.85.1-0.87.x";function Q(n){let e=/^(\d+)\.(\d+)\.(\d+)/.exec(n);if(!e)return!1;let[r,t,o]=e.slice(1).map(Number);return r!==0?!1:t===84?!0:t===85?o>=1:t===86||t===87}var B={INTERNAL:["Unexpected local failure","Reload; check the installed package integrity"],NOT_READY:["Protection is not initialized","Run /protecter status for the initialization error, fix it, then /reload"],UNSUPPORTED_PI:["Unsupported Pi version",`Use Pi ${z}`],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_UNAVAILABLE:["No model or credentials available to summarize","Select a model and sign in to its provider, then retry"],COMPACT_FAILED:["Could not summarize the redacted conversation",'Retry; if it persists, set "compaction" to "off" and use /new'],CONFIG_COMPACTION:["Invalid compaction setting",'Use "ask", "protected" or "off"'],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"]},Pe={INTERNAL:["未预期的本地错误","重载并检查安装包完整性"],NOT_READY:["防护尚未初始化","查看初始化错误,修复后重载"],UNSUPPORTED_PI:["Pi 版本不受支持",`请使用 Pi ${z}`],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_UNAVAILABLE:["没有可用于生成摘要的模型或凭证","选择模型并登录对应提供商后重试"],COMPACT_FAILED:["无法对脱敏后的会话生成摘要",'请重试;若持续失败,将 "compaction" 设为 "off" 并使用 /new'],CONFIG_COMPACTION:["compaction 配置值无效",'请使用 "ask"、"protected" 或 "off"'],AUDIT_BATCH_LIMIT:["审计批次超过上限","减少单个请求的命中内容"],AUDIT_FULL:["审计日志将超过上限","检查记录后清空日志或本地归档"],AUDIT_PARTIAL:["审计日志末行不完整","本地检查或清空日志,不要上传日志"],AUDIT_LOCKED:["审计锁持续被占用","等待写入完成,全部停止后再检查残留锁"],AUDIT_UNSAFE:["审计文件不安全","使用本人普通文件且不含链接,不会绕过检查"],AUDIT_IO:["审计文件操作失败","检查错误码、权限和磁盘空间,不暴露路径或内容"]},ee={blockedHeader:"SPI Protecter blocked this request",reasonLabel:"Reason",actionLabel:"Action",detailsLabel:"Details",statusReady:"ready",statusNotReady:"not ready",statusLine:"SPI Protecter: {state}; {rules}; {mappings}. Memory snapshot; /reload to refresh.",statusLastBlock:"Last block @ {at}:",statusNoBlock:"No recorded block in this session.",statusBarRules:"SPI Protecter · {rules}",statusBarNotReady:"SPI Protecter · not ready",emptyRules:"SPI Protecter: no rules configured; edit the local machine config, then /reload.",commandDescription:"View local SPI protection records",usage:"Usage: /protecter [logs [1-100|clear]|status|reload]. Never type secrets as arguments.",logsTuiOnly:"Open the local TUI to view protection records.",logsNone:"No readable records.",logsSelectTitle:"Protection records",logsTruncated:" (limited tail)",logsRevealTitle:"Sensitive plaintext",logsRevealBody:"Reveal locally? Never share this view.",logsPreviewTitle:"Local preview; edits are discarded",logsPreviewTruncated:"[Preview truncated]",clearTitle:"Clear the current audit log?",clearBody:"Irreversible. Only this machine's log is cleared; configuration and in-memory mappings stay. Later requests may add new records.",cleared:"Audit log cleared: {bytes}.",toolBlocked:"SPI Protecter blocked tool access to the protected configuration or audit log; edit it locally.",compactAskTitle:"Compact this conversation?",compactAskBody:`Pi builds the summarization request internally and never routes it through this extension's redaction, so allowing Pi to summarize directly would send the conversation, including protected values, as plaintext.
3
3
 
4
4
  Allowing here does NOT do that: the text is redacted first, the summary is generated from the redacted text, and the summary is restored locally afterwards. The extra request costs tokens, and the model reasons about replacements, so the summary may describe protected values inaccurately.
5
5
 
6
- This request will not be blocked if you allow it.`,compactAllowOnce:"Allow once",compactAllowAlways:"Allow for this session",compactDenyOnce:"Deny once",compactDenyAlways:"Deny for this session",compactWorking:"SPI Protecter: summarizing redacted text…",compactDone:"SPI Protecter: compaction summary generated from redacted text.",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."},Pe={compactAskTitle:"是否压缩当前会话?",compactAskBody:`Pi 在内部构造摘要请求,不经过本扩展的脱敏环节,因此直接让 Pi 生成摘要会将会话内容(包括受保护的值)以明文发送。
6
+ This request will not be blocked if you allow it.`,compactAllowOnce:"Allow once",compactAllowAlways:"Allow for this session",compactDenyOnce:"Deny once",compactDenyAlways:"Deny for this session",compactWorking:"SPI Protecter: summarizing redacted text…",compactDone:"SPI Protecter: compaction summary generated from redacted text.",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."},Le={compactAskTitle:"是否压缩当前会话?",compactAskBody:`Pi 在内部构造摘要请求,不经过本扩展的脱敏环节,因此直接让 Pi 生成摘要会将会话内容(包括受保护的值)以明文发送。
7
7
 
8
8
  在此处允许**不会**这样做:先对文本脱敏,再用脱敏后的内容生成摘要,最后在本地还原。这次额外请求会消耗 token;且模型推理的是替换值,摘要对受保护值的描述可能不准确。
9
9
 
10
- 若选择允许,本次请求不会被拦截。`,compactAllowOnce:"允许一次",compactAllowAlways:"本会话内全部允许",compactDenyOnce:"拒绝一次",compactDenyAlways:"本会话内全部拒绝",compactWorking:"SPI Protecter:正在对脱敏内容生成摘要…",compactDone:"SPI Protecter:已基于脱敏内容生成压缩摘要。",compactAlwaysNotice:'SPI Protecter:本会话内允许压缩。如需永久生效,请在本地配置中设置 "compaction"。',compactDenyNotice:"SPI Protecter:本会话内拒绝压缩;可使用 /new 开启新会话。",blockedHeader:"SPI Protecter 已阻止该请求",reasonLabel:"原因",actionLabel:"处理",detailsLabel:"详情",statusReady:"就绪",statusNotReady:"未就绪",statusLine:"SPI Protecter:{state};{rules};{mappings}。内存快照,重载后更新。",statusLastBlock:"最近一次拦截 @ {at}:",statusNoBlock:"本会话暂无拦截记录。",statusBarRules:"SPI Protecter · {rules}",statusBarNotReady:"SPI Protecter · 未就绪",emptyRules:"SPI Protecter:尚未配置规则,请编辑本地机器配置后重载。",commandDescription:"查看本地保护记录",usage:"用法:/protecter [logs [1-100|clear]|status|reload]。不要在参数中输入敏感内容。",logsTuiOnly:"请在本地 TUI 查看保护记录。",logsNone:"暂无可读记录。",logsSelectTitle:"保护记录",logsTruncated:"(仅显示有限尾部)",logsRevealTitle:"敏感明文",logsRevealBody:"确认在本地显示?请勿分享此界面。",logsPreviewTitle:"本地预览,编辑不会保存",logsPreviewTruncated:"[预览已截断]",clearTitle:"确认清空当前审计日志?",clearBody:"不可撤销。仅清空本机日志,配置和内存映射保留;后续请求可能写入新记录。",cleared:"已清空审计日志:{bytes}。",toolBlocked:"SPI Protecter 已阻止工具访问受保护的配置或审计日志,请在本地编辑。"};function H(o=process.env){let e=o.PI_PROTECTER_LANG||o.LC_ALL||o.LC_MESSAGES||o.LANG||o.LANGUAGE||Le();return/^zh\b|^zh[-_]/i.test(e.trim())?"zh":"en"}function Le(){try{return new Intl.DateTimeFormat().resolvedOptions().locale}catch{return""}}var E=H();function re(){return E}function oe(o){E=o}function m(o,e={}){return((E==="zh"?Pe:ee)[o]??ee[o]).replace(/\{(\w+)\}/g,(t,n)=>Object.hasOwn(e,n)?String(e[n]):t)}var Me={en:{rules:{one:"{n} rule",other:"{n} rules"},mappings:{one:"{n} mapping",other:"{n} mappings"},bytes:{one:"{n} byte",other:"{n} bytes"}},zh:{rules:{other:"规则 {n} 条"},mappings:{other:"映射 {n} 个"},bytes:{other:"{n} 字节"}}},te=new Map;function R(o,e){let r=E==="zh"?"zh-CN":"en",t=te.get(E);if(!t){try{t=new Intl.PluralRules(r)}catch{t=void 0}t&&te.set(E,t)}let n=t?.select(e)??"other",c=Me[E][o],u=c[n]??c.other,d=new Intl.NumberFormat(r).format(e);return u.replace("{n}",d)}function ne(o){let r=(E==="zh"?De[o]:B[o])??B[o]??B.INTERNAL;return{reason:r[0],action:r[1]}}var ie={INTERNAL:"internal",NOT_READY:"initialization",UNSUPPORTED_PI:"initialization",MACHINE_ID:"initialization",CONFIG_JSON:"configuration",CONFIG_SCHEMA:"configuration",CONFIG_REGEX:"configuration",CONFIG_TARGET:"configuration",CONFIG_CONFLICT:"configuration",CONFIG_SIZE:"configuration",CONFIG_IO:"configuration",CONFIG_UNSAFE:"configuration",CONFIG_EMPTY_MATCH:"configuration",CONFIG_SENSITIVE_TARGET:"configuration",CONFIG_ALIAS_CONFLICT:"configuration",CONFIG_TIMEOUT:"configuration",CONFIG_COMPACTION:"configuration",MIGRATION_LOCKED:"migration",MIGRATION_CHANGED:"migration",MIGRATION_LIMIT:"migration",MIGRATION_IO:"migration",PAYLOAD_JSON:"request",PAYLOAD_SIZE:"request",SCAN_TIMEOUT:"scan",WORKER_FAILED:"worker",SCAN_INTERNAL:"scan",SCAN_NUMBER_UNSAFE:"scan",SCAN_UNIQUE_FAILED:"scan",SCAN_ZERO_WIDTH:"scan",SCAN_MATCH_LIMIT:"scan",SCAN_MAPPING_LIMIT:"scan",FIXED_MAPPING_CONFLICT:"scan",FIXED_ALIAS_REUSED:"scan",FIXED_SENSITIVE_TARGET:"scan",FIXED_OVERLAP:"scan",FIXED_ALIAS_CROSSING:"scan",SCAN_COMPLEXITY:"scan",SCAN_JSON_REWRITE:"scan",SCAN_ATTACHMENT:"scan",SCAN_KEY_COLLISION:"scan",RESTORE_COMPLEXITY:"restore",RESTORE_KEY_COLLISION:"restore",COMPACT_DENIED:"compaction",COMPACT_UNAVAILABLE:"compaction",COMPACT_FAILED:"compaction",AUDIT_BATCH_LIMIT:"audit",AUDIT_FULL:"audit",AUDIT_PARTIAL:"audit",AUDIT_LOCKED:"audit",AUDIT_UNSAFE:"audit",AUDIT_IO:"audit"};var se=["rule","otherRule","node","bytes","limit","timeoutMs"],Fe=/^(EACCES|EPERM|ENOENT|ENOSPC|EDQUOT|EROFS|ELOOP|EISDIR|ENOTDIR|EMFILE|ENFILE|EIO|EEXIST|EBADF|EBUSY|ENOTEMPTY)$/;function ke(o,e={}){let{reason:r,action:t}=ne(o),n={};for(let c of se){let u=e[c];typeof u=="number"&&Number.isSafeInteger(u)&&u>=0&&(n[c]=u)}return typeof e.errno=="string"&&Fe.test(e.errno)&&(n.errno=e.errno),{code:o,stage:ie[o],reason:r,action:t,...n}}function S(o){let e=re()==="zh"?":":": ",r=[...se,"errno"].filter(t=>o[t]!==void 0).map(t=>`${t}=${o[t]}`).join(" ");return[m("blockedHeader"),`code=${o.code} stage=${o.stage}${r?` ${r}`:""}`,`${m("reasonLabel")}${e}${o.reason}`,`${m("actionLabel")}${e}${o.action}`,`${m("detailsLabel")}${e}/protecter status`].join(`
11
- `)}var C=class extends Error{diagnostic;constructor(e,r={}){let t=ke(e,r);super(S(t)),this.name="ProtectionError",this.diagnostic=t}};function s(o,e={}){return new C(o,e)}function y(o,e,r={}){if(o instanceof C)return s(o.diagnostic.code,{...o.diagnostic,...r});let t=o&&typeof o=="object"&&"code"in o?o.code:void 0;return s(e,{...r,errno:typeof t=="string"?t:void 0})}function M(o,e){if(!o||typeof o!="object")return s(e);let r=o,t=typeof r.code=="string"&&Object.hasOwn(ie,r.code)?r.code:e;return s(t,r)}import{constants as _,closeSync as ae,fchmodSync as be,fstatSync as xe,mkdirSync as Ge,openSync as ce,readFileSync as ve,writeFileSync as Ue}from"node:fs";import{dirname as ze}from"node:path";var Be=["ask","protected","off"],$={version:1,sensitiveWords:[]},le="ask";function J(o){let e;try{e=JSON.parse(o)}catch{throw s("CONFIG_JSON")}let r=0;try{if(!e||e.version!==1||!Array.isArray(e.sensitiveWords)||Object.keys(e).some(n=>!["version","sensitiveWords","compaction"].includes(n)))throw s("CONFIG_SCHEMA");if(Object.hasOwn(e,"compaction")&&!Be.includes(e.compaction))throw s("CONFIG_COMPACTION");if(e.sensitiveWords.length>1e3)throw s("CONFIG_SIZE",{limit:1e3});let t=new Map;for(let n of e.sensitiveWords){if(r++,typeof n=="string"){if(!n||n.length>8192)throw s("CONFIG_SCHEMA",{rule:r,limit:8192});let u=JSON.stringify(["literal",n]);if(t.has(u)&&t.get(u)!==void 0)throw s("CONFIG_CONFLICT",{rule:r});t.set(u,void 0);continue}if(!n||typeof n!="object")throw s("CONFIG_SCHEMA",{rule:r});if(Object.hasOwn(n,"replacement")&&(typeof n.replacement!="string"||!n.replacement.trim()||n.replacement.length>8192||n.replacement.includes("__PIP_")))throw s("CONFIG_TARGET",{rule:r,limit:8192});if(n.type==="literal"){if(Object.keys(n).some(u=>!["type","value","replacement"].includes(u))||typeof n.value!="string"||!n.value||n.value.length>8192)throw s("CONFIG_SCHEMA",{rule:r,limit:8192})}else if(n.type==="regex"){if(Object.keys(n).some(u=>!["type","pattern","flags","replacement"].includes(u))||typeof n.pattern!="string"||!n.pattern||n.pattern.length>8192||n.flags!==void 0&&(typeof n.flags!="string"||!/^[gimsu]*$/.test(n.flags)))throw s("CONFIG_REGEX",{rule:r,limit:8192});try{new RegExp(n.pattern,n.flags??"")}catch{throw s("CONFIG_REGEX",{rule:r})}}else throw s("CONFIG_SCHEMA",{rule:r});let c=n.type==="literal"?JSON.stringify(["literal",n.value]):JSON.stringify(["regex",n.pattern,[...new Set((n.flags??"")+"g")].sort().join("")]);if(t.has(c)&&t.get(c)!==n.replacement)throw s("CONFIG_CONFLICT",{rule:r});t.set(c,n.replacement)}return e}catch(t){throw t instanceof C?t:s("CONFIG_SCHEMA",{rule:r})}}function ue(o,e=!1){let r;try{if(e){Ge(ze(o),{recursive:!0,mode:448});try{let c=ce(o,_.O_WRONLY|_.O_CREAT|_.O_EXCL,384);try{Ue(c,JSON.stringify($,null,2)+`
12
- `)}finally{ae(c)}}catch(c){if(c.code!=="EEXIST")throw y(c,"CONFIG_IO")}}r=ce(o,_.O_RDONLY|_.O_NOFOLLOW|_.O_NONBLOCK);let t=xe(r);if(t.size>1024*1024)throw s("CONFIG_SIZE",{bytes:t.size,limit:1024*1024});if(!t.isFile()||t.nlink!==1||process.getuid&&t.uid!==process.getuid())throw s("CONFIG_UNSAFE");process.platform!=="win32"&&be(r,384);let n=ve(r,"utf8");if(Buffer.byteLength(n)>1024*1024)throw s("CONFIG_SIZE",{bytes:Buffer.byteLength(n),limit:1024*1024});return{config:J(n),raw:n}}catch(t){let n=t&&typeof t=="object"&&"code"in t?t.code:void 0;throw y(t,n==="ELOOP"||n==="EISDIR"||n==="ENOTDIR"?"CONFIG_UNSAFE":"CONFIG_IO")}finally{r!==void 0&&ae(r)}}var Y=/^protecter(?:\.[a-f0-9]{32})?\.json$/;function Ke(o){return new Promise((e,r)=>{let t=new We(Ye(new URL("./validate-worker.mjs",import.meta.url)),{workerData:o,execArgv:[],resourceLimits:{maxOldGenerationSizeMb:64}}),n=!1,c=(d,a=s("WORKER_FAILED"))=>{n||(n=!0,clearTimeout(u),t.terminate(),d?e():r(a))},u=setTimeout(()=>c(!1,s("CONFIG_TIMEOUT",{timeoutMs:2e3})),2e3);t.once("message",d=>d===!0?c(!0):c(!1,M(d,"CONFIG_SCHEMA"))),t.once("error",()=>c(!1)),t.once("exit",()=>c(!1))})}function je(o){let e=new Set,r=[];for(let a of o)for(let i of a.sensitiveWords){let l=typeof i=="string"?JSON.stringify(["literal",i,null]):i.type==="literal"?JSON.stringify(["literal",i.value,i.replacement??null]):JSON.stringify(["regex",i.pattern,[...new Set((i.flags??"")+"g")].sort().join(""),i.replacement??null]);e.has(l)||(e.add(l),r.push(i))}let t=o.map(a=>a.compaction),c=["off","ask","protected"].find(a=>t.includes(a)),u={version:1,sensitiveWords:r};c!==void 0&&(u.compaction=c);let d=JSON.stringify(u);if(Buffer.byteLength(d)>1024*1024)throw s("CONFIG_SIZE",{bytes:Buffer.byteLength(d),limit:1024*1024});return J(d)}function de(o){let e;try{e=p.lstatSync(o,{bigint:!0})}catch(r){throw y(r,"CONFIG_IO")}if(!e.isFile()||e.nlink!==1n||process.getuid&&e.uid!==BigInt(process.getuid()))throw s("CONFIG_UNSAFE");return`${e.dev}:${e.ino}:${e.size}:${e.mtimeNs}`}function W(o,e){let r=T(o,e),t=de(r),n=ue(r);if(de(r)!==t)throw s("MIGRATION_CHANGED");return{name:e,...n,identity:t,digest:$e("sha256").update(n.raw).digest("hex")}}function D(o,e){let r=W(o,e.name);if(r.identity!==e.identity||r.digest!==e.digest)throw s("MIGRATION_CHANGED")}function F(o){return p.readdirSync(o).filter(e=>Y.test(e)).sort()}function fe(o){if(process.platform==="win32")return;let e=p.openSync(o,p.constants.O_RDONLY);try{p.fsyncSync(e)}finally{p.closeSync(e)}}async function me(o,e,r={}){if(!/^[a-f0-9]{32}$/.test(e))throw s("MACHINE_ID");let t=He(o),n=`protecter.${e}.json`,c=T(t,n);p.mkdirSync(t,{recursive:!0,mode:448});let u=T(t,".protecter-migration.lock"),d=Date.now()+(r.lockTimeoutMs??5e3);for(;;)try{p.mkdirSync(u,{mode:448});break}catch(i){if(i.code!=="EEXIST")throw y(i,"MIGRATION_IO");if(Date.now()>=d)throw s("MIGRATION_LOCKED",{timeoutMs:r.lockTimeoutMs??5e3});await new Promise(l=>setTimeout(l,50))}let a;try{let i=F(t);if(i.length>64)throw s("MIGRATION_LIMIT",{limit:64});let f=[...i].sort((O,w)=>O===n?-1:w===n?1:O.localeCompare(w)).map(O=>W(t,O)),h=je(f.length?f.map(O=>O.config):[$]);if(await Ke([h]),f.length===1&&f[0].name===n){if(D(t,f[0]),JSON.stringify(F(t))!==JSON.stringify(i))throw s("MIGRATION_CHANGED");return{path:c,config:f[0].config,raw:f[0].raw,sourceRaws:[f[0].raw],migrated:0}}let I=JSON.stringify(h,null,2)+`
13
- `;if(Buffer.byteLength(I)>1024*1024)throw s("CONFIG_SIZE",{bytes:Buffer.byteLength(I),limit:1024*1024});a=T(t,`.protecter-migration.${Je()}.tmp`);let A=p.openSync(a,p.constants.O_WRONLY|p.constants.O_CREAT|p.constants.O_EXCL,384);try{p.writeFileSync(A,I),p.fsyncSync(A)}finally{p.closeSync(A)}if(r.checkpoint?.("beforeCommit",c),JSON.stringify(F(t))!==JSON.stringify(i))throw s("MIGRATION_CHANGED");for(let O of f)D(t,O);p.renameSync(a,c),a=void 0,fe(t);let N=W(t,n);if(N.raw!==I)throw s("MIGRATION_CHANGED");r.checkpoint?.("afterCommit",c);for(let O of f)O.name!==n&&(r.checkpoint?.("beforeDelete",T(t,O.name)),D(t,N),D(t,O),p.unlinkSync(T(t,O.name)));fe(t);let G=[n];if(JSON.stringify(F(t))!==JSON.stringify(G))throw s("MIGRATION_CHANGED");return D(t,N),{path:c,config:h,raw:I,sourceRaws:[...new Set([...f.map(O=>O.raw),I])],migrated:f.filter(O=>O.name!==n).length}}catch(i){throw i instanceof C?i:y(i,"MIGRATION_IO")}finally{if(a)try{p.unlinkSync(a)}catch{}p.rmdirSync(u)}}import{createHash as Xe}from"node:crypto";import{readFileSync as qe}from"node:fs";import{execFileSync as ge}from"node:child_process";function K(o){let e=o.trim().toLowerCase().replace(/-/g,"");if(!/^[a-f0-9]{32}$/.test(e)||/^0+$/.test(e))throw s("MACHINE_ID");return Xe("sha256").update(`pi-information-protecter:v1:${e}`).digest("hex").slice(0,32)}function pe(){try{if(process.platform==="linux")return K(qe("/etc/machine-id","utf8"));if(process.platform==="darwin"){let o=ge("/usr/sbin/ioreg",["-rd1","-c","IOPlatformExpertDevice"],{encoding:"utf8",timeout:5e3,maxBuffer:1048576,stdio:["ignore","pipe","pipe"]});return K(o.match(/"IOPlatformUUID"\s*=\s*"([a-fA-F0-9-]+)"/)?.[1]??"")}if(process.platform==="win32"){let o=ge("reg.exe",["query","HKLM\\SOFTWARE\\Microsoft\\Cryptography","/v","MachineGuid","/reg:64"],{encoding:"utf8",timeout:5e3,maxBuffer:65536,stdio:["ignore","pipe","pipe"]});return K(o.match(/MachineGuid\s+REG_SZ\s+([a-fA-F0-9-]+)/i)?.[1]??"")}}catch{}throw s("MACHINE_ID")}import*as g from"node:fs";import{randomUUID as Ve}from"node:crypto";var he=32*1024*1024,ye=8*1024*1024;function Ze(o){let e=r=>String(r).padStart(2,"0");return`${o.getFullYear()}-${e(o.getMonth()+1)}-${e(o.getDate())} ${e(o.getHours())}:${e(o.getMinutes())}:${e(o.getSeconds())}`}function j(o,e,r=e){let t=g.openSync(o,(e?g.constants.O_RDWR|(r?g.constants.O_CREAT:0):g.constants.O_RDONLY)|g.constants.O_NOFOLLOW|g.constants.O_NONBLOCK,384);try{let n=g.fstatSync(t);if(!n.isFile()||n.nlink!==1||process.getuid&&n.uid!==process.getuid())throw s("AUDIT_UNSAFE");return process.platform!=="win32"&&g.fchmodSync(t,384),t}catch(n){throw g.closeSync(t),y(n,"AUDIT_UNSAFE")}}function k(o){let e=o&&typeof o=="object"&&"code"in o?o.code:void 0;return y(o,e==="ELOOP"||e==="EISDIR"||e==="ENOTDIR"?"AUDIT_UNSAFE":"AUDIT_IO")}async function Ie(o){let e=`${o}.lock`,r=Date.now()+2e3;for(;;)try{return g.mkdirSync(e,{mode:448}),e}catch(t){if(t.code!=="EEXIST")throw y(t,"AUDIT_IO");if(Date.now()>=r)throw s("AUDIT_LOCKED",{timeoutMs:2e3});await new Promise(n=>setTimeout(n,25))}}async function Oe(o){let e=await Ie(o),r;try{try{r=j(o,!0,!1)}catch(n){if(n.code==="ENOENT")return 0;throw n}let t=g.fstatSync(r).size;return g.ftruncateSync(r,0),g.fsyncSync(r),t}catch(t){throw k(t)}finally{try{r!==void 0&&g.closeSync(r)}finally{g.rmdirSync(e)}}}async function Ae(o,e,r){if(!r.length)return;let t=new Date,n=Ve(),c=Buffer.from(r.map(([a,i])=>JSON.stringify({version:1,time:Ze(t),timezoneOffset:-t.getTimezoneOffset(),requestId:n,provider:e||"unknown",original:i,replacement:a})).join(`
10
+ 若选择允许,本次请求不会被拦截。`,compactAllowOnce:"允许一次",compactAllowAlways:"本会话内全部允许",compactDenyOnce:"拒绝一次",compactDenyAlways:"本会话内全部拒绝",compactWorking:"SPI Protecter:正在对脱敏内容生成摘要…",compactDone:"SPI Protecter:已基于脱敏内容生成压缩摘要。",compactAlwaysNotice:'SPI Protecter:本会话内允许压缩。如需永久生效,请在本地配置中设置 "compaction"。',compactDenyNotice:"SPI Protecter:本会话内拒绝压缩;可使用 /new 开启新会话。",blockedHeader:"SPI Protecter 已阻止该请求",reasonLabel:"原因",actionLabel:"处理",detailsLabel:"详情",statusReady:"就绪",statusNotReady:"未就绪",statusLine:"SPI Protecter:{state};{rules};{mappings}。内存快照,重载后更新。",statusLastBlock:"最近一次拦截 @ {at}:",statusNoBlock:"本会话暂无拦截记录。",statusBarRules:"SPI Protecter · {rules}",statusBarNotReady:"SPI Protecter · 未就绪",emptyRules:"SPI Protecter:尚未配置规则,请编辑本地机器配置后重载。",commandDescription:"查看本地保护记录",usage:"用法:/protecter [logs [1-100|clear]|status|reload]。不要在参数中输入敏感内容。",logsTuiOnly:"请在本地 TUI 查看保护记录。",logsNone:"暂无可读记录。",logsSelectTitle:"保护记录",logsTruncated:"(仅显示有限尾部)",logsRevealTitle:"敏感明文",logsRevealBody:"确认在本地显示?请勿分享此界面。",logsPreviewTitle:"本地预览,编辑不会保存",logsPreviewTruncated:"[预览已截断]",clearTitle:"确认清空当前审计日志?",clearBody:"不可撤销。仅清空本机日志,配置和内存映射保留;后续请求可能写入新记录。",cleared:"已清空审计日志:{bytes}。",toolBlocked:"SPI Protecter 已阻止工具访问受保护的配置或审计日志,请在本地编辑。"};function H(n=process.env){let e=n.PI_PROTECTER_LANG||n.LC_ALL||n.LC_MESSAGES||n.LANG||n.LANGUAGE||ke();return/^zh\b|^zh[-_]/i.test(e.trim())?"zh":"en"}function ke(){try{return new Intl.DateTimeFormat().resolvedOptions().locale}catch{return""}}var E=H();function re(){return E}function ne(n){E=n}function m(n,e={}){return((E==="zh"?Le:ee)[n]??ee[n]).replace(/\{(\w+)\}/g,(t,o)=>Object.hasOwn(e,o)?String(e[o]):t)}var Me={en:{rules:{one:"{n} rule",other:"{n} rules"},mappings:{one:"{n} mapping",other:"{n} mappings"},bytes:{one:"{n} byte",other:"{n} bytes"}},zh:{rules:{other:"规则 {n} 条"},mappings:{other:"映射 {n} 个"},bytes:{other:"{n} 字节"}}},te=new Map;function R(n,e){let r=E==="zh"?"zh-CN":"en",t=te.get(E);if(!t){try{t=new Intl.PluralRules(r)}catch{t=void 0}t&&te.set(E,t)}let o=t?.select(e)??"other",c=Me[E][n],u=c[o]??c.other,d=new Intl.NumberFormat(r).format(e);return u.replace("{n}",d)}function oe(n){let r=(E==="zh"?Pe[n]:B[n])??B[n]??B.INTERNAL;return{reason:r[0],action:r[1]}}var ie={INTERNAL:"internal",NOT_READY:"initialization",UNSUPPORTED_PI:"initialization",MACHINE_ID:"initialization",CONFIG_JSON:"configuration",CONFIG_SCHEMA:"configuration",CONFIG_REGEX:"configuration",CONFIG_TARGET:"configuration",CONFIG_CONFLICT:"configuration",CONFIG_SIZE:"configuration",CONFIG_IO:"configuration",CONFIG_UNSAFE:"configuration",CONFIG_EMPTY_MATCH:"configuration",CONFIG_SENSITIVE_TARGET:"configuration",CONFIG_ALIAS_CONFLICT:"configuration",CONFIG_TIMEOUT:"configuration",CONFIG_COMPACTION:"configuration",MIGRATION_LOCKED:"migration",MIGRATION_CHANGED:"migration",MIGRATION_LIMIT:"migration",MIGRATION_IO:"migration",PAYLOAD_JSON:"request",PAYLOAD_SIZE:"request",SCAN_TIMEOUT:"scan",WORKER_FAILED:"worker",SCAN_INTERNAL:"scan",SCAN_NUMBER_UNSAFE:"scan",SCAN_UNIQUE_FAILED:"scan",SCAN_ZERO_WIDTH:"scan",SCAN_MATCH_LIMIT:"scan",SCAN_MAPPING_LIMIT:"scan",FIXED_MAPPING_CONFLICT:"scan",FIXED_ALIAS_REUSED:"scan",FIXED_SENSITIVE_TARGET:"scan",FIXED_OVERLAP:"scan",FIXED_ALIAS_CROSSING:"scan",SCAN_COMPLEXITY:"scan",SCAN_JSON_REWRITE:"scan",SCAN_ATTACHMENT:"scan",SCAN_KEY_COLLISION:"scan",RESTORE_COMPLEXITY:"restore",RESTORE_KEY_COLLISION:"restore",COMPACT_DENIED:"compaction",COMPACT_UNAVAILABLE:"compaction",COMPACT_FAILED:"compaction",AUDIT_BATCH_LIMIT:"audit",AUDIT_FULL:"audit",AUDIT_PARTIAL:"audit",AUDIT_LOCKED:"audit",AUDIT_UNSAFE:"audit",AUDIT_IO:"audit"};var se=["rule","otherRule","node","bytes","limit","timeoutMs"],Fe=/^(EACCES|EPERM|ENOENT|ENOSPC|EDQUOT|EROFS|ELOOP|EISDIR|ENOTDIR|EMFILE|ENFILE|EIO|EEXIST|EBADF|EBUSY|ENOTEMPTY)$/;function be(n,e={}){let{reason:r,action:t}=oe(n),o={};for(let c of se){let u=e[c];typeof u=="number"&&Number.isSafeInteger(u)&&u>=0&&(o[c]=u)}return typeof e.errno=="string"&&Fe.test(e.errno)&&(o.errno=e.errno),{code:n,stage:ie[n],reason:r,action:t,...o}}function S(n){let e=re()==="zh"?":":": ",r=[...se,"errno"].filter(t=>n[t]!==void 0).map(t=>`${t}=${n[t]}`).join(" ");return[m("blockedHeader"),`code=${n.code} stage=${n.stage}${r?` ${r}`:""}`,`${m("reasonLabel")}${e}${n.reason}`,`${m("actionLabel")}${e}${n.action}`,`${m("detailsLabel")}${e}/protecter status`].join(`
11
+ `)}var C=class extends Error{diagnostic;constructor(e,r={}){let t=be(e,r);super(S(t)),this.name="ProtectionError",this.diagnostic=t}};function s(n,e={}){return new C(n,e)}function y(n,e,r={}){if(n instanceof C)return s(n.diagnostic.code,{...n.diagnostic,...r});let t=n&&typeof n=="object"&&"code"in n?n.code:void 0;return s(e,{...r,errno:typeof t=="string"?t:void 0})}function k(n,e){if(!n||typeof n!="object")return s(e);let r=n,t=typeof r.code=="string"&&Object.hasOwn(ie,r.code)?r.code:e;return s(t,r)}import{constants as _,closeSync as ae,fchmodSync as xe,fstatSync as Ge,mkdirSync as ve,openSync as ce,readFileSync as Ue,writeFileSync as ze}from"node:fs";import{dirname as Be}from"node:path";var He=["ask","protected","off"],$={version:1,sensitiveWords:[]},le="ask";function J(n){let e;try{e=JSON.parse(n)}catch{throw s("CONFIG_JSON")}let r=0;try{if(!e||e.version!==1||!Array.isArray(e.sensitiveWords)||Object.keys(e).some(o=>!["version","sensitiveWords","compaction"].includes(o)))throw s("CONFIG_SCHEMA");if(Object.hasOwn(e,"compaction")&&!He.includes(e.compaction))throw s("CONFIG_COMPACTION");if(e.sensitiveWords.length>1e3)throw s("CONFIG_SIZE",{limit:1e3});let t=new Map;for(let o of e.sensitiveWords){if(r++,typeof o=="string"){if(!o||o.length>8192)throw s("CONFIG_SCHEMA",{rule:r,limit:8192});let u=JSON.stringify(["literal",o]);if(t.has(u)&&t.get(u)!==void 0)throw s("CONFIG_CONFLICT",{rule:r});t.set(u,void 0);continue}if(!o||typeof o!="object")throw s("CONFIG_SCHEMA",{rule:r});if(Object.hasOwn(o,"replacement")&&(typeof o.replacement!="string"||!o.replacement.trim()||o.replacement.length>8192||o.replacement.includes("__PIP_")))throw s("CONFIG_TARGET",{rule:r,limit:8192});if(o.type==="literal"){if(Object.keys(o).some(u=>!["type","value","replacement"].includes(u))||typeof o.value!="string"||!o.value||o.value.length>8192)throw s("CONFIG_SCHEMA",{rule:r,limit:8192})}else if(o.type==="regex"){if(Object.keys(o).some(u=>!["type","pattern","flags","replacement"].includes(u))||typeof o.pattern!="string"||!o.pattern||o.pattern.length>8192||o.flags!==void 0&&(typeof o.flags!="string"||!/^[gimsu]*$/.test(o.flags)))throw s("CONFIG_REGEX",{rule:r,limit:8192});try{new RegExp(o.pattern,o.flags??"")}catch{throw s("CONFIG_REGEX",{rule:r})}}else throw s("CONFIG_SCHEMA",{rule:r});let c=o.type==="literal"?JSON.stringify(["literal",o.value]):JSON.stringify(["regex",o.pattern,[...new Set((o.flags??"")+"g")].sort().join("")]);if(t.has(c)&&t.get(c)!==o.replacement)throw s("CONFIG_CONFLICT",{rule:r});t.set(c,o.replacement)}return e}catch(t){throw t instanceof C?t:s("CONFIG_SCHEMA",{rule:r})}}function ue(n,e=!1){let r;try{if(e){ve(Be(n),{recursive:!0,mode:448});try{let c=ce(n,_.O_WRONLY|_.O_CREAT|_.O_EXCL,384);try{ze(c,JSON.stringify($,null,2)+`
12
+ `)}finally{ae(c)}}catch(c){if(c.code!=="EEXIST")throw y(c,"CONFIG_IO")}}r=ce(n,_.O_RDONLY|_.O_NOFOLLOW|_.O_NONBLOCK);let t=Ge(r);if(t.size>1024*1024)throw s("CONFIG_SIZE",{bytes:t.size,limit:1024*1024});if(!t.isFile()||t.nlink!==1||process.getuid&&t.uid!==process.getuid())throw s("CONFIG_UNSAFE");process.platform!=="win32"&&xe(r,384);let o=Ue(r,"utf8");if(Buffer.byteLength(o)>1024*1024)throw s("CONFIG_SIZE",{bytes:Buffer.byteLength(o),limit:1024*1024});return{config:J(o),raw:o}}catch(t){let o=t&&typeof t=="object"&&"code"in t?t.code:void 0;throw y(t,o==="ELOOP"||o==="EISDIR"||o==="ENOTDIR"?"CONFIG_UNSAFE":"CONFIG_IO")}finally{r!==void 0&&ae(r)}}var Y=/^protecter(?:\.[a-f0-9]{32})?\.json$/;function je(n){return new Promise((e,r)=>{let t=new Ye(Ke(new URL("./validate-worker.mjs",import.meta.url)),{workerData:n,execArgv:[],resourceLimits:{maxOldGenerationSizeMb:64}}),o=!1,c=(d,a=s("WORKER_FAILED"))=>{o||(o=!0,clearTimeout(u),t.terminate(),d?e():r(a))},u=setTimeout(()=>c(!1,s("CONFIG_TIMEOUT",{timeoutMs:2e3})),2e3);t.once("message",d=>d===!0?c(!0):c(!1,k(d,"CONFIG_SCHEMA"))),t.once("error",()=>c(!1)),t.once("exit",()=>c(!1))})}function Xe(n){let e=new Set,r=[];for(let a of n)for(let i of a.sensitiveWords){let l=typeof i=="string"?JSON.stringify(["literal",i,null]):i.type==="literal"?JSON.stringify(["literal",i.value,i.replacement??null]):JSON.stringify(["regex",i.pattern,[...new Set((i.flags??"")+"g")].sort().join(""),i.replacement??null]);e.has(l)||(e.add(l),r.push(i))}let t=n.map(a=>a.compaction),c=["off","ask","protected"].find(a=>t.includes(a)),u={version:1,sensitiveWords:r};c!==void 0&&(u.compaction=c);let d=JSON.stringify(u);if(Buffer.byteLength(d)>1024*1024)throw s("CONFIG_SIZE",{bytes:Buffer.byteLength(d),limit:1024*1024});return J(d)}function de(n){let e;try{e=g.lstatSync(n,{bigint:!0})}catch(r){throw y(r,"CONFIG_IO")}if(!e.isFile()||e.nlink!==1n||process.getuid&&e.uid!==BigInt(process.getuid()))throw s("CONFIG_UNSAFE");return`${e.dev}:${e.ino}:${e.size}:${e.mtimeNs}`}function W(n,e){let r=T(n,e),t=de(r),o=ue(r);if(de(r)!==t)throw s("MIGRATION_CHANGED");return{name:e,...o,identity:t,digest:Je("sha256").update(o.raw).digest("hex")}}function D(n,e){let r=W(n,e.name);if(r.identity!==e.identity||r.digest!==e.digest)throw s("MIGRATION_CHANGED")}function M(n){return g.readdirSync(n).filter(e=>Y.test(e)).sort()}function fe(n){if(process.platform==="win32")return;let e=g.openSync(n,g.constants.O_RDONLY);try{g.fsyncSync(e)}finally{g.closeSync(e)}}async function me(n,e,r={}){if(!/^[a-f0-9]{32}$/.test(e))throw s("MACHINE_ID");let t=$e(n),o=`protecter.${e}.json`,c=T(t,o);g.mkdirSync(t,{recursive:!0,mode:448});let u=T(t,".protecter-migration.lock"),d=Date.now()+(r.lockTimeoutMs??5e3);for(;;)try{g.mkdirSync(u,{mode:448});break}catch(i){if(i.code!=="EEXIST")throw y(i,"MIGRATION_IO");if(Date.now()>=d)throw s("MIGRATION_LOCKED",{timeoutMs:r.lockTimeoutMs??5e3});await new Promise(l=>setTimeout(l,50))}let a;try{let i=M(t);if(i.length>64)throw s("MIGRATION_LIMIT",{limit:64});let f=[...i].sort((O,w)=>O===o?-1:w===o?1:O.localeCompare(w)).map(O=>W(t,O)),h=Xe(f.length?f.map(O=>O.config):[$]);if(await je([h]),f.length===1&&f[0].name===o){if(D(t,f[0]),JSON.stringify(M(t))!==JSON.stringify(i))throw s("MIGRATION_CHANGED");return{path:c,config:f[0].config,raw:f[0].raw,sourceRaws:[f[0].raw],migrated:0}}let I=JSON.stringify(h,null,2)+`
13
+ `;if(Buffer.byteLength(I)>1024*1024)throw s("CONFIG_SIZE",{bytes:Buffer.byteLength(I),limit:1024*1024});a=T(t,`.protecter-migration.${We()}.tmp`);let A=g.openSync(a,g.constants.O_WRONLY|g.constants.O_CREAT|g.constants.O_EXCL,384);try{g.writeFileSync(A,I),g.fsyncSync(A)}finally{g.closeSync(A)}if(r.checkpoint?.("beforeCommit",c),JSON.stringify(M(t))!==JSON.stringify(i))throw s("MIGRATION_CHANGED");for(let O of f)D(t,O);g.renameSync(a,c),a=void 0,fe(t);let N=W(t,o);if(N.raw!==I)throw s("MIGRATION_CHANGED");r.checkpoint?.("afterCommit",c);for(let O of f)O.name!==o&&(r.checkpoint?.("beforeDelete",T(t,O.name)),D(t,N),D(t,O),g.unlinkSync(T(t,O.name)));fe(t);let G=[o];if(JSON.stringify(M(t))!==JSON.stringify(G))throw s("MIGRATION_CHANGED");return D(t,N),{path:c,config:h,raw:I,sourceRaws:[...new Set([...f.map(O=>O.raw),I])],migrated:f.filter(O=>O.name!==o).length}}catch(i){throw i instanceof C?i:y(i,"MIGRATION_IO")}finally{if(a)try{g.unlinkSync(a)}catch{}g.rmdirSync(u)}}import{createHash as qe}from"node:crypto";import{readFileSync as Ve}from"node:fs";import{execFileSync as pe}from"node:child_process";function K(n){let e=n.trim().toLowerCase().replace(/-/g,"");if(!/^[a-f0-9]{32}$/.test(e)||/^0+$/.test(e))throw s("MACHINE_ID");return qe("sha256").update(`pi-information-protecter:v1:${e}`).digest("hex").slice(0,32)}function ge(){try{if(process.platform==="linux")return K(Ve("/etc/machine-id","utf8"));if(process.platform==="darwin"){let n=pe("/usr/sbin/ioreg",["-rd1","-c","IOPlatformExpertDevice"],{encoding:"utf8",timeout:5e3,maxBuffer:1048576,stdio:["ignore","pipe","pipe"]});return K(n.match(/"IOPlatformUUID"\s*=\s*"([a-fA-F0-9-]+)"/)?.[1]??"")}if(process.platform==="win32"){let n=pe("reg.exe",["query","HKLM\\SOFTWARE\\Microsoft\\Cryptography","/v","MachineGuid","/reg:64"],{encoding:"utf8",timeout:5e3,maxBuffer:65536,stdio:["ignore","pipe","pipe"]});return K(n.match(/MachineGuid\s+REG_SZ\s+([a-fA-F0-9-]+)/i)?.[1]??"")}}catch{}throw s("MACHINE_ID")}import*as p from"node:fs";import{randomUUID as Ze}from"node:crypto";var he=32*1024*1024,ye=8*1024*1024;function Qe(n){let e=r=>String(r).padStart(2,"0");return`${n.getFullYear()}-${e(n.getMonth()+1)}-${e(n.getDate())} ${e(n.getHours())}:${e(n.getMinutes())}:${e(n.getSeconds())}`}function j(n,e,r=e){let t=p.openSync(n,(e?p.constants.O_RDWR|(r?p.constants.O_CREAT:0):p.constants.O_RDONLY)|p.constants.O_NOFOLLOW|p.constants.O_NONBLOCK,384);try{let o=p.fstatSync(t);if(!o.isFile()||o.nlink!==1||process.getuid&&o.uid!==process.getuid())throw s("AUDIT_UNSAFE");return process.platform!=="win32"&&p.fchmodSync(t,384),t}catch(o){throw p.closeSync(t),y(o,"AUDIT_UNSAFE")}}function F(n){let e=n&&typeof n=="object"&&"code"in n?n.code:void 0;return y(n,e==="ELOOP"||e==="EISDIR"||e==="ENOTDIR"?"AUDIT_UNSAFE":"AUDIT_IO")}async function Ie(n){let e=`${n}.lock`,r=Date.now()+2e3;for(;;)try{return p.mkdirSync(e,{mode:448}),e}catch(t){if(t.code!=="EEXIST")throw y(t,"AUDIT_IO");if(Date.now()>=r)throw s("AUDIT_LOCKED",{timeoutMs:2e3});await new Promise(o=>setTimeout(o,25))}}async function Oe(n){let e=await Ie(n),r;try{try{r=j(n,!0,!1)}catch(o){if(o.code==="ENOENT")return 0;throw o}let t=p.fstatSync(r).size;return p.ftruncateSync(r,0),p.fsyncSync(r),t}catch(t){throw F(t)}finally{try{r!==void 0&&p.closeSync(r)}finally{p.rmdirSync(e)}}}async function Ae(n,e,r){if(!r.length)return;let t=new Date,o=Ze(),c=Buffer.from(r.map(([a,i])=>JSON.stringify({version:1,time:Qe(t),timezoneOffset:-t.getTimezoneOffset(),requestId:o,provider:e||"unknown",original:i,replacement:a})).join(`
14
14
  `)+`
15
- `);if(c.length>ye)throw s("AUDIT_BATCH_LIMIT",{bytes:c.length,limit:ye});let u=await Ie(o),d;try{d=j(o,!0);let a=g.fstatSync(d).size;if(a+c.length>he)throw s("AUDIT_FULL",{bytes:a+c.length,limit:he});if(a){let i=Buffer.alloc(1);if(g.readSync(d,i,0,1,a-1),i[0]!==10)throw s("AUDIT_PARTIAL")}try{let i=0;for(;i<c.length;){let l=g.writeSync(d,c,i,c.length-i,a+i);if(!l)throw s("AUDIT_IO");i+=l}g.fsyncSync(d)}catch(i){throw g.ftruncateSync(d,a),g.fsyncSync(d),k(i)}}catch(a){throw k(a)}finally{d!==void 0&&g.closeSync(d),g.rmdirSync(u)}}function Ne(o,e=20){if(!Number.isInteger(e)||e<1||e>100)throw s("INTERNAL",{limit:100});let r;try{try{r=j(o,!1)}catch(h){if(h.code==="ENOENT")return{records:[],truncated:!1};throw h}let t=g.fstatSync(r).size,n=Math.max(0,t-1024*1024),c=Buffer.alloc(t-n),u=g.readSync(r,c,0,c.length,n),d=c.subarray(0,u).toString("utf8");if(n){let h=d.indexOf(`
15
+ `);if(c.length>ye)throw s("AUDIT_BATCH_LIMIT",{bytes:c.length,limit:ye});let u=await Ie(n),d;try{d=j(n,!0);let a=p.fstatSync(d).size;if(a+c.length>he)throw s("AUDIT_FULL",{bytes:a+c.length,limit:he});if(a){let i=Buffer.alloc(1);if(p.readSync(d,i,0,1,a-1),i[0]!==10)throw s("AUDIT_PARTIAL")}try{let i=0;for(;i<c.length;){let l=p.writeSync(d,c,i,c.length-i,a+i);if(!l)throw s("AUDIT_IO");i+=l}p.fsyncSync(d)}catch(i){throw p.ftruncateSync(d,a),p.fsyncSync(d),F(i)}}catch(a){throw F(a)}finally{d!==void 0&&p.closeSync(d),p.rmdirSync(u)}}function Ne(n,e=20){if(!Number.isInteger(e)||e<1||e>100)throw s("INTERNAL",{limit:100});let r;try{try{r=j(n,!1)}catch(h){if(h.code==="ENOENT")return{records:[],truncated:!1};throw h}let t=p.fstatSync(r).size,o=Math.max(0,t-1024*1024),c=Buffer.alloc(t-o),u=p.readSync(r,c,0,c.length,o),d=c.subarray(0,u).toString("utf8");if(o){let h=d.indexOf(`
16
16
  `);d=h<0?"":d.slice(h+1)}let a=d.split(`
17
- `),i=a.pop()!=="",l=[],f=!1;for(let h of a.slice(-e))try{let I=JSON.parse(h);if(I.version!==1||typeof I.time!="string"||typeof I.provider!="string"||typeof I.original!="string"||typeof I.replacement!="string"||typeof I.requestId!="string"||typeof I.timezoneOffset!="number")throw new Error;l.push(I)}catch{f=!0}return{records:l,truncated:n>0||a.length>e||i||f}}catch(t){throw k(t)}finally{r!==void 0&&g.closeSync(r)}}var b=class{constructor(e,r=2e3,t=pe){this.configDir=e;this.timeoutMs=r;this.machineId=t}configDir;timeoutMs;machineId;tokens=new Map;queue=Promise.resolve();workers=new Set;closed=!1;snapshot;lastError;restorePattern;restoreSize=-1;get lastDiagnostic(){return this.lastError?{...this.lastError}:void 0}get lastDiagnosticText(){return this.lastError?S(this.lastError):void 0}async initialize(){try{if(this.closed)throw s("NOT_READY");this.snapshot=void 0;let e;try{e=this.machineId()}catch{throw s("MACHINE_ID")}let r=await me(this.configDir,e);if(this.closed)throw s("NOT_READY");this.snapshot=r,this.lastError=void 0}catch(e){let r=y(e,"CONFIG_IO");throw this.lastError=r.diagnostic,r}}get configPath(){return this.snapshot?.path??""}get auditPath(){return this.configPath?this.configPath.replace(/\.json$/,".jsonl"):""}auditRecords(e=20){if(!this.ready)throw this.notReady();return Ne(this.auditPath,e)}clearAuditRecords(){let e=this.queue.then(()=>{if(!this.ready)throw this.notReady();return Oe(this.auditPath)});return this.queue=e.catch(()=>{}),e}get ruleCount(){return this.snapshot?.config.sensitiveWords.length??0}get compactionMode(){return this.snapshot?.config.compaction??le}get ready(){return!!this.snapshot&&!this.closed}get mappingCount(){return this.tokens.size}redact(e,r="unknown"){let t=this.queue.then(()=>this.scan(e,r)).catch(n=>{let c=y(n,"INTERNAL");throw this.lastError=c.diagnostic,c});return this.queue=t.catch(()=>{}),t}notReady(){return this.lastError?s(this.lastError.code,this.lastError):s("NOT_READY")}async scan(e,r){if(!this.ready)throw this.notReady();let{config:t,sourceRaws:n}=this.snapshot,c;try{c=JSON.stringify(e)}catch{throw s("PAYLOAD_JSON")}if(!c)throw s("PAYLOAD_JSON");if(Buffer.byteLength(c)>8*1024*1024)throw s("PAYLOAD_SIZE",{bytes:Buffer.byteLength(c),limit:8*1024*1024});let u;try{u=JSON.parse(c)}catch{throw s("PAYLOAD_JSON")}let d=await new Promise((a,i)=>{let l=!1,f;try{f=new Qe(et(new URL("./scan-worker.mjs",import.meta.url)),{workerData:{payload:u,rules:t.sensitiveWords,entries:[...this.tokens],configRaws:n},execArgv:[],resourceLimits:{maxOldGenerationSizeMb:128}})}catch(A){i(y(A,"WORKER_FAILED"));return}this.workers.add(f);let h=(A,N=s("WORKER_FAILED"))=>{if(!l){if(l=!0,clearTimeout(I),this.workers.delete(f),f.terminate(),!A||this.closed){i(this.closed?s("NOT_READY"):N);return}a(A)}},I=setTimeout(()=>h(void 0,s("SCAN_TIMEOUT",{timeoutMs:this.timeoutMs})),this.timeoutMs);f.once("message",A=>{A?.failed?h(void 0,M(A.diagnostic,"SCAN_INTERNAL")):A&&Array.isArray(A.additions)&&Array.isArray(A.hits)?h(A):h()}),f.once("error",()=>h()),f.once("exit",()=>h())});if(this.closed)throw s("NOT_READY");if(await Ae(this.auditPath,r,d.hits),this.closed)throw s("NOT_READY");for(let[a,i]of d.additions)this.tokens.set(a,i);return d.payload}restoreText(e){if(!this.tokens.size)return e;if(this.restoreSize!==this.tokens.size){let r=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.restorePattern=new RegExp([...this.tokens.keys()].sort((t,n)=>n.length-t.length).map(r).join("|"),"g"),this.restoreSize=this.tokens.size}return e.replace(this.restorePattern,r=>this.tokens.get(r)??r)}restore(e,r=0){if(r>80)throw s("RESTORE_COMPLEXITY",{node:r});if(typeof e=="string")return this.restoreText(e);if(typeof e=="number"){let t=this.tokens.get(String(e));if(t===void 0)return e;let n=Number(t);return!Number.isFinite(n)||String(n)!==t?e:n}if(Array.isArray(e))return e.map(t=>this.restore(t,r+1));if(e&&typeof e=="object"){let t=Object.create(null);for(let[n,c]of Object.entries(e)){let u=this.restoreText(n);if(Object.hasOwn(t,u))throw s("RESTORE_KEY_COLLISION");t[u]=this.restore(c,r+1)}return t}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 tt,statSync as Ee,readdirSync as rt}from"node:fs";import{homedir as ot}from"node:os";import{basename as X,dirname as P,isAbsolute as nt,relative as Se,resolve as x}from"node:path";import{fileURLToPath as it}from"node:url";function st(o,e){let r=o.replace(/^@/,"");return r.startsWith("file://")&&(r=it(r)),(r==="~"||r.startsWith("~/"))&&(r=ot()+r.slice(1)),x(e,r)}function q(o){try{return tt(o)}catch{let e=P(o);return e===o?o:x(q(e),Se(e,o))}}function at(o,e){let r=Se(o,e);return r===""||!r.startsWith("..")&&!nt(r)}function Ce(o,e){try{let r=Ee(o),t=Ee(e);return r.dev===t.dev&&r.ino===t.ino}catch{return!1}}function _e(o,e,r,t){if(!t)return!0;let n=q(x(t));if(["bash","powershell"].includes(o)){let d=typeof e.command=="string"?e.command:"";if(/protecter(?:\.[a-f0-9]{32})?\.jsonl?|\.protecter-migration/i.test(d)||d.includes(t))return!0}let c=e.path??e.file_path??e.filePath,u=["grep","find","ls"].includes(o);if(typeof c!="string"&&!u)return!1;try{let d=st(typeof c=="string"?c:".",r),a=q(d),i=/^protecter\.[a-f0-9]{32}\.jsonl(?:\.lock)?$/,l=rt(P(n)).filter(f=>i.test(f)).some(f=>Ce(d,x(P(n),f)));return P(a)===P(n)&&(Y.test(X(a))||i.test(X(a))||X(a).startsWith(".protecter-migration"))||a===n||Ce(d,t)||l||u&&at(a,n)}catch{return!0}}import{generateBranchSummary as ct,generateSummaryWithUsage as lt}from"@earendil-works/pi-coding-agent";async function Te(o){let e=o.model;if(!e)throw s("COMPACT_UNAVAILABLE");let r;try{r=await o.modelRegistry.getApiKeyAndHeaders(e)}catch{throw s("COMPACT_UNAVAILABLE")}if(!r.ok)throw s("COMPACT_UNAVAILABLE");let t=Object.fromEntries(Object.entries(r.headers??{}).filter(n=>typeof n[1]=="string"));return{model:e,apiKey:r.apiKey,headers:t,env:r.env}}async function we(o,e,r,t,n=lt){let{preparation:c}=o,u=await r.redact(c.messagesToSummarize,t),d=c.previousSummary===void 0?void 0:await r.redact(c.previousSummary,t),a=o.customInstructions===void 0?void 0:await r.redact(o.customInstructions,t),i=await Te(e),l,f;try{let h=await n(u,i.model,c.settings.reserveTokens,i.apiKey,i.headers,o.signal,a,d,e.thinkingLevel,void 0,i.env);l=h.text,f=h.usage}catch(h){throw y(h,"COMPACT_FAILED")}if(typeof l!="string"||!l.trim())throw s("COMPACT_FAILED");return{summary:r.restoreText(l),firstKeptEntryId:c.firstKeptEntryId,tokensBefore:c.tokensBefore,usage:f}}async function Re(o,e,r,t,n=ct){let{preparation:c}=o,u=await r.redact(c.entriesToSummarize,t),d=c.customInstructions===void 0?void 0:await r.redact(c.customInstructions,t),a=await Te(e),i;try{i=await n(u,{model:a.model,apiKey:a.apiKey,headers:a.headers,env:a.env,signal:o.signal,customInstructions:d,replaceInstructions:c.replaceInstructions})}catch(f){throw y(f,"COMPACT_FAILED")}let l=i?.summary;if(typeof l!="string"||!l.trim())throw s("COMPACT_FAILED");return{summary:r.restoreText(l),usage:i.usage}}function ft(o){oe(H());let e=new b(ut()),r=Q(dt),t=!1,n,c,u=a=>{let i=S(a);return n={at:new Date().toISOString(),text:i},i};o.on("session_start",async(a,i)=>{try{if(!r)throw s("UNSUPPORTED_PI");await e.initialize(),t=!0;let l=e.ruleCount;i.ui.setStatus("protecter",m("statusBarRules",{rules:R("rules",l)})),l===0&&i.ui.notify(m("emptyRules"),"warning")}catch(l){t=!1,i.ui.setStatus("protecter",m("statusBarNotReady")),i.ui.notify(u(y(l,"CONFIG_IO").diagnostic),"error")}}),o.on("before_provider_request",async(a,i)=>{try{if(!r)throw s("UNSUPPORTED_PI");let l=await e.redact(a.payload,i.model?.provider??"unknown");return t=!0,l}catch(l){t=!1;let f=u(y(l,"INTERNAL").diagnostic);try{await i.abort()}catch{}try{i.ui.notify(f,"error")}catch{}return{}}}),o.on("message_end",a=>{if(a.message.role!=="assistant")return;let i=a.message;return{message:{...i,content:i.content.map(l=>l.type==="text"?{...l,text:e.restoreText(l.text)}:l.type==="thinking"?{...l,thinking:e.restoreText(l.thinking)}:l.type==="toolCall"?{...l,arguments:e.restore(l.arguments)}:l),...i.errorMessage?{errorMessage:e.restoreText(i.errorMessage)}:{}}}}),o.registerMarkdownTransformer((a,i)=>i.messageType==="user"?a:e.restoreText(a)),o.on("tool_call",(a,i)=>{if(!t)return{block:!0,reason:e.lastDiagnosticText??n?.text??S(s("NOT_READY").diagnostic)};let l=e.restore(a.input);for(let f of Object.keys(a.input))delete a.input[f];if(Object.assign(a.input,l),_e(a.toolName,a.input,i.cwd,e.configPath))return{block:!0,reason:m("toolBlocked")}});let d=async(a,i)=>{if(!r)throw s("UNSUPPORTED_PI");if(!e.ready)throw e.lastDiagnostic?s(e.lastDiagnostic.code,e.lastDiagnostic):s("NOT_READY");let l=e.compactionMode;if(l==="off")throw s("COMPACT_DENIED");if(c==="deny")throw s("COMPACT_DENIED");if(l!=="ask"||c==="allow")return;let f=[m("compactAllowOnce"),m("compactAllowAlways"),m("compactDenyOnce"),m("compactDenyAlways")],h=await a.ui.select(`${m("compactAskTitle")}
17
+ `),i=a.pop()!=="",l=[],f=!1;for(let h of a.slice(-e))try{let I=JSON.parse(h);if(I.version!==1||typeof I.time!="string"||typeof I.provider!="string"||typeof I.original!="string"||typeof I.replacement!="string"||typeof I.requestId!="string"||typeof I.timezoneOffset!="number")throw new Error;l.push(I)}catch{f=!0}return{records:l,truncated:o>0||a.length>e||i||f}}catch(t){throw F(t)}finally{r!==void 0&&p.closeSync(r)}}var b=class{constructor(e,r=2e3,t=ge){this.configDir=e;this.timeoutMs=r;this.machineId=t}configDir;timeoutMs;machineId;tokens=new Map;queue=Promise.resolve();workers=new Set;closed=!1;snapshot;lastError;restorePattern;restoreSize=-1;get lastDiagnostic(){return this.lastError?{...this.lastError}:void 0}get lastDiagnosticText(){return this.lastError?S(this.lastError):void 0}async initialize(){try{if(this.closed)throw s("NOT_READY");this.snapshot=void 0;let e;try{e=this.machineId()}catch{throw s("MACHINE_ID")}let r=await me(this.configDir,e);if(this.closed)throw s("NOT_READY");this.snapshot=r,this.lastError=void 0}catch(e){let r=y(e,"CONFIG_IO");throw this.lastError=r.diagnostic,r}}get configPath(){return this.snapshot?.path??""}get auditPath(){return this.configPath?this.configPath.replace(/\.json$/,".jsonl"):""}auditRecords(e=20){if(!this.ready)throw this.notReady();return Ne(this.auditPath,e)}clearAuditRecords(){let e=this.queue.then(()=>{if(!this.ready)throw this.notReady();return Oe(this.auditPath)});return this.queue=e.catch(()=>{}),e}get ruleCount(){return this.snapshot?.config.sensitiveWords.length??0}get compactionMode(){return this.snapshot?.config.compaction??le}get ready(){return!!this.snapshot&&!this.closed}get mappingCount(){return this.tokens.size}redact(e,r="unknown"){let t=this.queue.then(()=>this.scan(e,r)).catch(o=>{let c=y(o,"INTERNAL");throw this.lastError=c.diagnostic,c});return this.queue=t.catch(()=>{}),t}notReady(){return this.lastError?s(this.lastError.code,this.lastError):s("NOT_READY")}async scan(e,r){if(!this.ready)throw this.notReady();let{config:t,sourceRaws:o}=this.snapshot,c;try{c=JSON.stringify(e)}catch{throw s("PAYLOAD_JSON")}if(!c)throw s("PAYLOAD_JSON");if(Buffer.byteLength(c)>8*1024*1024)throw s("PAYLOAD_SIZE",{bytes:Buffer.byteLength(c),limit:8*1024*1024});let u;try{u=JSON.parse(c)}catch{throw s("PAYLOAD_JSON")}let d=await new Promise((a,i)=>{let l=!1,f;try{f=new et(tt(new URL("./scan-worker.mjs",import.meta.url)),{workerData:{payload:u,rules:t.sensitiveWords,entries:[...this.tokens],configRaws:o},execArgv:[],resourceLimits:{maxOldGenerationSizeMb:128}})}catch(A){i(y(A,"WORKER_FAILED"));return}this.workers.add(f);let h=(A,N=s("WORKER_FAILED"))=>{if(!l){if(l=!0,clearTimeout(I),this.workers.delete(f),f.terminate(),!A||this.closed){i(this.closed?s("NOT_READY"):N);return}a(A)}},I=setTimeout(()=>h(void 0,s("SCAN_TIMEOUT",{timeoutMs:this.timeoutMs})),this.timeoutMs);f.once("message",A=>{A?.failed?h(void 0,k(A.diagnostic,"SCAN_INTERNAL")):A&&Array.isArray(A.additions)&&Array.isArray(A.hits)?h(A):h()}),f.once("error",()=>h()),f.once("exit",()=>h())});if(this.closed)throw s("NOT_READY");if(await Ae(this.auditPath,r,d.hits),this.closed)throw s("NOT_READY");for(let[a,i]of d.additions)this.tokens.set(a,i);return d.payload}restoreText(e){if(!this.tokens.size)return e;if(this.restoreSize!==this.tokens.size){let r=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.restorePattern=new RegExp([...this.tokens.keys()].sort((t,o)=>o.length-t.length).map(r).join("|"),"g"),this.restoreSize=this.tokens.size}return e.replace(this.restorePattern,r=>this.tokens.get(r)??r)}restore(e,r=0){if(r>80)throw s("RESTORE_COMPLEXITY",{node:r});if(typeof e=="string")return this.restoreText(e);if(typeof e=="number"){let t=this.tokens.get(String(e));if(t===void 0)return e;let o=Number(t);return!Number.isFinite(o)||String(o)!==t?e:o}if(Array.isArray(e))return e.map(t=>this.restore(t,r+1));if(e&&typeof e=="object"){let t=Object.create(null);for(let[o,c]of Object.entries(e)){let u=this.restoreText(o);if(Object.hasOwn(t,u))throw s("RESTORE_KEY_COLLISION");t[u]=this.restore(c,r+1)}return t}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 rt,statSync as Ee,readdirSync as nt}from"node:fs";import{homedir as ot}from"node:os";import{basename as X,dirname as P,isAbsolute as it,relative as Se,resolve as x}from"node:path";import{fileURLToPath as st}from"node:url";function at(n,e){let r=n.replace(/^@/,"");return r.startsWith("file://")&&(r=st(r)),(r==="~"||r.startsWith("~/"))&&(r=ot()+r.slice(1)),x(e,r)}function q(n){try{return rt(n)}catch{let e=P(n);return e===n?n:x(q(e),Se(e,n))}}function ct(n,e){let r=Se(n,e);return r===""||!r.startsWith("..")&&!it(r)}function Ce(n,e){try{let r=Ee(n),t=Ee(e);return r.dev===t.dev&&r.ino===t.ino}catch{return!1}}function _e(n,e,r,t){if(!t)return!0;let o=q(x(t));if(["bash","powershell"].includes(n)){let d=typeof e.command=="string"?e.command:"";if(/protecter(?:\.[a-f0-9]{32})?\.jsonl?|\.protecter-migration/i.test(d)||d.includes(t))return!0}let c=e.path??e.file_path??e.filePath,u=["grep","find","ls"].includes(n);if(typeof c!="string"&&!u)return!1;try{let d=at(typeof c=="string"?c:".",r),a=q(d),i=/^protecter\.[a-f0-9]{32}\.jsonl(?:\.lock)?$/,l=nt(P(o)).filter(f=>i.test(f)).some(f=>Ce(d,x(P(o),f)));return P(a)===P(o)&&(Y.test(X(a))||i.test(X(a))||X(a).startsWith(".protecter-migration"))||a===o||Ce(d,t)||l||u&&ct(a,o)}catch{return!0}}import{generateBranchSummary as lt,generateSummaryWithUsage as ut}from"@earendil-works/pi-coding-agent";async function Te(n){let e=n.model;if(!e)throw s("COMPACT_UNAVAILABLE");let r;try{r=await n.modelRegistry.getApiKeyAndHeaders(e)}catch{throw s("COMPACT_UNAVAILABLE")}if(!r.ok)throw s("COMPACT_UNAVAILABLE");let t=Object.fromEntries(Object.entries(r.headers??{}).filter(o=>typeof o[1]=="string"));return{model:e,apiKey:r.apiKey,headers:t,env:r.env}}function we(n){let e=n.modelRegistry;if(typeof e.streamSimple=="function")return(r,t,o)=>e.streamSimple(r,t,o);if(typeof e.complete=="function")return(r,t,o)=>({result:()=>e.complete(r,t,o)})}async function Re(n,e,r,t,o=ut){let{preparation:c}=n,u=await r.redact(c.messagesToSummarize,t),d=c.previousSummary===void 0?void 0:await r.redact(c.previousSummary,t),a=n.customInstructions===void 0?void 0:await r.redact(n.customInstructions,t),i=await Te(e),l,f;try{let h=await o(u,i.model,c.settings.reserveTokens,i.apiKey,i.headers,n.signal,a,d,e.thinkingLevel,we(e),i.env);l=h.text,f=h.usage}catch(h){throw y(h,"COMPACT_FAILED")}if(typeof l!="string"||!l.trim())throw s("COMPACT_FAILED");return{summary:r.restoreText(l),firstKeptEntryId:c.firstKeptEntryId,tokensBefore:c.tokensBefore,usage:f}}async function De(n,e,r,t,o=lt){let{preparation:c}=n,u=await r.redact(c.entriesToSummarize,t),d=c.customInstructions===void 0?void 0:await r.redact(c.customInstructions,t),a=await Te(e),i;try{i=await o(u,{model:a.model,apiKey:a.apiKey,headers:a.headers,env:a.env,signal:n.signal,customInstructions:d,replaceInstructions:c.replaceInstructions,streamFn:we(e)})}catch(f){throw y(f,"COMPACT_FAILED")}let l=i?.summary;if(typeof l!="string"||!l.trim())throw s("COMPACT_FAILED");return{summary:r.restoreText(l),usage:i.usage}}function mt(n){ne(H());let e=new b(dt()),r=Q(ft),t=!1,o,c,u=a=>{let i=S(a);return o={at:new Date().toISOString(),text:i},i};n.on("session_start",async(a,i)=>{try{if(!r)throw s("UNSUPPORTED_PI");await e.initialize(),t=!0;let l=e.ruleCount;i.ui.setStatus("protecter",m("statusBarRules",{rules:R("rules",l)})),l===0&&i.ui.notify(m("emptyRules"),"warning")}catch(l){t=!1,i.ui.setStatus("protecter",m("statusBarNotReady")),i.ui.notify(u(y(l,"CONFIG_IO").diagnostic),"error")}}),n.on("before_provider_request",async(a,i)=>{try{if(!r)throw s("UNSUPPORTED_PI");let l=await e.redact(a.payload,i.model?.provider??"unknown");return t=!0,l}catch(l){t=!1;let f=u(y(l,"INTERNAL").diagnostic);try{await i.abort()}catch{}try{i.ui.notify(f,"error")}catch{}return{}}}),n.on("message_end",a=>{if(a.message.role!=="assistant")return;let i=a.message;return{message:{...i,content:i.content.map(l=>l.type==="text"?{...l,text:e.restoreText(l.text)}:l.type==="thinking"?{...l,thinking:e.restoreText(l.thinking)}:l.type==="toolCall"?{...l,arguments:e.restore(l.arguments)}:l),...i.errorMessage?{errorMessage:e.restoreText(i.errorMessage)}:{}}}}),n.registerMarkdownTransformer((a,i)=>i.messageType==="user"?a:e.restoreText(a)),n.on("tool_call",(a,i)=>{if(!t)return{block:!0,reason:e.lastDiagnosticText??o?.text??S(s("NOT_READY").diagnostic)};let l=e.restore(a.input);for(let f of Object.keys(a.input))delete a.input[f];if(Object.assign(a.input,l),_e(a.toolName,a.input,i.cwd,e.configPath))return{block:!0,reason:m("toolBlocked")}});let d=async(a,i)=>{if(!r)throw s("UNSUPPORTED_PI");if(!e.ready)throw e.lastDiagnostic?s(e.lastDiagnostic.code,e.lastDiagnostic):s("NOT_READY");let l=e.compactionMode;if(l==="off")throw s("COMPACT_DENIED");if(c==="deny")throw s("COMPACT_DENIED");if(l!=="ask"||c==="allow")return;let f=[m("compactAllowOnce"),m("compactAllowAlways"),m("compactDenyOnce"),m("compactDenyAlways")],h=await a.ui.select(`${m("compactAskTitle")}
18
18
 
19
- ${m("compactAskBody")}`,f,{signal:i}),I=h===void 0?-1:f.indexOf(h);if(I===1?(c="allow",a.ui.notify(m("compactAlwaysNotice"),"info")):I===3&&(c="deny",a.ui.notify(m("compactDenyNotice"),"warning")),I!==0&&I!==1)throw s("COMPACT_DENIED")};o.on("session_before_compact",async(a,i)=>{try{await d(i,a.signal),i.ui.notify(m("compactWorking"),"info");let l=await we(a,i,e,i.model?.provider??"unknown");return i.ui.notify(m("compactDone"),"info"),{compaction:l}}catch(l){return i.ui.notify(u(y(l,"COMPACT_FAILED").diagnostic),"warning"),{cancel:!0}}}),o.on("session_before_tree",async(a,i)=>{if(a.preparation.userWantsSummary)try{await d(i,a.signal),i.ui.notify(m("compactWorking"),"info");let l=await Re(a,i,e,i.model?.provider??"unknown");return i.ui.notify(m("compactDone"),"info"),{summary:l}}catch(l){return i.ui.notify(u(y(l,"COMPACT_FAILED").diagnostic),"warning"),{cancel:!0}}}),o.registerCommand("protecter",{description:m("commandDescription"),handler:async(a,i)=>{let l=a.trim().split(/\s+/).filter(Boolean),f=l[0]??"logs";if(!["status","reload","logs"].includes(f)||f!=="logs"&&l.length>1||l.length>2||l[1]!==void 0&&l[1]!=="clear"&&!/^(?:[1-9]\d?|100)$/.test(l[1])){i.ui.notify(m("usage"),"info");return}if(f==="logs"){if(i.mode!=="tui"){i.ui.notify(m("logsTuiOnly"),"warning");return}if(l[1]==="clear"){try{if(!e.ready)throw s("NOT_READY");if(!await i.ui.confirm(m("clearTitle"),m("clearBody")))return;await i.waitForIdle();let N=await e.clearAuditRecords();t=e.ready,i.ui.notify(m("cleared",{bytes:R("bytes",N)}),"info")}catch(N){i.ui.notify(u(y(N,"AUDIT_IO").diagnostic),"error")}return}try{let{records:N,truncated:G}=e.auditRecords(Number(l[1]??20));if(!N.length){i.ui.notify(m("logsNone"),"info");return}let O=L=>JSON.stringify(L).replace(/[\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g,U=>`\\u${U.charCodeAt(0).toString(16).padStart(4,"0")}`),w=N.map((L,U)=>`${U+1}. ${O(L.time)} | ${O(L.provider).slice(0,120)}`),V=await i.ui.select(m("logsSelectTitle")+(G?m("logsTruncated"):""),w),Z=V===void 0?-1:w.indexOf(V);if(Z<0||!await i.ui.confirm(m("logsRevealTitle"),m("logsRevealBody")))return;let v=O(N[Z]);await i.ui.editor(m("logsPreviewTitle"),v.length>2e4?`${v.slice(0,2e4)}
20
- ${m("logsPreviewTruncated")}`:v)}catch(N){i.ui.notify(u(y(N,"AUDIT_IO").diagnostic),"error")}return}if(f==="reload"){await i.waitForIdle(),await i.reload();return}let h=e.lastDiagnosticText??n?.text,I=m("statusLine",{state:m(e.ready?"statusReady":"statusNotReady"),rules:R("rules",e.ruleCount),mappings:R("mappings",e.mappingCount)}),A=h?`
21
- ${m("statusLastBlock",{at:n?.at??""})}
19
+ ${m("compactAskBody")}`,f,{signal:i}),I=h===void 0?-1:f.indexOf(h);if(I===1?(c="allow",a.ui.notify(m("compactAlwaysNotice"),"info")):I===3&&(c="deny",a.ui.notify(m("compactDenyNotice"),"warning")),I!==0&&I!==1)throw s("COMPACT_DENIED")};n.on("session_before_compact",async(a,i)=>{try{await d(i,a.signal),i.ui.notify(m("compactWorking"),"info");let l=await Re(a,i,e,i.model?.provider??"unknown");return i.ui.notify(m("compactDone"),"info"),{compaction:l}}catch(l){return i.ui.notify(u(y(l,"COMPACT_FAILED").diagnostic),"warning"),{cancel:!0}}}),n.on("session_before_tree",async(a,i)=>{if(a.preparation.userWantsSummary)try{await d(i,a.signal),i.ui.notify(m("compactWorking"),"info");let l=await De(a,i,e,i.model?.provider??"unknown");return i.ui.notify(m("compactDone"),"info"),{summary:l}}catch(l){return i.ui.notify(u(y(l,"COMPACT_FAILED").diagnostic),"warning"),{cancel:!0}}}),n.registerCommand("protecter",{description:m("commandDescription"),handler:async(a,i)=>{let l=a.trim().split(/\s+/).filter(Boolean),f=l[0]??"logs";if(!["status","reload","logs"].includes(f)||f!=="logs"&&l.length>1||l.length>2||l[1]!==void 0&&l[1]!=="clear"&&!/^(?:[1-9]\d?|100)$/.test(l[1])){i.ui.notify(m("usage"),"info");return}if(f==="logs"){if(i.mode!=="tui"){i.ui.notify(m("logsTuiOnly"),"warning");return}if(l[1]==="clear"){try{if(!e.ready)throw s("NOT_READY");if(!await i.ui.confirm(m("clearTitle"),m("clearBody")))return;await i.waitForIdle();let N=await e.clearAuditRecords();t=e.ready,i.ui.notify(m("cleared",{bytes:R("bytes",N)}),"info")}catch(N){i.ui.notify(u(y(N,"AUDIT_IO").diagnostic),"error")}return}try{let{records:N,truncated:G}=e.auditRecords(Number(l[1]??20));if(!N.length){i.ui.notify(m("logsNone"),"info");return}let O=L=>JSON.stringify(L).replace(/[\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g,U=>`\\u${U.charCodeAt(0).toString(16).padStart(4,"0")}`),w=N.map((L,U)=>`${U+1}. ${O(L.time)} | ${O(L.provider).slice(0,120)}`),V=await i.ui.select(m("logsSelectTitle")+(G?m("logsTruncated"):""),w),Z=V===void 0?-1:w.indexOf(V);if(Z<0||!await i.ui.confirm(m("logsRevealTitle"),m("logsRevealBody")))return;let v=O(N[Z]);await i.ui.editor(m("logsPreviewTitle"),v.length>2e4?`${v.slice(0,2e4)}
20
+ ${m("logsPreviewTruncated")}`:v)}catch(N){i.ui.notify(u(y(N,"AUDIT_IO").diagnostic),"error")}return}if(f==="reload"){await i.waitForIdle(),await i.reload();return}let h=e.lastDiagnosticText??o?.text,I=m("statusLine",{state:m(e.ready?"statusReady":"statusNotReady"),rules:R("rules",e.ruleCount),mappings:R("mappings",e.mappingCount)}),A=h?`
21
+ ${m("statusLastBlock",{at:o?.at??""})}
22
22
  ${h}`:`
23
- ${m("statusNoBlock")}`;i.ui.notify(I+A,e.ready?"info":"error")}}),o.on("session_shutdown",()=>e.close())}export{ft as default};
23
+ ${m("statusNoBlock")}`;i.ui.notify(I+A,e.ready?"info":"error")}}),n.on("session_shutdown",()=>e.close())}export{mt as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-information-protecter",
3
- "version": "0.8.2",
3
+ "version": "0.8.3",
4
4
  "description": "Sensitive Personal Information (SPI) Protecter — local reversible privacy redaction for Pi",
5
5
  "type": "module",
6
6
  "license": "MIT",