@lincyaw/workspace 1.0.0-rc.13 → 1.0.0-rc.131

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.
Files changed (59) hide show
  1. package/README.md +4 -4
  2. package/package.json +8 -5
  3. package/src/domain/paths.ts +0 -15
  4. package/src/node/agent-activity.ts +46 -0
  5. package/src/node/archive.ts +33 -0
  6. package/src/node/authoring-clients.ts +73 -20
  7. package/src/node/authoring-windows.ts +165 -0
  8. package/src/node/build.ts +28 -23
  9. package/src/node/capture.ts +383 -0
  10. package/src/node/config.ts +136 -50
  11. package/src/node/document-assets.ts +2 -2
  12. package/src/node/document-audio.ts +65 -46
  13. package/src/node/document-authoring.ts +30 -15
  14. package/src/node/document-check.ts +36 -0
  15. package/src/node/document-history.ts +32 -5
  16. package/src/node/document-images.ts +24 -14
  17. package/src/node/document-import.ts +123 -0
  18. package/src/node/document-index.ts +644 -0
  19. package/src/node/document-materials.ts +80 -0
  20. package/src/node/document-operations.ts +4 -2
  21. package/src/node/document-transcription.ts +2 -1
  22. package/src/node/document-voice.ts +121 -13
  23. package/src/node/git-runner.mjs +19 -0
  24. package/src/node/git.ts +141 -22
  25. package/src/node/host-activity.ts +17 -0
  26. package/src/node/host-upgrade.ts +28 -0
  27. package/src/node/jobs.ts +40 -8
  28. package/src/node/local-history.ts +84 -0
  29. package/src/node/locks.ts +12 -0
  30. package/src/node/mcp-settings.ts +68 -0
  31. package/src/node/media-upload-messages.ts +4 -0
  32. package/src/node/media-upload-page.ts +57 -0
  33. package/src/node/media-upload.css +4 -0
  34. package/src/node/media-uploads.ts +116 -0
  35. package/src/node/page-delete.ts +0 -1
  36. package/src/node/project-files.ts +2 -2
  37. package/src/node/projects.ts +20 -5
  38. package/src/node/review/agent-session-reviews.ts +194 -63
  39. package/src/node/review/agent-workspace.ts +124 -0
  40. package/src/node/review/git-review.ts +47 -15
  41. package/src/node/review/record.ts +5 -1
  42. package/src/node/review/routes.ts +9 -1
  43. package/src/node/review/workspace-review.ts +87 -0
  44. package/src/node/revision-files.ts +54 -0
  45. package/src/node/revisions.ts +244 -59
  46. package/src/node/routes.ts +52 -59
  47. package/src/node/serve.ts +267 -52
  48. package/src/node/site.ts +5 -5
  49. package/src/node/source-editor.ts +66 -26
  50. package/src/node/speech-settings.ts +6 -8
  51. package/src/node/templates.ts +2 -2
  52. package/src/node/tree-operations.ts +425 -0
  53. package/src/node/tree-routes.ts +94 -0
  54. package/src/node/workbench-api.ts +14 -3
  55. package/src/node/workspace-changes.ts +130 -0
  56. package/src/node/workspace-migrate.ts +54 -0
  57. package/src/node/workspace-source.ts +133 -0
  58. package/src/node/writer.ts +21 -8
  59. package/templates/document/default/{lecture.json → index.pmd} +5 -1
