@lincyaw/workspace 1.0.0-rc.9 → 1.0.0-rc.91

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.
@@ -1,7 +1,7 @@
1
1
  import { createHash } from 'node:crypto'
2
2
  import { createRequire } from 'node:module'
3
3
  import { DOCUMENT_ENTRY, fnv1a64, hasRole, isRecord, jsonResponse, problemResponse, PRODUCTION_AUDIO_AUTHORING, pushStream, SPEECH, sseResponse } from '@lincyaw/kernel'
4
- import type { ChangesAnswer, CommitAnswer, CompileJob, DocumentsAnswer, JobsAnswer, Member, PresmiumNodePlugin, RequestContext, Route, SavedAnswer, ServerContribution, SourceTransactionAnswer, SourceTransactionChange } from '@lincyaw/kernel'
4
+ import type { CompileJob, DocumentsAnswer, JobsAnswer, PresmiumNodePlugin, RequestContext, Route, SavedAnswer, ServerContribution, SourceTransactionAnswer, SourceTransactionChange } from '@lincyaw/kernel'
5
5
  import { hasBearerToken } from '@lincyaw/server'
6
6
  import { saveSummary } from '../domain/commit-message.ts'
7
7
  import { documentSummaries, listDocuments } from './config.ts'
@@ -9,12 +9,11 @@ import type { WorkspaceConfig } from './config.ts'
9
9
  import { documentsDiff } from './document-operations.ts'
10
10
  import type { DocumentOperations, DocumentsChange } from './document-operations.ts'
11
11
  import { catchRequestErrors, RequestError } from './errors.ts'
12
- import { lockedError } from './locks.ts'
13
12
  import type { DocumentLocks } from './locks.ts'
14
13
  import type { Revisions } from './revisions.ts'
15
14
  import { reviewRoutes } from './review/routes.ts'
16
15
  import type { AgentSessionReviews } from './review/agent-session-reviews.ts'
17
- import { MAX_SOURCE, MAX_SOURCE_CHANGES, validateDocumentSource } from './source-editor.ts'
16
+ import { MAX_SOURCE, MAX_SOURCE_CHANGES } from './source-editor.ts'
18
17
  import type { SourceEditor } from './source-editor.ts'
19
18
  import { listTemplates } from './templates.ts'
20
19
  import type { Jobs } from './jobs.ts'
@@ -25,8 +24,8 @@ import { createDocumentAudioAuthoring } from './document-audio.ts'
25
24
  import { createDocumentImageAuthoring } from './document-images.ts'
26
25
  import { createDocumentTranscriptions, documentTranscriptionRoutes } from './document-transcription.ts'
27
26
  import type { DocumentTranscriptions, ProductionAudioAuthoring, SpeechService } from '@lincyaw/kernel'
28
- import { documentDirOf } from './writer.ts'
29
27
  import { createDocumentHistory } from './document-history.ts'
28
+ import { createWorkspaceChanges } from './workspace-changes.ts'
30
29
 
31
30
  const { version } = createRequire(import.meta.url)('../../package.json') as { version: string }
32
31
 
