@lincyaw/studio 0.2.0-rc.6 → 0.2.0-rc.60

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 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 the `presmium` package it depends on), 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).
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/studio
11
- presmium-studio [dir] [--port <n>] [--host <addr>]
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/studio`, `pnpm exec presmium studio` is the same command.
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 of the machine on the local network instead, with no login.
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.6",
3
+ "version": "0.2.0-rc.60",
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.6",
42
- "@lincyaw/presmium": "1.0.0-rc.7"
42
+ "@lincyaw/dsh": "0.2.0-rc.60"
43
43
  },
44
44
  "devDependencies": {
45
- "@lincyaw/cli": "1.0.0-rc.7"
45
+ "@lincyaw/cli": "1.0.0-rc.61"
46
46
  }
47
47
  }
package/src/cli.ts CHANGED
@@ -61,9 +61,15 @@ 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`)
67
+ if (studio.mcp.movedFrom) process.stderr.write(`${t.previewPortMoved(studio.mcp.movedFrom, studio.mcp.url)}\n`)
64
68
  process.stderr.write(`${t.log(studio.log)}\n`)
65
69
  if (values.host && values.host !== '127.0.0.1' && values.host !== '::1' && !values['public-url']) {
66
- process.stderr.write(`${t.openOnNetwork(values.host, new URL(studio.url).port, new URL(studio.workspaceServerUrl).port)}\n`)
70
+ process.stderr.write(`${studio.networkUrls.length
71
+ ? t.openOnAllNetworks(new URL(studio.url).port, new URL(studio.workspaceServerUrl).port)
72
+ : t.openOnNetwork(values.host, new URL(studio.url).port, new URL(studio.workspaceServerUrl).port)}\n`)
67
73
  }
68
74
 
69
75
  const signals = ['SIGINT', 'SIGTERM', 'SIGHUP'] as const
package/src/messages.ts CHANGED
@@ -10,14 +10,20 @@ 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
+ previewPortMoved(port: number, url: string): string
18
+ mcpToken(file: string): string
19
+ badMcpToken(file: string): string
15
20
  noFreePort(address: string): string
16
21
  badHost(address: string): string
17
22
  wholeLog(message: string, file: string): string
18
23
  serviceEnded: string
19
24
  appEnded: string
20
25
  modelVariables(variables: readonly string[], unset: string[]): string
26
+ presmiumMissing: string
21
27
  }
22
28
 
