@lincyaw/studio 0.2.0-rc.15 → 0.2.0-rc.150
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 -3
- package/package.json +7 -5
- package/src/cli.ts +38 -5
- package/src/messages.ts +37 -11
- package/src/model-env.ts +5 -3
- package/src/proxy.ts +62 -0
- package/src/studio.ts +174 -23
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
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 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.
|
|
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.3-alpha.2` (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
|
|
|
@@ -11,12 +11,18 @@ pnpm add -g @lincyaw/presmium
|
|
|
11
11
|
presmium studio [dir] [--port <n>] [--host <addr>]
|
|
12
12
|
```
|
|
13
13
|
|
|
14
|
-
Studio is included with Presmium. In a project
|
|
14
|
+
Studio is included with Presmium. In a project that installs `@lincyaw/presmium` ([how](https://www.npmjs.com/package/@lincyaw/presmium#in-a-project)), 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
|
+
Local AI clients use native stdio, configured once as `presmium mcp <absolute-workspace-or-document-path>`. It starts or reuses a current workspace authoring service before initialization. With default local listeners, Studio shares only a matching runtime version. A newer launch requests a graceful handover from an older service, waits for in-flight operations and the workspace lease, and starts the current runtime. Stdio relays reconnect subsequent requests and notification subscriptions without replaying business requests. MCP-owned services run in separate child processes so a surviving relay cannot reload cached older modules. Closing Studio preserves a borrowed service; closing its owning stdio session ends that service and Studio. Explicit listener settings require a dedicated service. An older Studio cannot downgrade a newer running service.
|
|
21
|
+
|
|
22
|
+
For Streamable HTTP clients, use the MCP URL and token-file path printed at startup and send `Authorization: Bearer <token>`. A service-state JSON file stores the credential in its `token` field; a plain token file contains it directly. Studio's own workspace service defaults to `http://127.0.0.1:4321/mcp` and preserves its credential for the same launch directory across restarts and upgrades. A borrowed service keeps its existing address and credential. With `--host 0.0.0.0`, use the printed network MCP address from other machines.
|
|
23
|
+
|
|
24
|
+
When Studio starts its own service and another workspace occupies 4321, it chooses a free port and reports the changed address. An occupied explicit port fails. Use `--preview-port <n>` for a fixed port, or `--preview-port 0` for a temporary port. Behind a reverse proxy, MCP is at `mcp` under `--preview-url`.
|
|
25
|
+
|
|
20
26
|
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
27
|
|
|
22
28
|
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.150",
|
|
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": {
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
],
|
|
20
20
|
"type": "module",
|
|
21
21
|
"engines": {
|
|
22
|
-
"node": "
|
|
22
|
+
"node": "^24.22.3 || >=26.13.1"
|
|
23
23
|
},
|
|
24
24
|
"publishConfig": {
|
|
25
25
|
"access": "public"
|
|
@@ -36,11 +36,13 @@
|
|
|
36
36
|
"src"
|
|
37
37
|
],
|
|
38
38
|
"dependencies": {
|
|
39
|
-
"@deepseek-ai/dsh": "0.2.
|
|
39
|
+
"@deepseek-ai/dsh": "0.2.3-alpha.2",
|
|
40
|
+
"http-proxy-3": "2.0.1",
|
|
40
41
|
"jiti": "^2.7.0",
|
|
41
|
-
"@lincyaw/dsh": "0.2.0-rc.
|
|
42
|
+
"@lincyaw/dsh": "0.2.0-rc.150",
|
|
43
|
+
"@lincyaw/kernel": "1.0.0-rc.151"
|
|
42
44
|
},
|
|
43
45
|
"devDependencies": {
|
|
44
|
-
"@lincyaw/cli": "1.0.0-rc.
|
|
46
|
+
"@lincyaw/cli": "1.0.0-rc.151"
|
|
45
47
|
}
|
|
46
48
|
}
|
package/src/cli.ts
CHANGED
|
@@ -27,11 +27,29 @@ function portOf(value: string | undefined): number | undefined {
|
|
|
27
27
|
return n
|
|
28
28
|
}
|
|
29
29
|
|
|
30
|
+
/** Desktop owns the input pipe; closing it must stop Studio even when the app cannot run cleanup. */
|
|
31
|
+
function watchParentPipe(onEnd: () => void): () => void {
|
|
32
|
+
if (process.env.PRESMIUM_STUDIO_PARENT_PIPE !== '1') return () => {}
|
|
33
|
+
delete process.env.PRESMIUM_STUDIO_PARENT_PIPE
|
|
34
|
+
let ended = false
|
|
35
|
+
const end = () => {
|
|
36
|
+
if (ended) return
|
|
37
|
+
ended = true
|
|
38
|
+
onEnd()
|
|
39
|
+
}
|
|
40
|
+
process.stdin.on('end', end).on('close', end).on('error', end)
|
|
41
|
+
process.stdin.resume()
|
|
42
|
+
return () => {
|
|
43
|
+
process.stdin.off('end', end).off('close', end).off('error', end)
|
|
44
|
+
process.stdin.pause()
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
30
48
|
export async function main(argv: string[], options: MainOptions = {}): Promise<number> {
|
|
31
|
-
let values: { port?: string, host?: string, 'public-url'?: string, 'preview-url'?: string, 'preview-port'?: string, help?: boolean }
|
|
49
|
+
let values: { port?: string, host?: string, 'public-url'?: string, 'preview-url'?: string, 'preview-port'?: string, verbose?: boolean, help?: boolean }
|
|
32
50
|
let dir: string
|
|
33
51
|
try {
|
|
34
|
-
const parsed = parseArgs({ args: argv, allowPositionals: true, options: { port: { type: 'string' }, host: { type: 'string' }, 'public-url': { type: 'string' }, 'preview-url': { type: 'string' }, 'preview-port': { type: 'string' }, help: { type: 'boolean', short: 'h' } } })
|
|
52
|
+
const parsed = parseArgs({ args: argv, allowPositionals: true, options: { port: { type: 'string' }, host: { type: 'string' }, 'public-url': { type: 'string' }, 'preview-url': { type: 'string' }, 'preview-port': { type: 'string' }, verbose: { type: 'boolean' }, help: { type: 'boolean', short: 'h' } } })
|
|
35
53
|
values = parsed.values
|
|
36
54
|
const [given = '.', ...extra] = parsed.positionals
|
|
37
55
|
if (extra.length > 0) throw new Error(t.unexpectedArgument(extra[0]!))
|
|
@@ -53,24 +71,39 @@ export async function main(argv: string[], options: MainOptions = {}): Promise<n
|
|
|
53
71
|
const model = modelEnv(process.env)
|
|
54
72
|
if (model.warning) process.stderr.write(`presmium studio: ${model.warning}\n`)
|
|
55
73
|
|
|
74
|
+
// During startup, exiting closes the watchdog pipes; once ready, use Studio's graceful close path.
|
|
75
|
+
let parentStop: () => void = () => process.exit(0)
|
|
76
|
+
const unwatchParent = watchParentPipe(() => parentStop())
|
|
56
77
|
let studio
|
|
57
78
|
try {
|
|
58
|
-
studio = await startStudio({ dir, port: portOf(values.port), onServiceOutput: text => process.stderr.write(text), ...values.host ? { listenAddress: values.host } : {}, ...values['public-url'] ? { publicUrl: urlOf('--public-url', values['public-url']) } : {}, ...values['preview-url'] ? { previewUrl: urlOf('--preview-url', values['preview-url']) } : {}, ...values['preview-port'] ? { previewPort: portOf(values['preview-port']) } : {}, ...options.presmium ? { presmium: options.presmium } : {} })
|
|
79
|
+
studio = await startStudio({ dir, port: portOf(values.port), ...values.verbose ? { onServiceOutput: (text: string) => void process.stderr.write(text) } : {}, ...values.host ? { listenAddress: values.host } : {}, ...values['public-url'] ? { publicUrl: urlOf('--public-url', values['public-url']) } : {}, ...values['preview-url'] ? { previewUrl: urlOf('--preview-url', values['preview-url']) } : {}, ...values['preview-port'] ? { previewPort: portOf(values['preview-port']) } : {}, ...options.presmium ? { presmium: options.presmium } : {} })
|
|
59
80
|
} catch (error) {
|
|
81
|
+
unwatchParent()
|
|
60
82
|
process.stderr.write(`presmium studio: ${error instanceof Error ? error.message : String(error)}\n`)
|
|
61
83
|
return 2
|
|
62
84
|
}
|
|
85
|
+
// One address to open; the MCP address, its token and the log file only with --verbose (the log has them too).
|
|
63
86
|
process.stdout.write(`studio ${studio.url}\n`)
|
|
64
|
-
process.
|
|
87
|
+
for (const url of studio.networkUrls) process.stdout.write(`network ${url}\n`)
|
|
88
|
+
if (values.verbose) {
|
|
89
|
+
process.stdout.write(`mcp ${studio.mcp.url}\n`)
|
|
90
|
+
process.stderr.write(`${t.mcpToken(studio.mcp.tokenFile)}\n`)
|
|
91
|
+
if (studio.mcp.movedFrom) process.stderr.write(`${t.previewPortMoved(studio.mcp.movedFrom, studio.mcp.url)}\n`)
|
|
92
|
+
process.stderr.write(`${t.log(studio.log)}\n`)
|
|
93
|
+
} else process.stderr.write(`${t.open}\n`)
|
|
65
94
|
if (values.host && values.host !== '127.0.0.1' && values.host !== '::1' && !values['public-url']) {
|
|
66
|
-
process.stderr.write(`${
|
|
95
|
+
process.stderr.write(`${studio.networkUrls.length
|
|
96
|
+
? t.openOnAllNetworks(new URL(studio.url).port, new URL(studio.workspaceServerUrl).port)
|
|
97
|
+
: t.openOnNetwork(values.host, new URL(studio.url).port, new URL(studio.workspaceServerUrl).port)}\n`)
|
|
67
98
|
}
|
|
68
99
|
|
|
69
100
|
const signals = ['SIGINT', 'SIGTERM', 'SIGHUP'] as const
|
|
70
101
|
let stop = () => {}
|
|
71
102
|
const stopped = new Promise<void>(done => stop = done)
|
|
103
|
+
parentStop = stop
|
|
72
104
|
for (const signal of signals) process.once(signal, stop)
|
|
73
105
|
const ended = await Promise.race([stopped.then(() => undefined), studio.ended])
|
|
106
|
+
unwatchParent()
|
|
74
107
|
for (const signal of signals) process.off(signal, stop)
|
|
75
108
|
await studio.close()
|
|
76
109
|
if (ended === undefined) return 0
|
package/src/messages.ts
CHANGED
|
@@ -9,9 +9,17 @@ export interface StudioMessages {
|
|
|
9
9
|
unexpectedArgument(argument: string): string
|
|
10
10
|
notDirectory(dir: string): string
|
|
11
11
|
log(file: string): string
|
|
12
|
+
open: string
|
|
12
13
|
openOnNetwork(address: string, port: string, previewPort: string): string
|
|
14
|
+
openOnAllNetworks(port: string, previewPort: string): string
|
|
13
15
|
ended(how: string, log: string): string
|
|
14
16
|
portInUse(port: number, address: string): string
|
|
17
|
+
previewPortInUse(port: number, address: string): string
|
|
18
|
+
previewPortMoved(port: number, url: string): string
|
|
19
|
+
mcpToken(file: string): string
|
|
20
|
+
badMcpToken(file: string): string
|
|
21
|
+
existingService(url: string): string
|
|
22
|
+
serviceUpgrade(reason: 'busy' | 'newer' | 'unavailable', version?: string): string
|
|
15
23
|
noFreePort(address: string): string
|
|
16
24
|
badHost(address: string): string
|
|
17
25
|
wholeLog(message: string, file: string): string
|
|
@@ -27,19 +35,21 @@ export const STUDIO_MESSAGES: Record<Locale, StudioMessages> = {
|
|
|
27
35
|
|
|
28
36
|
启动 Presmium Studio(实验性):在浏览器中编辑这个目录(工作区的根目录或一份文稿所在的目录;
|
|
29
37
|
默认为 .)中的文稿,并为它提供工作区服务。只打印一个要在浏览器中打开的网址。AI 助手所用的模型在
|
|
30
|
-
“设置 → 模型”中设置,也可以由环境变量给出:DEEPSEEK_API_KEY
|
|
38
|
+
“设置 → 模型”中设置,也可以由环境变量给出:DEEPSEEK_API_KEY(可加 DEEPSEEK_BASE_URL 与
|
|
39
|
+
DEEPSEEK_SEARCH_BASE_URL),或者兼容 Messages 接口的服务的
|
|
31
40
|
PRESMIUM_MODEL_URL、PRESMIUM_MODEL_KEY 与 PRESMIUM_MODEL_PROVIDER。对话、模型设置、密钥与日志
|
|
32
41
|
presmium-studio-<散列>.log(每个安装一个)保存在 $XDG_STATE_HOME/presmium/studio 中。
|
|
33
42
|
|
|
34
43
|
选项:
|
|
35
44
|
--port <端口> Presmium Studio 的端口(默认为 4320,被占用时取空闲端口)
|
|
36
|
-
--host <地址>
|
|
45
|
+
--host <地址> 改为监听本机在局域网中的一个 IP 地址或 0.0.0.0,且没有登录:
|
|
37
46
|
任何能访问这个端口的人都以你的身份操作
|
|
38
47
|
--public-url <网址> 有反向代理在前面时浏览器打开的根地址(例如 Presmium 云端);
|
|
39
48
|
它的主机受信任,打印的网址用它。代理需保留 Host 并转发 WebSocket
|
|
40
49
|
--preview-url <网址> 同样情况下预览所在的地址,由代理转发到工作区服务;可以带路径,
|
|
41
50
|
此时它必须与 Studio 不同源,否则预览中文稿的代码能读到 Studio 的会话
|
|
42
|
-
--preview-port <端口>
|
|
51
|
+
--preview-port <端口> 工作区服务与 HTTP MCP 的固定端口(默认 4321,被占用时换一个空闲端口);0 为随机端口
|
|
52
|
+
--verbose 另外打印 HTTP MCP 的地址与访问令牌文件、日志文件,并转发工作区服务的输出
|
|
43
53
|
-h, --help 显示本说明`,
|
|
44
54
|
badPort: value => `--port 需要 0 到 65535 之间的端口号,而不是“${value}”。`,
|
|
45
55
|
badUrl: (option, value) => `${option} 需要一个完整的网址,例如 https://studio.example.com/,而不是“${value}”。`,
|
|
@@ -47,11 +57,19 @@ presmium-studio-<散列>.log(每个安装一个)保存在 $XDG_STATE_HOME/pr
|
|
|
47
57
|
unexpectedArgument: argument => `多余的参数“${argument}”。只能给出一个目录。`,
|
|
48
58
|
notDirectory: dir => `${dir} 不是目录。请给出工作区的根目录或一份文稿所在的目录。`,
|
|
49
59
|
log: file => `presmium studio: 日志在 ${file}`,
|
|
60
|
+
open: 'presmium studio: 在浏览器中打开上面的网址。按 Ctrl+C 停止。',
|
|
50
61
|
openOnNetwork: (address, port, previewPort) => `presmium studio: 正在 ${address} 上监听,局域网中的设备可以访问,且没有登录:任何能用上面的网址访问端口 ${port}(以及预览的端口 ${previewPort})的人都以你的身份使用这个工作区(编辑、运行代码、使用你的模型)。请只在可信的网络中使用;不加 --host 时只在本机监听。`,
|
|
62
|
+
openOnAllNetworks: (port, previewPort) => `presmium studio: 正在全部局域网网络接口上监听,且没有登录:任何能用上面的网址访问端口 ${port}(以及预览的端口 ${previewPort})的人都以你的身份使用这个工作区(编辑、运行代码、使用你的模型)。请只在可信的网络中使用;不加 --host 时只在本机监听。`,
|
|
51
63
|
ended: (how, log) => `presmium studio: ${how}。日志在 ${log}`,
|
|
52
64
|
portInUse: (port, address) => `${address} 的端口 ${port} 已被占用。请用 --port 指定另一个端口。`,
|
|
65
|
+
previewPortInUse: (port, address) => `${address} 的工作区与 MCP 端口 ${port} 已被占用。请停止占用它的服务,或用 --preview-port 指定另一个固定端口。`,
|
|
66
|
+
previewPortMoved: (port, url) => `presmium studio: 端口 ${port} 已被占用,这次的 MCP 地址是 ${url}。按默认地址配置的 MCP 客户端这次连不上;需要固定地址时,用 --preview-port 指定一个空闲端口。`,
|
|
67
|
+
mcpToken: file => `presmium studio: HTTP MCP 客户端从 ${file} 读取访问令牌(server.json 使用 token 字段),设置 Authorization: Bearer <访问令牌>。本机客户端建议用 presmium mcp 自动发现服务。`,
|
|
68
|
+
badMcpToken: file => `MCP 访问令牌文件 ${file} 无效。请移走该文件后重试,并在客户端更新访问令牌。`,
|
|
69
|
+
existingService: url => `工作区服务已在 ${url} 运行。当前服务不支持复用,或指定的预览监听选项需要新服务;请先关闭它,再启动 Studio。`,
|
|
70
|
+
serviceUpgrade: (reason, version) => reason === 'busy' ? '工作区正在编辑或导出,请等待当前操作结束后重试升级。' : reason === 'newer' ? `工作区服务已运行更新版本 ${version},请升级当前 Presmium 后再打开。` : '无法自动切换旧版工作区服务,请关闭使用该工作区的旧版 Presmium 后重试。',
|
|
53
71
|
noFreePort: address => `${address} 上没有空闲的端口。请停止占用端口的服务后重试。`,
|
|
54
|
-
badHost: address => `--host
|
|
72
|
+
badHost: address => `--host 需要本机的一个 IP 地址,例如 192.168.0.21,也可以使用 0.0.0.0,而不是“${address}”。`,
|
|
55
73
|
wholeLog: (message, file) => `${message}${message.endsWith('\n') ? '' : '。'}完整的日志在 ${file}`,
|
|
56
74
|
serviceEnded: '工作区服务(presmium serve)已停止',
|
|
57
75
|
appEnded: 'Presmium Studio 的应用进程已停止',
|
|
@@ -63,21 +81,22 @@ presmium-studio-<散列>.log(每个安装一个)保存在 $XDG_STATE_HOME/pr
|
|
|
63
81
|
Presmium Studio (experimental): edit the documents of the directory (the workspace root, or a deck’s
|
|
64
82
|
directory; default: .) in the browser, with the workspace service of that directory. It prints the one
|
|
65
83
|
address to open in the browser. The AI Assistant’s model is chosen in Settings > Models, or given by the
|
|
66
|
-
environment: DEEPSEEK_API_KEY
|
|
67
|
-
for a Messages-compatible service. Chats, model settings, API keys, and the log
|
|
84
|
+
environment: DEEPSEEK_API_KEY (with DEEPSEEK_BASE_URL and DEEPSEEK_SEARCH_BASE_URL if needed), or
|
|
85
|
+
PRESMIUM_MODEL_URL, PRESMIUM_MODEL_KEY, and PRESMIUM_MODEL_PROVIDER for a Messages-compatible service. Chats, model settings, API keys, and the log
|
|
68
86
|
presmium-studio-<hash>.log (one per installation) are kept in $XDG_STATE_HOME/presmium/studio.
|
|
69
87
|
|
|
70
88
|
Options:
|
|
71
89
|
--port <n> Presmium Studio’s port (default: 4320, or a free one when that is in use)
|
|
72
|
-
--host <addr> listen on
|
|
73
|
-
no login: whoever reaches the port works as you
|
|
90
|
+
--host <addr> listen on one local IP address, or on all IPv4 network interfaces with 0.0.0.0,
|
|
91
|
+
with no login: whoever reaches the port works as you
|
|
74
92
|
--public-url <url> the root browsers open when a reverse proxy fronts Studio (as in Presmium
|
|
75
93
|
Cloud): its host is trusted, and the printed address uses it. The proxy keeps Host and
|
|
76
94
|
forwards WebSockets
|
|
77
95
|
--preview-url <url> in that case, the address of the previews, forwarded to the workspace service; it
|
|
78
96
|
may have a path, and should be another origin than Studio’s, or the documents’ code in
|
|
79
97
|
previews can read Studio’s session
|
|
80
|
-
--preview-port <n>
|
|
98
|
+
--preview-port <n> fixed workspace-service and HTTP MCP port (default: 4321, or a free one when that is in use); 0 requests a random port
|
|
99
|
+
--verbose also print the HTTP MCP address, its access token file and the log file, and pass on the workspace service’s output
|
|
81
100
|
-h, --help show this help`,
|
|
82
101
|
badPort: value => `--port takes a port number from 0 to 65535, not “${value}”.`,
|
|
83
102
|
badUrl: (option, value) => `${option} takes a full address, such as https://studio.example.com/, not “${value}”.`,
|
|
@@ -85,15 +104,22 @@ Options:
|
|
|
85
104
|
unexpectedArgument: argument => `Unexpected argument “${argument}”. Give one directory.`,
|
|
86
105
|
notDirectory: dir => `${dir} is not a directory. Give the workspace root, or the directory of a document.`,
|
|
87
106
|
log: file => `presmium studio: log ${file}`,
|
|
107
|
+
open: 'presmium studio: open the address above in your browser. Press Ctrl+C to stop.',
|
|
88
108
|
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.`,
|
|
109
|
+
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.`,
|
|
89
110
|
ended: (how, log) => `presmium studio: ${how}; the log is ${log}`,
|
|
90
111
|
portInUse: (port, address) => `Port ${port} of ${address} is in use. Give another with --port.`,
|
|
112
|
+
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.`,
|
|
113
|
+
previewPortMoved: (port, url) => `presmium studio: port ${port} is in use, so the MCP address is ${url} this time. MCP clients set up with the usual address cannot reach it; for a fixed address, choose a free port with --preview-port.`,
|
|
114
|
+
mcpToken: file => `presmium studio: HTTP MCP clients read the access token from ${file} (the token field in server.json) and set Authorization: Bearer <value>. Local clients should use presmium mcp to discover the service automatically.`,
|
|
115
|
+
badMcpToken: file => `MCP access token file ${file} is invalid. Move it aside and retry, then update the access token in your clients.`,
|
|
116
|
+
existingService: url => `A workspace service is running at ${url}. It cannot be reused, or the explicit preview listener options require a new service; close it before starting Studio.`,
|
|
117
|
+
serviceUpgrade: (reason, version) => reason === 'busy' ? 'The workspace is being edited or exported. Wait for the current operation to finish, then retry the upgrade.' : reason === 'newer' ? `The workspace service runs the newer version ${version}. Update this Presmium before opening it.` : 'The older workspace service could not be replaced automatically. Close the older Presmium using this workspace, then retry.',
|
|
91
118
|
noFreePort: address => `There is no free port on ${address}. Stop a service that uses one, then retry.`,
|
|
92
|
-
badHost: address => `--host takes one
|
|
119
|
+
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}”.`,
|
|
93
120
|
wholeLog: (message, file) => `${message.endsWith('\n') ? message : `${message}; `}the whole log is ${file}`,
|
|
94
121
|
serviceEnded: 'the workspace service (presmium serve) ended',
|
|
95
122
|
appEnded: 'the Presmium Studio app ended',
|
|
96
123
|
modelVariables: (variables, unset) => `${variables.join(', ')} go together; ${unset.join(' and ')} ${unset.length > 1 ? 'are' : 'is'} not set.`,
|
|
97
124
|
},
|
|
98
125
|
}
|
|
99
|
-
|
package/src/model-env.ts
CHANGED
|
@@ -12,12 +12,14 @@ const searchUrl = (url: string) => `${url.replace(/\/+$/, '').replace(/\/v1$/, '
|
|
|
12
12
|
|
|
13
13
|
const deepseekEndpoints = (url: string) => ({ DEEPSEEK_BASE_URL: url, DEEPSEEK_SEARCH_BASE_URL: searchUrl(url) })
|
|
14
14
|
|
|
15
|
+
/** DeepSeek Harness's own provider variables, passed on as the launching shell sets them. */
|
|
16
|
+
export const DEEPSEEK_VARIABLES = ['DEEPSEEK_API_KEY', 'DEEPSEEK_BASE_URL', 'DEEPSEEK_SEARCH_BASE_URL'] as const
|
|
17
|
+
|
|
15
18
|
export function modelEnv(env: NodeJS.ProcessEnv): ModelEnv {
|
|
16
19
|
const [url, key, provider] = MODEL_VARIABLES.map(name => env[name]?.trim() || undefined)
|
|
17
20
|
if (url && key && provider) return { env: { ...deepseekEndpoints(url), DEEPSEEK_API_KEY: key }, from: [...MODEL_VARIABLES] }
|
|
18
21
|
const unset = MODEL_VARIABLES.filter((_, i) => ![url, key, provider][i])
|
|
19
22
|
const warning = unset.length < MODEL_VARIABLES.length ? { warning: STUDIO_MESSAGES[systemLocale(env)].modelVariables(MODEL_VARIABLES, unset) } : {}
|
|
20
|
-
const
|
|
21
|
-
|
|
22
|
-
return { env: {}, from: [], ...warning }
|
|
23
|
+
const given = DEEPSEEK_VARIABLES.flatMap(name => env[name]?.trim() ? [[name, env[name]!.trim()] as const] : [])
|
|
24
|
+
return { env: Object.fromEntries(given), from: given.map(([name]) => name), ...warning }
|
|
23
25
|
}
|
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,22 @@
|
|
|
1
1
|
import { createHash, randomBytes } from 'node:crypto'
|
|
2
|
-
import { closeSync, copyFileSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, 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'
|
|
6
|
+
import { homedir, hostname, networkInterfaces } from 'node:os'
|
|
7
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
|
+
import { compareServiceVersion, findWorkspaceServiceState, readServiceState, serveStateDir, SERVICE_VERSION, ServiceUpgradeError, upgradeWorkspaceService } from '@lincyaw/kernel/node'
|
|
11
12
|
import { STUDIO_MESSAGES, systemLocale } from './messages.ts'
|
|
12
|
-
import { modelEnv } from './model-env.ts'
|
|
13
|
+
import { DEEPSEEK_VARIABLES, modelEnv } from './model-env.ts'
|
|
14
|
+
import { startProxy } from './proxy.ts'
|
|
15
|
+
import type { Proxy } from './proxy.ts'
|
|
13
16
|
|
|
14
17
|
const PROFILE = 'presmium-studio'
|
|
15
18
|
const DEFAULT_PORT = 4320
|
|
19
|
+
const DEFAULT_PREVIEW_PORT = 4321
|
|
16
20
|
const LOG_BYTES = 16 << 20
|
|
17
21
|
|
|
18
22
|
const PACKAGE_DIR = fileURLToPath(new URL('..', import.meta.url))
|
|
@@ -28,7 +32,7 @@ export interface StudioOptions {
|
|
|
28
32
|
*/
|
|
29
33
|
publicUrl?: string
|
|
30
34
|
previewUrl?: string
|
|
31
|
-
/** The workspace service
|
|
35
|
+
/** The workspace service and HTTP MCP port. Without it Studio uses 4321, or a free port when 4321 is in use; zero requests a free port. */
|
|
32
36
|
previewPort?: number
|
|
33
37
|
env?: NodeJS.ProcessEnv
|
|
34
38
|
presmium?: string
|
|
@@ -38,7 +42,10 @@ export interface StudioOptions {
|
|
|
38
42
|
|
|
39
43
|
export interface Studio {
|
|
40
44
|
url: string
|
|
45
|
+
networkUrls: string[]
|
|
41
46
|
workspaceServerUrl: string
|
|
47
|
+
/** `movedFrom` is the default port when it was in use and the MCP address differs from the usual one. */
|
|
48
|
+
mcp: { url: string, tokenFile: string, movedFrom?: number }
|
|
42
49
|
root: string
|
|
43
50
|
home: string
|
|
44
51
|
log: string
|
|
@@ -52,6 +59,23 @@ function studioHome(env: NodeJS.ProcessEnv = process.env): string {
|
|
|
52
59
|
return join(env.XDG_STATE_HOME || join(env.HOME || homedir(), '.local', 'state'), 'presmium', 'studio')
|
|
53
60
|
}
|
|
54
61
|
|
|
62
|
+
/** Independent of the installation/profile so upgrades and restarts preserve external MCP access. */
|
|
63
|
+
function workspaceCredential(home: string, dir: string): { token: string, file: string } {
|
|
64
|
+
const directory = join(home, 'mcp')
|
|
65
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 })
|
|
66
|
+
const id = createHash('sha256').update(realpathSync(dir)).digest('hex').slice(0, 32)
|
|
67
|
+
const file = join(directory, `${id}.token`)
|
|
68
|
+
try {
|
|
69
|
+
writeFileSync(file, `${randomBytes(24).toString('base64url')}\n`, { flag: 'wx', mode: 0o600 })
|
|
70
|
+
} catch (error) {
|
|
71
|
+
if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error
|
|
72
|
+
}
|
|
73
|
+
chmodSync(file, 0o600)
|
|
74
|
+
const token = readFileSync(file, 'utf8').trim()
|
|
75
|
+
if (!/^[A-Za-z0-9_-]{32}$/.test(token)) throw new Error(STUDIO_MESSAGES[systemLocale()].badMcpToken(file))
|
|
76
|
+
return { token, file }
|
|
77
|
+
}
|
|
78
|
+
|
|
55
79
|
/** The bundle `@lincyaw/dsh` this package depends on: the directory the profile links to. */
|
|
56
80
|
function bundleDir(): string {
|
|
57
81
|
return realpathSync(dirname(createRequire(join(PACKAGE_DIR, 'package.json')).resolve('@lincyaw/dsh/package.json')))
|
|
@@ -113,7 +137,27 @@ function nodeScript(command: string): string | undefined {
|
|
|
113
137
|
}
|
|
114
138
|
}
|
|
115
139
|
|
|
116
|
-
const WILDCARD = /^
|
|
140
|
+
const WILDCARD = /^0\.0\.0\.0$/
|
|
141
|
+
|
|
142
|
+
function networkHosts(): string[] {
|
|
143
|
+
return [...new Set(Object.values(networkInterfaces()).flatMap(entries => entries ?? []).filter(entry => entry.family === 'IPv4' && !entry.internal).map(entry => entry.address))]
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function authority(host: string, port: number): string {
|
|
147
|
+
return `${bracketIPv6(host)}:${port}`
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function httpOrigin(host: string, port: number): string {
|
|
151
|
+
return `http://${authority(host, port)}`
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function studioUrl(backend: string, publicUrl: string | undefined, host: string, port: number): string {
|
|
155
|
+
const token = new URL(backend).searchParams.get('token')
|
|
156
|
+
if (!token) throw new Error('DeepSeek Harness printed an address without its launch token')
|
|
157
|
+
const url = new URL(publicUrl ?? `http://${authority(host, port)}/`)
|
|
158
|
+
url.searchParams.set('token', token)
|
|
159
|
+
return url.href
|
|
160
|
+
}
|
|
117
161
|
|
|
118
162
|
function freePort(listenAddress: string, port: number): Promise<number | undefined> {
|
|
119
163
|
return new Promise((done) => {
|
|
@@ -126,12 +170,12 @@ function freePort(listenAddress: string, port: number): Promise<number | undefin
|
|
|
126
170
|
})
|
|
127
171
|
}
|
|
128
172
|
|
|
129
|
-
async function choosePort(listenAddress: string, port: number | undefined): Promise<number> {
|
|
173
|
+
async function choosePort(listenAddress: string, port: number | undefined, preferred?: number): Promise<number> {
|
|
130
174
|
if (port) {
|
|
131
175
|
if (await freePort(listenAddress, port) === undefined) throw new Error(STUDIO_MESSAGES[systemLocale()].portInUse(port, listenAddress))
|
|
132
176
|
return port
|
|
133
177
|
}
|
|
134
|
-
const chosen = (port === undefined ? await freePort(listenAddress, DEFAULT_PORT) : undefined) ?? await freePort(listenAddress, 0)
|
|
178
|
+
const chosen = (port === undefined ? (preferred ? await freePort(listenAddress, preferred) : undefined) ?? await freePort(listenAddress, DEFAULT_PORT) : undefined) ?? await freePort(listenAddress, 0)
|
|
135
179
|
if (chosen === undefined) throw new Error(STUDIO_MESSAGES[systemLocale()].noFreePort(listenAddress))
|
|
136
180
|
return chosen
|
|
137
181
|
}
|
|
@@ -174,31 +218,81 @@ export async function startStudio(options: StudioOptions): Promise<Studio> {
|
|
|
174
218
|
const env = options.env ?? process.env
|
|
175
219
|
const t = STUDIO_MESSAGES[systemLocale(env)]
|
|
176
220
|
const { listenAddress } = options
|
|
177
|
-
if (listenAddress !== undefined &&
|
|
221
|
+
if (listenAddress !== undefined && isIP(listenAddress) === 0) {
|
|
178
222
|
throw new Error(t.badHost(listenAddress))
|
|
179
223
|
}
|
|
180
|
-
const
|
|
181
|
-
|
|
182
|
-
|
|
224
|
+
const boundAddress = listenAddress ?? '127.0.0.1'
|
|
225
|
+
let existing = findWorkspaceServiceState(options.dir, env)
|
|
226
|
+
const canReuse = () => existing?.state.launcherToken && listenAddress === undefined && options.previewPort === undefined && options.previewUrl === undefined
|
|
227
|
+
if (existing && !canReuse()) throw new Error(t.existingService(existing.state.url))
|
|
228
|
+
try {
|
|
229
|
+
while (existing && compareServiceVersion(existing.state, SERVICE_VERSION) !== 0) {
|
|
230
|
+
if (compareServiceVersion(existing.state, SERVICE_VERSION) > 0) throw new ServiceUpgradeError('newer', existing.state.version)
|
|
231
|
+
await upgradeWorkspaceService(existing.root, existing.state, SERVICE_VERSION, env)
|
|
232
|
+
existing = findWorkspaceServiceState(options.dir, env)
|
|
233
|
+
}
|
|
234
|
+
} catch (error) {
|
|
235
|
+
if (error instanceof ServiceUpgradeError) throw new Error(t.serviceUpgrade(error.reason, error.version))
|
|
236
|
+
throw error
|
|
237
|
+
}
|
|
238
|
+
const wildcard = WILDCARD.test(boundAddress)
|
|
239
|
+
// External MCP clients keep the default address, so it is preferred; an explicit port must be free.
|
|
240
|
+
let previewPort = options.previewPort ?? DEFAULT_PREVIEW_PORT
|
|
241
|
+
let movedFrom: number | undefined
|
|
242
|
+
if (!existing && previewPort !== 0 && await freePort(boundAddress, previewPort) === undefined) {
|
|
243
|
+
if (options.previewPort !== undefined) throw new Error(t.previewPortInUse(previewPort, boundAddress))
|
|
244
|
+
movedFrom = previewPort
|
|
245
|
+
previewPort = 0
|
|
246
|
+
}
|
|
183
247
|
const home = studioHome(env)
|
|
184
248
|
mkdirSync(home, { recursive: true, mode: 0o700 })
|
|
249
|
+
// Preserve the browser origin (and its caches/return state) when the default port is held by another app.
|
|
250
|
+
const portFile = options.port === undefined && listenAddress === undefined && !options.publicUrl
|
|
251
|
+
? join(home, 'ports', `${createHash('sha256').update(realpathSync(options.dir)).digest('hex').slice(0, 32)}.json`) : undefined
|
|
252
|
+
let preferredPort: number | undefined
|
|
253
|
+
if (portFile) {
|
|
254
|
+
try {
|
|
255
|
+
const saved = JSON.parse(readFileSync(portFile, 'utf8')) as { port?: unknown }
|
|
256
|
+
if (typeof saved.port === 'number' && Number.isInteger(saved.port) && saved.port > 0 && saved.port <= 65535) preferredPort = saved.port
|
|
257
|
+
} catch { /* A missing preference uses the normal default/free-port selection. */ }
|
|
258
|
+
}
|
|
259
|
+
const port = await choosePort(boundAddress, options.port, preferredPort)
|
|
260
|
+
const dshAddress = wildcard ? '127.0.0.1' : boundAddress
|
|
261
|
+
const dshPort = wildcard ? await choosePort(dshAddress, undefined) : port
|
|
262
|
+
const hosts = wildcard ? networkHosts() : []
|
|
263
|
+
const primaryHost = hosts[0] ?? dshAddress
|
|
264
|
+
const origins = options.publicUrl
|
|
265
|
+
? [new URL(options.publicUrl).origin, ...hosts.map(host => httpOrigin(host, port)), httpOrigin('127.0.0.1', port)]
|
|
266
|
+
: wildcard
|
|
267
|
+
? [...hosts.map(host => httpOrigin(host, port)), httpOrigin('127.0.0.1', port), `http://localhost:${port}`]
|
|
268
|
+
: [httpOrigin(boundAddress, port), ...boundAddress === '127.0.0.1' ? [`http://localhost:${port}`] : []]
|
|
269
|
+
|
|
185
270
|
const bundle = bundleDir()
|
|
186
271
|
const profile = installProfile(home, bundle)
|
|
187
272
|
writeProfile(home, profile, 'web', bundle)
|
|
273
|
+
const credential = existing ? undefined : workspaceCredential(home, options.dir)
|
|
274
|
+
const mcpToken = credential?.token
|
|
188
275
|
const log = new Log(join(home, `${profile}.log`))
|
|
189
|
-
|
|
276
|
+
let serviceToken = existing?.state.launcherToken ?? randomBytes(24).toString('base64url')
|
|
190
277
|
const started: LaunchedProcess[] = []
|
|
278
|
+
let proxy: Proxy | undefined
|
|
279
|
+
let hostMonitor: ReturnType<typeof setInterval> | undefined
|
|
191
280
|
const stopAll = async () => {
|
|
281
|
+
clearInterval(hostMonitor)
|
|
282
|
+
await proxy?.close()
|
|
283
|
+
proxy = undefined
|
|
192
284
|
for (const launched of started.reverse()) await launched.stop()
|
|
193
285
|
started.length = 0
|
|
194
286
|
}
|
|
195
287
|
|
|
196
288
|
try {
|
|
197
|
-
const
|
|
198
|
-
|
|
289
|
+
const presmium = options.presmium ?? presmiumBin(env, t.presmiumMissing)
|
|
290
|
+
const server = existing ? undefined : launchWorkspaceServer({
|
|
291
|
+
presmium,
|
|
199
292
|
dir: resolve(options.dir),
|
|
200
293
|
serviceToken,
|
|
201
|
-
|
|
294
|
+
mcpToken: mcpToken!,
|
|
295
|
+
port: previewPort,
|
|
202
296
|
args: [
|
|
203
297
|
...listenAddress ? ['--host', listenAddress] : [],
|
|
204
298
|
...origins.flatMap(origin => ['--preview-origin', origin]),
|
|
@@ -207,19 +301,62 @@ export async function startStudio(options: StudioOptions): Promise<Studio> {
|
|
|
207
301
|
env,
|
|
208
302
|
onOutput: text => { log.write('serve', text); options.onServiceOutput?.(text) },
|
|
209
303
|
})
|
|
210
|
-
started.push(server.process)
|
|
211
|
-
|
|
304
|
+
if (server) started.push(server.process)
|
|
305
|
+
let ready: { url: string, root: string }
|
|
306
|
+
if (existing) ready = { url: existing.state.url, root: existing.root }
|
|
307
|
+
else {
|
|
308
|
+
try { ready = await server!.ready }
|
|
309
|
+
catch (error) {
|
|
310
|
+
// Another local client may win the workspace lease after our initial discovery.
|
|
311
|
+
await server!.process.stop()
|
|
312
|
+
const deadline = Date.now() + 10_000
|
|
313
|
+
while (!existing && Date.now() < deadline) {
|
|
314
|
+
existing = findWorkspaceServiceState(options.dir, env)
|
|
315
|
+
if (!existing) await new Promise(done => setTimeout(done, 100))
|
|
316
|
+
}
|
|
317
|
+
if (!existing || !canReuse()) throw error
|
|
318
|
+
if (compareServiceVersion(existing.state, SERVICE_VERSION) !== 0) throw new Error(t.serviceUpgrade('unavailable'))
|
|
319
|
+
serviceToken = existing.state.launcherToken!
|
|
320
|
+
ready = { url: existing.state.url, root: existing.root }
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
const { url, root } = ready
|
|
324
|
+
const tokenFile = existing ? join(serveStateDir(root, env), 'server.json') : credential!.file
|
|
325
|
+
let serverEnded: Promise<unknown>
|
|
326
|
+
if (existing) {
|
|
327
|
+
const ownerPid = existing.state.pid
|
|
328
|
+
const response = await fetch(`${url}/__presmium/presmium.workspace/preview-origins`, {
|
|
329
|
+
method: 'POST', headers: { authorization: `Bearer ${serviceToken}`, 'content-type': 'application/json' },
|
|
330
|
+
body: JSON.stringify({ origins }), signal: AbortSignal.timeout(10_000),
|
|
331
|
+
})
|
|
332
|
+
if (!response.ok) throw new Error(t.existingService(url))
|
|
333
|
+
// Studio borrows this host. If its owner closes it, end the workbench without stopping or replacing it.
|
|
334
|
+
serverEnded = new Promise<void>(done => {
|
|
335
|
+
hostMonitor = setInterval(() => {
|
|
336
|
+
const current = readServiceState(join(serveStateDir(root, env), 'server.json'))
|
|
337
|
+
if (!current || current.pid !== ownerPid || current.url !== url) { clearInterval(hostMonitor); done() }
|
|
338
|
+
}, 500)
|
|
339
|
+
hostMonitor.unref()
|
|
340
|
+
})
|
|
341
|
+
} else serverEnded = server!.process.exited
|
|
342
|
+
const mcpUrl = new URL(`${(options.previewUrl ?? url).replace(/\/+$/, '')}/mcp`)
|
|
343
|
+
if (!options.previewUrl && listenAddress) mcpUrl.hostname = bracketIPv6(primaryHost)
|
|
212
344
|
|
|
345
|
+
const trustedHosts = wildcard
|
|
346
|
+
? [...hosts, hostname(), `${hostname()}.local`]
|
|
347
|
+
: listenAddress ? [listenAddress] : []
|
|
213
348
|
const dsh = launchNode('DeepSeek Harness', [
|
|
214
|
-
dshBin(PACKAGE_DIR), ...launchArgs(profile, 'web'), '--port', String(
|
|
215
|
-
...listenAddress ? ['--host',
|
|
349
|
+
dshBin(PACKAGE_DIR), ...launchArgs(profile, 'web'), '--port', String(dshPort), '--no-open',
|
|
350
|
+
...wildcard || listenAddress ? ['--host', dshAddress] : [],
|
|
351
|
+
...trustedHosts.flatMap(host => ['--trusted-host', authority(host, port)]),
|
|
216
352
|
...options.publicUrl ? ['--public-url', options.publicUrl, '--trusted-host', new URL(options.publicUrl).host] : [],
|
|
217
353
|
], {
|
|
218
354
|
cwd: root,
|
|
219
355
|
env: {
|
|
220
|
-
...inheritedEnv(env, name => isLauncherVariable(name) ||
|
|
356
|
+
...inheritedEnv(env, name => isLauncherVariable(name) || (DEEPSEEK_VARIABLES as readonly string[]).includes(name)),
|
|
221
357
|
...modelEnv(env).env,
|
|
222
|
-
...launchEnv(home, env),
|
|
358
|
+
...launchEnv(home, env, root),
|
|
359
|
+
PRESMIUM_COMMAND: presmium,
|
|
223
360
|
PRESMIUM_SERVICE_URL: url,
|
|
224
361
|
PRESMIUM_SERVICE_TOKEN: serviceToken,
|
|
225
362
|
PRESMIUM_WORKSPACE: root,
|
|
@@ -227,20 +364,34 @@ export async function startStudio(options: StudioOptions): Promise<Studio> {
|
|
|
227
364
|
onOutput: text => log.write('dsh', text),
|
|
228
365
|
})
|
|
229
366
|
started.push(dsh)
|
|
230
|
-
const
|
|
367
|
+
const backend = (await dsh.ready(WEB_READY))[1]!
|
|
368
|
+
if (portFile) {
|
|
369
|
+
try {
|
|
370
|
+
const content = `${JSON.stringify({ port })}\n`
|
|
371
|
+
if (!existsSync(portFile) || readFileSync(portFile, 'utf8') !== content) {
|
|
372
|
+
mkdirSync(dirname(portFile), { recursive: true, mode: 0o700 })
|
|
373
|
+
writeFileSync(portFile, content, { mode: 0o600 })
|
|
374
|
+
}
|
|
375
|
+
} catch { /* Failure to retain a preferred port must not prevent opening the workspace. */ }
|
|
376
|
+
}
|
|
377
|
+
if (wildcard) proxy = await startProxy({ host: boundAddress, port, target: `http://${authority(dshAddress, dshPort)}` })
|
|
231
378
|
dsh.stopBuffering()
|
|
379
|
+
const address = studioUrl(backend, options.publicUrl, primaryHost, port)
|
|
380
|
+
const networkUrls = hosts.slice(1).map(host => studioUrl(backend, `http://${authority(host, port)}/`, host, port))
|
|
232
381
|
// The address with its launch token, for a host that opens Studio for the user (0600, removed on close).
|
|
233
382
|
const state = join(home, `${profile}.json`)
|
|
234
383
|
writeFileSync(state, `${JSON.stringify({ url: address, workspace: root, workspaceServerUrl: url, pid: process.pid }, null, 2)}\n`, { mode: 0o600 })
|
|
235
384
|
|
|
236
385
|
let closing: Promise<void> | undefined
|
|
237
386
|
const ended = Promise.race([
|
|
238
|
-
|
|
387
|
+
serverEnded.then(() => t.serviceEnded),
|
|
239
388
|
dsh.exited.then(() => t.appEnded),
|
|
240
389
|
]).then(how => (closing ? new Promise<string>(() => {}) : how))
|
|
241
390
|
return {
|
|
242
391
|
url: address,
|
|
392
|
+
networkUrls,
|
|
243
393
|
workspaceServerUrl: url,
|
|
394
|
+
mcp: { url: mcpUrl.href, tokenFile, ...movedFrom ? { movedFrom } : {} },
|
|
244
395
|
root,
|
|
245
396
|
home,
|
|
246
397
|
log: log.file,
|