@@ -62,6 +61,9 @@ export interface WorkspaceRoutesOptions {
62
61
  authoringClientRoutes?: Record<string, Route>
63
62
  projectRoutes?: Record<string, Route>
64
63
  speechSettings?: Route
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 {
@@ -70,13 +72,6 @@ function toRendererIds(body: unknown): string[] | undefined {
70
72
  return ids.length > 0 ? ids : undefined
71
73
  }
72
74
 
73
- const NO_GIT = 'the workspace is not a git repository: run git init in it to use the document operations and the history'
74
-
75
-
76
- function toChosenPaths(body: unknown, uncommitted: string[]): string[] {
77
- const asked = isRecord(body) && Array.isArray(body.paths) ? body.paths.filter((path): path is string => typeof path === 'string') : undefined
78
- return asked ? uncommitted.filter(path => asked.includes(path)) : uncommitted
79
- }
80
75
 
81
76
  function toSaveMessage(value: unknown): string {
82
77
  return typeof value === 'string' ? [...(value.trim().split(/\r?\n/)[0] ?? '').trim()].slice(0, 200).join('') : ''
@@ -87,26 +82,31 @@ export function workspaceRoutes(options: WorkspaceRoutesOptions): ServerContribu
87
82
  const { config, editor, locks, revisions, operations, reviews, workbench } = options
88
83
  const listed = () => listDocuments(config).map(doc => doc.dir)
89
84
  const scopeOf = (ctx: RequestContext) => editor.scope(ctx.document)
90
- const uncommitted = async (ctx: RequestContext) => (revisions ? await revisions.uncommittedFiles(editor.roots(scopeOf(ctx))) : [])
91
- const withChosenChanges = async (request: Request, ctx: RequestContext, holder: string, work: (revisions: Revisions, paths: string[], member: Member, body: Record<string, unknown>) => Promise<Response>) => {
92
- if (request.method !== 'POST') return problemResponse(405, 'POST')
93
- if (!revisions) return problemResponse(409, NO_GIT)
94
- const body: unknown = await request.json().catch(() => ({}))
95
- const paths = toChosenPaths(body, (await uncommitted(ctx)).map(file => file.path))
96
- if (paths.length === 0) return problemResponse(409, 'no changes to take: every file is as committed')
97
- const claimed = locks.claimAll(paths.map(path => documentDirOf(config, path) ?? ''), holder)
98
- if ('holder' in claimed) throw lockedError(claimed.document, claimed.holder)
99
- try {
100
- return await work(revisions, paths, ctx.member, isRecord(body) ? body : {})
101
- } finally {
102
- claimed.release()
103
- }
104
- }
85
+ const changes = options.changesRoutes ?? createWorkspaceChanges({ config, editor, locks, revisions, changed: options.documentsChanged }).routes
105
86
  const ownedHistory = options.historyRoutes ? undefined : createDocumentHistory({ config, editor, locks, revisions, changed: (before, after) => options.documentsChanged(documentsDiff(before, after)), reverted: (target, revision) => reviews?.reverted(target, revision) })
106
87
  const ownedTranscriptions = options.transcriptions ? undefined : createDocumentTranscriptions({ root: config.root, editor, audio: options.audio, speech: options.speech })
107
88
  const transcriptions = options.transcriptions ?? ownedTranscriptions!
108
89
  const ownedAudio = options.audioAuthoringRoutes ? undefined : createDocumentAudioAuthoring({ root: config.root, editor, revisions, audio: options.audio, reviewRequired: config.settings['presmium.assistant']?.review === 'required' })
109
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 } : {},
110
110
  ...options.speechSettings ? { 'speech-settings': options.speechSettings } : {},
111
111
  ...documentEditorRoutes({ root: config.root, editor, documentEditor: options.documentEditor, workbench }),
112
112
  ...(options.audioAuthoringRoutes ?? ownedAudio!.routes),
@@ -178,39 +178,11 @@ export function workspaceRoutes(options: WorkspaceRoutesOptions): ServerContribu
178
178
  return jsonResponse(await editor.transaction(scopeOf(ctx), changes, ctx.member, history) satisfies SourceTransactionAnswer)
179
179
  }),
180
180
  },
181
- 'changes': {
182
- role: 'editor',
183
- handle: (request, ctx) => catchRequestErrors(async () => {
184
- if (request.method !== 'GET') return problemResponse(405, 'GET')
185
- return jsonResponse({ files: await uncommitted(ctx) } satisfies ChangesAnswer)
186
- }),
187
- },
188
- 'changes/commit': {
189
- role: 'editor',
190
- handle: (request, ctx) => catchRequestErrors(() => withChosenChanges(request, ctx, 'editor:commit', async (history, paths, member, body) => {
191
- const message = typeof body.message === 'string' ? body.message.trim().slice(0, 4000) : ''
192
- if (!message) return problemResponse(400, '{ message: what the change is, paths? }')
193
- for (const path of paths) {
194
- if (!path.endsWith(`/${DOCUMENT_ENTRY}`) && path !== DOCUMENT_ENTRY) continue
195
- const source = editor.read(scopeOf(ctx), path, member)
196
- validateDocumentSource(path, source.content)
197
- }
198
- const revision = await history.commit({ files: paths, message, origin: { kind: 'editor', member } })
199
- return jsonResponse({ ...revision ? { revision } : {}, paths } satisfies CommitAnswer)
200
- })),
201
- },
181
+ ...changes,
202
182
  ...workbench ? workbenchRoutes(workbench) : {},
203
183
  ...options.jobs ? jobRoutes(options.jobs, editor) : {},
204
184
  ...reviews ? reviewRoutes(reviews) : {},
205
- 'changes/discard': {
206
- role: 'editor',
207
- handle: (request, ctx) => catchRequestErrors(() => withChosenChanges(request, ctx, 'editor:discard', async (history, paths) => {
208
- const before = listed()
209
- await history.discard(paths)
210
- await options.documentsChanged(documentsDiff(before, listed()))
211
- return jsonResponse({ paths } satisfies CommitAnswer)
212
- })),
213
- },
185
+
214
186
  }
215
187
  return { routes: authorizeWorkspaceRoutes(routes, options.launcherToken), close: async () => { await Promise.all([ownedTranscriptions?.close(), ownedAudio?.close(), ownedHistory?.close()]) } }