package/src/node/serve.ts CHANGED
@@ -1,16 +1,24 @@
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 { createAgentActivity } from './agent-activity.ts'
8
+ import { readAuthoringDocument } from './document-editor.ts'
9
+ import { createDocumentCapture } from './capture.ts'
10
+ import { chmodSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
11
+ import { stripVTControlCharacters } from 'node:util'
12
+ import { tmpdir } from 'node:os'
13
+ import { join, relative, resolve } from 'node:path'
8
14
  import { Compiler, operatorDir as resolveOperatorDir, pluginLogger, runBlock, workspacePlugins } from '@lincyaw/compiler'
9
15
  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'
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
+ import { compareServiceVersion, irRevision, OperatorSpeechSettings, readServiceState, removeServiceState, serveStateDir, SERVICE_VERSION, tryAcquireServiceHostLease, upgradeWorkspaceService } from '@lincyaw/kernel/node'
18
+ import type { ServiceHostLease } from '@lincyaw/kernel/node'
19
+ import { createMcpSettings } from './mcp-settings.ts'
12
20
  import { speechSettingsRoute } from './speech-settings.ts'
13
- import type { CanonicalSource, ChangeReviewService, Finding, IRDocument, Logger, ProductionAudioAuthoring, ServiceToken, SiteSpec, SpeechService } from '@lincyaw/kernel'
21
+ import type { ApprovalKind, CanonicalSource, DocumentTreeService, ChangeReviewService, Finding, IRDocument, Logger, ProductionAudioAuthoring, ServiceToken, SiteSpec, SpeechService } from '@lincyaw/kernel'
14
22
  import { serverConfigKey, servedDocument, startServer } from '@lincyaw/server'
15
23
  import type { DiagnosticStore, PresmiumServer, ServedDocument, ServedPlugin, ServerHost } from '@lincyaw/server'
16
24
  import { CompileSession } from './compile-session.ts'
@@ -18,15 +26,19 @@ import { documentSummaries, listDocuments, readWorkspaceConfig } from './config.
18
26
  import { DocumentOperations, documentsDiff } from './document-operations.ts'
19
27
  import type { DocumentsChange } from './document-operations.ts'
20
28
  import { RequestError } from './errors.ts'
21
- import { Git } from './git.ts'
29
+ import { excludeDeltaboxState, Git } from './git.ts'
30
+ import { captureLocalBaseline, clearStaleHistoryLock, openLocalHistory } from './local-history.ts'
22
31
  import { createJobs, OUTPUTS_PATH } from './jobs.ts'
23
32
  import { DocumentLocks } from './locks.ts'
24
33
  import { AgentSessionReviews } from './review/agent-session-reviews.ts'
34
+ import { createWorkspaceReview } from './review/workspace-review.ts'
35
+ import { createWorkspaceSource } from './workspace-source.ts'
36
+ import { createWorkspaceChanges } from './workspace-changes.ts'
25
37
  import { createTaskReviewService } from './review/task-reviews.ts'
26
38
  import { Revisions } from './revisions.ts'
27
39
  import { WORKSPACE_ID, authorizeWorkspaceRoutes, workspaceRoutes, workspaceRoutesPlugin } from './routes.ts'
28
40
  import { refreshDocumentVitePlugins, siteContext, siteDocument, siteDocumentIR, siteSpec, untranslatedFindings, webRenderer } from './site.ts'
29
- import { SourceEditor } from './source-editor.ts'
41
+ import { SourceEditor, versionOf } from './source-editor.ts'
30
42
  import { createDocumentEditor } from './document-editor.ts'
31
43
  import type { DocumentEditor } from './document-editor.ts'
32
44
  import { createDocumentTranscriptions } from './document-transcription.ts'
@@ -38,6 +50,13 @@ import type { DocumentVoiceServices } from './document-voice.ts'
38
50
  import { createWorkbenchBackend } from './workbench-api.ts'
39
51
  import type { WorkbenchBackend } from './workbench-api.ts'
40
52
  import { localWriter } from './writer.ts'
53
+ import { DocumentIndex } from './document-index.ts'
54
+ import { TreeOperations } from './tree-operations.ts'
55
+ import { documentImportRoute } from './document-import.ts'
56
+ import { documentMaterialsRoute } from './document-materials.ts'
57
+ import { workspaceMigrateRoute } from './workspace-migrate.ts'
58
+ import { hostUpgradeRoute } from './host-upgrade.ts'
59
+ import { createHostActivity } from './host-activity.ts'
41
60
 
42
61
  export interface ServeOptions {
43
62
  dir: string
@@ -50,8 +69,15 @@ export interface ServeOptions {
50
69
  /** The address browsers use when a reverse proxy fronts the service (see `ServerOptions.publicUrl`). */
51
70
  publicUrl?: string
52
71
  env?: NodeJS.ProcessEnv
72
+ /** Approvals given without asking, over the workspace's `approvals` (`presmium serve --allow`). */
73
+ allow?: ApprovalKind[]
53
74
  approvalTimeoutMs?: number
54
75
  log?: Logger
76
+ /** A launcher may reserve the shared workspace host before starting it. Released after close. */
77
+ hostLease?: ServiceHostLease
78
+ signal?: AbortSignal
79
+ /** A CLI host ends its process after a graceful upgrade; stdio relays remain separate. */
80
+ onUpgrade?(version: string): void
55
81
  }
56
82
 
57
83
  export interface WorkspaceServer {
@@ -61,10 +87,11 @@ export interface WorkspaceServer {
61
87
  close(): Promise<void>
62
88
  }
63
89
 
64
- /** What the workspace keeps when it is a git repository: its revisions, the document operations and the reviews. */
90
+ /** Local editing history and the separate project version-control boundary. */
65
91
  interface WorkspaceHistory {
66
92
  git: Git
67
93
  revisions: Revisions
94
+ projectRevisions?: Revisions
68
95
  operations: DocumentOperations
69
96
  agentSessionReviews: AgentSessionReviews
70
97
  taskReviews: ChangeReviewService
@@ -76,27 +103,90 @@ interface NodeServiceLoad { key: string, promise: Promise<AuthoringServices>, co
76
103
  const DISK_LOOK_MS = 1000
77
104
 
78
105
  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))
106
+ const dir = serveStateDir(root, env)
81
107
  mkdirSync(dir, { recursive: true })
82
108
  return dir
83
109
  }
84
110
 
85
111
  export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceServer> {
112
+ const root = realpathSync(resolve(options.dir)), env = options.env ?? process.env
113
+ let advertised = readServiceState(join(serveStateDir(root, env), 'server.json'))
114
+ if (advertised && compareServiceVersion(advertised, SERVICE_VERSION) < 0) {
115
+ await upgradeWorkspaceService(root, advertised, SERVICE_VERSION, env, options.signal)
116
+ advertised = readServiceState(join(serveStateDir(root, env), 'server.json'))
117
+ }
118
+ if (advertised) throw Object.assign(new Error('workspace-service-already-running'), { code: 'workspace-service-already-running', url: advertised.url })
119
+ const lease = options.hostLease ?? await tryAcquireServiceHostLease(root, env)
120
+ if (!lease) {
121
+ const state = readServiceState(join(serveStateDir(root, env), 'server.json'))
122
+ throw Object.assign(new Error('workspace-service-already-running'), { code: 'workspace-service-already-running', ...state ? { url: state.url } : {} })
123
+ }
124
+ if (lease.root !== root) throw new Error('workspace-service-lease-scope')
125
+ const existing = readServiceState(join(serveStateDir(root, env), 'server.json'))
126
+ if (existing) {
127
+ await lease.release()
128
+ throw Object.assign(new Error('workspace-service-already-running'), { code: 'workspace-service-already-running', url: existing.url })
129
+ }
130
+ let running: WorkspaceServer | undefined, closing: Promise<void> | undefined
131
+ const close = () => closing ??= Promise.resolve().then(async () => {
132
+ try { await running?.close() }
133
+ finally { await lease.release() }
134
+ })
135
+ const compromised = () => {
136
+ const log = options.log ?? pluginLogger('presmium serve')
137
+ // The lease is renewed on a timer: a lost lease is most often the event loop held longer than the lease's stale time.
138
+ log.error(`the workspace service stops: it lost the workspace's host lease (${errorMessage(lease.signal.reason ?? 'unknown reason')}); another process may host the workspace now, or the service was blocked too long`)
139
+ void close().catch(error => log.error(errorMessage(error)))
140
+ }
141
+ try {
142
+ lease.signal.throwIfAborted()
143
+ options.signal?.throwIfAborted()
144
+ running = await startWorkspace({ ...options, onUpgrade: version => {
145
+ options.onUpgrade?.(version)
146
+ void close().catch(error => (options.log ?? pluginLogger('presmium serve')).error(errorMessage(error)))
147
+ } })
148
+ lease.signal.throwIfAborted()
149
+ options.signal?.throwIfAborted()
150
+ lease.signal.addEventListener('abort', compromised, { once: true })
151
+ return { ...running, async close() {
152
+ lease.signal.removeEventListener('abort', compromised)
153
+ await close()
154
+ } }
155
+ } catch (error) {
156
+ await close()
157
+ throw error
158
+ }
159
+ }
160
+
161
+ async function startWorkspace(options: ServeOptions): Promise<WorkspaceServer> {
86
162
  const env = options.env ?? process.env
87
163
  const log = options.log ?? pluginLogger('presmium serve')
88
164
  const config = readWorkspaceConfig(options.dir)
165
+ if (env.PRESMIUM_AGENT_CANDIDATE === '1') config.settings['presmium.assistant'] = { ...config.settings['presmium.assistant'], review: 'auto' }
89
166
  const { root } = config
167
+ // A failure nobody awaited is a log line, never the end of the service that hosts the author's workspace.
168
+ const unhandled = (reason: unknown) => log.error(`an operation failed unexpectedly: ${errorMessage(reason)}`)
169
+ process.on('unhandledRejection', unhandled)
170
+ if (clearStaleHistoryLock(root, env)) log.warn('removed the local history\'s index lock that an earlier service, ended in the middle of a git command, left behind')
171
+ const excluded = await excludeDeltaboxState(root).catch((error: unknown) => { log.warn(`could not leave DeltaBox's state directories out of the project: ${errorMessage(error)}`); return [] })
172
+ if (excluded.length) log.warn(`left ${excluded.join(', ')} out of the project in its git info/exclude: DeltaBox state an earlier service put in the workspace`)
173
+ const historyGit = await openLocalHistory(root, env)
174
+ await historyGit.exclusive(() => captureLocalBaseline(historyGit, ['.']))
90
175
  const operatorDirectory = resolveOperatorDir(root, options.operatorDir ?? env.PRESMIUM_OPERATOR_DIR)
176
+ const speechSettings = new OperatorSpeechSettings(operatorDirectory, name => env[name])
91
177
  const stateDir = makeStateDir(root, env)
92
178
  const docs = () => listDocuments(config)
93
179
  const compileSessions = new Map<string, CompileSession>()
94
180
  const agentToolListeners = new Set<(document: string) => void>()
95
181
  const locks = new DocumentLocks()
182
+ const activity = createHostActivity()
96
183
  const writer = localWriter(config)
97
- const editor = new SourceEditor({ config, writer, locks })
184
+ // The document tree's index, built before anything lists the documents: the compiler's scans in this process read it.
185
+ const documentIndex = new DocumentIndex(config)
186
+ await documentIndex.start()
187
+ const editor = new SourceEditor({ config, writer, locks, beforeWrite: (paths, historyLocked) => historyLocked ? captureLocalBaseline(historyGit, paths) : historyGit.exclusive(() => captureLocalBaseline(historyGit, paths)) })
98
188
  const check = options.check ?? (compilation => compilation.check())
99
- const launcherToken = env.PRESMIUM_SERVICE_TOKEN || undefined
189
+ const launcherToken = env.PRESMIUM_SERVICE_TOKEN || randomBytes(32).toString('hex')
100
190
  const preview = { origins: options.previewOrigins ?? [] }
101
191
  // Behind a proxy that forwards a path (`--public-url https://host/user/a/preview/`), the site, the jobs' files and the
102
192
  // previews' links are all below that path; the server finds its own routes below it too.
@@ -112,15 +202,23 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
112
202
  let history: WorkspaceHistory | undefined
113
203
  let documentEditor: DocumentEditor | undefined
114
204
  let documentHistory: ReturnType<typeof createDocumentHistory> | undefined
205
+ let workspaceReview: ReturnType<typeof createWorkspaceReview> | undefined
206
+ let workspaceSource: ReturnType<typeof createWorkspaceSource> | undefined
207
+ let workspaceChanges: ReturnType<typeof createWorkspaceChanges> | undefined
115
208
  let projectAuthoring: ReturnType<typeof createProjectAuthoring> | undefined
116
209
  let authoringClients: ReturnType<typeof createAuthoringClients> | undefined
210
+ let authoringWindows: ReturnType<typeof createAuthoringWindows> | undefined
211
+ const agentActivity = createAgentActivity()
117
212
  let transcriptions: ReturnType<typeof createDocumentTranscriptions> | undefined
118
213
  let transcriptionAdoption: ReturnType<typeof createTranscriptionAdoption> | undefined
214
+ let mediaUploads: ReturnType<typeof createMediaUploads> | undefined
119
215
  let audioAuthoring: ReturnType<typeof createDocumentAudioAuthoring> | undefined
120
216
  let imageAuthoring: ReturnType<typeof createDocumentImageAuthoring> | undefined
217
+ let capture: ReturnType<typeof createDocumentCapture> | undefined
121
218
  let voiceAuthoring: ReturnType<typeof createDocumentVoiceAuthoring> | undefined
122
219
  let workspaceRoutesOwner: ReturnType<typeof workspaceRoutes> | undefined
123
220
  let routesPlugin: ServedPlugin | undefined
221
+ let treeService: DocumentTreeService | undefined
124
222
  // The builds and exports, as jobs the workbench and the AI start and follow.
125
223
  const jobs = createJobs({
126
224
  stateDir,
@@ -166,7 +264,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
166
264
  services: [...serverServices, ...workspaceServices],
167
265
  bundled: options.bundled,
168
266
  operatorDir: operatorDirectory,
169
- secret: operatorSpeechSecrets(operatorDirectory, name => env[name]),
267
+ secret: speechSettings.secret,
170
268
  })
171
269
 
172
270
  // Coalesce only in-flight discovery. A later read reassembles actual services and problems;
@@ -194,9 +292,11 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
194
292
  authoringServicesClosed = true
195
293
  transcriptionAdoption?.close()
196
294
  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?.()])
295
+ const results = await Promise.allSettled([agentActivity.close(), mediaUploads?.close(), projectAuthoring?.close(), transcriptions?.close(), audioAuthoring?.close(), voiceAuthoring?.close(), documentHistory?.close(), authoringClients?.close(), authoringWindows?.close(), workspaceRoutesOwner?.close?.()])
198
296
  await Promise.allSettled([...nodeServicePending].map(load => load.promise))
199
297
  nodeServiceLoads.clear()
298
+ const failure = results.find(result => result.status === 'rejected')
299
+ if (failure?.status === 'rejected') throw failure.reason
200
300
  }
