@lincyaw/workspace 1.0.0-rc.80 → 1.0.0-rc.82

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.80",
3
+ "version": "1.0.0-rc.82",
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/kernel": "1.0.0-rc.80",
38
- "@lincyaw/compiler": "1.0.0-rc.80",
39
- "@lincyaw/server": "1.0.0-rc.80",
40
- "@lincyaw/design": "1.0.0-rc.80"
37
+ "@lincyaw/compiler": "1.0.0-rc.82",
38
+ "@lincyaw/design": "1.0.0-rc.82",
39
+ "@lincyaw/server": "1.0.0-rc.82",
40
+ "@lincyaw/kernel": "1.0.0-rc.82"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@types/mime-types": "^3.0.1",
44
- "@lincyaw/mcp": "1.0.0-rc.80"
44
+ "@lincyaw/mcp": "1.0.0-rc.82"
45
45
  }
46
46
  }
@@ -62,6 +62,8 @@ export interface WorkspaceRoutesOptions {
62
62
  projectRoutes?: Record<string, Route>
63
63
  speechSettings?: Route
64
64
  changesRoutes?: Record<string, Route>
65
+ /** Shared mutable allow-list; a later local Studio may register its preview origin. */
66
+ previewOrigins?: string[]
65
67
  }
66
68
 