216
188
  }
@@ -257,7 +229,7 @@ function workbenchRoutes(workbench: WorkbenchApi): Record<string, Route> {
257
229
  const params = new URL(request.url).searchParams
258
230
  const renderer = params.get('view') ?? undefined
259
231
  if (renderer !== undefined && renderer !== 'web' && renderer !== 'slides') return problemResponse(400, 'view must be web or slides')
260
- return jsonResponse(await workbench.preview(ctx.document, renderer, params.get('prefetch') === '1'))
232
+ return jsonResponse(await workbench.preview(ctx.document, renderer, params.get('prefetch') === '1', request.headers.get('x-presmium-preview-origin') ?? undefined))
261
233
  }),
262
234
  },
263
235
  'build': {
package/src/node/serve.ts CHANGED
@@ -1,16 +1,22 @@
1
+ import { createMediaUploads } from './media-uploads.ts'
2
+ import { randomBytes } from 'node:crypto'
1
3
  import { createProjectAuthoring } from './projects.ts'
2
4
  import { createDocumentHistory } from './document-history.ts'
3
5
  import { createAuthoringClients } from './authoring-clients.ts'
4
- import { createHash } from 'node:crypto'
5
- import { mkdirSync, mkdtempSync, rmSync } from 'node:fs'
6
- import { homedir, tmpdir } from 'node:os'
7
- import { join, relative } from 'node:path'
6
+ import { createAuthoringWindows } from './authoring-windows.ts'
7
+ import { readAuthoringDocument } from './document-editor.ts'
8
+ import { createDocumentCapture } from './capture.ts'
9
+ import { chmodSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
10
+ import { stripVTControlCharacters } from 'node:util'
11
+ import { tmpdir } from 'node:os'
12
+ import { join, relative, resolve } from 'node:path'
8
13
  import { Compiler, operatorDir as resolveOperatorDir, pluginLogger, runBlock, workspacePlugins } from '@lincyaw/compiler'
9
14
  import type { Compilation, CompilerOptions } from '@lincyaw/compiler'
10
- import { CHANGE_REVIEW, DOCUMENT_FILES, DOCUMENT_LOCKS, DOCUMENT_VOICE_TASKS, errorMessage, PRODUCTION_AUDIO_AUTHORING, REVISIONS, SPEECH, VOICEOVER, VOICEOVER_EXECUTION } from '@lincyaw/kernel'
11
- import { irRevision, operatorSpeechSecrets } from '@lincyaw/kernel/node'
15
+ import { CHANGE_REVIEW, DOCUMENT_FILES, DOCUMENT_LOCKS, DOCUMENT_VOICE_TASKS, errorMessage, PreviewPreparing, PRODUCTION_AUDIO_AUTHORING, REVISIONS, SPEECH, VOICEOVER, VOICEOVER_EXECUTION } from '@lincyaw/kernel'
16
+ import { irRevision, OperatorSpeechSettings, readServiceState, removeServiceState, serveStateDir, tryAcquireServiceHostLease } from '@lincyaw/kernel/node'
17
+ import type { ServiceHostLease } from '@lincyaw/kernel/node'
12
18
  import { speechSettingsRoute } from './speech-settings.ts'
13
- import type { CanonicalSource, ChangeReviewService, Finding, IRDocument, Logger, ProductionAudioAuthoring, ServiceToken, SiteSpec, SpeechService } from '@lincyaw/kernel'
19
+ import type { ApprovalKind, CanonicalSource, ChangeReviewService, Finding, IRDocument, Logger, ProductionAudioAuthoring, ServiceToken, SiteSpec, SpeechService } from '@lincyaw/kernel'
14
20
  import { serverConfigKey, servedDocument, startServer } from '@lincyaw/server'
15
21
  import type { DiagnosticStore, PresmiumServer, ServedDocument, ServedPlugin, ServerHost } from '@lincyaw/server'
16
22
  import { CompileSession } from './compile-session.ts'
@@ -22,11 +28,14 @@ import { Git } from './git.ts'
22
28
  import { createJobs, OUTPUTS_PATH } from './jobs.ts'
23
29
  import { DocumentLocks } from './locks.ts'
24
30
  import { AgentSessionReviews } from './review/agent-session-reviews.ts'
31
+ import { createWorkspaceReview } from './review/workspace-review.ts'
32
+ import { createWorkspaceSource } from './workspace-source.ts'
33
+ import { createWorkspaceChanges } from './workspace-changes.ts'
25
34
  import { createTaskReviewService } from './review/task-reviews.ts'
26
35
  import { Revisions } from './revisions.ts'
27
36
  import { WORKSPACE_ID, authorizeWorkspaceRoutes, workspaceRoutes, workspaceRoutesPlugin } from './routes.ts'
28
37
  import { refreshDocumentVitePlugins, siteContext, siteDocument, siteDocumentIR, siteSpec, untranslatedFindings, webRenderer } from './site.ts'
29
- import { SourceEditor } from './source-editor.ts'
38
+ import { SourceEditor, versionOf } from './source-editor.ts'
30
39
  import { createDocumentEditor } from './document-editor.ts'
31
40
  import type { DocumentEditor } from './document-editor.ts'
32
41
  import { createDocumentTranscriptions } from './document-transcription.ts'
@@ -50,8 +59,13 @@ export interface ServeOptions {
50
59
  /** The address browsers use when a reverse proxy fronts the service (see `ServerOptions.publicUrl`). */
51
60
  publicUrl?: string
52
61
  env?: NodeJS.ProcessEnv
62
+ /** Approvals given without asking, over the workspace's `approvals` (`presmium serve --allow`). */
63
+ allow?: ApprovalKind[]
53
64
  approvalTimeoutMs?: number
54
65
  log?: Logger
66
+ /** A launcher may reserve the shared workspace host before starting it. Released after close. */
67
+ hostLease?: ServiceHostLease
68
+ signal?: AbortSignal
55
69
  }
56
70
 
57
71
  export interface WorkspaceServer {
@@ -76,18 +90,57 @@ interface NodeServiceLoad { key: string, promise: Promise<AuthoringServices>, co
76
90
  const DISK_LOOK_MS = 1000
77
91
 
78
92
  function makeStateDir(root: string, env: NodeJS.ProcessEnv): string {
79
- const base = env.XDG_CACHE_HOME || join(homedir(), '.cache')
80
- const dir = join(base, 'presmium', 'serve', createHash('sha256').update(root).digest('hex').slice(0, 16))
93
+ const dir = serveStateDir(root, env)
81
94
  mkdirSync(dir, { recursive: true })
82
95
  return dir
83
96
  }
84
97
 
85
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> {
86
137
  const env = options.env ?? process.env
87
138
  const log = options.log ?? pluginLogger('presmium serve')
88
139
  const config = readWorkspaceConfig(options.dir)
140
+ if (env.PRESMIUM_AGENT_CANDIDATE === '1') config.settings['presmium.assistant'] = { ...config.settings['presmium.assistant'], review: 'auto' }
89
141
  const { root } = config
90
142
  const operatorDirectory = resolveOperatorDir(root, options.operatorDir ?? env.PRESMIUM_OPERATOR_DIR)
143
+ const speechSettings = new OperatorSpeechSettings(operatorDirectory, name => env[name])
91
144
  const stateDir = makeStateDir(root, env)
92
145
  const docs = () => listDocuments(config)
93
146
  const compileSessions = new Map<string, CompileSession>()
@@ -96,7 +149,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
96
149
  const writer = localWriter(config)
97
150
  const editor = new SourceEditor({ config, writer, locks })
98
151
  const check = options.check ?? (compilation => compilation.check())
99
- const launcherToken = env.PRESMIUM_SERVICE_TOKEN || undefined
152
+ const launcherToken = env.PRESMIUM_SERVICE_TOKEN || randomBytes(32).toString('hex')
100
153
  const preview = { origins: options.previewOrigins ?? [] }
101
154
  // Behind a proxy that forwards a path (`--public-url https://host/user/a/preview/`), the site, the jobs' files and the
102
155
  // previews' links are all below that path; the server finds its own routes below it too.
@@ -112,12 +165,18 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
112
165
  let history: WorkspaceHistory | undefined
113
166
  let documentEditor: DocumentEditor | undefined
114
167
  let documentHistory: ReturnType<typeof createDocumentHistory> | undefined
168
+ let workspaceReview: ReturnType<typeof createWorkspaceReview> | undefined
169
+ let workspaceSource: ReturnType<typeof createWorkspaceSource> | undefined
170
+ let workspaceChanges: ReturnType<typeof createWorkspaceChanges> | undefined
115
171
  let projectAuthoring: ReturnType<typeof createProjectAuthoring> | undefined
116
172
  let authoringClients: ReturnType<typeof createAuthoringClients> | undefined
173
+ let authoringWindows: ReturnType<typeof createAuthoringWindows> | undefined
117
174
  let transcriptions: ReturnType<typeof createDocumentTranscriptions> | undefined
118
175
  let transcriptionAdoption: ReturnType<typeof createTranscriptionAdoption> | undefined
176
+ let mediaUploads: ReturnType<typeof createMediaUploads> | undefined
119
177
  let audioAuthoring: ReturnType<typeof createDocumentAudioAuthoring> | undefined
120
178
  let imageAuthoring: ReturnType<typeof createDocumentImageAuthoring> | undefined
179
+ let capture: ReturnType<typeof createDocumentCapture> | undefined
121
180
  let voiceAuthoring: ReturnType<typeof createDocumentVoiceAuthoring> | undefined
122
181
  let workspaceRoutesOwner: ReturnType<typeof workspaceRoutes> | undefined
123
182
  let routesPlugin: ServedPlugin | undefined
@@ -166,7 +225,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
166
225
  services: [...serverServices, ...workspaceServices],
167
226
  bundled: options.bundled,
168
227
  operatorDir: operatorDirectory,
169
- secret: operatorSpeechSecrets(operatorDirectory, name => env[name]),
228
+ secret: speechSettings.secret,
170
229
  })
171
230
 
172
231
  // Coalesce only in-flight discovery. A later read reassembles actual services and problems;
@@ -194,9 +253,11 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
194
253
  authoringServicesClosed = true
195
254
  transcriptionAdoption?.close()
196
255
  for (const load of nodeServicePending) load.controller.abort()
197
- await Promise.all([projectAuthoring?.close(), transcriptions?.close(), audioAuthoring?.close(), voiceAuthoring?.close(), documentHistory?.close(), authoringClients?.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?.()])
198
257
  await Promise.allSettled([...nodeServicePending].map(load => load.promise))
199
258
  nodeServiceLoads.clear()
259
+ const failure = results.find(result => result.status === 'rejected')
260
+ if (failure?.status === 'rejected') throw failure.reason
200
261
  }
201
262
 
202
263
  const spec: SiteSpec = siteSpec(config, docs().map(doc => siteDocument(doc)))
@@ -249,7 +310,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
249
310
  revisions,
250
311
  operations: new DocumentOperations({ config, git, revisions, writer, changed: documentsChanged, locks }),
251
312
  git,
252
- agentSessionReviews: new AgentSessionReviews({ config, revisions, locks, files: writer, log }),
313
+ agentSessionReviews: new AgentSessionReviews({ config, revisions, locks, files: writer, log, flush: (documents, member) => authoringClients?.flush(documents, member) ?? Promise.resolve() }),
253
314
  taskReviews: createTaskReviewService({ config, locks, files: writer, log }),
254
315
  }
255
316
  }