201
301
 
202
302
  const spec: SiteSpec = siteSpec(config, docs().map(doc => siteDocument(doc)))
@@ -211,6 +311,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
211
311
  // Undoing prose also refreshes the list: retain compiled document modules and translations.
212
312
  delete known.lang
213
313
  delete known.tags
314
+ delete known.parent
214
315
  return Object.assign(known, summary)
215
316
  })
216
317
  spec.documents.splice(0, spec.documents.length, ...listed)
@@ -218,6 +319,9 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
218
319
  }
219
320
 
220
321
  const documentsChanged = async (change: DocumentsChange): Promise<void> => {
322
+ // Folder events reach the index only for folders it watches; a document written into a new nested folder (an
323
+ // import) would wait for the occasional walk, and the list and the tree would miss it until then.
324
+ await documentIndex.changed([...change.added, ...change.removed])
221
325
  for (const dir of change.removed) {
222
326
  server?.diagnostics.forget(dir)
223
327
  compileSessions.get(dir)?.close()
@@ -239,17 +343,14 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
239
343
  }
240
344
 
241
345
  const openHistory = (): WorkspaceHistory | undefined => {
242
- if (!Git.isRepository(root)) {
243
- log.warn(`${root} is not a git repository: editing, the document operations and the history are not available (run git init)`)
244
- return undefined
245
- }
246
- const git = new Git(root)
346
+ const git = historyGit
247
347
  const revisions = new Revisions(git, { config, writer })
248
348
  return {
249
349
  revisions,
350
+ ...Git.isRepository(root) ? { projectRevisions: new Revisions(new Git(root), { config, writer }) } : {},
250
351
  operations: new DocumentOperations({ config, git, revisions, writer, changed: documentsChanged, locks }),
251
352
  git,
252
- agentSessionReviews: new AgentSessionReviews({ config, revisions, locks, files: writer, log }),
353
+ agentSessionReviews: new AgentSessionReviews({ config, revisions, locks, files: writer, log, flush: (documents, member) => authoringClients?.flush(documents, member) ?? Promise.resolve() }),
253
354
  taskReviews: createTaskReviewService({ config, locks, files: writer, log }),
254
355
  }
255
356
  }
@@ -258,16 +359,26 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
258
359
  const ready = new Promise<void>(resolve => started = resolve)
259
360
 
260
361
  const serverHost: ServerHost = {
362
+ beginOperation: route => route?.plugin === WORKSPACE_ID && route.path === 'host-upgrade' ? () => {} : activity.begin(),
363
+ agentActivity: agentActivity.service,
261
364
  workspaceRoot: root,
262
365
  get authoring() { return documentEditor },
263
366
  get documentHistory() { return documentHistory?.service },
264
367
  get projectAuthoring() { return projectAuthoring?.service },
368
+ get documentTree() { return treeService },
265
369
  get authoringClients() { return authoringClients?.service },
370
+ get authoringWindows() { return authoringWindows?.service },
371
+ get mediaUploads() { return mediaUploads },
266
372
  get audioAuthoring() { return audioAuthoring?.service },
267
373
  get imageAuthoring() { return imageAuthoring?.service },
268
374
  get voiceAuthoring() { return voiceAuthoring?.service },
375
+ speechSettings,
376
+ get workspaceReview() { return workspaceReview },
377
+ get workspaceSource() { return workspaceSource },
378
+ get workspaceChanges() { return workspaceChanges?.service },
269
379
  get transcriptions() { return transcriptions },
270
380
  get transcriptionAdoption() { return transcriptionAdoption?.service },
381
+ get capture() { return capture?.service },
271
382
  get routes() { return workspaceRoutesOwner?.routes ? { [WORKSPACE_ID]: workspaceRoutesOwner.routes, ...voiceAuthoring ? { 'presmium.lecture': authorizeWorkspaceRoutes(voiceAuthoring.routes, launcherToken) } : {} } : undefined },
272
383
  agentTools(document) {
273
384
  const compiled = (document === undefined ? [...compileSessions.values()] : [compileSessions.get(document)]).flatMap(session => session?.latest ? [session.latest] : [])
@@ -342,7 +453,6 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
342
453
  listenAddress: options.listenAddress,
343
454
  port: options.port,
344
455
  ...options.publicUrl ? { publicUrl: options.publicUrl } : {},
345
- stateFile,
346
456
  forward: async (path) => {
347
457
  lookAtDisk()
348
458
  if (path.startsWith(outputsPath)) return await jobs.origin()
@@ -355,10 +465,10 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
355
465
  }
356
466
  },
357
467
  settings: config.settings,
358
- approvals: config.approvals,
468
+ approvals: { ...config.approvals, ...Object.fromEntries((options.allow ?? []).map(kind => [kind, 'allow' as const])) },
359
469
  operatorDir: operatorDirectory,
360
470
  serverHost,
361
- env,
471
+ env: { ...env, PRESMIUM_SERVICE_TOKEN: launcherToken },
362
472
  ...options.approvalTimeoutMs ? { approvalTimeoutMs: options.approvalTimeoutMs } : {},
363
473
  log,
364
474
  async document(dir) {
@@ -374,19 +484,44 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
374
484
  })
375
485
  const running = server
376
486
  serverServices = running.services
377
- voiceAuthoring = createDocumentVoiceAuthoring({ editor, services: authoringServices, revision: document => { const latest = compileSessions.get(document)?.latest; return latest ? irRevision(latest.doc) : undefined } })
487
+ mediaUploads = createMediaUploads({ editor, url: () => `${publicOrigin()}${basePath.replace(/\/$/, '')}` })
488
+ voiceAuthoring = createDocumentVoiceAuthoring({
489
+ editor, uploads: mediaUploads, services: authoringServices,
490
+ async prepareExecution(document, source, signal) {
491
+ signal.throwIfAborted()
492
+ const session = compileSessionOf(document)
493
+ const matches = (compilation: Compilation) => compilation.doc.source?.documentId === source.documentId && compilation.doc.source.version === source.version && compilation.doc.source.fingerprint === source.fingerprint
494
+ let compilation = await session.ready()
495
+ signal.throwIfAborted()
496
+ if (!matches(compilation)) compilation = await session.recompile()
497
+ signal.throwIfAborted()
498
+ if (!matches(compilation)) throw new RequestError(409, 'document-version-changed')
499
+ },
500
+ revision: document => { const latest = compileSessions.get(document)?.latest; return latest ? irRevision(latest.doc) : undefined },
501
+ })
378
502
  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
503
  history = openHistory()
504
+ workspaceChanges = createWorkspaceChanges({ config, editor, locks, revisions: history?.projectRevisions, changed: documentsChanged })
505
+ workspaceSource = createWorkspaceSource({ config, editor, revisions: history?.revisions })
506
+ workspaceReview = history && createWorkspaceReview(history.agentSessionReviews)
380
507
  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
508
  projectAuthoring = createProjectAuthoring({ config, documentEditor, operations: history?.operations, revisions: history?.revisions, git: history?.git })
382
- authoringClients = createAuthoringClients(editor)
509
+ authoringClients = createAuthoringClients(editor, { reviewRequired: config.settings['presmium.assistant']?.review === 'required' })
510
+ authoringWindows = createAuthoringWindows((document, member) => {
511
+ if (!docs().some(value => value.dir === document)) throw new RequestError(404, 'window-target-unavailable')
512
+ return readAuthoringDocument(editor, { document, member }).content.id
513
+ })
383
514
  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
515
  transcriptions = createDocumentTranscriptions({ root, editor, services: authoringServices })
385
516
  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' })
517
+ audioAuthoring = createDocumentAudioAuthoring({ root, editor, uploads: mediaUploads, revisions: history?.revisions, services: authoringServices, reviewRequired: config.settings['presmium.assistant']?.review === 'required' })
518
+ imageAuthoring = createDocumentImageAuthoring({ root, editor, uploads: mediaUploads, revisions: history?.revisions, reviewRequired: config.settings['presmium.assistant']?.review === 'required' })
519
+ const mcpSettings = await createMcpSettings({ root, stateFile, server: running, command: env.PRESMIUM_COMMAND })
388
520
  const routeOptions = {
389
- speechSettings: speechSettingsRoute(operatorDirectory, name => env[name]),
521
+ mcpSettings: mcpSettings.route,
522
+ speechSettings: speechSettingsRoute(speechSettings),
523
+ changesRoutes: workspaceChanges.routes,
524
+ projectRevisions: history?.projectRevisions,
390
525
  config,
391
526
  editor,
392
527
  documentEditor,
@@ -395,33 +530,91 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
395
530
  audioAuthoringRoutes: audioAuthoring.routes,
396
531
  imageAuthoringRoutes: imageAuthoring.routes,
397
532
  historyRoutes: documentHistory.routes,
398
- authoringClientRoutes: authoringClients.routes,
533
+ authoringClientRoutes: { ...authoringClients.routes, ...authoringWindows.routes, ...agentActivity.routes },
399
534
  projectRoutes: projectAuthoring.routes,
535
+ documentImport: documentImportRoute({ config, writer, locks, revisions: history?.revisions, changed: documentsChanged }),
536
+ documentMaterials: documentMaterialsRoute({ config, writer, locks, revisions: history?.revisions }),
537
+ workspaceMigrate: workspaceMigrateRoute({ config, locks, revisions: history?.revisions, changed: documentsChanged }),
400
538
  locks,
401
539
  ...history ? { revisions: history.revisions, operations: history.operations, reviews: history.agentSessionReviews } : {},
402
540
  documentsChanged,
403
541
  workbench,
404
542
  jobs,
543
+ previewOrigins: preview.origins,
544
+ hostUpgrade: hostUpgradeRoute(locks, jobs, () => !transcriptions?.busy() && !voiceAuthoring?.busy() && !audioAuthoring?.busy() && !imageAuthoring?.busy() && activity.quiesce(), version => options.onUpgrade?.(version)),
405
545
  ...launcherToken ? { launcherToken } : {},
406
546
  }
407
- workspaceRoutesOwner = workspaceRoutes(routeOptions)
408
- routesPlugin = { id: WORKSPACE_ID, plugin: workspaceRoutesPlugin(routeOptions, workspaceRoutesOwner.routes), config: {} }
547
+ // A move or rename changes titles and places in the site's list without adding or removing a document.
548
+ const placed = (dirs: string[]) => {
549
+ const { documents } = documentIndex.scan()
550
+ const byDir = new Map([...documents.values()].map(entry => [entry.dir, entry]))
551
+ for (const dir of dirs) {
552
+ const known = spec.documents.find(document => document.dir === dir), entry = byDir.get(dir)
553
+ if (!known || !entry) continue
554
+ known.title = entry.title
555
+ const parent = entry.placement.parent === null ? undefined : documents.get(entry.placement.parent)?.dir
556
+ if (parent === undefined) delete known.parent
557
+ else known.parent = parent
558
+ }
559
+ }
560
+ const treeOperations = new TreeOperations({ config, index: documentIndex, writer, locks, revisions: history?.revisions, changed: documentsChanged, placed, warn: message => log.warn(message) })
561
+ const read = async <T>(answer: () => T) => { await documentIndex.ready(); return answer() }
562
+ treeService = {
563
+ tree: () => read(() => documentIndex.tree()),
564
+ apply: (operation, member, origin) => treeOperations.apply(operation, member, origin),
565
+ links: id => read(() => documentIndex.links(id)),
566
+ search: (query, limit) => read(() => documentIndex.search(query, limit)),
567
+ preview: (id, target) => read(() => documentIndex.preview(id, target)),
568
+ embedSource: async (document, block) => { await documentIndex.ready(); return documentIndex.embedSource(document, block) },
569
+ }
570
+ const routeOptionsWithTree = { ...routeOptions, index: documentIndex, treeOperations }
571
+ workspaceRoutesOwner = workspaceRoutes(routeOptionsWithTree)
572
+ routesPlugin = { id: WORKSPACE_ID, plugin: workspaceRoutesPlugin(routeOptionsWithTree, workspaceRoutesOwner.routes), config: {} }
409
573
  workspaceServices = [
410
574
  ...history ? [[REVISIONS, history.revisions] as [ServiceToken<unknown>, unknown]] : [],
411
575
  [DOCUMENT_FILES, writer],
412
576
  [DOCUMENT_LOCKS, locks],
413
577
  [DOCUMENT_VOICE_TASKS, voiceAuthoring.service],
414
578
  ]
579
+ let hostClosing: Promise<void> | undefined
580
+ const closeHost = (): Promise<void> => hostClosing ??= Promise.resolve().then(async () => {
581
+ // Stop advertising before releasing any authoring resource; contenders keep waiting for the lease.
582
+ removeServiceState(stateFile)
583
+ treeOperations.close()
584
+ process.off('unhandledRejection', unhandled)
585
+ documentIndex.close()
586
+ const results = await Promise.allSettled([
587
+ () => running.close(),
588
+ async () => history?.agentSessionReviews.close(),
589
+ closeAuthoring,
590
+ async () => { for (const session of compileSessions.values()) session.close() },
591
+ () => jobs.close(),
592
+ async () => capture?.close(),
593
+ async () => workbench?.close(),
594
+ async () => site?.close(),
595
+ ].map(async cleanup => cleanup()))
596
+ removeServiceState(stateFile)
597
+ if (home) rmSync(home, { recursive: true, force: true })
598
+ const failure = results.find(result => result.status === 'rejected')
599
+ if (failure?.status === 'rejected') throw failure.reason
600
+ })
415
601
  try {
416
602
  await history?.agentSessionReviews.recover(docs().map(doc => doc.dir))
603
+ options.signal?.throwIfAborted()
417
604
  } catch (error) {
418
- history?.agentSessionReviews.close()
419
- await closeAuthoring()
420
- await workbench.close()
421
- await running.close()
605
+ await closeHost()
422
606
  throw error
423
607
  }
424
608
 
609
+ // A picture right after a save shows what was saved: the document is compiled first when its file is newer.
610
+ const savedCompilation = async (dir: string): Promise<Compilation> => {
611
+ const session = compileSessionOf(dir)
612
+ const compilation = await session.ready()
613
+ const entry = docs().find(doc => doc.dir === dir)?.entry
614
+ const saved = entry ? versionOf(readFileSync(join(root, entry))) : undefined
615
+ return saved && compilation.doc.source?.version !== saved ? await session.recompile() : compilation
616
+ }
617
+ 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
618
  started()
426
619
 
427
620
  const compileForSite = async (dir: string): Promise<IRDocument> => {
@@ -431,11 +624,12 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
431
624
  }
432
625
  try {
433
626
  site = await startWorkspaceSite({ root, spec, basePath, bundled: options.bundled, stateDir, compile: compileForSite, stampPreviewRevision: (compilation, doc) => workbench!.stampPreviewRevision(compilation, doc), diagnostics: running.diagnostics, preview, log })
627
+ options.signal?.throwIfAborted()
628
+ // Publish only the fully assembled authoring host. Another MCP client may discover it immediately.
629
+ writeFileSync(stateFile, `${JSON.stringify({ url: running.url, mcp: `${running.url}/mcp`, token: running.mcpToken, pid: process.pid, launcherToken, version: SERVICE_VERSION }, null, 2)}\n`, { mode: 0o600 })
630
+ chmodSync(stateFile, 0o600)
434
631
  } catch (error) {
435
- await closeAuthoring()
436
- await workbench.close()
437
- await running.close()
438
- if (home) rmSync(home, { recursive: true, force: true })
632
+ await closeHost()
439
633
  throw error
440
634
  }
441
635
 
@@ -443,16 +637,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
443
637
  url: running.url,
444
638
  root,
445
639
  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
- },
640
+ close: closeHost,
456
641
  }
