pi-information-protecter 0.8.4 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,44 @@
1
1
  # Changelog / 更新日志
2
2
 
3
+ ## 0.10.0 — Pi 1.x compatibility / 兼容 Pi 1.x
4
+
5
+ ### Added / 新增
6
+
7
+ - Accept Pi 0.99.x and 1.2.0–1.3.x, established by running the full suite, including the real loader and worker integration tests, against 0.87.1, 0.99.2, 1.2.0 and 1.3.0. The runtime gate refused every 0.88+ version, so on current Pi releases the extension failed every request closed with `UNSUPPORTED_PI` while the status bar still showed it as loaded.
8
+ 接收 Pi 0.99.x 与 1.2.0–1.3.x,依据是在 0.87.1、0.99.2、1.2.0 和 1.3.0 上运行完整测试(含真实加载器与 worker 集成测试)。之前运行时门禁拒绍所有 0.88+ 版本,因此在当前 Pi 上每个请求都以 `UNSUPPORTED_PI` 被拦,状态栏却仍显示已加载。
9
+ - Document that nested model calls outside the agent loop are not redacted: a `codemode` script's `models.classify()` or `models.generateImages()`, and any `modelRegistry` call another extension makes, carry no `onPayload` callback. Pi 0.99.0 added `codemode`, MCP and tool search as built-in extensions, so this boundary is new.
10
+ 记录智能体循环之外的嵌套模型调用不会脖敏:`codemode` 脚本的 `models.classify()`、`models.generateImages()` 以及其他扩展的 `modelRegistry` 调用都不携带 `onPayload` 回调。Pi 0.99.0 新增了内置的 `codemode`、MCP 与工具检索扩展,因此这是新的边界。
11
+
12
+ ### Changed / 变更
13
+
14
+ - Refuse Pi 1.0.x and 1.1.0: both depend on `@earendil-works/pi-codemode: ^1.0.4`, which now resolves to 1.3.0, whose missing `MCP_TYPESCRIPT_PREAMBLE` export makes Pi itself throw while loading. This mirrors the existing 0.85.0 exclusion — Pi's own unresolvable import, not an extension defect.
15
+ 拒绝 Pi 1.0.x 与 1.1.0:二者依赖 `@earendil-works/pi-codemode: ^1.0.4`,它如今解析到 1.3.0,而该版本已不导出 `MCP_TYPESCRIPT_PREAMBLE`,导致 Pi 自身在加载时抛错。这与现有的 0.85.0 排除同理:问题出在 Pi 自身无法解析的引用,而非扩展缺陷。
16
+ - Build and verify against Pi 1.3.0 and widen the declared peer range to match the runtime gate exactly.
17
+ 构建与验证基线改为 Pi 1.3.0,并将声明的 peer 范围与运行时门禁保持完全一致。
18
+
19
+ ## 0.9.0 — A dedicated summarization model / 专用摘要模型
20
+
21
+ ### Added / 新增
22
+
23
+ - Support a dedicated summarization model through `compaction.provider` and `compaction.model`. `contextWindow` is inherited from Pi's model catalogue and `reserveTokens` from Pi's own compaction settings, so both are overrides rather than required fields. Summarizing sends the whole conversation, redacted, to a second destination, so it can now be a local or otherwise trusted endpoint.
24
+ 通过 `compaction.provider` 与 `compaction.model` 支持专用摘要模型。`contextWindow` 继承自 Pi 的模型目录,`reserveTokens` 继承自 Pi 自身的压缩设置,二者均为覆盖项而非必填。生成摘要会把脱敏后的整段对话发往第二个目的地,现在它可以是本地或其他可信端点。
25
+ - Drive the compaction threshold from the summarization model's window instead of the main model's. Pi compacts near the main window, about 983k tokens for a 1M model, which a 256k summarizer cannot read; compaction now happens at the summarization model's window minus the reserve.
26
+ 压缩阈值改为依据摘要模型的窗口而非主模型。Pi 在主窗口附近压缩(1M 模型约 98.3 万 token),而 256k 的摘要模型读不下;现在按摘要模型窗口减去预留触发。
27
+ - Resolve and report a configured summarization model at startup, and never fall back to the main model when it cannot be resolved, which would send the conversation to a destination the user did not choose.
28
+ 在启动时解析并反馈配置的摘要模型;无法解析时不回退到主模型,以免把对话发往用户未选择的目的地。
29
+ - Show the compaction target and effective threshold in `/protecter status`.
30
+ 在 `/protecter status` 中显示压缩目标与生效阈值。
31
+
32
+ ### Fixed / 修复
33
+
34
+ - Record the summarization provider in the audit log instead of the conversation's provider. The audit answers where plaintext went, so filing a summary sent to a dedicated model under the main model's provider made that record wrong.
35
+ 审计日志记录摘要使用的 provider,而非对话模型的 provider。审计的作用是回答明文去了哪里,把发往专用模型的摘要记在主模型名下会使该记录失真。
36
+
37
+ ### Changed / 变更
38
+
39
+ - Degrade to a local, deterministic summary when the summarization call fails or returns nothing, instead of cancelling compaction. The local summary is built from the same redacted messages and sends nothing. Compaction still cancels if redaction itself fails.
40
+ 摘要调用失败或返回空时降级为本地确定性摘要,而不再取消压缩。本地摘要基于同一批已脱敏消息生成且不发送任何内容;若脱敏本身失败,压缩仍然取消。
41
+
3
42
  ## 0.8.4 — Summarization failures report their kind / 摘要失败上报失败类型
4
43
 
5
44
  ### Added / 新增
package/README.md CHANGED
@@ -10,14 +10,14 @@ A Pi extension that inspects outgoing LLM request bodies locally, replaces confi
10
10
 
11
11
  ## Installation
12
12
 
13
- Requires Node.js 22+ and `@earendil-works/pi-coding-agent` **0.84.0–0.84.x or 0.85.1–0.87.x**. Every accepted release was verified by running the full suite, including the real loader and worker integration tests. 0.83.0 and earlier lack `registerMarkdownTransformer`, and 0.85.0 imports `@earendil-works/pi-server`, which no Pi release declares, so both fail to load. Legacy `@mariozechner/*` releases are not supported.
13
+ Requires Node.js 22+ and `@earendil-works/pi-coding-agent` **0.84.0–0.84.x, 0.85.1–0.87.x, 0.99.x or 1.2.0–1.3.x**. Every accepted release was verified by running the full suite, including the real loader and worker integration tests. 0.83.0 and earlier lack `registerMarkdownTransformer`; 0.85.0 imports `@earendil-works/pi-server`, which no Pi release declares; and 1.0.x and 1.1.0 resolve `@earendil-works/pi-codemode` to a version that no longer exports `MCP_TYPESCRIPT_PREAMBLE`, so all of them fail to load. Legacy `@mariozechner/*` releases are not supported.
14
14
 