23
29
  export const STUDIO_MESSAGES: Record<Locale, StudioMessages> = {
@@ -32,24 +38,30 @@ presmium-studio-<散列>.log(每个安装一个)保存在 $XDG_STATE_HOME/pr
32
38
 
33
39
  选项:
34
40
  --port <端口> Presmium Studio 的端口(默认为 4320,被占用时取空闲端口)
35
- --host <地址> 改为监听本机在局域网中的这个地址,而不是 127.0.0.1,且没有登录:
41
+ --host <地址> 改为监听本机在局域网中的一个 IP 地址或 0.0.0.0,且没有登录:
36
42
  任何能访问这个端口的人都以你的身份操作
37
43
  --public-url <网址> 有反向代理在前面时浏览器打开的根地址(例如 Presmium 云端);
38
44
  它的主机受信任,打印的网址用它。代理需保留 Host 并转发 WebSocket
39
45
  --preview-url <网址> 同样情况下预览所在的地址,由代理转发到工作区服务;可以带路径,
40
46
  此时它必须与 Studio 不同源,否则预览中文稿的代码能读到 Studio 的会话
41
- --preview-port <端口> 工作区服务的端口(默认为空闲端口),供需要事先知道端口的代理使用
47
+ --preview-port <端口> 工作区服务与 HTTP MCP 的固定端口(默认 4321,被占用时换一个空闲端口);0 为随机端口
42
48
  -h, --help 显示本说明`,
43
49
  badPort: value => `--port 需要 0 到 65535 之间的端口号,而不是“${value}”。`,
44
50
  badUrl: (option, value) => `${option} 需要一个完整的网址,例如 https://studio.example.com/,而不是“${value}”。`,
51
+ presmiumMissing: 'presmium-studio 找不到 presmium 命令。Presmium Studio 随 Presmium 一起安装:请运行 pnpm add -g @lincyaw/presmium,然后用 presmium studio 启动。',
45
52
  unexpectedArgument: argument => `多余的参数“${argument}”。只能给出一个目录。`,
46
53
  notDirectory: dir => `${dir} 不是目录。请给出工作区的根目录或一份文稿所在的目录。`,
47
54
  log: file => `presmium studio: 日志在 ${file}`,
48
55
  openOnNetwork: (address, port, previewPort) => `presmium studio: 正在 ${address} 上监听,局域网中的设备可以访问,且没有登录:任何能用上面的网址访问端口 ${port}(以及预览的端口 ${previewPort})的人都以你的身份使用这个工作区(编辑、运行代码、使用你的模型)。请只在可信的网络中使用;不加 --host 时只在本机监听。`,
56
+ openOnAllNetworks: (port, previewPort) => `presmium studio: 正在全部局域网网络接口上监听,且没有登录:任何能用上面的网址访问端口 ${port}(以及预览的端口 ${previewPort})的人都以你的身份使用这个工作区(编辑、运行代码、使用你的模型)。请只在可信的网络中使用;不加 --host 时只在本机监听。`,
49
57
  ended: (how, log) => `presmium studio: ${how}。日志在 ${log}`,
50
58
  portInUse: (port, address) => `${address} 的端口 ${port} 已被占用。请用 --port 指定另一个端口。`,
59
+ previewPortInUse: (port, address) => `${address} 的工作区与 MCP 端口 ${port} 已被占用。请停止占用它的服务,或用 --preview-port 指定另一个固定端口。`,
60
+ previewPortMoved: (port, url) => `presmium studio: 端口 ${port} 已被占用,这次的 MCP 地址是 ${url}。按默认地址配置的 MCP 客户端这次连不上;需要固定地址时,用 --preview-port 指定一个空闲端口。`,
61
+ mcpToken: file => `presmium studio: MCP 客户端使用 HTTP(Streamable HTTP),从 ${file} 读取访问令牌,设置 Authorization: Bearer <访问令牌>;同一目录重启与升级后保持不变。`,
62
+ badMcpToken: file => `MCP 访问令牌文件 ${file} 无效。请移走该文件后重试,并在客户端更新访问令牌。`,
51
63
  noFreePort: address => `${address} 上没有空闲的端口。请停止占用端口的服务后重试。`,
52
- badHost: address => `--host 需要本机的一个地址,例如 192.168.0.21,而不是“${address}”(Presmium Studio 只在一个确定的地址上监听,不能同时监听全部地址)。`,
64
+ badHost: address => `--host 需要本机的一个 IP 地址,例如 192.168.0.21,也可以使用 0.0.0.0,而不是“${address}”。`,
53
65
  wholeLog: (message, file) => `${message}${message.endsWith('\n') ? '' : '。'}完整的日志在 ${file}`,
54
66
  serviceEnded: '工作区服务(presmium serve)已停止',
55
67
  appEnded: 'Presmium Studio 的应用进程已停止',
@@ -67,30 +79,35 @@ presmium-studio-<hash>.log (one per installation) are kept in $XDG_STATE_HOME/pr
67
79
 
68
80
  Options:
69
81
  --port <n> Presmium Studio’s port (default: 4320, or a free one when that is in use)
70
- --host <addr> listen on this address of the machine on the local network instead of 127.0.0.1, with
71
- no login: whoever reaches the port works as you
82
+ --host <addr> listen on one local IP address, or on all IPv4 network interfaces with 0.0.0.0,
83
+ with no login: whoever reaches the port works as you
72
84
  --public-url <url> the root browsers open when a reverse proxy fronts Studio (as in Presmium
73
85
  Cloud): its host is trusted, and the printed address uses it. The proxy keeps Host and
74
86
  forwards WebSockets
75
87
  --preview-url <url> in that case, the address of the previews, forwarded to the workspace service; it
76
88
  may have a path, and should be another origin than Studio’s, or the documents’ code in
77
89
  previews can read Studio’s session
78
- --preview-port <n> the workspace service’s port (default: a free one), for a proxy that needs it in advance
90
+ --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
79
91
  -h, --help show this help`,
80
92
  badPort: value => `--port takes a port number from 0 to 65535, not “${value}”.`,
81
93
  badUrl: (option, value) => `${option} takes a full address, such as https://studio.example.com/, not “${value}”.`,
94
+ 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
95
  unexpectedArgument: argument => `Unexpected argument “${argument}”. Give one directory.`,
83
96
  notDirectory: dir => `${dir} is not a directory. Give the workspace root, or the directory of a document.`,
84
97
  log: file => `presmium studio: log ${file}`,
85
98
  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.`,
99
+ 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
100
  ended: (how, log) => `presmium studio: ${how}; the log is ${log}`,
87
101
  portInUse: (port, address) => `Port ${port} of ${address} is in use. Give another with --port.`,
102
+ 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.`,
103
+ 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.`,
104
+ 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.`,
105
+ badMcpToken: file => `MCP access token file ${file} is invalid. Move it aside and retry, then update the access token in your clients.`,
88
106
  noFreePort: address => `There is no free port on ${address}. Stop a service that uses one, then retry.`,
89
- badHost: address => `--host takes one address of this machine, such as 192.168.0.21, not “${address}” (Presmium Studio listens on one concrete address, never on all of them).`,
107
+ 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
108
  wholeLog: (message, file) => `${message.endsWith('\n') ? message : `${message}; `}the whole log is ${file}`,
91
109
  serviceEnded: 'the workspace service (presmium serve) ended',
92
110
  appEnded: 'the Presmium Studio app ended',
93
111
  modelVariables: (variables, unset) => `${variables.join(', ')} go together; ${unset.join(' and ')} ${unset.length > 1 ? 'are' : 'is'} not set.`,
94
112
  },