457
642
  }
458
643
 
@@ -471,6 +656,23 @@ interface WorkspaceSiteOptions {
471
656
 
472
657
  type WorkspaceSite = Awaited<ReturnType<typeof startWorkspaceSite>>
473
658
 
659
+ /** The bundler's failure as a diagnostic: the file and the module it could not find, when that is the failure. */
660
+ function codeFailure(error: unknown): Finding {
661
+ const text = stripVTControlCharacters(errorMessage(error))
662
+ const unresolved = /failed to resolve import "([^"]+)" from "([^"]+)"/.exec(text)
663
+ if (unresolved) {
664
+ return {
665
+ checkId: 'presmium.preview.code',
666
+ severity: 'error',
667
+ message: `the document's code could not be bundled: ${unresolved[1]} cannot be found from this file`,
668
+ hint: 'Name the plugin that provides it in metadata.plugins, or add its package to the project’s dependencies.',
669
+ source: { file: unresolved[2]! },
670
+ }
671
+ }
672
+ const reason = text.split('\n').map(line => line.replace(/^Error:\s*/, '').trim()).find(line => line && !/^Build failed/.test(line)) ?? text
673
+ return { checkId: 'presmium.preview.code', severity: 'error', message: `the document's code could not be bundled: ${reason}` }
674
+ }
675
+
474
676
  /** The workspace site's dev router in this process, which serve forwards the site's paths to. */
475
677
  async function startWorkspaceSite(options: WorkspaceSiteOptions) {
476
678
  const { root, spec, log } = options
@@ -497,7 +699,20 @@ async function startWorkspaceSite(options: WorkspaceSiteOptions) {
497
699
  })
498
700
  },
