@lincyaw/studio 0.2.0-rc.1 → 0.2.0-rc.100

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,28 @@
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
+ Local AI clients use native stdio, configured once as `presmium mcp <absolute-workspace-or-document-path>`. It starts or reuses the workspace authoring service before initialization. With default local listener settings, Studio can borrow a service already started by MCP; closing Studio leaves that service running. Keep the original owning stdio session open while using Studio: closing it ends the borrowed service and Studio. Studio does not migrate to a replacement host. Explicit `--host`, `--preview-port` or `--preview-url` settings require stopping the current service and starting Studio with those settings first. Older services lacking the separate launcher credential also require replacement before Studio can attach.
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.1",
3
+ "version": "0.2.0-rc.100",
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,12 @@
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.1",
42
- "@lincyaw/presmium": "1.0.0-rc.2"
42
+ "@lincyaw/dsh": "0.2.0-rc.100",
43
+ "@lincyaw/kernel": "1.0.0-rc.101"
43
44
  },
44
45
  "devDependencies": {
45
- "@lincyaw/cli": "1.0.0-rc.2"
46
+ "@lincyaw/cli": "1.0.0-rc.101"
46
47
  }
47
48
  }
package/src/cli.ts CHANGED
@@ -27,6 +27,24 @@ 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
49
  let values: { port?: string, host?: string, 'public-url'?: string, 'preview-url'?: string, 'preview-port'?: string, help?: boolean }
32
50
  let dir: string
@@ -53,24 +71,36 @@ 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
79
  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 } : {} })
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
  }
63
85
  process.stdout.write(`studio ${studio.url}\n`)
86
+ for (const url of studio.networkUrls) process.stdout.write(`network ${url}\n`)
87
+ process.stdout.write(`mcp ${studio.mcp.url}\n`)
88
+ process.stderr.write(`${t.mcpToken(studio.mcp.tokenFile)}\n`)
89
+ if (studio.mcp.movedFrom) process.stderr.write(`${t.previewPortMoved(studio.mcp.movedFrom, studio.mcp.url)}\n`)
64
90
  process.stderr.write(`${t.log(studio.log)}\n`)
65
91
  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`)
92
+ process.stderr.write(`${studio.networkUrls.length
93
+ ? t.openOnAllNetworks(new URL(studio.url).port, new URL(studio.workspaceServerUrl).port)
94
+ : t.openOnNetwork(values.host, new URL(studio.url).port, new URL(studio.workspaceServerUrl).port)}\n`)
67
95
  }
68
96
 
69
97
  const signals = ['SIGINT', 'SIGTERM', 'SIGHUP'] as const
70
98
  let stop = () => {}
71
99
  const stopped = new Promise<void>(done => stop = done)
100
+ parentStop = stop
72
101
  for (const signal of signals) process.once(signal, stop)
73
102
  const ended = await Promise.race([stopped.then(() => undefined), studio.ended])
103
+ unwatchParent()
74
104
  for (const signal of signals) process.off(signal, stop)
75
105
  await studio.close()
76
106
  if (ended === undefined) return 0
package/src/messages.ts CHANGED
@@ -10,14 +10,21 @@ 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
20
+ existingService(url: string): string
15
21
  noFreePort(address: string): string
16
22
  badHost(address: string): string
17
23
  wholeLog(message: string, file: string): string
18
24
  serviceEnded: string
19
25
  appEnded: string
20
26
  modelVariables(variables: readonly string[], unset: string[]): string
27
+ presmiumMissing: string
21
28
  }
22
29
 
23
30
  export const STUDIO_MESSAGES: Record<Locale, StudioMessages> = {
@@ -32,24 +39,31 @@ presmium-studio-<散列>.log(每个安装一个)保存在 $XDG_STATE_HOME/pr
32
39
 
33
40
  选项:
34
41
  --port <端口> Presmium Studio 的端口(默认为 4320,被占用时取空闲端口)
35
- --host <地址> 改为监听本机在局域网中的这个地址,而不是 127.0.0.1,且没有登录:
42
+ --host <地址> 改为监听本机在局域网中的一个 IP 地址或 0.0.0.0,且没有登录:
36
43
  任何能访问这个端口的人都以你的身份操作
37
44
  --public-url <网址> 有反向代理在前面时浏览器打开的根地址(例如 Presmium 云端);
38
45
  它的主机受信任,打印的网址用它。代理需保留 Host 并转发 WebSocket
39
46
  --preview-url <网址> 同样情况下预览所在的地址,由代理转发到工作区服务;可以带路径,
40
47
  此时它必须与 Studio 不同源,否则预览中文稿的代码能读到 Studio 的会话
41
- --preview-port <端口> 工作区服务的端口(默认为空闲端口),供需要事先知道端口的代理使用
48
+ --preview-port <端口> 工作区服务与 HTTP MCP 的固定端口(默认 4321,被占用时换一个空闲端口);0 为随机端口
42
49
  -h, --help 显示本说明`,
