@lincyaw/workspace 1.0.0-rc.100 → 1.0.0-rc.102
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/package.json +6 -6
- package/src/node/git.ts +16 -1
- package/src/node/mcp-settings.ts +68 -0
- package/src/node/routes.ts +2 -0
- package/src/node/serve.ts +4 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lincyaw/workspace",
|
|
3
|
-
"version": "1.0.0-rc.
|
|
3
|
+
"version": "1.0.0-rc.102",
|
|
4
4
|
"description": "Presmium's workspace service (presmium serve): documents, their history, reviews and the workspace site",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -34,13 +34,13 @@
|
|
|
34
34
|
"mime-types": "3.0.2",
|
|
35
35
|
"playwright-chromium": "1.64.1",
|
|
36
36
|
"yaml": "^2.9.1",
|
|
37
|
-
"@lincyaw/
|
|
38
|
-
"@lincyaw/
|
|
39
|
-
"@lincyaw/server": "1.0.0-rc.
|
|
40
|
-
"@lincyaw/design": "1.0.0-rc.
|
|
37
|
+
"@lincyaw/kernel": "1.0.0-rc.102",
|
|
38
|
+
"@lincyaw/compiler": "1.0.0-rc.102",
|
|
39
|
+
"@lincyaw/server": "1.0.0-rc.102",
|
|
40
|
+
"@lincyaw/design": "1.0.0-rc.102"
|
|
41
41
|
},
|
|
42
42
|
"devDependencies": {
|
|
43
43
|
"@types/mime-types": "^3.0.1",
|
|
44
|
-
"@lincyaw/mcp": "1.0.0-rc.
|
|
44
|
+
"@lincyaw/mcp": "1.0.0-rc.102"
|
|
45
45
|
}
|
|
46
46
|
}
|
package/src/node/git.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { execFile, execFileSync } from 'node:child_process'
|
|
2
|
-
import { realpathSync } from 'node:fs'
|
|
2
|
+
import { existsSync, readdirSync, realpathSync } from 'node:fs'
|
|
3
|
+
import { join } from 'node:path'
|
|
4
|
+
import { promisify } from 'node:util'
|
|
3
5
|
import { gitConfigArgs, gitEnvironment } from '@lincyaw/kernel'
|
|
4
6
|
|
|
5
7
|
export interface GitResult {
|
|
@@ -26,6 +28,19 @@ export class Git {
|
|
|
26
28
|
}
|
|
27
29
|
}
|
|
28
30
|
|
|
31
|
+
/** Prepare a new, empty authoring workspace; existing content needs its own real history baseline. */
|
|
32
|
+
static async initialize(root: string): Promise<void> {
|
|
33
|
+
if (Git.isRepository(root) || existsSync(join(root, '.git'))) return
|
|
34
|
+
if (readdirSync(root).some(name => name !== '.DS_Store')) return
|
|
35
|
+
await promisify(execFile)('git', [...gitConfigArgs(), 'init', '--quiet', '--initial-branch=main'], { cwd: root, env: gitEnvironment(process.env) })
|
|
36
|
+
const git = new Git(root)
|
|
37
|
+
const tree = await git.run(['hash-object', '-w', '-t', 'tree', '--stdin'], {}, new Uint8Array())
|
|
38
|
+
if (tree.code !== 0) throw new Error(tree.stderr)
|
|
39
|
+
const commit = (await git.output(['-c', 'user.name=Presmium', '-c', 'user.email=workspace@presmium.invalid', 'commit-tree', tree.stdout.toString('utf8').trim(), '-m', 'Initialize workspace history'])).trim()
|
|
40
|
+
const ref = (await git.output(['symbolic-ref', 'HEAD'])).trim()
|
|
41
|
+
await git.output(['update-ref', ref, commit, '0'.repeat(commit.length)])
|
|
42
|
+
}
|
|
43
|
+
|
|
29
44
|
run(command: string[], env: Record<string, string> = {}, input?: Uint8Array): Promise<GitResult> {
|
|
30
45
|
return new Promise((done) => {
|
|
31
46
|
let inputError: Error | undefined
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
3
|
+
import { basename, dirname, isAbsolute, join } from 'node:path'
|
|
4
|
+
import { isRecord, jsonResponse, problemResponse } from '@lincyaw/kernel'
|
|
5
|
+
import type { McpConnectionSettings, McpConnectionChange, Route } from '@lincyaw/kernel'
|
|
6
|
+
import type { PresmiumServer } from '@lincyaw/server'
|
|
7
|
+
|
|
8
|
+
/** A separate MCP listener never changes the editor's address or takes over the stdio host. */
|
|
9
|
+
export async function createMcpSettings(options: { root: string, stateFile: string, server: PresmiumServer, command?: string }) {
|
|
10
|
+
const file = join(options.root, '.presmium', 'mcp-settings.json')
|
|
11
|
+
let preference: { transport: 'stdio' | 'http', port: number } = { transport: 'stdio', port: 0 }
|
|
12
|
+
try {
|
|
13
|
+
const saved: unknown = JSON.parse(readFileSync(file, 'utf8'))
|
|
14
|
+
if (validPreference(saved)) preference = { transport: saved.transport, port: saved.port }
|
|
15
|
+
} catch { /* A missing or invalid preference leaves the default stdio connection usable. */ }
|
|
16
|
+
let listener: Awaited<ReturnType<PresmiumServer['listenMcp']>> | undefined
|
|
17
|
+
let issue: 'mcp-port-unavailable' | undefined
|
|
18
|
+
if (preference.transport === 'http') {
|
|
19
|
+
try { listener = await options.server.listenMcp(preference.port) } catch { issue = 'mcp-port-unavailable' }
|
|
20
|
+
}
|
|
21
|
+
const command = options.command ?? process.argv[1]
|
|
22
|
+
const stdio = command && isAbsolute(command) && basename(command) === 'presmium.mjs' && existsSync(command)
|
|
23
|
+
? { command: process.execPath, args: [command, 'mcp', options.root] } : undefined
|
|
24
|
+
const revision = () => createHash('sha256').update(JSON.stringify(preference)).digest('hex')
|
|
25
|
+
const read = (): McpConnectionSettings => ({ ...preference, revision: revision(), root: options.root,
|
|
26
|
+
...(stdio ? { stdio } : {}), ...(listener ? { url: listener.url } : {}), ...(issue ? { issue } : {}), stateFile: options.stateFile })
|
|
27
|
+
let queue = Promise.resolve()
|
|
28
|
+
const change = (body: McpConnectionChange) => {
|
|
29
|
+
const result = queue.then(async () => {
|
|
30
|
+
if (body.revision !== revision()) throw new Error('mcp-settings-conflict')
|
|
31
|
+
const next = body.transport === 'http' && (body.port !== preference.port || !listener) ? await options.server.listenMcp(body.port).catch(() => { throw new Error('mcp-port-unavailable') }) : body.transport === 'http' ? listener : undefined
|
|
32
|
+
try {
|
|
33
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
34
|
+
writeFileSync(`${file}.tmp`, JSON.stringify({ transport: body.transport, port: body.port }) + '\n', { mode: 0o600 })
|
|
35
|
+
renameSync(`${file}.tmp`, file)
|
|
36
|
+
} catch (error) { if (next !== listener) await next?.close(); throw error }
|
|
37
|
+
const previous = listener
|
|
38
|
+
preference = { transport: body.transport, port: body.port }; listener = next; issue = undefined
|
|
39
|
+
if (previous !== listener) await previous?.close()
|
|
40
|
+
return read()
|
|
41
|
+
})
|
|
42
|
+
queue = result.then(() => {}, () => {})
|
|
43
|
+
return result
|
|
44
|
+
}
|
|
45
|
+
const route: Route = { role: 'owner', maxBody: 8192, handle: async request => {
|
|
46
|
+
try {
|
|
47
|
+
if (request.method === 'GET') return jsonResponse(read(), 200, { 'cache-control': 'no-store' })
|
|
48
|
+
if (request.method !== 'POST') return problemResponse(405, 'GET or POST')
|
|
49
|
+
const body: unknown = await request.json().catch(() => undefined)
|
|
50
|
+
if (isRecord(body) && body.action === 'export' && typeof body.revision === 'string' && Object.keys(body).length === 2) {
|
|
51
|
+
await queue
|
|
52
|
+
if (body.revision !== revision()) return problemResponse(409, 'mcp-settings-conflict')
|
|
53
|
+
const connection = preference.transport === 'stdio' ? stdio : listener ? { url: listener.url, headers: { Authorization: `Bearer ${options.server.mcpToken}` } } : undefined
|
|
54
|
+
if (!connection) return problemResponse(409, 'mcp-connection-unavailable')
|
|
55
|
+
return jsonResponse({ mcpServers: { presmium: connection } }, 200, { 'cache-control': 'no-store' })
|
|
56
|
+
}
|
|
57
|
+
if (!validPreference(body) || typeof body.revision !== 'string' || Object.keys(body).some(key => !['revision', 'transport', 'port'].includes(key))) return problemResponse(400, 'mcp-settings-invalid')
|
|
58
|
+
return jsonResponse(await change(body as unknown as McpConnectionChange), 200, { 'cache-control': 'no-store' })
|
|
59
|
+
} catch (error) {
|
|
60
|
+
const code = error instanceof Error && ['mcp-settings-conflict', 'mcp-port-unavailable'].includes(error.message) ? error.message : 'mcp-settings-unavailable'
|
|
61
|
+
return problemResponse(code === 'mcp-settings-unavailable' ? 503 : 409, code)
|
|
62
|
+
}
|
|
63
|
+
} }
|
|
64
|
+
return { route }
|
|
65
|
+
}
|
|
66
|
+
function validPreference(value: unknown): value is { transport: 'stdio' | 'http', port: number, revision?: unknown } {
|
|
67
|
+
return isRecord(value) && ['stdio', 'http'].includes(String(value.transport)) && typeof value.port === 'number' && Number.isInteger(value.port) && value.port >= 0 && value.port <= 65535
|
|
68
|
+
}
|
package/src/node/routes.ts
CHANGED
|
@@ -60,6 +60,7 @@ export interface WorkspaceRoutesOptions {
|
|
|
60
60
|
historyRoutes?: Record<string, Route>
|
|
61
61
|
authoringClientRoutes?: Record<string, Route>
|
|
62
62
|
projectRoutes?: Record<string, Route>
|
|
63
|
+
mcpSettings?: Route
|
|
63
64
|
speechSettings?: Route
|
|
64
65
|
changesRoutes?: Record<string, Route>
|
|
65
66
|
/** Shared mutable allow-list; a later local Studio may register its preview origin. */
|
|
@@ -107,6 +108,7 @@ export function workspaceRoutes(options: WorkspaceRoutesOptions): ServerContribu
|
|
|
107
108
|
return jsonResponse({ added: origins.length })
|
|
108
109
|
},
|
|
109
110
|
} satisfies Route } : {},
|
|
111
|
+
...options.mcpSettings ? { 'mcp-settings': options.mcpSettings } : {},
|
|
110
112
|
...options.speechSettings ? { 'speech-settings': options.speechSettings } : {},
|
|
111
113
|
...documentEditorRoutes({ root: config.root, editor, documentEditor: options.documentEditor, workbench }),
|
|
112
114
|
...(options.audioAuthoringRoutes ?? ownedAudio!.routes),
|
package/src/node/serve.ts
CHANGED
|
@@ -16,6 +16,7 @@ import type { Compilation, CompilerOptions } from '@lincyaw/compiler'
|
|
|
16
16
|
import { CHANGE_REVIEW, DOCUMENT_FILES, DOCUMENT_LOCKS, DOCUMENT_VOICE_TASKS, errorMessage, PreviewPreparing, PRODUCTION_AUDIO_AUTHORING, REVISIONS, SPEECH, VOICEOVER, VOICEOVER_EXECUTION } from '@lincyaw/kernel'
|
|
17
17
|
import { irRevision, OperatorSpeechSettings, readServiceState, removeServiceState, serveStateDir, tryAcquireServiceHostLease } from '@lincyaw/kernel/node'
|
|
18
18
|
import type { ServiceHostLease } from '@lincyaw/kernel/node'
|
|
19
|
+
import { createMcpSettings } from './mcp-settings.ts'
|
|
19
20
|
import { speechSettingsRoute } from './speech-settings.ts'
|
|
20
21
|
import type { ApprovalKind, CanonicalSource, ChangeReviewService, Finding, IRDocument, Logger, ProductionAudioAuthoring, ServiceToken, SiteSpec, SpeechService } from '@lincyaw/kernel'
|
|
21
22
|
import { serverConfigKey, servedDocument, startServer } from '@lincyaw/server'
|
|
@@ -140,6 +141,7 @@ async function startWorkspace(options: ServeOptions): Promise<WorkspaceServer> {
|
|
|
140
141
|
const config = readWorkspaceConfig(options.dir)
|
|
141
142
|
if (env.PRESMIUM_AGENT_CANDIDATE === '1') config.settings['presmium.assistant'] = { ...config.settings['presmium.assistant'], review: 'auto' }
|
|
142
143
|
const { root } = config
|
|
144
|
+
await Git.initialize(root).catch(error => log.warn(`the workspace history could not be prepared: ${errorMessage(error)}`))
|
|
143
145
|
const operatorDirectory = resolveOperatorDir(root, options.operatorDir ?? env.PRESMIUM_OPERATOR_DIR)
|
|
144
146
|
const speechSettings = new OperatorSpeechSettings(operatorDirectory, name => env[name])
|
|
145
147
|
const stateDir = makeStateDir(root, env)
|
|
@@ -476,7 +478,9 @@ async function startWorkspace(options: ServeOptions): Promise<WorkspaceServer> {
|
|
|
476
478
|
transcriptionAdoption = createTranscriptionAdoption({ documentEditor, transcriptions })
|
|
477
479
|
audioAuthoring = createDocumentAudioAuthoring({ root, editor, uploads: mediaUploads, revisions: history?.revisions, services: authoringServices, reviewRequired: config.settings['presmium.assistant']?.review === 'required' })
|
|
478
480
|
imageAuthoring = createDocumentImageAuthoring({ root, editor, uploads: mediaUploads, revisions: history?.revisions, reviewRequired: config.settings['presmium.assistant']?.review === 'required' })
|
|
481
|
+
const mcpSettings = await createMcpSettings({ root, stateFile, server: running, command: env.PRESMIUM_COMMAND })
|
|
479
482
|
const routeOptions = {
|
|
483
|
+
mcpSettings: mcpSettings.route,
|
|
480
484
|
speechSettings: speechSettingsRoute(speechSettings),
|
|
481
485
|
changesRoutes: workspaceChanges.routes,
|
|
482
486
|
config,
|