499
701
  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),
702
+ app: async (dir: string, wait: boolean): Promise<string | undefined> => {
703
+ // A file of the document's own code (a scene, a component) that does not bundle fails alone: what imports it
704
+ // shows its failure. Each such file is a diagnostic, where the author, the workbench's AI and MCP clients find
705
+ // it, until a preview bundles it; when none of the code bundles, the preview fails, and the reason is one.
706
+ const source = { document: dir, origin: 'preview', renderer: 'web', instance: 'code' } as const
707
+ try {
708
+ const page = await (dev.app?.(dir, wait) ?? Promise.resolve(undefined))
709
+ if (wait && page) options.diagnostics.replace(source, dev.codeFindings?.(dir) ?? [], { root, irRevision: options.diagnostics.irRevision(dir) })
710
+ return page
711
+ } catch (error) {
712
+ if (wait && !(error instanceof PreviewPreparing)) options.diagnostics.replace(source, [codeFailure(error)], { root, irRevision: options.diagnostics.irRevision(dir) })
713
+ throw error
714
+ }
715
+ },
501
716
  close: (): Promise<void> => dev.close(),
502
717
  }
503
718
  }
package/src/node/site.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs'
2
2
  import { basename, dirname, join, relative, resolve, sep } from 'node:path'
3
- import { compileTranslations, directoryAsset, fileHash, lineContaining, loadPlugins, nodeVitePlugins, portable, publishesDirectory, viewFor } from '@lincyaw/compiler'
3
+ import { compileTranslations, directoryAsset, effectiveDocumentIn, fileHash, lineContaining, loadPlugins, nodeVitePlugins, portable, publishesDirectory, viewFor } from '@lincyaw/compiler'
4
4
  import type { Compilation } from '@lincyaw/compiler'