43
50
  badPort: value => `--port 需要 0 到 65535 之间的端口号,而不是“${value}”。`,
44
51
  badUrl: (option, value) => `${option} 需要一个完整的网址,例如 https://studio.example.com/,而不是“${value}”。`,
52
+ presmiumMissing: 'presmium-studio 找不到 presmium 命令。Presmium Studio 随 Presmium 一起安装:请运行 pnpm add -g @lincyaw/presmium,然后用 presmium studio 启动。',
45
53
  unexpectedArgument: argument => `多余的参数“${argument}”。只能给出一个目录。`,
46
54
  notDirectory: dir => `${dir} 不是目录。请给出工作区的根目录或一份文稿所在的目录。`,
47
55
  log: file => `presmium studio: 日志在 ${file}`,
48
56
  openOnNetwork: (address, port, previewPort) => `presmium studio: 正在 ${address} 上监听,局域网中的设备可以访问,且没有登录:任何能用上面的网址访问端口 ${port}(以及预览的端口 ${previewPort})的人都以你的身份使用这个工作区(编辑、运行代码、使用你的模型)。请只在可信的网络中使用;不加 --host 时只在本机监听。`,
57
+ openOnAllNetworks: (port, previewPort) => `presmium studio: 正在全部局域网网络接口上监听,且没有登录:任何能用上面的网址访问端口 ${port}(以及预览的端口 ${previewPort})的人都以你的身份使用这个工作区(编辑、运行代码、使用你的模型)。请只在可信的网络中使用;不加 --host 时只在本机监听。`,
49
58
  ended: (how, log) => `presmium studio: ${how}。日志在 ${log}`,
50
59
  portInUse: (port, address) => `${address} 的端口 ${port} 已被占用。请用 --port 指定另一个端口。`,
60
+ previewPortInUse: (port, address) => `${address} 的工作区与 MCP 端口 ${port} 已被占用。请停止占用它的服务,或用 --preview-port 指定另一个固定端口。`,
61
+ previewPortMoved: (port, url) => `presmium studio: 端口 ${port} 已被占用,这次的 MCP 地址是 ${url}。按默认地址配置的 MCP 客户端这次连不上;需要固定地址时,用 --preview-port 指定一个空闲端口。`,
62
+ mcpToken: file => `presmium studio: HTTP MCP 客户端从 ${file} 读取访问令牌(server.json 使用 token 字段),设置 Authorization: Bearer <访问令牌>。本机客户端建议用 presmium mcp 自动发现服务。`,
63
+ badMcpToken: file => `MCP 访问令牌文件 ${file} 无效。请移走该文件后重试,并在客户端更新访问令牌。`,
64
+ existingService: url => `工作区服务已在 ${url} 运行。当前服务不支持复用,或指定的预览监听选项需要新服务;请先关闭它,再启动 Studio。`,
51
65
  noFreePort: address => `${address} 上没有空闲的端口。请停止占用端口的服务后重试。`,
52
- badHost: address => `--host 需要本机的一个地址,例如 192.168.0.21,而不是“${address}”(Presmium Studio 只在一个确定的地址上监听,不能同时监听全部地址)。`,
66
+ badHost: address => `--host 需要本机的一个 IP 地址,例如 192.168.0.21,也可以使用 0.0.0.0,而不是“${address}”。`,
53
67
  wholeLog: (message, file) => `${message}${message.endsWith('\n') ? '' : '。'}完整的日志在 ${file}`,
54
68
  serviceEnded: '工作区服务(presmium serve)已停止',
55
69
  appEnded: 'Presmium Studio 的应用进程已停止',
@@ -67,30 +81,36 @@ presmium-studio-<hash>.log (one per installation) are kept in $XDG_STATE_HOME/pr
67
81
 
68
82
  Options:
69
83
  --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
84
+ --host <addr> listen on one local IP address, or on all IPv4 network interfaces with 0.0.0.0,
85
+ with no login: whoever reaches the port works as you
72
86
  --public-url <url> the root browsers open when a reverse proxy fronts Studio (as in Presmium
73
87
  Cloud): its host is trusted, and the printed address uses it. The proxy keeps Host and
74
88
  forwards WebSockets
75
89
  --preview-url <url> in that case, the address of the previews, forwarded to the workspace service; it
