@lincyaw/studio 0.2.0-rc.79 → 0.2.0-rc.80

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
@@ -17,9 +17,11 @@ Studio is included with Presmium. In a project with `pnpm add -D @lincyaw/presmi
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.
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
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`.
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`.
23
25
 
24
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.
25
27
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lincyaw/studio",
3
- "version": "0.2.0-rc.79",
3
+ "version": "0.2.0-rc.80",
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": {
@@ -39,9 +39,10 @@
39
39
  "@deepseek-ai/dsh": "0.2.1-alpha.4",
40
40
  "http-proxy-3": "2.0.1",
41
41
  "jiti": "^2.7.0",
42
- "@lincyaw/dsh": "0.2.0-rc.79"
42
+ "@lincyaw/dsh": "0.2.0-rc.80",
43
+ "@lincyaw/kernel": "1.0.0-rc.81"
43
44
  },
44
45
  "devDependencies": {
45
- "@lincyaw/cli": "1.0.0-rc.80"
46
+ "@lincyaw/cli": "1.0.0-rc.81"
46
47
  }
47
48
  }
package/src/messages.ts CHANGED
@@ -17,6 +17,7 @@ export interface StudioMessages {
17
17
  previewPortMoved(port: number, url: string): string
18
18
  mcpToken(file: string): string
19
19
  badMcpToken(file: string): string
20
+ existingService(url: string): string
20
21
  noFreePort(address: string): string
21
22
  badHost(address: string): string
22
23
  wholeLog(message: string, file: string): string
@@ -58,8 +59,9 @@ presmium-studio-<散列>.log(每个安装一个)保存在 $XDG_STATE_HOME/pr
58
59
  portInUse: (port, address) => `${address} 的端口 ${port} 已被占用。请用 --port 指定另一个端口。`,
59
60
  previewPortInUse: (port, address) => `${address} 的工作区与 MCP 端口 ${port} 已被占用。请停止占用它的服务,或用 --preview-port 指定另一个固定端口。`,
60
61
  previewPortMoved: (port, url) => `presmium studio: 端口 ${port} 已被占用,这次的 MCP 地址是 ${url}。按默认地址配置的 MCP 客户端这次连不上;需要固定地址时,用 --preview-port 指定一个空闲端口。`,
61
- mcpToken: file => `presmium studio: MCP 客户端使用 HTTP(Streamable HTTP),从 ${file} 读取访问令牌,设置 Authorization: Bearer <访问令牌>;同一目录重启与升级后保持不变。`,
62
+ mcpToken: file => `presmium studio: HTTP MCP 客户端从 ${file} 读取访问令牌(server.json 使用 token 字段),设置 Authorization: Bearer <访问令牌>。本机客户端建议用 presmium mcp 自动发现服务。`,
62
63
  badMcpToken: file => `MCP 访问令牌文件 ${file} 无效。请移走该文件后重试,并在客户端更新访问令牌。`,
64
+ existingService: url => `工作区服务已在 ${url} 运行。当前服务不支持复用,或指定的预览监听选项需要新服务;请先关闭它,再启动 Studio。`,
63
65
  noFreePort: address => `${address} 上没有空闲的端口。请停止占用端口的服务后重试。`,
64
66
  badHost: address => `--host 需要本机的一个 IP 地址,例如 192.168.0.21,也可以使用 0.0.0.0,而不是“${address}”。`,
65
67
  wholeLog: (message, file) => `${message}${message.endsWith('\n') ? '' : '。'}完整的日志在 ${file}`,
@@ -101,8 +103,9 @@ Options:
101
103
  portInUse: (port, address) => `Port ${port} of ${address} is in use. Give another with --port.`,
102
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.`,
103
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.`,
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.`,
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.`,
105
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.`,
106
109
  noFreePort: address => `There is no free port on ${address}. Stop a service that uses one, then retry.`,