15
15
  ```bash
16
16
  # Install the latest npm release.
17
17
  pi install npm:pi-information-protecter
18
18
 
19
19
  # Pin a version only when you have a reason to; older releases miss fixes.
20
- pi install npm:pi-information-protecter@0.7.0
20
+ pi install npm:pi-information-protecter@0.10.0
21
21
 
22
22
  # Alternatively, build and install from this repository without copying it.
23
23
  npm ci
@@ -163,6 +163,30 @@ Set `compaction` in the local configuration:
163
163
 
164
164
  The prompt offers allow once, allow for this session, deny once and deny for this session. A session choice lasts until reload or exit; `compaction` in the configuration is the permanent setting. Dismissing the dialog denies that compaction.
165
165
 
166
+ ### A dedicated summarization model
167
+
168
+ Summarizing sends the whole conversation, redacted, to a second destination. Point it at a local or otherwise trusted endpoint:
169
+
170
+ ```json
171
+ {
172
+ "version": 1,
173
+ "compaction": {
174
+ "mode": "protected",
175
+ "provider": "A6000-vLLM",
176
+ "model": "Qwen38-27B-FP8",
177
+ "contextWindow": 262144,
178
+ "reserveTokens": 16384
179
+ },
180
+ "sensitiveWords": []
181
+ }
182
+ ```
183
+
184
+ Both `contextWindow` and `reserveTokens` are inherited and only needed as overrides: the window comes from Pi's model catalogue, and the reserve from Pi's own `compaction.reserveTokens` setting. Set the window for a private endpoint Pi does not know, and the reserve only when the summarization model needs a different margin. A minimal configuration is therefore just `mode`, `provider` and `model`. A configured model that cannot be resolved is an error, reported at startup rather than when the context fills up, and compaction never falls back to the main model, which would send the conversation somewhere you did not choose.
185
+
186
+ **The threshold follows the summarization model, not the main one.** Pi compacts when the main model's window is nearly full; with a 1M main model that is around 983k tokens, which a 256k summarizer cannot read. The extension therefore compacts earlier, at the summarization model's window minus `reserveTokens`. `/protecter status` shows the target and the effective threshold.
187
+
188
+ The conversation is redacted before it reaches this model as well, so a trusted endpoint improves reliability, cost and privacy, but the summary still describes replacements rather than the original values.
189
+
166
190
  Two costs are unavoidable: the extra summarization request consumes tokens, and the model reasons about replacements, so the summary can describe protected values inaccurately.
167
191
 
168
192
  Summarized `/tree` navigation takes the same internal Pi path and is protected the same way, using the same setting and prompt. Navigation without a summary sends nothing and is never gated.
@@ -237,7 +261,7 @@ Local response and tool-argument restoration
237
261
  - Exit, reload and session switching discard mappings. Final restored local messages remain readable; crash leftovers, old summaries and raw deltas cannot recover tokens across restarts.
238
262
  - Broad rules such as `.` or all digits may alter protocol fields, model names, tool schemas or IDs and break requests. Matching numbers become token strings. Prefer precise rules.
239
263
  - Reused tokens reveal equality relationships; context may imply identity. This is not formal anonymization.
240
- - Hooks do not cover HTTP headers, authentication keys, gateway endpoints, Pi telemetry, `/share`, independent extension SDK/fetch calls or tool networking. The gateway still receives its authentication credentials.
264
+ - Hooks do not cover HTTP headers, authentication keys, gateway endpoints, Pi telemetry, `/share`, independent extension SDK/fetch calls or tool networking. The gateway still receives its authentication credentials. Nested model calls outside the agent loop are also uncovered: a `codemode` script's `models.classify()` or `models.generateImages()`, and any `modelRegistry` call another extension makes, are sent without redaction. Pi 0.99.0 ships `codemode`, MCP and tool search as built-in extensions; keep `codemode` out of `defaultTools` and avoid MCP servers where that matters.
241
265
  - **Load after other payload rewriters and trust every installed extension.** Later handlers can reintroduce originals. Extensions have local permissions, and Pi may continue if this extension fails to load. Check status before entering secrets.
242
266
  - Local sessions, terminals, exports and files written by tools may contain plaintext. They are not encrypted or cleaned by this project.
243
267
 
@@ -266,14 +290,14 @@ API references: [Pi Extensions](https://pi.dev/docs/latest/extensions), local 0.
266
290
 
267
291
  ## 安装
268
292
 
269
- 要求 Node.js 22+ 和 `@earendil-works/pi-coding-agent` **0.84.0–0.84.x 或 0.85.1–0.87.x**。每个受支持版本都经过完整测试验证(含真实加载器与 worker 集成测试)。0.83.0 及更早缺少 `registerMarkdownTransformer`,0.85.0 引用了任何 Pi 版本都未声明的 `@earendil-works/pi-server`,两者均无法加载。不支持旧 `@mariozechner/*` 版本。
293
+ 要求 Node.js 22+ 和 `@earendil-works/pi-coding-agent` **0.84.0–0.84.x、0.85.1–0.87.x、0.99.x 或 1.2.0–1.3.x**。每个受支持版本都经过完整测试验证(含真实加载器与 worker 集成测试)。0.83.0 及更早缺少 `registerMarkdownTransformer`;0.85.0 引用了任何 Pi 版本都未声明的 `@earendil-works/pi-server`;1.0.x 与 1.1.0 将 `@earendil-works/pi-codemode` 解析到已不再导出 `MCP_TYPESCRIPT_PREAMBLE` 的版本,三者均无法加载。不支持旧 `@mariozechner/*` 版本。
270
294
 
271
295
  ```bash
272
296
  # 安装最新 npm 版本。
273
297
  pi install npm:pi-information-protecter
274
298
 
275
299
  # 确有需要时才固定版本;旧版本缺少后续修复。
276
- pi install npm:pi-information-protecter@0.7.0
300
+ pi install npm:pi-information-protecter@0.10.0
277
301
 
278
302
  # 或在本仓库构建后本地安装,不复制仓库。
279
303
  npm ci
@@ -421,6 +445,30 @@ Pi 在自己的压缩代码中构造摘要请求并直接发给提供商。该
421
445
 
422
446
  弹窗提供四个选项:允许一次、本会话内全部允许、拒绝一次、本会话内全部拒绝。会话级选择在重载或退出前有效;配置中的 `compaction` 才是永久设置。关闭对话框视为拒绝本次压缩。
423
447
 
448
+ ### 专用摘要模型
449
+
450
+ 生成摘要会把脱敏后的整段对话发往第二个目的地。请指向本地或其他可信端点:
451
+
452
+ ```json
453
+ {
454
+ "version": 1,
455
+ "compaction": {
456
+ "mode": "protected",
457
+ "provider": "A6000-vLLM",
458
+ "model": "Qwen38-27B-FP8",
459
+ "contextWindow": 262144,
460
+ "reserveTokens": 16384
461
+ },
462
+ "sensitiveWords": []
463
+ }
464
+ ```
465
+
466
+ `contextWindow` 与 `reserveTokens` 都会继承,仅在需要覆盖时填写:窗口取自 Pi 的模型目录,预留值取自 Pi 自身的 `compaction.reserveTokens` 设置。Pi 未收录的私有端点需填写窗口;只有当摘要模型需要不同余量时才填预留值。因此最小配置只需 `mode`、`provider`、`model`。配置了却无法解析的模型属于错误,会在启动时报出而非等到上下文写满;压缩也不会回退到主模型——那会把对话发往你未选择的地方。
467
+
468
+ **阈值跟随摘要模型,而非主模型。** Pi 在主模型窗口将满时压缩,1M 主模型约为 98.3 万 token,而 256k 的摘要模型读不下。因此扩展会提前压缩,阈值为摘要模型窗口减去 `reserveTokens`。`/protecter status` 会显示目标模型与生效阈值。
469
+
470
+ 发往该模型的内容同样先经脱敏,因此可信端点改善的是可靠性、成本与隐私,摘要描述的仍是替换值而非原始值。
471
+
424
472
  有两项代价无法避免:额外的摘要请求会消耗 token;模型推理的是替换值,摘要对受保护值的描述可能不准确。
425
473
 
426
474
  带摘要的 `/tree` 导航走同一条内部路径,采用相同保护方式,并共用同一设置与弹窗。不生成摘要的导航不发送任何内容,也不会被拦截。
@@ -495,7 +543,7 @@ before_provider_request:最终 JSON 文本扫描
495
543
  - 退出、重载和切换会话会丢弃映射。最终已还原消息仍可读,但崩溃残留、旧摘要和原始增量无法跨重启恢复占位符。
496
544
  - 过宽规则可能改写协议字段、模型名、工具结构和 ID,导致请求失败;命中数字变为占位符字符串,应优先使用精确规则。
497
545
  - 复用占位符会暴露值相等的关系,上下文也可能揭示身份,这不是形式化匿名化。
498
- - 钩子不覆盖认证头、API key、网关地址、遥测、分享、扩展独立网络调用和工具联网;网关仍收到其认证凭证。
546
+ - 钩子不覆盖认证头、API key、网关地址、遥测、分享、扩展独立网络调用和工具联网;网关仍收到其认证凭证。智能体循环之外的嵌套模型调用同样不覆盖:`codemode` 脚本的 `models.classify()`、`models.generateImages()` 以及其他扩展的 `modelRegistry` 调用都不经脖敏即发出。Pi 0.99.0 将 `codemode`、MCP 与工具检索内置为扩展,在意这一点时请不要将 `codemode` 加入 `defaultTools`,并避免使用 MCP 服务器。
499
547
  - **在其他请求改写扩展之后加载,并只使用可信扩展。** 后续处理器可重新加入原文;扩展有本机权限,插件加载失败时 Pi 可能继续运行,请先检查状态再输入秘密。
500
548
  - 本地会话、终端、导出和工具写出的文件可能包含明文,本项目不加密或清理它们。
501
549
 
package/SECURITY.md CHANGED
@@ -33,8 +33,10 @@ Prevent configured personal information from accidentally entering Pi LLM reques
33
33
  拦截诊断仅包含目录错误码、阶段、非负整数定位和白名单系统错误码。规则序号和节点数只是位置,不是内容。不输出原始异常消息、请求文本、命中原文、替换值、配置内容和文件路径,worker 边界同样适用,因此诊断可安全分享;错误码有意保持粗粒度,精确定位规则仍可能需要本地查看。
34
34
  - Limit worker regex scans to 2 seconds, with resource and input limits. Errors exclude original configuration, rules and request text.
35
35
  worker 正则扫描限制为 2 秒,并限制资源和输入;错误不包含原始配置、规则或请求文本。
36
- - Pi 0.84.0–0.87.x catches `before_provider_request` errors and continues with the current payload. Error paths therefore return `{}` and attempt cancellation. This does not guarantee zero HTTP requests; it prevents this handler from falling back to the original payload.
37
- Pi 0.84.0–0.87.x 会捕获该钩子异常并继续使用当前请求体,因此错误路径返回空对象并尝试取消。这不保证没有 HTTP 请求,只保证本处理器不回退原始请求体。
36
+ - Every supported Pi release, 0.84.0–0.87.x, 0.99.x and 1.2.0–1.3.x, catches `before_provider_request` errors and continues with the current payload. Error paths therefore return `{}` and attempt cancellation. This does not guarantee zero HTTP requests; it prevents this handler from falling back to the original payload.
37
+ 所有受支持的 Pi 版本(0.84.0–0.87.x、0.99.x 与 1.2.0–1.3.x)都会捕获该钩子异常并继续使用当前请求体,因此错误路径返回空对象并尝试取消。这不保证没有 HTTP 请求,只保证本处理器不回退原始请求体。
38
+ - Only the agent's own model requests carry the `onPayload` callback this extension hooks. Nested model calls made outside that loop, such as a `codemode` script's `models.classify()` or `models.generateImages()`, another extension's `modelRegistry` call, or any direct SDK call, are sent without redaction. Pi 0.99.0 added `codemode`, MCP and tool search as built-in extensions; `codemode` is active only when `defaultTools` or `--tools` enables it, and MCP servers are external programs that receive tool arguments directly. Keep both off in high-risk environments.
39
+ 只有智能体自身的模型请求会携带本扩展挂接的 `onPayload` 回调。循环之外的嵌套模型调用(如 `codemode` 脚本的 `models.classify()`、`models.generateImages()`、其他扩展的 `modelRegistry` 调用或任何直接 SDK 调用)不经脖敏即发出。Pi 0.99.0 将 `codemode`、MCP 与工具检索内置为扩展;`codemode` 仅在 `defaultTools` 或 `--tools` 启用时生效,MCP 服务器则是直接接收工具参数的外部程序。高风险环境下应将二者保持关闭。
38
40
  - Create configuration separately with Unix mode 0600. Reject links, non-regular files, multiple links and files owned by others. Users remain responsible for directories and OS permissions; TOCTOU races are not prevented.
39
41
  独立创建配置,Unix 权限为 0600;拒绝链接、非普通文件、多链接及他人所有文件。用户仍需维护目录和系统权限,无法防止检查与使用之间的竞态。
40
42
  - Direct-access blocking is supplementary. File tools inspect target paths rather than document bodies. Shell can bypass string checks, and command mentions or ancestor directory checks can still cause false positives.
package/dist/index.mjs CHANGED
@@ -1,23 +1,25 @@
1
1
  /*! SPI Protecter | MIT | see LICENSE / SPI 隐私保护插件 | MIT 许可 */