@@ -263,11 +324,18 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
263
324
  get documentHistory() { return documentHistory?.service },
264
325
  get projectAuthoring() { return projectAuthoring?.service },
265
326
  get authoringClients() { return authoringClients?.service },
327
+ get authoringWindows() { return authoringWindows?.service },
328
+ get mediaUploads() { return mediaUploads },
266
329
  get audioAuthoring() { return audioAuthoring?.service },
267
330
  get imageAuthoring() { return imageAuthoring?.service },
268
331
  get voiceAuthoring() { return voiceAuthoring?.service },
332
+ speechSettings,
333
+ get workspaceReview() { return workspaceReview },
334
+ get workspaceSource() { return workspaceSource },
335
+ get workspaceChanges() { return workspaceChanges?.service },
269
336
  get transcriptions() { return transcriptions },
270
337
  get transcriptionAdoption() { return transcriptionAdoption?.service },
338
+ get capture() { return capture?.service },
271
339
  get routes() { return workspaceRoutesOwner?.routes ? { [WORKSPACE_ID]: workspaceRoutesOwner.routes, ...voiceAuthoring ? { 'presmium.lecture': authorizeWorkspaceRoutes(voiceAuthoring.routes, launcherToken) } : {} } : undefined },
272
340
  agentTools(document) {
273
341
  const compiled = (document === undefined ? [...compileSessions.values()] : [compileSessions.get(document)]).flatMap(session => session?.latest ? [session.latest] : [])
@@ -342,7 +410,6 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
342
410
  listenAddress: options.listenAddress,
343
411
  port: options.port,
344
412
  ...options.publicUrl ? { publicUrl: options.publicUrl } : {},
345
- stateFile,
346
413
  forward: async (path) => {
347
414
  lookAtDisk()
348
415
  if (path.startsWith(outputsPath)) return await jobs.origin()
@@ -355,10 +422,10 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
355
422
  }
356
423
  },