95
113
  }
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's port (default: a free one), for a proxy that needs it in advance. */
34
+ /** 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
35
  previewPort?: number
33
36
  env?: NodeJS.ProcessEnv
34
37
  presmium?: string
@@ -38,7 +41,10 @@ export interface StudioOptions {
38
41
 
39
42
  export interface Studio {
40
43
  url: string
44
+ networkUrls: string[]
41
45
  workspaceServerUrl: string
46
+ /** `movedFrom` is the default port when it was in use and the MCP address differs from the usual one. */
47
+ mcp: { url: string, tokenFile: string, movedFrom?: number }
42
48
  root: string
43
49
  home: string
44
50
  log: string
@@ -52,6 +58,23 @@ function studioHome(env: NodeJS.ProcessEnv = process.env): string {
52
58
  return join(env.XDG_STATE_HOME || join(env.HOME || homedir(), '.local', 'state'), 'presmium', 'studio')
53
59
  }
54
60
 
61
+ /** Independent of the installation/profile so upgrades and restarts preserve external MCP access. */
62
+ function workspaceCredential(home: string, dir: string): { token: string, file: string } {
63
+ const directory = join(home, 'mcp')
64
+ mkdirSync(directory, { recursive: true, mode: 0o700 })
65
+ const id = createHash('sha256').update(realpathSync(dir)).digest('hex').slice(0, 32)
66
+ const file = join(directory, `${id}.token`)
67
+ try {
68
+ writeFileSync(file, `${randomBytes(24).toString('base64url')}\n`, { flag: 'wx', mode: 0o600 })
69
+ } catch (error) {
70
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error
71
+ }
72
+ chmodSync(file, 0o600)
73
+ const token = readFileSync(file, 'utf8').trim()
74
+ if (!/^[A-Za-z0-9_-]{32}$/.test(token)) throw new Error(STUDIO_MESSAGES[systemLocale()].badMcpToken(file))
75
+ return { token, file }
76
+ }
77
+
55
78
  /** The bundle `@lincyaw/dsh` this package depends on: the directory the profile links to. */
