@lincyaw/workspace 1.0.0-rc.3 → 1.0.0-rc.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +6 -5
- package/src/node/authoring-clients.ts +23 -4
- package/src/node/build.ts +67 -10
- package/src/node/capture.ts +356 -0
- package/src/node/config.ts +1 -0
- package/src/node/document-authoring.ts +7 -1
- package/src/node/locks.ts +12 -0
- package/src/node/review/agent-session-reviews.ts +102 -44
- package/src/node/review/agent-workspace.ts +106 -0
- package/src/node/review/git-review.ts +4 -2
- package/src/node/review/record.ts +4 -1
- package/src/node/review/routes.ts +7 -0
- package/src/node/revisions.ts +14 -4
- package/src/node/routes.ts +1 -1
- package/src/node/serve.ts +58 -12
- package/src/node/site.ts +1 -1
- package/src/node/source-editor.ts +3 -7
- package/src/node/workbench-api.ts +14 -3
package/src/node/serve.ts
CHANGED
|
@@ -1,16 +1,17 @@
|
|
|
1
1
|
import { createProjectAuthoring } from './projects.ts'
|
|
2
2
|
import { createDocumentHistory } from './document-history.ts'
|
|
3
3
|
import { createAuthoringClients } from './authoring-clients.ts'
|
|
4
|
-
import {
|
|
5
|
-
import { mkdirSync, mkdtempSync, rmSync } from 'node:fs'
|
|
6
|
-
import {
|
|
4
|
+
import { createDocumentCapture } from './capture.ts'
|
|
5
|
+
import { mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'
|
|
6
|
+
import { stripVTControlCharacters } from 'node:util'
|
|
7
|
+
import { tmpdir } from 'node:os'
|
|
7
8
|
import { join, relative } from 'node:path'
|
|
8
9
|
import { Compiler, operatorDir as resolveOperatorDir, pluginLogger, runBlock, workspacePlugins } from '@lincyaw/compiler'
|
|
9
10
|
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'
|
|
11
|
+
import { CHANGE_REVIEW, DOCUMENT_FILES, DOCUMENT_LOCKS, DOCUMENT_VOICE_TASKS, errorMessage, PreviewPreparing, PRODUCTION_AUDIO_AUTHORING, REVISIONS, SPEECH, VOICEOVER, VOICEOVER_EXECUTION } from '@lincyaw/kernel'
|
|
12
|
+
import { irRevision, operatorSpeechSecrets, serveStateDir } from '@lincyaw/kernel/node'
|
|
12
13
|
import { speechSettingsRoute } from './speech-settings.ts'
|
|
13
|
-
import type { CanonicalSource, ChangeReviewService, Finding, IRDocument, Logger, ProductionAudioAuthoring, ServiceToken, SiteSpec, SpeechService } from '@lincyaw/kernel'
|
|
14
|
+
import type { ApprovalKind, CanonicalSource, ChangeReviewService, Finding, IRDocument, Logger, ProductionAudioAuthoring, ServiceToken, SiteSpec, SpeechService } from '@lincyaw/kernel'
|
|
14
15
|
import { serverConfigKey, servedDocument, startServer } from '@lincyaw/server'
|
|
15
16
|
import type { DiagnosticStore, PresmiumServer, ServedDocument, ServedPlugin, ServerHost } from '@lincyaw/server'
|
|
16
17
|
import { CompileSession } from './compile-session.ts'
|
|
@@ -26,7 +27,7 @@ import { createTaskReviewService } from './review/task-reviews.ts'
|
|
|
26
27
|
import { Revisions } from './revisions.ts'
|
|
27
28
|
import { WORKSPACE_ID, authorizeWorkspaceRoutes, workspaceRoutes, workspaceRoutesPlugin } from './routes.ts'
|
|
28
29
|
import { refreshDocumentVitePlugins, siteContext, siteDocument, siteDocumentIR, siteSpec, untranslatedFindings, webRenderer } from './site.ts'
|
|
29
|
-
import { SourceEditor } from './source-editor.ts'
|
|
30
|
+
import { SourceEditor, versionOf } from './source-editor.ts'
|
|
30
31
|
import { createDocumentEditor } from './document-editor.ts'
|
|
31
32
|
import type { DocumentEditor } from './document-editor.ts'
|
|
32
33
|
import { createDocumentTranscriptions } from './document-transcription.ts'
|
|
@@ -50,6 +51,8 @@ export interface ServeOptions {
|
|
|
50
51
|
/** The address browsers use when a reverse proxy fronts the service (see `ServerOptions.publicUrl`). */
|
|
51
52
|
publicUrl?: string
|
|
52
53
|
env?: NodeJS.ProcessEnv
|
|
54
|
+
/** Approvals given without asking, over the workspace's `approvals` (`presmium serve --allow`). */
|
|
55
|
+
allow?: ApprovalKind[]
|
|
53
56
|
approvalTimeoutMs?: number
|
|
54
57
|
log?: Logger
|
|
55
58
|
}
|
|
@@ -76,8 +79,7 @@ interface NodeServiceLoad { key: string, promise: Promise<AuthoringServices>, co
|
|
|
76
79
|
const DISK_LOOK_MS = 1000
|
|
77
80
|
|
|
78
81
|
function makeStateDir(root: string, env: NodeJS.ProcessEnv): string {
|
|
79
|
-
const
|
|
80
|
-
const dir = join(base, 'presmium', 'serve', createHash('sha256').update(root).digest('hex').slice(0, 16))
|
|
82
|
+
const dir = serveStateDir(root, env)
|
|
81
83
|
mkdirSync(dir, { recursive: true })
|
|
82
84
|
return dir
|
|
83
85
|
}
|
|
@@ -86,6 +88,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
|
|
|
86
88
|
const env = options.env ?? process.env
|
|
87
89
|
const log = options.log ?? pluginLogger('presmium serve')
|
|
88
90
|
const config = readWorkspaceConfig(options.dir)
|
|
91
|
+
if (env.PRESMIUM_AGENT_CANDIDATE === '1') config.settings['presmium.assistant'] = { ...config.settings['presmium.assistant'], review: 'auto' }
|
|
89
92
|
const { root } = config
|
|
90
93
|
const operatorDirectory = resolveOperatorDir(root, options.operatorDir ?? env.PRESMIUM_OPERATOR_DIR)
|
|
91
94
|
const stateDir = makeStateDir(root, env)
|
|
@@ -118,6 +121,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
|
|
|
118
121
|
let transcriptionAdoption: ReturnType<typeof createTranscriptionAdoption> | undefined
|
|
119
122
|
let audioAuthoring: ReturnType<typeof createDocumentAudioAuthoring> | undefined
|
|
120
123
|
let imageAuthoring: ReturnType<typeof createDocumentImageAuthoring> | undefined
|
|
124
|
+
let capture: ReturnType<typeof createDocumentCapture> | undefined
|
|
121
125
|
let voiceAuthoring: ReturnType<typeof createDocumentVoiceAuthoring> | undefined
|
|
122
126
|
let workspaceRoutesOwner: ReturnType<typeof workspaceRoutes> | undefined
|
|
123
127
|
let routesPlugin: ServedPlugin | undefined
|
|
@@ -249,7 +253,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
|
|
|
249
253
|
revisions,
|
|
250
254
|
operations: new DocumentOperations({ config, git, revisions, writer, changed: documentsChanged, locks }),
|
|
251
255
|
git,
|
|
252
|
-
agentSessionReviews: new AgentSessionReviews({ config, revisions, locks, files: writer, log }),
|
|
256
|
+
agentSessionReviews: new AgentSessionReviews({ config, revisions, locks, files: writer, log, flush: (documents, member) => authoringClients?.flush(documents, member) ?? Promise.resolve() }),
|
|
253
257
|
taskReviews: createTaskReviewService({ config, locks, files: writer, log }),
|
|
254
258
|
}
|
|
255
259
|
}
|
|
@@ -268,6 +272,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
|
|
|
268
272
|
get voiceAuthoring() { return voiceAuthoring?.service },
|
|
269
273
|
get transcriptions() { return transcriptions },
|
|
270
274
|
get transcriptionAdoption() { return transcriptionAdoption?.service },
|
|
275
|
+
get capture() { return capture?.service },
|
|
271
276
|
get routes() { return workspaceRoutesOwner?.routes ? { [WORKSPACE_ID]: workspaceRoutesOwner.routes, ...voiceAuthoring ? { 'presmium.lecture': authorizeWorkspaceRoutes(voiceAuthoring.routes, launcherToken) } : {} } : undefined },
|
|
272
277
|
agentTools(document) {
|
|
273
278
|
const compiled = (document === undefined ? [...compileSessions.values()] : [compileSessions.get(document)]).flatMap(session => session?.latest ? [session.latest] : [])
|
|
@@ -355,7 +360,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
|
|
|
355
360
|
}
|
|
356
361
|
},
|
|
357
362
|
settings: config.settings,
|
|
358
|
-
approvals: config.approvals,
|
|
363
|
+
approvals: { ...config.approvals, ...Object.fromEntries((options.allow ?? []).map(kind => [kind, 'allow' as const])) },
|
|
359
364
|
operatorDir: operatorDirectory,
|
|
360
365
|
serverHost,
|
|
361
366
|
env,
|
|
@@ -422,6 +427,15 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
|
|
|
422
427
|
throw error
|
|
423
428
|
}
|
|
424
429
|
|
|
430
|
+
// A picture right after a save shows what was saved: the document is compiled first when its file is newer.
|
|
431
|
+
const savedCompilation = async (dir: string): Promise<Compilation> => {
|
|
432
|
+
const session = compileSessionOf(dir)
|
|
433
|
+
const compilation = await session.ready()
|
|
434
|
+
const entry = docs().find(doc => doc.dir === dir)?.entry
|
|
435
|
+
const saved = entry ? versionOf(readFileSync(join(root, entry))) : undefined
|
|
436
|
+
return saved && compilation.doc.source?.version !== saved ? await session.recompile() : compilation
|
|
437
|
+
}
|
|
438
|
+
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
439
|
started()
|
|
426
440
|
|
|
427
441
|
const compileForSite = async (dir: string): Promise<IRDocument> => {
|
|
@@ -433,6 +447,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
|
|
|
433
447
|
site = await startWorkspaceSite({ root, spec, basePath, bundled: options.bundled, stateDir, compile: compileForSite, stampPreviewRevision: (compilation, doc) => workbench!.stampPreviewRevision(compilation, doc), diagnostics: running.diagnostics, preview, log })
|
|
434
448
|
} catch (error) {
|
|
435
449
|
await closeAuthoring()
|
|
450
|
+
await capture.close()
|
|
436
451
|
await workbench.close()
|
|
437
452
|
await running.close()
|
|
438
453
|
if (home) rmSync(home, { recursive: true, force: true })
|
|
@@ -448,6 +463,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
|
|
|
448
463
|
await closeAuthoring()
|
|
449
464
|
for (const session of compileSessions.values()) session.close()
|
|
450
465
|
await jobs.close()
|
|
466
|
+
await capture?.close()
|
|
451
467
|
await workbench?.close()
|
|
452
468
|
await site?.close()
|
|
453
469
|
await running.close()
|
|
@@ -471,6 +487,23 @@ interface WorkspaceSiteOptions {
|
|
|
471
487
|
|
|
472
488
|
type WorkspaceSite = Awaited<ReturnType<typeof startWorkspaceSite>>
|
|
473
489
|
|
|
490
|
+
/** The bundler's failure as a diagnostic: the file and the module it could not find, when that is the failure. */
|
|
491
|
+
function codeFailure(error: unknown): Finding {
|
|
492
|
+
const text = stripVTControlCharacters(errorMessage(error))
|
|
493
|
+
const unresolved = /failed to resolve import "([^"]+)" from "([^"]+)"/.exec(text)
|
|
494
|
+
if (unresolved) {
|
|
495
|
+
return {
|
|
496
|
+
checkId: 'presmium.preview.code',
|
|
497
|
+
severity: 'error',
|
|
498
|
+
message: `the document's code could not be bundled: ${unresolved[1]} cannot be found from this file`,
|
|
499
|
+
hint: 'Name the plugin that provides it in metadata.plugins, or add its package to the project’s dependencies.',
|
|
500
|
+
source: { file: unresolved[2]! },
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
const reason = text.split('\n').map(line => line.replace(/^Error:\s*/, '').trim()).find(line => line && !/^Build failed/.test(line)) ?? text
|
|
504
|
+
return { checkId: 'presmium.preview.code', severity: 'error', message: `the document's code could not be bundled: ${reason}` }
|
|
505
|
+
}
|
|
506
|
+
|
|
474
507
|
/** The workspace site's dev router in this process, which serve forwards the site's paths to. */
|
|
475
508
|
async function startWorkspaceSite(options: WorkspaceSiteOptions) {
|
|
476
509
|
const { root, spec, log } = options
|
|
@@ -497,7 +530,20 @@ async function startWorkspaceSite(options: WorkspaceSiteOptions) {
|
|
|
497
530
|
})
|
|
498
531
|
},
|
|
499
532
|
warm: (dir: string): Promise<void> => dev.warm?.(dir) ?? Promise.resolve(),
|
|
500
|
-
app: (dir: string, wait: boolean): Promise<string | undefined> =>
|
|
533
|
+
app: async (dir: string, wait: boolean): Promise<string | undefined> => {
|
|
534
|
+
// A file of the document's own code (a scene, a component) that does not bundle fails alone: what imports it
|
|
535
|
+
// shows its failure. Each such file is a diagnostic, where the author, the workbench's AI and MCP clients find
|
|
536
|
+
// it, until a preview bundles it; when none of the code bundles, the preview fails, and the reason is one.
|
|
537
|
+
const source = { document: dir, origin: 'preview', renderer: 'web', instance: 'code' } as const
|
|
538
|
+
try {
|
|
539
|
+
const page = await (dev.app?.(dir, wait) ?? Promise.resolve(undefined))
|
|
540
|
+
if (wait && page) options.diagnostics.replace(source, dev.codeFindings?.(dir) ?? [], { root, irRevision: options.diagnostics.irRevision(dir) })
|
|
541
|
+
return page
|
|
542
|
+
} catch (error) {
|
|
543
|
+
if (wait && !(error instanceof PreviewPreparing)) options.diagnostics.replace(source, [codeFailure(error)], { root, irRevision: options.diagnostics.irRevision(dir) })
|
|
544
|
+
throw error
|
|
545
|
+
}
|
|
546
|
+
},
|
|
501
547
|
close: (): Promise<void> => dev.close(),
|
|
502
548
|
}
|
|
503
549
|
}
|
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 {
|
|
@@ -8,7 +8,6 @@ import { isWithin } from '../domain/paths.ts'
|
|
|
8
8
|
import { listDocumentEntries, readDocumentSummary } from './config.ts'
|
|
9
9
|
import type { DocumentEntry, WorkspaceConfig } from './config.ts'
|
|
10
10
|
import { RequestError } from './errors.ts'
|
|
11
|
-
import { lockedError } from './locks.ts'
|
|
12
11
|
import type { DocumentLocks } from './locks.ts'
|
|
13
12
|
import { documentDirOf, FilesError, writeChanges } from './writer.ts'
|
|
14
13
|
import type { DocumentWriter } from './writer.ts'
|
|
@@ -178,8 +177,7 @@ export class SourceEditor {
|
|
|
178
177
|
if (BINARY.test(path)) throw new RequestError(415, `${path} is not a text file`)
|
|
179
178
|
const document = this.#documentHolding(path, documents)?.dir
|
|
180
179
|
const scopeDir = document ?? ''
|
|
181
|
-
const release = this.#locks ? this.#locks.
|
|
182
|
-
if (!release) throw lockedError(scopeDir, this.#locks!.holder(scopeDir)!)
|
|
180
|
+
const release = this.#locks ? await this.#locks.acquire(scopeDir, 'editor:create') : () => {}
|
|
183
181
|
try {
|
|
184
182
|
await this.#writer.create(path, Buffer.alloc(0), document === undefined)
|
|
185
183
|
return { path, content: '', version: versionOf('') }
|
|
@@ -229,8 +227,7 @@ export class SourceEditor {
|
|
|
229
227
|
const document = documents[0]
|
|
230
228
|
if (!document || documents.some(found => found?.dir !== document.dir)) throw new RequestError(400, 'a source transaction must stay in one document')
|
|
231
229
|
const scopeDir = document.dir
|
|
232
|
-
const release = this.#locks ? this.#locks.
|
|
233
|
-
if (!release) throw lockedError(scopeDir, this.#locks!.holder(scopeDir)!)
|
|
230
|
+
const release = this.#locks ? await this.#locks.acquire(scopeDir, 'editor:transaction') : () => {}
|
|
234
231
|
const work = async (): Promise<SourceTransactionAnswer> => {
|
|
235
232
|
// Read every preimage before creating directories or writing any file.
|
|
236
233
|
const snapshots = changes.map(change => {
|
|
@@ -299,8 +296,7 @@ export class SourceEditor {
|
|
|
299
296
|
const document = this.#documentHolding(path, documents)
|
|
300
297
|
const outside = document === undefined
|
|
301
298
|
const scopeDir = document?.dir ?? ''
|
|
302
|
-
const release = this.#locks ? this.#locks.
|
|
303
|
-
if (!release) throw lockedError(scopeDir, this.#locks!.holder(scopeDir)!)
|
|
299
|
+
const release = this.#locks ? await this.#locks.acquire(scopeDir, 'editor:save') : () => {}
|
|
304
300
|
try {
|
|
305
301
|
const bytes = this.#readBytes(scope, path, member, documents)
|
|
306
302
|
const now = versionOf(bytes)
|
|
@@ -33,7 +33,7 @@ export interface WorkbenchApi {
|
|
|
33
33
|
* `prefetch`: the workbench prepares the document ahead of the author's click, answered at once. A build still running
|
|
34
34
|
* after the wait is answered with 503 `preview-preparing` and `Retry-After`.
|
|
35
35
|
*/
|
|
36
|
-
preview(document: string, renderer?: PreviewRenderer, prefetch?: boolean): Promise<PreviewAnswer>
|
|
36
|
+
preview(document: string, renderer?: PreviewRenderer, prefetch?: boolean, browserOrigin?: string): Promise<PreviewAnswer>
|
|
37
37
|
build(document: string, to?: string[]): Promise<BuildAnswer>
|
|
38
38
|
check(document: string): Promise<CheckAnswer>
|
|
39
39
|
}
|
|
@@ -80,6 +80,17 @@ export function createWorkbenchBackend(options: WorkbenchBackendOptions): Workbe
|
|
|
80
80
|
const { root, log } = options
|
|
81
81
|
const irRevisions = new WeakMap<Compilation, string>()
|
|
82
82
|
const relativeDocs = new WeakMap<Compilation, IRDocument>()
|
|
83
|
+
const previewBase = (base: string, browserOrigin: string | undefined): string => {
|
|
84
|
+
if (!browserOrigin) return base
|
|
85
|
+
try {
|
|
86
|
+
const preview = new URL(base), browser = new URL(browserOrigin)
|
|
87
|
+
if (preview.protocol !== browser.protocol || !['localhost', '127.0.0.1', '[::1]'].includes(preview.hostname)) return base
|
|
88
|
+
preview.hostname = browser.hostname
|
|
89
|
+
return base.endsWith('/') ? preview.href : preview.href.replace(/\/$/, '')
|
|
90
|
+
} catch {
|
|
91
|
+
return base
|
|
92
|
+
}
|
|
93
|
+
}
|
|
83
94
|
const irRevisionOf = (compilation: Compilation) => {
|
|
84
95
|
let known = irRevisions.get(compilation)
|
|
85
96
|
if (!known) irRevisions.set(compilation, known = irRevision(compilation.doc))
|
|
@@ -119,7 +130,7 @@ export function createWorkbenchBackend(options: WorkbenchBackendOptions): Workbe
|
|
|
119
130
|
return () => own.delete(listener)
|
|
120
131
|
}, { signal })
|
|
121
132
|
},
|
|
122
|
-
async preview(document, renderer, prefetch = false) {
|
|
133
|
+
async preview(document, renderer, prefetch = false, browserOrigin) {
|
|
123
134
|
const request = ++previewRequest
|
|
124
135
|
const started = Date.now()
|
|
125
136
|
const label = `[preview ${request}] document=${JSON.stringify(document || '.')} renderer=${renderer ?? 'all'} prefetch=${prefetch}`
|
|
@@ -127,7 +138,7 @@ export function createWorkbenchBackend(options: WorkbenchBackendOptions): Workbe
|
|
|
127
138
|
let outcome = 'failed'
|
|
128
139
|
log.info(`${label} state=started`)
|
|
129
140
|
try {
|
|
130
|
-
const base = options.url()
|
|
141
|
+
const base = previewBase(options.url(), browserOrigin)
|
|
131
142
|
// The viewer app's page once it has what the document needs (an opened document waits for it a while), else the
|
|
132
143
|
// document's page on the site.
|
|
133
144
|
const page = await options.viewerPage?.(document, !prefetch).catch((error: unknown) => {
|