67
69
  function toRendererIds(body: unknown): string[] | undefined {
@@ -86,6 +88,25 @@ export function workspaceRoutes(options: WorkspaceRoutesOptions): ServerContribu
86
88
  const transcriptions = options.transcriptions ?? ownedTranscriptions!
87
89
  const ownedAudio = options.audioAuthoringRoutes ? undefined : createDocumentAudioAuthoring({ root: config.root, editor, revisions, audio: options.audio, reviewRequired: config.settings['presmium.assistant']?.review === 'required' })
88
90
  const routes: Record<string, Route> = {
91
+ ...options.previewOrigins ? { 'preview-origins': {
92
+ role: 'owner', maxBody: 8192,
93
+ handle: async (request: Request) => {
94
+ if (request.method !== 'POST') return problemResponse(405, 'POST')
95
+ const body: unknown = await request.json().catch(() => undefined)
96
+ if (!isRecord(body) || Object.keys(body).some(key => key !== 'origins') || !Array.isArray(body.origins) || body.origins.length > 16) return problemResponse(400, 'preview-origins-invalid')
97
+ const origins: string[] = []
98
+ for (const value of body.origins) {
99
+ if (typeof value !== 'string' || value.length > 2048) return problemResponse(400, 'preview-origins-invalid')
100
+ let url: URL
101
+ try { url = new URL(value) } catch { return problemResponse(400, 'preview-origins-invalid') }
102
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.origin !== value) return problemResponse(400, 'preview-origins-invalid')
103
+ if (!origins.includes(value) && !options.previewOrigins!.includes(value)) origins.push(value)
104
+ }
105
+ if (options.previewOrigins!.length + origins.length > 128) return problemResponse(413, 'preview-origins-limit')
106
+ options.previewOrigins!.push(...origins)
107
+ return jsonResponse({ added: origins.length })
108
+ },
109
+ } satisfies Route } : {},
89
110
  ...options.speechSettings ? { 'speech-settings': options.speechSettings } : {},
90
111
  ...documentEditorRoutes({ root: config.root, editor, documentEditor: options.documentEditor, workbench }),
91
112
  ...(options.audioAuthoringRoutes ?? ownedAudio!.routes),
package/src/node/serve.ts CHANGED
@@ -1,18 +1,20 @@
1
1
  import { createMediaUploads } from './media-uploads.ts'
2
+ import { randomBytes } from 'node:crypto'
2
3
  import { createProjectAuthoring } from './projects.ts'
3
4
  import { createDocumentHistory } from './document-history.ts'
4
5
  import { createAuthoringClients } from './authoring-clients.ts'
5
6
  import { createAuthoringWindows } from './authoring-windows.ts'
6
7
  import { readAuthoringDocument } from './document-editor.ts'
7
8
  import { createDocumentCapture } from './capture.ts'
8
- import { mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'
9
+ import { chmodSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
9
10
  import { stripVTControlCharacters } from 'node:util'
10
11
  import { tmpdir } from 'node:os'
11
- import { join, relative } from 'node:path'
12
+ import { join, relative, resolve } from 'node:path'
12
13
  import { Compiler, operatorDir as resolveOperatorDir, pluginLogger, runBlock, workspacePlugins } from '@lincyaw/compiler'
13
14
  import type { Compilation, CompilerOptions } from '@lincyaw/compiler'
14
15
  import { CHANGE_REVIEW, DOCUMENT_FILES, DOCUMENT_LOCKS, DOCUMENT_VOICE_TASKS, errorMessage, PreviewPreparing, PRODUCTION_AUDIO_AUTHORING, REVISIONS, SPEECH, VOICEOVER, VOICEOVER_EXECUTION } from '@lincyaw/kernel'
15
- import { irRevision, OperatorSpeechSettings, serveStateDir } from '@lincyaw/kernel/node'
16
+ import { irRevision, OperatorSpeechSettings, readServiceState, removeServiceState, serveStateDir, tryAcquireServiceHostLease } from '@lincyaw/kernel/node'
17
+ import type { ServiceHostLease } from '@lincyaw/kernel/node'
16
18
  import { speechSettingsRoute } from './speech-settings.ts'
17
19
  import type { ApprovalKind, CanonicalSource, ChangeReviewService, Finding, IRDocument, Logger, ProductionAudioAuthoring, ServiceToken, SiteSpec, SpeechService } from '@lincyaw/kernel'
18
20
  import { serverConfigKey, servedDocument, startServer } from '@lincyaw/server'
@@ -61,6 +63,9 @@ export interface ServeOptions {
61
63
  allow?: ApprovalKind[]
62
64
  approvalTimeoutMs?: number
63
65
  log?: Logger
66
+ /** A launcher may reserve the shared workspace host before starting it. Released after close. */
67
+ hostLease?: ServiceHostLease
68
+ signal?: AbortSignal
64
69
  }
65
70
 
66
71
  export interface WorkspaceServer {
@@ -91,6 +96,44 @@ function makeStateDir(root: string, env: NodeJS.ProcessEnv): string {
91
96
  }
92
97
 
93
98
  export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceServer> {
99
+ const root = realpathSync(resolve(options.dir)), env = options.env ?? process.env
100
+ const advertised = readServiceState(join(serveStateDir(root, env), 'server.json'))
101
+ if (advertised) throw Object.assign(new Error('workspace-service-already-running'), { code: 'workspace-service-already-running', url: advertised.url })
102
+ const lease = options.hostLease ?? await tryAcquireServiceHostLease(root, env)
103
+ if (!lease) {
104
+ const state = readServiceState(join(serveStateDir(root, env), 'server.json'))
105
+ throw Object.assign(new Error('workspace-service-already-running'), { code: 'workspace-service-already-running', ...state ? { url: state.url } : {} })
106
+ }
107
+ if (lease.root !== root) throw new Error('workspace-service-lease-scope')
108
+ const existing = readServiceState(join(serveStateDir(root, env), 'server.json'))
109
+ if (existing) {
110
+ await lease.release()
111
+ throw Object.assign(new Error('workspace-service-already-running'), { code: 'workspace-service-already-running', url: existing.url })
112
+ }
113
+ let running: WorkspaceServer | undefined, closing: Promise<void> | undefined
114
+ const close = () => closing ??= Promise.resolve().then(async () => {
115
+ try { await running?.close() }
116
+ finally { await lease.release() }
117
+ })
118
+ const compromised = () => { void close().catch(error => (options.log ?? pluginLogger('presmium serve')).error(errorMessage(error))) }
119
+ try {
120
+ lease.signal.throwIfAborted()
121
+ options.signal?.throwIfAborted()
122
+ running = await startWorkspace(options)
123
+ lease.signal.throwIfAborted()
124
+ options.signal?.throwIfAborted()
125
+ lease.signal.addEventListener('abort', compromised, { once: true })
126
+ return { ...running, async close() {
127
+ lease.signal.removeEventListener('abort', compromised)
128
+ await close()
129
+ } }
130
+ } catch (error) {
131
+ await close()
132
+ throw error
133
+ }
134
+ }
135
+
136
+ async function startWorkspace(options: ServeOptions): Promise<WorkspaceServer> {
94
137
  const env = options.env ?? process.env
95
138
  const log = options.log ?? pluginLogger('presmium serve')
96
139
  const config = readWorkspaceConfig(options.dir)
@@ -106,7 +149,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
106
149
  const writer = localWriter(config)
107
150
  const editor = new SourceEditor({ config, writer, locks })
108
151
  const check = options.check ?? (compilation => compilation.check())
109
- const launcherToken = env.PRESMIUM_SERVICE_TOKEN || undefined
152
+ const launcherToken = env.PRESMIUM_SERVICE_TOKEN || randomBytes(32).toString('hex')
110
153
  const preview = { origins: options.previewOrigins ?? [] }
111
154
  // Behind a proxy that forwards a path (`--public-url https://host/user/a/preview/`), the site, the jobs' files and the
112
155
  // previews' links are all below that path; the server finds its own routes below it too.
@@ -210,9 +253,11 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
210
253
  authoringServicesClosed = true
211
254
  transcriptionAdoption?.close()
212
255
  for (const load of nodeServicePending) load.controller.abort()
213
- await Promise.all([mediaUploads?.close(), projectAuthoring?.close(), transcriptions?.close(), audioAuthoring?.close(), voiceAuthoring?.close(), documentHistory?.close(), authoringClients?.close(), authoringWindows?.close(), workspaceRoutesOwner?.close?.()])
256
+ const results = await Promise.allSettled([mediaUploads?.close(), projectAuthoring?.close(), transcriptions?.close(), audioAuthoring?.close(), voiceAuthoring?.close(), documentHistory?.close(), authoringClients?.close(), authoringWindows?.close(), workspaceRoutesOwner?.close?.()])
214
257
  await Promise.allSettled([...nodeServicePending].map(load => load.promise))
215
258
  nodeServiceLoads.clear()
259
+ const failure = results.find(result => result.status === 'rejected')
260
+ if (failure?.status === 'rejected') throw failure.reason
216
261
  }
217
262
 
218
263
  const spec: SiteSpec = siteSpec(config, docs().map(doc => siteDocument(doc)))
@@ -365,7 +410,6 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
365
410
  listenAddress: options.listenAddress,
366
411
  port: options.port,
367
412
  ...options.publicUrl ? { publicUrl: options.publicUrl } : {},
368
- stateFile,
369
413
  forward: async (path) => {
370
414
  lookAtDisk()
371
415
  if (path.startsWith(outputsPath)) return await jobs.origin()
@@ -381,7 +425,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
381
425
  approvals: { ...config.approvals, ...Object.fromEntries((options.allow ?? []).map(kind => [kind, 'allow' as const])) },
382
426
  operatorDir: operatorDirectory,
383
427
  serverHost,
384
- env,
428
+ env: { ...env, PRESMIUM_SERVICE_TOKEN: launcherToken },
385
429
  ...options.approvalTimeoutMs ? { approvalTimeoutMs: options.approvalTimeoutMs } : {},
386
430
  log,
387
431
  async document(dir) {
@@ -434,6 +478,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
434
478
  documentsChanged,
435
479
  workbench,
436
480
  jobs,
481
+ previewOrigins: preview.origins,
437
482
  ...launcherToken ? { launcherToken } : {},
438
483
  }
439
484
  workspaceRoutesOwner = workspaceRoutes(routeOptions)
@@ -444,13 +489,30 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
444
489
  [DOCUMENT_LOCKS, locks],
445
490
  [DOCUMENT_VOICE_TASKS, voiceAuthoring.service],
446
491
  ]
492
+ let hostClosing: Promise<void> | undefined
493
+ const closeHost = (): Promise<void> => hostClosing ??= Promise.resolve().then(async () => {
494
+ // Stop advertising before releasing any authoring resource; contenders keep waiting for the lease.
495
+ removeServiceState(stateFile)
496
+ const results = await Promise.allSettled([
497
+ () => running.close(),
498
+ async () => history?.agentSessionReviews.close(),
499
+ closeAuthoring,
500
+ async () => { for (const session of compileSessions.values()) session.close() },
501
+ () => jobs.close(),
502
+ async () => capture?.close(),
503
+ async () => workbench?.close(),
504
+ async () => site?.close(),
505
+ ].map(async cleanup => cleanup()))
506
+ removeServiceState(stateFile)
507
+ if (home) rmSync(home, { recursive: true, force: true })
508
+ const failure = results.find(result => result.status === 'rejected')
509
+ if (failure?.status === 'rejected') throw failure.reason
510
+ })
447
511
  try {
448
512
  await history?.agentSessionReviews.recover(docs().map(doc => doc.dir))
513
+ options.signal?.throwIfAborted()
449
514
  } catch (error) {
450
- history?.agentSessionReviews.close()
451
- await closeAuthoring()
452
- await workbench.close()
453
- await running.close()
515
+ await closeHost()
454
516
  throw error
455
517
  }
456
518
 
@@ -472,12 +534,12 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
472
534
  }
473
535
  try {
474
536
  site = await startWorkspaceSite({ root, spec, basePath, bundled: options.bundled, stateDir, compile: compileForSite, stampPreviewRevision: (compilation, doc) => workbench!.stampPreviewRevision(compilation, doc), diagnostics: running.diagnostics, preview, log })
537
+ options.signal?.throwIfAborted()
538
+ // Publish only the fully assembled authoring host. Another MCP client may discover it immediately.
539
+ writeFileSync(stateFile, `${JSON.stringify({ url: running.url, mcp: `${running.url}/mcp`, token: running.mcpToken, pid: process.pid, launcherToken }, null, 2)}\n`, { mode: 0o600 })
540
+ chmodSync(stateFile, 0o600)
475
541
  } catch (error) {
476
- await closeAuthoring()
477
- await capture.close()
478
- await workbench.close()
479
- await running.close()
480
- if (home) rmSync(home, { recursive: true, force: true })
542
+ await closeHost()
481
543
  throw error
482
544
  }
483
545
 
@@ -485,17 +547,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
485
547
  url: running.url,
486
548
  root,
487
549
  mcp: { url: `${running.url}/mcp`, stateFile },
488
- async close() {
489
- history?.agentSessionReviews.close()
490
- await closeAuthoring()
491
- for (const session of compileSessions.values()) session.close()
492
- await jobs.close()
493
- await capture?.close()
494
- await workbench?.close()
495
- await site?.close()
496
- await running.close()
497
- if (home) rmSync(home, { recursive: true, force: true })
498
- },
550
+ close: closeHost,
499
551
  }
500
552
  }
501
553