76
90
  may have a path, and should be another origin than Studio’s, or the documents’ code in
77
91
  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
92
+ --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
93
  -h, --help show this help`,
80
94
  badPort: value => `--port takes a port number from 0 to 65535, not “${value}”.`,
81
95
  badUrl: (option, value) => `${option} takes a full address, such as https://studio.example.com/, not “${value}”.`,
96
+ 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
97
  unexpectedArgument: argument => `Unexpected argument “${argument}”. Give one directory.`,
83
98
  notDirectory: dir => `${dir} is not a directory. Give the workspace root, or the directory of a document.`,
84
99
  log: file => `presmium studio: log ${file}`,
85
100
  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.`,
101
+ 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
102
  ended: (how, log) => `presmium studio: ${how}; the log is ${log}`,
87
103
  portInUse: (port, address) => `Port ${port} of ${address} is in use. Give another with --port.`,
104
+ 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.`,
105
+ 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.`,
106
+ 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.`,
107
+ badMcpToken: file => `MCP access token file ${file} is invalid. Move it aside and retry, then update the access token in your clients.`,
108
+ 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.`,
88
109
  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).`,
110
+ 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
111
  wholeLog: (message, file) => `${message.endsWith('\n') ? message : `${message}; `}the whole log is ${file}`,
91
112
  serviceEnded: 'the workspace service (presmium serve) ended',
92
113
  appEnded: 'the Presmium Studio app ended',
93
114
  modelVariables: (variables, unset) => `${variables.join(', ')} go together; ${unset.join(' and ')} ${unset.length > 1 ? 'are' : 'is'} not set.`,
94
115
  },
95
116
  }
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,22 @@
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
+ import { findWorkspaceServiceState, readServiceState, serveStateDir } from '@lincyaw/kernel/node'
11
12
  import { STUDIO_MESSAGES, systemLocale } from './messages.ts'
12
13
  import { 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's port (default: a free one), for a proxy that needs it in advance. */
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')))
@@ -81,12 +105,59 @@ function installProfile(home: string, bundle: string): string {
81
105
  return name
82
106
  }
83
107
 
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')
108
+ /**
109
+ * The `presmium` command a Studio started by itself (`presmium-studio`) runs: `@lincyaw/presmium` where it can be
110
+ * resolved from here, else the one on PATH. `presmium studio` passes its own instead; Studio does not depend on it, which
111
+ * would make the two packages depend on each other.
112
+ */
113
+ function presmiumBin(env: NodeJS.ProcessEnv, missing: string): string {
114
+ try {
115
+ return join(dirname(createRequire(join(PACKAGE_DIR, 'package.json')).resolve('@lincyaw/presmium/package.json')), 'bin', 'presmium.mjs')
116
+ } catch {}
117
+ const names = process.platform === 'win32' ? ['presmium.cmd', 'presmium'] : ['presmium']
118
+ for (const dir of (env.PATH ?? '').split(delimiter).filter(Boolean)) {
119
+ for (const name of names) {
120
+ const script = existsSync(join(dir, name)) ? nodeScript(join(dir, name)) : undefined
121
+ if (script) return script
122
+ }
123
+ }
124
+ throw new Error(missing)
125
+ }
126
+
127
+ /** The Node script a command runs: the file itself (an npm link), or the target a pnpm shim names. */
128
+ function nodeScript(command: string): string | undefined {
129
+ try {
130
+ const file = realpathSync(command)
131
+ const head = readFileSync(file, 'utf8').slice(0, 4096)
132
+ if (/\.[cm]?js$/.test(file) || /^#!.*\bnode\b/.test(head)) return file
133
+ const target = /cmd-shim-target=(.+)$/m.exec(head)?.[1]?.trim()
134
+ return target && existsSync(target) ? target : undefined
135
+ } catch {
136
+ return undefined
137
+ }
138
+ }
139
+
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)}`
87
152
  }
88
153
 
89
- const WILDCARD = /^(?:0\.0\.0\.0|::|(?:0+:){7}0+|::ffff:0\.0\.0\.0)$/i
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
+ }
90
161
 
91
162
  function freePort(listenAddress: string, port: number): Promise<number | undefined> {
92
163
  return new Promise((done) => {
@@ -147,31 +218,61 @@ export async function startStudio(options: StudioOptions): Promise<Studio> {
147
218
  const env = options.env ?? process.env
148
219
  const t = STUDIO_MESSAGES[systemLocale(env)]
149
220
  const { listenAddress } = options
150
- if (listenAddress !== undefined && (isIP(listenAddress) === 0 || WILDCARD.test(listenAddress))) {
221
+ if (listenAddress !== undefined && isIP(listenAddress) === 0) {
151
222
  throw new Error(t.badHost(listenAddress))
152
223
  }
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}`] : []]
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
+ const wildcard = WILDCARD.test(boundAddress)
229
+ // External MCP clients keep the default address, so it is preferred; an explicit port must be free.
230
+ let previewPort = options.previewPort ?? DEFAULT_PREVIEW_PORT
231
+ let movedFrom: number | undefined
232
+ if (!existing && previewPort !== 0 && await freePort(boundAddress, previewPort) === undefined) {
233
+ if (options.previewPort !== undefined) throw new Error(t.previewPortInUse(previewPort, boundAddress))
234
+ movedFrom = previewPort
235
+ previewPort = 0
236
+ }
237
+ const port = await choosePort(boundAddress, options.port)
238
+ const dshAddress = wildcard ? '127.0.0.1' : boundAddress
239
+ const dshPort = wildcard ? await choosePort(dshAddress, undefined) : port
240
+ const hosts = wildcard ? networkHosts() : []
241
+ const primaryHost = hosts[0] ?? dshAddress
242
+ const origins = options.publicUrl
243
+ ? [new URL(options.publicUrl).origin, ...hosts.map(host => httpOrigin(host, port)), httpOrigin('127.0.0.1', port)]
244
+ : wildcard
245
+ ? [...hosts.map(host => httpOrigin(host, port)), httpOrigin('127.0.0.1', port), `http://localhost:${port}`]
246
+ : [httpOrigin(boundAddress, port), ...boundAddress === '127.0.0.1' ? [`http://localhost:${port}`] : []]
155
247
 
