leakshield 0.2.0 → 0.3.1

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/LICENSE CHANGED
@@ -1,21 +1,202 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Jared Wang
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,2 @@
1
+ LeakShield
2
+ Copyright 2026 Jared Wang
package/README.md CHANGED
@@ -26,10 +26,10 @@ MCP server mode has been removed. It depended on the model voluntarily calling a
26
26
 
27
27
  **Experimental, `0.x`.** Published to npm as `leakshield`: run `npx leakshield --help` to see the commands, or build locally (`npm ci && npm run build`) and point OpenCode at the `dist` directory. Without arguments or input, the CLI waits on stdin.
28
28
 
29
- - Transparent mode has been verified on OpenCode v2.0.28 with local loopback providers, and once against a real OpenAI model. It is **not** a guarantee that nothing sensitive reaches a model: the recommended hook-first setup is reported as `PARTIAL` by `--doctor`, and content added after the plugin's hooks or sent by permitted tools (curl, remote MCP) is outside its coverage.
29
+ - Transparent mode has been verified on OpenCode v2.0.28 with local loopback providers, and once against a real OpenAI model. The 0.3.0 tool restoration was rechecked on OpenCode v2.2.5 with a loopback provider, the OpenChamber render tool and `rtk` ([record](docs/evidence/2026-11-06-opencode-2.2.5-tool-restoration.md)). It is **not** a guarantee that nothing sensitive reaches a model: the recommended hook-first setup is reported as `PARTIAL` by `--doctor`, and content added after the plugin's hooks or sent by permitted tools (curl, remote MCP) is outside its coverage.
30
30
  - Not yet verified: OS-keychain custody on Windows and Linux (macOS verified 2026-10-20), a real Anthropic provider, long histories on other providers, long-running use ([#26](https://github.com/jwcrystal/leakshield/issues/26)).
31
31
  - Defaults may still change during `0.x`; see the [changelog](CHANGELOG.md).
32
- - Verification records: [docs/evidence](docs/evidence/README.md). Report vulnerabilities privately: [SECURITY.md](SECURITY.md). License: [MIT](LICENSE).
32
+ - Verification records: [docs/evidence](docs/evidence/README.md). Report vulnerabilities privately: [SECURITY.md](SECURITY.md). License: [Apache-2.0](LICENSE).
33
33
 
34
34
  ---
35
35
 
@@ -282,7 +282,7 @@ See [Wire protection](docs/plugin/wire-protection.md) for both levels.
282
282
 
283
283
  #### Detailed guides
284
284
 
285
- - [Transparent mode](docs/plugin/transparent-mode.md): placeholders, supported protocols, shell argument restoration, restart limitation
285
+ - [Transparent mode](docs/plugin/transparent-mode.md): placeholders, supported protocols, tool argument restoration (per field, `code`/`script` fields, Code Mode, `curl`, `rtk`), restart limitation
286
286
  - [Wire protection](docs/plugin/wire-protection.md): hook-only and final wire levels, AI SDK providers, refusals, reply-side recovery
287
287
  - [Native WebSocket](docs/plugin/websocket.md): experimental Responses-family support and its limits
288
288
  - [Mapping persistence](docs/plugin/persistence.md): opt-in encrypted storage, key custody, erasure
@@ -345,7 +345,7 @@ Doctor is an install-level check that runs outside the host — it cannot see in
345
345
 
346
346
  ### What this protects — and what it does not
347
347
 
348
- LeakShield protects model-conversation content: prompts, replayed history, tool outputs, and (in transparent mode) provider-bound request bodies whose shape it can parse. It is **not** a tool-egress firewall: a permitted local tool can still transmit originals over the network via `curl`, a remote MCP server, or any other channel. Controlling tool destinations requires a separate permission layer outside this plugin.
348
+ LeakShield protects model-conversation content: prompts, replayed history, tool outputs, and (in transparent mode) provider-bound request bodies whose shape it can parse. It is **not** a tool-egress firewall: a permitted local tool can still transmit originals over the network via `curl`, a remote MCP server, or any other channel. Controlling tool destinations requires a separate permission layer outside this plugin. Since 0.3.0, `curl` and `http` may also hold a placeholder inside an argument, so a tool can call an API with the protected value; the original then leaves the machine by design.
349
349
 
350
350
  Detection also has known gaps: street/postal addresses, dates, IPv6, and generic assignments outside the keyword list or below the 8-character minimum pass through undetected. Credit card and IBAN numbers are detected only when the checksum validates; IP detection covers public IPv4 only; URL detection exists but is opt-in — see [Detection Coverage](#detection-coverage).
351
351
 
package/README.zh-TW.md CHANGED
@@ -26,10 +26,10 @@ MCP Server 模式已移除。它依賴模型在已收到相關 context 後自行
26
26
 
27
27
  **實驗性,`0.x` 版本。** 已發佈到 npm(`leakshield`):可用 `npx leakshield --help` 查看指令,或在本機建置(`npm ci && npm run build`)再讓 OpenCode 指向 `dist` 目錄。沒有參數也沒有輸入時,CLI 會等待 stdin。
28
28
 
29
- - Transparent 模式已在 OpenCode v2.0.28 搭配本機替身 provider 驗證,並用真實 OpenAI 模型驗證過一次。它**不保證**敏感內容絕不會送到模型:建議的 hook-first 設定在 `--doctor` 顯示為 `PARTIAL`,hook 之後才加入的內容,以及被允許的工具外送(curl、遠端 MCP),都不在保護範圍內。
29
+ - Transparent 模式已在 OpenCode v2.0.28 搭配本機替身 provider 驗證,並用真實 OpenAI 模型驗證過一次。0.3.0 的工具還原另在 OpenCode v2.2.5 用本機替身 provider、OpenChamber 的 render 工具與 `rtk` 重新驗證([紀錄](docs/evidence/2026-11-06-opencode-2.2.5-tool-restoration.md))。它**不保證**敏感內容絕不會送到模型:建議的 hook-first 設定在 `--doctor` 顯示為 `PARTIAL`,hook 之後才加入的內容,以及被允許的工具外送(curl、遠端 MCP),都不在保護範圍內。
30
30
  - 尚未驗證:Windows 與 Linux 的 OS keychain 持久化(macOS 已於 2026-10-20 驗證)、真實 Anthropic provider、其他 provider 的長對話、長時間使用([#26](https://github.com/jwcrystal/leakshield/issues/26))。
31
31
  - `0.x` 期間預設值仍可能調整,變更見 [CHANGELOG](CHANGELOG.md)。
32
- - 驗證紀錄:[docs/evidence](docs/evidence/README.md)。漏洞請私下回報:[SECURITY.md](SECURITY.md)。授權:[MIT](LICENSE)。
32
+ - 驗證紀錄:[docs/evidence](docs/evidence/README.md)。漏洞請私下回報:[SECURITY.md](SECURITY.md)。授權:[Apache-2.0](LICENSE)。
33
33
 
34
34
  ---
35
35
 
@@ -278,7 +278,7 @@ LeakShield 只支援 OpenCode v2:v2 載入套件的 `id` + `setup(ctx)` 定義
278
278
 
279
279
  #### 詳細說明
280
280
 
281
- - [Transparent 模式](docs/plugin/transparent-mode.zh-TW.md): 佔位符、支援的協定、Shell 參數還原、重啟限制
281
+ - [Transparent 模式](docs/plugin/transparent-mode.zh-TW.md): 佔位符、支援的協定、工具參數還原(依欄位判斷、`code`/`script` 欄位、Code Mode、`curl`、`rtk`)、重啟限制
282
282
  - [Wire 保護](docs/plugin/wire-protection.zh-TW.md): hook-only 與 final wire 兩種層級、AI SDK provider、拒絕、回覆端復原
283
283
  - [Native WebSocket](docs/plugin/websocket.zh-TW.md): 實驗性的 Responses-family 支援與限制
284
284
  - [映射持久化](docs/plugin/persistence.zh-TW.md): 選擇性開啟的加密儲存、金鑰保管、清除
@@ -341,7 +341,7 @@ Doctor 是在 host 之外執行的安裝層檢查,看不到執行中的 sessio
341
341
 
342
342
  ### 保護範圍與不保護的部分
343
343
 
344
- LeakShield 保護送往模型的對話內容:prompt、重播的歷史、工具輸出,以及(transparent 模式下)可解析其結構的 provider 請求 body。它**不是**工具對外連線的防火牆:被允許的本機工具仍可透過 `curl`、遠端 MCP server 或任何其他管道把原文傳出去。要管控工具的目的地,需要此 plugin 之外的權限層。
344
+ LeakShield 保護送往模型的對話內容:prompt、重播的歷史、工具輸出,以及(transparent 模式下)可解析其結構的 provider 請求 body。它**不是**工具對外連線的防火牆:被允許的本機工具仍可透過 `curl`、遠端 MCP server 或任何其他管道把原文傳出去。要管控工具的目的地,需要此 plugin 之外的權限層。從 0.3.0 起,`curl` 與 `http` 的參數內也可以放 placeholder,讓工具帶著受保護的值呼叫 API;這時原文會依設計離開本機。
345
345
 
346
346
  偵測也有已知缺口:街道/郵遞地址、日期、IPv6,以及關鍵字清單之外或短於 8 字元的一般賦值都不會被偵測。信用卡與 IBAN 只有在檢查碼驗證通過時才會命中;IP 偵測只涵蓋公開 IPv4(超過四段的點分數字會整段回報,避免內嵌位址漏遮;`2026.10.21.14.32.59` 這類點分日期也會回報);URL 偵測存在但需手動開啟,見[偵測範圍](#偵測範圍)。
347
347
 
@@ -419,7 +419,9 @@ function withOpaqueReasoningContent(body, fn) {
419
419
  return fn(body);
420
420
  const originals = [];
421
421
  for (const item of input) {
422
- if (isRecord(item) && item.type === "reasoning" && typeof item.encrypted_content === "string") {
422
+ if (isRecord(item) &&
423
+ (item.type === "reasoning" || item.type === "compaction") &&
424
+ typeof item.encrypted_content === "string") {
423
425
  originals.push(item.encrypted_content);
424
426
  item.encrypted_content = `${OPAQUE_REASONING_SENTINEL}_${originals.length - 1}`;
425
427
  }
@@ -947,10 +949,11 @@ export async function remaskAnthropicMessagesRequest(service, sessionID, request
947
949
  /**
948
950
  * Validates an OpenAI Responses request body: `instructions` string, `input`
949
951
  * (string or item array: message | function_call | function_call_output |
950
- * reasoning), flat `tools` ({type:"function", name, parameters}). Reasoning
951
- * items pass with their encrypted payload opaque (unscanned, verbatim) and
952
- * their summary/content text masked; item references and unknown types
953
- * refuse.
952
+ * custom_tool_call | custom_tool_call_output | reasoning | compaction |
953
+ * configuration_update), flat `tools` ({type:"function", name, parameters}).
954
+ * Reasoning and compaction items pass with their encrypted payload opaque
955
+ * (unscanned, verbatim); reasoning summary/content text is masked; item
956
+ * references and unknown types refuse.
954
957
  */
955
958
  function validateResponsesContentParts(content, allowAttachments) {
956
959
  if (content === undefined || content === null || typeof content === "string")
@@ -1010,7 +1013,13 @@ function validateResponsesInputItem(item, allowAttachments) {
1010
1013
  throw new Error(refusal("responses-function-call-shape"));
1011
1014
  }
1012
1015
  return;
1016
+ case "custom_tool_call":
1017
+ if (typeof item.name !== "string" || typeof item.input !== "string") {
1018
+ throw new Error(refusal("responses-custom-tool-call-shape"));
1019
+ }
1020
+ return;
1013
1021
  case "function_call_output":
1022
+ case "custom_tool_call_output":
1014
1023
  if (typeof item.output !== "string") {
1015
1024
  if (!Array.isArray(item.output))
1016
1025
  throw new Error(refusal("responses-function-output"));
@@ -1032,6 +1041,19 @@ function validateResponsesInputItem(item, allowAttachments) {
1032
1041
  validateResponsesReasoningParts(item.content);
1033
1042
  return;
1034
1043
  }
1044
+ case "compaction":
1045
+ // Same opacity argument as reasoning.encrypted_content: a provider
1046
+ // checkpoint of already-masked history, replayed to the same provider.
1047
+ if (typeof item.encrypted_content !== "string" ||
1048
+ (item.id !== undefined && item.id !== null && typeof item.id !== "string")) {
1049
+ throw new Error(refusal("responses-compaction-shape"));
1050
+ }
1051
+ return;
1052
+ case "configuration_update":
1053
+ if (!isRecord(item.reasoning) || typeof item.reasoning.effort !== "string") {
1054
+ throw new Error(refusal("responses-configuration-update-shape"));
1055
+ }
1056
+ return;
1035
1057
  default:
1036
1058
  // item_reference / unknown: cannot verify or place.
1037
1059
  throw new Error(refusal("responses-item-type"));
@@ -1077,10 +1099,14 @@ function collectResponsesStructuralStrings(body) {
1077
1099
  pushString(out, item.type);
1078
1100
  pushString(out, item.role);
1079
1101
  pushString(out, item.call_id);
1080
- if (item.type === "function_call")
1102
+ if (item.type === "function_call" || item.type === "custom_tool_call")
1081
1103
  pushString(out, item.name);
1082
- if (item.type === "reasoning")
1104
+ if (item.type === "function_call")
1105
+ pushString(out, item.namespace);
1106
+ if (item.type === "reasoning" || item.type === "compaction")
1083
1107
  pushString(out, item.id);
1108
+ if (item.type === "configuration_update" && isRecord(item.reasoning))
1109
+ pushString(out, item.reasoning.effort);
1084
1110
  }
1085
1111
  }
1086
1112
  if (Array.isArray(body.tools)) {
@@ -1962,7 +1988,10 @@ function restoreResponsesItemText(service, sessionID, item, fields) {
1962
1988
  if (item.type === "function_call" && typeof item.arguments === "string") {
1963
1989
  allowResponsesField(fields, item, "arguments");
1964
1990
  }
1965
- if (item.type === "function_call_output" && typeof item.output === "string") {
1991
+ if (item.type === "custom_tool_call" && typeof item.input === "string") {
1992
+ allowResponsesField(fields, item, "input");
1993
+ }
1994
+ if ((item.type === "function_call_output" || item.type === "custom_tool_call_output") && typeof item.output === "string") {
1966
1995
  allowResponsesField(fields, item, "output");
1967
1996
  }
1968
1997
  let changed = false;
@@ -2017,6 +2046,9 @@ export function restoreResponsesEventDisplay(service, sessionID, chunk) {
2017
2046
  else if (type === "response.function_call_arguments.delta" || type === "response.function_call_arguments.done") {
2018
2047
  allowResponsesField(fields, chunk, type.endsWith(".delta") ? "delta" : "arguments");
2019
2048
  }
2049
+ else if (type === "response.custom_tool_call_input.delta" || type === "response.custom_tool_call_input.done") {
2050
+ allowResponsesField(fields, chunk, type.endsWith(".delta") ? "delta" : "input");
2051
+ }
2020
2052
  else if (type === "response.output_item.added" || type === "response.output_item.done") {
2021
2053
  if (isRecord(chunk.item))
2022
2054
  restoreResponsesItemText(service, sessionID, chunk.item, fields);
@@ -2273,6 +2305,11 @@ export function createResponsesSseRestoreStream(service, sessionID, body) {
2273
2305
  if (typeof chunk[field] === "string")
2274
2306
  allowResponsesField(fields, chunk, field);
2275
2307
  }
2308
+ else if (eventType === "response.custom_tool_call_input.delta" || eventType === "response.custom_tool_call_input.done") {
2309
+ const field = eventType.endsWith(".delta") ? "delta" : "input";
2310
+ if (typeof chunk[field] === "string")
2311
+ allowResponsesField(fields, chunk, field);
2312
+ }
2276
2313
  // P1 (2026-10-06b): an unplaceable placeholder is degradation — WARN
2277
2314
  // and emit literally; mapping loss never refuses response delivery.
2278
2315
  if (responsesStrayTokenIn(chunk, fields)) {
@@ -42,6 +42,7 @@ import { MappingForgottenError, MappingKeyMismatchError, MappingSnapshotTooLarge
42
42
  import { resolveMappingKey } from "./decision/mapping-key.js";
43
43
  import { walkSchemaStrings } from "./decision/schema-strings.js";
44
44
  import { classifyModelRoute, remaskModelRequest, restoreModelResponse, withOpaqueAttachments, } from "./opencode-transparent-http.js";
45
+ import { FINDING_TYPES } from "./types.js";
45
46
  import { createResponsesWebSocketAdapter } from "./opencode-transparent-ws.js";
46
47
  import { createAISDKTransportAdmission } from "./opencode-transparent-aisdk.js";
47
48
  import { BUILTIN_RULES } from "./rules/builtin.js";
@@ -54,7 +55,25 @@ const TOOL_REFUSAL_ERROR = "LeakShield blocked this tool call because its argume
54
55
  const TOOL_UNKNOWN_MAPPING_ERROR = "LeakShield blocked this tool call before execution: a placeholder has no mapping in this session. The tool did not run. Reread the source and rebuild the affected arguments from current references; rereading does not make an old placeholder valid. If it is refused again, stop retrying and ask the user.";
55
56
  const TOOL_RESTORE_LIMIT_ERROR = "LeakShield blocked this tool call because its arguments are too large to restore safely. Use smaller arguments and try again.";
56
57
  const TOOL_SHELL_CONTEXT_ERROR = "LeakShield blocked this tool call because the shell command's quoting is not supported. Use a simple command with plain arguments, or a different tool.";
57
- const TOOL_INPUT_SHAPE_ERROR = "LeakShield blocked this tool call because its argument structure cannot be safely restored. Use plain JSON values and try again.";
58
+ const TOOL_CODE_CONTEXT_ERROR = "LeakShield blocked this tool call because a protected value cannot be safely inserted into code. Pass the value through a plain argument or a file instead, or ask the user.";
59
+ const TOOL_CODE_POSITION_ERROR = "LeakShield blocked this tool call; the tool did not run.\n- Allowed: a placeholder in a plain single-line quoted string with no interpolation, outside any multi-line string or line continuation.\n- Fix: copy the placeholder exactly as it appears in this conversation, including its brackets, into such a string, assign that to a variable, and reference the variable.\n- Do not replace the placeholder with other text, and do not ask for or write the real value. If refused again, stop and ask the user.";
60
+ /**
61
+ * OpenCode's built-in Code Mode tool (v2.2.5): custom tools are reachable only
62
+ * through it, with input `{code: string}`.
63
+ */
64
+ const CODE_MODE_TOOL = "execute";
65
+ /**
66
+ * Refusal for `fetch` inside Code Mode source that holds a protected value.
67
+ * This only avoids a misleading result: the inner fetch would send the
68
+ * placeholder, the remote would answer with an error, and the model would read
69
+ * that as a verdict on the real value. It is NOT a security boundary: it is a
70
+ * text match on the source, not a network control, so other spellings are not
71
+ * caught (and then send only the placeholder).
72
+ */
73
+ const TOOL_CODE_FETCH_ERROR = "LeakShield blocked this tool call; the tool did not run.\n- Reason: fetch inside execute cannot use protected values, because it would send the placeholder rather than the real value, so a failed response says nothing about the value.\n- Fix: use a tool call instead, or tell the user this cannot be done here.\n- Do not report the value as invalid, and do not ask for or write the real value.";
74
+ /** Refusal for a value recognisably derived from this session's placeholder whose format was changed. */
75
+ const TOOL_PLACEHOLDER_NEAR_MISS_ERROR = "LeakShield blocked this tool call; the tool did not run.\n- A value looks like a placeholder from this conversation, but its format was changed.\n- Fix: copy it exactly as it appears, including its brackets; do not replace it with other text.\n- Do not ask for or write the real value. If refused again, stop and ask the user.";
76
+ const TOOL_INPUT_SHAPE_ERROR = "LeakShield blocked this tool call because the structure of one argument could not be restored. This is not about what the value looks like or contains. Use plain JSON values (strings, numbers, booleans, arrays and plain objects) and try again.";
58
77
  const STRUCTURAL_SENSITIVE_ERROR = "LeakShield blocked this request because a structural identifier (message or tool id, name, role, or part type) scans as sensitive and cannot be masked. Change it or adjust the matching rule, then try again.";
59
78
  function toolRestoreError(reason) {
60
79
  if (reason === "unknown_token" || reason === "malformed_token")
@@ -165,6 +184,41 @@ const INLINE_SCRIPT_FLAGS = new Map([
165
184
  ]);
166
185
  const SCRIPT_ARGUMENT_INTERPRETERS = new Set(["awk", "sed", "jq"]);
167
186
  const SHELL_INTERPRETERS = new Set(["sh", "bash", "dash", "zsh", "ksh", "ash", "csh", "tcsh", "fish"]);
187
+ /**
188
+ * `rtk` is a command-output wrapper: `rtk <command> <args>` runs the command
189
+ * and condenses its output, so the command actually executed is the word
190
+ * after it. Without this, `rtk sh -c T` would be judged as plain arguments to
191
+ * `rtk` and restore a token into a second shell parse. These subcommands run
192
+ * another command themselves (`rtk err sh -c T`, `rtk proxy sh -c T`), so the
193
+ * word after them cannot be judged as the executed command and the form is
194
+ * refused. The list comes from `rtk --help` for rtk 1.1.0; a new rtk release
195
+ * may add runners. `rtk` counts however it's spelled (a path, quotes, any case),
196
+ * as the other command checks do.
197
+ */
198
+ const RTK_COMMAND_RUNNERS = new Set(["err", "test", "summary", "run", "bypass", "proxy", "pipe"]);
199
+ /**
200
+ * Index of the word that names the command actually executed: the first
201
+ * non-assignment word, or the word after a leading `rtk`. Returns -1 when
202
+ * there is no such word or the form must be refused (`rtk` alone, an option
203
+ * after `rtk`, `rtk` wrapping `rtk`, or an rtk subcommand that runs another
204
+ * command).
205
+ */
206
+ function resolveExecutedCommandIndex(words) {
207
+ const commandIndex = words.findIndex((word) => word.quote !== "none" || !ASSIGNMENT_WORD.test(word.value));
208
+ if (commandIndex === -1)
209
+ return -1;
210
+ const command = words[commandIndex];
211
+ if (command.redirect || command.value.split("/").at(-1)?.toLowerCase() !== "rtk")
212
+ return commandIndex;
213
+ const next = words[commandIndex + 1];
214
+ if (next === undefined || next.redirect || next.value.startsWith("-"))
215
+ return -1;
216
+ if (next.value.split("/").at(-1)?.toLowerCase() === "rtk")
217
+ return -1;
218
+ if (RTK_COMMAND_RUNNERS.has(next.value.toLowerCase()))
219
+ return -1;
220
+ return commandIndex + 1;
221
+ }
168
222
  /** Returns only ordinary arguments, never command/assignment/redirect words. */
169
223
  function parseSupportedShellArguments(text) {
170
224
  const parsed = parseLiteralShellWords(text);
@@ -178,7 +232,7 @@ function parseSupportedShellArguments(text) {
178
232
  return null;
179
233
  }
180
234
  const words = redirectIndex === -1 ? parsed : parsed.slice(0, redirectIndex);
181
- const commandIndex = words.findIndex((word) => word.quote !== "none" || !ASSIGNMENT_WORD.test(word.value));
235
+ const commandIndex = resolveExecutedCommandIndex(words);
182
236
  if (commandIndex === -1)
183
237
  return null;
184
238
  const commandName = words[commandIndex].value.split("/").at(-1)?.toLowerCase() ?? "";
@@ -200,37 +254,55 @@ function parseSupportedShellArguments(text) {
200
254
  /** Characters forbidden inside restored shell argument words. */
201
255
  const SHELL_UNSAFE = /[\s'"`\\$;|&<>(){}*?\[\]!~#\x00-\x1F\x7F]/;
202
256
  /**
203
- * Conservative allowlist of non-executing tools. Any tool not listed here is
204
- * treated as potentially shell-like and requires shell-safe originals, so an
205
- * unrecognized (or newly added) executing tool fails closed rather than
206
- * receiving a value that could change its meaning.
257
+ * Restore policy is decided per field, not per tool. A tool name that is in
258
+ * SHELL_TOOLS or has a shell-interpreter segment (bash, shell, sh, zsh, pwsh,
259
+ * powershell) makes every field "shell". Otherwise a field named like a
260
+ * command (command, cmd, commands, argv, ...) is "shell", a field named like
261
+ * code (code, script, ...) is "inert" (no parsing; originals with
262
+ * shell-unsafe characters are refused), and any other field restores
263
+ * verbatim. The list is built into the source, not configurable; an executing
264
+ * tool using other field names is not detected.
207
265
  */
208
- const NON_SHELL_TOOLS = new Set([
209
- "read",
210
- "read_file",
211
- "view",
212
- "write",
213
- "write_file",
214
- "create_file",
215
- "edit",
216
- "edit_file",
217
- "multiedit",
218
- "patch",
219
- "apply_patch",
220
- "str_replace",
221
- "str_replace_editor",
222
- "grep",
223
- "glob",
224
- "list",
225
- "ls",
226
- "find",
227
- "webfetch",
228
- "websearch",
229
- "fetch",
230
- "todowrite",
231
- "todoread",
232
- "notebookedit",
266
+ const SHELL_TOOLS = new Set([
267
+ "bash",
268
+ "shell",
269
+ "sh",
270
+ "zsh",
271
+ "exec",
272
+ "command",
273
+ "run",
274
+ "pwsh",
275
+ "powershell",
233
276
  ]);
277
+ /** Splits on non-alphanumerics and camelCase boundaries; lowercase segments. */
278
+ const nameSegments = (raw) => raw
279
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
280
+ .replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2")
281
+ .split(/[^A-Za-z0-9]+/)
282
+ .filter((segment) => segment.length > 0)
283
+ .map((segment) => segment.toLowerCase());
284
+ const SHELL_TOOL_SEGMENTS = new Set(["bash", "shell", "sh", "zsh", "pwsh", "powershell"]);
285
+ const METADATA_KEYS = new Set(["description", "title", "label"]);
286
+ const SHELL_KEY_LAST_SEGMENTS = new Set(["command", "commands", "cmd", "cmds"]);
287
+ const SHELL_KEYS_JOINED = new Set(["shell", "commandline", "cmdline", "argv"]);
288
+ const CODE_KEYS_JOINED = new Set(["code", "script", "scripts", "sourcecode", "codesnippet", "inlinescript"]);
289
+ const isShellTool = (rawTool) => SHELL_TOOLS.has(rawTool.toLowerCase()) || nameSegments(rawTool).some((segment) => SHELL_TOOL_SEGMENTS.has(segment));
290
+ const isShellKey = (key) => {
291
+ const segments = nameSegments(key);
292
+ return ((segments.length > 0 && SHELL_KEY_LAST_SEGMENTS.has(segments[segments.length - 1])) ||
293
+ SHELL_KEYS_JOINED.has(segments.join("")));
294
+ };
295
+ const isCodeKey = (key) => CODE_KEYS_JOINED.has(nameSegments(key).join(""));
296
+ const keyPolicy = (key, inherited) => {
297
+ const segments = nameSegments(key);
298
+ if (segments.length === 1 && METADATA_KEYS.has(segments[0]))
299
+ return "verbatim";
300
+ if (isShellKey(key))
301
+ return "shell";
302
+ if (isCodeKey(key))
303
+ return inherited === "shell" ? "shell" : "inert";
304
+ return inherited;
305
+ };
234
306
  /**
235
307
  * Tools whose calls are observably read-only: an unresolved placeholder in
236
308
  * their arguments reads/greps/lists against a literal string and matches
@@ -270,8 +342,212 @@ function isShellSafeOriginal(text, quote) {
270
342
  return !/["`\\$!]/.test(text);
271
343
  return !SHELL_UNSAFE.test(text);
272
344
  }
345
+ /**
346
+ * HTTP clients that take credentials inside an argument (`-H 'x-api-key: T'`,
347
+ * `-u user:T`, `--header=x:T`). `wget` is deliberately not listed: its `-e`
348
+ * option family keeps producing bypasses, so it follows the whole-word rule.
349
+ * `isShellSafeOriginal` only covers the first
350
+ * shell parse; commands such as `sh -c`, `python -c`, `ssh` and `eval` parse
351
+ * their arguments again, so embedding is decided by the command that actually
352
+ * executes: the first word, unquoted, exactly one of these names. Paths,
353
+ * quoted names, assignments and wrappers (`env`, `sudo`) do not qualify.
354
+ * `rtk curl ...` does not qualify either: rtk records command lines in its
355
+ * local history database in plaintext, so a restored secret would persist
356
+ * there. Under `rtk` only whole-word placeholders restore.
357
+ */
358
+ const EMBEDDED_PLACEHOLDER_COMMANDS = new Set(["curl", "http"]);
359
+ function commandAllowsEmbeddedTokens(text) {
360
+ const first = parseLiteralShellWords(text)?.[0];
361
+ return (first !== undefined &&
362
+ first.quote === "none" &&
363
+ !first.redirect &&
364
+ EMBEDDED_PLACEHOLDER_COMMANDS.has(first.value));
365
+ }
366
+ /**
367
+ * `wget -e CMD` / `--execute CMD` hands its value to wgetrc parsing, a second
368
+ * parse that `isShellSafeOriginal` does not cover (the value can set
369
+ * `output_document`, `post_file` and the like). This check stays although
370
+ * `wget` no longer holds embedded tokens: `wget -e T u` would otherwise
371
+ * restore a whole-word token into wgetrc parsing. The command must be
372
+ * `wget` however it's spelled (a path, quotes, leading assignments), resolved
373
+ * as in `parseSupportedShellArguments`. `curl -e` is a referer and
374
+ * `curl -K`/`--config` only name a file.
375
+ * GNU long options accept unique abbreviations (`--exec`), so any prefix of
376
+ * `--execute` counts; the shorter ambiguous ones make wget exit with an error.
377
+ */
378
+ function isWgetExecuteCommand(text) {
379
+ const words = parseLiteralShellWords(text);
380
+ if (words === null)
381
+ return false;
382
+ const commandIndex = resolveExecutedCommandIndex(words);
383
+ if (commandIndex === -1)
384
+ return false;
385
+ if (words[commandIndex].value.split("/").at(-1)?.toLowerCase() !== "wget")
386
+ return false;
387
+ return words.slice(commandIndex + 1).some((word) => {
388
+ if (word.redirect)
389
+ return false;
390
+ const optionName = word.value.split("=", 1)[0];
391
+ return /^-[A-Za-z0-9]*e/.test(word.value) || (optionName.length >= 3 && "--execute".startsWith(optionName));
392
+ });
393
+ }
273
394
  /** Matches a fully formed reserved token (either version), for per-token shell safety checks. */
274
395
  const TOKEN_SCAN = /\[SGP1:[0-9a-f]{32}-\d{8,12}\]|\[SGP2:[A-Z][A-Z_]{0,31}-[a-z]{4}-[a-z]{4}-[a-z]{4}\]/g;
396
+ /**
397
+ * Relaxed (brackets optional, separators up to 4 non-alphanumerics, any case)
398
+ * forms of the SGP2 placeholder, used only to spot a placeholder the
399
+ * model reformatted. Every quantifier is bounded and there is no nested
400
+ * unbounded group. A candidate counts only if its canonical form restores in
401
+ * the session, so no token enumeration is needed.
402
+ *
403
+ * SGP2 reads the letters after the `SGP2` head, tolerating separator runs of
404
+ * up to 4 non-alphanumerics between letters (changed separators) or none at
405
+ * all (removed separators), and stopping at a digit, a longer run or about 80
406
+ * letters. Each known category, compared without underscores, is tried as a
407
+ * prefix of those letters; the next 12 letters become the three segments. The
408
+ * text after a stripped token is often more short words, which this ignores
409
+ * because only exactly 12 letters follow the category.
410
+ */
411
+ const NEAR_MISS_V2_HEAD = /(?<![A-Za-z0-9])SGP2/gi;
412
+ const NEAR_MISS_V2_MAX_SEPARATOR = 4;
413
+ const NEAR_MISS_V2_MAX_LETTERS = 80;
414
+ const NEAR_MISS_V2_SEGMENT_LETTERS = 12;
415
+ const NEAR_MISS_V2_CATEGORIES = new Map(FINDING_TYPES.map((label) => [label.replaceAll("_", "").toUpperCase(), label]));
416
+ /** Letters following `from`, skipping short separator runs; stops at a digit or a long run. */
417
+ function collectNearMissLetters(text, from) {
418
+ let letters = "";
419
+ let at = from;
420
+ while (at < text.length && letters.length < NEAR_MISS_V2_MAX_LETTERS) {
421
+ const char = text[at];
422
+ if (/[A-Za-z]/.test(char)) {
423
+ letters += char;
424
+ at += 1;
425
+ }
426
+ else if (/[0-9]/.test(char)) {
427
+ break;
428
+ }
429
+ else {
430
+ let run = 0;
431
+ while (at + run < text.length && /[^A-Za-z0-9]/.test(text[at + run]))
432
+ run += 1;
433
+ if (run > NEAR_MISS_V2_MAX_SEPARATOR)
434
+ break;
435
+ at += run;
436
+ }
437
+ }
438
+ return letters;
439
+ }
440
+ /**
441
+ * Builds the position check for the placeholders of one code/script field.
442
+ * Call the result with each token's [start, end) in increasing order; it keeps
443
+ * its state between calls, so the whole field costs one forward pass however
444
+ * many tokens it holds, and a false result ends the field's check. A token's
445
+ * position passes unless `crossesLineBoundary` or `isInPlainStringLiteral`
446
+ * rejects it.
447
+ *
448
+ * Conservative, language-agnostic, line-based heuristic; it is not a parser
449
+ * and does not confirm the match is in a string. It can both over-refuse and
450
+ * miss. It guards the restoration context only and is not egress protection:
451
+ * code can still print, send or re-interpret the restored value.
452
+ */
453
+ function createInertPositionCheck(text) {
454
+ const lineBreak = /[\n\r\u2028\u2029]/g;
455
+ // Current line is [lineStart, lineEnd); lineEnd sits on its separator.
456
+ let lineStart = 0;
457
+ let lineEnd = -1;
458
+ // Triple quotes in text[0, countedTo). A separator ends any run of quotes, so
459
+ // per-line counts add up to the non-overlapping count over the whole prefix.
460
+ let countedTo = 0;
461
+ let doubleTriples = 0;
462
+ let singleTriples = 0;
463
+ let crossesLineBoundary = false;
464
+ // Quote scan of the current line, resumed from `cursor` for each token.
465
+ let cursor = 0;
466
+ let quote = null;
467
+ let introducerInString = false;
468
+ let closingQuote = -1;
469
+ const enterLineOf = (index) => {
470
+ while (lineEnd < index) {
471
+ lineStart = lineEnd + 1;
472
+ lineBreak.lastIndex = lineStart;
473
+ lineEnd = lineBreak.exec(text)?.index ?? text.length;
474
+ }
475
+ const uncounted = text.slice(countedTo, lineStart);
476
+ doubleTriples += uncounted.match(/"""/g)?.length ?? 0;
477
+ singleTriples += uncounted.match(/'''/g)?.length ?? 0;
478
+ countedTo = lineStart;
479
+ const line = text.slice(lineStart, lineEnd);
480
+ // True when the line may belong to a multi-line construct, so the
481
+ // line-based string check cannot be trusted: the line holds a triple quote,
482
+ // an odd number of non-overlapping triple quotes precedes the line (inside
483
+ // an open multi-line string), or the previous line ends in a backslash
484
+ // (continuation; doubled backslashes are not distinguished, so refuse).
485
+ // Deliberately not a whole-field ban, so a script with a balanced docstring
486
+ // above the assignment still works.
487
+ crossesLineBoundary =
488
+ line.includes('"""') ||
489
+ line.includes("'''") ||
490
+ doubleTriples % 2 === 1 ||
491
+ singleTriples % 2 === 1 ||
492
+ /\\(?:\r\n|[\n\r\u2028\u2029])$/.test(text.slice(Math.max(0, lineStart - 3), lineStart));
493
+ cursor = lineStart;
494
+ quote = null;
495
+ introducerInString = false;
496
+ };
497
+ /**
498
+ * True when [start, end) looks like it sits inside an ordinary quoted string
499
+ * that opens and closes on the current line, with no interpolation or escape
500
+ * introducer between the opening quote and the token.
501
+ */
502
+ const isInPlainStringLiteral = (start, end) => {
503
+ while (cursor < start) {
504
+ const c = text[cursor];
505
+ if (quote === null) {
506
+ if (c === "'" || c === '"') {
507
+ quote = c;
508
+ introducerInString = false;
509
+ }
510
+ else if (c === "`" || c === "#" || text.startsWith("//", cursor) || text.startsWith("/*", cursor) || text.startsWith("--", cursor)) {
511
+ return false;
512
+ }
513
+ }
514
+ else if (c === "\\") {
515
+ introducerInString = true;
516
+ cursor++;
517
+ }
518
+ else if (c === quote) {
519
+ quote = null;
520
+ }
521
+ else if (c === "{" || c === "$" || c === "`") {
522
+ introducerInString = true;
523
+ }
524
+ cursor++;
525
+ }
526
+ if (quote === null || introducerInString)
527
+ return false;
528
+ // A token holds no quote or backslash, so a search from an earlier token
529
+ // in this string walked through this one: its answer still holds, and each
530
+ // string on the line is searched once.
531
+ if (closingQuote >= end)
532
+ return true;
533
+ for (let i = end; i < lineEnd; i++) {
534
+ if (text[i] === "\\") {
535
+ i++;
536
+ continue;
537
+ }
538
+ if (text[i] === quote) {
539
+ closingQuote = i;
540
+ return true;
541
+ }
542
+ }
543
+ return false;
544
+ };
545
+ return (start, end) => {
546
+ if (start > lineEnd)
547
+ enterLineOf(start);
548
+ return !crossesLineBoundary && isInPlainStringLiteral(start, end);
549
+ };
550
+ }
275
551
  /**
276
552
  * Bound on distinct session identities retained for disposal. The core already
277
553
  * caps committed sessions; this bounds identities seen with safe-only content
@@ -1211,30 +1487,148 @@ export function createTransparentSessionGuard(config, attachmentsPolicy = "block
1211
1487
  }
1212
1488
  };
1213
1489
  /**
1214
- * Restores registered tokens in a tool input leaf. For shell-like tools the
1215
- * token must occupy a complete argument word AND its original must be safe
1216
- * in that word's existing quote context. Command/assignment/redirect tokens,
1217
- * expansion, quote-breaking and option injection refuse the whole call.
1490
+ * True when at least one placeholder in `text` belongs to this session.
1491
+ * Shell quoting rules only matter when a placeholder is actually replaced;
1492
+ * an unmapped literal must fall through to the mapping policy instead of
1493
+ * being reported as an unsupported shell construct.
1494
+ */
1495
+ const containsMappedToken = (sessionID, text) => {
1496
+ for (const match of text.matchAll(TOKEN_SCAN)) {
1497
+ if (transportService.restoreText(sessionID, match[0]).ok)
1498
+ return true;
1499
+ }
1500
+ return false;
1501
+ };
1502
+ /**
1503
+ * True when `text` holds a placeholder of this session whose format was
1504
+ * changed (brackets dropped or half-dropped, separators swapped, case
1505
+ * lowered, separators changed or removed). Exact canonical tokens are blanked first; partially masked forms
1506
+ * and tokens unknown to the session never qualify.
1507
+ */
1508
+ const textHasNearMiss = (sessionID, text) => {
1509
+ if (!/sgp2/i.test(text))
1510
+ return false;
1511
+ const rest = text.replace(TOKEN_SCAN, " ");
1512
+ for (const head of rest.matchAll(NEAR_MISS_V2_HEAD)) {
1513
+ const letters = collectNearMissLetters(rest, head.index + head[0].length);
1514
+ const upper = letters.toUpperCase();
1515
+ for (const [compact, label] of NEAR_MISS_V2_CATEGORIES) {
1516
+ if (!upper.startsWith(compact) || letters.length - compact.length < NEAR_MISS_V2_SEGMENT_LETTERS)
1517
+ continue;
1518
+ const body = letters.slice(compact.length, compact.length + NEAR_MISS_V2_SEGMENT_LETTERS).toLowerCase();
1519
+ const canonical = `[SGP2:${label}-${body.slice(0, 4)}-${body.slice(4, 8)}-${body.slice(8, 12)}]`;
1520
+ ensureSeeded(sessionID);
1521
+ if (transportService.restoreText(sessionID, canonical).ok)
1522
+ return true;
1523
+ }
1524
+ }
1525
+ return false;
1526
+ };
1527
+ /**
1528
+ * Read-only walk over every string leaf and object key of a tool input.
1529
+ * Never throws and never runs getters: proxies, accessors, symbols and
1530
+ * non-plain objects are skipped silently, cycles are guarded, frozen objects
1531
+ * are scanned. `skipCode` leaves the top-level `code` string of a Code Mode
1532
+ * call alone.
1533
+ */
1534
+ const inputHasNearMiss = (sessionID, input, skipCode) => {
1535
+ try {
1536
+ if (typeof input === "string")
1537
+ return textHasNearMiss(sessionID, input);
1538
+ const seen = new WeakSet();
1539
+ const stack = [{ value: input, top: true }];
1540
+ while (stack.length > 0) {
1541
+ const { value, top } = stack.pop();
1542
+ if (value === null || typeof value !== "object")
1543
+ continue;
1544
+ if (types.isProxy(value) || seen.has(value))
1545
+ continue;
1546
+ seen.add(value);
1547
+ const isArray = Array.isArray(value);
1548
+ if (!isArray) {
1549
+ const prototype = Object.getPrototypeOf(value);
1550
+ if (prototype !== Object.prototype && prototype !== null)
1551
+ continue;
1552
+ }
1553
+ const descriptors = Object.getOwnPropertyDescriptors(value);
1554
+ for (const key of Object.keys(descriptors)) {
1555
+ if (isArray && key === "length")
1556
+ continue;
1557
+ if (!isArray && textHasNearMiss(sessionID, key))
1558
+ return true;
1559
+ const descriptor = descriptors[key];
1560
+ if (!("value" in descriptor))
1561
+ continue;
1562
+ if (skipCode && top && key === "code" && typeof descriptor.value === "string")
1563
+ continue;
1564
+ if (typeof descriptor.value === "string") {
1565
+ if (textHasNearMiss(sessionID, descriptor.value))
1566
+ return true;
1567
+ }
1568
+ else {
1569
+ stack.push({ value: descriptor.value, top: false });
1570
+ }
1571
+ }
1572
+ }
1573
+ }
1574
+ catch {
1575
+ return false;
1576
+ }
1577
+ return false;
1578
+ };
1579
+ /**
1580
+ * Restores registered tokens in a tool input leaf according to its policy.
1581
+ * "shell": the token must occupy a complete argument word AND its original
1582
+ * must be safe in that word's quote context; command/assignment/redirect
1583
+ * tokens, expansion, quote-breaking and option injection refuse the call.
1584
+ * "inert" (code/script fields): every restorable token's original must be
1585
+ * free of shell-unsafe characters (spaces included), and the token must sit
1586
+ * look like it sits in an ordinary single-line quoted string without
1587
+ * interpolation, outside any multi-line string or line continuation
1588
+ * (conservative heuristic, not a parser: it can over-refuse and miss, and
1589
+ * does not confirm the token is in a string; it guards the restoration
1590
+ * context, not egress). Otherwise the call is refused. "verbatim": plain restore.
1218
1591
  *
1219
1592
  * P1 (2026-10-06b) limited best-effort: when `allowDegraded` is set (the
1220
- * call is a proven read-only tool, not shell-like) a mapping failure
1221
- * (unknown/malformed marker) keeps the leaf literal and records a
1222
- * degradation instead of refusing — the placeholder reads as a literal
1223
- * that matches nothing, the tool's own output is the in-band signal, and a
1224
- * content-free WARN line is logged. Every other failure kind still refuses.
1593
+ * call is a proven read-only tool with no shell/code fields) and the leaf is
1594
+ * "verbatim", a mapping failure (unknown/malformed marker) keeps the leaf
1595
+ * literal and records a degradation instead of refusing. Every other
1596
+ * failure kind still refuses.
1225
1597
  */
1226
- const restoreLeaf = (sessionID, text, shellLike, allowDegraded, degraded) => {
1598
+ const restoreLeaf = (sessionID, text, policy, allowDegraded, degraded) => {
1227
1599
  if (!containsTokenPrefix(text))
1228
1600
  return text;
1229
- if (shellLike) {
1601
+ if (policy === "inert" && containsMappedToken(sessionID, text)) {
1602
+ const isAllowedPosition = createInertPositionCheck(text);
1603
+ for (const match of text.matchAll(TOKEN_SCAN)) {
1604
+ const restoredToken = transportService.restoreText(sessionID, match[0]);
1605
+ if (!restoredToken.ok)
1606
+ continue;
1607
+ if (!isShellSafeOriginal(restoredToken.text, "none"))
1608
+ throw new Error(TOOL_CODE_CONTEXT_ERROR);
1609
+ if (!isAllowedPosition(match.index, match.index + match[0].length))
1610
+ throw new Error(TOOL_CODE_POSITION_ERROR);
1611
+ }
1612
+ }
1613
+ if (policy === "shell" && containsMappedToken(sessionID, text)) {
1230
1614
  const argumentsOnly = parseSupportedShellArguments(text);
1231
1615
  if (argumentsOnly === null)
1232
1616
  throw new Error(TOOL_SHELL_CONTEXT_ERROR);
1617
+ const embedded = commandAllowsEmbeddedTokens(text);
1618
+ if (isWgetExecuteCommand(text))
1619
+ throw new Error(TOOL_SHELL_CONTEXT_ERROR);
1233
1620
  for (const match of text.matchAll(TOKEN_SCAN)) {
1234
1621
  const end = match.index + match[0].length;
1235
- const argument = argumentsOnly.find((word) => word.value === match[0] && word.start <= match.index && word.end >= end);
1622
+ const argument = argumentsOnly.find((word) => (embedded || word.value === match[0]) && word.start <= match.index && word.end >= end);
1236
1623
  if (argument === undefined)
1237
1624
  throw new Error(TOOL_SHELL_CONTEXT_ERROR);
1625
+ // In a word starting with `-`, only `--name=value` may hold a token. Short
1626
+ // options cluster, with punctuation flags too (`-#`, `-:`), so restored
1627
+ // text could become an option and its value (`-#T/tmp/x` uploads a file).
1628
+ const valueStart = argument.start + (argument.quote === "none" ? 0 : 1);
1629
+ const before = text.slice(valueStart, match.index);
1630
+ if (before.startsWith("-") && !/^--[A-Za-z0-9-]+=/.test(before))
1631
+ throw new Error(TOOL_SHELL_CONTEXT_ERROR);
1238
1632
  const restoredToken = transportService.restoreText(sessionID, match[0]);
1239
1633
  if (!restoredToken.ok)
1240
1634
  throw new Error(toolRestoreError(restoredToken.reason));
@@ -1246,6 +1640,7 @@ export function createTransparentSessionGuard(config, attachmentsPolicy = "block
1246
1640
  if (restored.ok)
1247
1641
  return restored.text;
1248
1642
  if (allowDegraded &&
1643
+ policy === "verbatim" &&
1249
1644
  (restored.reason === "unknown_token" || restored.reason === "malformed_token")) {
1250
1645
  degraded.count += 1;
1251
1646
  return text;
@@ -1254,61 +1649,100 @@ export function createTransparentSessionGuard(config, attachmentsPolicy = "block
1254
1649
  };
1255
1650
  /**
1256
1651
  * Planning pass: computes every replacement WITHOUT mutating, and rejects
1257
- * frozen/unwritable containers or token-bearing keys. Nothing is written
1258
- * until the whole plan is known to be applicable.
1652
+ * proxies, shared/cyclic references, symbol keys, accessors, odd prototypes,
1653
+ * non-index array keys and token-bearing keys anywhere in the tree.
1654
+ *
1655
+ * A writable container gets its replacements pushed onto `out`. A frozen
1656
+ * container is never written: when its subtree needs a change it is rebuilt
1657
+ * as a new plain container and RETURNED, so the caller (the nearest writable
1658
+ * ancestor, or an enclosing frozen copy) takes it in place of the original.
1659
+ * It returns `undefined` when the value needs no replacement.
1259
1660
  */
1260
- const planToolInput = (value, sessionID, shellLike, seen, out, allowDegraded, degraded) => {
1661
+ const planToolInput = (value, sessionID, policy, seen, out, allowDegraded, degraded) => {
1261
1662
  if (value === null || typeof value !== "object")
1262
- return;
1263
- if (types.isProxy(value) || seen.has(value) || Object.isFrozen(value)) {
1663
+ return undefined;
1664
+ if (types.isProxy(value) || seen.has(value))
1264
1665
  throw new Error(TOOL_INPUT_SHAPE_ERROR);
1265
- }
1266
1666
  seen.add(value);
1667
+ const frozen = Object.isFrozen(value);
1267
1668
  if (Object.getOwnPropertySymbols(value).length > 0)
1268
1669
  throw new Error(TOOL_INPUT_SHAPE_ERROR);
1269
- if (Array.isArray(value)) {
1270
- for (const key of Object.keys(value)) {
1670
+ const isArray = Array.isArray(value);
1671
+ const changes = [];
1672
+ const plan = (item, itemPolicy, key) => {
1673
+ if (typeof item === "string") {
1674
+ const next = restoreLeaf(sessionID, item, itemPolicy, allowDegraded, degraded);
1675
+ if (next !== item)
1676
+ changes.push({ key, next });
1677
+ }
1678
+ else {
1679
+ const next = planToolInput(item, sessionID, itemPolicy, seen, out, allowDegraded, degraded);
1680
+ if (next !== undefined)
1681
+ changes.push({ key, next });
1682
+ }
1683
+ };
1684
+ if (isArray) {
1685
+ const array = value;
1686
+ for (const key of Object.keys(array)) {
1271
1687
  if (!/^(0|[1-9]\d*)$/.test(key))
1272
1688
  throw new Error(TOOL_INPUT_SHAPE_ERROR);
1273
1689
  }
1274
- for (let index = 0; index < value.length; index++) {
1275
- const descriptor = Object.getOwnPropertyDescriptor(value, index);
1690
+ for (let index = 0; index < array.length; index++) {
1691
+ const descriptor = Object.getOwnPropertyDescriptor(array, index);
1276
1692
  if (descriptor === undefined)
1277
1693
  continue;
1278
- if (!("value" in descriptor))
1694
+ if (!("value" in descriptor) || !descriptor.enumerable)
1279
1695
  throw new Error(TOOL_INPUT_SHAPE_ERROR);
1280
- const item = descriptor.value;
1281
- if (typeof item === "string") {
1282
- const next = restoreLeaf(sessionID, item, shellLike, allowDegraded, degraded);
1283
- if (next !== item)
1284
- out.push({ container: value, key: index, value: next });
1285
- }
1286
- else {
1287
- planToolInput(item, sessionID, shellLike, seen, out, allowDegraded, degraded);
1288
- }
1696
+ plan(descriptor.value, policy, index);
1289
1697
  }
1290
- return;
1291
1698
  }
1292
- const prototype = Object.getPrototypeOf(value);
1293
- if (prototype !== Object.prototype && prototype !== null)
1294
- throw new Error(TOOL_INPUT_SHAPE_ERROR);
1295
- const record = value;
1296
- for (const key of Object.keys(record)) {
1297
- if (containsTokenPrefix(key))
1699
+ else {
1700
+ const prototype = Object.getPrototypeOf(value);
1701
+ if (prototype !== Object.prototype && prototype !== null)
1298
1702
  throw new Error(TOOL_INPUT_SHAPE_ERROR);
1299
- const descriptor = Object.getOwnPropertyDescriptor(record, key);
1300
- if (descriptor === undefined || !("value" in descriptor))
1703
+ const record = value;
1704
+ // A copy keeps enumerable keys only, so a hidden property would vanish from it.
1705
+ if (Object.getOwnPropertyNames(record).length !== Object.keys(record).length)
1301
1706
  throw new Error(TOOL_INPUT_SHAPE_ERROR);
1302
- const item = descriptor.value;
1303
- if (typeof item === "string") {
1304
- const next = restoreLeaf(sessionID, item, shellLike, allowDegraded, degraded);
1305
- if (next !== item)
1306
- out.push({ container: record, key, value: next });
1707
+ for (const key of Object.keys(record)) {
1708
+ if (containsTokenPrefix(key))
1709
+ throw new Error(TOOL_INPUT_SHAPE_ERROR);
1710
+ const descriptor = Object.getOwnPropertyDescriptor(record, key);
1711
+ if (descriptor === undefined || !("value" in descriptor))
1712
+ throw new Error(TOOL_INPUT_SHAPE_ERROR);
1713
+ plan(descriptor.value, keyPolicy(key, policy), key);
1307
1714
  }
1308
- else {
1309
- planToolInput(item, sessionID, shellLike, seen, out, allowDegraded, degraded);
1715
+ }
1716
+ if (changes.length === 0)
1717
+ return undefined;
1718
+ if (!frozen) {
1719
+ for (const change of changes) {
1720
+ out.push({ container: value, key: change.key, value: change.next });
1721
+ }
1722
+ return undefined;
1723
+ }
1724
+ // Frozen: copy only this container, keeping key order and array positions.
1725
+ const replaced = new Map(changes.map((change) => [change.key, change.next]));
1726
+ if (isArray) {
1727
+ const source = value;
1728
+ const copy = new Array(source.length);
1729
+ for (const key of Object.keys(source)) {
1730
+ const index = Number(key);
1731
+ copy[index] = replaced.has(index) ? replaced.get(index) : source[index];
1310
1732
  }
1733
+ return copy;
1311
1734
  }
1735
+ const source = value;
1736
+ const copy = Object.create(Object.getPrototypeOf(source));
1737
+ for (const key of Object.keys(source)) {
1738
+ Object.defineProperty(copy, key, {
1739
+ value: replaced.has(key) ? replaced.get(key) : source[key],
1740
+ writable: true,
1741
+ enumerable: true,
1742
+ configurable: true,
1743
+ });
1744
+ }
1745
+ return copy;
1312
1746
  };
1313
1747
  const assertToolPlanWritable = (plan) => {
1314
1748
  for (const assignment of plan) {
@@ -1328,29 +1762,73 @@ export function createTransparentSessionGuard(config, attachmentsPolicy = "block
1328
1762
  }
1329
1763
  }
1330
1764
  };
1765
+ /** Classifies without running a getter or proxy trap: only an own string data property counts. */
1766
+ const isCodeModeCall = (event) => {
1767
+ if (event.tool !== CODE_MODE_TOOL || !isRecordLike(event.input) || types.isProxy(event.input))
1768
+ return false;
1769
+ const descriptor = Object.getOwnPropertyDescriptor(event.input, "code");
1770
+ return descriptor !== undefined && "value" in descriptor && typeof descriptor.value === "string";
1771
+ };
1331
1772
  const onToolBefore = (event) => {
1773
+ const codeMode = isCodeModeCall(event);
1774
+ // Placeholders whose format the model changed would reach the tool as junk
1775
+ // with no error; refuse them before anything is restored or mutated.
1776
+ if (typeof event.sessionID === "string" && event.sessionID.length > 0) {
1777
+ if (inputHasNearMiss(event.sessionID, event.input, codeMode)) {
1778
+ throw new Error(TOOL_PLACEHOLDER_NEAR_MISS_ERROR);
1779
+ }
1780
+ if (codeMode) {
1781
+ const code = event.input.code;
1782
+ if (/\bfetch\b/.test(code) && /sgp[12]/i.test(code)) {
1783
+ ensureSeeded(event.sessionID);
1784
+ if (containsMappedToken(event.sessionID, code) || textHasNearMiss(event.sessionID, code)) {
1785
+ throw new Error(TOOL_CODE_FETCH_ERROR);
1786
+ }
1787
+ }
1788
+ }
1789
+ }
1332
1790
  if (!inputCarriesToken(event.input, new WeakSet()))
1333
1791
  return;
1334
1792
  const sessionID = requireSessionID(event);
1335
1793
  ensureSeeded(sessionID);
1336
- const tool = typeof event.tool === "string" ? event.tool.toLowerCase() : "";
1337
- const shellLike = !NON_SHELL_TOOLS.has(tool) ||
1338
- (isRecordLike(event.input) && typeof event.input.command === "string");
1339
- // P1 (2026-10-06b): only proven read-only, non-shell tools may degrade to
1340
- // literal placeholders; writes/deletes/outbound/unknown tools keep
1341
- // refusing the affected invocation when restoration is incomplete.
1342
- const allowDegraded = READ_ONLY_TOOLS.has(tool) && !shellLike;
1794
+ const rawTool = typeof event.tool === "string" ? event.tool : "";
1795
+ const tool = rawTool.toLowerCase();
1796
+ // Code Mode source is JavaScript and the host re-fires this hook for each
1797
+ // inner tool call with evaluated arguments; that is where restoration and
1798
+ // the shell/inert/verbatim rules apply. A placeholder in the source stays
1799
+ // literal. Any other shape or name falls through to the logic below.
1800
+ if (codeMode) {
1801
+ return;
1802
+ }
1803
+ // Field-level model: the root policy is "shell" for shell tools and
1804
+ // "verbatim" otherwise; each key may then switch the policy for its value
1805
+ // (shell/command-like keys -> "shell", code/script keys -> "inert",
1806
+ // description/title/label -> "verbatim").
1807
+ const shellTool = isShellTool(rawTool);
1808
+ const rootPolicy = shellTool ? "shell" : "verbatim";
1809
+ // P1 (2026-10-06b): only proven read-only tools without shell/code fields
1810
+ // may degrade to literal placeholders; everything else refuses the
1811
+ // affected invocation when restoration is incomplete.
1812
+ const allowDegraded = READ_ONLY_TOOLS.has(tool) &&
1813
+ !shellTool &&
1814
+ !(isRecordLike(event.input) &&
1815
+ Object.keys(event.input).some((key) => isShellKey(key) || isCodeKey(key)));
1343
1816
  const degraded = { count: 0 };
1344
1817
  if (typeof event.input === "string") {
1345
1818
  const descriptor = Object.getOwnPropertyDescriptor(event, "input");
1346
1819
  if (descriptor === undefined || !("value" in descriptor) || descriptor.writable !== true) {
1347
1820
  throw new Error(TOOL_INPUT_SHAPE_ERROR);
1348
1821
  }
1349
- event.input = restoreLeaf(sessionID, event.input, shellLike, allowDegraded, degraded);
1822
+ event.input = restoreLeaf(sessionID, event.input, rootPolicy, allowDegraded, degraded);
1350
1823
  }
1351
1824
  else {
1825
+ // The root is the one container that is never copied: it is the host's
1826
+ // own event object slot, so a frozen root stays refused.
1827
+ if (event.input !== null && typeof event.input === "object" && (types.isProxy(event.input) || Object.isFrozen(event.input))) {
1828
+ throw new Error(TOOL_INPUT_SHAPE_ERROR);
1829
+ }
1352
1830
  const plan = [];
1353
- planToolInput(event.input, sessionID, shellLike, new WeakSet(), plan, allowDegraded, degraded);
1831
+ planToolInput(event.input, sessionID, rootPolicy, new WeakSet(), plan, allowDegraded, degraded);
1354
1832
  assertToolPlanWritable(plan);
1355
1833
  applyToolPlan(plan);
1356
1834
  }
package/package.json CHANGED
@@ -1,8 +1,9 @@
1
1
  {
2
2
  "name": "leakshield",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "description": "OpenCode plugin, CLI, and web scanner for sensitive content before sending it to AI",
5
- "license": "MIT",
5
+ "license": "Apache-2.0",
6
+ "author": "Jared Wang",
6
7
  "repository": {
7
8
  "type": "git",
8
9
  "url": "git+https://github.com/jwcrystal/leakshield.git"
@@ -28,7 +29,8 @@
28
29
  "./package.json": "./package.json"
29
30
  },
30
31
  "files": [
31
- "dist"
32
+ "dist",
33
+ "NOTICE"
32
34
  ],
33
35
  "engines": {
34
36
  "node": ">=20"