@lincyaw/studio 0.0.0-stage → 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,28 @@
1
- # Temporary Holding Version
1
+ # @lincyaw/studio
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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).
4
+
5
+ Part of [Presmium](https://github.com/Lincyaw/presmium), which turns lectures written in MyST Markdown into web pages, slides, Jupyter notebooks and narrated lectures.
6
+
7
+ ## Usage
8
+
9
+ ```sh
10
+ pnpm add -g @lincyaw/studio
11
+ presmium-studio [dir] [--port <n>] [--host <addr>]
12
+ ```
13
+
14
+ In a project with `pnpm add -D @lincyaw/studio`, `pnpm exec presmium studio` is the same command.
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.
17
+
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
+
20
+ 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 `presmium-studio.log`) is `$XDG_STATE_HOME/presmium/studio`, never your own `~/.dsh`.
21
+
22
+ ## Documentation
23
+
24
+ - [Design of the workbench on DeepSeek Harness](https://github.com/Lincyaw/presmium/blob/main/docs/design-dsh.md)
25
+
26
+ ## License
27
+
28
+ Apache-2.0. DeepSeek Harness is a separate project under the MIT license; this package is not affiliated with or endorsed by DeepSeek.
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+ import { createJiti } from 'jiti'
3
+
4
+ const jiti = createJiti(import.meta.url)
5
+ const { main } = await jiti.import('../src/cli.ts')
6
+ process.exitCode = await main(process.argv.slice(2))
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "@lincyaw/studio",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "presmium studio: Presmium's workbench on DeepSeek Harness in one command, with the workspace service of a directory (experimental)",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/Lincyaw/presmium.git",
9
+ "directory": "packages/studio"
10
+ },
11
+ "homepage": "https://github.com/Lincyaw/presmium/tree/main/packages/studio#readme",
12
+ "bugs": "https://github.com/Lincyaw/presmium/issues",
13
+ "keywords": [
14
+ "presmium",
15
+ "studio",
16
+ "workbench",
17
+ "dsh",
18
+ "deepseek-harness"
19
+ ],
20
+ "type": "module",
21
+ "engines": {
22
+ "node": ">=22.19"
23
+ },
24
+ "publishConfig": {
25
+ "access": "public"
26
+ },
27
+ "bin": {
28
+ "presmium-studio": "./bin/presmium-studio.mjs"
29
+ },
30
+ "exports": {
31
+ ".": "./src/index.ts",
32
+ "./package.json": "./package.json"
33
+ },
34
+ "files": [
35
+ "bin",
36
+ "src"
37
+ ],
38
+ "dependencies": {
39
+ "@deepseek-ai/dsh": "0.2.1-alpha.4",
40
+ "jiti": "^2.7.0",
41
+ "@lincyaw/dsh": "0.1.0",
42
+ "presmium": "1.0.0-rc.0"
43
+ },
44
+ "devDependencies": {
45
+ "@lincyaw/cli": "1.0.0-rc.0"
46
+ }
6
47
  }