56
79
  function bundleDir(): string {
57
80
  return realpathSync(dirname(createRequire(join(PACKAGE_DIR, 'package.json')).resolve('@lincyaw/dsh/package.json')))
@@ -81,12 +104,59 @@ function installProfile(home: string, bundle: string): string {
81
104
  return name
82
105
  }
83
106
 
84
- /** The `presmium` command of the `@lincyaw/presmium` package this one depends on. */
85
- function presmiumBin(): string {
86
- return join(dirname(createRequire(join(PACKAGE_DIR, 'package.json')).resolve('@lincyaw/presmium/package.json')), 'bin', 'presmium.mjs')
107
+ /**
108
+ * The `presmium` command a Studio started by itself (`presmium-studio`) runs: `@lincyaw/presmium` where it can be
109
+ * resolved from here, else the one on PATH. `presmium studio` passes its own instead; Studio does not depend on it, which
110
+ * would make the two packages depend on each other.
111
+ */
112
+ function presmiumBin(env: NodeJS.ProcessEnv, missing: string): string {
113
+ try {
114
+ return join(dirname(createRequire(join(PACKAGE_DIR, 'package.json')).resolve('@lincyaw/presmium/package.json')), 'bin', 'presmium.mjs')
115
+ } catch {}
116
+ const names = process.platform === 'win32' ? ['presmium.cmd', 'presmium'] : ['presmium']
117
+ for (const dir of (env.PATH ?? '').split(delimiter).filter(Boolean)) {
118
+ for (const name of names) {
119
+ const script = existsSync(join(dir, name)) ? nodeScript(join(dir, name)) : undefined
120
+ if (script) return script
121
+ }
122
+ }
123
+ throw new Error(missing)
87
124
  }
88
125
 
89
- const WILDCARD = /^(?:0\.0\.0\.0|::|(?:0+:){7}0+|::ffff:0\.0\.0\.0)$/i
126
+ /** The Node script a command runs: the file itself (an npm link), or the target a pnpm shim names. */
127
+ function nodeScript(command: string): string | undefined {
128
+ try {
129
+ const file = realpathSync(command)
130
+ const head = readFileSync(file, 'utf8').slice(0, 4096)
131
+ if (/\.[cm]?js$/.test(file) || /^#!.*\bnode\b/.test(head)) return file
132
+ const target = /cmd-shim-target=(.+)$/m.exec(head)?.[1]?.trim()
133
+ return target && existsSync(target) ? target : undefined
134
+ } catch {
135
+ return undefined
136
+ }
137
+ }
138
+
139
+ const WILDCARD = /^0\.0\.0\.0$/
140
+
141
+ function networkHosts(): string[] {
142
+ return [...new Set(Object.values(networkInterfaces()).flatMap(entries => entries ?? []).filter(entry => entry.family === 'IPv4' && !entry.internal).map(entry => entry.address))]
143
+ }
144
+
145
+ function authority(host: string, port: number): string {
146
+ return `${bracketIPv6(host)}:${port}`
147
+ }
148
+
149
+ function httpOrigin(host: string, port: number): string {
150
+ return `http://${authority(host, port)}`
151
+ }
152
+
153
+ function studioUrl(backend: string, publicUrl: string | undefined, host: string, port: number): string {
154
+ const token = new URL(backend).searchParams.get('token')
155
+ if (!token) throw new Error('DeepSeek Harness printed an address without its launch token')
156
+ const url = new URL(publicUrl ?? `http://${authority(host, port)}/`)
157
+ url.searchParams.set('token', token)
158
+ return url.href
159
+ }
90
160
 
91
161
  function freePort(listenAddress: string, port: number): Promise<number | undefined> {
92
162
  return new Promise((done) => {
@@ -147,31 +217,55 @@ export async function startStudio(options: StudioOptions): Promise<Studio> {
147
217
  const env = options.env ?? process.env
148
218
  const t = STUDIO_MESSAGES[systemLocale(env)]
149
219
  const { listenAddress } = options
150
- if (listenAddress !== undefined && (isIP(listenAddress) === 0 || WILDCARD.test(listenAddress))) {
220
+ if (listenAddress !== undefined && isIP(listenAddress) === 0) {
151
221
  throw new Error(t.badHost(listenAddress))
152
222
  }
153
- const port = await choosePort(listenAddress ?? '127.0.0.1', options.port)
154
- const origins = options.publicUrl ? [new URL(options.publicUrl).origin] : [`http://${bracketIPv6(listenAddress ?? '127.0.0.1')}:${port}`, ...!listenAddress || listenAddress === '127.0.0.1' ? [`http://localhost:${port}`] : []]
223
+ const boundAddress = listenAddress ?? '127.0.0.1'
224
+ const wildcard = WILDCARD.test(boundAddress)
225
+ // External MCP clients keep the default address, so it is preferred; an explicit port must be free.
226
+ let previewPort = options.previewPort ?? DEFAULT_PREVIEW_PORT
227
+ let movedFrom: number | undefined
228
+ if (previewPort !== 0 && await freePort(boundAddress, previewPort) === undefined) {
229
+ if (options.previewPort !== undefined) throw new Error(t.previewPortInUse(previewPort, boundAddress))
230
+ movedFrom = previewPort
231
+ previewPort = 0
232
+ }
233
+ const port = await choosePort(boundAddress, options.port)
234
+ const dshAddress = wildcard ? '127.0.0.1' : boundAddress
235
+ const dshPort = wildcard ? await choosePort(dshAddress, undefined) : port
236
+ const hosts = wildcard ? networkHosts() : []
237
+ const primaryHost = hosts[0] ?? dshAddress
238
+ const origins = options.publicUrl
239
+ ? [new URL(options.publicUrl).origin, ...hosts.map(host => httpOrigin(host, port)), httpOrigin('127.0.0.1', port)]
240
+ : wildcard
241
+ ? [...hosts.map(host => httpOrigin(host, port)), httpOrigin('127.0.0.1', port), `http://localhost:${port}`]
242
+ : [httpOrigin(boundAddress, port), ...boundAddress === '127.0.0.1' ? [`http://localhost:${port}`] : []]
155
243
 
156
244
  const home = studioHome(env)
157
245
  mkdirSync(home, { recursive: true, mode: 0o700 })
158
246
  const bundle = bundleDir()
159
247
  const profile = installProfile(home, bundle)
160
248
  writeProfile(home, profile, 'web', bundle)
249
+ const { token: mcpToken, file: tokenFile } = workspaceCredential(home, options.dir)
161
250
  const log = new Log(join(home, `${profile}.log`))
162
251
  const serviceToken = randomBytes(24).toString('base64url')
163
252
  const started: LaunchedProcess[] = []
253
+ let proxy: Proxy | undefined
164
254
  const stopAll = async () => {
255
+ await proxy?.close()
256
+ proxy = undefined
165
257
  for (const launched of started.reverse()) await launched.stop()
166
258
  started.length = 0
167
259
  }
168
260
 
169
261
  try {
262
+ const presmium = options.presmium ?? presmiumBin(env, t.presmiumMissing)
170
263
  const server = launchWorkspaceServer({
171
- presmium: options.presmium ?? presmiumBin(),
264
+ presmium,
172
265
  dir: resolve(options.dir),
173
266
  serviceToken,
174
- ...options.previewPort ? { port: options.previewPort } : {},
267
+ mcpToken,
268
+ port: previewPort,
175
269
  args: [
176
270
  ...listenAddress ? ['--host', listenAddress] : [],
177
271
  ...origins.flatMap(origin => ['--preview-origin', origin]),
@@ -182,10 +276,16 @@ export async function startStudio(options: StudioOptions): Promise<Studio> {
182
276
  })
183
277
  started.push(server.process)
184
278
  const { url, root } = await server.ready
279
+ const mcpUrl = new URL(`${(options.previewUrl ?? url).replace(/\/+$/, '')}/mcp`)
280
+ if (!options.previewUrl && listenAddress) mcpUrl.hostname = bracketIPv6(primaryHost)
185
281
 
282
+ const trustedHosts = wildcard
283
+ ? [...hosts, hostname(), `${hostname()}.local`]
284
+ : listenAddress ? [listenAddress] : []
186
285
  const dsh = launchNode('DeepSeek Harness', [
187
- dshBin(PACKAGE_DIR), ...launchArgs(profile, 'web'), '--port', String(port), '--no-open',
188
- ...listenAddress ? ['--host', listenAddress, '--trusted-host', `${bracketIPv6(listenAddress)}:${port}`] : [],
286
+ dshBin(PACKAGE_DIR), ...launchArgs(profile, 'web'), '--port', String(dshPort), '--no-open',
287
+ ...wildcard || listenAddress ? ['--host', dshAddress] : [],
288
+ ...trustedHosts.flatMap(host => ['--trusted-host', authority(host, port)]),
189
289
  ...options.publicUrl ? ['--public-url', options.publicUrl, '--trusted-host', new URL(options.publicUrl).host] : [],
190
290
  ], {
191
291
  cwd: root,
@@ -193,6 +293,7 @@ export async function startStudio(options: StudioOptions): Promise<Studio> {
193
293
  ...inheritedEnv(env, name => isLauncherVariable(name) || ['DEEPSEEK_API_KEY', 'DEEPSEEK_BASE_URL', 'DEEPSEEK_SEARCH_BASE_URL'].includes(name)),
194
294
  ...modelEnv(env).env,
195
295
  ...launchEnv(home, env),
296
+ PRESMIUM_COMMAND: presmium,
196
297
  PRESMIUM_SERVICE_URL: url,
197
298
  PRESMIUM_SERVICE_TOKEN: serviceToken,
198
299
  PRESMIUM_WORKSPACE: root,
@@ -200,8 +301,11 @@ export async function startStudio(options: StudioOptions): Promise<Studio> {
200
301
  onOutput: text => log.write('dsh', text),
201
302
  })
202
303
  started.push(dsh)
203
- const address = (await dsh.ready(WEB_READY))[1]!
304
+ const backend = (await dsh.ready(WEB_READY))[1]!
305
+ if (wildcard) proxy = await startProxy({ host: boundAddress, port, target: `http://${authority(dshAddress, dshPort)}` })
204
306
  dsh.stopBuffering()
307
+ const address = studioUrl(backend, options.publicUrl, primaryHost, port)
308
+ const networkUrls = hosts.slice(1).map(host => studioUrl(backend, `http://${authority(host, port)}/`, host, port))
205
309
  // The address with its launch token, for a host that opens Studio for the user (0600, removed on close).
206
310
  const state = join(home, `${profile}.json`)
207
311
  writeFileSync(state, `${JSON.stringify({ url: address, workspace: root, workspaceServerUrl: url, pid: process.pid }, null, 2)}\n`, { mode: 0o600 })
@@ -213,7 +317,9 @@ export async function startStudio(options: StudioOptions): Promise<Studio> {
213
317
  ]).then(how => (closing ? new Promise<string>(() => {}) : how))
214
318
  return {
215
319
  url: address,
320
+ networkUrls,
216
321
  workspaceServerUrl: url,
322
+ mcp: { url: mcpUrl.href, tokenFile, ...movedFrom ? { movedFrom } : {} },
217
323
  root,
218
324
  home,
219
325
  log: log.file,