107
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}”.`,
108
111
  wholeLog: (message, file) => `${message.endsWith('\n') ? message : `${message}; `}the whole log is ${file}`,
package/src/studio.ts CHANGED
@@ -8,6 +8,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'
13
14
  import { startProxy } from './proxy.ts'
@@ -221,11 +222,14 @@ export async function startStudio(options: StudioOptions): Promise<Studio> {
221
222
  throw new Error(t.badHost(listenAddress))
222
223
  }
223
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))
224
228
  const wildcard = WILDCARD.test(boundAddress)
225
229
  // External MCP clients keep the default address, so it is preferred; an explicit port must be free.
226
230
  let previewPort = options.previewPort ?? DEFAULT_PREVIEW_PORT
227
231
  let movedFrom: number | undefined
228
- if (previewPort !== 0 && await freePort(boundAddress, previewPort) === undefined) {
232
+ if (!existing && previewPort !== 0 && await freePort(boundAddress, previewPort) === undefined) {
229
233
  if (options.previewPort !== undefined) throw new Error(t.previewPortInUse(previewPort, boundAddress))
230
234
  movedFrom = previewPort
231
235
  previewPort = 0
@@ -246,12 +250,15 @@ export async function startStudio(options: StudioOptions): Promise<Studio> {
246
250
  const bundle = bundleDir()
247
251
  const profile = installProfile(home, bundle)
248
252
  writeProfile(home, profile, 'web', bundle)
249
- const { token: mcpToken, file: tokenFile } = workspaceCredential(home, options.dir)
253
+ const credential = existing ? undefined : workspaceCredential(home, options.dir)
254
+ const mcpToken = credential?.token
250
255
  const log = new Log(join(home, `${profile}.log`))
251
- const serviceToken = randomBytes(24).toString('base64url')
256
+ let serviceToken = existing?.state.launcherToken ?? randomBytes(24).toString('base64url')
252
257
  const started: LaunchedProcess[] = []
253
258
  let proxy: Proxy | undefined
259
+ let hostMonitor: ReturnType<typeof setInterval> | undefined
254
260
  const stopAll = async () => {
261
+ clearInterval(hostMonitor)
255
262
  await proxy?.close()
256
263
  proxy = undefined
257
264
  for (const launched of started.reverse()) await launched.stop()
@@ -260,11 +267,11 @@ export async function startStudio(options: StudioOptions): Promise<Studio> {
260
267
 
261
268
  try {
262
269
  const presmium = options.presmium ?? presmiumBin(env, t.presmiumMissing)
263
- const server = launchWorkspaceServer({
270
+ const server = existing ? undefined : launchWorkspaceServer({
264
271
  presmium,
265
272
  dir: resolve(options.dir),
266
273
  serviceToken,
267
- mcpToken,
274
+ mcpToken: mcpToken!,
268
275
  port: previewPort,
269
276
  args: [
270
277
  ...listenAddress ? ['--host', listenAddress] : [],
@@ -274,8 +281,43 @@ export async function startStudio(options: StudioOptions): Promise<Studio> {
274
281
  env,
275
282
  onOutput: text => { log.write('serve', text); options.onServiceOutput?.(text) },
276
283
  })
277
- started.push(server.process)
278
- 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
279
321
  const mcpUrl = new URL(`${(options.previewUrl ?? url).replace(/\/+$/, '')}/mcp`)
280
322
  if (!options.previewUrl && listenAddress) mcpUrl.hostname = bracketIPv6(primaryHost)
281
323
 
@@ -312,7 +354,7 @@ export async function startStudio(options: StudioOptions): Promise<Studio> {
312
354
 
313
355
  let closing: Promise<void> | undefined
314
356
  const ended = Promise.race([
315
- server.process.exited.then(() => t.serviceEnded),
357
+ serverEnded.then(() => t.serviceEnded),
316
358
  dsh.exited.then(() => t.appEnded),
317
359
  ]).then(how => (closing ? new Promise<string>(() => {}) : how))
318
360
  return {