dsh-pocket 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,21 +1,344 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 shaobeichen
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 2, June 1991
3
+
4
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
5
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
6
+
7
+ Everyone is permitted to copy and distribute verbatim copies
8
+ of this license document, but changing it is not allowed.
9
+
10
+ Preamble
11
+
12
+ The licenses for most software are designed to take away your
13
+ freedom to share and change it. By contrast, the GNU General Public
14
+ License is intended to guarantee your freedom to share and change free
15
+ software--to make sure the software is free for all its users. This
16
+ General Public License applies to most of the Free Software
17
+ Foundation's software and to any other program whose authors commit to
18
+ using it. (Some other Free Software Foundation software is covered by
19
+ the GNU Lesser General Public License instead.) You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ this service if you wish), that you receive source code or can get it
26
+ if you want it, that you can change the software or use pieces of it
27
+ in new free programs; and that you know you can do these things.
28
+
29
+ To protect your rights, we need to make restrictions that forbid
30
+ anyone to deny you these rights or to ask you to surrender the rights.
31
+ These restrictions translate to certain responsibilities for you if you
32
+ distribute copies of the software, or if you modify it.
33
+
34
+ For example, if you distribute copies of such a program, whether
35
+ gratis or for a fee, you must give the recipients all the rights that
36
+ you have. You must make sure that they, too, receive or can get the
37
+ source code. And you must show them these terms so they know their
38
+ rights.
39
+
40
+ We protect your rights with two steps: (1) copyright the software, and
41
+ (2) offer you this license which gives you legal permission to copy,
42
+ distribute and/or modify the software.
43
+
44
+ Also, for each author's protection and ours, we want to make certain
45
+ that everyone understands that there is no warranty for this free
46
+ software. If the software is modified by someone else and passed on, we
47
+ want its recipients to know that what they have is not the original, so
48
+ that any problems introduced by others will not reflect on the original
49
+ authors' reputations.
50
+
51
+ Finally, any free program is threatened constantly by software
52
+ patents. We wish to avoid the danger that redistributors of a free
53
+ program will individually obtain patent licenses, in effect making the
54
+ program proprietary. To prevent this, we have made it clear that any
55
+ patent must be licensed for everyone's free use or not licensed at all.
56
+
57
+ The precise terms and conditions for copying, distribution and
58
+ modification follow.
59
+
60
+ GNU GENERAL PUBLIC LICENSE
61
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
62
+
63
+ 0. This License applies to any program or other work which contains
64
+ a notice placed by the copyright holder saying it may be distributed
65
+ under the terms of this General Public License. The "Program", below,
66
+ refers to any such program or work, and a "work based on the Program"
67
+ means either the Program or any derivative work under copyright law:
68
+ that is to say, a work containing the Program or a portion of it,
69
+ either verbatim or with modifications and/or translated into another
70
+ language. (Hereinafter, translation is included without limitation in
71
+ the term "modification".) Each licensee is addressed as "you".
72
+
73
+ Activities other than copying, distribution and modification are not
74
+ covered by this License; they are outside its scope. The act of
75
+ running the Program is not restricted, and the output from the Program
76
+ is covered only if its contents constitute a work based on the
77
+ Program (independent of having been made by running the Program).
78
+ Whether that is true depends on what the Program does.
79
+
80
+ 1. You may copy and distribute verbatim copies of the Program's
81
+ source code as you receive it, in any medium, provided that you
82
+ conspicuously and appropriately publish on each copy an appropriate
83
+ copyright notice and disclaimer of warranty; keep intact all the
84
+ notices that refer to this License and to the absence of any warranty;
85
+ and give any other recipients of the Program a copy of this License
86
+ along with the Program.
87
+
88
+ You may charge a fee for the physical act of transferring a copy, and
89
+ you may at your option offer warranty protection in exchange for a fee.
90
+
91
+ 2. You may modify your copy or copies of the Program or any portion
92
+ of it, thus forming a work based on the Program, and copy and
93
+ distribute such modifications or work under the terms of Section 1
94
+ above, provided that you also meet all of these conditions:
95
+
96
+ a) You must cause the modified files to carry prominent notices
97
+ stating that you changed the files and the date of any change.
98
+
99
+ b) You must cause any work that you distribute or publish, that in
100
+ whole or in part contains or is derived from the Program or any
101
+ part thereof, to be licensed as a whole at no charge to all third
102
+ parties under the terms of this License.
103
+
104
+ c) If the modified program normally reads commands interactively
105
+ when run, you must cause it, when started running for such
106
+ interactive use in the most ordinary way, to print or display an
107
+ announcement including an appropriate copyright notice and a notice
108
+ that there is no warranty (or else, saying that you provide a
109
+ warranty) and that users may redistribute the program under these
110
+ conditions, and telling the user how to view a copy of this License.
111
+ (Exception: if the Program itself is interactive but does not
112
+ normally print such an announcement, your work based on the Program
113
+ is not required to print an announcement.)
114
+
115
+ These requirements apply to the modified work as a whole. If
116
+ identifiable sections of that work are not derived from the Program,
117
+ and can be reasonably considered independent and separate works in
118
+ themselves, then this License, and its terms, do not apply to those
119
+ sections when you distribute them as separate works. But when you
120
+ distribute the same sections as part of a whole which is a work based
121
+ on the Program, the distribution of the whole must be on the terms of
122
+ this License, whose permissions for other licensees extend to the
123
+ entire whole, and thus to each and every part regardless of who wrote it.
124
+
125
+ Thus, it is not the intent of this section to claim rights or contest
126
+ your rights to work written entirely by you; rather, the intent is to
127
+ exercise the right to control the distribution of derivative or
128
+ collective works based on the Program.
129
+
130
+ In addition, mere aggregation of another work not based on the Program
131
+ with the Program (or with a work based on the Program) on a volume of
132
+ a storage or distribution medium does not bring the other work under
133
+ the scope of this License.
134
+
135
+ 3. You may copy and distribute the Program (or a work based on it,
136
+ under Section 2) in object code or executable form under the terms of
137
+ Sections 1 and 2 above provided that you also do one of the following:
138
+
139
+ a) Accompany it with the complete corresponding machine-readable
140
+ source code, which must be distributed under the terms of Sections
141
+ 1 and 2 above on a medium customarily used for software interchange;
142
+ or,
143
+
144
+ b) Accompany it with a written offer, valid for at least three
145
+ years, to give any third party, for a charge no more than your cost
146
+ of physically performing source distribution, a complete
147
+ machine-readable copy of the corresponding source code, to be
148
+ distributed under the terms of Sections 1 and 2 above on a medium
149
+ customarily used for software interchange; or,
150
+
151
+ c) Accompany it with the information you received as to the offer
152
+ to distribute corresponding source code. (This alternative is
153
+ allowed only for noncommercial distribution and only if you
154
+ received the program in object code or executable form with such an
155
+ offer, in accord with Subsection b above.)
156
+
157
+ The source code for a work means the preferred form of the work for
158
+ making modifications to it. For an executable work, complete source
159
+ code means all the source code for all modules it contains, plus any
160
+ associated interface definition files, plus the scripts used to
161
+ control compilation and installation of the executable. However, as a
162
+ special exception, the source code distributed need not include
163
+ anything that is normally distributed (in either source or binary
164
+ form) with the major components (compiler, kernel, and so on) of the
165
+ operating system on which the executable runs, unless that component
166
+ itself accompanies the executable.
167
+
168
+ If distribution of executable or object code is made by offering
169
+ access to copy from a designated place, then offering equivalent
170
+ access to copy the source code from the same place counts as
171
+ distribution of the source code, even though third parties are not
172
+ compelled to copy the source along with the object code.
173
+
174
+ 4. You may not copy, modify, sublicense, or distribute the Program
175
+ except as expressly provided under this License. Any attempt
176
+ otherwise to copy, modify, sublicense or distribute the Program is
177
+ void, and will automatically terminate your rights under this License.
178
+ However, parties who have received copies, or rights, from you under
179
+ this License will not have their licenses terminated so long as such
180
+ parties remain in full compliance.
181
+
182
+ 5. You are not required to accept this License, since you have not
183
+ signed it. However, nothing else grants you permission to modify or
184
+ distribute the Program or its derivative works. These actions are
185
+ prohibited by law if you do not accept this License. Therefore, by
186
+ modifying or distributing the Program (or any work based on the
187
+ Program), you indicate your acceptance of this License to do so, and
188
+ all its terms and conditions for copying, distributing or modifying
189
+ the Program or works based on it.
190
+
191
+ 6. Each time you redistribute the Program (or any work based on the
192
+ Program), the recipient automatically receives a license from the
193
+ original licensor to copy, distribute or modify the Program subject to
194
+ these terms and conditions. You may not impose any further
195
+ restrictions on the recipients' exercise of the rights granted herein.
196
+ You are not responsible for enforcing compliance by third parties to
197
+ this License.
198
+
199
+ 7. If, as a consequence of a court judgment or allegation of patent
200
+ infringement or for any other reason (not limited to patent issues),
201
+ conditions are imposed on you (whether by court order, agreement or
202
+ otherwise) that contradict the conditions of this License, they do not
203
+ excuse you from the conditions of this License. If you cannot
204
+ distribute so as to satisfy simultaneously your obligations under this
205
+ License and any other pertinent obligations, then as a consequence you
206
+ may not distribute the Program at all. For example, if a patent
207
+ license would not permit royalty-free redistribution of the Program by
208
+ all those who receive copies directly or indirectly through you, then
209
+ the only way you could satisfy both it and this License would be to
210
+ refrain entirely from distribution of the Program.
211
+
212
+ If any portion of this section is held invalid or unenforceable under
213
+ any particular circumstance, the balance of the section is intended to
214
+ apply and the section as a whole is intended to apply in other
215
+ circumstances.
216
+
217
+ It is not the purpose of this section to induce you to infringe any
218
+ patents or other property right claims or to contest validity of any
219
+ such claims; this section has the sole purpose of protecting the
220
+ integrity of the free software distribution system, which is
221
+ implemented by public license practices. Many people have made
222
+ generous contributions to the wide range of software distributed
223
+ through that system in reliance on consistent application of that
224
+ system; it is up to the author/donor to decide if he or she is willing
225
+ to distribute software through any other system and a licensee cannot
226
+ impose that choice.
227
+
228
+ This section is intended to make thoroughly clear what is believed to
229
+ be a consequence of the rest of this License.
230
+
231
+ 8. If the distribution and/or use of the Program is restricted in
232
+ certain countries either by patents or by copyrighted interfaces, the
233
+ original copyright holder who places this Program under this License
234
+ may add an explicit geographical distribution limitation excluding
235
+ those countries, so that distribution is permitted only in or among
236
+ countries not thus excluded. In such case, this License incorporates
237
+ the limitation as if written in the body of this License.
238
+
239
+ 9. The Free Software Foundation may publish revised and/or new
240
+ versions of the General Public License from time to time. Such new
241
+ versions will be similar in spirit to the present version, but may
242
+ differ in detail to address new problems or concerns.
243
+
244
+ Each version is given a distinguishing version number. If the Program
245
+ specifies a version number of this License which applies to it and
246
+ "any later version", you have the option of following the terms and
247
+ conditions either of that version or of any later version published by
248
+ the Free Software Foundation. If the Program does not specify a
249
+ version number of this License, you may choose any version ever
250
+ published by the Free Software Foundation.
251
+
252
+ 10. If you wish to incorporate parts of the Program into other free
253
+ programs whose distribution conditions are different, write to the
254
+ author to ask for permission. For software which is copyrighted by the
255
+ Free Software Foundation, write to the Free Software Foundation; we
256
+ sometimes make exceptions for this. Our decision will be guided by the
257
+ two goals of preserving the free status of all derivatives of our free
258
+ software and of promoting the sharing and reuse of software generally.
259
+
260
+ NO WARRANTY
261
+
262
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO
263
+ WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
264
+ EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
265
+ OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND,
266
+ EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
267
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
268
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
269
+ PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME
270
+ THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
271
+
272
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
273
+ WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
274
+ AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU
275
+ FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
276
+ CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
277
+ PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
278
+ RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
279
+ FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF
280
+ SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
281
+ DAMAGES.
282
+
283
+ END OF TERMS AND CONDITIONS
284
+
285
+ How to Apply These Terms to Your New Programs
286
+
287
+ If you develop a new program, and you want it to be of the greatest
288
+ possible use to the public, the best way to achieve this is to make it
289
+ free software which everyone can redistribute and change under these
290
+ terms.
291
+
292
+ To do so, attach the following notices to the program. It is safest
293
+ to attach them to the start of each source file to most effectively
294
+ convey the exclusion of warranty; and each file should have at least
295
+ the "copyright" line and a pointer to where the full notice is found.
296
+
297
+ <one line to give the program's name and a brief idea of what it does.>
298
+ Copyright (C) <year> <name of author>
299
+
300
+ This program is free software; you can redistribute it and/or modify
301
+ it under the terms of the GNU General Public License as published by
302
+ the Free Software Foundation; either version 2 of the License, or
303
+ (at your option) any later version.
304
+
305
+ This program is distributed in the hope that it will be useful,
306
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
307
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
308
+ GNU General Public License for more details.
309
+
310
+ You should have received a copy of the GNU General Public License
311
+ along with this program; if not, write to the Free Software
312
+ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
313
+
314
+
315
+ Also add information on how to contact you by electronic and paper mail.
316
+
317
+ If the program is interactive, make it output a short notice like this
318
+ when it starts in an interactive mode:
319
+
320
+ Gnomovision version 69, Copyright (C) year name of author
321
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
322
+ This is free software, and you are welcome to redistribute it
323
+ under certain conditions; type `show c' for details.
324
+
325
+ The hypothetical commands `show w' and `show c' should show the appropriate
326
+ parts of the General Public License. Of course, the commands you use may
327
+ be called something other than `show w' and `show c'; they could even be
328
+ mouse-clicks or menu items--whatever suits your program.
329
+
330
+ You should also get your employer (if you work as a programmer) or your
331
+ school, if any, to sign a "copyright disclaimer" for the program, if
332
+ necessary. Here is a sample; alter the names:
333
+
334
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
335
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
336
+
337
+ <signature of Ty Coon>, 1 April 1989
338
+ Ty Coon, President of Vice
339
+
340
+ This General Public License does not permit incorporating your program
341
+ into proprietary programs. If your program is a subroutine library, you
342
+ may consider it more useful to permit linking proprietary applications
343
+ with the library. If this is what you want to do, use the GNU Lesser
344
+ General Public License instead of this License.
package/README.en.md ADDED
@@ -0,0 +1,122 @@
1
+ <p align="center">
2
+ <img src="docs/banner.jpg" alt="DSH Pocket" width="100%">
3
+ </p>
4
+
5
+ # DSH Pocket
6
+
7
+ <p align="center">
8
+ <a href="https://www.npmjs.com/package/dsh-pocket"><img alt="npm" src="https://img.shields.io/npm/v/dsh-pocket?color=4d6bfe&label=npm"></a>
9
+ <a href="https://www.npmjs.com/package/dsh-pocket"><img alt="downloads" src="https://img.shields.io/npm/dm/dsh-pocket?color=4d6bfe"></a>
10
+ <a href="https://github.com/shaobeichen/dsh-pocket/actions"><img alt="CI" src="https://github.com/shaobeichen/dsh-pocket/actions/workflows/npm-publish.yml/badge.svg"></a>
11
+ <a href="LICENSE"><img alt="License: MIT" src="https://img.shields.io/badge/license-GPL--2.0-red.svg"></a>
12
+ <a href="https://github.com/shaobeichen/dsh-pocket/stargazers"><img alt="GitHub stars" src="https://img.shields.io/github/stars/shaobeichen/dsh-pocket"></a>
13
+ </p>
14
+
15
+ > Put **DeepSeek Harness in your pocket**: one package, one settings tab — scan a QR code and your phone shows exactly what's on your computer screen, live, from anywhere.
16
+ >
17
+ > [English](README.en.md) | [中文](README.md)
18
+
19
+ ## What is this
20
+
21
+ `dsh web` only allows local access by default (`127.0.0.1:3080`). DSH Pocket puts a **header-rewriting proxy** in front of it and hands you QR codes right in the DSH web settings page:
22
+
23
+ ```
24
+ Phone ──scan──> dsh-pocket proxy ──> dsh web :3080
25
+ (rewrites Host/Origin to loopback; passes DSH's trust fence)
26
+ ```
27
+
28
+ ## ✨ Features
29
+
30
+ | Feature | Description |
31
+ |---|---|
32
+ | 📶 LAN QR access | Works out of the box: Settings → Plugins → Phone access — scan the LAN QR on the same Wi-Fi |
33
+ | 🌐 Public QR (from anywhere) | Click "Enable anywhere" → cloudflared tunnel → scan the public QR over 4G / any network |
34
+ | ⚡ Real-time sync | Streaming output passes through WebSocket untouched — what the computer renders, the phone renders live; fully interactive both ways |
35
+ | 📱 Mobile-adaptive layout | Narrow screens get a drawer layout automatically (ported from dsh-web-mobile, MIT): sidebar drawer, full-width conversation, safe-area insets, touch optimizations |
36
+ | 🧩 Zero-dependency install | One npm package, one settings tab — no core/adapter split, no account, no server |
37
+ | 🔒 URL is the key | No public URL exposure in LAN mode; public URL rotates on every restart |
38
+ | 🔔 Web Push | Phone notifications when a task finishes or fails (even with the page closed); requires the HTTPS public tunnel or localhost |
39
+
40
+ ## 🚀 Usage
41
+
42
+ ```sh
43
+ # 1. Install the plugin (everything in one package)
44
+ dsh plugin --profile web add dsh-pocket -w
45
+
46
+ # 2. Restart dsh web
47
+ npx @deepseek-ai/dsh web
48
+ ```
49
+
50
+ ### LAN (same Wi-Fi)
51
+
52
+ Settings → Plugins → **Phone access** → scan the "📶 LAN" QR code → the phone opens the exact same DSH, in real time.
53
+
54
+ ### Public (from anywhere)
55
+
56
+ On the same page click "**Enable anywhere**" → wait for the tunnel (first run downloads cloudflared) → scan the "🌐 Public" QR code → works from outside (4G / office network).
57
+
58
+ > Upgrading: `dsh plugin --profile web update dsh-pocket --latest -w` (`--latest` is required across major versions — a `^0.x` range won't auto-jump to 1.x).
59
+
60
+ ## 🧭 How it works
61
+
62
+ DSH's `/api` browser-trust fence only accepts loopback or `--trusted-host` authorities (and the official build refuses `0.0.0.0` binding to avoid exposing remote code execution to the network). Pocket rewrites every inbound request's `Host` / `Origin` to `127.0.0.1:<dsh-port>`, so the fence always sees loopback — **no dsh configuration changes needed**. The proxy auto-starts with the plugin; the public tunnel is on demand (cloudflared forced to HTTP/2 over TCP 443 to bypass blocked QUIC/UDP).
63
+
64
+ ## ⚠️ Security (read first)
65
+
66
+ - **DSH can execute code on your computer.** The QR code / URL is the key — **never share it with anyone**.
67
+ - The public URL is randomly assigned by cloudflared and **changes on every restart** (old links die automatically — a natural key rotation).
68
+ - LAN mode exposes nothing publicly; only devices on the same network can reach it.
69
+ - Built for personal use; access tokens for multi-device/sharing are planned.
70
+
71
+ ## ⚠️ Public tunnel troubleshooting (read first)
72
+
73
+ **Symptom**: after clicking "Enable anywhere", the public URL shows `error 1033` (Tunnel error) on the phone.
74
+
75
+ **Most common cause: a local proxy/VPN (Clash, Surge, v2ray, sing-box, etc., especially in TUN mode).**
76
+ Such tools take over all traffic and often cut cloudflared's tunnel-edge connections
77
+ (`*.argotunnel.com`, Cloudflare edge IPs), so the tunnel registers but the data plane never connects.
78
+
79
+ **Fix (any one of)**:
80
+
81
+ 1. Temporarily **fully quit the proxy** (not just close the window: quit Clash from the menu-bar icon; if a
82
+ background service is installed, stop it in the service manager and confirm with `ps aux | grep clash`), then retry.
83
+ 2. Add **DIRECT rules** to the proxy for the tunnel domains and Cloudflare edge (Clash example):
84
+ ```yaml
85
+ - DOMAIN-SUFFIX,argotunnel.com,DIRECT
86
+ - DOMAIN-SUFFIX,trycloudflare.com,DIRECT
87
+ - IP-CIDR,198.41.192.0/24,DIRECT,no-resolve
88
+ ```
89
+ 3. If the network really can't reach the tunnel, use **LAN mode**: turn on the phone hotspot → connect the computer to it → scan the LAN QR. Same experience, from anywhere.
90
+
91
+ **Other causes**: corporate firewalls / campus networks blocking outbound — ask IT to allow it, or use a hotspot.
92
+
93
+ ## 🗂 Architecture (single package)
94
+
95
+ | File | Purpose |
96
+ |---|---|
97
+ | `lib/index.js` | Plugin entry: auto-start proxy + register RPC (`inject: connection, webServer`) |
98
+ | `lib/service.mjs` | Service: proxy lifecycle, public tunnel, status snapshot (with QR data URLs) |
99
+ | `lib/proxy.mjs` | Header-rewriting reverse proxy: Host/Origin → loopback, HTTP + WebSocket passthrough + polyfill injection |
100
+ | `lib/tunnel.mjs` | cloudflared quick tunnel: download/extract/start/parse public URL (HTTP/2) |
101
+ | `lib/web-rpc.js` | Loopback RPC: `pocket.status` / `tunnel.start` / `tunnel.stop` |
102
+ | `client/` | "Phone access" settings tab + mobile adaptation (dsh-web-mobile port) |
103
+ | `bin/dsh-pocket.mjs` | CLI: LAN/public modes, prints URL + QR |
104
+
105
+ ## 🛠 Development
106
+
107
+ ```sh
108
+ npm install
109
+ node client/build.mjs # rebuild after editing client/
110
+ npm test # proxy rewrite / WS passthrough / tunnel / service / RPC (7 tests)
111
+ ```
112
+
113
+ ## 🤝 Credits
114
+
115
+ - Mobile adaptation ported from [mexiaosqwq/dsh-web-mobile](https://github.com/mexiaosqwq/dsh-web-mobile) (MIT)
116
+ - Public tunnel powered by [cloudflared](https://github.com/cloudflare/cloudflared)
117
+
118
+ ## 📄 License
119
+
120
+ [GPL-2.0](LICENSE) — copyleft: free to use, modify, and redistribute, but **derivatives must stay GPL** and keep the copyright notice; commercial use included.
121
+
122
+ > Note: the mobile-adaptation portion is ported from [dsh-web-mobile](https://github.com/mexiaosqwq/dsh-web-mobile) (MIT, GPL-compatible); its copyright notice stays in `client/mobile/LICENSE.dsh-web-mobile`.
package/README.md CHANGED
@@ -1,8 +1,20 @@
1
+ <p align="center">
2
+ <img src="docs/banner.jpg" alt="DSH Pocket" width="100%">
3
+ </p>
4
+
1
5
  # DSH Pocket
2
6
 
3
- **DeepSeek Harness 装进你的口袋**:一个包、一个设置页,手机扫二维码就实时看到电脑上的同一个界面——人在外面也能用。
7
+ <p align="center">
8
+ <a href="https://www.npmjs.com/package/dsh-pocket"><img alt="npm" src="https://img.shields.io/npm/v/dsh-pocket?color=4d6bfe&label=npm"></a>
9
+ <a href="https://www.npmjs.com/package/dsh-pocket"><img alt="downloads" src="https://img.shields.io/npm/dm/dsh-pocket?color=4d6bfe"></a>
10
+ <a href="https://github.com/shaobeichen/dsh-pocket/actions"><img alt="CI" src="https://github.com/shaobeichen/dsh-pocket/actions/workflows/npm-publish.yml/badge.svg"></a>
11
+ <a href="LICENSE"><img alt="License: MIT" src="https://img.shields.io/badge/license-GPL--2.0-red.svg"></a>
12
+ <a href="https://github.com/shaobeichen/dsh-pocket/stargazers"><img alt="GitHub stars" src="https://img.shields.io/github/stars/shaobeichen/dsh-pocket"></a>
13
+ </p>
4
14
 
5
- > EN: Put DeepSeek Harness in your pocket. One package, one settings tab — scan a QR code and your phone shows exactly what's on your computer screen, live, anywhere.
15
+ > **DeepSeek Harness 装进你的口袋**:一个包、一个设置页,手机扫二维码就实时看到电脑上的同一个界面——人在外面也能用。
16
+ >
17
+ > [English](README.en.md) | [中文](README.md)
6
18
 
7
19
  ## 这是什么
8
20
 
@@ -13,28 +25,49 @@
13
25
  (改写 Host/Origin 为 loopback,DSH 信任栅栏放行)
14
26
  ```
15
27
 
16
- - **局域网**:装好插件,设置 → 插件 → **手机访问**,打开就有一个局域网二维码——手机连同一 WiFi 扫码即用
17
- - **公网**:同一页点「**开启公网访问**」,出第二个二维码——人在外面(4G/公司网)也能访问
18
- - **实时同步**:DSH 的流式输出走 WebSocket,代理原样透传——**电脑上看到什么,手机上就是什么**
28
+ ## 特性
29
+
30
+ | 特性 | 说明 |
31
+ |---|---|
32
+ | 📶 局域网扫码 | 装好即用:设置 → 插件 → 手机访问,打开就有局域网二维码,手机连同一 WiFi 扫码即开 |
33
+ | 🌐 公网扫码(人在外面) | 点「开启公网访问」→ cloudflared 隧道 → 出公网二维码,4G/任何网络都能访问 |
34
+ | ⚡ 实时同步 | 流式输出走 WebSocket 全透传——**电脑上在输出,手机上同步在滚**,可双向操作 |
35
+ | 📱 移动端适配 | 窄屏自动变抽屉布局(移植 dsh-web-mobile,MIT):侧栏抽屉、会话全宽、状态栏安全区、触控优化 |
36
+ | 🧩 零依赖安装 | 一个 npm 包、一个设置页,没有核心/适配器要分开装;无需账号、无需服务器 |
37
+ | 🔒 URL 即钥匙 | 无公网 URL 暴露给第三方(局域网模式);公网 URL 每次重启自动换新 |
38
+ | 🔔 Web Push 通知 | agent 跑完/出错 → 手机推送通知(即使没开页面);需 HTTPS 公网路径或 localhost |
19
39
 
20
- ## 安装
40
+ ## 🚀 怎么用
21
41
 
22
42
  ```sh
43
+ # 1. 装插件(一个包全都有)
23
44
  dsh plugin --profile web add dsh-pocket -w
45
+
46
+ # 2. 重启 dsh web
47
+ npx @deepseek-ai/dsh web
24
48
  ```
25
49
 
26
- 重启 `dsh web` → 设置 → 插件 → **手机访问**。**就这一个包,没有核心/适配器要分开装。**
50
+ ### 局域网(同一 WiFi)
51
+
52
+ 设置 → 插件 → **手机访问** → 手机扫「📶 局域网」二维码 → 打开的就是电脑上的 DSH,实时同步。
53
+
54
+ ### 公网(人在外面)
55
+
56
+ 同一页点「**开启公网访问**」→ 等隧道建立(首次会下载 cloudflared)→ 手机扫「🌐 公网」二维码 → 人在外面(4G/公司网)也能访问。
57
+
58
+ > 更新到新版本:`dsh plugin --profile web update dsh-pocket --latest -w`(跨大版本时 `--latest` 是必须的,`^0.x` 范围不会自动升到 1.x)。
59
+
60
+ ## 🧭 原理
61
+
62
+ DSH 的 `/api` 浏览器信任栅栏只认 loopback 或 `--trusted-host`(官方还禁了 `0.0.0.0` 绑定,防止把远程执行代码暴露给网络)。Pocket 把入站请求的 `Host` / `Origin` 统一改写成 `127.0.0.1:<dsh端口>`,栅栏永远看到 loopback——**不需要改 dsh 的任何配置**。代理随插件自动启动,公网隧道按需开启(cloudflared 强制走 HTTP/2/TCP 443,绕开被网络屏蔽的 QUIC/UDP)。
27
63
 
28
64
  ## ⚠️ 安全(必读)
29
65
 
30
66
  - **DSH 能执行你电脑上的代码**。二维码/URL 就是钥匙,**请勿把二维码或 URL 发给任何人**
31
- - 公网 URL 由 cloudflared 随机分配,**每次重启 dsh web 会变化**(旧链接自动失效,相当于天然轮换)
67
+ - 公网 URL 由 cloudflared 随机分配,**每次重启会变化**(旧链接自动失效,相当于天然轮换)
68
+ - 局域网模式不暴露公网,只有同一网络内的设备能访问
32
69
  - 适合个人自用;多设备/分享场景后续会加访问令牌
33
70
 
34
- ## 原理
35
-
36
- DSH 的 `/api` 浏览器信任栅栏只认 loopback 或 `--trusted-host`(官方还禁了 `0.0.0.0` 绑定,防止把远程执行代码暴露给网络)。Pocket 把入站请求的 `Host` / `Origin` 统一改写成 `127.0.0.1:<dsh端口>`,栅栏永远看到 loopback——**不需要改 dsh 的任何配置**。代理随插件自动启动,公网隧道按需开启(首次自动下载 cloudflared)。
37
-
38
71
  ## ⚠️ 公网隧道常见问题(必读)
39
72
 
40
73
  **现象**:点「开启公网访问」后,手机上打开公网地址报 `error 1033`(Tunnel error)。
@@ -58,25 +91,33 @@ DSH 的 `/api` 浏览器信任栅栏只认 loopback 或 `--trusted-host`(官
58
91
 
59
92
  **其他可能**:企业防火墙/校园网拦截出站;此时请让 IT 放行或改用热点。
60
93
 
61
- ## 架构(单包)
94
+ ## 🗂 架构(单包)
62
95
 
63
96
  | 文件 | 说明 |
64
97
  |---|---|
65
98
  | `lib/index.js` | 插件入口:自动起代理 + 注册 RPC(`inject: connection, webServer`) |
66
99
  | `lib/service.mjs` | 服务:代理生命周期、公网隧道、状态快照(含二维码 data URL) |
67
- | `lib/proxy.mjs` | 改头反向代理:Host/Origin → loopback,HTTP + WebSocket 全透传 |
68
- | `lib/tunnel.mjs` | cloudflared 快速隧道:下载/启动/解析公网 URL |
100
+ | `lib/proxy.mjs` | 改头反向代理:Host/Origin → loopback,HTTP + WebSocket 全透传 + polyfill 注入 |
101
+ | `lib/tunnel.mjs` | cloudflared 快速隧道:下载/解压/启动/解析公网 URL(HTTP/2) |
69
102
  | `lib/web-rpc.js` | loopback RPC:`pocket.status` / `tunnel.start` / `tunnel.stop` |
70
- | `client/` | 设置页「手机访问」标签(React,esbuild 打包) |
103
+ | `client/` | 设置页「手机访问」+ 移动端适配(dsh-web-mobile 移植) |
104
+ | `bin/dsh-pocket.mjs` | CLI:局域网/公网模式,打印 URL + 二维码 |
71
105
 
72
- ## 开发
106
+ ## 🛠 开发
73
107
 
74
108
  ```sh
75
109
  npm install
76
- node client/build.mjs # 改 client/index.jsx 后重新打包
77
- npm test # 代理改写 + WS 透传 + 服务 + RPC(5 个测试)
110
+ node client/build.mjs # 改 client/ 后重新打包
111
+ npm test # 代理改写 / WS 透传 / 隧道 / 服务 / RPC(7 测试)
78
112
  ```
79
113
 
80
- ## License
114
+ ## 🤝 致谢
115
+
116
+ - 移动端适配移植自 [mexiaosqwq/dsh-web-mobile](https://github.com/mexiaosqwq/dsh-web-mobile)(MIT)
117
+ - 公网隧道基于 [cloudflared](https://github.com/cloudflare/cloudflared)
118
+
119
+ ## 📄 License
120
+
121
+ [GPL-2.0](LICENSE) —— 自由软件许可:可自由使用、修改、分发,但**修改版必须同样以 GPL 开源**并保留版权声明;商用同样适用。
81
122
 
82
- MIT
123
+ > 说明:移动端适配部分移植自 [dsh-web-mobile](https://github.com/mexiaosqwq/dsh-web-mobile)(MIT 许可,兼容 GPL),其版权声明保留在 `client/mobile/LICENSE.dsh-web-mobile`。
package/client/api.js CHANGED
@@ -5,6 +5,10 @@ export const POCKET_ENDPOINTS = Object.freeze({
5
5
  status: 'pocket.status',
6
6
  tunnelStart: 'tunnel.start',
7
7
  tunnelStop: 'tunnel.stop',
8
+ pushVapidKey: 'push.vapidKey',
9
+ pushSubscribe: 'push.subscribe',
10
+ pushUnsubscribe: 'push.unsubscribe',
11
+ pushStatus: 'push.status',
8
12
  });
9
13
 
10
14
  /** 浏览器可见的状态字段(无敏感信息;含二维码 data URL)。 */
package/client/client.js CHANGED
@@ -37,7 +37,11 @@ var POCKET_RPC_CHANNEL = "/dsh-pocket";
37
37
  var POCKET_ENDPOINTS = Object.freeze({
38
38
  status: "pocket.status",
39
39
  tunnelStart: "tunnel.start",
40
- tunnelStop: "tunnel.stop"
40
+ tunnelStop: "tunnel.stop",
41
+ pushVapidKey: "push.vapidKey",
42
+ pushSubscribe: "push.subscribe",
43
+ pushUnsubscribe: "push.unsubscribe",
44
+ pushStatus: "push.status"
41
45
  });
42
46
  function redactStatus(s) {
43
47
  return {
@@ -1241,6 +1245,32 @@ function mobileApply(ctx) {
1241
1245
  // client/index.jsx
1242
1246
  var name = "dsh-pocket";
1243
1247
  var inject = ["slots", "connection", "layout", "locale", "sessionLogDownload"];
1248
+ async function setupPush(rpcCall) {
1249
+ try {
1250
+ if (!("serviceWorker" in navigator) || !("PushManager" in window)) return "unsupported";
1251
+ if (!window.isSecureContext) return "insecure";
1252
+ const reg = await navigator.serviceWorker.register("/pocket-sw.js");
1253
+ const vapid = await rpcCall(POCKET_ENDPOINTS.pushVapidKey, {});
1254
+ if (!vapid?.ok) return "host-error";
1255
+ let sub = await reg.pushManager.getSubscription();
1256
+ if (!sub) {
1257
+ sub = await reg.pushManager.subscribe({
1258
+ userVisibleOnly: true,
1259
+ applicationServerKey: urlBase64ToUint8Array(vapid.value.publicKey)
1260
+ });
1261
+ }
1262
+ const res = await rpcCall(POCKET_ENDPOINTS.pushSubscribe, { subscription: sub.toJSON() });
1263
+ return res?.ok ? "on" : "host-error";
1264
+ } catch {
1265
+ return "error";
1266
+ }
1267
+ }
1268
+ function urlBase64ToUint8Array(base64url) {
1269
+ const pad = "=".repeat((4 - base64url.length % 4) % 4);
1270
+ const b64 = (base64url + pad).replace(/-/g, "+").replace(/_/g, "/");
1271
+ const raw = atob(b64);
1272
+ return Uint8Array.from(raw, (c) => c.charCodeAt(0));
1273
+ }
1244
1274
  var styles = {
1245
1275
  card: { background: "var(--dsw-alias-bg-layer-1,#fff)", border: "1px solid var(--dsw-alias-border-l2,#e5e7eb)", borderRadius: 12, padding: "14px 16px", maxWidth: 480 },
1246
1276
  block: { borderTop: "1px solid var(--dsw-alias-border-l2,#e5e7eb)", marginTop: 12, paddingTop: 12 },
@@ -1255,6 +1285,7 @@ function PocketSettingsTab({ rpcCall }) {
1255
1285
  const [status, setStatus] = (0, import_react2.useState)(null);
1256
1286
  const [busy, setBusy] = (0, import_react2.useState)(false);
1257
1287
  const [error, setError] = (0, import_react2.useState)(null);
1288
+ const [pushState, setPushState] = (0, import_react2.useState)("checking");
1258
1289
  const call = async (endpoint, payload) => {
1259
1290
  const res = await rpcCall(endpoint, payload);
1260
1291
  if (!res?.ok) throw new Error(res?.error?.message ?? "RPC failed");
@@ -1271,6 +1302,9 @@ function PocketSettingsTab({ rpcCall }) {
1271
1302
  const t = setInterval(load, 3e3);
1272
1303
  return () => clearInterval(t);
1273
1304
  }, []);
1305
+ (0, import_react2.useEffect)(() => {
1306
+ setupPush(rpcCall).then(setPushState);
1307
+ }, []);
1274
1308
  const startTunnel = async () => {
1275
1309
  setBusy(true);
1276
1310
  setError(null);
@@ -1331,6 +1365,17 @@ function PocketSettingsTab({ rpcCall }) {
1331
1365
  (0, import_react2.createElement)("div", { style: styles.warn, marginTop: 8 }, "\u26A0\uFE0F DSH \u80FD\u6267\u884C\u7535\u8111\u4EE3\u7801\uFF1A\u4E8C\u7EF4\u7801/URL \u5C31\u662F\u94A5\u5319\uFF0C\u8BF7\u52FF\u53D1\u7ED9\u522B\u4EBA")
1332
1366
  )
1333
1367
  ),
1368
+ // Web Push 状态
1369
+ (0, import_react2.createElement)(
1370
+ "div",
1371
+ { style: styles.block },
1372
+ (0, import_react2.createElement)("div", { style: { fontWeight: 600, fontSize: 13 } }, "\u{1F514} \u63A8\u9001\u901A\u77E5 | Push notifications"),
1373
+ (0, import_react2.createElement)(
1374
+ "div",
1375
+ { style: styles.muted },
1376
+ pushState === "on" ? "\u5DF2\u5F00\u542F\uFF1Aagent \u8DD1\u5B8C/\u51FA\u9519\u65F6\u624B\u673A\u6536\u5230\u901A\u77E5 | on: notified when tasks finish or fail" : pushState === "unsupported" ? "\u5F53\u524D\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u63A8\u9001 | this browser does not support push" : pushState === "insecure" ? "\u9700\u8981 HTTPS\uFF08\u516C\u7F51\u96A7\u9053\uFF09\u6216 localhost \u624D\u80FD\u5F00\u542F\u63A8\u9001 | push needs HTTPS (public tunnel) or localhost" : pushState === "checking" ? "\u68C0\u67E5\u4E2D\u2026 | checking\u2026" : "\u63A8\u9001\u672A\u5F00\u542F | push not enabled"
1377
+ )
1378
+ ),
1334
1379
  error ? (0, import_react2.createElement)("div", { style: { color: "var(--dsw-alias-state-error-primary,#dc2626)", fontSize: 12, marginTop: 8 } }, `\u274C ${error}`) : null
1335
1380
  );
1336
1381
  }
package/client/index.jsx CHANGED
@@ -1,6 +1,7 @@
1
1
  // dsh-pocket 网页客户端:
2
- // 1. 设置页签「手机访问」(局域网/公网二维码)
2
+ // 1. 设置页签「手机访问」(局域网/公网二维码 + Web Push 状态)
3
3
  // 2. 移动端适配(移植自 MIT 项目 dsh-web-mobile,见 client/mobile/LICENSE.dsh-web-mobile)
4
+ // 3. Web Push:注册 Service Worker + 订阅推送(agent 跑完/出错 → 手机通知)
4
5
  //
5
6
  // 手机扫码打开的就是电脑上的 dsh web,实时同步;窄屏自动变成抽屉布局。
6
7
 
@@ -12,6 +13,36 @@ import { mobileApply } from './mobile/mobile-apply.tsx';
12
13
  const name = 'dsh-pocket';
13
14
  const inject = ['slots', 'connection', 'layout', 'locale', 'sessionLogDownload'];
14
15
 
16
+ /** Web Push:注册 SW + 订阅(仅安全上下文可用:HTTPS 公网 / localhost)。 */
17
+ async function setupPush(rpcCall) {
18
+ try {
19
+ if (!('serviceWorker' in navigator) || !('PushManager' in window)) return 'unsupported';
20
+ if (!window.isSecureContext) return 'insecure'; // http://LAN-IP 无 Push API
21
+ const reg = await navigator.serviceWorker.register('/pocket-sw.js');
22
+ const vapid = await rpcCall(POCKET_ENDPOINTS.pushVapidKey, {});
23
+ if (!vapid?.ok) return 'host-error';
24
+ let sub = await reg.pushManager.getSubscription();
25
+ if (!sub) {
26
+ sub = await reg.pushManager.subscribe({
27
+ userVisibleOnly: true,
28
+ applicationServerKey: urlBase64ToUint8Array(vapid.value.publicKey),
29
+ });
30
+ }
31
+ const res = await rpcCall(POCKET_ENDPOINTS.pushSubscribe, { subscription: sub.toJSON() });
32
+ return res?.ok ? 'on' : 'host-error';
33
+ } catch {
34
+ return 'error';
35
+ }
36
+ }
37
+
38
+ /** VAPID 公钥(base64url)→ Uint8Array(pushManager.subscribe 需要)。 */
39
+ function urlBase64ToUint8Array(base64url) {
40
+ const pad = '='.repeat((4 - (base64url.length % 4)) % 4);
41
+ const b64 = (base64url + pad).replace(/-/g, '+').replace(/_/g, '/');
42
+ const raw = atob(b64);
43
+ return Uint8Array.from(raw, (c) => c.charCodeAt(0));
44
+ }
45
+
15
46
  const styles = {
16
47
  card: { background: 'var(--dsw-alias-bg-layer-1,#fff)', border: '1px solid var(--dsw-alias-border-l2,#e5e7eb)', borderRadius: 12, padding: '14px 16px', maxWidth: 480 },
17
48
  block: { borderTop: '1px solid var(--dsw-alias-border-l2,#e5e7eb)', marginTop: 12, paddingTop: 12 },
@@ -27,6 +58,7 @@ function PocketSettingsTab({ rpcCall }) {
27
58
  const [status, setStatus] = useState(null);
28
59
  const [busy, setBusy] = useState(false);
29
60
  const [error, setError] = useState(null);
61
+ const [pushState, setPushState] = useState('checking'); // checking|on|unsupported|insecure|off
30
62
 
31
63
  const call = async (endpoint, payload) => {
32
64
  const res = await rpcCall(endpoint, payload);
@@ -44,6 +76,11 @@ function PocketSettingsTab({ rpcCall }) {
44
76
  return () => clearInterval(t);
45
77
  }, []);
46
78
 
79
+ // Web Push 订阅(只跑一次)
80
+ useEffect(() => {
81
+ setupPush(rpcCall).then(setPushState);
82
+ }, []);
83
+
47
84
  const startTunnel = async () => {
48
85
  setBusy(true);
49
86
  setError(null);
@@ -97,6 +134,17 @@ function PocketSettingsTab({ rpcCall }) {
97
134
  ),
98
135
  ),
99
136
 
137
+ // Web Push 状态
138
+ h('div', { style: styles.block },
139
+ h('div', { style: { fontWeight: 600, fontSize: 13 } }, '🔔 推送通知 | Push notifications'),
140
+ h('div', { style: styles.muted },
141
+ pushState === 'on' ? '已开启:agent 跑完/出错时手机收到通知 | on: notified when tasks finish or fail'
142
+ : pushState === 'unsupported' ? '当前浏览器不支持推送 | this browser does not support push'
143
+ : pushState === 'insecure' ? '需要 HTTPS(公网隧道)或 localhost 才能开启推送 | push needs HTTPS (public tunnel) or localhost'
144
+ : pushState === 'checking' ? '检查中… | checking…'
145
+ : '推送未开启 | push not enabled'),
146
+ ),
147
+
100
148
  error ? h('div', { style: { color: 'var(--dsw-alias-state-error-primary,#dc2626)', fontSize: 12, marginTop: 8 } }, `❌ ${error}`) : null,
101
149
  );
102
150
  }
package/lib/index.js CHANGED
@@ -3,14 +3,27 @@
3
3
  // 设置页「设置 → 插件 → 手机访问」:
4
4
  // - 局域网二维码:自动显示(代理随插件启动)
5
5
  // - 公网二维码:点「开启公网」→ cloudflared 隧道 → 扫码即用,人在外面也能访问
6
+ // - Web Push:agent 跑完/出错 → 手机推送通知(需 HTTPS 公网路径或 localhost)
6
7
  // 手机看到的界面 = 电脑上的 dsh web,实时同步(WebSocket 透传)。
7
8
 
9
+ import { readFile } from 'node:fs/promises';
10
+ import { fileURLToPath } from 'node:url';
11
+
8
12
  import { createPocketService } from './service.mjs';
9
13
  import { installPocketRpc } from './web-rpc.js';
14
+ import { createPushService } from './push.mjs';
10
15
 
11
16
  const name = 'dsh-pocket';
12
17
  const inject = ['connection', 'webServer'];
13
18
 
19
+ // 服务 worker 源码(同源提供:/pocket-sw.js)
20
+ const SW_SOURCE = new URL('./pocket-sw.js', import.meta.url);
21
+ let swCache = null;
22
+ async function swScript() {
23
+ if (!swCache) swCache = await readFile(fileURLToPath(SW_SOURCE), 'utf8');
24
+ return swCache;
25
+ }
26
+
14
27
  export function apply(ctx, config = {}, internals = {}) {
15
28
  const logger = ctx.logger?.(name) ?? console;
16
29
  const dshPort = internals.dshPort ?? ctx.webServer?.port;
@@ -25,7 +38,52 @@ export function apply(ctx, config = {}, internals = {}) {
25
38
  internals,
26
39
  });
27
40
 
28
- const disposeRpc = installPocketRpc(ctx, { service, log: logger });
41
+ // Web Push 服务(web-push 库;测试可注入 stub)
42
+ const pushPromise = internals.pushPromise ?? createPushService({ internals });
43
+ pushPromise.catch((err) => logger.error('dsh-pocket: push service init failed | 推送服务初始化失败: %s', err?.message ?? err));
44
+
45
+ const disposers = [];
46
+ const disposeRpc = installPocketRpc(ctx, {
47
+ service,
48
+ push: internals.push ?? { vapidPublicKey: () => '', count: () => 0, subscribe: async () => false, unsubscribe: async () => false },
49
+ log: logger,
50
+ });
51
+ disposers.push(disposeRpc);
52
+
53
+ // 同源提供 Service Worker(Web Push 必需)
54
+ try {
55
+ const removeSw = ctx.webServer.register({
56
+ kind: 'exact',
57
+ path: '/pocket-sw.js',
58
+ handler: async (req, res) => {
59
+ res.writeHead(200, { 'content-type': 'application/javascript', 'cache-control': 'no-cache' });
60
+ res.end(await swScript());
61
+ },
62
+ });
63
+ disposers.push(removeSw);
64
+ } catch (err) {
65
+ logger.error('dsh-pocket: sw route register failed | SW 路由注册失败: %s', err?.message ?? err);
66
+ }
67
+
68
+ // Agent 回合结束/出错 → 推送通知(有订阅才发)
69
+ const onSessionEvent = (session, event) => {
70
+ if (event?.type !== 'turn/end') return;
71
+ const reason = event?.data?.reason ?? event?.reason;
72
+ if (!reason) return;
73
+ void pushPromise.then(async (push) => {
74
+ try {
75
+ if (reason.kind === 'error') {
76
+ await push.notify({ title: '❌ 任务失败 | Task failed', body: String(reason.error?.message ?? '').slice(0, 120) || 'Agent 执行出错', url: '/' });
77
+ } else if (reason.kind === 'completed') {
78
+ await push.notify({ title: '✅ 任务完成 | Task done', body: 'Agent 已完成任务,点开查看结果', url: '/' });
79
+ }
80
+ } catch (err) {
81
+ logger.error('dsh-pocket: push send failed | 推送发送失败: %s', err?.message ?? err);
82
+ }
83
+ });
84
+ };
85
+ const offSession = ctx.on('session/event', onSessionEvent);
86
+ disposers.push(offSession);
29
87
 
30
88
  // 代理随插件自动启动(局域网二维码开箱即用,零配置)
31
89
  void service.startProxy().then((proxy) => {
@@ -35,9 +93,9 @@ export function apply(ctx, config = {}, internals = {}) {
35
93
  });
36
94
 
37
95
  ctx.effect(() => async () => {
38
- disposeRpc();
96
+ for (const d of disposers.reverse()) { try { d(); } catch { /* 忽略 */ } }
39
97
  await service.dispose();
40
- }, 'dsh-pocket: stop proxy and tunnel');
98
+ }, 'dsh-pocket: stop proxy, tunnel and push');
41
99
  }
42
100
 
43
101
  export { name, inject };
@@ -0,0 +1,32 @@
1
+ // dsh-pocket Service Worker(经 webServer 同源提供:/pocket-sw.js)
2
+ // 职责:接收推送 → 显示通知;点击通知 → 聚焦/打开 DSH 页面。
3
+ const ICON = '/favicon.svg';
4
+
5
+ self.addEventListener('push', (event) => {
6
+ let data = {};
7
+ try {
8
+ data = event.data ? event.data.json() : {};
9
+ } catch { /* 非 JSON 载荷忽略 */ }
10
+ event.waitUntil(
11
+ self.registration.showNotification(data.title || 'DSH Pocket', {
12
+ body: data.body || '',
13
+ icon: ICON,
14
+ badge: ICON,
15
+ tag: data.tag || 'dsh-pocket',
16
+ data: { url: data.url || '/' },
17
+ }),
18
+ );
19
+ });
20
+
21
+ self.addEventListener('notificationclick', (event) => {
22
+ event.notification.close();
23
+ const url = event.notification.data?.url || '/';
24
+ event.waitUntil(
25
+ self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((windowClients) => {
26
+ for (const client of windowClients) {
27
+ if ('focus' in client) return client.focus();
28
+ }
29
+ return self.clients.openWindow(url);
30
+ }),
31
+ );
32
+ });
package/lib/push.mjs ADDED
@@ -0,0 +1,122 @@
1
+ // dsh-pocket Web Push 服务(Agent 跑完/出错 → 手机推送通知,即使没开页面)
2
+ //
3
+ // 原理:浏览器 Push API(Service Worker + pushManager.subscribe)把订阅
4
+ // 交给我们,我们在 dsh web 进程内用 web-push(VAPID 认证 + RFC 8030 协议)
5
+ // 直接推送到浏览器厂商的推送服务(Chrome→FCM / Firefox→Mozilla / Safari→APNs)。
6
+ // 免费、无需第三方账号;VAPID 密钥与订阅存本机。
7
+ //
8
+ // ⚠️ 硬性前提:Web Push 只在**安全上下文**可用(HTTPS 或 localhost)。
9
+ // - 公网隧道 https://xxx.trycloudflare.com ✅(人在外面的主场景)
10
+ // - 桌面 localhost:3080 ✅
11
+ // - 局域网 http://192.168.x.x ❌(明文 HTTP 没有 Push API)
12
+
13
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
14
+ import { homedir } from 'node:os';
15
+ import { join, dirname } from 'node:path';
16
+
17
+ const DATA_REL = join('dsh-pocket', 'push');
18
+ const VAPID_FILE = 'vapid.json';
19
+ const SUBS_FILE = 'subscriptions.json';
20
+
21
+ function defaultWebPush() {
22
+ // 动态 require(web-push 是 CJS)
23
+ return require('web-push');
24
+ }
25
+
26
+ /**
27
+ * 创建推送服务。
28
+ * @param {object} opts
29
+ * @param {string} [opts.home] $DSH_HOME(默认 ~/.dsh)
30
+ * @param {object} [opts.webpush] web-push 库(测试注入 stub)
31
+ * @param {string} [opts.subject] VAPID subject(mailto:)
32
+ * @param {object} [opts.internals] 测试注入:mkdir/write/read
33
+ * @returns {Promise<PushService>}
34
+ */
35
+ export async function createPushService({
36
+ home,
37
+ webpush = defaultWebPush(),
38
+ subject = 'mailto:shaobeichen@outlook.com',
39
+ internals = {},
40
+ } = {}) {
41
+ const dshHome = home ?? process.env.DSH_HOME ?? join(homedir(), '.dsh');
42
+ const dir = join(dshHome, DATA_REL);
43
+ const vapidPath = join(dir, VAPID_FILE);
44
+ const subsPath = join(dir, SUBS_FILE);
45
+ const mkdirFn = internals.mkdir ?? mkdir;
46
+ const read = internals.read ?? readFile;
47
+ const write = internals.write ?? writeFile;
48
+
49
+ await mkdirFn(dir, { recursive: true });
50
+
51
+ // VAPID 密钥:生成一次,持久化
52
+ let vapid;
53
+ try {
54
+ vapid = JSON.parse(await read(vapidPath, 'utf8'));
55
+ } catch {
56
+ vapid = webpush.generateVAPIDKeys();
57
+ await write(vapidPath, JSON.stringify(vapid, null, 2) + '\n', { mode: 0o600 });
58
+ }
59
+ webpush.setVapidDetails(subject, vapid.publicKey, vapid.privateKey);
60
+
61
+ // 订阅集合:endpoint → subscription
62
+ let subs = new Map();
63
+ try {
64
+ for (const s of JSON.parse(await read(subsPath, 'utf8')) ?? []) {
65
+ if (s?.endpoint) subs.set(s.endpoint, s);
66
+ }
67
+ } catch { /* 空开始 */ }
68
+
69
+ const persist = async () => {
70
+ await write(subsPath, JSON.stringify([...subs.values()], null, 2) + '\n', { mode: 0o600 });
71
+ };
72
+
73
+ return {
74
+ vapidPublicKey: () => vapid.publicKey,
75
+ count: () => subs.size,
76
+
77
+ /** 记录浏览器订阅。 */
78
+ async subscribe(subscription) {
79
+ if (!subscription?.endpoint || !subscription?.keys) return false;
80
+ subs.set(subscription.endpoint, subscription);
81
+ await persist();
82
+ return true;
83
+ },
84
+
85
+ /** 按 endpoint 取消订阅。 */
86
+ async unsubscribe(endpoint) {
87
+ const removed = subs.delete(endpoint);
88
+ if (removed) await persist();
89
+ return removed;
90
+ },
91
+
92
+ /**
93
+ * 推送通知到所有订阅;失效订阅自动清理。
94
+ * @param {object} opts
95
+ * @param {string} opts.title
96
+ * @param {string} [opts.body]
97
+ * @param {string} [opts.url] 点击通知打开的地址(默认 /)
98
+ * @param {object} [opts.data] 额外载荷
99
+ */
100
+ async notify({ title, body = '', url = '/', data = {} }) {
101
+ if (subs.size === 0) return 0;
102
+ const payload = JSON.stringify({ title, body, url, ...data });
103
+ let sent = 0;
104
+ for (const [endpoint, sub] of [...subs.entries()]) {
105
+ try {
106
+ await webpush.sendNotification(sub, payload, { TTL: 600 });
107
+ sent += 1;
108
+ } catch (err) {
109
+ // 410 Gone / 404 = 订阅失效,清理
110
+ const code = err?.statusCode;
111
+ if (code === 410 || code === 404) {
112
+ subs.delete(endpoint);
113
+ await persist();
114
+ }
115
+ }
116
+ }
117
+ return sent;
118
+ },
119
+
120
+ async dispose() { /* 无长连接需要清理 */ },
121
+ };
122
+ }
package/lib/web-rpc.js CHANGED
@@ -17,12 +17,12 @@ function fail(code, message) {
17
17
  }
18
18
 
19
19
  /** 注册 /dsh-pocket 逻辑通道(仅本机 loopback 可调)。 */
20
- export function installPocketRpc(ctx, { service, log = console }) {
20
+ export function installPocketRpc(ctx, { service, push, log = console }) {
21
21
  if (!ctx?.connection?.rpc?.handle) {
22
22
  log.warn?.('dsh-pocket: DSH Host Connection RPC unavailable — settings tab disabled | 无 Connection RPC,设置页不可用');
23
23
  return () => {};
24
24
  }
25
- return ctx.connection.rpc.handle(POCKET_RPC_CHANNEL, async (endpoint, _payload = {}, signal) => {
25
+ return ctx.connection.rpc.handle(POCKET_RPC_CHANNEL, async (endpoint, payload = {}, signal) => {
26
26
  if (signal?.aborted) return fail('cancelled', 'The request was cancelled.');
27
27
 
28
28
  try {
@@ -37,10 +37,24 @@ export function installPocketRpc(ctx, { service, log = console }) {
37
37
  service.stopTunnel();
38
38
  return ok(redactStatus(await service.status()));
39
39
  }
40
+ if (endpoint === POCKET_ENDPOINTS.pushVapidKey) {
41
+ return ok({ publicKey: push.vapidPublicKey() });
42
+ }
43
+ if (endpoint === POCKET_ENDPOINTS.pushSubscribe) {
44
+ const added = await push.subscribe(payload?.subscription);
45
+ return ok({ subscribed: added, count: push.count() });
46
+ }
47
+ if (endpoint === POCKET_ENDPOINTS.pushUnsubscribe) {
48
+ const removed = await push.unsubscribe(payload?.endpoint);
49
+ return ok({ removed, count: push.count() });
50
+ }
51
+ if (endpoint === POCKET_ENDPOINTS.pushStatus) {
52
+ return ok({ enabled: push.count() > 0, count: push.count() });
53
+ }
40
54
  return fail('bad-request', `Unknown endpoint: ${endpoint}`);
41
55
  } catch (err) {
42
56
  log.error?.('dsh-pocket: rpc %s failed | RPC 失败: %s', endpoint, err?.message ?? err);
43
- return fail('internal', err?.message ?? String(err));
57
+ return fail('bad-request', err?.message ?? String(err));
44
58
  }
45
59
  }, { authority: 'loopback' });
46
60
  }
package/package.json CHANGED
@@ -27,7 +27,8 @@
27
27
  },
28
28
  "dependencies": {
29
29
  "qrcode": "^1.5.4",
30
- "qrcode-terminal": "^0.12.0"
30
+ "qrcode-terminal": "^0.12.0",
31
+ "web-push": "^3.6.7"
31
32
  },
32
33
  "devDependencies": {
33
34
  "esbuild": "^0.25.9",
@@ -39,7 +40,7 @@
39
40
  "engines": {
40
41
  "node": ">=22"
41
42
  },
42
- "license": "MIT",
43
+ "license": "GPL-2.0",
43
44
  "keywords": [
44
45
  "deepseek-harness",
45
46
  "dsh",
@@ -76,5 +77,5 @@
76
77
  "access": "public",
77
78
  "registry": "https://registry.npmjs.org/"
78
79
  },
79
- "version": "1.0.0"
80
+ "version": "1.0.2"
80
81
  }