5
5
  import { DOCUMENT_ENTRY, isRecord, NON_FILE_URL, WEB_RENDERER_PACKAGE } from '@lincyaw/kernel'
6
- import type { DocumentSummary, Finding, IRDocument, RenderContext, Renderer, SiteDocument, SiteSpec, SourcePos } from '@lincyaw/kernel'
6
+ import type { DocumentSummary, Finding, IRDocument, PresmiumDocument, RenderContext, Renderer, SiteDocument, SiteSpec, SourcePos } from '@lincyaw/kernel'
7
7
  import { isInside } from '@lincyaw/kernel/node'
8
8
  import type { WorkspaceConfig } from './config.ts'
9
9
 
@@ -34,8 +34,8 @@ export async function siteTranslations(compilation: Compilation): Promise<{ tran
34
34
  return { translations: translations.map(({ lang, doc }) => ({ lang, doc: siteIR(compilation, doc) })), findings }
35
35
  }
36
36
 
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) } : {} }
37
+ export function siteDocument(document: DocumentSummary & { parentDir?: string }, doc?: IRDocument, translations?: SiteDocument['translations'], compilation?: Compilation): SiteDocument {
38
+ return { dir: document.dir, title: document.title, ...document.parentDir !== undefined ? { parent: document.parentDir } : {}, 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 {
@@ -116,7 +116,7 @@ function publishedAsset(options: SiteContextOptions, source: SourcePos, url: str
116
116
  const deck = deckOf(source.file, options.root)
117
117
  if (!deck || !publishesDirectory(target, deck)) return undefined
118
118
  const document: unknown = JSON.parse(readFileSync(join(deck, DOCUMENT_ENTRY), 'utf8'))
119
- const lang = isRecord(document) && isRecord(document.metadata) ? document.metadata.lang : undefined
119
+ const lang = isRecord(document) && isRecord(document.metadata) && isRecord(document.production) && isRecord(document.placement) ? effectiveDocumentIn(options.root, join(deck, DOCUMENT_ENTRY), document as unknown as PresmiumDocument).metadata.lang : undefined
120
120
  return directoryAsset(target, deck, join(options.workDir, 'files'), typeof lang === 'string' ? lang : undefined, message => warn(`${url} is not published: ${message}`))
121
121
  }
122
122