@lincyaw/workspace 1.0.0-rc.101 → 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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lincyaw/workspace",
3
- "version": "1.0.0-rc.101",
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/compiler": "1.0.0-rc.101",
38
- "@lincyaw/kernel": "1.0.0-rc.101",
39
- "@lincyaw/design": "1.0.0-rc.101",
40
- "@lincyaw/server": "1.0.0-rc.101"
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.101"
44
+ "@lincyaw/mcp": "1.0.0-rc.102"
45
45
  }
46
46
  }
@@ -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
+ }
@@ -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'
@@ -477,7 +478,9 @@ async function startWorkspace(options: ServeOptions): Promise<WorkspaceServer> {
477
478
  transcriptionAdoption = createTranscriptionAdoption({ documentEditor, transcriptions })
478
479
  audioAuthoring = createDocumentAudioAuthoring({ root, editor, uploads: mediaUploads, revisions: history?.revisions, services: authoringServices, reviewRequired: config.settings['presmium.assistant']?.review === 'required' })
479
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 })
480
482
  const routeOptions = {
483
+ mcpSettings: mcpSettings.route,
481
484
  speechSettings: speechSettingsRoute(speechSettings),
482
485
  changesRoutes: workspaceChanges.routes,
483
486
  config,