156
248
  const home = studioHome(env)
157
249
  mkdirSync(home, { recursive: true, mode: 0o700 })
158
250
  const bundle = bundleDir()
159
251
  const profile = installProfile(home, bundle)
160
252
  writeProfile(home, profile, 'web', bundle)
253
+ const credential = existing ? undefined : workspaceCredential(home, options.dir)
254
+ const mcpToken = credential?.token
161
255
  const log = new Log(join(home, `${profile}.log`))
162
- const serviceToken = randomBytes(24).toString('base64url')
256
+ let serviceToken = existing?.state.launcherToken ?? randomBytes(24).toString('base64url')
163
257
  const started: LaunchedProcess[] = []
258
+ let proxy: Proxy | undefined
259
+ let hostMonitor: ReturnType<typeof setInterval> | undefined
164
260
  const stopAll = async () => {
261
+ clearInterval(hostMonitor)
262
+ await proxy?.close()
263
+ proxy = undefined
165
264
  for (const launched of started.reverse()) await launched.stop()
166
265
  started.length = 0
167
266
  }
168
267
 
169
268
  try {
170
- const server = launchWorkspaceServer({
171
- presmium: options.presmium ?? presmiumBin(),
269
+ const presmium = options.presmium ?? presmiumBin(env, t.presmiumMissing)
270
+ const server = existing ? undefined : launchWorkspaceServer({
271
+ presmium,
172
272
  dir: resolve(options.dir),
173
273
  serviceToken,
174
- ...options.previewPort ? { port: options.previewPort } : {},
274
+ mcpToken: mcpToken!,
275
+ port: previewPort,
175
276
  args: [
176
277
  ...listenAddress ? ['--host', listenAddress] : [],
177
278
  ...origins.flatMap(origin => ['--preview-origin', origin]),
@@ -180,12 +281,53 @@ export async function startStudio(options: StudioOptions): Promise<Studio> {
180
281
  env,
181
282
  onOutput: text => { log.write('serve', text); options.onServiceOutput?.(text) },
182
283
  })
183
- started.push(server.process)
184
- const { url, root } = await server.ready
284
+ if (server) started.push(server.process)
285
+ let ready: { url: string, root: string }
286
+ if (existing) ready = { url: existing.state.url, root: existing.root }
287
+ else {
288
+ try { ready = await server!.ready }
289
+ catch (error) {
290
+ // Another local client may win the workspace lease after our initial discovery.
291
+ await server!.process.stop()
292
+ const deadline = Date.now() + 10_000
293
+ while (!existing && Date.now() < deadline) {
294
+ existing = findWorkspaceServiceState(options.dir, env)
295
+ if (!existing) await new Promise(done => setTimeout(done, 100))
296
+ }
297
+ if (!existing || !canReuse()) throw error
298
+ serviceToken = existing.state.launcherToken!
299
+ ready = { url: existing.state.url, root: existing.root }
300
+ }
301
+ }
302
+ const { url, root } = ready
303
+ const tokenFile = existing ? join(serveStateDir(root, env), 'server.json') : credential!.file
304
+ let serverEnded: Promise<unknown>
305
+ if (existing) {
306
+ const ownerPid = existing.state.pid
307
+ const response = await fetch(`${url}/__presmium/presmium.workspace/preview-origins`, {
308
+ method: 'POST', headers: { authorization: `Bearer ${serviceToken}`, 'content-type': 'application/json' },
309
+ body: JSON.stringify({ origins }), signal: AbortSignal.timeout(10_000),
310
+ })
311
+ if (!response.ok) throw new Error(t.existingService(url))
312
+ // Studio borrows this host. If its owner closes it, end the workbench without stopping or replacing it.
313
+ serverEnded = new Promise<void>(done => {
314
+ hostMonitor = setInterval(() => {
315
+ const current = readServiceState(join(serveStateDir(root, env), 'server.json'))
316
+ if (!current || current.pid !== ownerPid || current.url !== url) { clearInterval(hostMonitor); done() }
317
+ }, 500)
318
+ hostMonitor.unref()
319
+ })
320
+ } else serverEnded = server!.process.exited
321
+ const mcpUrl = new URL(`${(options.previewUrl ?? url).replace(/\/+$/, '')}/mcp`)
322
+ if (!options.previewUrl && listenAddress) mcpUrl.hostname = bracketIPv6(primaryHost)
185
323
 
324
+ const trustedHosts = wildcard
325
+ ? [...hosts, hostname(), `${hostname()}.local`]
326
+ : listenAddress ? [listenAddress] : []
186
327
  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}`] : [],
328
+ dshBin(PACKAGE_DIR), ...launchArgs(profile, 'web'), '--port', String(dshPort), '--no-open',
329
+ ...wildcard || listenAddress ? ['--host', dshAddress] : [],
330
+ ...trustedHosts.flatMap(host => ['--trusted-host', authority(host, port)]),
189
331
  ...options.publicUrl ? ['--public-url', options.publicUrl, '--trusted-host', new URL(options.publicUrl).host] : [],
190
332
  ], {
191
333
  cwd: root,
@@ -193,6 +335,7 @@ export async function startStudio(options: StudioOptions): Promise<Studio> {
193
335
  ...inheritedEnv(env, name => isLauncherVariable(name) || ['DEEPSEEK_API_KEY', 'DEEPSEEK_BASE_URL', 'DEEPSEEK_SEARCH_BASE_URL'].includes(name)),
194
336
  ...modelEnv(env).env,
195
337
  ...launchEnv(home, env),
338
+ PRESMIUM_COMMAND: presmium,
196
339
  PRESMIUM_SERVICE_URL: url,
197
340
  PRESMIUM_SERVICE_TOKEN: serviceToken,
198
341
  PRESMIUM_WORKSPACE: root,
@@ -200,20 +343,25 @@ export async function startStudio(options: StudioOptions): Promise<Studio> {
200
343
  onOutput: text => log.write('dsh', text),
201
344
  })
202
345
  started.push(dsh)
203
- const address = (await dsh.ready(WEB_READY))[1]!
346
+ const backend = (await dsh.ready(WEB_READY))[1]!
347
+ if (wildcard) proxy = await startProxy({ host: boundAddress, port, target: `http://${authority(dshAddress, dshPort)}` })
204
348
  dsh.stopBuffering()
349
+ const address = studioUrl(backend, options.publicUrl, primaryHost, port)
350
+ const networkUrls = hosts.slice(1).map(host => studioUrl(backend, `http://${authority(host, port)}/`, host, port))
205
351
  // The address with its launch token, for a host that opens Studio for the user (0600, removed on close).
206
352
  const state = join(home, `${profile}.json`)
207
353
  writeFileSync(state, `${JSON.stringify({ url: address, workspace: root, workspaceServerUrl: url, pid: process.pid }, null, 2)}\n`, { mode: 0o600 })
208
354
 
209
355
  let closing: Promise<void> | undefined
210
356
  const ended = Promise.race([
211
- server.process.exited.then(() => t.serviceEnded),
357
+ serverEnded.then(() => t.serviceEnded),
212
358
  dsh.exited.then(() => t.appEnded),
213
359
  ]).then(how => (closing ? new Promise<string>(() => {}) : how))
214
360
  return {
215
361
  url: address,
362
+ networkUrls,
216
363
  workspaceServerUrl: url,
364
+ mcp: { url: mcpUrl.href, tokenFile, ...movedFrom ? { movedFrom } : {} },
217
365
  root,
218
366
  home,
219
367
  log: log.file,