@gpzhang2001/sharpkit-browser 0.2.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 +201 -0
- package/README.md +18 -0
- package/THIRD_PARTY_NOTICES.md +48 -0
- package/lib/index.d.ts +58 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +204 -0
- package/lib/index.js.map +1 -0
- package/package.json +52 -0
- package/src/index.ts +224 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 gpzhang2001
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# @gpzhang2001/sharpkit-browser
|
|
2
|
+
|
|
3
|
+
`view_image`:把沙箱内的截图以图像内容块回传给模型。浏览器驱动本身不经独立工具——agent 经 `exec_command` 调容器内 `agent-browser` CLI,截图默认落在 `/workspace/.agent-browser-screenshots/`。
|
|
4
|
+
|
|
5
|
+
## view_image
|
|
6
|
+
|
|
7
|
+
- 相对路径落 screenshotDir;绝对路径必须在工作区内(strix 错误文案)
|
|
8
|
+
- `session.getFile`(docker cp 二进制安全)读字节 → magic bytes 识别 PNG/JPEG/WebP/GIF
|
|
9
|
+
- **attachments 管线**(mcp-client 对齐):execute 内经 `resolveModelInfo` 证明模型 image input 能力 → `attachments.saveImages` 持久化 → `finalizeContent`(WeakMap 投影)换入 image block;任一步失败降级为文本诊断,canonical base64 保留——视觉模型缺失不会杀扫描(strix `strip_all_images_from_session` 的准入侧等价)
|
|
10
|
+
- `maxContextImages`(默认 3,strix STRIX_MAX_CONTEXT_IMAGES):每 scan 准入预算;窗口级图片剥离属 dsh compaction 层
|
|
11
|
+
|
|
12
|
+
## Config
|
|
13
|
+
|
|
14
|
+
`scanId`、`screenshotDir`、`maxImageBytes`(5MB)、`maxContextImages`(3)、`workspaceRoot`。
|
|
15
|
+
|
|
16
|
+
## 测试
|
|
17
|
+
|
|
18
|
+
`tests/browser.test.ts`:magic bytes / 路径解析 / 预算 / canonical value / finalizeContent 投影与降级(fake sandbox + attachments + llm)。
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# Third-Party Notices
|
|
2
|
+
|
|
3
|
+
This project builds on and derives assets from the following upstream
|
|
4
|
+
projects. Their licenses and attribution requirements are acknowledged here
|
|
5
|
+
as required by Apache-2.0 §4.
|
|
6
|
+
|
|
7
|
+
## strix — https://github.com/usestrix/strix
|
|
8
|
+
|
|
9
|
+
Copyright 2025 OmniSecure Inc. Licensed under the Apache License, Version 2.0.
|
|
10
|
+
|
|
11
|
+
sharpkit is an independent TypeScript reimplementation of strix's pentest
|
|
12
|
+
domain assets on the DeepSeek Harness plugin architecture (no strix code is
|
|
13
|
+
executed; no Python runtime is required). The following files are carried
|
|
14
|
+
**verbatim or near-verbatim** from strix and remain subject to the above
|
|
15
|
+
notice:
|
|
16
|
+
|
|
17
|
+
| sharpkit path | Origin | Changes |
|
|
18
|
+
| --- | --- | --- |
|
|
19
|
+
| `packages/preset/src/system_prompt.jinja` | `strix/agents/prompts/system_prompt.jinja` | none (byte-identical template) |
|
|
20
|
+
| `packages/skills/skills/**` (75 knowledge packs, 11 categories) | `strix/strix/skills/**` | none (migrated verbatim) |
|
|
21
|
+
| `sandbox-image/caido_api.py` | `strix/strix/tools/proxy/caido_api.py` | none (byte-identical) |
|
|
22
|
+
| `sandbox-image/docker-entrypoint.sh` | `strix/containers/docker-entrypoint.sh` | none (byte-identical) |
|
|
23
|
+
| `sandbox-image/Dockerfile` | `strix/containers/Dockerfile` | COPY source paths adapted to the standalone context; added overridable `GOPROXY`/`KALI_MIRROR` build args |
|
|
24
|
+
| `packages/preset/src/skills.ts` | `strix/strix/skills/__init__.py` | reimplemented in TypeScript (selection/validation semantics) |
|
|
25
|
+
|
|
26
|
+
The following subsystems are **semantic ports** (behavior-preserving
|
|
27
|
+
reimplementation, no verbatim text): the SARIF writer and vulnerability
|
|
28
|
+
artifact writers (`packages/tool-reporting/src/{sarif,writers,state}.ts` ←
|
|
29
|
+
`strix/report/*`), the reporting/analysis tool schemas
|
|
30
|
+
(`packages/tool-reporting`, `packages/tool-analysis` ← `strix/tools/*`), the
|
|
31
|
+
Caido client (`packages/tool-proxy/src/client.ts` ← the client half of
|
|
32
|
+
`strix/tools/proxy/caido_api.py`), the sandbox session manager
|
|
33
|
+
(`packages/sandbox` ← `strix/runtime/*`), and the scan-mode preset semantics
|
|
34
|
+
(`packages/preset` ← `strix/agents/factory.py` + `core/inputs.py`).
|
|
35
|
+
|
|
36
|
+
## DeepSeek Harness (dsh) — https://github.com/deepseek-ai/deepseek-harness
|
|
37
|
+
|
|
38
|
+
MIT License. Copyright (c) DeepSeek.
|
|
39
|
+
|
|
40
|
+
dsh is a runtime dependency only (`@deepseek-ai/dsh-*` npm packages); no dsh
|
|
41
|
+
source is embedded or modified in this repository.
|
|
42
|
+
|
|
43
|
+
## Sandbox image components
|
|
44
|
+
|
|
45
|
+
The built `sharpkit-sandbox` image bundles Kali Linux and third-party security
|
|
46
|
+
tools (nmap, sqlmap, nuclei, Caido, agent-browser, chromium, and others), each
|
|
47
|
+
under its own license inside the image. Distributing a built image is the
|
|
48
|
+
operator's responsibility; this repository ships only the build recipe.
|
package/lib/index.d.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import z from "@deepseek-ai/schemastery";
|
|
2
|
+
import { Context } from "@deepseek-ai/cordis";
|
|
3
|
+
import { ImageMediaType } from "@deepseek-ai/dsh-attachment";
|
|
4
|
+
//#region src/index.d.ts
|
|
5
|
+
var [Config] = [
|
|
6
|
+
0,
|
|
7
|
+
() => [],
|
|
8
|
+
[
|
|
9
|
+
"",
|
|
10
|
+
"",
|
|
11
|
+
"",
|
|
12
|
+
"",
|
|
13
|
+
""
|
|
14
|
+
]
|
|
15
|
+
];
|
|
16
|
+
var [name] = [
|
|
17
|
+
1,
|
|
18
|
+
() => [],
|
|
19
|
+
[]
|
|
20
|
+
];
|
|
21
|
+
var [inject] = [
|
|
22
|
+
2,
|
|
23
|
+
() => [],
|
|
24
|
+
[]
|
|
25
|
+
];
|
|
26
|
+
var [Config] = [
|
|
27
|
+
3,
|
|
28
|
+
() => [Config, z],
|
|
29
|
+
["", ""]
|
|
30
|
+
];
|
|
31
|
+
var [detectImageMediaType] = [
|
|
32
|
+
4,
|
|
33
|
+
() => [Uint8Array, ImageMediaType],
|
|
34
|
+
[
|
|
35
|
+
"",
|
|
36
|
+
"",
|
|
37
|
+
""
|
|
38
|
+
]
|
|
39
|
+
];
|
|
40
|
+
var [resolveContainerPath] = [
|
|
41
|
+
5,
|
|
42
|
+
() => [],
|
|
43
|
+
["", ""]
|
|
44
|
+
];
|
|
45
|
+
var [apply] = [
|
|
46
|
+
6,
|
|
47
|
+
() => [Context, Config],
|
|
48
|
+
[
|
|
49
|
+
"",
|
|
50
|
+
"",
|
|
51
|
+
"",
|
|
52
|
+
""
|
|
53
|
+
]
|
|
54
|
+
];
|
|
55
|
+
//#endregion
|
|
56
|
+
export { Config, apply, detectImageMediaType, inject, name, resolveContainerPath };
|
|
57
|
+
|
|
58
|
+
//# sourceMappingURL=index.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.ts","names":["Schema"],"sources":["../src/index.d.ts"],"sourcesContent":["/**\n * `view_image` over the pentest sandbox — strix SDK ViewImageTool semantics:\n * load an image from the container workspace and hand it to the model as an\n * image content block. Screenshots default to the image's\n * `/workspace/.agent-browser-screenshots/` (the agent-browser CLI writes\n * there; driving the browser itself stays exec_command work, per strix —\n * skills/tooling/agent_browser.md). The canonical value carries the base64\n * payload losslessly (mcp-client parity); the image is durably stored in\n * `execute` through the host attachment store after proving the routed model\n * accepts image input, and `finalizeContent` swaps the image block in —\n * degrading to a text diagnostic otherwise, so a vision-less model never\n * kills the scan (strix strips images from session instead; we refuse at\n * admission). `maxContextImages` bounds per-scan admissions (strix\n * STRIX_MAX_CONTEXT_IMAGES analogue; window-level stripping is a dsh\n * compaction concern).\n * @module @gpzhang2001/sharpkit-browser\n */\nimport type { Context } from '@deepseek-ai/cordis';\nimport type Schema from '@deepseek-ai/schemastery';\nimport type { ImageMediaType } from '@deepseek-ai/dsh-attachment';\n/** Deployment-tunable configuration. */\nexport interface Config {\n /** Sandbox session cache key shared with the other tool packages. */\n readonly scanId?: string;\n /** Default directory for relative paths (the image's screenshot dir). */\n readonly screenshotDir?: string;\n /** Per-call byte ceiling on admitted images. */\n readonly maxImageBytes?: number;\n /**\n * Per-scan admission budget (strix STRIX_MAX_CONTEXT_IMAGES, default 3);\n * window-level stripping stays with dsh compaction.\n */\n readonly maxContextImages?: number;\n /** Container workspace root (path resolution). */\n readonly workspaceRoot?: string;\n}\nexport declare const name = \"pentest-tool-browser\";\nexport declare const inject: string[];\nexport declare const Config: Schema<Config>;\n/**\n * Detect the image media type from magic bytes (admission re-verifies).\n * @param bytes - the raw file bytes.\n * @returns the media type, or null when the signature matches none.\n */\nexport declare function detectImageMediaType(bytes: Uint8Array): ImageMediaType | null;\n/**\n * Resolve the container path for a view_image argument: absolute paths must\n * stay inside the workspace; relative paths land in the screenshot dir.\n * @param path - the model-supplied path argument.\n * @param screenshotDir - default directory for relative paths.\n * @returns the absolute container path.\n */\nexport declare function resolveContainerPath(path: string, screenshotDir: string): string;\nexport declare function apply(ctx: Context, config?: Config): void;\n"],"mappings":";;;;AAGA,IAAW,CAAC,UAAU;CAAC;OAAS,CAAC;CAAG;EAAC;EAAI;EAAI;EAAI;EAAI;CAAE;AAAC;AACxD,IAAW,CAAC,QAAQ;CAAC;OAAS,CAAC;CAAG,CAAC;AAAC;AACpC,IAAW,CAAC,UAAU;CAAC;OAAS,CAAC;CAAG,CAAC;AAAC;AACtC,IAAW,CAAC,UAAU;CAAC;OAAS,CAAC,QAAQA,CAAM;CAAG,CAAC,IAAI,EAAE;AAAC;AAC1D,IAAW,CAAC,wBAAwB;CAAC;OAAS,CAAC,YAAY,cAAc;CAAG;EAAC;EAAI;EAAI;CAAE;AAAC;AACxF,IAAW,CAAC,wBAAwB;CAAC;OAAS,CAAC;CAAG,CAAC,IAAI,EAAE;AAAC;AAC1D,IAAW,CAAC,SAAS;CAAC;OAAS,CAAC,SAAS,MAAM;CAAG;EAAC;EAAI;EAAI;EAAI;CAAE;AAAC"}
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
import { Buffer } from "node:buffer";
|
|
2
|
+
import z from "@deepseek-ai/schemastery";
|
|
3
|
+
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
4
|
+
//#region src/index.ts
|
|
5
|
+
/**
|
|
6
|
+
* `view_image` over the pentest sandbox — strix SDK ViewImageTool semantics:
|
|
7
|
+
* load an image from the container workspace and hand it to the model as an
|
|
8
|
+
* image content block. Screenshots default to the image's
|
|
9
|
+
* `/workspace/.agent-browser-screenshots/` (the agent-browser CLI writes
|
|
10
|
+
* there; driving the browser itself stays exec_command work, per strix —
|
|
11
|
+
* skills/tooling/agent_browser.md). The canonical value carries the base64
|
|
12
|
+
* payload losslessly (mcp-client parity); the image is durably stored in
|
|
13
|
+
* `execute` through the host attachment store after proving the routed model
|
|
14
|
+
* accepts image input, and `finalizeContent` swaps the image block in —
|
|
15
|
+
* degrading to a text diagnostic otherwise, so a vision-less model never
|
|
16
|
+
* kills the scan (strix strips images from session instead; we refuse at
|
|
17
|
+
* admission). `maxContextImages` bounds per-scan admissions (strix
|
|
18
|
+
* STRIX_MAX_CONTEXT_IMAGES analogue; window-level stripping is a dsh
|
|
19
|
+
* compaction concern).
|
|
20
|
+
* @module @gpzhang2001/sharpkit-browser
|
|
21
|
+
*/
|
|
22
|
+
const name = "pentest-tool-browser";
|
|
23
|
+
const inject = ["tools", "pentestSandbox"];
|
|
24
|
+
const Config = z.object({
|
|
25
|
+
scanId: z.string().default("pentest"),
|
|
26
|
+
screenshotDir: z.string().default("/workspace/.agent-browser-screenshots"),
|
|
27
|
+
maxImageBytes: z.number().default(5242880),
|
|
28
|
+
maxContextImages: z.number().default(3),
|
|
29
|
+
workspaceRoot: z.string().default("/workspace")
|
|
30
|
+
});
|
|
31
|
+
/**
|
|
32
|
+
* Detect the image media type from magic bytes (admission re-verifies).
|
|
33
|
+
* @param bytes - the raw file bytes.
|
|
34
|
+
* @returns the media type, or null when the signature matches none.
|
|
35
|
+
*/
|
|
36
|
+
function detectImageMediaType(bytes) {
|
|
37
|
+
if (bytes.length >= 8 && bytes[0] === 137 && bytes[1] === 80 && bytes[2] === 78 && bytes[3] === 71) return "image/png";
|
|
38
|
+
if (bytes.length >= 3 && bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) return "image/jpeg";
|
|
39
|
+
if (bytes.length >= 12 && bytes[8] === 87 && bytes[9] === 69 && bytes[10] === 66 && bytes[11] === 80) return "image/webp";
|
|
40
|
+
if (bytes.length >= 6 && bytes[0] === 71 && bytes[1] === 73 && bytes[2] === 70) return "image/gif";
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Resolve the container path for a view_image argument: absolute paths must
|
|
45
|
+
* stay inside the workspace; relative paths land in the screenshot dir.
|
|
46
|
+
* @param path - the model-supplied path argument.
|
|
47
|
+
* @param screenshotDir - default directory for relative paths.
|
|
48
|
+
* @returns the absolute container path.
|
|
49
|
+
*/
|
|
50
|
+
function resolveContainerPath(path, screenshotDir) {
|
|
51
|
+
if (path.startsWith("/")) return path;
|
|
52
|
+
return `${screenshotDir.replace(/\/$/, "")}/${path}`;
|
|
53
|
+
}
|
|
54
|
+
function apply(ctx, config = {}) {
|
|
55
|
+
const admittedPerScan = /* @__PURE__ */ new Map();
|
|
56
|
+
const projections = /* @__PURE__ */ new WeakMap();
|
|
57
|
+
const session = () => ctx.pentestSandbox.createSession({ scanId: config.scanId ?? "pentest" });
|
|
58
|
+
const screenshotDir = config.screenshotDir ?? "/workspace/.agent-browser-screenshots";
|
|
59
|
+
const maxImageBytes = config.maxImageBytes ?? 5242880;
|
|
60
|
+
const maxContextImages = config.maxContextImages ?? 3;
|
|
61
|
+
const workspaceRoot = config.workspaceRoot ?? "/workspace";
|
|
62
|
+
ctx.tools.register(defineTool({
|
|
63
|
+
name: "view_image",
|
|
64
|
+
description: `Load an image from the sandbox filesystem and return it visually (for screenshots taken with the agent-browser CLI via exec_command). Paths resolve inside ${workspaceRoot}; bare filenames land in ${screenshotDir}.`,
|
|
65
|
+
parameters: { path: {
|
|
66
|
+
type: "string",
|
|
67
|
+
required: true,
|
|
68
|
+
description: `Image path inside ${workspaceRoot}, or a bare filename inside ${screenshotDir}.`
|
|
69
|
+
} },
|
|
70
|
+
output: {
|
|
71
|
+
schema: {
|
|
72
|
+
type: "object",
|
|
73
|
+
properties: {
|
|
74
|
+
path: {
|
|
75
|
+
type: "string",
|
|
76
|
+
required: true
|
|
77
|
+
},
|
|
78
|
+
media_type: {
|
|
79
|
+
type: "string",
|
|
80
|
+
required: true
|
|
81
|
+
},
|
|
82
|
+
size_bytes: {
|
|
83
|
+
type: "integer",
|
|
84
|
+
required: true
|
|
85
|
+
},
|
|
86
|
+
data_base64: {
|
|
87
|
+
type: "string",
|
|
88
|
+
required: true
|
|
89
|
+
}
|
|
90
|
+
},
|
|
91
|
+
additionalProperties: false
|
|
92
|
+
},
|
|
93
|
+
render: (_args, value) => {
|
|
94
|
+
const image = value;
|
|
95
|
+
return [{
|
|
96
|
+
type: "text",
|
|
97
|
+
text: `[image ${image.path} — ${image.media_type}, ${String(image.size_bytes)} bytes]`
|
|
98
|
+
}];
|
|
99
|
+
}
|
|
100
|
+
},
|
|
101
|
+
presentResult: (_args, result) => ({
|
|
102
|
+
card: "generic",
|
|
103
|
+
content: result.content.filter((block) => block.type === "text").map((block) => block.text).map((text) => ({
|
|
104
|
+
type: "text",
|
|
105
|
+
text
|
|
106
|
+
}))
|
|
107
|
+
}),
|
|
108
|
+
execute: async (args, exec) => {
|
|
109
|
+
const containerPath = resolveContainerPath(args.path, screenshotDir);
|
|
110
|
+
if (!containerPath.startsWith(`${workspaceRoot}/`)) throw new Error(`view_image: path must be inside ${workspaceRoot}. Got: '${args.path}'.`);
|
|
111
|
+
const scanKey = exec.agent?.session.id ?? config.scanId ?? "pentest";
|
|
112
|
+
const admitted = admittedPerScan.get(scanKey) ?? 0;
|
|
113
|
+
if (admitted >= maxContextImages) throw new Error(`view_image: the per-scan image budget is exhausted (maxContextImages=${String(maxContextImages)}); reuse earlier screenshots or start a new scan session.`);
|
|
114
|
+
const bytes = await (await session()).getFile(containerPath);
|
|
115
|
+
if (bytes.byteLength === 0) throw new Error(`view_image: ${containerPath} is empty`);
|
|
116
|
+
if (bytes.byteLength > maxImageBytes) throw new Error(`view_image: ${containerPath} is ${String(bytes.byteLength)} bytes, over the ${String(maxImageBytes)} limit`);
|
|
117
|
+
const mediaType = detectImageMediaType(bytes);
|
|
118
|
+
if (mediaType === null) throw new Error(`view_image: ${containerPath} is not a PNG/JPEG/WebP/GIF image`);
|
|
119
|
+
const value = {
|
|
120
|
+
path: containerPath,
|
|
121
|
+
media_type: mediaType,
|
|
122
|
+
size_bytes: bytes.byteLength,
|
|
123
|
+
data_base64: Buffer.from(bytes).toString("base64")
|
|
124
|
+
};
|
|
125
|
+
const fallback = [{
|
|
126
|
+
type: "text",
|
|
127
|
+
text: `[image ${containerPath} — ${mediaType}, ${String(bytes.byteLength)} bytes]`
|
|
128
|
+
}];
|
|
129
|
+
const projection = await prepareProjection(ctx, exec, {
|
|
130
|
+
data: bytes,
|
|
131
|
+
mediaType,
|
|
132
|
+
name: containerPath
|
|
133
|
+
}, value, fallback);
|
|
134
|
+
projections.set(exec, projection);
|
|
135
|
+
if (projection.content.some((block) => block.type === "image")) admittedPerScan.set(scanKey, admitted + 1);
|
|
136
|
+
return value;
|
|
137
|
+
},
|
|
138
|
+
finalizeContent(exec, result) {
|
|
139
|
+
const projection = projections.get(exec);
|
|
140
|
+
if (projection === void 0) return void 0;
|
|
141
|
+
projections.delete(exec);
|
|
142
|
+
if (result.isError) return void 0;
|
|
143
|
+
return projection.content;
|
|
144
|
+
}
|
|
145
|
+
}));
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Prove the routed model accepts image input, durably store the bytes, and
|
|
149
|
+
* build the final content (image block on success, diagnostic otherwise).
|
|
150
|
+
* Admission mirrors mcp-client: store → route → capability → save.
|
|
151
|
+
*/
|
|
152
|
+
async function prepareProjection(ctx, exec, input, value, fallback) {
|
|
153
|
+
const diagnostic = (reason) => ({
|
|
154
|
+
value,
|
|
155
|
+
fallback,
|
|
156
|
+
content: [{
|
|
157
|
+
type: "text",
|
|
158
|
+
text: `[image unavailable: ${input.name ?? "unknown"}; ${reason}; the raw base64 remains in the tool result]`
|
|
159
|
+
}]
|
|
160
|
+
});
|
|
161
|
+
let attachments;
|
|
162
|
+
try {
|
|
163
|
+
attachments = await resolveAttachmentStore(ctx, exec);
|
|
164
|
+
} catch (error) {
|
|
165
|
+
return diagnostic(String(error instanceof Error ? error.message : error));
|
|
166
|
+
}
|
|
167
|
+
try {
|
|
168
|
+
const attachment = (await attachments.saveImages([input]))[0];
|
|
169
|
+
if (attachment === void 0) return diagnostic("the attachment store returned no reference");
|
|
170
|
+
return {
|
|
171
|
+
value,
|
|
172
|
+
fallback,
|
|
173
|
+
content: [{
|
|
174
|
+
type: "image",
|
|
175
|
+
attachment
|
|
176
|
+
}]
|
|
177
|
+
};
|
|
178
|
+
} catch (error) {
|
|
179
|
+
return diagnostic(String(error instanceof Error ? error.message : error));
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
/** Resolve the attachment store after an exact model image-input proof. */
|
|
183
|
+
async function resolveAttachmentStore(ctx, exec) {
|
|
184
|
+
const attachments = ctx.get("attachments");
|
|
185
|
+
if (attachments === void 0) throw new Error("no attachment store is mounted");
|
|
186
|
+
const routed = exec.agent?.session.requestHeader()?.config;
|
|
187
|
+
const provider = routed?.provider ?? exec.agent?.options.provider;
|
|
188
|
+
const model = routed?.model ?? exec.agent?.options.model;
|
|
189
|
+
const llm = ctx.get("llm");
|
|
190
|
+
if (provider === void 0 || model === void 0 || llm === void 0) throw new Error("the current model route could not be resolved");
|
|
191
|
+
let info;
|
|
192
|
+
try {
|
|
193
|
+
info = await llm.resolveModelInfo(provider, model, exec.signal);
|
|
194
|
+
} catch {
|
|
195
|
+
throw new Error("the current model route could not be verified");
|
|
196
|
+
}
|
|
197
|
+
if (info.inputModalities === void 0 || !info.inputModalities.includes("image")) throw new Error(`model "${model}" does not declare image input`);
|
|
198
|
+
if (exec.signal.aborted) throw new Error("the tool call was canceled before image storage");
|
|
199
|
+
return attachments;
|
|
200
|
+
}
|
|
201
|
+
//#endregion
|
|
202
|
+
export { Config, apply, detectImageMediaType, inject, name, resolveContainerPath };
|
|
203
|
+
|
|
204
|
+
//# sourceMappingURL=index.js.map
|
package/lib/index.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * `view_image` over the pentest sandbox — strix SDK ViewImageTool semantics:\n * load an image from the container workspace and hand it to the model as an\n * image content block. Screenshots default to the image's\n * `/workspace/.agent-browser-screenshots/` (the agent-browser CLI writes\n * there; driving the browser itself stays exec_command work, per strix —\n * skills/tooling/agent_browser.md). The canonical value carries the base64\n * payload losslessly (mcp-client parity); the image is durably stored in\n * `execute` through the host attachment store after proving the routed model\n * accepts image input, and `finalizeContent` swaps the image block in —\n * degrading to a text diagnostic otherwise, so a vision-less model never\n * kills the scan (strix strips images from session instead; we refuse at\n * admission). `maxContextImages` bounds per-scan admissions (strix\n * STRIX_MAX_CONTEXT_IMAGES analogue; window-level stripping is a dsh\n * compaction concern).\n * @module @gpzhang2001/sharpkit-browser\n */\n\nimport { Buffer } from 'node:buffer'\nimport type { Context } from '@deepseek-ai/cordis'\nimport type Schema from '@deepseek-ai/schemastery'\nimport z from '@deepseek-ai/schemastery'\nimport { defineTool } from '@deepseek-ai/dsh-tools'\nimport type { ToolExecution, ToolExecutionResult } from '@deepseek-ai/dsh-tools'\nimport type { ContentBlock } from '@deepseek-ai/dsh-llm'\nimport type { AttachmentStore, ImageMediaType, SaveImageAttachment } from '@deepseek-ai/dsh-attachment'\n\n/** Deployment-tunable configuration. */\nexport interface Config {\n /** Sandbox session cache key shared with the other tool packages. */\n readonly scanId?: string\n /** Default directory for relative paths (the image's screenshot dir). */\n readonly screenshotDir?: string\n /** Per-call byte ceiling on admitted images. */\n readonly maxImageBytes?: number\n /**\n * Per-scan admission budget (strix STRIX_MAX_CONTEXT_IMAGES, default 3);\n * window-level stripping stays with dsh compaction.\n */\n readonly maxContextImages?: number\n /** Container workspace root (path resolution). */\n readonly workspaceRoot?: string\n}\n\nexport const name = 'pentest-tool-browser'\n\nexport const inject = ['tools', 'pentestSandbox']\n\nexport const Config: Schema<Config> = z.object({\n scanId: z.string().default('pentest'),\n screenshotDir: z.string().default('/workspace/.agent-browser-screenshots'),\n maxImageBytes: z.number().default(5_242_880),\n maxContextImages: z.number().default(3),\n workspaceRoot: z.string().default('/workspace'),\n})\n\n/**\n * Detect the image media type from magic bytes (admission re-verifies).\n * @param bytes - the raw file bytes.\n * @returns the media type, or null when the signature matches none.\n */\nexport function detectImageMediaType(bytes: Uint8Array): ImageMediaType | null {\n if (bytes.length >= 8 && bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47) return 'image/png'\n if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return 'image/jpeg'\n if (bytes.length >= 12 && bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50) return 'image/webp'\n if (bytes.length >= 6 && bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46) return 'image/gif'\n return null\n}\n\n/**\n * Resolve the container path for a view_image argument: absolute paths must\n * stay inside the workspace; relative paths land in the screenshot dir.\n * @param path - the model-supplied path argument.\n * @param screenshotDir - default directory for relative paths.\n * @returns the absolute container path.\n */\nexport function resolveContainerPath(path: string, screenshotDir: string): string {\n if (path.startsWith('/')) return path\n return `${screenshotDir.replace(/\\/$/, '')}/${path}`\n}\n\n/** One prepared image projection: stored ref + fallback content + value. */\ninterface ImageProjection {\n readonly value: unknown\n readonly fallback: readonly ContentBlock[]\n readonly content: readonly ContentBlock[]\n}\n\nexport function apply(ctx: Context, config: Config = {}): void {\n const admittedPerScan = new Map<string, number>()\n const projections = new WeakMap<ToolExecution, ImageProjection>()\n\n const session = () => ctx.pentestSandbox.createSession({ scanId: config.scanId ?? 'pentest' })\n const screenshotDir = config.screenshotDir ?? '/workspace/.agent-browser-screenshots'\n const maxImageBytes = config.maxImageBytes ?? 5_242_880\n const maxContextImages = config.maxContextImages ?? 3\n const workspaceRoot = config.workspaceRoot ?? '/workspace'\n\n ctx.tools.register(defineTool({\n name: 'view_image',\n description: `Load an image from the sandbox filesystem and return it visually (for screenshots taken with the agent-browser CLI via exec_command). Paths resolve inside ${workspaceRoot}; bare filenames land in ${screenshotDir}.`,\n parameters: {\n path: { type: 'string', required: true, description: `Image path inside ${workspaceRoot}, or a bare filename inside ${screenshotDir}.` },\n },\n output: {\n schema: {\n type: 'object',\n properties: {\n path: { type: 'string', required: true },\n media_type: { type: 'string', required: true },\n size_bytes: { type: 'integer', required: true },\n data_base64: { type: 'string', required: true },\n },\n additionalProperties: false,\n },\n render: (_args, value) => {\n const image = value as { path: string; media_type: string; size_bytes: number }\n return [{ type: 'text', text: `[image ${image.path} — ${image.media_type}, ${String(image.size_bytes)} bytes]` }]\n },\n },\n presentResult: (_args, result) => ({\n card: 'generic',\n content: result.content.filter(block => block.type === 'text').map(block => block.text).map(text => ({ type: 'text' as const, text })),\n }),\n execute: async (args, exec) => {\n const containerPath = resolveContainerPath(args.path, screenshotDir)\n if (!containerPath.startsWith(`${workspaceRoot}/`)) {\n throw new Error(`view_image: path must be inside ${workspaceRoot}. Got: '${args.path}'.`)\n }\n const scanKey = exec.agent?.session.id ?? (config.scanId ?? 'pentest')\n const admitted = admittedPerScan.get(scanKey) ?? 0\n if (admitted >= maxContextImages) {\n throw new Error(`view_image: the per-scan image budget is exhausted (maxContextImages=${String(maxContextImages)}); reuse earlier screenshots or start a new scan session.`)\n }\n const bytes = await (await session()).getFile(containerPath)\n if (bytes.byteLength === 0) throw new Error(`view_image: ${containerPath} is empty`)\n if (bytes.byteLength > maxImageBytes) throw new Error(`view_image: ${containerPath} is ${String(bytes.byteLength)} bytes, over the ${String(maxImageBytes)} limit`)\n const mediaType = detectImageMediaType(bytes)\n if (mediaType === null) throw new Error(`view_image: ${containerPath} is not a PNG/JPEG/WebP/GIF image`)\n const value = {\n path: containerPath,\n media_type: mediaType,\n size_bytes: bytes.byteLength,\n data_base64: Buffer.from(bytes).toString('base64'),\n }\n const fallback: ContentBlock[] = [{\n type: 'text',\n text: `[image ${containerPath} — ${mediaType}, ${String(bytes.byteLength)} bytes]`,\n }]\n const projection = await prepareProjection(ctx, exec, { data: bytes, mediaType, name: containerPath }, value, fallback)\n projections.set(exec, projection)\n // Count the admission only when the image actually entered the model\n // surface (a diagnostic-degraded projection consumed no image budget).\n if (projection.content.some(block => block.type === 'image')) {\n admittedPerScan.set(scanKey, admitted + 1)\n }\n return value\n },\n finalizeContent(exec: Readonly<ToolExecution>, result: Readonly<ToolExecutionResult>) {\n const projection = projections.get(exec)\n if (projection === undefined) return undefined\n projections.delete(exec)\n if (result.isError) return undefined\n return projection.content as ContentBlock[]\n },\n }))\n}\n\n/**\n * Prove the routed model accepts image input, durably store the bytes, and\n * build the final content (image block on success, diagnostic otherwise).\n * Admission mirrors mcp-client: store → route → capability → save.\n */\nasync function prepareProjection(\n ctx: Context,\n exec: ToolExecution,\n input: SaveImageAttachment,\n value: unknown,\n fallback: readonly ContentBlock[],\n): Promise<ImageProjection> {\n const diagnostic = (reason: string): ImageProjection => ({\n value,\n fallback,\n content: [{ type: 'text', text: `[image unavailable: ${input.name ?? 'unknown'}; ${reason}; the raw base64 remains in the tool result]` }],\n })\n let attachments: AttachmentStore | undefined\n try {\n attachments = await resolveAttachmentStore(ctx, exec)\n } catch (error) {\n return diagnostic(String(error instanceof Error ? error.message : error))\n }\n try {\n const refs = await attachments.saveImages([input])\n const attachment = refs[0]\n if (attachment === undefined) return diagnostic('the attachment store returned no reference')\n return { value, fallback, content: [{ type: 'image', attachment }] }\n } catch (error) {\n return diagnostic(String(error instanceof Error ? error.message : error))\n }\n}\n\n/** Resolve the attachment store after an exact model image-input proof. */\nasync function resolveAttachmentStore(ctx: Context, exec: ToolExecution): Promise<AttachmentStore> {\n const attachments = ctx.get('attachments')\n if (attachments === undefined) throw new Error('no attachment store is mounted')\n const routed = exec.agent?.session.requestHeader()?.config\n const provider = routed?.provider ?? exec.agent?.options.provider\n const model = routed?.model ?? exec.agent?.options.model\n const llm = ctx.get('llm')\n if (provider === undefined || model === undefined || llm === undefined) {\n throw new Error('the current model route could not be resolved')\n }\n let info: { readonly inputModalities?: readonly string[] }\n try {\n info = await llm.resolveModelInfo(provider, model, exec.signal)\n } catch {\n throw new Error('the current model route could not be verified')\n }\n if (info.inputModalities === undefined || !info.inputModalities.includes('image')) {\n throw new Error(`model \"${model}\" does not declare image input`)\n }\n if (exec.signal.aborted) throw new Error('the tool call was canceled before image storage')\n return attachments\n}\n"],"mappings":"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"}
|
package/package.json
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@gpzhang2001/sharpkit-browser",
|
|
3
|
+
"description": "view_image screenshot return over the attachment pipeline; browser driving stays exec_command (agent-browser CLI in the sandbox image)",
|
|
4
|
+
"version": "0.2.1",
|
|
5
|
+
"publishConfig": {
|
|
6
|
+
"access": "public"
|
|
7
|
+
},
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/gpzhang2001/sharpkit.git",
|
|
11
|
+
"directory": "packages/tool-browser"
|
|
12
|
+
},
|
|
13
|
+
"type": "module",
|
|
14
|
+
"license": "Apache-2.0",
|
|
15
|
+
"exports": {
|
|
16
|
+
".": {
|
|
17
|
+
"types": "./lib/index.d.ts",
|
|
18
|
+
"default": "./lib/index.js"
|
|
19
|
+
},
|
|
20
|
+
"./src/*": "./src/*",
|
|
21
|
+
"./package.json": "./package.json"
|
|
22
|
+
},
|
|
23
|
+
"files": [
|
|
24
|
+
"lib",
|
|
25
|
+
"src",
|
|
26
|
+
"LICENSE",
|
|
27
|
+
"THIRD_PARTY_NOTICES.md"
|
|
28
|
+
],
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"@deepseek-ai/schemastery": "3.18.2",
|
|
31
|
+
"@gpzhang2001/sharpkit-sandbox": "^0.2.1"
|
|
32
|
+
},
|
|
33
|
+
"peerDependencies": {
|
|
34
|
+
"@deepseek-ai/cordis": "^4.0.2",
|
|
35
|
+
"@deepseek-ai/dsh-attachment": "^0.1.2-rc.1",
|
|
36
|
+
"@deepseek-ai/dsh-llm": "^0.1.2-rc.1",
|
|
37
|
+
"@deepseek-ai/dsh-tools": "^0.1.2-rc.1",
|
|
38
|
+
"@gpzhang2001/sharpkit-sandbox": "^0.1.0"
|
|
39
|
+
},
|
|
40
|
+
"devDependencies": {
|
|
41
|
+
"@deepseek-ai/cordis": "4.0.2",
|
|
42
|
+
"@deepseek-ai/dsh-attachment": "0.1.2-rc.1",
|
|
43
|
+
"@deepseek-ai/dsh-llm": "0.1.2-rc.1",
|
|
44
|
+
"@deepseek-ai/dsh-tools": "0.1.2-rc.1",
|
|
45
|
+
"@gpzhang2001/sharpkit-sandbox": "^0.2.1"
|
|
46
|
+
},
|
|
47
|
+
"main": "lib/index.js",
|
|
48
|
+
"types": "lib/index.d.ts",
|
|
49
|
+
"scripts": {
|
|
50
|
+
"build": "cp ../../LICENSE ../../THIRD_PARTY_NOTICES.md . && tsdown && mv -f lib/index.ts lib/index.d.ts && mv -f lib/index.ts.map lib/index.d.ts.map"
|
|
51
|
+
}
|
|
52
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `view_image` over the pentest sandbox — strix SDK ViewImageTool semantics:
|
|
3
|
+
* load an image from the container workspace and hand it to the model as an
|
|
4
|
+
* image content block. Screenshots default to the image's
|
|
5
|
+
* `/workspace/.agent-browser-screenshots/` (the agent-browser CLI writes
|
|
6
|
+
* there; driving the browser itself stays exec_command work, per strix —
|
|
7
|
+
* skills/tooling/agent_browser.md). The canonical value carries the base64
|
|
8
|
+
* payload losslessly (mcp-client parity); the image is durably stored in
|
|
9
|
+
* `execute` through the host attachment store after proving the routed model
|
|
10
|
+
* accepts image input, and `finalizeContent` swaps the image block in —
|
|
11
|
+
* degrading to a text diagnostic otherwise, so a vision-less model never
|
|
12
|
+
* kills the scan (strix strips images from session instead; we refuse at
|
|
13
|
+
* admission). `maxContextImages` bounds per-scan admissions (strix
|
|
14
|
+
* STRIX_MAX_CONTEXT_IMAGES analogue; window-level stripping is a dsh
|
|
15
|
+
* compaction concern).
|
|
16
|
+
* @module @gpzhang2001/sharpkit-browser
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { Buffer } from 'node:buffer'
|
|
20
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
21
|
+
import type Schema from '@deepseek-ai/schemastery'
|
|
22
|
+
import z from '@deepseek-ai/schemastery'
|
|
23
|
+
import { defineTool } from '@deepseek-ai/dsh-tools'
|
|
24
|
+
import type { ToolExecution, ToolExecutionResult } from '@deepseek-ai/dsh-tools'
|
|
25
|
+
import type { ContentBlock } from '@deepseek-ai/dsh-llm'
|
|
26
|
+
import type { AttachmentStore, ImageMediaType, SaveImageAttachment } from '@deepseek-ai/dsh-attachment'
|
|
27
|
+
|
|
28
|
+
/** Deployment-tunable configuration. */
|
|
29
|
+
export interface Config {
|
|
30
|
+
/** Sandbox session cache key shared with the other tool packages. */
|
|
31
|
+
readonly scanId?: string
|
|
32
|
+
/** Default directory for relative paths (the image's screenshot dir). */
|
|
33
|
+
readonly screenshotDir?: string
|
|
34
|
+
/** Per-call byte ceiling on admitted images. */
|
|
35
|
+
readonly maxImageBytes?: number
|
|
36
|
+
/**
|
|
37
|
+
* Per-scan admission budget (strix STRIX_MAX_CONTEXT_IMAGES, default 3);
|
|
38
|
+
* window-level stripping stays with dsh compaction.
|
|
39
|
+
*/
|
|
40
|
+
readonly maxContextImages?: number
|
|
41
|
+
/** Container workspace root (path resolution). */
|
|
42
|
+
readonly workspaceRoot?: string
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export const name = 'pentest-tool-browser'
|
|
46
|
+
|
|
47
|
+
export const inject = ['tools', 'pentestSandbox']
|
|
48
|
+
|
|
49
|
+
export const Config: Schema<Config> = z.object({
|
|
50
|
+
scanId: z.string().default('pentest'),
|
|
51
|
+
screenshotDir: z.string().default('/workspace/.agent-browser-screenshots'),
|
|
52
|
+
maxImageBytes: z.number().default(5_242_880),
|
|
53
|
+
maxContextImages: z.number().default(3),
|
|
54
|
+
workspaceRoot: z.string().default('/workspace'),
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Detect the image media type from magic bytes (admission re-verifies).
|
|
59
|
+
* @param bytes - the raw file bytes.
|
|
60
|
+
* @returns the media type, or null when the signature matches none.
|
|
61
|
+
*/
|
|
62
|
+
export function detectImageMediaType(bytes: Uint8Array): ImageMediaType | null {
|
|
63
|
+
if (bytes.length >= 8 && bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47) return 'image/png'
|
|
64
|
+
if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return 'image/jpeg'
|
|
65
|
+
if (bytes.length >= 12 && bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50) return 'image/webp'
|
|
66
|
+
if (bytes.length >= 6 && bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46) return 'image/gif'
|
|
67
|
+
return null
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Resolve the container path for a view_image argument: absolute paths must
|
|
72
|
+
* stay inside the workspace; relative paths land in the screenshot dir.
|
|
73
|
+
* @param path - the model-supplied path argument.
|
|
74
|
+
* @param screenshotDir - default directory for relative paths.
|
|
75
|
+
* @returns the absolute container path.
|
|
76
|
+
*/
|
|
77
|
+
export function resolveContainerPath(path: string, screenshotDir: string): string {
|
|
78
|
+
if (path.startsWith('/')) return path
|
|
79
|
+
return `${screenshotDir.replace(/\/$/, '')}/${path}`
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** One prepared image projection: stored ref + fallback content + value. */
|
|
83
|
+
interface ImageProjection {
|
|
84
|
+
readonly value: unknown
|
|
85
|
+
readonly fallback: readonly ContentBlock[]
|
|
86
|
+
readonly content: readonly ContentBlock[]
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function apply(ctx: Context, config: Config = {}): void {
|
|
90
|
+
const admittedPerScan = new Map<string, number>()
|
|
91
|
+
const projections = new WeakMap<ToolExecution, ImageProjection>()
|
|
92
|
+
|
|
93
|
+
const session = () => ctx.pentestSandbox.createSession({ scanId: config.scanId ?? 'pentest' })
|
|
94
|
+
const screenshotDir = config.screenshotDir ?? '/workspace/.agent-browser-screenshots'
|
|
95
|
+
const maxImageBytes = config.maxImageBytes ?? 5_242_880
|
|
96
|
+
const maxContextImages = config.maxContextImages ?? 3
|
|
97
|
+
const workspaceRoot = config.workspaceRoot ?? '/workspace'
|
|
98
|
+
|
|
99
|
+
ctx.tools.register(defineTool({
|
|
100
|
+
name: 'view_image',
|
|
101
|
+
description: `Load an image from the sandbox filesystem and return it visually (for screenshots taken with the agent-browser CLI via exec_command). Paths resolve inside ${workspaceRoot}; bare filenames land in ${screenshotDir}.`,
|
|
102
|
+
parameters: {
|
|
103
|
+
path: { type: 'string', required: true, description: `Image path inside ${workspaceRoot}, or a bare filename inside ${screenshotDir}.` },
|
|
104
|
+
},
|
|
105
|
+
output: {
|
|
106
|
+
schema: {
|
|
107
|
+
type: 'object',
|
|
108
|
+
properties: {
|
|
109
|
+
path: { type: 'string', required: true },
|
|
110
|
+
media_type: { type: 'string', required: true },
|
|
111
|
+
size_bytes: { type: 'integer', required: true },
|
|
112
|
+
data_base64: { type: 'string', required: true },
|
|
113
|
+
},
|
|
114
|
+
additionalProperties: false,
|
|
115
|
+
},
|
|
116
|
+
render: (_args, value) => {
|
|
117
|
+
const image = value as { path: string; media_type: string; size_bytes: number }
|
|
118
|
+
return [{ type: 'text', text: `[image ${image.path} — ${image.media_type}, ${String(image.size_bytes)} bytes]` }]
|
|
119
|
+
},
|
|
120
|
+
},
|
|
121
|
+
presentResult: (_args, result) => ({
|
|
122
|
+
card: 'generic',
|
|
123
|
+
content: result.content.filter(block => block.type === 'text').map(block => block.text).map(text => ({ type: 'text' as const, text })),
|
|
124
|
+
}),
|
|
125
|
+
execute: async (args, exec) => {
|
|
126
|
+
const containerPath = resolveContainerPath(args.path, screenshotDir)
|
|
127
|
+
if (!containerPath.startsWith(`${workspaceRoot}/`)) {
|
|
128
|
+
throw new Error(`view_image: path must be inside ${workspaceRoot}. Got: '${args.path}'.`)
|
|
129
|
+
}
|
|
130
|
+
const scanKey = exec.agent?.session.id ?? (config.scanId ?? 'pentest')
|
|
131
|
+
const admitted = admittedPerScan.get(scanKey) ?? 0
|
|
132
|
+
if (admitted >= maxContextImages) {
|
|
133
|
+
throw new Error(`view_image: the per-scan image budget is exhausted (maxContextImages=${String(maxContextImages)}); reuse earlier screenshots or start a new scan session.`)
|
|
134
|
+
}
|
|
135
|
+
const bytes = await (await session()).getFile(containerPath)
|
|
136
|
+
if (bytes.byteLength === 0) throw new Error(`view_image: ${containerPath} is empty`)
|
|
137
|
+
if (bytes.byteLength > maxImageBytes) throw new Error(`view_image: ${containerPath} is ${String(bytes.byteLength)} bytes, over the ${String(maxImageBytes)} limit`)
|
|
138
|
+
const mediaType = detectImageMediaType(bytes)
|
|
139
|
+
if (mediaType === null) throw new Error(`view_image: ${containerPath} is not a PNG/JPEG/WebP/GIF image`)
|
|
140
|
+
const value = {
|
|
141
|
+
path: containerPath,
|
|
142
|
+
media_type: mediaType,
|
|
143
|
+
size_bytes: bytes.byteLength,
|
|
144
|
+
data_base64: Buffer.from(bytes).toString('base64'),
|
|
145
|
+
}
|
|
146
|
+
const fallback: ContentBlock[] = [{
|
|
147
|
+
type: 'text',
|
|
148
|
+
text: `[image ${containerPath} — ${mediaType}, ${String(bytes.byteLength)} bytes]`,
|
|
149
|
+
}]
|
|
150
|
+
const projection = await prepareProjection(ctx, exec, { data: bytes, mediaType, name: containerPath }, value, fallback)
|
|
151
|
+
projections.set(exec, projection)
|
|
152
|
+
// Count the admission only when the image actually entered the model
|
|
153
|
+
// surface (a diagnostic-degraded projection consumed no image budget).
|
|
154
|
+
if (projection.content.some(block => block.type === 'image')) {
|
|
155
|
+
admittedPerScan.set(scanKey, admitted + 1)
|
|
156
|
+
}
|
|
157
|
+
return value
|
|
158
|
+
},
|
|
159
|
+
finalizeContent(exec: Readonly<ToolExecution>, result: Readonly<ToolExecutionResult>) {
|
|
160
|
+
const projection = projections.get(exec)
|
|
161
|
+
if (projection === undefined) return undefined
|
|
162
|
+
projections.delete(exec)
|
|
163
|
+
if (result.isError) return undefined
|
|
164
|
+
return projection.content as ContentBlock[]
|
|
165
|
+
},
|
|
166
|
+
}))
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Prove the routed model accepts image input, durably store the bytes, and
|
|
171
|
+
* build the final content (image block on success, diagnostic otherwise).
|
|
172
|
+
* Admission mirrors mcp-client: store → route → capability → save.
|
|
173
|
+
*/
|
|
174
|
+
async function prepareProjection(
|
|
175
|
+
ctx: Context,
|
|
176
|
+
exec: ToolExecution,
|
|
177
|
+
input: SaveImageAttachment,
|
|
178
|
+
value: unknown,
|
|
179
|
+
fallback: readonly ContentBlock[],
|
|
180
|
+
): Promise<ImageProjection> {
|
|
181
|
+
const diagnostic = (reason: string): ImageProjection => ({
|
|
182
|
+
value,
|
|
183
|
+
fallback,
|
|
184
|
+
content: [{ type: 'text', text: `[image unavailable: ${input.name ?? 'unknown'}; ${reason}; the raw base64 remains in the tool result]` }],
|
|
185
|
+
})
|
|
186
|
+
let attachments: AttachmentStore | undefined
|
|
187
|
+
try {
|
|
188
|
+
attachments = await resolveAttachmentStore(ctx, exec)
|
|
189
|
+
} catch (error) {
|
|
190
|
+
return diagnostic(String(error instanceof Error ? error.message : error))
|
|
191
|
+
}
|
|
192
|
+
try {
|
|
193
|
+
const refs = await attachments.saveImages([input])
|
|
194
|
+
const attachment = refs[0]
|
|
195
|
+
if (attachment === undefined) return diagnostic('the attachment store returned no reference')
|
|
196
|
+
return { value, fallback, content: [{ type: 'image', attachment }] }
|
|
197
|
+
} catch (error) {
|
|
198
|
+
return diagnostic(String(error instanceof Error ? error.message : error))
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** Resolve the attachment store after an exact model image-input proof. */
|
|
203
|
+
async function resolveAttachmentStore(ctx: Context, exec: ToolExecution): Promise<AttachmentStore> {
|
|
204
|
+
const attachments = ctx.get('attachments')
|
|
205
|
+
if (attachments === undefined) throw new Error('no attachment store is mounted')
|
|
206
|
+
const routed = exec.agent?.session.requestHeader()?.config
|
|
207
|
+
const provider = routed?.provider ?? exec.agent?.options.provider
|
|
208
|
+
const model = routed?.model ?? exec.agent?.options.model
|
|
209
|
+
const llm = ctx.get('llm')
|
|
210
|
+
if (provider === undefined || model === undefined || llm === undefined) {
|
|
211
|
+
throw new Error('the current model route could not be resolved')
|
|
212
|
+
}
|
|
213
|
+
let info: { readonly inputModalities?: readonly string[] }
|
|
214
|
+
try {
|
|
215
|
+
info = await llm.resolveModelInfo(provider, model, exec.signal)
|
|
216
|
+
} catch {
|
|
217
|
+
throw new Error('the current model route could not be verified')
|
|
218
|
+
}
|
|
219
|
+
if (info.inputModalities === undefined || !info.inputModalities.includes('image')) {
|
|
220
|
+
throw new Error(`model "${model}" does not declare image input`)
|
|
221
|
+
}
|
|
222
|
+
if (exec.signal.aborted) throw new Error('the tool call was canceled before image storage')
|
|
223
|
+
return attachments
|
|
224
|
+
}
|