@forfeeling/dsh-media-player 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 forfeeling
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.
package/README.md CHANGED
@@ -1,3 +1,112 @@
1
- # Temporary Holding Version
1
+ # dsh-media-player
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > 📦 npm package renamed to **`@forfeeling/dsh-media-player`** (unscoped name taken by someone else). Install: `dsh plugin add @forfeeling/dsh-media-player`
4
+
5
+ Inline **video / animation player** for the [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) Web GUI.
6
+
7
+ The harness attachment system only accepts `png/jpeg/webp/gif`, and its README
8
+ lists video support as deferred — so generated videos could not be played
9
+ inside the chat. This plugin closes that gap with two small halves:
10
+
11
+ - **Host half** — registers a `media_show` tool that mints a short-lived,
12
+ opaque token URL for a local media file, plus a `/dsh-media` prefix route on
13
+ the Web server that streams the bytes with HTTP **Range** support (the
14
+ browser player can seek).
15
+ - **Client half** — a hand-authored browser bundle (no build step) that
16
+ registers a keyed `tool.call.toolview` renderer, so `media_show` tool calls
17
+ render as a native `<video controls>` / `<img>` card right in the chat flow.
18
+
19
+ ```
20
+ agent calls media_show(path) ──▶ token URL minted (in-memory, dies with process)
21
+ │ │
22
+ ▼ ▼
23
+ tool-call event in session ──▶ client renderer ──▶ <video src="/dsh-media/<token>">
24
+ │
25
+ ▼
26
+ webserver prefix route (Range-aware)
27
+ ```
28
+
29
+ ## Security posture
30
+
31
+ - The route **never accepts paths** — only random 96-bit tokens minted by the
32
+ tool, each bound to one absolute path at mint time. No directory listing, no
33
+ traversal surface.
34
+ - Tokens are in-memory only; a server restart invalidates them (the player
35
+ then shows a clean 404 and the agent can re-mint).
36
+ - `cache-control: no-store` on every media response.
37
+
38
+ ## Install
39
+
40
+ The plugin is a Cordis loader entry with a `dsh.client` browser bundle.
41
+
42
+ 1. Clone anywhere, e.g. `git clone https://github.com/<you>/dsh-media-player ~/dsh-media-player`.
43
+ 2. Link it into your Web profile so the bare specifier resolves:
44
+
45
+ ```bash
46
+ ln -s ~/dsh-media-player "$HOME/.dsh/profiles/web/node_modules/@forfeeling/dsh-media-player"
47
+ ```
48
+
49
+ (its only runtime dep, `@deepseek-ai/dsh-tools`, is symlinked the same way
50
+ from your dsh runtime store — see `scripts/link-deps.sh`)
51
+ 3. Enable it in `$HOME/.dsh/profiles/web/cordis.patch.yml`:
52
+
53
+ ```yaml
54
+ - insert:
55
+ - id: dsh-media-player
56
+ name: "@forfeeling/dsh-media-player"
57
+ ```
58
+
59
+ 4. **Restart `dsh web`** — client-package metadata is cached per name for the
60
+ life of the process, so plugin-set changes need a restart (bundle *content*
61
+ changes of an already-known package ride the HMR chain instead).
62
+ 5. Refresh the GUI. New chat sessions now expose `media_show`.
63
+
64
+ ## Usage
65
+
66
+ In any new chat session:
67
+
68
+ > 把 ./out.mp4 打开看看 / show me the video at ./out.mp4
69
+
70
+ The agent calls `media_show` and the conversation shows a native player card:
71
+
72
+ ```jsonc
73
+ // tool result
74
+ { "url": "/dsh-media/582e7e5a001f0ef59f18a947",
75
+ "kind": "video", "mime": "video/mp4",
76
+ "bytes": 7938745, "path": "/abs/path/out.mp4", "label": "optional caption" }
77
+ ```
78
+
79
+ Supported extensions: `mp4 webm mov m4v mkv gif webp png jpg jpeg`
80
+ (video kinds render `<video controls playsInline>`, image kinds `<img>`).
81
+
82
+ ## Development
83
+
84
+ ```bash
85
+ node test/unit.mjs # host + client unit validation (needs ffmpeg for the fallback clip)
86
+ ```
87
+
88
+ The suite stubs the Cordis context (tool registry, prompt sections, webserver
89
+ route table) and the browser module loader, then asserts: minting, error
90
+ paths, 200/206/416/404 route behavior, `output.render` shape, toolview
91
+ registration and the rendered element tree.
92
+
93
+ ### Why the client bundle is hand-written
94
+
95
+ DSH client bundles are classic scripts of the form
96
+ `window.__ModuleLoader__.load({ id, factory })` where `factory(require)`
97
+ receives the shell's `require` (seed words like `react`). The component here is
98
+ small enough to author directly in `React.createElement` form — no bundler, no
99
+ JSX, no build step to forget.
100
+
101
+ ### Gotchas learned the hard way
102
+
103
+ - Cordis `inject` is a **service-name array** (`["tools", "systemPrompt",
104
+ "webServer"]`); accessing an undeclared service throws at apply.
105
+ - Webserver prefix routes match `pathname.startsWith(prefix + "/")` — register
106
+ **without** a trailing slash.
107
+ - Loader entry `name` must be a package specifier resolvable from the profile
108
+ root (CJS resolution of `<spec>/package.json`), not a file path.
109
+
110
+ ## License
111
+
112
+ MIT
package/lib/client.js ADDED
@@ -0,0 +1,133 @@
1
+ /* dsh-media-player — client half (browser bundle).
2
+ * Hand-authored in the DSH client-module factory form (no build step):
3
+ * the loader runs factory(require) once; require("react") resolves to the
4
+ * shell's React instance. Registers a keyed `tool.call.toolview` renderer so
5
+ * `media_show` tool calls render as a native <video>/<img> player card.
6
+ */
7
+ window.__ModuleLoader__.load({
8
+ id: "dsh-media-player",
9
+ factory: (require) => {
10
+ var module = { exports: {} };
11
+ var exports = module.exports;
12
+ const react = require("react");
13
+ const e = react.createElement;
14
+
15
+ const CARD = {
16
+ margin: "4px 0 6px",
17
+ maxWidth: "100%",
18
+ };
19
+ const MEDIA = {
20
+ maxWidth: "100%",
21
+ maxHeight: "480px",
22
+ borderRadius: "12px",
23
+ background: "#000",
24
+ display: "block",
25
+ };
26
+ const CAPTION = {
27
+ fontSize: "12px",
28
+ lineHeight: "18px",
29
+ color: "var(--dsw-alias-label-secondary)",
30
+ marginTop: "4px",
31
+ };
32
+ const META = {
33
+ fontSize: "11px",
34
+ lineHeight: "16px",
35
+ color: "var(--dsw-alias-label-tertiary)",
36
+ marginTop: "2px",
37
+ overflowWrap: "anywhere",
38
+ };
39
+
40
+ function collectText(value, out) {
41
+ if (value == null) return;
42
+ if (typeof value === "string") {
43
+ out.push(value);
44
+ return;
45
+ }
46
+ if (Array.isArray(value)) {
47
+ for (const part of value) collectText(part, out);
48
+ return;
49
+ }
50
+ if (typeof value === "object") {
51
+ if (typeof value.text === "string") out.push(value.text);
52
+ if (value.content !== undefined) collectText(value.content, out);
53
+ }
54
+ }
55
+
56
+ function flattenBlock(block) {
57
+ const out = [];
58
+ if (block == null) return "";
59
+ collectText(block.content, out);
60
+ collectText(block.resultView, out);
61
+ collectText(block.text, out);
62
+ return out.join("\n");
63
+ }
64
+
65
+ function extractInfo(text) {
66
+ if (!text) return null;
67
+ try {
68
+ const obj = JSON.parse(text);
69
+ if (obj && typeof obj.url === "string") return obj;
70
+ } catch {
71
+ /* fall through to regex salvage */
72
+ }
73
+ const m = text.match(/"url"\s*:\s*"(\/dsh-media\/[A-Za-z0-9_-]+)"/);
74
+ if (m) return { url: m[1] };
75
+ return null;
76
+ }
77
+
78
+ function fmtBytes(bytes) {
79
+ if (typeof bytes !== "number" || !isFinite(bytes)) return "";
80
+ if (bytes >= 1048576) return `${(bytes / 1048576).toFixed(1)} MB`;
81
+ return `${Math.round(bytes / 1024)} KB`;
82
+ }
83
+
84
+ function MediaRow(props) {
85
+ const block = props && props.block;
86
+ const info = extractInfo(flattenBlock(block));
87
+ if (info === null || typeof info.url !== "string") {
88
+ return e(
89
+ "div",
90
+ { style: { color: "var(--dsw-alias-label-tertiary)", fontSize: "12px", padding: "2px 4px" } },
91
+ "media_show: result carries no playable URL",
92
+ );
93
+ }
94
+ const isImage = info.kind === "image";
95
+ const media = isImage
96
+ ? e("img", { src: info.url, alt: info.label || "media", style: MEDIA })
97
+ : e("video", {
98
+ src: info.url,
99
+ controls: true,
100
+ playsInline: true,
101
+ preload: "metadata",
102
+ style: MEDIA,
103
+ });
104
+ const size = fmtBytes(info.bytes);
105
+ const metaBits = [isImage ? "image" : "video", info.mime, size].filter(Boolean);
106
+ return e(
107
+ "div",
108
+ { style: CARD, "data-dsh-media-player": "card" },
109
+ media,
110
+ info.label ? e("div", { style: CAPTION }, info.label) : null,
111
+ e("div", { style: META }, metaBits.join(" · "), info.path ? ` · ${info.path}` : ""),
112
+ );
113
+ }
114
+
115
+ function apply(ctx) {
116
+ ctx.slots.inject("tool.call.toolview", () =>
117
+ ctx.slots.register(
118
+ {
119
+ name: "tool.call.toolview",
120
+ key: "media_show",
121
+ },
122
+ MediaRow,
123
+ ),
124
+ );
125
+ }
126
+
127
+ const inject = ["slots"];
128
+
129
+ exports.apply = apply;
130
+ exports.inject = inject;
131
+ return module.exports;
132
+ },
133
+ });
package/lib/index.js ADDED
@@ -0,0 +1,158 @@
1
+ /**
2
+ * dsh-media-player — host half.
3
+ *
4
+ * Registers the `media_show` tool (mints a short-lived, tokenized media URL for
5
+ * a local file) and a `/dsh-media/` prefix route on the Web server that streams
6
+ * the bytes with HTTP Range support so the browser player can seek.
7
+ *
8
+ * Security posture: the route never accepts paths — only opaque random tokens
9
+ * minted by the tool, each bound to one absolute path at mint time. Tokens die
10
+ * with the process; there is no directory listing and no path traversal surface.
11
+ */
12
+ import { createReadStream } from "node:fs";
13
+ import { stat } from "node:fs/promises";
14
+ import { extname, isAbsolute, resolve as resolvePath } from "node:path";
15
+ import { randomBytes } from "node:crypto";
16
+ import { defineTool } from "@deepseek-ai/dsh-tools";
17
+
18
+ export const name = "dsh-media-player";
19
+
20
+ /** Services required: tool registry, prompt sections, and the Web server route table. */
21
+ export const inject = ["tools", "systemPrompt", "webServer"];
22
+
23
+ const MIME = {
24
+ ".mp4": "video/mp4",
25
+ ".webm": "video/webm",
26
+ ".mov": "video/quicktime",
27
+ ".m4v": "video/x-m4v",
28
+ ".mkv": "video/x-matroska",
29
+ ".gif": "image/gif",
30
+ ".webp": "image/webp",
31
+ ".png": "image/png",
32
+ ".jpg": "image/jpeg",
33
+ ".jpeg": "image/jpeg",
34
+ };
35
+
36
+ export function apply(ctx) {
37
+ /** @type {Map<string, {abs: string, mime: string, bytes: number}>} */
38
+ const tokens = new Map();
39
+
40
+ ctx.tools.register(
41
+ defineTool({
42
+ name: "media_show",
43
+ description:
44
+ "Show a local video or animation inline in the chat as a native player card. Mints a short-lived URL served by this host; call it after generating a video/animation or whenever the user asks to view one. Supported: mp4, webm, mov, m4v, mkv, gif, webp, png, jpg.",
45
+ parameters: {
46
+ path: {
47
+ type: "string",
48
+ required: true,
49
+ description: "Absolute or workspace-relative path to the media file.",
50
+ },
51
+ label: {
52
+ type: "string",
53
+ description: "Optional caption rendered under the player.",
54
+ },
55
+ },
56
+ output: {
57
+ schema: {
58
+ type: "object",
59
+ additionalProperties: true,
60
+ properties: {
61
+ url: { type: "string" },
62
+ kind: { type: "string" },
63
+ mime: { type: "string" },
64
+ bytes: { type: "number" },
65
+ path: { type: "string" },
66
+ label: { type: "string" },
67
+ error: { type: "string" },
68
+ },
69
+ },
70
+ render(_args, value) {
71
+ return [{ type: "text", text: JSON.stringify(value) }];
72
+ },
73
+ },
74
+ isConcurrencySafe: () => true,
75
+ async execute(args, exec) {
76
+ const cwd = exec?.agent?.session?.header?.cwd ?? process.cwd();
77
+ const abs = isAbsolute(args.path) ? args.path : resolvePath(cwd, args.path);
78
+ const ext = extname(abs).toLowerCase();
79
+ const mime = MIME[ext];
80
+ if (mime === undefined) {
81
+ return { error: `unsupported media extension "${ext || "(none)"}"; supported: ${Object.keys(MIME).join(", ")}` };
82
+ }
83
+ const st = await stat(abs).catch(() => null);
84
+ if (st === null || !st.isFile()) {
85
+ return { error: `media file not found: ${args.path}` };
86
+ }
87
+ const token = randomBytes(12).toString("hex");
88
+ tokens.set(token, { abs, mime, bytes: st.size });
89
+ return {
90
+ url: `/dsh-media/${token}`,
91
+ kind: mime.startsWith("video/") ? "video" : "image",
92
+ mime,
93
+ bytes: st.size,
94
+ path: abs,
95
+ label: typeof args.label === "string" ? args.label : "",
96
+ };
97
+ },
98
+ }),
99
+ );
100
+
101
+ ctx.systemPrompt.section({
102
+ name: "tool:media_show",
103
+ order: 103,
104
+ text: "To display a local video or animation inline in the chat player, call media_show with its file path (mp4/webm/mov/gif/webp/png/jpg). Prefer it over describing generated video contents in prose; the player card renders in the conversation.",
105
+ });
106
+
107
+ const webServer = ctx.get("webServer");
108
+ const disposeRoute = webServer.register({
109
+ kind: "prefix",
110
+ path: "/dsh-media",
111
+ async handler(req, res) {
112
+ const pathname = new URL(req.url ?? "/", "http://internal").pathname;
113
+ const token = decodeURIComponent(pathname.slice("/dsh-media/".length));
114
+ const entry = tokens.get(token);
115
+ if (entry === undefined) {
116
+ res.writeHead(404, { "content-type": "text/plain; charset=utf-8" });
117
+ res.end("media token unknown or expired (tokens die with the server process)");
118
+ return;
119
+ }
120
+ const st = await stat(entry.abs).catch(() => null);
121
+ if (st === null || !st.isFile()) {
122
+ res.writeHead(404, { "content-type": "text/plain; charset=utf-8" });
123
+ res.end("media file no longer exists");
124
+ return;
125
+ }
126
+ const headers = {
127
+ "content-type": entry.mime,
128
+ "accept-ranges": "bytes",
129
+ "cache-control": "no-store",
130
+ };
131
+ const range = req.headers.range;
132
+ if (typeof range === "string" && range.startsWith("bytes=")) {
133
+ const m = /^bytes=(\d*)-(\d*)$/.exec(range.trim());
134
+ const start = m && m[1] !== "" ? Number(m[1]) : 0;
135
+ const end = m && m[2] !== "" ? Number(m[2]) : st.size - 1;
136
+ if (m === null || Number.isNaN(start) || Number.isNaN(end) || start > end || end >= st.size) {
137
+ res.writeHead(416, { "content-range": `bytes */${st.size}` });
138
+ res.end();
139
+ return;
140
+ }
141
+ res.writeHead(206, {
142
+ ...headers,
143
+ "content-range": `bytes ${start}-${end}/${st.size}`,
144
+ "content-length": String(end - start + 1),
145
+ });
146
+ createReadStream(entry.abs, { start, end }).pipe(res);
147
+ return;
148
+ }
149
+ res.writeHead(200, { ...headers, "content-length": String(st.size) });
150
+ createReadStream(entry.abs).pipe(res);
151
+ },
152
+ });
153
+
154
+ return () => {
155
+ disposeRoute();
156
+ tokens.clear();
157
+ };
158
+ }
package/package.json CHANGED
@@ -1,6 +1,32 @@
1
1
  {
2
2
  "name": "@forfeeling/dsh-media-player",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Inline video/animation player for the DSH Web GUI: media_show tool mints short-lived host-served URLs; client plugin renders a native <video> player in the chat flow.",
5
+ "type": "module",
6
+ "main": "lib/index.js",
7
+ "exports": {
8
+ ".": "./lib/index.js",
9
+ "./client": "./lib/client.js",
10
+ "./package.json": "./package.json"
11
+ },
12
+ "dsh": {
13
+ "client": {
14
+ "inject": [
15
+ "@deepseek-ai/dsh-client-runtime"
16
+ ],
17
+ "platform": "web"
18
+ }
19
+ },
20
+ "files": [
21
+ "lib",
22
+ "README.md",
23
+ "LICENSE"
24
+ ],
25
+ "publishConfig": {
26
+ "access": "public"
27
+ },
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "git+https://github.com/forfeeling/dsh-media-player.git"
31
+ }
32
+ }