357
424
  settings: config.settings,
358
- approvals: config.approvals,
425
+ approvals: { ...config.approvals, ...Object.fromEntries((options.allow ?? []).map(kind => [kind, 'allow' as const])) },
359
426
  operatorDir: operatorDirectory,
360
427
  serverHost,
361
- env,
428
+ env: { ...env, PRESMIUM_SERVICE_TOKEN: launcherToken },
362
429
  ...options.approvalTimeoutMs ? { approvalTimeoutMs: options.approvalTimeoutMs } : {},
363
430
  log,
364
431
  async document(dir) {
@@ -374,19 +441,41 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
374
441
  })
375
442
  const running = server
376
443
  serverServices = running.services
377
- voiceAuthoring = createDocumentVoiceAuthoring({ editor, services: authoringServices, revision: document => { const latest = compileSessions.get(document)?.latest; return latest ? irRevision(latest.doc) : undefined } })
444
+ mediaUploads = createMediaUploads({ editor, url: () => `${publicOrigin()}${basePath.replace(/\/$/, '')}` })
445
+ voiceAuthoring = createDocumentVoiceAuthoring({
446
+ editor, uploads: mediaUploads, services: authoringServices,
447
+ async prepareExecution(document, source, signal) {
448
+ signal.throwIfAborted()
449
+ const session = compileSessionOf(document)
450
+ const matches = (compilation: Compilation) => compilation.doc.source?.documentId === source.documentId && compilation.doc.source.version === source.version && compilation.doc.source.fingerprint === source.fingerprint
451
+ let compilation = await session.ready()
452
+ signal.throwIfAborted()
453
+ if (!matches(compilation)) compilation = await session.recompile()
454
+ signal.throwIfAborted()
455
+ if (!matches(compilation)) throw new RequestError(409, 'document-version-changed')
456
+ },
457
+ revision: document => { const latest = compileSessions.get(document)?.latest; return latest ? irRevision(latest.doc) : undefined },
458
+ })
378
459
  workbench = createWorkbenchBackend({ root, compileSessionOf, serverHost, voices: voiceAuthoring.service, diagnostics: running.diagnostics, url: () => options.publicUrl ? new URL(options.publicUrl).origin : running.url, basePath, preview, log, warmSite: dir => site?.warm(dir) ?? Promise.resolve(), viewerPage: (dir, wait) => site?.app(dir, wait) ?? Promise.resolve(undefined) })
