@lincyaw/studio 0.2.0-rc.5 → 0.2.0-rc.51
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/README.md +9 -5
- package/package.json +4 -4
- package/src/cli.ts +6 -1
- package/src/messages.ts +22 -8
- package/src/proxy.ts +62 -0
- package/src/studio.ts +115 -16
package/README.md
CHANGED
|
@@ -1,22 +1,26 @@
|
|
|
1
1
|
# @lincyaw/studio
|
|
2
2
|
|
|
3
|
-
`presmium studio`: Presmium's workbench in one command. It starts [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) (MIT) with Presmium's bundle, [`@lincyaw/dsh`](https://www.npmjs.com/package/@lincyaw/dsh), and the workspace service of a directory (`presmium serve`, from
|
|
3
|
+
`presmium studio`: Presmium's workbench in one command. It starts [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) (MIT) with Presmium's bundle, [`@lincyaw/dsh`](https://www.npmjs.com/package/@lincyaw/dsh), and the workspace service of a directory (`presmium serve`, from its host package `@lincyaw/presmium`), and prints the one address to open in the browser. Experimental (0.x): it installs one exact version of DeepSeek Harness, `0.2.1-alpha.4` (about 865 MB with its dependencies).
|
|
4
4
|
|
|
5
5
|
Part of [Presmium](https://github.com/Lincyaw/presmium), which turns structured teaching documents into web pages, slides, Jupyter notebooks and narrated lectures.
|
|
6
6
|
|
|
7
7
|
## Usage
|
|
8
8
|
|
|
9
9
|
```sh
|
|
10
|
-
pnpm add -g @lincyaw/
|
|
11
|
-
presmium
|
|
10
|
+
pnpm add -g @lincyaw/presmium
|
|
11
|
+
presmium studio [dir] [--port <n>] [--host <addr>]
|
|
12
12
|
```
|
|
13
13
|
|
|
14
|
-
In a project with `pnpm add -D @lincyaw/
|
|
14
|
+
Studio is included with Presmium. In a project with `pnpm add -D @lincyaw/presmium`, use `pnpm exec presmium studio`. The separate `presmium-studio` command remains available when this package is installed directly; it runs the `presmium` command on PATH (install it with `pnpm add -g @lincyaw/presmium`).
|
|
15
15
|
|
|
16
|
-
`dir` is a workspace root (`presmium.workspace.yaml`) or a deck's directory, as for `presmium serve`. The workbench listens on 127.0.0.1, port 4320 by default (a free port when that one is in use); `--host <addr>` makes it listen on one address
|
|
16
|
+
`dir` is a workspace root (`presmium.workspace.yaml`) or a deck's directory, as for `presmium serve`. The workbench listens on 127.0.0.1, port 4320 by default (a free port when that one is in use); `--host <addr>` makes it listen on one local IP address, and `--host 0.0.0.0` makes it listen on all local IPv4 network interfaces, with no login. Network access prints one address for each local network interface.
|
|
17
17
|
|
|
18
18
|
Sessions use the workspace root as their working directory and can read and write files throughout it. Opening another lecture changes document context, not the session or its directory.
|
|
19
19
|
|
|
20
|
+
External MCP clients connect over Streamable HTTP at `http://127.0.0.1:4321/mcp`. Set `Authorization: Bearer <token>` using the token file named at startup. Studio keeps this credential for the same launch directory across restarts and upgrades, separately from its internal service credential. With `--host 0.0.0.0`, use the printed network MCP address from other machines. The address and credential need configuring once; clients reconnect after Studio restarts.
|
|
21
|
+
|
|
22
|
+
The workspace service and MCP share fixed port 4321. If it is occupied, Studio reports an error instead of changing the address. Use `--preview-port <n>` to choose another fixed port for a second workspace, or `--preview-port 0` to explicitly request a temporary port. Behind a reverse proxy, MCP is at `mcp` under `--preview-url`.
|
|
23
|
+
|
|
20
24
|
The model is chosen in the workbench's model settings, or given by the environment: `DEEPSEEK_API_KEY`, or `PRESMIUM_MODEL_URL`, `PRESMIUM_MODEL_KEY` and `PRESMIUM_MODEL_PROVIDER` for a Messages-compatible service. DeepSeek Harness's home for the workbench (its sessions, model settings and credentials, and the log) is `$XDG_STATE_HOME/presmium/studio`, never your own `~/.dsh`. Each installation (a version, or a checkout) has its own profile there, `profiles/presmium-studio-<hash>`, and its own log, `presmium-studio-<hash>.log`, so Studios of different installations can run at the same time without loading each other's code. Sessions and credentials are shared; a new installation's profile starts with the settings of the one used last.
|
|
21
25
|
|
|
22
26
|
Startup prints the log path to stderr and streams workspace-service logs there while running. The file keeps timestamped output from both processes. Preview logs identify the document, renderer, request, cache/fallback choice and elapsed time; export logs identify the job and phase. A backend preview marked ready means its address is prepared; browser loading and the preview handshake may still be pending. The host's output, including its login URL, stays in the log file.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lincyaw/studio",
|
|
3
|
-
"version": "0.2.0-rc.
|
|
3
|
+
"version": "0.2.0-rc.51",
|
|
4
4
|
"description": "presmium studio: Presmium's workbench on DeepSeek Harness in one command, with the workspace service of a directory (experimental)",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -37,11 +37,11 @@
|
|
|
37
37
|
],
|
|
38
38
|
"dependencies": {
|
|
39
39
|
"@deepseek-ai/dsh": "0.2.1-alpha.4",
|
|
40
|
+
"http-proxy-3": "2.0.1",
|
|
40
41
|
"jiti": "^2.7.0",
|
|
41
|
-
"@lincyaw/dsh": "0.2.0-rc.
|
|
42
|
-
"@lincyaw/presmium": "1.0.0-rc.6"
|
|
42
|
+
"@lincyaw/dsh": "0.2.0-rc.51"
|
|
43
43
|
},
|
|
44
44
|
"devDependencies": {
|
|
45
|
-
"@lincyaw/cli": "1.0.0-rc.
|
|
45
|
+
"@lincyaw/cli": "1.0.0-rc.52"
|
|
46
46
|
}
|
|
47
47
|
}
|
package/src/cli.ts
CHANGED
|
@@ -61,9 +61,14 @@ export async function main(argv: string[], options: MainOptions = {}): Promise<n
|
|
|
61
61
|
return 2
|
|
62
62
|
}
|
|
63
63
|
process.stdout.write(`studio ${studio.url}\n`)
|
|
64
|
+
for (const url of studio.networkUrls) process.stdout.write(`network ${url}\n`)
|
|
65
|
+
process.stdout.write(`mcp ${studio.mcp.url}\n`)
|
|
66
|
+
process.stderr.write(`${t.mcpToken(studio.mcp.tokenFile)}\n`)
|
|
64
67
|
process.stderr.write(`${t.log(studio.log)}\n`)
|
|
65
68
|
if (values.host && values.host !== '127.0.0.1' && values.host !== '::1' && !values['public-url']) {
|
|
66
|
-
process.stderr.write(`${
|
|
69
|
+
process.stderr.write(`${studio.networkUrls.length
|
|
70
|
+
? t.openOnAllNetworks(new URL(studio.url).port, new URL(studio.workspaceServerUrl).port)
|
|
71
|
+
: t.openOnNetwork(values.host, new URL(studio.url).port, new URL(studio.workspaceServerUrl).port)}\n`)
|
|
67
72
|
}
|
|
68
73
|
|
|
69
74
|
const signals = ['SIGINT', 'SIGTERM', 'SIGHUP'] as const
|
package/src/messages.ts
CHANGED
|
@@ -10,14 +10,19 @@ export interface StudioMessages {
|
|
|
10
10
|
notDirectory(dir: string): string
|
|
11
11
|
log(file: string): string
|
|
12
12
|
openOnNetwork(address: string, port: string, previewPort: string): string
|
|
13
|
+
openOnAllNetworks(port: string, previewPort: string): string
|
|
13
14
|
ended(how: string, log: string): string
|
|
14
15
|
portInUse(port: number, address: string): string
|
|
16
|
+
previewPortInUse(port: number, address: string): string
|
|
17
|
+
mcpToken(file: string): string
|
|
18
|
+
badMcpToken(file: string): string
|
|
15
19
|
noFreePort(address: string): string
|
|
16
20
|
badHost(address: string): string
|
|
17
21
|
wholeLog(message: string, file: string): string
|
|
18
22
|
serviceEnded: string
|
|
19
23
|
appEnded: string
|
|
20
24
|
modelVariables(variables: readonly string[], unset: string[]): string
|
|
25
|
+
presmiumMissing: string
|
|
21
26
|
}
|
|
22
27
|
|
|
23
28
|
export const STUDIO_MESSAGES: Record<Locale, StudioMessages> = {
|
|
@@ -32,24 +37,29 @@ presmium-studio-<散列>.log(每个安装一个)保存在 $XDG_STATE_HOME/pr
|
|
|
32
37
|
|
|
33
38
|
选项:
|
|
34
39
|
--port <端口> Presmium Studio 的端口(默认为 4320,被占用时取空闲端口)
|
|
35
|
-
--host <地址>
|
|
40
|
+
--host <地址> 改为监听本机在局域网中的一个 IP 地址或 0.0.0.0,且没有登录:
|
|
36
41
|
任何能访问这个端口的人都以你的身份操作
|
|
37
42
|
--public-url <网址> 有反向代理在前面时浏览器打开的根地址(例如 Presmium 云端);
|
|
38
43
|
它的主机受信任,打印的网址用它。代理需保留 Host 并转发 WebSocket
|
|
39
44
|
--preview-url <网址> 同样情况下预览所在的地址,由代理转发到工作区服务;可以带路径,
|
|
40
45
|
此时它必须与 Studio 不同源,否则预览中文稿的代码能读到 Studio 的会话
|
|
41
|
-
--preview-port <端口>
|
|
46
|
+
--preview-port <端口> 工作区服务与 HTTP MCP 的固定端口(默认 4321);0 为随机端口
|
|
42
47
|
-h, --help 显示本说明`,
|
|
43
48
|
badPort: value => `--port 需要 0 到 65535 之间的端口号,而不是“${value}”。`,
|
|
44
49
|
badUrl: (option, value) => `${option} 需要一个完整的网址,例如 https://studio.example.com/,而不是“${value}”。`,
|
|
50
|
+
presmiumMissing: 'presmium-studio 找不到 presmium 命令。Presmium Studio 随 Presmium 一起安装:请运行 pnpm add -g @lincyaw/presmium,然后用 presmium studio 启动。',
|
|
45
51
|
unexpectedArgument: argument => `多余的参数“${argument}”。只能给出一个目录。`,
|
|
46
52
|
notDirectory: dir => `${dir} 不是目录。请给出工作区的根目录或一份文稿所在的目录。`,
|
|
47
53
|
log: file => `presmium studio: 日志在 ${file}`,
|
|
48
54
|
openOnNetwork: (address, port, previewPort) => `presmium studio: 正在 ${address} 上监听,局域网中的设备可以访问,且没有登录:任何能用上面的网址访问端口 ${port}(以及预览的端口 ${previewPort})的人都以你的身份使用这个工作区(编辑、运行代码、使用你的模型)。请只在可信的网络中使用;不加 --host 时只在本机监听。`,
|
|
55
|
+
openOnAllNetworks: (port, previewPort) => `presmium studio: 正在全部局域网网络接口上监听,且没有登录:任何能用上面的网址访问端口 ${port}(以及预览的端口 ${previewPort})的人都以你的身份使用这个工作区(编辑、运行代码、使用你的模型)。请只在可信的网络中使用;不加 --host 时只在本机监听。`,
|
|
49
56
|
ended: (how, log) => `presmium studio: ${how}。日志在 ${log}`,
|
|
50
57
|
portInUse: (port, address) => `${address} 的端口 ${port} 已被占用。请用 --port 指定另一个端口。`,
|
|
58
|
+
previewPortInUse: (port, address) => `${address} 的工作区与 MCP 端口 ${port} 已被占用。请停止占用它的服务,或用 --preview-port 指定另一个固定端口。`,
|
|
59
|
+
mcpToken: file => `presmium studio: MCP 客户端使用 HTTP(Streamable HTTP),从 ${file} 读取访问令牌,设置 Authorization: Bearer <访问令牌>;同一目录重启与升级后保持不变。`,
|
|
60
|
+
badMcpToken: file => `MCP 访问令牌文件 ${file} 无效。请移走该文件后重试,并在客户端更新访问令牌。`,
|
|
51
61
|
noFreePort: address => `${address} 上没有空闲的端口。请停止占用端口的服务后重试。`,
|
|
52
|
-
badHost: address => `--host
|
|
62
|
+
badHost: address => `--host 需要本机的一个 IP 地址,例如 192.168.0.21,也可以使用 0.0.0.0,而不是“${address}”。`,
|
|
53
63
|
wholeLog: (message, file) => `${message}${message.endsWith('\n') ? '' : '。'}完整的日志在 ${file}`,
|
|
54
64
|
serviceEnded: '工作区服务(presmium serve)已停止',
|
|
55
65
|
appEnded: 'Presmium Studio 的应用进程已停止',
|
|
@@ -67,30 +77,34 @@ presmium-studio-<hash>.log (one per installation) are kept in $XDG_STATE_HOME/pr
|
|
|
67
77
|
|
|
68
78
|
Options:
|
|
69
79
|
--port <n> Presmium Studio’s port (default: 4320, or a free one when that is in use)
|
|
70
|
-
--host <addr> listen on
|
|
71
|
-
no login: whoever reaches the port works as you
|
|
80
|
+
--host <addr> listen on one local IP address, or on all IPv4 network interfaces with 0.0.0.0,
|
|
81
|
+
with no login: whoever reaches the port works as you
|
|
72
82
|
--public-url <url> the root browsers open when a reverse proxy fronts Studio (as in Presmium
|
|
73
83
|
Cloud): its host is trusted, and the printed address uses it. The proxy keeps Host and
|
|
74
84
|
forwards WebSockets
|
|
75
85
|
--preview-url <url> in that case, the address of the previews, forwarded to the workspace service; it
|
|
76
86
|
may have a path, and should be another origin than Studio’s, or the documents’ code in
|
|
77
87
|
previews can read Studio’s session
|
|
78
|
-
--preview-port <n>
|
|
88
|
+
--preview-port <n> fixed workspace-service and HTTP MCP port (default: 4321); 0 requests a random port
|
|
79
89
|
-h, --help show this help`,
|
|
80
90
|
badPort: value => `--port takes a port number from 0 to 65535, not “${value}”.`,
|
|
81
91
|
badUrl: (option, value) => `${option} takes a full address, such as https://studio.example.com/, not “${value}”.`,
|
|
92
|
+
presmiumMissing: 'presmium-studio can’t find the presmium command. Presmium Studio comes with Presmium: run pnpm add -g @lincyaw/presmium, then start it with presmium studio.',
|
|
82
93
|
unexpectedArgument: argument => `Unexpected argument “${argument}”. Give one directory.`,
|
|
83
94
|
notDirectory: dir => `${dir} is not a directory. Give the workspace root, or the directory of a document.`,
|
|
84
95
|
log: file => `presmium studio: log ${file}`,
|
|
85
96
|
openOnNetwork: (address, port, previewPort) => `presmium studio: listening on ${address}, on the local network, with no login: anyone who reaches port ${port} (and the previews’ port ${previewPort}) with the address above works in this workspace as you (edits, runs code, uses your model). Use it on a network you trust; without --host it listens on this machine only.`,
|
|
97
|
+
openOnAllNetworks: (port, previewPort) => `presmium studio: listening on all local network interfaces, with no login: anyone who reaches port ${port} (and the previews’ port ${previewPort}) with the addresses above works in this workspace as you (edits, runs code, uses your model). Use it on a network you trust; without --host it listens on this machine only.`,
|
|
86
98
|
ended: (how, log) => `presmium studio: ${how}; the log is ${log}`,
|
|
87
99
|
portInUse: (port, address) => `Port ${port} of ${address} is in use. Give another with --port.`,
|
|
100
|
+
previewPortInUse: (port, address) => `Workspace and MCP port ${port} of ${address} is in use. Stop the service using it, or choose another fixed port with --preview-port.`,
|
|
101
|
+
mcpToken: file => `presmium studio: MCP clients use HTTP (Streamable HTTP); read the access token from ${file} and set Authorization: Bearer <value>. It stays the same for this directory across restarts and upgrades.`,
|
|
102
|
+
badMcpToken: file => `MCP access token file ${file} is invalid. Move it aside and retry, then update the access token in your clients.`,
|
|
88
103
|
noFreePort: address => `There is no free port on ${address}. Stop a service that uses one, then retry.`,
|
|
89
|
-
badHost: address => `--host takes one
|
|
104
|
+
badHost: address => `--host takes one local IP address, such as 192.168.0.21, or 0.0.0.0 to listen on all IPv4 network interfaces, not “${address}”.`,
|
|
90
105
|
wholeLog: (message, file) => `${message.endsWith('\n') ? message : `${message}; `}the whole log is ${file}`,
|
|
91
106
|
serviceEnded: 'the workspace service (presmium serve) ended',
|
|
92
107
|
appEnded: 'the Presmium Studio app ended',
|
|
93
108
|
modelVariables: (variables, unset) => `${variables.join(', ')} go together; ${unset.join(' and ')} ${unset.length > 1 ? 'are' : 'is'} not set.`,
|
|
94
109
|
},
|
|
95
110
|
}
|
|
96
|
-
|
package/src/proxy.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { createServer } from 'node:http'
|
|
2
|
+
import type { Server } from 'node:http'
|
|
3
|
+
import type { Duplex } from 'node:stream'
|
|
4
|
+
import { createProxyServer } from 'http-proxy-3'
|
|
5
|
+
|
|
6
|
+
export interface ProxyOptions {
|
|
7
|
+
host: string
|
|
8
|
+
port: number
|
|
9
|
+
target: string
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface Proxy {
|
|
13
|
+
close(): Promise<void>
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function listen(server: Server, port: number, host: string): Promise<void> {
|
|
17
|
+
return new Promise((resolve, reject) => {
|
|
18
|
+
server.once('error', reject)
|
|
19
|
+
server.listen(port, host, () => {
|
|
20
|
+
server.off('error', reject)
|
|
21
|
+
resolve()
|
|
22
|
+
})
|
|
23
|
+
})
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export async function startProxy(options: ProxyOptions): Promise<Proxy> {
|
|
27
|
+
const proxy = createProxyServer({ ws: true, xfwd: false })
|
|
28
|
+
proxy.on('error', (error: Error, _request: unknown, response: unknown) => {
|
|
29
|
+
const answer = response as { writeHead?: (status: number, headers: Record<string, string>) => void, end?: (body: string) => void, destroy?: () => void, headersSent?: boolean } | undefined
|
|
30
|
+
if (answer?.writeHead && answer.end && !answer.headersSent) {
|
|
31
|
+
answer.writeHead(502, { 'Content-Type': 'text/plain; charset=utf-8' })
|
|
32
|
+
answer.end(`proxy error: ${error.message}`)
|
|
33
|
+
} else {
|
|
34
|
+
answer?.destroy?.()
|
|
35
|
+
}
|
|
36
|
+
})
|
|
37
|
+
const upgrades = new Set<Duplex>()
|
|
38
|
+
const server: Server = createServer((request, response) => {
|
|
39
|
+
request.url = request.url ?? '/'
|
|
40
|
+
proxy.web(request, response, { target: options.target })
|
|
41
|
+
})
|
|
42
|
+
server.on('upgrade', (request, socket, head) => {
|
|
43
|
+
upgrades.add(socket)
|
|
44
|
+
socket.once('close', () => upgrades.delete(socket))
|
|
45
|
+
request.url = request.url ?? '/'
|
|
46
|
+
proxy.ws(request, socket, head, { target: options.target })
|
|
47
|
+
})
|
|
48
|
+
try {
|
|
49
|
+
await listen(server, options.port, options.host)
|
|
50
|
+
} catch (error) {
|
|
51
|
+
proxy.close()
|
|
52
|
+
throw error
|
|
53
|
+
}
|
|
54
|
+
return {
|
|
55
|
+
close: () => new Promise((resolve) => {
|
|
56
|
+
server.close(() => resolve())
|
|
57
|
+
server.closeAllConnections()
|
|
58
|
+
for (const socket of upgrades) socket.destroy()
|
|
59
|
+
proxy.close()
|
|
60
|
+
}),
|
|
61
|
+
}
|
|
62
|
+
}
|
package/src/studio.ts
CHANGED
|
@@ -1,18 +1,21 @@
|
|
|
1
1
|
import { createHash, randomBytes } from 'node:crypto'
|
|
2
|
-
import { closeSync, copyFileSync, existsSync, mkdirSync, openSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from 'node:fs'
|
|
2
|
+
import { chmodSync, closeSync, copyFileSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from 'node:fs'
|
|
3
3
|
import { createRequire } from 'node:module'
|
|
4
4
|
import { createServer, isIP } from 'node:net'
|
|
5
5
|
import type { AddressInfo } from 'node:net'
|
|
6
|
-
import { homedir } from 'node:os'
|
|
7
|
-
import { dirname, join, resolve } from 'node:path'
|
|
6
|
+
import { homedir, hostname, networkInterfaces } from 'node:os'
|
|
7
|
+
import { delimiter, dirname, join, resolve } from 'node:path'
|
|
8
8
|
import { fileURLToPath } from 'node:url'
|
|
9
9
|
import { bracketIPv6, dshBin, inheritedEnv, isLauncherVariable, launchArgs, launchEnv, launchNode, launchWorkspaceServer, WEB_READY, writeProfile } from '@lincyaw/dsh/launch'
|
|
10
10
|
import type { LaunchedProcess } from '@lincyaw/dsh/launch'
|
|
11
11
|
import { STUDIO_MESSAGES, systemLocale } from './messages.ts'
|
|
12
12
|
import { modelEnv } from './model-env.ts'
|
|
13
|
+
import { startProxy } from './proxy.ts'
|
|
14
|
+
import type { Proxy } from './proxy.ts'
|
|
13
15
|
|
|
14
16
|
const PROFILE = 'presmium-studio'
|
|
15
17
|
const DEFAULT_PORT = 4320
|
|
18
|
+
const DEFAULT_PREVIEW_PORT = 4321
|
|
16
19
|
const LOG_BYTES = 16 << 20
|
|
17
20
|
|
|
18
21
|
const PACKAGE_DIR = fileURLToPath(new URL('..', import.meta.url))
|
|
@@ -28,7 +31,7 @@ export interface StudioOptions {
|
|
|
28
31
|
*/
|
|
29
32
|
publicUrl?: string
|
|
30
33
|
previewUrl?: string
|
|
31
|
-
/** The workspace service
|
|
34
|
+
/** The workspace service and HTTP MCP port (default: 4321). Zero explicitly requests a free port. */
|
|
32
35
|
previewPort?: number
|
|
33
36
|
env?: NodeJS.ProcessEnv
|
|
34
37
|
presmium?: string
|
|
@@ -38,7 +41,9 @@ export interface StudioOptions {
|
|
|
38
41
|
|
|
39
42
|
export interface Studio {
|
|
40
43
|
url: string
|
|
44
|
+
networkUrls: string[]
|
|
41
45
|
workspaceServerUrl: string
|
|
46
|
+
mcp: { url: string, tokenFile: string }
|
|
42
47
|
root: string
|
|
43
48
|
home: string
|
|
44
49
|
log: string
|
|
@@ -52,6 +57,23 @@ function studioHome(env: NodeJS.ProcessEnv = process.env): string {
|
|
|
52
57
|
return join(env.XDG_STATE_HOME || join(env.HOME || homedir(), '.local', 'state'), 'presmium', 'studio')
|
|
53
58
|
}
|
|
54
59
|
|
|
60
|
+
/** Independent of the installation/profile so upgrades and restarts preserve external MCP access. */
|
|
61
|
+
function workspaceCredential(home: string, dir: string): { token: string, file: string } {
|
|
62
|
+
const directory = join(home, 'mcp')
|
|
63
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 })
|
|
64
|
+
const id = createHash('sha256').update(realpathSync(dir)).digest('hex').slice(0, 32)
|
|
65
|
+
const file = join(directory, `${id}.token`)
|
|
66
|
+
try {
|
|
67
|
+
writeFileSync(file, `${randomBytes(24).toString('base64url')}\n`, { flag: 'wx', mode: 0o600 })
|
|
68
|
+
} catch (error) {
|
|
69
|
+
if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error
|
|
70
|
+
}
|
|
71
|
+
chmodSync(file, 0o600)
|
|
72
|
+
const token = readFileSync(file, 'utf8').trim()
|
|
73
|
+
if (!/^[A-Za-z0-9_-]{32}$/.test(token)) throw new Error(STUDIO_MESSAGES[systemLocale()].badMcpToken(file))
|
|
74
|
+
return { token, file }
|
|
75
|
+
}
|
|
76
|
+
|
|
55
77
|
/** The bundle `@lincyaw/dsh` this package depends on: the directory the profile links to. */
|
|
56
78
|
function bundleDir(): string {
|
|
57
79
|
return realpathSync(dirname(createRequire(join(PACKAGE_DIR, 'package.json')).resolve('@lincyaw/dsh/package.json')))
|
|
@@ -81,12 +103,59 @@ function installProfile(home: string, bundle: string): string {
|
|
|
81
103
|
return name
|
|
82
104
|
}
|
|
83
105
|
|
|
84
|
-
/**
|
|
85
|
-
|
|
86
|
-
|
|
106
|
+
/**
|
|
107
|
+
* The `presmium` command a Studio started by itself (`presmium-studio`) runs: `@lincyaw/presmium` where it can be
|
|
108
|
+
* resolved from here, else the one on PATH. `presmium studio` passes its own instead; Studio does not depend on it, which
|
|
109
|
+
* would make the two packages depend on each other.
|
|
110
|
+
*/
|
|
111
|
+
function presmiumBin(env: NodeJS.ProcessEnv, missing: string): string {
|
|
112
|
+
try {
|
|
113
|
+
return join(dirname(createRequire(join(PACKAGE_DIR, 'package.json')).resolve('@lincyaw/presmium/package.json')), 'bin', 'presmium.mjs')
|
|
114
|
+
} catch {}
|
|
115
|
+
const names = process.platform === 'win32' ? ['presmium.cmd', 'presmium'] : ['presmium']
|
|
116
|
+
for (const dir of (env.PATH ?? '').split(delimiter).filter(Boolean)) {
|
|
117
|
+
for (const name of names) {
|
|
118
|
+
const script = existsSync(join(dir, name)) ? nodeScript(join(dir, name)) : undefined
|
|
119
|
+
if (script) return script
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
throw new Error(missing)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** The Node script a command runs: the file itself (an npm link), or the target a pnpm shim names. */
|
|
126
|
+
function nodeScript(command: string): string | undefined {
|
|
127
|
+
try {
|
|
128
|
+
const file = realpathSync(command)
|
|
129
|
+
const head = readFileSync(file, 'utf8').slice(0, 4096)
|
|
130
|
+
if (/\.[cm]?js$/.test(file) || /^#!.*\bnode\b/.test(head)) return file
|
|
131
|
+
const target = /cmd-shim-target=(.+)$/m.exec(head)?.[1]?.trim()
|
|
132
|
+
return target && existsSync(target) ? target : undefined
|
|
133
|
+
} catch {
|
|
134
|
+
return undefined
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const WILDCARD = /^0\.0\.0\.0$/
|
|
139
|
+
|
|
140
|
+
function networkHosts(): string[] {
|
|
141
|
+
return [...new Set(Object.values(networkInterfaces()).flatMap(entries => entries ?? []).filter(entry => entry.family === 'IPv4' && !entry.internal).map(entry => entry.address))]
|
|
87
142
|
}
|
|
88
143
|
|
|
89
|
-
|
|
144
|
+
function authority(host: string, port: number): string {
|
|
145
|
+
return `${bracketIPv6(host)}:${port}`
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function httpOrigin(host: string, port: number): string {
|
|
149
|
+
return `http://${authority(host, port)}`
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function studioUrl(backend: string, publicUrl: string | undefined, host: string, port: number): string {
|
|
153
|
+
const token = new URL(backend).searchParams.get('token')
|
|
154
|
+
if (!token) throw new Error('DeepSeek Harness printed an address without its launch token')
|
|
155
|
+
const url = new URL(publicUrl ?? `http://${authority(host, port)}/`)
|
|
156
|
+
url.searchParams.set('token', token)
|
|
157
|
+
return url.href
|
|
158
|
+
}
|
|
90
159
|
|
|
91
160
|
function freePort(listenAddress: string, port: number): Promise<number | undefined> {
|
|
92
161
|
return new Promise((done) => {
|
|
@@ -147,31 +216,49 @@ export async function startStudio(options: StudioOptions): Promise<Studio> {
|
|
|
147
216
|
const env = options.env ?? process.env
|
|
148
217
|
const t = STUDIO_MESSAGES[systemLocale(env)]
|
|
149
218
|
const { listenAddress } = options
|
|
150
|
-
if (listenAddress !== undefined &&
|
|
219
|
+
if (listenAddress !== undefined && isIP(listenAddress) === 0) {
|
|
151
220
|
throw new Error(t.badHost(listenAddress))
|
|
152
221
|
}
|
|
153
|
-
const
|
|
154
|
-
const
|
|
222
|
+
const boundAddress = listenAddress ?? '127.0.0.1'
|
|
223
|
+
const wildcard = WILDCARD.test(boundAddress)
|
|
224
|
+
const previewPort = options.previewPort ?? DEFAULT_PREVIEW_PORT
|
|
225
|
+
if (previewPort !== 0 && await freePort(boundAddress, previewPort) === undefined) throw new Error(t.previewPortInUse(previewPort, boundAddress))
|
|
226
|
+
const port = await choosePort(boundAddress, options.port)
|
|
227
|
+
const dshAddress = wildcard ? '127.0.0.1' : boundAddress
|
|
228
|
+
const dshPort = wildcard ? await choosePort(dshAddress, undefined) : port
|
|
229
|
+
const hosts = wildcard ? networkHosts() : []
|
|
230
|
+
const primaryHost = hosts[0] ?? dshAddress
|
|
231
|
+
const origins = options.publicUrl
|
|
232
|
+
? [new URL(options.publicUrl).origin, ...hosts.map(host => httpOrigin(host, port)), httpOrigin('127.0.0.1', port)]
|
|
233
|
+
: wildcard
|
|
234
|
+
? [...hosts.map(host => httpOrigin(host, port)), httpOrigin('127.0.0.1', port), `http://localhost:${port}`]
|
|
235
|
+
: [httpOrigin(boundAddress, port), ...boundAddress === '127.0.0.1' ? [`http://localhost:${port}`] : []]
|
|
155
236
|
|
|
156
237
|
const home = studioHome(env)
|
|
157
238
|
mkdirSync(home, { recursive: true, mode: 0o700 })
|
|
158
239
|
const bundle = bundleDir()
|
|
159
240
|
const profile = installProfile(home, bundle)
|
|
160
241
|
writeProfile(home, profile, 'web', bundle)
|
|
242
|
+
const { token: mcpToken, file: tokenFile } = workspaceCredential(home, options.dir)
|
|
161
243
|
const log = new Log(join(home, `${profile}.log`))
|
|
162
244
|
const serviceToken = randomBytes(24).toString('base64url')
|
|
163
245
|
const started: LaunchedProcess[] = []
|
|
246
|
+
let proxy: Proxy | undefined
|
|
164
247
|
const stopAll = async () => {
|
|
248
|
+
await proxy?.close()
|
|
249
|
+
proxy = undefined
|
|
165
250
|
for (const launched of started.reverse()) await launched.stop()
|
|
166
251
|
started.length = 0
|
|
167
252
|
}
|
|
168
253
|
|
|
169
254
|
try {
|
|
255
|
+
const presmium = options.presmium ?? presmiumBin(env, t.presmiumMissing)
|
|
170
256
|
const server = launchWorkspaceServer({
|
|
171
|
-
presmium
|
|
257
|
+
presmium,
|
|
172
258
|
dir: resolve(options.dir),
|
|
173
259
|
serviceToken,
|
|
174
|
-
|
|
260
|
+
mcpToken,
|
|
261
|
+
port: previewPort,
|
|
175
262
|
args: [
|
|
176
263
|
...listenAddress ? ['--host', listenAddress] : [],
|
|
177
264
|
...origins.flatMap(origin => ['--preview-origin', origin]),
|
|
@@ -182,10 +269,16 @@ export async function startStudio(options: StudioOptions): Promise<Studio> {
|
|
|
182
269
|
})
|
|
183
270
|
started.push(server.process)
|
|
184
271
|
const { url, root } = await server.ready
|
|
272
|
+
const mcpUrl = new URL(`${(options.previewUrl ?? url).replace(/\/+$/, '')}/mcp`)
|
|
273
|
+
if (!options.previewUrl && listenAddress) mcpUrl.hostname = bracketIPv6(primaryHost)
|
|
185
274
|
|
|
275
|
+
const trustedHosts = wildcard
|
|
276
|
+
? [...hosts, hostname(), `${hostname()}.local`]
|
|
277
|
+
: listenAddress ? [listenAddress] : []
|
|
186
278
|
const dsh = launchNode('DeepSeek Harness', [
|
|
187
|
-
dshBin(PACKAGE_DIR), ...launchArgs(profile, 'web'), '--port', String(
|
|
188
|
-
...listenAddress ? ['--host',
|
|
279
|
+
dshBin(PACKAGE_DIR), ...launchArgs(profile, 'web'), '--port', String(dshPort), '--no-open',
|
|
280
|
+
...wildcard || listenAddress ? ['--host', dshAddress] : [],
|
|
281
|
+
...trustedHosts.flatMap(host => ['--trusted-host', authority(host, port)]),
|
|
189
282
|
...options.publicUrl ? ['--public-url', options.publicUrl, '--trusted-host', new URL(options.publicUrl).host] : [],
|
|
190
283
|
], {
|
|
191
284
|
cwd: root,
|
|
@@ -193,6 +286,7 @@ export async function startStudio(options: StudioOptions): Promise<Studio> {
|
|
|
193
286
|
...inheritedEnv(env, name => isLauncherVariable(name) || ['DEEPSEEK_API_KEY', 'DEEPSEEK_BASE_URL', 'DEEPSEEK_SEARCH_BASE_URL'].includes(name)),
|
|
194
287
|
...modelEnv(env).env,
|
|
195
288
|
...launchEnv(home, env),
|
|
289
|
+
PRESMIUM_COMMAND: presmium,
|
|
196
290
|
PRESMIUM_SERVICE_URL: url,
|
|
197
291
|
PRESMIUM_SERVICE_TOKEN: serviceToken,
|
|
198
292
|
PRESMIUM_WORKSPACE: root,
|
|
@@ -200,8 +294,11 @@ export async function startStudio(options: StudioOptions): Promise<Studio> {
|
|
|
200
294
|
onOutput: text => log.write('dsh', text),
|
|
201
295
|
})
|
|
202
296
|
started.push(dsh)
|
|
203
|
-
const
|
|
297
|
+
const backend = (await dsh.ready(WEB_READY))[1]!
|
|
298
|
+
if (wildcard) proxy = await startProxy({ host: boundAddress, port, target: `http://${authority(dshAddress, dshPort)}` })
|
|
204
299
|
dsh.stopBuffering()
|
|
300
|
+
const address = studioUrl(backend, options.publicUrl, primaryHost, port)
|
|
301
|
+
const networkUrls = hosts.slice(1).map(host => studioUrl(backend, `http://${authority(host, port)}/`, host, port))
|
|
205
302
|
// The address with its launch token, for a host that opens Studio for the user (0600, removed on close).
|
|
206
303
|
const state = join(home, `${profile}.json`)
|
|
207
304
|
writeFileSync(state, `${JSON.stringify({ url: address, workspace: root, workspaceServerUrl: url, pid: process.pid }, null, 2)}\n`, { mode: 0o600 })
|
|
@@ -213,7 +310,9 @@ export async function startStudio(options: StudioOptions): Promise<Studio> {
|
|
|
213
310
|
]).then(how => (closing ? new Promise<string>(() => {}) : how))
|
|
214
311
|
return {
|
|
215
312
|
url: address,
|
|
313
|
+
networkUrls,
|
|
216
314
|
workspaceServerUrl: url,
|
|
315
|
+
mcp: { url: mcpUrl.href, tokenFile },
|
|
217
316
|
root,
|
|
218
317
|
home,
|
|
219
318
|
log: log.file,
|