package/src/cli.ts ADDED
@@ -0,0 +1,78 @@
1
+ import { existsSync, statSync } from 'node:fs'
2
+ import { resolve } from 'node:path'
3
+ import { parseArgs } from 'node:util'
4
+ import { modelEnv } from './model.ts'
5
+ import { startStudio } from './studio.ts'
6
+
7
+ const USAGE = `Usage: presmium studio [dir] [options]
8
+
9
+ The workbench of Presmium (experimental): DeepSeek Harness with Presmium's bundle, and the workspace
10
+ service of the directory (the workspace root, or a deck's directory; default: .). It prints the one
11
+ address to open in the browser. The model is chosen in the workbench's model settings, or given by the
12
+ environment: DEEPSEEK_API_KEY, or PRESMIUM_MODEL_URL, PRESMIUM_MODEL_KEY and PRESMIUM_MODEL_PROVIDER for
13
+ a Messages-compatible service. DeepSeek Harness's home (sessions, model settings and credentials, the
14
+ log presmium-studio.log) is $XDG_STATE_HOME/presmium/studio.
15
+
16
+ Options:
17
+ --port <n> the workbench's port (default: 4320, or a free one when that is in use)
18
+ --host <addr> listen on this address of the machine on the local network instead of 127.0.0.1, with
19
+ no login: whoever reaches the port works as you
20
+ -h, --help show this help`
21
+
22
+ export interface MainOptions {
23
+ presmium?: string
24
+ }
25
+
26
+ function portOf(value: string | undefined): number | undefined {
27
+ if (value === undefined) return undefined
28
+ const n = Number(value)
29
+ if (!Number.isInteger(n) || n < 0 || n > 65535) throw new Error(`--port takes a port number, not "${value}"`)
30
+ return n
31
+ }
32
+
33
+ export async function main(argv: string[], options: MainOptions = {}): Promise<number> {
34
+ let values: { port?: string, host?: string, help?: boolean }
35
+ let dir: string
36
+ try {
37
+ const parsed = parseArgs({ args: argv, allowPositionals: true, options: { port: { type: 'string' }, host: { type: 'string' }, help: { type: 'boolean', short: 'h' } } })
38
+ values = parsed.values
39
+ const [given = '.', ...extra] = parsed.positionals
40
+ if (extra.length > 0) throw new Error(`unexpected argument "${extra[0]}"`)
41
+ dir = resolve(given)
42
+ if (!values.help && (!existsSync(dir) || !statSync(dir).isDirectory())) throw new Error(`${dir} is not a directory`)
43
+ portOf(values.port)
44
+ } catch (error) {
45
+ process.stderr.write(`presmium studio: ${error instanceof Error ? error.message : String(error)}\n\n${USAGE}\n`)
46
+ return 2
47
+ }
48
+ if (values.help) {
49
+ process.stdout.write(`${USAGE}\n`)
50
+ return 0
51
+ }
52
+
53
+ const model = modelEnv(process.env)
54
+ if (model.warning) process.stderr.write(`presmium studio: ${model.warning}\n`)
55
+
56
+ let studio
57
+ try {
58
+ studio = await startStudio({ dir, port: portOf(values.port), ...values.host ? { host: values.host } : {}, ...options.presmium ? { presmium: options.presmium } : {} })
59
+ } catch (error) {
60
+ process.stderr.write(`presmium studio: ${error instanceof Error ? error.message : String(error)}\n`)
61
+ return 2
62
+ }
63
+ process.stdout.write(`studio ${studio.url}\n`)
64
+ if (values.host && values.host !== '127.0.0.1' && values.host !== '::1') {
65
+ process.stderr.write(`presmium studio: listening on ${values.host}, on the local network, with no login: anyone who reaches port ${new URL(studio.url).port} (and the previews' port ${new URL(studio.service).port}) 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.\n`)
66
+ }
67
+
68
+ const signals = ['SIGINT', 'SIGTERM', 'SIGHUP'] as const
69
+ let stop = () => {}
70
+ const stopped = new Promise<void>(done => stop = done)
71
+ for (const signal of signals) process.once(signal, stop)
72
+ const ended = await Promise.race([stopped.then(() => undefined), studio.ended])
73
+ for (const signal of signals) process.off(signal, stop)
74
+ await studio.close()
75
+ if (ended === undefined) return 0
76
+ process.stderr.write(`presmium studio: ${ended}; the log is ${studio.log}\n`)
77
+ return 1
78
+ }
package/src/index.ts ADDED
@@ -0,0 +1,6 @@
1
+ export { main } from './cli.ts'
2
+ export type { MainOptions } from './cli.ts'
3
+ export { DEFAULT_PORT, PROFILE, presmiumBin, startStudio, studioHome } from './studio.ts'
4
+ export type { Studio, StudioOptions } from './studio.ts'
5
+ export { modelEnv } from './model.ts'
6
+ export type { ModelEnv } from './model.ts'
package/src/model.ts ADDED
@@ -0,0 +1,21 @@
1
+ export const MODEL_VARIABLES = ['PRESMIUM_MODEL_URL', 'PRESMIUM_MODEL_KEY', 'PRESMIUM_MODEL_PROVIDER'] as const
2
+
3
+ export interface ModelEnv {
4
+ env: Record<string, string>
5
+ from: string[]
6
+ warning?: string
7
+ }
8
+
9
+ const searchUrl = (url: string) => `${url.replace(/\/+$/, '').replace(/\/v1$/, '')}/v1`
10
+
11
+ const service = (url: string) => ({ DEEPSEEK_BASE_URL: url, DEEPSEEK_SEARCH_BASE_URL: searchUrl(url) })
12
+
13
+ export function modelEnv(env: NodeJS.ProcessEnv): ModelEnv {
14
+ const [url, key, provider] = MODEL_VARIABLES.map(name => env[name]?.trim() || undefined)
15
+ if (url && key && provider) return { env: { ...service(url), DEEPSEEK_API_KEY: key }, from: [...MODEL_VARIABLES] }
16
+ const unset = MODEL_VARIABLES.filter((_, i) => ![url, key, provider][i])
17
+ const warning = unset.length < MODEL_VARIABLES.length ? { warning: `${MODEL_VARIABLES.join(', ')} go together; ${unset.join(' and ')} ${unset.length > 1 ? 'are' : 'is'} not set` } : {}
18
+ const deepseek = env.DEEPSEEK_API_KEY?.trim()
19
+ if (deepseek) return { env: { DEEPSEEK_API_KEY: deepseek }, from: ['DEEPSEEK_API_KEY'], ...warning }
20
+ return { env: {}, from: [], ...warning }
21
+ }
package/src/studio.ts ADDED
@@ -0,0 +1,257 @@
1
+ import { spawn } from 'node:child_process'
2
+ import type { ChildProcess } from 'node:child_process'
3
+ import { randomBytes } from 'node:crypto'
4
+ import { closeSync, mkdirSync, openSync, renameSync, writeSync } from 'node:fs'
5
+ import { createRequire } from 'node:module'
6
+ import { createServer, isIP } from 'node:net'
7
+ import type { AddressInfo } from 'node:net'
8
+ import { homedir } from 'node:os'
9
+ import { dirname, join, resolve } from 'node:path'
10
+ import { fileURLToPath } from 'node:url'
11
+ import { dshBin, launchArgs, launchEnv, WATCHDOG, WEB_READY, writeProfile } from '@lincyaw/dsh/launch'
12
+ import { modelEnv } from './model.ts'
13
+
14
+ export const PROFILE = 'presmium-studio'
15
+ export const DEFAULT_PORT = 4320
16
+ const START_MS = 180_000
17
+ const STOP_MS = 15_000
18
+ const LOG_BYTES = 16 << 20
19
+
20
+ const PACKAGE_DIR = fileURLToPath(new URL('..', import.meta.url))
21
+
22
+ export interface StudioOptions {
23
+ dir: string
24
+ port?: number
25
+ host?: string
26
+ env?: NodeJS.ProcessEnv
27
+ presmium?: string
28
+ }
29
+
30
+ export interface Studio {
31
+ url: string
32
+ service: string
33
+ root: string
34
+ home: string
35
+ log: string
36
+ ended: Promise<string>
37
+ close(): Promise<void>
38
+ }
39
+
40
+ export function studioHome(env: NodeJS.ProcessEnv = process.env): string {
41
+ return join(env.XDG_STATE_HOME || join(env.HOME || homedir(), '.local', 'state'), 'presmium', 'studio')
42
+ }
43
+
44
+ export function presmiumBin(): string {
45
+ return join(dirname(createRequire(join(PACKAGE_DIR, 'package.json')).resolve('presmium/package.json')), 'bin', 'presmium.mjs')
46
+ }
47
+
48
+ const urlHost = (host: string) => (host.includes(':') ? `[${host}]` : host)
49
+
50
+ const WILDCARD = /^(?:0\.0\.0\.0|::|(?:0+:){7}0+|::ffff:0\.0\.0\.0)$/i
51
+
52
+ function freePort(host: string, port: number): Promise<number | undefined> {
53
+ return new Promise((done) => {
54
+ const server = createServer()
55
+ server.once('error', () => done(undefined))
56
+ server.listen(port, host, () => {
57
+ const bound = (server.address() as AddressInfo).port
58
+ server.close(() => done(bound))
59
+ })
60
+ })
61
+ }
62
+
63
+ async function choosePort(host: string, port: number | undefined): Promise<number> {
64
+ if (port) {
65
+ if (await freePort(host, port) === undefined) throw new Error(`port ${port} of ${host} is in use: give another with --port`)
66
+ return port
67
+ }
68
+ const chosen = (port === undefined ? await freePort(host, DEFAULT_PORT) : undefined) ?? await freePort(host, 0)
69
+ if (chosen === undefined) throw new Error(`no free port on ${host}`)
70
+ return chosen
71
+ }
72
+
73
+ function inherited(env: NodeJS.ProcessEnv, drop: (name: string) => boolean): Record<string, string> {
74
+ return Object.fromEntries(Object.entries(env).filter((entry): entry is [string, string] => entry[1] !== undefined && !drop(entry[0])))
75
+ }
76
+
77
+ const OWN = (name: string) => /^(?:DSH_|PRESMIUM_MODEL_|PRESMIUM_SERVICE_)/.test(name) || ['PRESMIUM_WORKSPACE', 'NODE_ENV', 'PORT'].includes(name)
78
+
79
+ class Log {
80
+ readonly file: string
81
+ #fd: number
82
+ #bytes = 0
83
+ readonly #rest = new Map<string, string>()
84
+
85
+ constructor(file: string) {
86
+ this.file = file
87
+ this.#fd = openSync(file, 'w', 0o600)
88
+ }
89
+
90
+ write(name: string, text: string): void {
91
+ if (this.#fd < 0) return
92
+ const lines = ((this.#rest.get(name) ?? '') + text).split('\n')
93
+ this.#rest.set(name, lines.pop()!)
94
+ if (lines.length === 0) return
95
+ const out = lines.map(line => `[${name}] ${line}\n`).join('')
96
+ if (this.#bytes + out.length > LOG_BYTES) {
97
+ closeSync(this.#fd)
98
+ renameSync(this.file, `${this.file}.1`)
99
+ this.#fd = openSync(this.file, 'w', 0o600)
100
+ this.#bytes = 0
101
+ }
102
+ this.#bytes += writeSync(this.#fd, out)
103
+ }
104
+
105
+ close(): void {
106
+ if (this.#fd < 0) return
107
+ for (const [name, rest] of this.#rest) if (rest) this.write(name, '\n')
108
+ closeSync(this.#fd)
109
+ this.#fd = -1
110
+ }
111
+ }
112
+
113
+ interface Supervised {
114
+ child: ChildProcess
115
+ ready(pattern: RegExp): Promise<RegExpExecArray>
116
+ started(): void
117
+ exited: Promise<void>
118
+ stop(): Promise<void>
119
+ }
120
+
121
+ function supervise(name: string, args: string[], options: { cwd: string, env: Record<string, string>, log: Log }): Supervised {
122
+ const child = spawn(process.execPath, [WATCHDOG, process.execPath, ...args], { cwd: options.cwd, env: options.env, detached: true, stdio: ['pipe', 'pipe', 'pipe'] })
123
+ child.stdin!.on('error', () => {})
124
+ let output: string | undefined = ''
125
+ const waiting = new Set<() => void>()
126
+ const read = (chunk: Buffer) => {
127
+ const text = chunk.toString()
128
+ options.log.write(name, text)
129
+ if (output === undefined) return
130
+ output += text
131
+ for (const check of waiting) check()
132
+ }
133
+ child.stdout!.on('data', read)
134
+ child.stderr!.on('data', read)
135
+ let ended = false
136
+ const exited = new Promise<void>(done => child.once('exit', () => {
137
+ ended = true
138
+ done()
139
+ }))
140
+ return {
141
+ child,
142
+ exited,
143
+ ready(pattern) {
144
+ return new Promise((resolveReady, reject) => {
145
+ const tail = () => (output ?? '').trimEnd().split('\n').slice(-12).map(line => ` ${line}`).join('\n')
146
+ const timer = setTimeout(() => finish(new Error(`${name} did not start within ${START_MS / 1000} s:\n${tail()}\n`)), START_MS)
147
+ const check = () => {
148
+ const match = pattern.exec(output ?? '')
149
+ if (match) finish(match)
150
+ }
151
+ const finish = (result: RegExpExecArray | Error) => {
152
+ clearTimeout(timer)
153
+ waiting.delete(check)
154
+ if (result instanceof Error) reject(result)
155
+ else resolveReady(result)
156
+ }
157
+ waiting.add(check)
158
+ void exited.then(() => finish(new Error(`${name} ended before it was ready:\n${tail()}\n`)))
159
+ check()
160
+ })
161
+ },
162
+ started() {
163
+ output = undefined
164
+ },
165
+ async stop() {
166
+ if (ended) return
167
+ child.kill('SIGTERM')
168
+ const timer = setTimeout(() => {
169
+ try {
170
+ process.kill(-child.pid!, 'SIGKILL')
171
+ } catch {
172
+ }
173
+ }, STOP_MS)
174
+ await exited
175
+ clearTimeout(timer)
176
+ },
177
+ }
178
+ }
179
+
180
+ export async function startStudio(options: StudioOptions): Promise<Studio> {
181
+ const env = options.env ?? process.env
182
+ const host = options.host
183
+ if (host !== undefined && (isIP(host) === 0 || WILDCARD.test(host))) {
184
+ throw new Error(`--host takes one address of this machine, such as 192.168.0.21, not "${host}" (DeepSeek Harness listens on one concrete address, never on all of them)`)
185
+ }
186
+ const port = await choosePort(host ?? '127.0.0.1', options.port)
187
+ const origins = [`http://${urlHost(host ?? '127.0.0.1')}:${port}`, ...!host || host === '127.0.0.1' ? [`http://localhost:${port}`] : []]
188
+
189
+ const home = studioHome(env)
190
+ mkdirSync(home, { recursive: true, mode: 0o700 })
191
+ writeProfile(home, PROFILE, 'web')
192
+ const log = new Log(join(home, 'presmium-studio.log'))
193
+ const token = randomBytes(24).toString('base64url')
194
+ const started: Supervised[] = []
195
+ const stopAll = async () => {
196
+ for (const process_ of started.reverse()) await process_.stop()
197
+ started.length = 0
198
+ }
199
+
200
+ try {
201
+ const service = supervise('serve', [
202
+ options.presmium ?? presmiumBin(), 'serve', resolve(options.dir), '--port', '0',
203
+ ...host ? ['--host', host] : [],
204
+ ...origins.flatMap(origin => ['--preview-origin', origin]),
205
+ ], {
206
+ cwd: resolve(options.dir),
207
+ env: { ...inherited(env, name => OWN(name) || name.startsWith('DEEPSEEK_')), PRESMIUM_SERVICE_TOKEN: token },
208
+ log,
209
+ })
210
+ started.push(service)
211
+ const url = (await service.ready(/^serve {2}(http\S+)$/m))[1]!
212
+ const root = (await service.ready(/^workspace {2}(.+)$/m))[1]!.trim()
213
+ service.started()
214
+
215
+ const dsh = supervise('dsh', [
216
+ dshBin(PACKAGE_DIR), ...launchArgs(PROFILE, 'web'), '--port', String(port), '--no-open',
217
+ ...host ? ['--host', host, '--trusted-host', `${urlHost(host)}:${port}`] : [],
218
+ ], {
219
+ cwd: root,
220
+ env: {
221
+ ...inherited(env, name => OWN(name) || ['DEEPSEEK_API_KEY', 'DEEPSEEK_BASE_URL', 'DEEPSEEK_SEARCH_BASE_URL'].includes(name)),
222
+ ...modelEnv(env).env,
223
+ ...launchEnv(home),
224
+ PRESMIUM_SERVICE_URL: url,
225
+ PRESMIUM_SERVICE_TOKEN: token,
226
+ PRESMIUM_WORKSPACE: root,
227
+ },
228
+ log,
229
+ })
230
+ started.push(dsh)
231
+ const address = (await dsh.ready(WEB_READY))[1]!
232
+ dsh.started()
233
+
234
+ let closing: Promise<void> | undefined
235
+ const ended = Promise.race([
236
+ service.exited.then(() => 'the workspace service (presmium serve) ended'),
237
+ dsh.exited.then(() => 'DeepSeek Harness ended'),
238
+ ]).then(how => (closing ? new Promise<string>(() => {}) : how))
239
+ return {
240
+ url: address,
241
+ service: url,
242
+ root,
243
+ home,
244
+ log: log.file,
245
+ ended,
246
+ close() {
247
+ closing ??= stopAll().finally(() => log.close())
248
+ return closing
249
+ },
250
+ }
251
+ } catch (error) {
252
+ await stopAll()
253
+ log.close()
254
+ const message = error instanceof Error ? error.message : String(error)
255
+ throw new Error(`${message.endsWith('\n') ? message : `${message}; `}the whole log is ${log.file}`)
256
+ }
257
+ }