2
- import{getAgentDir as mt,VERSION as gt}from"@earendil-works/pi-coding-agent";import{Worker as rt}from"node:worker_threads";import{fileURLToPath as nt}from"node:url";import*as h from"node:fs";import{join as T,resolve as We}from"node:path";import{createHash as Ye,randomUUID as Ke}from"node:crypto";import{Worker as je}from"node:worker_threads";import{fileURLToPath as Xe}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"]},Le={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 St,VERSION as _t}from"@earendil-works/pi-coding-agent";import{Worker as mt}from"node:worker_threads";import{fileURLToPath as pt}from"node:url";import*as I from"node:fs";import{join as P,resolve as ot}from"node:path";import{createHash as nt,randomUUID as rt}from"node:crypto";import{Worker as it}from"node:worker_threads";import{fileURLToPath as st}from"node:url";var J="0.84.0-0.84.x, 0.85.1-0.87.x, 0.99.x, 1.2.0-1.3.x";function se(o){let e=/^(\d+)\.(\d+)\.(\d+)/.exec(o);if(!e)return!1;let[n,t,r]=e.slice(1).map(Number);return n===1?t===2||t===3:n!==0?!1:t===84?!0:t===85?r>=1:t===86||t===87||t===99}var Y={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 ${J}`],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'],COMPACT_EMPTY:["The model returned an empty summary","A local summary was used instead; no action is required"],CONFIG_COMPACTION:["Invalid compaction setting",'Use "ask", "protected" or "off", or an object with mode, provider, model, contextWindow and reserveTokens'],CONFIG_COMPACT_MODEL:["The compaction model cannot be resolved","Set both provider and model, check their spelling, and sign in to that provider"],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"]},$e={INTERNAL:["未预期的本地错误","重载并检查安装包完整性"],NOT_READY:["防护尚未初始化","查看初始化错误,修复后重载"],UNSUPPORTED_PI:["Pi 版本不受支持",`请使用 Pi ${J}`],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'],COMPACT_EMPTY:["模型返回了空摘要","已改用本地摘要,无需处理"],CONFIG_COMPACTION:["compaction 配置值无效",'请使用 "ask"、"protected"、"off",或含 mode、provider、model、contextWindow、reserveTokens 的对象'],CONFIG_COMPACT_MODEL:["无法解析压缩模型","请同时填写 provider 和 model、核对拼写,并登录该提供商"],AUDIT_BATCH_LIMIT:["审计批次超过上限","减少单个请求的命中内容"],AUDIT_FULL:["审计日志将超过上限","检查记录后清空日志或本地归档"],AUDIT_PARTIAL:["审计日志末行不完整","本地检查或清空日志,不要上传日志"],AUDIT_LOCKED:["审计锁持续被占用","等待写入完成,全部停止后再检查残留锁"],AUDIT_UNSAFE:["审计文件不安全","使用本人普通文件且不含链接,不会绕过检查"],AUDIT_IO:["审计文件操作失败","检查错误码、权限和磁盘空间,不暴露路径或内容"]},ae={blockedHeader:"SPI Protecter blocked this request",reasonLabel:"Reason",actionLabel:"Action",detailsLabel:"Details",statusReady:"ready",statusNotReady:"not ready",statusLine:"SPI Protecter: {state}; {rules}; {mappings}. Memory snapshot; /reload to refresh.",statusLastBlock:"Last block @ {at}:",statusNoBlock:"No recorded block in this session.",statusBarRules:"SPI Protecter · {rules}",statusBarNotReady:"SPI Protecter · not ready",emptyRules:"SPI Protecter: no rules configured; edit the local machine config, then /reload.",commandDescription:"View local SPI protection records",usage:"Usage: /protecter [logs [1-100|clear]|status|reload]. Never type secrets as arguments.",logsTuiOnly:"Open the local TUI to view protection records.",logsNone:"No readable records.",logsSelectTitle:"Protection records",logsTruncated:" (limited tail)",logsRevealTitle:"Sensitive plaintext",logsRevealBody:"Reveal locally? Never share this view.",logsPreviewTitle:"Local preview; edits are discarded",logsPreviewTruncated:"[Preview truncated]",clearTitle:"Clear the current audit log?",clearBody:"Irreversible. Only this machine's log is cleared; configuration and in-memory mappings stay. Later requests may add new records.",cleared:"Audit log cleared: {bytes}.",toolBlocked:"SPI Protecter blocked tool access to the protected configuration or audit log; edit it locally.",compactAskTitle:"Compact this conversation?",compactAskBody:`Pi builds the summarization request internally and never routes it through this extension's redaction, so 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."},ke={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.",compactDegraded:"SPI Protecter: the model produced no usable summary, so a local one was used. It lists facts rather than interpreting them, so earlier context is less detailed.",compactModelConfigured:"SPI Protecter: compaction will summarize with {model}. It receives the whole conversation, redacted, so prefer a local or otherwise trusted endpoint.",compactEarly:"SPI Protecter: compacting early at {tokens} so the summarization model can still read the conversation.",compactMainModel:"the current model",compactNoThreshold:"Pi's own threshold",statusCompaction:"Compaction: {mode} via {target}; compacts above {threshold}.",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."},We={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(n=process.env){let e=n.PI_PROTECTER_LANG||n.LC_ALL||n.LC_MESSAGES||n.LANG||n.LANGUAGE||Me();return/^zh\b|^zh[-_]/i.test(e.trim())?"zh":"en"}function Me(){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"?ke:ee)[n]??ee[n]).replace(/\{(\w+)\}/g,(t,o)=>Object.hasOwn(e,o)?String(e[o]):t)}var Fe={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=Fe[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"?Le[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","status"],be=/^[A-Za-z][A-Za-z0-9]{0,39}$/,xe=/^(EACCES|EPERM|ENOENT|ENOSPC|EDQUOT|EROFS|ELOOP|EISDIR|ENOTDIR|EMFILE|ENFILE|EIO|EEXIST|EBADF|EBUSY|ENOTEMPTY)$/;function Ge(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"&&xe.test(e.errno)&&(o.errno=e.errno),typeof e.errorName=="string"&&be.test(e.errorName)&&(o.errorName=e.errorName),{code:n,stage:ie[n],reason:r,action:t,...o}}function S(n){let e=re()==="zh"?":":": ",r=[...se,"errno","errorName"].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=Ge(e,r);super(S(t)),this.name="ProtectionError",this.diagnostic=t}};function s(n,e={}){return new C(n,e)}function I(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 ve,fstatSync as Ue,mkdirSync as ze,openSync as ce,readFileSync as Be,writeFileSync as He}from"node:fs";import{dirname as $e}from"node:path";var Je=["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")&&!Je.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){ze($e(n),{recursive:!0,mode:448});try{let c=ce(n,_.O_WRONLY|_.O_CREAT|_.O_EXCL,384);try{He(c,JSON.stringify($,null,2)+`
12
- `)}finally{ae(c)}}catch(c){if(c.code!=="EEXIST")throw I(c,"CONFIG_IO")}}r=ce(n,_.O_RDONLY|_.O_NOFOLLOW|_.O_NONBLOCK);let t=Ue(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"&&ve(r,384);let o=Be(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 I(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 qe(n){return new Promise((e,r)=>{let t=new je(Xe(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 Ze(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=h.lstatSync(n,{bigint:!0})}catch(r){throw I(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:Ye("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 h.readdirSync(n).filter(e=>Y.test(e)).sort()}function fe(n){if(process.platform==="win32")return;let e=h.openSync(n,h.constants.O_RDONLY);try{h.fsyncSync(e)}finally{h.closeSync(e)}}async function me(n,e,r={}){if(!/^[a-f0-9]{32}$/.test(e))throw s("MACHINE_ID");let t=We(n),o=`protecter.${e}.json`,c=T(t,o);h.mkdirSync(t,{recursive:!0,mode:448});let u=T(t,".protecter-migration.lock"),d=Date.now()+(r.lockTimeoutMs??5e3);for(;;)try{h.mkdirSync(u,{mode:448});break}catch(i){if(i.code!=="EEXIST")throw I(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)),p=Ze(f.length?f.map(O=>O.config):[$]);if(await qe([p]),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 y=JSON.stringify(p,null,2)+`
13
- `;if(Buffer.byteLength(y)>1024*1024)throw s("CONFIG_SIZE",{bytes:Buffer.byteLength(y),limit:1024*1024});a=T(t,`.protecter-migration.${Ke()}.tmp`);let A=h.openSync(a,h.constants.O_WRONLY|h.constants.O_CREAT|h.constants.O_EXCL,384);try{h.writeFileSync(A,y),h.fsyncSync(A)}finally{h.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);h.renameSync(a,c),a=void 0,fe(t);let N=W(t,o);if(N.raw!==y)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),h.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:p,raw:y,sourceRaws:[...new Set([...f.map(O=>O.raw),y])],migrated:f.filter(O=>O.name!==o).length}}catch(i){throw i instanceof C?i:I(i,"MIGRATION_IO")}finally{if(a)try{h.unlinkSync(a)}catch{}h.rmdirSync(u)}}import{createHash as Ve}from"node:crypto";import{readFileSync as Qe}from"node:fs";import{execFileSync as ge}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 Ve("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 n=ge("/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=ge("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 g from"node:fs";import{randomUUID as et}from"node:crypto";var he=32*1024*1024,ye=8*1024*1024;function tt(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=g.openSync(n,(e?g.constants.O_RDWR|(r?g.constants.O_CREAT:0):g.constants.O_RDONLY)|g.constants.O_NOFOLLOW|g.constants.O_NONBLOCK,384);try{let o=g.fstatSync(t);if(!o.isFile()||o.nlink!==1||process.getuid&&o.uid!==process.getuid())throw s("AUDIT_UNSAFE");return process.platform!=="win32"&&g.fchmodSync(t,384),t}catch(o){throw g.closeSync(t),I(o,"AUDIT_UNSAFE")}}function F(n){let e=n&&typeof n=="object"&&"code"in n?n.code:void 0;return I(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 g.mkdirSync(e,{mode:448}),e}catch(t){if(t.code!=="EEXIST")throw I(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=g.fstatSync(r).size;return g.ftruncateSync(r,0),g.fsyncSync(r),t}catch(t){throw F(t)}finally{try{r!==void 0&&g.closeSync(r)}finally{g.rmdirSync(e)}}}async function Ae(n,e,r){if(!r.length)return;let t=new Date,o=et(),c=Buffer.from(r.map(([a,i])=>JSON.stringify({version:1,time:tt(t),timezoneOffset:-t.getTimezoneOffset(),requestId:o,provider:e||"unknown",original:i,replacement:a})).join(`
10
+ 若选择允许,本次请求不会被拦截。`,compactAllowOnce:"允许一次",compactAllowAlways:"本会话内全部允许",compactDenyOnce:"拒绝一次",compactDenyAlways:"本会话内全部拒绝",compactWorking:"SPI Protecter:正在对脱敏内容生成摘要…",compactDone:"SPI Protecter:已基于脱敏内容生成压缩摘要。",compactDegraded:"SPI Protecter:模型未产出可用摘要,已改用本地摘要。它只罗列事实而不做理解,因此早期上下文会更粗略。",compactModelConfigured:"SPI Protecter:压缩将使用 {model} 生成摘要。它会收到脱敏后的整段对话,请优先使用本地或可信端点。",compactEarly:"SPI Protecter:已在 {tokens} 提前压缩,以便摘要模型仍能读取该对话。",compactMainModel:"当前模型",compactNoThreshold:"Pi 自身阈值",statusCompaction:"压缩:{mode},经由 {target};超过 {threshold} 时压缩。",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 j(o=process.env){let e=o.PI_PROTECTER_LANG||o.LC_ALL||o.LC_MESSAGES||o.LANG||o.LANGUAGE||He();return/^zh\b|^zh[-_]/i.test(e.trim())?"zh":"en"}function He(){try{return new Intl.DateTimeFormat().resolvedOptions().locale}catch{return""}}var w=j();function le(){return w}function de(o){w=o}function g(o,e={}){return((w==="zh"?We:ae)[o]??ae[o]).replace(/\{(\w+)\}/g,(t,r)=>Object.hasOwn(e,r)?String(e[r]):t)}var Je={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"}},zh:{rules:{other:"规则 {n} 条"},mappings:{other:"映射 {n} 个"},bytes:{other:"{n} 字节"},tokens:{other:"{n} token"}}},ce=new Map;function S(o,e){let n=w==="zh"?"zh-CN":"en",t=ce.get(w);if(!t){try{t=new Intl.PluralRules(n)}catch{t=void 0}t&&ce.set(w,t)}let r=t?.select(e)??"other",a=Je[w][o],c=a[r]??a.other,u=new Intl.NumberFormat(n).format(e);return c.replace("{n}",u)}function ue(o){let n=(w==="zh"?$e[o]:Y[o])??Y[o]??Y.INTERNAL;return{reason:n[0],action:n[1]}}var fe={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",CONFIG_COMPACT_MODEL:"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",COMPACT_EMPTY:"compaction",AUDIT_BATCH_LIMIT:"audit",AUDIT_FULL:"audit",AUDIT_PARTIAL:"audit",AUDIT_LOCKED:"audit",AUDIT_UNSAFE:"audit",AUDIT_IO:"audit"};var me=["rule","otherRule","node","bytes","limit","timeoutMs","status"],Ye=/^[A-Za-z][A-Za-z0-9]{0,39}$/,je=/^(EACCES|EPERM|ENOENT|ENOSPC|EDQUOT|EROFS|ELOOP|EISDIR|ENOTDIR|EMFILE|ENFILE|EIO|EEXIST|EBADF|EBUSY|ENOTEMPTY)$/;function Ke(o,e={}){let{reason:n,action:t}=ue(o),r={};for(let a of me){let c=e[a];typeof c=="number"&&Number.isSafeInteger(c)&&c>=0&&(r[a]=c)}return typeof e.errno=="string"&&je.test(e.errno)&&(r.errno=e.errno),typeof e.errorName=="string"&&Ye.test(e.errorName)&&(r.errorName=e.errorName),{code:o,stage:fe[o],reason:n,action:t,...r}}function _(o){let e=le()==="zh"?":":": ",n=[...me,"errno","errorName"].filter(t=>o[t]!==void 0).map(t=>`${t}=${o[t]}`).join(" ");return[g("blockedHeader"),`code=${o.code} stage=${o.stage}${n?` ${n}`:""}`,`${g("reasonLabel")}${e}${o.reason}`,`${g("actionLabel")}${e}${o.action}`,`${g("detailsLabel")}${e}/protecter status`].join(`
11
+ `)}var T=class extends Error{diagnostic;constructor(e,n={}){let t=Ke(e,n);super(_(t)),this.name="ProtectionError",this.diagnostic=t}};function i(o,e={}){return new T(o,e)}function O(o,e,n={}){if(o instanceof T)return i(o.diagnostic.code,{...o.diagnostic,...n});let t=o&&typeof o=="object"&&"code"in o?o.code:void 0;return i(e,{...n,errno:typeof t=="string"?t:void 0})}function b(o,e){if(!o||typeof o!="object")return i(e);let n=o,t=typeof n.code=="string"&&Object.hasOwn(fe,n.code)?n.code:e;return i(t,n)}import{constants as R,closeSync as pe,fchmodSync as Xe,fstatSync as qe,mkdirSync as Ze,openSync as ge,readFileSync as Ve,writeFileSync as Qe}from"node:fs";import{dirname as et}from"node:path";var he=["ask","protected","off"],K={version:1,sensitiveWords:[]},F="ask";function tt(o){if(typeof o=="string"){if(!he.includes(o))throw i("CONFIG_COMPACTION");return}if(!o||typeof o!="object"||Array.isArray(o))throw i("CONFIG_COMPACTION");let e=o,n=["mode","provider","model","contextWindow","reserveTokens"];if(Object.keys(e).some(a=>!n.includes(a)))throw i("CONFIG_COMPACTION");if(e.mode!==void 0&&!he.includes(e.mode))throw i("CONFIG_COMPACTION");for(let a of["provider","model"]){let c=e[a];if(c!==void 0&&(typeof c!="string"||!c.trim()||c.length>200))throw i("CONFIG_COMPACTION")}if(e.provider===void 0!=(e.model===void 0))throw i("CONFIG_COMPACT_MODEL");for(let a of["contextWindow","reserveTokens"]){let c=e[a];if(c!==void 0&&(typeof c!="number"||!Number.isSafeInteger(c)||c<=0||c>1e8))throw i("CONFIG_COMPACTION")}let t=e.contextWindow,r=e.reserveTokens;if(t!==void 0&&r!==void 0&&r>=t)throw i("CONFIG_COMPACTION")}function v(o){return o===void 0?{mode:F}:typeof o=="string"?{mode:o}:{...o,mode:o.mode??F}}function X(o){let e;try{e=JSON.parse(o)}catch{throw i("CONFIG_JSON")}let n=0;try{if(!e||e.version!==1||!Array.isArray(e.sensitiveWords)||Object.keys(e).some(r=>!["version","sensitiveWords","compaction"].includes(r)))throw i("CONFIG_SCHEMA");if(Object.hasOwn(e,"compaction")&&tt(e.compaction),e.sensitiveWords.length>1e3)throw i("CONFIG_SIZE",{limit:1e3});let t=new Map;for(let r of e.sensitiveWords){if(n++,typeof r=="string"){if(!r||r.length>8192)throw i("CONFIG_SCHEMA",{rule:n,limit:8192});let c=JSON.stringify(["literal",r]);if(t.has(c)&&t.get(c)!==void 0)throw i("CONFIG_CONFLICT",{rule:n});t.set(c,void 0);continue}if(!r||typeof r!="object")throw i("CONFIG_SCHEMA",{rule:n});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:n,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:n,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:n,limit:8192});try{new RegExp(r.pattern,r.flags??"")}catch{throw i("CONFIG_REGEX",{rule:n})}}else throw i("CONFIG_SCHEMA",{rule:n});let a=r.type==="literal"?JSON.stringify(["literal",r.value]):JSON.stringify(["regex",r.pattern,[...new Set((r.flags??"")+"g")].sort().join("")]);if(t.has(a)&&t.get(a)!==r.replacement)throw i("CONFIG_CONFLICT",{rule:n});t.set(a,r.replacement)}return e}catch(t){throw t instanceof T?t:i("CONFIG_SCHEMA",{rule:n})}}function ye(o,e=!1){let n;try{if(e){Ze(et(o),{recursive:!0,mode:448});try{let a=ge(o,R.O_WRONLY|R.O_CREAT|R.O_EXCL,384);try{Qe(a,JSON.stringify(K,null,2)+`
12
+ `)}finally{pe(a)}}catch(a){if(a.code!=="EEXIST")throw O(a,"CONFIG_IO")}}n=ge(o,R.O_RDONLY|R.O_NOFOLLOW|R.O_NONBLOCK);let t=qe(n);if(t.size>1024*1024)throw i("CONFIG_SIZE",{bytes:t.size,limit:1024*1024});if(!t.isFile()||t.nlink!==1||process.getuid&&t.uid!==process.getuid())throw i("CONFIG_UNSAFE");process.platform!=="win32"&&Xe(n,384);let r=Ve(n,"utf8");if(Buffer.byteLength(r)>1024*1024)throw i("CONFIG_SIZE",{bytes:Buffer.byteLength(r),limit:1024*1024});return{config:X(r),raw:r}}catch(t){let r=t&&typeof t=="object"&&"code"in t?t.code:void 0;throw O(t,r==="ELOOP"||r==="EISDIR"||r==="ENOTDIR"?"CONFIG_UNSAFE":"CONFIG_IO")}finally{n!==void 0&&pe(n)}}var Z=/^protecter(?:\.[a-f0-9]{32})?\.json$/;function at(o){return new Promise((e,n)=>{let t=new it(st(new URL("./validate-worker.mjs",import.meta.url)),{workerData:o,execArgv:[],resourceLimits:{maxOldGenerationSizeMb:64}}),r=!1,a=(u,m=i("WORKER_FAILED"))=>{r||(r=!0,clearTimeout(c),t.terminate(),u?e():n(m))},c=setTimeout(()=>a(!1,i("CONFIG_TIMEOUT",{timeoutMs:2e3})),2e3);t.once("message",u=>u===!0?a(!0):a(!1,b(u,"CONFIG_SCHEMA"))),t.once("error",()=>a(!1)),t.once("exit",()=>a(!1))})}function ct(o){let e=new Set,n=[];for(let f of o)for(let h of f.sensitiveWords){let l=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(l)||(e.add(l),n.push(h))}let t=[];for(let f of o)f.compaction!==void 0&&t.push(v(f.compaction));let a=["off","ask","protected"].find(f=>t.some(h=>h.mode===f)),c=t.find(f=>f.provider&&f.model),u={version:1,sensitiveWords:n};if(a!==void 0||c!==void 0){let f={mode:a??F};c&&(f.provider=c.provider,f.model=c.model,c.contextWindow!==void 0&&(f.contextWindow=c.contextWindow),c.reserveTokens!==void 0&&(f.reserveTokens=c.reserveTokens)),u.compaction=f}let m=JSON.stringify(u);if(Buffer.byteLength(m)>1024*1024)throw i("CONFIG_SIZE",{bytes:Buffer.byteLength(m),limit:1024*1024});return X(m)}function Ie(o){let e;try{e=I.lstatSync(o,{bigint:!0})}catch(n){throw O(n,"CONFIG_IO")}if(!e.isFile()||e.nlink!==1n||process.getuid&&e.uid!==BigInt(process.getuid()))throw i("CONFIG_UNSAFE");return`${e.dev}:${e.ino}:${e.size}:${e.mtimeNs}`}function q(o,e){let n=P(o,e),t=Ie(n),r=ye(n);if(Ie(n)!==t)throw i("MIGRATION_CHANGED");return{name:e,...r,identity:t,digest:nt("sha256").update(r.raw).digest("hex")}}function L(o,e){let n=q(o,e.name);if(n.identity!==e.identity||n.digest!==e.digest)throw i("MIGRATION_CHANGED")}function x(o){return I.readdirSync(o).filter(e=>Z.test(e)).sort()}function Oe(o){if(process.platform==="win32")return;let e=I.openSync(o,I.constants.O_RDONLY);try{I.fsyncSync(e)}finally{I.closeSync(e)}}async function Ce(o,e,n={}){if(!/^[a-f0-9]{32}$/.test(e))throw i("MACHINE_ID");let t=ot(o),r=`protecter.${e}.json`,a=P(t,r);I.mkdirSync(t,{recursive:!0,mode:448});let c=P(t,".protecter-migration.lock"),u=Date.now()+(n.lockTimeoutMs??5e3);for(;;)try{I.mkdirSync(c,{mode:448});break}catch(f){if(f.code!=="EEXIST")throw O(f,"MIGRATION_IO");if(Date.now()>=u)throw i("MIGRATION_LOCKED",{timeoutMs:n.lockTimeoutMs??5e3});await new Promise(h=>setTimeout(h,50))}let m;try{let f=x(t);if(f.length>64)throw i("MIGRATION_LIMIT",{limit:64});let l=[...f].sort((C,D)=>C===r?-1:D===r?1:C.localeCompare(D)).map(C=>q(t,C)),s=ct(l.length?l.map(C=>C.config):[K]);if(await at([s]),l.length===1&&l[0].name===r){if(L(t,l[0]),JSON.stringify(x(t))!==JSON.stringify(f))throw i("MIGRATION_CHANGED");return{path:a,config:l[0].config,raw:l[0].raw,sourceRaws:[l[0].raw],migrated:0}}let d=JSON.stringify(s,null,2)+`
13
+ `;if(Buffer.byteLength(d)>1024*1024)throw i("CONFIG_SIZE",{bytes:Buffer.byteLength(d),limit:1024*1024});m=P(t,`.protecter-migration.${rt()}.tmp`);let p=I.openSync(m,I.constants.O_WRONLY|I.constants.O_CREAT|I.constants.O_EXCL,384);try{I.writeFileSync(p,d),I.fsyncSync(p)}finally{I.closeSync(p)}if(n.checkpoint?.("beforeCommit",a),JSON.stringify(x(t))!==JSON.stringify(f))throw i("MIGRATION_CHANGED");for(let C of l)L(t,C);I.renameSync(m,a),m=void 0,Oe(t);let A=q(t,r);if(A.raw!==d)throw i("MIGRATION_CHANGED");n.checkpoint?.("afterCommit",a);for(let C of l)C.name!==r&&(n.checkpoint?.("beforeDelete",P(t,C.name)),L(t,A),L(t,C),I.unlinkSync(P(t,C.name)));Oe(t);let N=[r];if(JSON.stringify(x(t))!==JSON.stringify(N))throw i("MIGRATION_CHANGED");return L(t,A),{path:a,config:s,raw:d,sourceRaws:[...new Set([...l.map(C=>C.raw),d])],migrated:l.filter(C=>C.name!==r).length}}catch(f){throw f instanceof T?f:O(f,"MIGRATION_IO")}finally{if(m)try{I.unlinkSync(m)}catch{}I.rmdirSync(c)}}import{createHash as lt}from"node:crypto";import{readFileSync as dt}from"node:fs";import{execFileSync as Ae}from"node:child_process";function V(o){let e=o.trim().toLowerCase().replace(/-/g,"");if(!/^[a-f0-9]{32}$/.test(e)||/^0+$/.test(e))throw i("MACHINE_ID");return lt("sha256").update(`pi-information-protecter:v1:${e}`).digest("hex").slice(0,32)}function Ne(){try{if(process.platform==="linux")return V(dt("/etc/machine-id","utf8"));if(process.platform==="darwin"){let o=Ae("/usr/sbin/ioreg",["-rd1","-c","IOPlatformExpertDevice"],{encoding:"utf8",timeout:5e3,maxBuffer:1048576,stdio:["ignore","pipe","pipe"]});return V(o.match(/"IOPlatformUUID"\s*=\s*"([a-fA-F0-9-]+)"/)?.[1]??"")}if(process.platform==="win32"){let o=Ae("reg.exe",["query","HKLM\\SOFTWARE\\Microsoft\\Cryptography","/v","MachineGuid","/reg:64"],{encoding:"utf8",timeout:5e3,maxBuffer:65536,stdio:["ignore","pipe","pipe"]});return V(o.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 ut}from"node:crypto";var Ee=32*1024*1024,we=8*1024*1024;function ft(o){let e=n=>String(n).padStart(2,"0");return`${o.getFullYear()}-${e(o.getMonth()+1)}-${e(o.getDate())} ${e(o.getHours())}:${e(o.getMinutes())}:${e(o.getSeconds())}`}function Q(o,e,n=e){let t=y.openSync(o,(e?y.constants.O_RDWR|(n?y.constants.O_CREAT:0):y.constants.O_RDONLY)|y.constants.O_NOFOLLOW|y.constants.O_NONBLOCK,384);try{let r=y.fstatSync(t);if(!r.isFile()||r.nlink!==1||process.getuid&&r.uid!==process.getuid())throw i("AUDIT_UNSAFE");return process.platform!=="win32"&&y.fchmodSync(t,384),t}catch(r){throw y.closeSync(t),O(r,"AUDIT_UNSAFE")}}function G(o){let e=o&&typeof o=="object"&&"code"in o?o.code:void 0;return O(o,e==="ELOOP"||e==="EISDIR"||e==="ENOTDIR"?"AUDIT_UNSAFE":"AUDIT_IO")}async function Te(o){let e=`${o}.lock`,n=Date.now()+2e3;for(;;)try{return y.mkdirSync(e,{mode:448}),e}catch(t){if(t.code!=="EEXIST")throw O(t,"AUDIT_IO");if(Date.now()>=n)throw i("AUDIT_LOCKED",{timeoutMs:2e3});await new Promise(r=>setTimeout(r,25))}}async function Se(o){let e=await Te(o),n;try{try{n=Q(o,!0,!1)}catch(r){if(r.code==="ENOENT")return 0;throw r}let t=y.fstatSync(n).size;return y.ftruncateSync(n,0),y.fsyncSync(n),t}catch(t){throw G(t)}finally{try{n!==void 0&&y.closeSync(n)}finally{y.rmdirSync(e)}}}async function _e(o,e,n){if(!n.length)return;let t=new Date,r=ut(),a=Buffer.from(n.map(([m,f])=>JSON.stringify({version:1,time:ft(t),timezoneOffset:-t.getTimezoneOffset(),requestId:r,provider:e||"unknown",original:f,replacement:m})).join(`
14
14
  `)+`
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=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),F(i)}}catch(a){throw F(a)}finally{d!==void 0&&g.closeSync(d),g.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(p){if(p.code==="ENOENT")return{records:[],truncated:!1};throw p}let t=g.fstatSync(r).size,o=Math.max(0,t-1024*1024),c=Buffer.alloc(t-o),u=g.readSync(r,c,0,c.length,o),d=c.subarray(0,u).toString("utf8");if(o){let p=d.indexOf(`
16
- `);d=p<0?"":d.slice(p+1)}let a=d.split(`
17
- `),i=a.pop()!=="",l=[],f=!1;for(let p of a.slice(-e))try{let y=JSON.parse(p);if(y.version!==1||typeof y.time!="string"||typeof y.provider!="string"||typeof y.original!="string"||typeof y.replacement!="string"||typeof y.requestId!="string"||typeof y.timezoneOffset!="number")throw new Error;l.push(y)}catch{f=!0}return{records:l,truncated:o>0||a.length>e||i||f}}catch(t){throw F(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=I(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=I(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 rt(nt(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(I(A,"WORKER_FAILED"));return}this.workers.add(f);let p=(A,N=s("WORKER_FAILED"))=>{if(!l){if(l=!0,clearTimeout(y),this.workers.delete(f),f.terminate(),!A||this.closed){i(this.closed?s("NOT_READY"):N);return}a(A)}},y=setTimeout(()=>p(void 0,s("SCAN_TIMEOUT",{timeoutMs:this.timeoutMs})),this.timeoutMs);f.once("message",A=>{A?.failed?p(void 0,k(A.diagnostic,"SCAN_INTERNAL")):A&&Array.isArray(A.additions)&&Array.isArray(A.hits)?p(A):p()}),f.once("error",()=>p()),f.once("exit",()=>p())});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 ot,statSync as Ee,readdirSync as it}from"node:fs";import{homedir as st}from"node:os";import{basename as X,dirname as P,isAbsolute as at,relative as Se,resolve as x}from"node:path";import{fileURLToPath as ct}from"node:url";function lt(n,e){let r=n.replace(/^@/,"");return r.startsWith("file://")&&(r=ct(r)),(r==="~"||r.startsWith("~/"))&&(r=st()+r.slice(1)),x(e,r)}function q(n){try{return ot(n)}catch{let e=P(n);return e===n?n:x(q(e),Se(e,n))}}function ut(n,e){let r=Se(n,e);return r===""||!r.startsWith("..")&&!at(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=lt(typeof c=="string"?c:".",r),a=q(d),i=/^protecter\.[a-f0-9]{32}\.jsonl(?:\.lock)?$/,l=it(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&&ut(a,o)}catch{return!0}}import{generateBranchSummary as dt,generateSummaryWithUsage as ft}from"@earendil-works/pi-coding-agent";function Te(n){let e={};if(!n||typeof n!="object")return e;let r=n.name;typeof r=="string"?e.errorName=r:typeof n.constructor?.name=="string"&&(e.errorName=n.constructor.name);for(let t of["status","statusCode"]){let o=n[t];if(typeof o=="number"&&Number.isSafeInteger(o)&&o>=0){e.status=o;break}}return e}async function we(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 Re(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 De(n,e,r,t,o=ft){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 we(e),l,f;try{let p=await o(u,i.model,c.settings.reserveTokens,i.apiKey,i.headers,n.signal,a,d,e.thinkingLevel,Re(e),i.env);l=p.text,f=p.usage}catch(p){let y=I(p,"COMPACT_FAILED");throw y.diagnostic.code==="COMPACT_FAILED"?s("COMPACT_FAILED",Te(p)):y}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 Pe(n,e,r,t,o=dt){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 we(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:Re(e)})}catch(f){let p=I(f,"COMPACT_FAILED");throw p.diagnostic.code==="COMPACT_FAILED"?s("COMPACT_FAILED",Te(f)):p}let l=i?.summary;if(typeof l!="string"||!l.trim())throw s("COMPACT_FAILED");return{summary:r.restoreText(l),usage:i.usage}}function pt(n){ne(H());let e=new b(mt()),r=Q(gt),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(I(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(I(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")],p=await a.ui.select(`${m("compactAskTitle")}
15
+ `);if(a.length>we)throw i("AUDIT_BATCH_LIMIT",{bytes:a.length,limit:we});let c=await Te(o),u;try{u=Q(o,!0);let m=y.fstatSync(u).size;if(m+a.length>Ee)throw i("AUDIT_FULL",{bytes:m+a.length,limit:Ee});if(m){let f=Buffer.alloc(1);if(y.readSync(u,f,0,1,m-1),f[0]!==10)throw i("AUDIT_PARTIAL")}try{let f=0;for(;f<a.length;){let h=y.writeSync(u,a,f,a.length-f,m+f);if(!h)throw i("AUDIT_IO");f+=h}y.fsyncSync(u)}catch(f){throw y.ftruncateSync(u,m),y.fsyncSync(u),G(f)}}catch(m){throw G(m)}finally{u!==void 0&&y.closeSync(u),y.rmdirSync(c)}}function Re(o,e=20){if(!Number.isInteger(e)||e<1||e>100)throw i("INTERNAL",{limit:100});let n;try{try{n=Q(o,!1)}catch(s){if(s.code==="ENOENT")return{records:[],truncated:!1};throw s}let t=y.fstatSync(n).size,r=Math.max(0,t-1024*1024),a=Buffer.alloc(t-r),c=y.readSync(n,a,0,a.length,r),u=a.subarray(0,c).toString("utf8");if(r){let s=u.indexOf(`
16
+ `);u=s<0?"":u.slice(s+1)}let m=u.split(`
17
+ `),f=m.pop()!=="",h=[],l=!1;for(let s of m.slice(-e))try{let d=JSON.parse(s);if(d.version!==1||typeof d.time!="string"||typeof d.provider!="string"||typeof d.original!="string"||typeof d.replacement!="string"||typeof d.requestId!="string"||typeof d.timezoneOffset!="number")throw new Error;h.push(d)}catch{l=!0}return{records:h,truncated:r>0||m.length>e||f||l}}catch(t){throw G(t)}finally{n!==void 0&&y.closeSync(n)}}var U=class{constructor(e,n=2e3,t=Ne){this.configDir=e;this.timeoutMs=n;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?_(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 n=await Ce(this.configDir,e);if(this.closed)throw i("NOT_READY");this.snapshot=n,this.lastError=void 0}catch(e){let n=O(e,"CONFIG_IO");throw this.lastError=n.diagnostic,n}}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 Re(this.auditPath,e)}clearAuditRecords(){let e=this.queue.then(()=>{if(!this.ready)throw this.notReady();return Se(this.auditPath)});return this.queue=e.catch(()=>{}),e}get ruleCount(){return this.snapshot?.config.sensitiveWords.length??0}get compaction(){return v(this.snapshot?.config.compaction)}get compactionMode(){return this.compaction.mode}get ready(){return!!this.snapshot&&!this.closed}get mappingCount(){return this.tokens.size}redact(e,n="unknown"){let t=this.queue.then(()=>this.scan(e,n)).catch(r=>{let a=O(r,"INTERNAL");throw this.lastError=a.diagnostic,a});return this.queue=t.catch(()=>{}),t}notReady(){return this.lastError?i(this.lastError.code,this.lastError):i("NOT_READY")}async scan(e,n){if(!this.ready)throw this.notReady();let{config:t,sourceRaws:r}=this.snapshot,a;try{a=JSON.stringify(e)}catch{throw i("PAYLOAD_JSON")}if(!a)throw i("PAYLOAD_JSON");if(Buffer.byteLength(a)>8*1024*1024)throw i("PAYLOAD_SIZE",{bytes:Buffer.byteLength(a),limit:8*1024*1024});let c;try{c=JSON.parse(a)}catch{throw i("PAYLOAD_JSON")}let u=await new Promise((m,f)=>{let h=!1,l;try{l=new mt(pt(new URL("./scan-worker.mjs",import.meta.url)),{workerData:{payload:c,rules:t.sensitiveWords,entries:[...this.tokens],configRaws:r},execArgv:[],resourceLimits:{maxOldGenerationSizeMb:128}})}catch(p){f(O(p,"WORKER_FAILED"));return}this.workers.add(l);let s=(p,A=i("WORKER_FAILED"))=>{if(!h){if(h=!0,clearTimeout(d),this.workers.delete(l),l.terminate(),!p||this.closed){f(this.closed?i("NOT_READY"):A);return}m(p)}},d=setTimeout(()=>s(void 0,i("SCAN_TIMEOUT",{timeoutMs:this.timeoutMs})),this.timeoutMs);l.once("message",p=>{p?.failed?s(void 0,b(p.diagnostic,"SCAN_INTERNAL")):p&&Array.isArray(p.additions)&&Array.isArray(p.hits)?s(p):s()}),l.once("error",()=>s()),l.once("exit",()=>s())});if(this.closed)throw i("NOT_READY");if(await _e(this.auditPath,n,u.hits),this.closed)throw i("NOT_READY");for(let[m,f]of u.additions)this.tokens.set(m,f);return u.payload}restoreText(e){if(!this.tokens.size)return e;if(this.restoreSize!==this.tokens.size){let n=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.restorePattern=new RegExp([...this.tokens.keys()].sort((t,r)=>r.length-t.length).map(n).join("|"),"g"),this.restoreSize=this.tokens.size}return e.replace(this.restorePattern,n=>this.tokens.get(n)??n)}restore(e,n=0){if(n>80)throw i("RESTORE_COMPLEXITY",{node:n});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 r=Number(t);return!Number.isFinite(r)||String(r)!==t?e:r}if(Array.isArray(e))return e.map(t=>this.restore(t,n+1));if(e&&typeof e=="object"){let t=Object.create(null);for(let[r,a]of Object.entries(e)){let c=this.restoreText(r);if(Object.hasOwn(t,c))throw i("RESTORE_KEY_COLLISION");t[c]=this.restore(a,n+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 gt,statSync as Pe,readdirSync as ht}from"node:fs";import{homedir as yt}from"node:os";import{basename as ee,dirname as k,isAbsolute as It,relative as Le,resolve as z}from"node:path";import{fileURLToPath as Ot}from"node:url";function Ct(o,e){let n=o.replace(/^@/,"");return n.startsWith("file://")&&(n=Ot(n)),(n==="~"||n.startsWith("~/"))&&(n=yt()+n.slice(1)),z(e,n)}function te(o){try{return gt(o)}catch{let e=k(o);return e===o?o:z(te(e),Le(e,o))}}function At(o,e){let n=Le(o,e);return n===""||!n.startsWith("..")&&!It(n)}function De(o,e){try{let n=Pe(o),t=Pe(e);return n.dev===t.dev&&n.ino===t.ino}catch{return!1}}function ke(o,e,n,t){if(!t)return!0;let r=te(z(t));if(["bash","powershell"].includes(o)){let u=typeof e.command=="string"?e.command:"";if(/protecter(?:\.[a-f0-9]{32})?\.jsonl?|\.protecter-migration/i.test(u)||u.includes(t))return!0}let a=e.path??e.file_path??e.filePath,c=["grep","find","ls"].includes(o);if(typeof a!="string"&&!c)return!1;try{let u=Ct(typeof a=="string"?a:".",n),m=te(u),f=/^protecter\.[a-f0-9]{32}\.jsonl(?:\.lock)?$/,h=ht(k(r)).filter(l=>f.test(l)).some(l=>De(u,z(k(r),l)));return k(m)===k(r)&&(Z.test(ee(m))||f.test(ee(m))||ee(m).startsWith(".protecter-migration"))||m===r||De(u,t)||h||c&&At(m,r)}catch{return!0}}import{DEFAULT_COMPACTION_SETTINGS as Nt,generateBranchSummary as Et,generateSummaryWithUsage as wt}from"@earendil-works/pi-coding-agent";function Me(o){let e={};if(!o||typeof o!="object")return e;let n=o.name;typeof n=="string"?e.errorName=n:typeof o.constructor?.name=="string"&&(e.errorName=o.constructor.name);for(let t of["status","statusCode"]){let r=o[t];if(typeof r=="number"&&Number.isSafeInteger(r)&&r>=0){e.status=r;break}}return e}function B(o,e){if(!e?.provider||!e.model)return o.model;let n=o.modelRegistry.find(e.provider,e.model);if(!n)throw i("CONFIG_COMPACT_MODEL");return n}function oe(o,e,n){let t;try{t=B(o,e)}catch{return}let r=e.contextWindow??t?.contextWindow;if(typeof r!="number"||r<=0)return;let a=e.reserveTokens??n??Nt.reserveTokens;if(!(a>=r))return{window:r,reserve:a,threshold:r-a}}async function be(o,e){let n=B(o,e);if(!n)throw i("COMPACT_UNAVAILABLE");let t;try{t=await o.modelRegistry.getApiKeyAndHeaders(n)}catch{throw i("COMPACT_UNAVAILABLE")}if(!t.ok)throw i("COMPACT_UNAVAILABLE");let r=Object.fromEntries(Object.entries(t.headers??{}).filter(a=>typeof a[1]=="string"));return{model:n,apiKey:t.apiKey,headers:r,env:t.env}}function Fe(o){let e=o.modelRegistry;if(typeof e.streamSimple=="function")return(n,t,r)=>e.streamSimple(n,t,r);if(typeof e.complete=="function")return(n,t,r)=>({result:()=>e.complete(n,t,r)})}function Tt(o){let e=[],n=[],t=new Map,r=(u,m)=>u.length>m?`${u.slice(0,m)}…`:u;for(let u of o){let m=u;if(Array.isArray(m.content))for(let f of m.content){let h=f;if(h.type==="toolCall"&&typeof h.name=="string"&&t.set(h.name,(t.get(h.name)??0)+1),h.type!=="text"||typeof h.text!="string")continue;let l=h.text.trim();l&&(m.role==="user"?e.push(r(l,300)):m.role==="assistant"&&n.push(r(l,300)))}}let a=[...t.entries()].sort((u,m)=>m[1]-u[1]).slice(0,12).map(([u,m])=>`${u} x${m}`);return["# Local compaction summary","","Generated locally without a model call, so it lists facts rather than","interpreting them. Protected values appear as their replacements.","",`- Messages summarized: ${o.length}`,a.length?`- Tools used: ${a.join(", ")}`:"","","## Requests",...e.length?e.slice(-12).map(u=>`- ${u}`):["- (none recorded)"],"","## Latest replies",...n.length?n.slice(-6).map(u=>`- ${u}`):["- (none recorded)"]].filter(u=>u!=="").join(`
18
+ `)}async function ve(o,e,n,t,r=wt,a){let{preparation:c}=o,u=await n.redact(c.messagesToSummarize,t),m=c.previousSummary===void 0?void 0:await n.redact(c.previousSummary,t),f=o.customInstructions===void 0?void 0:await n.redact(o.customInstructions,t),h="",l,s;try{let d=await be(e,a),p=await r(u,d.model,c.settings.reserveTokens,d.apiKey,d.headers,o.signal,f,m,e.thinkingLevel,Fe(e),d.env);h=typeof p.text=="string"?p.text:"",l=p.usage,h.trim()||(s=i("COMPACT_EMPTY").diagnostic)}catch(d){let p=O(d,"COMPACT_FAILED");s=p.diagnostic.code==="COMPACT_FAILED"?i("COMPACT_FAILED",Me(d)).diagnostic:p.diagnostic}return s?{summary:n.restoreText(Tt(u)),firstKeptEntryId:c.firstKeptEntryId,tokensBefore:c.tokensBefore,details:{protecter:s}}:{summary:n.restoreText(h),firstKeptEntryId:c.firstKeptEntryId,tokensBefore:c.tokensBefore,usage:l}}async function xe(o,e,n,t,r=Et,a){let{preparation:c}=o,u=await n.redact(c.entriesToSummarize,t),m=c.customInstructions===void 0?void 0:await n.redact(c.customInstructions,t),f=await be(e,a),h;try{h=await r(u,{model:f.model,apiKey:f.apiKey,headers:f.headers,env:f.env,signal:o.signal,customInstructions:m,replaceInstructions:c.replaceInstructions,streamFn:Fe(e)})}catch(s){let d=O(s,"COMPACT_FAILED");throw d.diagnostic.code==="COMPACT_FAILED"?i("COMPACT_FAILED",Me(s)):d}let l=h?.summary;if(typeof l!="string"||!l.trim())throw i("COMPACT_FAILED");return{summary:n.restoreText(l),usage:h.usage}}function Rt(o){de(j());let e=new U(St()),n=se(_t),t=!1,r,a,c=l=>{let s=_(l);return r={at:new Date().toISOString(),text:s},s};o.on("session_start",async(l,s)=>{try{if(!n)throw i("UNSUPPORTED_PI");await e.initialize(),t=!0;let d=e.ruleCount;s.ui.setStatus("protecter",g("statusBarRules",{rules:S("rules",d)})),d===0&&s.ui.notify(g("emptyRules"),"warning");let p=e.compaction;if(p.provider&&p.model)try{B(s,p),s.ui.notify(g("compactModelConfigured",{model:`${p.model} @ ${p.provider}`}),"info")}catch(A){s.ui.notify(c(O(A,"CONFIG_COMPACT_MODEL").diagnostic),"error")}}catch(d){t=!1,s.ui.setStatus("protecter",g("statusBarNotReady")),s.ui.notify(c(O(d,"CONFIG_IO").diagnostic),"error")}}),o.on("before_provider_request",async(l,s)=>{try{if(!n)throw i("UNSUPPORTED_PI");let d=await e.redact(l.payload,s.model?.provider??"unknown");return t=!0,d}catch(d){t=!1;let p=c(O(d,"INTERNAL").diagnostic);try{await s.abort()}catch{}try{s.ui.notify(p,"error")}catch{}return{}}}),o.on("message_end",l=>{if(l.message.role!=="assistant")return;let s=l.message;return{message:{...s,content:s.content.map(d=>d.type==="text"?{...d,text:e.restoreText(d.text)}:d.type==="thinking"?{...d,thinking:e.restoreText(d.thinking)}:d.type==="toolCall"?{...d,arguments:e.restore(d.arguments)}:d),...s.errorMessage?{errorMessage:e.restoreText(s.errorMessage)}:{}}}}),o.registerMarkdownTransformer((l,s)=>s.messageType==="user"?l:e.restoreText(l)),o.on("tool_call",(l,s)=>{if(!t)return{block:!0,reason:e.lastDiagnosticText??r?.text??_(i("NOT_READY").diagnostic)};let d=e.restore(l.input);for(let p of Object.keys(l.input))delete l.input[p];if(Object.assign(l.input,d),ke(l.toolName,l.input,s.cwd,e.configPath))return{block:!0,reason:g("toolBlocked")}});let u=!1,m,f=l=>e.compaction.provider??l.model?.provider??"unknown";o.on("agent_settled",(l,s)=>{if(!t||u)return;let d=e.compaction;if(d.mode==="off")return;let p=oe(s,d,m);if(!p)return;let A=s.getContextUsage(),N=A?.tokens;typeof N=="number"&&(N<=p.threshold||A&&N>A.contextWindow-p.reserve||(u=!0,s.ui.notify(g("compactEarly",{tokens:S("tokens",N)}),"info"),s.compact({onComplete:()=>{u=!1},onError:()=>{u=!1}})))});let h=async(l,s)=>{if(!n)throw i("UNSUPPORTED_PI");if(!e.ready)throw e.lastDiagnostic?i(e.lastDiagnostic.code,e.lastDiagnostic):i("NOT_READY");let d=e.compactionMode;if(d==="off")throw i("COMPACT_DENIED");if(a==="deny")throw i("COMPACT_DENIED");if(d!=="ask"||a==="allow")return;let p=[g("compactAllowOnce"),g("compactAllowAlways"),g("compactDenyOnce"),g("compactDenyAlways")],A=await l.ui.select(`${g("compactAskTitle")}
18
19
 
19
- ${m("compactAskBody")}`,f,{signal:i}),y=p===void 0?-1:f.indexOf(p);if(y===1?(c="allow",a.ui.notify(m("compactAlwaysNotice"),"info")):y===3&&(c="deny",a.ui.notify(m("compactDenyNotice"),"warning")),y!==0&&y!==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 De(a,i,e,i.model?.provider??"unknown");return i.ui.notify(m("compactDone"),"info"),{compaction:l}}catch(l){return i.ui.notify(u(I(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 Pe(a,i,e,i.model?.provider??"unknown");return i.ui.notify(m("compactDone"),"info"),{summary:l}}catch(l){return i.ui.notify(u(I(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(I(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)}`),Z=await i.ui.select(m("logsSelectTitle")+(G?m("logsTruncated"):""),w),V=Z===void 0?-1:w.indexOf(Z);if(V<0||!await i.ui.confirm(m("logsRevealTitle"),m("logsRevealBody")))return;let v=O(N[V]);await i.ui.editor(m("logsPreviewTitle"),v.length>2e4?`${v.slice(0,2e4)}
20
- ${m("logsPreviewTruncated")}`:v)}catch(N){i.ui.notify(u(I(N,"AUDIT_IO").diagnostic),"error")}return}if(f==="reload"){await i.waitForIdle(),await i.reload();return}let p=e.lastDiagnosticText??o?.text,y=m("statusLine",{state:m(e.ready?"statusReady":"statusNotReady"),rules:R("rules",e.ruleCount),mappings:R("mappings",e.mappingCount)}),A=p?`
21
- ${m("statusLastBlock",{at:o?.at??""})}
22
- ${p}`:`
23
- ${m("statusNoBlock")}`;i.ui.notify(y+A,e.ready?"info":"error")}}),n.on("session_shutdown",()=>e.close())}export{pt as default};
20
+ ${g("compactAskBody")}`,p,{signal:s}),N=A===void 0?-1:p.indexOf(A);if(N===1?(a="allow",l.ui.notify(g("compactAlwaysNotice"),"info")):N===3&&(a="deny",l.ui.notify(g("compactDenyNotice"),"warning")),N!==0&&N!==1)throw i("COMPACT_DENIED")};o.on("session_before_compact",async(l,s)=>{let d=l.preparation.settings?.reserveTokens;typeof d=="number"&&Number.isSafeInteger(d)&&(m=d);try{await h(s,l.signal),s.ui.notify(g("compactWorking"),"info");let p=await ve(l,s,e,f(s),void 0,e.compaction),A=p.details?.protecter;return A?(s.ui.notify(g("compactDegraded"),"warning"),s.ui.notify(c(A),"warning")):s.ui.notify(g("compactDone"),"info"),{compaction:p}}catch(p){return s.ui.notify(c(O(p,"COMPACT_FAILED").diagnostic),"warning"),{cancel:!0}}}),o.on("session_before_tree",async(l,s)=>{if(l.preparation.userWantsSummary)try{await h(s,l.signal),s.ui.notify(g("compactWorking"),"info");let d=await xe(l,s,e,f(s),void 0,e.compaction);return s.ui.notify(g("compactDone"),"info"),{summary:d}}catch(d){return s.ui.notify(c(O(d,"COMPACT_FAILED").diagnostic),"warning"),{cancel:!0}}}),o.registerCommand("protecter",{description:g("commandDescription"),handler:async(l,s)=>{let d=l.trim().split(/\s+/).filter(Boolean),p=d[0]??"logs";if(!["status","reload","logs"].includes(p)||p!=="logs"&&d.length>1||d.length>2||d[1]!==void 0&&d[1]!=="clear"&&!/^(?:[1-9]\d?|100)$/.test(d[1])){s.ui.notify(g("usage"),"info");return}if(p==="logs"){if(s.mode!=="tui"){s.ui.notify(g("logsTuiOnly"),"warning");return}if(d[1]==="clear"){try{if(!e.ready)throw i("NOT_READY");if(!await s.ui.confirm(g("clearTitle"),g("clearBody")))return;await s.waitForIdle();let E=await e.clearAuditRecords();t=e.ready,s.ui.notify(g("cleared",{bytes:S("bytes",E)}),"info")}catch(E){s.ui.notify(c(O(E,"AUDIT_IO").diagnostic),"error")}return}try{let{records:E,truncated:Be}=e.auditRecords(Number(d[1]??20));if(!E.length){s.ui.notify(g("logsNone"),"info");return}let $=M=>JSON.stringify(M).replace(/[\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g,H=>`\\u${H.charCodeAt(0).toString(16).padStart(4,"0")}`),ne=E.map((M,H)=>`${H+1}. ${$(M.time)} | ${$(M.provider).slice(0,120)}`),re=await s.ui.select(g("logsSelectTitle")+(Be?g("logsTruncated"):""),ne),ie=re===void 0?-1:ne.indexOf(re);if(ie<0||!await s.ui.confirm(g("logsRevealTitle"),g("logsRevealBody")))return;let W=$(E[ie]);await s.ui.editor(g("logsPreviewTitle"),W.length>2e4?`${W.slice(0,2e4)}
21
+ ${g("logsPreviewTruncated")}`:W)}catch(E){s.ui.notify(c(O(E,"AUDIT_IO").diagnostic),"error")}return}if(p==="reload"){await s.waitForIdle(),await s.reload();return}let A=e.lastDiagnosticText??r?.text,N=g("statusLine",{state:g(e.ready?"statusReady":"statusNotReady"),rules:S("rules",e.ruleCount),mappings:S("mappings",e.mappingCount)}),C=e.compaction,D=oe(s,C,m),Ge=C.provider&&C.model?`${C.model} @ ${C.provider}`:g("compactMainModel"),Ue=`
22
+ ${g("statusCompaction",{mode:C.mode,target:Ge,threshold:D?S("tokens",D.threshold):g("compactNoThreshold")})}`,ze=A?`
23
+ ${g("statusLastBlock",{at:r?.at??""})}
24
+ ${A}`:`
25
+ ${g("statusNoBlock")}`;s.ui.notify(N+Ue+ze,e.ready?"info":"error")}}),o.on("session_shutdown",()=>e.close())}export{Rt as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-information-protecter",
3
- "version": "0.8.4",
3
+ "version": "0.10.0",
4
4
  "description": "Sensitive Personal Information (SPI) Protecter — local reversible privacy redaction for Pi",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -40,10 +40,10 @@
40
40
  "node": ">=22"
41
41
  },
42
42
  "peerDependencies": {
43
- "@earendil-works/pi-coding-agent": ">=0.84.0 <0.85.0 || >=0.85.1 <0.88.0"
43
+ "@earendil-works/pi-coding-agent": ">=0.84.0 <0.85.0 || >=0.85.1 <0.88.0 || >=0.99.0 <1.0.0 || >=1.2.0 <1.4.0"
44
44
  },
45
45
  "devDependencies": {
46
- "@earendil-works/pi-coding-agent": "0.86.1",
46
+ "@earendil-works/pi-coding-agent": "1.3.0",
47
47
  "@types/node": "^22.0.0",
48
48
  "esbuild": "0.28.2",
49
49
  "tsx": "^4.20.0",
@@ -1,6 +1,8 @@
1
1
  {
2
2
  "version": 1,
3
- "compaction": "ask",
3
+ "compaction": {
4
+ "mode": "ask"
5
+ },
4
6
  "sensitiveWords": [
5
7
  "张三",
6
8
  {