379
460
  history = openHistory()
461
+ workspaceChanges = createWorkspaceChanges({ config, editor, locks, revisions: history?.revisions, changed: documentsChanged })
462
+ workspaceSource = createWorkspaceSource({ config, editor, revisions: history?.revisions })
463
+ workspaceReview = history && createWorkspaceReview(history.agentSessionReviews)
380
464
  documentEditor = createDocumentEditor({ productionPlan: async (document, source) => { const audio = (await authoringServices(document, source)).audio; if (!audio) throw new RequestError(503, 'caption-production-unavailable'); return audio.readPlan({ source }) }, editor, revisions: history?.revisions, reviewRequired: config.settings['presmium.assistant']?.review === 'required' })
381
465
  projectAuthoring = createProjectAuthoring({ config, documentEditor, operations: history?.operations, revisions: history?.revisions, git: history?.git })
382
- authoringClients = createAuthoringClients(editor)
466
+ authoringClients = createAuthoringClients(editor, { reviewRequired: config.settings['presmium.assistant']?.review === 'required' })
467
+ authoringWindows = createAuthoringWindows((document, member) => {
468
+ if (!docs().some(value => value.dir === document)) throw new RequestError(404, 'window-target-unavailable')
469
+ return readAuthoringDocument(editor, { document, member }).content.id
470
+ })
383
471
  documentHistory = createDocumentHistory({ config, editor, locks, revisions: history?.revisions, reviewRequired: config.settings['presmium.assistant']?.review === 'required', changed: (before, after) => documentsChanged(documentsDiff(before, after)), reverted: (target, revision) => history?.agentSessionReviews.reverted(target, revision) })
384
472
  transcriptions = createDocumentTranscriptions({ root, editor, services: authoringServices })
385
473
  transcriptionAdoption = createTranscriptionAdoption({ documentEditor, transcriptions })
386
- audioAuthoring = createDocumentAudioAuthoring({ root, editor, revisions: history?.revisions, services: authoringServices, reviewRequired: config.settings['presmium.assistant']?.review === 'required' })
387
- imageAuthoring = createDocumentImageAuthoring({ root, editor, revisions: history?.revisions, reviewRequired: config.settings['presmium.assistant']?.review === 'required' })
474
+ audioAuthoring = createDocumentAudioAuthoring({ root, editor, uploads: mediaUploads, revisions: history?.revisions, services: authoringServices, reviewRequired: config.settings['presmium.assistant']?.review === 'required' })
475
+ imageAuthoring = createDocumentImageAuthoring({ root, editor, uploads: mediaUploads, revisions: history?.revisions, reviewRequired: config.settings['presmium.assistant']?.review === 'required' })
388
476
  const routeOptions = {
389
- speechSettings: speechSettingsRoute(operatorDirectory, name => env[name]),
477
+ speechSettings: speechSettingsRoute(speechSettings),
478
+ changesRoutes: workspaceChanges.routes,
390
479
  config,
391
480
  editor,
392
481
  documentEditor,
@@ -395,13 +484,14 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
395
484
  audioAuthoringRoutes: audioAuthoring.routes,
396
485
  imageAuthoringRoutes: imageAuthoring.routes,
397
486
  historyRoutes: documentHistory.routes,
398
- authoringClientRoutes: authoringClients.routes,
487
+ authoringClientRoutes: { ...authoringClients.routes, ...authoringWindows.routes },
399
488
  projectRoutes: projectAuthoring.routes,
400
489
  locks,
401
490
  ...history ? { revisions: history.revisions, operations: history.operations, reviews: history.agentSessionReviews } : {},
402
491
  documentsChanged,
403
492
  workbench,
404
493
  jobs,
494
+ previewOrigins: preview.origins,
405
495
  ...launcherToken ? { launcherToken } : {},
406
496
  }
