@gpzhang2001/sharpkit-shell 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 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,29 @@
1
+ # @gpzhang2001/sharpkit-shell
2
+
3
+ `exec_command` / `write_stdin`:沙箱内命令执行与 PTY 交互(对齐原版 Shell 工具语义)。
4
+
5
+ ## 工具
6
+
7
+ **exec_command**(`inject: ['tools', 'pentestSandbox']`)
8
+ - `cmd` 必填;`cwd` 必须在 workspace 内(strix 精确错误文案);`tty`、`timeout_ms`(钳制到 `[1, maxTimeoutMs]`)、`run_in_background`(Config 门控)
9
+ - 默认路径:fresh 非交互 `bash -lc`,超时竞速终止,尊重 `exec.signal`(协作式取消)
10
+ - `tty=true`:启动 PTY 返回 `process_id`,交给 `write_stdin` 驱动(Ctrl-C 写 `\x03`)
11
+ - `run_in_background=true`:`ctx.jobs.start`(kind `pentest-exec`,JobKindMap 扩展),readOutput 增量、cancel→terminate 且 done 映射 `killed`;免费获得 `job_output`/`job_list`/`job_kill`
12
+
13
+ **write_stdin**
14
+ - 仅对运行中的 PTY 进程有效;未知/已退出 → strix 精确错误文案
15
+ - `chars=""` 非阻塞轮询新输出;转义解码(`\n \t \r \0 \a \b \v \f \\`、`\xNN`、`\uXXXX`)逐字移植 `_decode_chars_escape`
16
+
17
+ ## 横切
18
+
19
+ - **审批门**:`tools/pre-execute` 对 `exec_command` 返回 `ask`(Config `requireApproval` 默认 true;无审批服务的组合会 fail-closed 拒绝)
20
+ - 会话:`ctx.pentestSandbox.createSession({scanId})` create_or_reuse——编排方用真实 scanId 预建会话即可共享
21
+
22
+ ## Config
23
+
24
+ `scanId`(默认 `pentest`)、`sources`、`requireApproval`、`enableRunInBackground`、`defaultTimeoutMs`(120s)、`maxTimeoutMs`(600s,工具声明 deadline)、`workspaceRoot`。
25
+
26
+ ## 测试
27
+
28
+ - `tests/shell.test.ts`:纯函数(转义/workdir/钳制)+ fake sandbox 全路径(含审批 ask 决策)
29
+ - `tests/integration.test.ts`:真实 sandbox + 真实 jobs(docker 门控):前台/PTY/后台 job 增量输出与 kill
@@ -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,81 @@
1
+ import z from "@deepseek-ai/schemastery";
2
+ import { Context } from "@deepseek-ai/cordis";
3
+ //#region src/index.d.ts
4
+ var [STDIN_UNAVAILABLE] = [
5
+ 0,
6
+ () => [],
7
+ []
8
+ ];
9
+ var [ConfigSource] = [
10
+ 1,
11
+ () => [],
12
+ [
13
+ "",
14
+ "",
15
+ ""
16
+ ]
17
+ ];
18
+ var [Config] = [
19
+ 2,
20
+ () => [ConfigSource],
21
+ [
22
+ "",
23
+ "",
24
+ "",
25
+ "",
26
+ "",
27
+ "",
28
+ "",
29
+ "",
30
+ ""
31
+ ]
32
+ ];
33
+ var [_0] = [
34
+ 3,
35
+ () => [],
36
+ ["", ""],
37
+ sideEffect(_0)
38
+ ];
39
+ var [name] = [
40
+ 4,
41
+ () => [],
42
+ []
43
+ ];
44
+ var [inject] = [
45
+ 5,
46
+ () => [],
47
+ []
48
+ ];
49
+ var [Config] = [
50
+ 6,
51
+ () => [Config, z],
52
+ ["", ""]
53
+ ];
54
+ var [workdirError] = [
55
+ 7,
56
+ () => [],
57
+ ["", ""]
58
+ ];
59
+ var [clampTimeout] = [
60
+ 8,
61
+ () => [],
62
+ [
63
+ "",
64
+ "",
65
+ ""
66
+ ]
67
+ ];
68
+ var [apply] = [
69
+ 9,
70
+ () => [Context, Config],
71
+ [
72
+ "",
73
+ "",
74
+ "",
75
+ ""
76
+ ]
77
+ ];
78
+ //#endregion
79
+ export { Config, ConfigSource, STDIN_UNAVAILABLE, apply, clampTimeout, inject, name, workdirError };
80
+
81
+ //# sourceMappingURL=index.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.ts","names":["Schema"],"sources":["../src/index.d.ts"],"sourcesContent":["/**\n * `exec_command` / `write_stdin` model-facing shell tools over the pentest\n * sandbox — strix SDK ShellTool semantics (tools/shell/README.md + factory\n * wrapping): a fresh non-interactive login shell per call by default, PTY\n * processes for interactive work driven by `write_stdin` (chars=\"\" polls),\n * workdir restricted to the workspace, per-call timeout clamped by config,\n * and `run_in_background` mapped onto the dsh jobs runtime\n * (job_output/job_list/job_kill come free). Every exec passes an ask\n * approval gate (config-gated; the registry resolves `ask` through the\n * host's approval service and fails closed when none is composed).\n * @module @gpzhang2001/sharpkit-shell\n */\nimport type { Context } from '@deepseek-ai/cordis';\nimport type Schema from '@deepseek-ai/schemastery';\n/** strix's exact refusal text for write_stdin against a non-PTY process. */\nexport declare const STDIN_UNAVAILABLE = \"stdin is not available for this process. Start the command with 'tty=true' in 'exec_command' before using 'write_stdin'.\";\n/** One source tree Config entry (mutable twin of the sandbox spec for schemastery). */\nexport interface ConfigSource {\n workspaceSubdir: string;\n sourcePath: string;\n protectMetadata?: boolean;\n}\n/** Deployment-tunable configuration. */\nexport interface Config {\n /** Sandbox session cache key; the orchestrator pre-creates the real session under this id. */\n readonly scanId?: string;\n /** Source trees for the session this tool creates when none exists yet. */\n readonly sources?: ConfigSource[];\n /** Ask-approval gate on every exec_command (fail-closed without an approval service). */\n readonly requireApproval?: boolean;\n /** Expose run_in_background (needs a jobs provider at runtime). */\n readonly enableRunInBackground?: boolean;\n /** Default per-call timeout; model values are clamped into [1, maxTimeoutMs]. */\n readonly defaultTimeoutMs?: number;\n /** Hard ceiling for the model's timeout_ms and the tool's own deadline. */\n readonly maxTimeoutMs?: number;\n /** Container workspace root (workdir validation). */\n readonly workspaceRoot?: string;\n /** Unpolled PTY output ceiling in bytes (approx; the tail is kept). */\n readonly maxTtyBufferBytes?: number;\n}\ndeclare module '@deepseek-ai/dsh-jobs' {\n interface JobKindMap {\n 'pentest-exec': 'pentest-exec';\n }\n}\nexport declare const name = \"pentest-tool-shell\";\nexport declare const inject: string[];\nexport declare const Config: Schema<Config>;\n/**\n * Validate a workdir against the workspace root (strix workdir contract),\n * segment by segment: no absolute escape, no `..`/`.`/empty segments, no\n * trailing slash.\n * @param cwd - the requested working directory.\n * @param workspaceRoot - container workspace root.\n * @returns null when valid, else strix's exact error text.\n */\nexport declare function workdirError(cwd: string | undefined, workspaceRoot: string): string | null;\n/** Clamp a requested timeout into the configured window. */\nexport declare function clampTimeout(requested: number | undefined, defaultTimeoutMs: number, maxTimeoutMs: number): number;\nexport declare function apply(ctx: Context, config?: Config): void;\n"],"mappings":";;;AAEA,IAAW,CAAC,qBAAqB;CAAC;OAAS,CAAC;CAAG,CAAC;AAAC;AACjD,IAAW,CAAC,gBAAgB;CAAC;OAAS,CAAC;CAAG;EAAC;EAAI;EAAI;CAAE;AAAC;AACtD,IAAW,CAAC,UAAU;CAAC;OAAS,CAAC,YAAY;CAAG;EAAC;EAAI;EAAI;EAAI;EAAI;EAAI;EAAI;EAAI;EAAI;CAAE;AAAC;AACpF,IAAI,CAAC,MAAM;CAAC;OAAS,CAAC;CAAG,CAAC,IAAI,EAAE;CAAG,WAAW,EAAE;AAAC;AACjD,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,gBAAgB;CAAC;OAAS,CAAC;CAAG,CAAC,IAAI,EAAE;AAAC;AAClD,IAAW,CAAC,gBAAgB;CAAC;OAAS,CAAC;CAAG;EAAC;EAAI;EAAI;CAAE;AAAC;AACtD,IAAW,CAAC,SAAS;CAAC;OAAS,CAAC,SAAS,MAAM;CAAG;EAAC;EAAI;EAAI;EAAI;CAAE;AAAC"}
package/lib/index.js ADDED
@@ -0,0 +1,308 @@
1
+ import z from "@deepseek-ai/schemastery";
2
+ import { defineTool } from "@deepseek-ai/dsh-tools";
3
+ //#region src/chars.ts
4
+ /**
5
+ * Escape decoding for `write_stdin` chars, ported verbatim from strix
6
+ * factory.py `_decode_chars_escape` (\\uXXXX, \\xNN, and the C-style short
7
+ * escapes; unknown escapes and backslash-free strings pass through).
8
+ * @module @gpzhang2001/sharpkit-shell/chars
9
+ */
10
+ const ESCAPE_RE = /\\(?:u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|[0abtnvfr\\])/g;
11
+ const SHORT_ESCAPES = {
12
+ "\\\\": "\\",
13
+ "\\n": "\n",
14
+ "\\t": " ",
15
+ "\\r": "\r",
16
+ "\\0": "\0",
17
+ "\\a": "\x07",
18
+ "\\b": "\b",
19
+ "\\v": "\v",
20
+ "\\f": "\f"
21
+ };
22
+ /**
23
+ * Decode the model-facing escape forms in a `chars` argument.
24
+ * @param chars - the raw argument value.
25
+ * @returns the decoded characters to deliver to the process.
26
+ */
27
+ function decodeCharsEscape(chars) {
28
+ if (!chars.includes("\\")) return chars;
29
+ return chars.replace(ESCAPE_RE, (token) => {
30
+ const short = SHORT_ESCAPES[token];
31
+ if (short !== void 0) return short;
32
+ return String.fromCodePoint(Number.parseInt(token.slice(2), 16));
33
+ });
34
+ }
35
+ //#endregion
36
+ //#region src/index.ts
37
+ /** strix's exact refusal text for write_stdin against a non-PTY process. */
38
+ const STDIN_UNAVAILABLE = "stdin is not available for this process. Start the command with 'tty=true' in 'exec_command' before using 'write_stdin'.";
39
+ const name = "pentest-tool-shell";
40
+ const inject = ["tools", "pentestSandbox"];
41
+ const Config = z.object({
42
+ scanId: z.string().default("pentest"),
43
+ sources: z.array(z.object({
44
+ workspaceSubdir: z.string(),
45
+ sourcePath: z.string(),
46
+ protectMetadata: z.boolean()
47
+ })),
48
+ requireApproval: z.boolean().default(true),
49
+ enableRunInBackground: z.boolean().default(true),
50
+ defaultTimeoutMs: z.number().default(12e4),
51
+ maxTimeoutMs: z.number().default(6e5),
52
+ workspaceRoot: z.string().default("/workspace"),
53
+ maxTtyBufferBytes: z.number().default(1048576)
54
+ });
55
+ /**
56
+ * Validate a workdir against the workspace root (strix workdir contract),
57
+ * segment by segment: no absolute escape, no `..`/`.`/empty segments, no
58
+ * trailing slash.
59
+ * @param cwd - the requested working directory.
60
+ * @param workspaceRoot - container workspace root.
61
+ * @returns null when valid, else strix's exact error text.
62
+ */
63
+ function workdirError(cwd, workspaceRoot) {
64
+ if (cwd === void 0) return null;
65
+ if (cwd === workspaceRoot) return null;
66
+ const prefix = `${workspaceRoot}/`;
67
+ return cwd.startsWith(prefix) && cwd.slice(prefix.length).split("/").every((segment) => segment !== "" && segment !== "." && segment !== "..") ? null : `exec_command: workdir must be a path inside ${workspaceRoot} (or omitted to use the turn's cwd). Got: '${cwd}'.`;
68
+ }
69
+ /** Clamp a requested timeout into the configured window. */
70
+ function clampTimeout(requested, defaultTimeoutMs, maxTimeoutMs) {
71
+ return Math.min(Math.max(1, requested ?? defaultTimeoutMs), maxTimeoutMs);
72
+ }
73
+ function apply(ctx, config = {}) {
74
+ const ttyProcesses = /* @__PURE__ */ new Map();
75
+ const session = () => ctx.pentestSandbox.createSession({
76
+ scanId: config.scanId ?? "pentest",
77
+ ...config.sources !== void 0 ? { sources: config.sources.map((source) => ({
78
+ workspaceSubdir: source.workspaceSubdir,
79
+ sourcePath: source.sourcePath,
80
+ ...source.protectMetadata !== void 0 ? { protectMetadata: source.protectMetadata } : {}
81
+ })) } : {}
82
+ });
83
+ if (config.requireApproval !== false) ctx.on("tools/pre-execute", async (exec, next) => {
84
+ if (exec.name === "exec_command") return {
85
+ kind: "ask",
86
+ reason: "pentest: run a command inside the attack sandbox"
87
+ };
88
+ return next();
89
+ });
90
+ const workspaceRoot = config.workspaceRoot ?? "/workspace";
91
+ const defaultTimeoutMs = config.defaultTimeoutMs ?? 12e4;
92
+ const maxTimeoutMs = config.maxTimeoutMs ?? 6e5;
93
+ const maxTtyBufferBytes = config.maxTtyBufferBytes ?? 1048576;
94
+ const backgroundEnabled = config.enableRunInBackground !== false;
95
+ ctx.tools.register(defineTool({
96
+ name: "exec_command",
97
+ description: `Run a shell command inside the pentest sandbox (Kali container) in a fresh non-interactive bash login shell. Set tty=true for interactive programs (REPLs, ssh, msfconsole) and then drive them with write_stdin; run_in_background starts a job for long scans and returns a job id for job_output/job_kill.${backgroundEnabled ? "" : " (run_in_background is disabled in this deployment.)"}`,
98
+ parameters: {
99
+ cmd: {
100
+ type: "string",
101
+ required: true,
102
+ description: "The shell command line to execute."
103
+ },
104
+ ...backgroundEnabled ? { run_in_background: {
105
+ type: "boolean",
106
+ description: "Start as a background job; returns a job id (long scans)."
107
+ } } : {},
108
+ cwd: {
109
+ type: "string",
110
+ description: `Working directory inside ${workspaceRoot}.`
111
+ },
112
+ timeout_ms: {
113
+ type: "integer",
114
+ description: "Per-call timeout in milliseconds (clamped by deployment)."
115
+ },
116
+ tty: {
117
+ type: "boolean",
118
+ description: "Run under a PTY for interactive input via write_stdin."
119
+ }
120
+ },
121
+ output: {
122
+ schema: {
123
+ type: "object",
124
+ properties: {
125
+ kind: {
126
+ type: "string",
127
+ required: true,
128
+ enum: [
129
+ "foreground",
130
+ "tty",
131
+ "background"
132
+ ]
133
+ },
134
+ exit_code: { type: "integer" },
135
+ signal: { type: "string" },
136
+ timed_out: { type: "boolean" },
137
+ stdout: { type: "string" },
138
+ stderr: { type: "string" },
139
+ process_id: { type: "string" },
140
+ job_id: { type: "string" }
141
+ },
142
+ additionalProperties: false
143
+ },
144
+ render: (_args, value) => {
145
+ if (value.kind === "foreground") return [{
146
+ type: "text",
147
+ text: `exit_code=${value.exit_code === null ? "none" : String(value.exit_code)}${value.timed_out === true ? " (timed out)" : ""}\nstdout:\n${value.stdout}\nstderr:\n${value.stderr}`
148
+ }];
149
+ if (value.kind === "tty") return [{
150
+ type: "text",
151
+ text: `PTY process ${value.process_id} started. Poll with write_stdin(process_id="${value.process_id}", chars=""); send input via chars; deliver Ctrl-C with chars="\\x03".`
152
+ }];
153
+ return [{
154
+ type: "text",
155
+ text: `started background job ${value.job_id} (job_output to read, job_kill to stop)`
156
+ }];
157
+ }
158
+ },
159
+ timeoutMs: maxTimeoutMs,
160
+ presentCall: (args) => ({
161
+ card: "terminal",
162
+ title: String(args.cmd ?? "")
163
+ }),
164
+ presentResult: (args, result) => {
165
+ const text = result.content.filter((block) => block.type === "text").map((block) => block.text).join("\n");
166
+ return {
167
+ card: "terminal",
168
+ output: text === "" ? String(args.cmd ?? "") : text
169
+ };
170
+ },
171
+ execute: async (args, exec) => {
172
+ const cwdProblem = workdirError(args.cwd, workspaceRoot);
173
+ if (cwdProblem !== null) throw new Error(cwdProblem);
174
+ if (args.tty === true && args.run_in_background === true) throw new Error("exec_command: tty=true and run_in_background cannot be combined — start a PTY process and drive it with write_stdin, or start a background job without a PTY.");
175
+ if (args.run_in_background === true && !backgroundEnabled) throw new Error("run_in_background is disabled for this deployment (enableRunInBackground: false)");
176
+ const sandbox = await session();
177
+ if (args.tty === true) {
178
+ const process = await sandbox.execTty(args.cmd, { cwd: args.cwd });
179
+ const tracked = {
180
+ process,
181
+ buffer: "",
182
+ cursor: 0,
183
+ settled: void 0
184
+ };
185
+ process.subscribe((chunk) => {
186
+ tracked.buffer += chunk;
187
+ if (tracked.buffer.length > maxTtyBufferBytes) {
188
+ const excess = tracked.buffer.length - maxTtyBufferBytes;
189
+ tracked.buffer = tracked.buffer.slice(excess);
190
+ tracked.cursor = Math.max(0, tracked.cursor - excess);
191
+ }
192
+ });
193
+ process.done.then((outcome) => {
194
+ tracked.settled = {
195
+ exitCode: outcome.exitCode,
196
+ signal: outcome.signal
197
+ };
198
+ }, () => {
199
+ tracked.settled = {
200
+ exitCode: null,
201
+ signal: null
202
+ };
203
+ });
204
+ ttyProcesses.set(process.id, tracked);
205
+ return {
206
+ kind: "tty",
207
+ process_id: process.id
208
+ };
209
+ }
210
+ if (args.run_in_background === true) {
211
+ const jobs = ctx.get("jobs");
212
+ if (jobs === void 0) throw new Error("run_in_background needs a jobs provider (load @deepseek-ai/dsh-jobs-local)");
213
+ const job = sandbox.execJob(args.cmd, { cwd: args.cwd });
214
+ let cancelled = false;
215
+ return {
216
+ kind: "background",
217
+ job_id: jobs.start({
218
+ kind: "pentest-exec",
219
+ label: args.cmd,
220
+ ...exec.agent !== void 0 ? { owner: exec.agent } : {},
221
+ run: () => ({
222
+ cancel: () => {
223
+ cancelled = true;
224
+ job.terminate();
225
+ },
226
+ done: job.done.then((outcome) => cancelled ? {
227
+ status: "killed",
228
+ detail: "cancelled by request"
229
+ } : {
230
+ status: outcome.exitCode === 0 ? "completed" : "failed",
231
+ detail: `exit code: ${outcome.exitCode === null ? "none" : String(outcome.exitCode)}`
232
+ }),
233
+ readOutput: () => job.readOutput()
234
+ })
235
+ })
236
+ };
237
+ }
238
+ const result = await sandbox.exec(args.cmd, {
239
+ cwd: args.cwd,
240
+ timeoutMs: clampTimeout(args.timeout_ms, defaultTimeoutMs, maxTimeoutMs),
241
+ signal: exec.signal
242
+ });
243
+ return {
244
+ kind: "foreground",
245
+ ...result.exitCode !== null ? { exit_code: result.exitCode } : {},
246
+ ...result.signal !== null ? { signal: result.signal } : {},
247
+ timed_out: result.timedOut,
248
+ stdout: result.stdout,
249
+ stderr: result.stderr
250
+ };
251
+ }
252
+ }));
253
+ ctx.tools.register(defineTool({
254
+ name: "write_stdin",
255
+ description: "Send characters to a PTY-backed process started by exec_command(tty=true). chars=\"\" polls for new output without sending anything. Escapes (\\n, \\t, \\x03 for Ctrl-C, \\uXXXX) are decoded.",
256
+ parameters: {
257
+ process_id: {
258
+ type: "string",
259
+ required: true,
260
+ description: "The process id returned by exec_command(tty=true)."
261
+ },
262
+ chars: {
263
+ type: "string",
264
+ required: true,
265
+ description: "Characters to write (\"\" to poll for output only)."
266
+ }
267
+ },
268
+ output: {
269
+ schema: {
270
+ type: "object",
271
+ properties: {
272
+ output: {
273
+ type: "string",
274
+ required: true
275
+ },
276
+ running: {
277
+ type: "boolean",
278
+ required: true
279
+ },
280
+ exit_code: { type: "integer" }
281
+ },
282
+ additionalProperties: false
283
+ },
284
+ render: (_args, value) => [{
285
+ type: "text",
286
+ text: `${value.running ? "(running)" : `(exited${value.exit_code === void 0 ? "" : ` exit_code=${String(value.exit_code)}`})`}\n${value.output}`
287
+ }]
288
+ },
289
+ execute: async (args) => {
290
+ const tracked = ttyProcesses.get(args.process_id);
291
+ if (tracked === void 0) throw new Error(STDIN_UNAVAILABLE);
292
+ const chars = decodeCharsEscape(args.chars);
293
+ if (chars !== "") await tracked.process.write(chars);
294
+ const delta = tracked.buffer.slice(tracked.cursor);
295
+ tracked.cursor = tracked.buffer.length;
296
+ if (tracked.settled !== void 0) ttyProcesses.delete(args.process_id);
297
+ return {
298
+ output: delta,
299
+ running: tracked.settled === void 0,
300
+ ...tracked.settled !== void 0 && tracked.settled.exitCode !== null ? { exit_code: tracked.settled.exitCode } : {}
301
+ };
302
+ }
303
+ }));
304
+ }
305
+ //#endregion
306
+ export { Config, STDIN_UNAVAILABLE, apply, clampTimeout, inject, name, workdirError };
307
+
308
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/chars.ts","../src/index.ts"],"sourcesContent":["/**\n * Escape decoding for `write_stdin` chars, ported verbatim from strix\n * factory.py `_decode_chars_escape` (\\\\uXXXX, \\\\xNN, and the C-style short\n * escapes; unknown escapes and backslash-free strings pass through).\n * @module @gpzhang2001/sharpkit-shell/chars\n */\n\nconst ESCAPE_RE = /\\\\(?:u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|[0abtnvfr\\\\])/g\n\nconst SHORT_ESCAPES: Record<string, string> = {\n '\\\\\\\\': '\\\\',\n '\\\\n': '\\n',\n '\\\\t': '\\t',\n '\\\\r': '\\r',\n '\\\\0': '\\x00',\n '\\\\a': '\\x07',\n '\\\\b': '\\x08',\n '\\\\v': '\\x0b',\n '\\\\f': '\\x0c',\n}\n\n/**\n * Decode the model-facing escape forms in a `chars` argument.\n * @param chars - the raw argument value.\n * @returns the decoded characters to deliver to the process.\n */\nexport function decodeCharsEscape(chars: string): string {\n if (!chars.includes('\\\\')) return chars\n return chars.replace(ESCAPE_RE, token => {\n const short = SHORT_ESCAPES[token]\n if (short !== undefined) return short\n return String.fromCodePoint(Number.parseInt(token.slice(2), 16))\n })\n}\n","/**\n * `exec_command` / `write_stdin` model-facing shell tools over the pentest\n * sandbox — strix SDK ShellTool semantics (tools/shell/README.md + factory\n * wrapping): a fresh non-interactive login shell per call by default, PTY\n * processes for interactive work driven by `write_stdin` (chars=\"\" polls),\n * workdir restricted to the workspace, per-call timeout clamped by config,\n * and `run_in_background` mapped onto the dsh jobs runtime\n * (job_output/job_list/job_kill come free). Every exec passes an ask\n * approval gate (config-gated; the registry resolves `ask` through the\n * host's approval service and fails closed when none is composed).\n * @module @gpzhang2001/sharpkit-shell\n */\n\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 { SandboxTtyProcess } from '@gpzhang2001/sharpkit-sandbox'\nimport { decodeCharsEscape } from './chars.ts'\n\n/** strix's exact refusal text for write_stdin against a non-PTY process. */\nexport const STDIN_UNAVAILABLE = \"stdin is not available for this process. Start the command with 'tty=true' in 'exec_command' before using 'write_stdin'.\"\n\n/** One source tree Config entry (mutable twin of the sandbox spec for schemastery). */\nexport interface ConfigSource {\n workspaceSubdir: string\n sourcePath: string\n protectMetadata?: boolean\n}\n\n/** Deployment-tunable configuration. */\nexport interface Config {\n /** Sandbox session cache key; the orchestrator pre-creates the real session under this id. */\n readonly scanId?: string\n /** Source trees for the session this tool creates when none exists yet. */\n readonly sources?: ConfigSource[]\n /** Ask-approval gate on every exec_command (fail-closed without an approval service). */\n readonly requireApproval?: boolean\n /** Expose run_in_background (needs a jobs provider at runtime). */\n readonly enableRunInBackground?: boolean\n /** Default per-call timeout; model values are clamped into [1, maxTimeoutMs]. */\n readonly defaultTimeoutMs?: number\n /** Hard ceiling for the model's timeout_ms and the tool's own deadline. */\n readonly maxTimeoutMs?: number\n /** Container workspace root (workdir validation). */\n readonly workspaceRoot?: string\n /** Unpolled PTY output ceiling in bytes (approx; the tail is kept). */\n readonly maxTtyBufferBytes?: number\n}\n\nimport type {} from '@deepseek-ai/dsh-jobs'\n\ndeclare module '@deepseek-ai/dsh-jobs' {\n interface JobKindMap {\n 'pentest-exec': 'pentest-exec'\n }\n}\n\n/** One tracked PTY process with a read cursor for polling. */\ninterface TrackedTty {\n readonly process: SandboxTtyProcess\n buffer: string\n cursor: number\n settled: { exitCode: number | null; signal: string | null } | undefined\n}\n\nexport const name = 'pentest-tool-shell'\n\nexport const inject = ['tools', 'pentestSandbox']\n\nexport const Config: Schema<Config> = z.object({\n scanId: z.string().default('pentest'),\n sources: z.array(z.object({\n workspaceSubdir: z.string(),\n sourcePath: z.string(),\n protectMetadata: z.boolean(),\n })),\n requireApproval: z.boolean().default(true),\n enableRunInBackground: z.boolean().default(true),\n defaultTimeoutMs: z.number().default(120_000),\n maxTimeoutMs: z.number().default(600_000),\n workspaceRoot: z.string().default('/workspace'),\n maxTtyBufferBytes: z.number().default(1_048_576),\n})\n\n/**\n * Validate a workdir against the workspace root (strix workdir contract),\n * segment by segment: no absolute escape, no `..`/`.`/empty segments, no\n * trailing slash.\n * @param cwd - the requested working directory.\n * @param workspaceRoot - container workspace root.\n * @returns null when valid, else strix's exact error text.\n */\nexport function workdirError(cwd: string | undefined, workspaceRoot: string): string | null {\n if (cwd === undefined) return null\n if (cwd === workspaceRoot) return null\n const prefix = `${workspaceRoot}/`\n const inside = cwd.startsWith(prefix)\n && cwd.slice(prefix.length).split('/').every(segment => segment !== '' && segment !== '.' && segment !== '..')\n return inside ? null : `exec_command: workdir must be a path inside ${workspaceRoot} (or omitted to use the turn's cwd). Got: '${cwd}'.`\n}\n\n/** Clamp a requested timeout into the configured window. */\nexport function clampTimeout(requested: number | undefined, defaultTimeoutMs: number, maxTimeoutMs: number): number {\n const value = requested ?? defaultTimeoutMs\n return Math.min(Math.max(1, value), maxTimeoutMs)\n}\n\nexport function apply(ctx: Context, config: Config = {}): void {\n const ttyProcesses = new Map<string, TrackedTty>()\n\n const session = () =>\n ctx.pentestSandbox.createSession({\n scanId: config.scanId ?? 'pentest',\n ...(config.sources !== undefined ? { sources: config.sources.map(source => ({\n workspaceSubdir: source.workspaceSubdir,\n sourcePath: source.sourcePath,\n ...(source.protectMetadata !== undefined ? { protectMetadata: source.protectMetadata } : {}),\n })) } : {}),\n })\n\n if (config.requireApproval !== false) {\n void ctx.on('tools/pre-execute', async (exec, next) => {\n if (exec.name === 'exec_command') return { kind: 'ask' as const, reason: 'pentest: run a command inside the attack sandbox' }\n return next()\n })\n }\n\n const workspaceRoot = config.workspaceRoot ?? '/workspace'\n const defaultTimeoutMs = config.defaultTimeoutMs ?? 120_000\n const maxTimeoutMs = config.maxTimeoutMs ?? 600_000\n const maxTtyBufferBytes = config.maxTtyBufferBytes ?? 1_048_576\n const backgroundEnabled = config.enableRunInBackground !== false\n\n ctx.tools.register(defineTool({\n name: 'exec_command',\n description: `Run a shell command inside the pentest sandbox (Kali container) in a fresh non-interactive bash login shell. Set tty=true for interactive programs (REPLs, ssh, msfconsole) and then drive them with write_stdin; run_in_background starts a job for long scans and returns a job id for job_output/job_kill.${backgroundEnabled ? '' : ' (run_in_background is disabled in this deployment.)'}`,\n parameters: {\n cmd: { type: 'string', required: true, description: 'The shell command line to execute.' },\n ...(backgroundEnabled ? { run_in_background: { type: 'boolean', description: 'Start as a background job; returns a job id (long scans).' } } : {}),\n cwd: { type: 'string', description: `Working directory inside ${workspaceRoot}.` },\n timeout_ms: { type: 'integer', description: 'Per-call timeout in milliseconds (clamped by deployment).' },\n tty: { type: 'boolean', description: 'Run under a PTY for interactive input via write_stdin.' },\n },\n output: {\n schema: {\n type: 'object',\n properties: {\n kind: { type: 'string', required: true, enum: ['foreground', 'tty', 'background'] },\n exit_code: { type: 'integer' },\n signal: { type: 'string' },\n timed_out: { type: 'boolean' },\n stdout: { type: 'string' },\n stderr: { type: 'string' },\n process_id: { type: 'string' },\n job_id: { type: 'string' },\n },\n additionalProperties: false,\n },\n render: (_args, value) => {\n if (value.kind === 'foreground') {\n return [{ type: 'text', text: `exit_code=${value.exit_code === null ? 'none' : String(value.exit_code)}${value.timed_out === true ? ' (timed out)' : ''}\\nstdout:\\n${value.stdout}\\nstderr:\\n${value.stderr}` }]\n }\n if (value.kind === 'tty') {\n return [{ type: 'text', text: `PTY process ${value.process_id} started. Poll with write_stdin(process_id=\"${value.process_id}\", chars=\"\"); send input via chars; deliver Ctrl-C with chars=\"\\\\x03\".` }]\n }\n return [{ type: 'text', text: `started background job ${value.job_id} (job_output to read, job_kill to stop)` }]\n },\n },\n timeoutMs: maxTimeoutMs,\n presentCall: args => ({ card: 'terminal', title: String(args.cmd ?? '') }),\n presentResult: (args, result) => {\n const text = result.content.filter(block => block.type === 'text').map(block => block.text).join('\\n')\n return { card: 'terminal', output: text === '' ? String(args.cmd ?? '') : text }\n },\n execute: async (args, exec) => {\n const cwdProblem = workdirError(args.cwd, workspaceRoot)\n if (cwdProblem !== null) throw new Error(cwdProblem)\n if (args.tty === true && args.run_in_background === true) {\n throw new Error('exec_command: tty=true and run_in_background cannot be combined — start a PTY process and drive it with write_stdin, or start a background job without a PTY.')\n }\n if (args.run_in_background === true && !backgroundEnabled) throw new Error('run_in_background is disabled for this deployment (enableRunInBackground: false)')\n const sandbox = await session()\n if (args.tty === true) {\n const process = await sandbox.execTty(args.cmd, { cwd: args.cwd })\n const tracked: TrackedTty = { process, buffer: '', cursor: 0, settled: undefined }\n process.subscribe(chunk => {\n tracked.buffer += chunk\n // Bound unpolled output; keep the tail and re-base the read cursor.\n if (tracked.buffer.length > maxTtyBufferBytes) {\n const excess = tracked.buffer.length - maxTtyBufferBytes\n tracked.buffer = tracked.buffer.slice(excess)\n tracked.cursor = Math.max(0, tracked.cursor - excess)\n }\n })\n void process.done.then(\n outcome => {\n tracked.settled = { exitCode: outcome.exitCode, signal: outcome.signal }\n },\n () => {\n tracked.settled = { exitCode: null, signal: null }\n },\n )\n ttyProcesses.set(process.id, tracked)\n return { kind: 'tty' as const, process_id: process.id }\n }\n if (args.run_in_background === true) {\n const jobs = ctx.get('jobs')\n if (jobs === undefined) throw new Error('run_in_background needs a jobs provider (load @deepseek-ai/dsh-jobs-local)')\n const job = sandbox.execJob(args.cmd, { cwd: args.cwd })\n let cancelled = false\n const jobId = jobs.start({\n kind: 'pentest-exec',\n label: args.cmd,\n ...exec.agent !== undefined ? { owner: exec.agent } : {},\n run: () => ({\n cancel: () => {\n cancelled = true\n job.terminate()\n },\n done: job.done.then(outcome =>\n // A killed docker-exec tree can still report exit code 0; the\n // cancellation flag is the authoritative kill signal.\n cancelled\n ? { status: 'killed' as const, detail: 'cancelled by request' }\n : {\n status: outcome.exitCode === 0 ? 'completed' as const : 'failed' as const,\n detail: `exit code: ${outcome.exitCode === null ? 'none' : String(outcome.exitCode)}`,\n }),\n readOutput: () => job.readOutput(),\n }),\n })\n return { kind: 'background' as const, job_id: jobId }\n }\n const result = await sandbox.exec(args.cmd, { cwd: args.cwd, timeoutMs: clampTimeout(args.timeout_ms, defaultTimeoutMs, maxTimeoutMs), signal: exec.signal })\n return {\n kind: 'foreground' as const,\n ...(result.exitCode !== null ? { exit_code: result.exitCode } : {}),\n ...(result.signal !== null ? { signal: result.signal } : {}),\n timed_out: result.timedOut,\n stdout: result.stdout,\n stderr: result.stderr,\n }\n },\n }))\n\n ctx.tools.register(defineTool({\n name: 'write_stdin',\n description: 'Send characters to a PTY-backed process started by exec_command(tty=true). chars=\"\" polls for new output without sending anything. Escapes (\\\\n, \\\\t, \\\\x03 for Ctrl-C, \\\\uXXXX) are decoded.',\n parameters: {\n process_id: { type: 'string', required: true, description: 'The process id returned by exec_command(tty=true).' },\n chars: { type: 'string', required: true, description: 'Characters to write (\"\" to poll for output only).' },\n },\n output: {\n schema: {\n type: 'object',\n properties: {\n output: { type: 'string', required: true },\n running: { type: 'boolean', required: true },\n exit_code: { type: 'integer' },\n },\n additionalProperties: false,\n },\n render: (_args, value) => [{\n type: 'text',\n text: `${value.running ? '(running)' : `(exited${value.exit_code === undefined ? '' : ` exit_code=${String(value.exit_code)}`})`}\\n${value.output}`,\n }],\n },\n execute: async args => {\n const tracked = ttyProcesses.get(args.process_id)\n if (tracked === undefined) throw new Error(STDIN_UNAVAILABLE)\n const chars = decodeCharsEscape(args.chars)\n if (chars !== '') await tracked.process.write(chars)\n const delta = tracked.buffer.slice(tracked.cursor)\n tracked.cursor = tracked.buffer.length\n if (tracked.settled !== undefined) ttyProcesses.delete(args.process_id)\n return {\n output: delta,\n running: tracked.settled === undefined,\n ...(tracked.settled !== undefined && tracked.settled.exitCode !== null ? { exit_code: tracked.settled.exitCode } : {}),\n }\n },\n }))\n}\n"],"mappings":";;;;;;;;;AAOA,MAAM,YAAY;AAElB,MAAM,gBAAwC;CAC5C,QAAQ;CACR,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;AACT;;;;;;AAOA,SAAgB,kBAAkB,OAAuB;CACvD,IAAI,CAAC,MAAM,SAAS,IAAI,GAAG,OAAO;CAClC,OAAO,MAAM,QAAQ,YAAW,UAAS;EACvC,MAAM,QAAQ,cAAc;EAC5B,IAAI,UAAU,KAAA,GAA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,KAAK,KAAK;GAC1C,IAAI,UAAU,IAAI,MAAM,QAAQ,QAAQ,MAAM,KAAK;GACnD,MAAM,QAAQ,QAAQ,OAAO,MAAM,QAAQ,MAAM;GACjD,QAAQ,SAAS,QAAQ,OAAO;GAChC,IAAI,QAAQ,YAAY,KAAA,GAAW,aAAa,OAAO,KAAK,UAAU;GACtE,OAAO;IACL,QAAQ;IACR,SAAS,QAAQ,YAAY,KAAA;IAC7B,GAAI,QAAQ,YAAY,KAAA,KAAa,QAAQ,QAAQ,aAAa,OAAO,EAAE,WAAW,QAAQ,QAAQ,SAAS,IAAI,CAAC;GACtH;EACF;CACF,CAAC,CAAC;AACJ"}
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@gpzhang2001/sharpkit-shell",
3
+ "description": "exec_command / write_stdin model-facing shell tools over the sharpkit sandbox",
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-shell"
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-jobs": "^0.1.2-rc.1",
36
+ "@deepseek-ai/dsh-tools": "^0.1.2-rc.1",
37
+ "@gpzhang2001/sharpkit-sandbox": "^0.1.0"
38
+ },
39
+ "devDependencies": {
40
+ "@deepseek-ai/cordis": "4.0.2",
41
+ "@deepseek-ai/dsh-jobs": "0.1.2-rc.1",
42
+ "@deepseek-ai/dsh-tools": "0.1.2-rc.1",
43
+ "@deepseek-ai/dsh-llm": "0.1.2-rc.1",
44
+ "@deepseek-ai/dsh-jobs-local": "0.1.2-rc.1"
45
+ },
46
+ "main": "lib/index.js",
47
+ "types": "lib/index.d.ts",
48
+ "scripts": {
49
+ "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"
50
+ }
51
+ }
package/src/chars.ts ADDED
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Escape decoding for `write_stdin` chars, ported verbatim from strix
3
+ * factory.py `_decode_chars_escape` (\\uXXXX, \\xNN, and the C-style short
4
+ * escapes; unknown escapes and backslash-free strings pass through).
5
+ * @module @gpzhang2001/sharpkit-shell/chars
6
+ */
7
+
8
+ const ESCAPE_RE = /\\(?:u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|[0abtnvfr\\])/g
9
+
10
+ const SHORT_ESCAPES: Record<string, string> = {
11
+ '\\\\': '\\',
12
+ '\\n': '\n',
13
+ '\\t': '\t',
14
+ '\\r': '\r',
15
+ '\\0': '\x00',
16
+ '\\a': '\x07',
17
+ '\\b': '\x08',
18
+ '\\v': '\x0b',
19
+ '\\f': '\x0c',
20
+ }
21
+
22
+ /**
23
+ * Decode the model-facing escape forms in a `chars` argument.
24
+ * @param chars - the raw argument value.
25
+ * @returns the decoded characters to deliver to the process.
26
+ */
27
+ export function decodeCharsEscape(chars: string): string {
28
+ if (!chars.includes('\\')) return chars
29
+ return chars.replace(ESCAPE_RE, token => {
30
+ const short = SHORT_ESCAPES[token]
31
+ if (short !== undefined) return short
32
+ return String.fromCodePoint(Number.parseInt(token.slice(2), 16))
33
+ })
34
+ }
package/src/index.ts ADDED
@@ -0,0 +1,284 @@
1
+ /**
2
+ * `exec_command` / `write_stdin` model-facing shell tools over the pentest
3
+ * sandbox — strix SDK ShellTool semantics (tools/shell/README.md + factory
4
+ * wrapping): a fresh non-interactive login shell per call by default, PTY
5
+ * processes for interactive work driven by `write_stdin` (chars="" polls),
6
+ * workdir restricted to the workspace, per-call timeout clamped by config,
7
+ * and `run_in_background` mapped onto the dsh jobs runtime
8
+ * (job_output/job_list/job_kill come free). Every exec passes an ask
9
+ * approval gate (config-gated; the registry resolves `ask` through the
10
+ * host's approval service and fails closed when none is composed).
11
+ * @module @gpzhang2001/sharpkit-shell
12
+ */
13
+
14
+ import type { Context } from '@deepseek-ai/cordis'
15
+ import type Schema from '@deepseek-ai/schemastery'
16
+ import z from '@deepseek-ai/schemastery'
17
+ import { defineTool } from '@deepseek-ai/dsh-tools'
18
+ import type { SandboxTtyProcess } from '@gpzhang2001/sharpkit-sandbox'
19
+ import { decodeCharsEscape } from './chars.ts'
20
+
21
+ /** strix's exact refusal text for write_stdin against a non-PTY process. */
22
+ export const STDIN_UNAVAILABLE = "stdin is not available for this process. Start the command with 'tty=true' in 'exec_command' before using 'write_stdin'."
23
+
24
+ /** One source tree Config entry (mutable twin of the sandbox spec for schemastery). */
25
+ export interface ConfigSource {
26
+ workspaceSubdir: string
27
+ sourcePath: string
28
+ protectMetadata?: boolean
29
+ }
30
+
31
+ /** Deployment-tunable configuration. */
32
+ export interface Config {
33
+ /** Sandbox session cache key; the orchestrator pre-creates the real session under this id. */
34
+ readonly scanId?: string
35
+ /** Source trees for the session this tool creates when none exists yet. */
36
+ readonly sources?: ConfigSource[]
37
+ /** Ask-approval gate on every exec_command (fail-closed without an approval service). */
38
+ readonly requireApproval?: boolean
39
+ /** Expose run_in_background (needs a jobs provider at runtime). */
40
+ readonly enableRunInBackground?: boolean
41
+ /** Default per-call timeout; model values are clamped into [1, maxTimeoutMs]. */
42
+ readonly defaultTimeoutMs?: number
43
+ /** Hard ceiling for the model's timeout_ms and the tool's own deadline. */
44
+ readonly maxTimeoutMs?: number
45
+ /** Container workspace root (workdir validation). */
46
+ readonly workspaceRoot?: string
47
+ /** Unpolled PTY output ceiling in bytes (approx; the tail is kept). */
48
+ readonly maxTtyBufferBytes?: number
49
+ }
50
+
51
+ import type {} from '@deepseek-ai/dsh-jobs'
52
+
53
+ declare module '@deepseek-ai/dsh-jobs' {
54
+ interface JobKindMap {
55
+ 'pentest-exec': 'pentest-exec'
56
+ }
57
+ }
58
+
59
+ /** One tracked PTY process with a read cursor for polling. */
60
+ interface TrackedTty {
61
+ readonly process: SandboxTtyProcess
62
+ buffer: string
63
+ cursor: number
64
+ settled: { exitCode: number | null; signal: string | null } | undefined
65
+ }
66
+
67
+ export const name = 'pentest-tool-shell'
68
+
69
+ export const inject = ['tools', 'pentestSandbox']
70
+
71
+ export const Config: Schema<Config> = z.object({
72
+ scanId: z.string().default('pentest'),
73
+ sources: z.array(z.object({
74
+ workspaceSubdir: z.string(),
75
+ sourcePath: z.string(),
76
+ protectMetadata: z.boolean(),
77
+ })),
78
+ requireApproval: z.boolean().default(true),
79
+ enableRunInBackground: z.boolean().default(true),
80
+ defaultTimeoutMs: z.number().default(120_000),
81
+ maxTimeoutMs: z.number().default(600_000),
82
+ workspaceRoot: z.string().default('/workspace'),
83
+ maxTtyBufferBytes: z.number().default(1_048_576),
84
+ })
85
+
86
+ /**
87
+ * Validate a workdir against the workspace root (strix workdir contract),
88
+ * segment by segment: no absolute escape, no `..`/`.`/empty segments, no
89
+ * trailing slash.
90
+ * @param cwd - the requested working directory.
91
+ * @param workspaceRoot - container workspace root.
92
+ * @returns null when valid, else strix's exact error text.
93
+ */
94
+ export function workdirError(cwd: string | undefined, workspaceRoot: string): string | null {
95
+ if (cwd === undefined) return null
96
+ if (cwd === workspaceRoot) return null
97
+ const prefix = `${workspaceRoot}/`
98
+ const inside = cwd.startsWith(prefix)
99
+ && cwd.slice(prefix.length).split('/').every(segment => segment !== '' && segment !== '.' && segment !== '..')
100
+ return inside ? null : `exec_command: workdir must be a path inside ${workspaceRoot} (or omitted to use the turn's cwd). Got: '${cwd}'.`
101
+ }
102
+
103
+ /** Clamp a requested timeout into the configured window. */
104
+ export function clampTimeout(requested: number | undefined, defaultTimeoutMs: number, maxTimeoutMs: number): number {
105
+ const value = requested ?? defaultTimeoutMs
106
+ return Math.min(Math.max(1, value), maxTimeoutMs)
107
+ }
108
+
109
+ export function apply(ctx: Context, config: Config = {}): void {
110
+ const ttyProcesses = new Map<string, TrackedTty>()
111
+
112
+ const session = () =>
113
+ ctx.pentestSandbox.createSession({
114
+ scanId: config.scanId ?? 'pentest',
115
+ ...(config.sources !== undefined ? { sources: config.sources.map(source => ({
116
+ workspaceSubdir: source.workspaceSubdir,
117
+ sourcePath: source.sourcePath,
118
+ ...(source.protectMetadata !== undefined ? { protectMetadata: source.protectMetadata } : {}),
119
+ })) } : {}),
120
+ })
121
+
122
+ if (config.requireApproval !== false) {
123
+ void ctx.on('tools/pre-execute', async (exec, next) => {
124
+ if (exec.name === 'exec_command') return { kind: 'ask' as const, reason: 'pentest: run a command inside the attack sandbox' }
125
+ return next()
126
+ })
127
+ }
128
+
129
+ const workspaceRoot = config.workspaceRoot ?? '/workspace'
130
+ const defaultTimeoutMs = config.defaultTimeoutMs ?? 120_000
131
+ const maxTimeoutMs = config.maxTimeoutMs ?? 600_000
132
+ const maxTtyBufferBytes = config.maxTtyBufferBytes ?? 1_048_576
133
+ const backgroundEnabled = config.enableRunInBackground !== false
134
+
135
+ ctx.tools.register(defineTool({
136
+ name: 'exec_command',
137
+ description: `Run a shell command inside the pentest sandbox (Kali container) in a fresh non-interactive bash login shell. Set tty=true for interactive programs (REPLs, ssh, msfconsole) and then drive them with write_stdin; run_in_background starts a job for long scans and returns a job id for job_output/job_kill.${backgroundEnabled ? '' : ' (run_in_background is disabled in this deployment.)'}`,
138
+ parameters: {
139
+ cmd: { type: 'string', required: true, description: 'The shell command line to execute.' },
140
+ ...(backgroundEnabled ? { run_in_background: { type: 'boolean', description: 'Start as a background job; returns a job id (long scans).' } } : {}),
141
+ cwd: { type: 'string', description: `Working directory inside ${workspaceRoot}.` },
142
+ timeout_ms: { type: 'integer', description: 'Per-call timeout in milliseconds (clamped by deployment).' },
143
+ tty: { type: 'boolean', description: 'Run under a PTY for interactive input via write_stdin.' },
144
+ },
145
+ output: {
146
+ schema: {
147
+ type: 'object',
148
+ properties: {
149
+ kind: { type: 'string', required: true, enum: ['foreground', 'tty', 'background'] },
150
+ exit_code: { type: 'integer' },
151
+ signal: { type: 'string' },
152
+ timed_out: { type: 'boolean' },
153
+ stdout: { type: 'string' },
154
+ stderr: { type: 'string' },
155
+ process_id: { type: 'string' },
156
+ job_id: { type: 'string' },
157
+ },
158
+ additionalProperties: false,
159
+ },
160
+ render: (_args, value) => {
161
+ if (value.kind === 'foreground') {
162
+ return [{ type: 'text', text: `exit_code=${value.exit_code === null ? 'none' : String(value.exit_code)}${value.timed_out === true ? ' (timed out)' : ''}\nstdout:\n${value.stdout}\nstderr:\n${value.stderr}` }]
163
+ }
164
+ if (value.kind === 'tty') {
165
+ return [{ type: 'text', text: `PTY process ${value.process_id} started. Poll with write_stdin(process_id="${value.process_id}", chars=""); send input via chars; deliver Ctrl-C with chars="\\x03".` }]
166
+ }
167
+ return [{ type: 'text', text: `started background job ${value.job_id} (job_output to read, job_kill to stop)` }]
168
+ },
169
+ },
170
+ timeoutMs: maxTimeoutMs,
171
+ presentCall: args => ({ card: 'terminal', title: String(args.cmd ?? '') }),
172
+ presentResult: (args, result) => {
173
+ const text = result.content.filter(block => block.type === 'text').map(block => block.text).join('\n')
174
+ return { card: 'terminal', output: text === '' ? String(args.cmd ?? '') : text }
175
+ },
176
+ execute: async (args, exec) => {
177
+ const cwdProblem = workdirError(args.cwd, workspaceRoot)
178
+ if (cwdProblem !== null) throw new Error(cwdProblem)
179
+ if (args.tty === true && args.run_in_background === true) {
180
+ throw new Error('exec_command: tty=true and run_in_background cannot be combined — start a PTY process and drive it with write_stdin, or start a background job without a PTY.')
181
+ }
182
+ if (args.run_in_background === true && !backgroundEnabled) throw new Error('run_in_background is disabled for this deployment (enableRunInBackground: false)')
183
+ const sandbox = await session()
184
+ if (args.tty === true) {
185
+ const process = await sandbox.execTty(args.cmd, { cwd: args.cwd })
186
+ const tracked: TrackedTty = { process, buffer: '', cursor: 0, settled: undefined }
187
+ process.subscribe(chunk => {
188
+ tracked.buffer += chunk
189
+ // Bound unpolled output; keep the tail and re-base the read cursor.
190
+ if (tracked.buffer.length > maxTtyBufferBytes) {
191
+ const excess = tracked.buffer.length - maxTtyBufferBytes
192
+ tracked.buffer = tracked.buffer.slice(excess)
193
+ tracked.cursor = Math.max(0, tracked.cursor - excess)
194
+ }
195
+ })
196
+ void process.done.then(
197
+ outcome => {
198
+ tracked.settled = { exitCode: outcome.exitCode, signal: outcome.signal }
199
+ },
200
+ () => {
201
+ tracked.settled = { exitCode: null, signal: null }
202
+ },
203
+ )
204
+ ttyProcesses.set(process.id, tracked)
205
+ return { kind: 'tty' as const, process_id: process.id }
206
+ }
207
+ if (args.run_in_background === true) {
208
+ const jobs = ctx.get('jobs')
209
+ if (jobs === undefined) throw new Error('run_in_background needs a jobs provider (load @deepseek-ai/dsh-jobs-local)')
210
+ const job = sandbox.execJob(args.cmd, { cwd: args.cwd })
211
+ let cancelled = false
212
+ const jobId = jobs.start({
213
+ kind: 'pentest-exec',
214
+ label: args.cmd,
215
+ ...exec.agent !== undefined ? { owner: exec.agent } : {},
216
+ run: () => ({
217
+ cancel: () => {
218
+ cancelled = true
219
+ job.terminate()
220
+ },
221
+ done: job.done.then(outcome =>
222
+ // A killed docker-exec tree can still report exit code 0; the
223
+ // cancellation flag is the authoritative kill signal.
224
+ cancelled
225
+ ? { status: 'killed' as const, detail: 'cancelled by request' }
226
+ : {
227
+ status: outcome.exitCode === 0 ? 'completed' as const : 'failed' as const,
228
+ detail: `exit code: ${outcome.exitCode === null ? 'none' : String(outcome.exitCode)}`,
229
+ }),
230
+ readOutput: () => job.readOutput(),
231
+ }),
232
+ })
233
+ return { kind: 'background' as const, job_id: jobId }
234
+ }
235
+ const result = await sandbox.exec(args.cmd, { cwd: args.cwd, timeoutMs: clampTimeout(args.timeout_ms, defaultTimeoutMs, maxTimeoutMs), signal: exec.signal })
236
+ return {
237
+ kind: 'foreground' as const,
238
+ ...(result.exitCode !== null ? { exit_code: result.exitCode } : {}),
239
+ ...(result.signal !== null ? { signal: result.signal } : {}),
240
+ timed_out: result.timedOut,
241
+ stdout: result.stdout,
242
+ stderr: result.stderr,
243
+ }
244
+ },
245
+ }))
246
+
247
+ ctx.tools.register(defineTool({
248
+ name: 'write_stdin',
249
+ description: 'Send characters to a PTY-backed process started by exec_command(tty=true). chars="" polls for new output without sending anything. Escapes (\\n, \\t, \\x03 for Ctrl-C, \\uXXXX) are decoded.',
250
+ parameters: {
251
+ process_id: { type: 'string', required: true, description: 'The process id returned by exec_command(tty=true).' },
252
+ chars: { type: 'string', required: true, description: 'Characters to write ("" to poll for output only).' },
253
+ },
254
+ output: {
255
+ schema: {
256
+ type: 'object',
257
+ properties: {
258
+ output: { type: 'string', required: true },
259
+ running: { type: 'boolean', required: true },
260
+ exit_code: { type: 'integer' },
261
+ },
262
+ additionalProperties: false,
263
+ },
264
+ render: (_args, value) => [{
265
+ type: 'text',
266
+ text: `${value.running ? '(running)' : `(exited${value.exit_code === undefined ? '' : ` exit_code=${String(value.exit_code)}`})`}\n${value.output}`,
267
+ }],
268
+ },
269
+ execute: async args => {
270
+ const tracked = ttyProcesses.get(args.process_id)
271
+ if (tracked === undefined) throw new Error(STDIN_UNAVAILABLE)
272
+ const chars = decodeCharsEscape(args.chars)
273
+ if (chars !== '') await tracked.process.write(chars)
274
+ const delta = tracked.buffer.slice(tracked.cursor)
275
+ tracked.cursor = tracked.buffer.length
276
+ if (tracked.settled !== undefined) ttyProcesses.delete(args.process_id)
277
+ return {
278
+ output: delta,
279
+ running: tracked.settled === undefined,
280
+ ...(tracked.settled !== undefined && tracked.settled.exitCode !== null ? { exit_code: tracked.settled.exitCode } : {}),
281
+ }
282
+ },
283
+ }))
284
+ }