407
497
  workspaceRoutesOwner = workspaceRoutes(routeOptions)
@@ -412,16 +502,42 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
412
502
  [DOCUMENT_LOCKS, locks],
413
503
  [DOCUMENT_VOICE_TASKS, voiceAuthoring.service],
414
504
  ]
505
+ let hostClosing: Promise<void> | undefined
506
+ const closeHost = (): Promise<void> => hostClosing ??= Promise.resolve().then(async () => {
507
+ // Stop advertising before releasing any authoring resource; contenders keep waiting for the lease.
508
+ removeServiceState(stateFile)
509
+ const results = await Promise.allSettled([
510
+ () => running.close(),
511
+ async () => history?.agentSessionReviews.close(),
512
+ closeAuthoring,
513
+ async () => { for (const session of compileSessions.values()) session.close() },
514
+ () => jobs.close(),
515
+ async () => capture?.close(),
516
+ async () => workbench?.close(),
517
+ async () => site?.close(),
518
+ ].map(async cleanup => cleanup()))
519
+ removeServiceState(stateFile)
520
+ if (home) rmSync(home, { recursive: true, force: true })
521
+ const failure = results.find(result => result.status === 'rejected')
522
+ if (failure?.status === 'rejected') throw failure.reason
523
+ })
415
524
  try {
416
525
  await history?.agentSessionReviews.recover(docs().map(doc => doc.dir))
526
+ options.signal?.throwIfAborted()
417
527
  } catch (error) {
418
- history?.agentSessionReviews.close()
419
- await closeAuthoring()
420
- await workbench.close()
421
- await running.close()
528
+ await closeHost()
422
529
  throw error
423
530
  }
424
531
 
532
+ // A picture right after a save shows what was saved: the document is compiled first when its file is newer.
533
+ const savedCompilation = async (dir: string): Promise<Compilation> => {
534
+ const session = compileSessionOf(dir)
535
+ const compilation = await session.ready()
536
+ const entry = docs().find(doc => doc.dir === dir)?.entry
537
+ const saved = entry ? versionOf(readFileSync(join(root, entry))) : undefined
538
+ return saved && compilation.doc.source?.version !== saved ? await session.recompile() : compilation
539
+ }
540
+ capture = createDocumentCapture({ root, url: () => running.url, viewerPage: dir => site?.app(dir, true) ?? Promise.resolve(undefined), compiled: async dir => (await savedCompilation(dir)).doc, dir: join(stateDir, 'captures') })
425
541
  started()
426
542
 
427
543
  const compileForSite = async (dir: string): Promise<IRDocument> => {
@@ -431,11 +547,12 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
431
547
  }
432
548
  try {
433
549
  site = await startWorkspaceSite({ root, spec, basePath, bundled: options.bundled, stateDir, compile: compileForSite, stampPreviewRevision: (compilation, doc) => workbench!.stampPreviewRevision(compilation, doc), diagnostics: running.diagnostics, preview, log })
550
+ options.signal?.throwIfAborted()
551
+ // Publish only the fully assembled authoring host. Another MCP client may discover it immediately.
552
+ writeFileSync(stateFile, `${JSON.stringify({ url: running.url, mcp: `${running.url}/mcp`, token: running.mcpToken, pid: process.pid, launcherToken }, null, 2)}\n`, { mode: 0o600 })
553
+ chmodSync(stateFile, 0o600)
434
554
  } catch (error) {
435
- await closeAuthoring()
436
- await workbench.close()
437
- await running.close()
438
- if (home) rmSync(home, { recursive: true, force: true })
555
+ await closeHost()
439
556
  throw error
440
557
  }
441
558
 
@@ -443,16 +560,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
443
560
  url: running.url,
444
561
  root,
445
562
  mcp: { url: `${running.url}/mcp`, stateFile },
446
- async close() {
447
- history?.agentSessionReviews.close()
448
- await closeAuthoring()
449
- for (const session of compileSessions.values()) session.close()
450
- await jobs.close()
451
- await workbench?.close()
452
- await site?.close()
453
- await running.close()
454
- if (home) rmSync(home, { recursive: true, force: true })
455
- },
563
+ close: closeHost,
456
564
  }
457
565
  }
458
566
 
@@ -471,6 +579,23 @@ interface WorkspaceSiteOptions {
471
579
 
472
580
  type WorkspaceSite = Awaited<ReturnType<typeof startWorkspaceSite>>
473
581
 
582
+ /** The bundler's failure as a diagnostic: the file and the module it could not find, when that is the failure. */
583
+ function codeFailure(error: unknown): Finding {
584
+ const text = stripVTControlCharacters(errorMessage(error))
585
+ const unresolved = /failed to resolve import "([^"]+)" from "([^"]+)"/.exec(text)
586
+ if (unresolved) {
587
+ return {
588
+ checkId: 'presmium.preview.code',
589
+ severity: 'error',
590
+ message: `the document's code could not be bundled: ${unresolved[1]} cannot be found from this file`,
591
+ hint: 'Name the plugin that provides it in metadata.plugins, or add its package to the project’s dependencies.',
592
+ source: { file: unresolved[2]! },
593
+ }
594
+ }
595
+ const reason = text.split('\n').map(line => line.replace(/^Error:\s*/, '').trim()).find(line => line && !/^Build failed/.test(line)) ?? text
596
+ return { checkId: 'presmium.preview.code', severity: 'error', message: `the document's code could not be bundled: ${reason}` }
597
+ }
598
+
474
599
  /** The workspace site's dev router in this process, which serve forwards the site's paths to. */
475
600
  async function startWorkspaceSite(options: WorkspaceSiteOptions) {
476
601
  const { root, spec, log } = options
@@ -497,7 +622,20 @@ async function startWorkspaceSite(options: WorkspaceSiteOptions) {
497
622
  })
498
623
  },
499
624
  warm: (dir: string): Promise<void> => dev.warm?.(dir) ?? Promise.resolve(),
500
- app: (dir: string, wait: boolean): Promise<string | undefined> => dev.app?.(dir, wait) ?? Promise.resolve(undefined),
625
+ app: async (dir: string, wait: boolean): Promise<string | undefined> => {
626
+ // A file of the document's own code (a scene, a component) that does not bundle fails alone: what imports it
627
+ // shows its failure. Each such file is a diagnostic, where the author, the workbench's AI and MCP clients find
628
+ // it, until a preview bundles it; when none of the code bundles, the preview fails, and the reason is one.
629
+ const source = { document: dir, origin: 'preview', renderer: 'web', instance: 'code' } as const
630
+ try {
631
+ const page = await (dev.app?.(dir, wait) ?? Promise.resolve(undefined))
632
+ if (wait && page) options.diagnostics.replace(source, dev.codeFindings?.(dir) ?? [], { root, irRevision: options.diagnostics.irRevision(dir) })
633
+ return page
634
+ } catch (error) {
635
+ if (wait && !(error instanceof PreviewPreparing)) options.diagnostics.replace(source, [codeFailure(error)], { root, irRevision: options.diagnostics.irRevision(dir) })
636
+ throw error
637
+ }
638
+ },
501
639
  close: (): Promise<void> => dev.close(),
502
640
  }
503
641
  }
package/src/node/site.ts CHANGED
@@ -35,7 +35,7 @@ export async function siteTranslations(compilation: Compilation): Promise<{ tran
35
35
  }
36
36
 
37
37
  export function siteDocument(document: DocumentSummary, doc?: IRDocument, translations?: SiteDocument['translations'], compilation?: Compilation): SiteDocument {
38
- return { dir: document.dir, title: document.title, description: document.description, ...document.lang ? { lang: document.lang } : {}, ...document.tags ? { tags: document.tags } : {}, ...doc ? { doc } : {}, ...translations?.length ? { translations } : {}, ...compilation ? { nodeVitePlugins: nodeVitePlugins(compilation) } : {} }
38
+ return { dir: document.dir, title: document.title, description: document.description, ...document.lang ? { lang: document.lang } : {}, ...document.tags ? { tags: document.tags } : {}, ...document.slides ? { slides: true } : {}, ...doc ? { doc } : {}, ...translations?.length ? { translations } : {}, ...compilation ? { nodeVitePlugins: nodeVitePlugins(compilation) } : {} }
39
39
  }
40
40
 
41
41
  export function refreshDocumentVitePlugins(site: SiteSpec, dir: string, compilation: Compilation): void {