@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.
- package/README.md +4 -4
- package/package.json +8 -5
- package/src/domain/paths.ts +0 -15
- package/src/node/agent-activity.ts +46 -0
- package/src/node/archive.ts +33 -0
- package/src/node/authoring-clients.ts +73 -20
- package/src/node/authoring-windows.ts +165 -0
- package/src/node/build.ts +28 -23
- package/src/node/capture.ts +383 -0
- package/src/node/config.ts +136 -50
- package/src/node/document-assets.ts +2 -2
- package/src/node/document-audio.ts +65 -46
- package/src/node/document-authoring.ts +30 -15
- package/src/node/document-check.ts +36 -0
- package/src/node/document-history.ts +32 -5
- package/src/node/document-images.ts +24 -14
- package/src/node/document-import.ts +123 -0
- package/src/node/document-index.ts +644 -0
- package/src/node/document-materials.ts +80 -0
- package/src/node/document-operations.ts +4 -2
- package/src/node/document-transcription.ts +2 -1
- package/src/node/document-voice.ts +121 -13
- package/src/node/git-runner.mjs +19 -0
- package/src/node/git.ts +141 -22
- package/src/node/host-activity.ts +17 -0
- package/src/node/host-upgrade.ts +28 -0
- package/src/node/jobs.ts +40 -8
- package/src/node/local-history.ts +84 -0
- package/src/node/locks.ts +12 -0
- package/src/node/mcp-settings.ts +68 -0
- package/src/node/media-upload-messages.ts +4 -0
- package/src/node/media-upload-page.ts +57 -0
- package/src/node/media-upload.css +4 -0
- package/src/node/media-uploads.ts +116 -0
- package/src/node/page-delete.ts +0 -1
- package/src/node/project-files.ts +2 -2
- package/src/node/projects.ts +20 -5
- package/src/node/review/agent-session-reviews.ts +194 -63
- package/src/node/review/agent-workspace.ts +124 -0
- package/src/node/review/git-review.ts +47 -15
- package/src/node/review/record.ts +5 -1
- package/src/node/review/routes.ts +9 -1
- package/src/node/review/workspace-review.ts +87 -0
- package/src/node/revision-files.ts +54 -0
- package/src/node/revisions.ts +244 -59
- package/src/node/routes.ts +52 -59
- package/src/node/serve.ts +267 -52
- package/src/node/site.ts +5 -5
- package/src/node/source-editor.ts +66 -26
- package/src/node/speech-settings.ts +6 -8
- package/src/node/templates.ts +2 -2
- package/src/node/tree-operations.ts +425 -0
- package/src/node/tree-routes.ts +94 -0
- package/src/node/workbench-api.ts +14 -3
- package/src/node/workspace-changes.ts +130 -0
- package/src/node/workspace-migrate.ts +54 -0
- package/src/node/workspace-source.ts +133 -0
- package/src/node/writer.ts +21 -8
- package/templates/document/default/{lecture.json → index.pmd} +5 -1
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { existsSync, rmSync } from 'node:fs'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import { DOCUMENT_ENTRY, DOCUMENT_MATERIALS_DIR, DOCUMENT_MATERIALS_MAX_BYTES, DOCUMENT_MATERIALS_MAX_FILES, hasRole, jsonResponse } from '@lincyaw/kernel'
|
|
4
|
+
import type { DocumentMaterialsAnswer, Route } from '@lincyaw/kernel'
|
|
5
|
+
import type { WorkspaceConfig } from './config.ts'
|
|
6
|
+
import { catchRequestErrors, RequestError } from './errors.ts'
|
|
7
|
+
import type { DocumentLocks } from './locks.ts'
|
|
8
|
+
import type { Revisions } from './revisions.ts'
|
|
9
|
+
import type { DocumentWriter } from './writer.ts'
|
|
10
|
+
|
|
11
|
+
const NAME_MAX = 120
|
|
12
|
+
const bad = (status: number, code: string): never => { throw new RequestError(status, `document-materials-${code}`) }
|
|
13
|
+
|
|
14
|
+
/** A file name that stays one plain name in the materials folder: no folders, control characters or leading dots. */
|
|
15
|
+
function plainName(name: string): string {
|
|
16
|
+
const base = (name.split(/[\\/]/).at(-1) ?? '').replace(/[\u0000-\u001f\u007f:*?"<>|]/g, '').replace(/^[.\s]+/, '').trim()
|
|
17
|
+
if (!base) return 'material'
|
|
18
|
+
if ([...base].length <= NAME_MAX) return base
|
|
19
|
+
const dot = base.lastIndexOf('.'), extension = dot > 0 && base.length - dot <= 12 ? base.slice(dot) : ''
|
|
20
|
+
return [...base.slice(0, base.length - extension.length)].slice(0, NAME_MAX - extension.length).join('') + extension
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** `name`, or `name (2)`, `name (3)`… before its extension, whichever is not taken yet. */
|
|
24
|
+
function freeName(name: string, taken: (name: string) => boolean): string {
|
|
25
|
+
if (!taken(name)) return name
|
|
26
|
+
const dot = name.lastIndexOf('.'), stem = dot > 0 ? name.slice(0, dot) : name, extension = dot > 0 ? name.slice(dot) : ''
|
|
27
|
+
for (let n = 2; ; n++) {
|
|
28
|
+
const next = `${stem} (${n})${extension}`
|
|
29
|
+
if (!taken(next)) return next
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Adds the author's source material (PDF, Word, slides, pictures, text…) to a document: the files are kept as they
|
|
35
|
+
* are in the document's `materials/` folder, under its lock and recorded as one revision, for the AI to write the
|
|
36
|
+
* document from. Nothing in the document refers to them.
|
|
37
|
+
*/
|
|
38
|
+
export function documentMaterialsRoute(options: { config: WorkspaceConfig, writer: DocumentWriter, locks: DocumentLocks, revisions?: Revisions }): Route {
|
|
39
|
+
const { config, writer, locks, revisions } = options
|
|
40
|
+
return {
|
|
41
|
+
role: 'editor',
|
|
42
|
+
maxBody: DOCUMENT_MATERIALS_MAX_BYTES + (1 << 20),
|
|
43
|
+
handle: (request, ctx) => catchRequestErrors(async () => {
|
|
44
|
+
if (request.method !== 'POST') return bad(405, 'method')
|
|
45
|
+
if (!hasRole(ctx.member, 'editor')) return bad(403, 'forbidden')
|
|
46
|
+
const dir = ctx.document
|
|
47
|
+
if (!existsSync(join(config.root, dir, DOCUMENT_ENTRY))) return bad(404, 'document')
|
|
48
|
+
const form = await request.formData().catch(() => bad(400, 'invalid'))
|
|
49
|
+
const uploads = form.getAll('files')
|
|
50
|
+
if (uploads.length === 0 || uploads.some(file => typeof file === 'string')) return bad(400, 'invalid')
|
|
51
|
+
const files = uploads as File[]
|
|
52
|
+
if (files.length > DOCUMENT_MATERIALS_MAX_FILES || files.reduce((sum, file) => sum + file.size, 0) > DOCUMENT_MATERIALS_MAX_BYTES) return bad(413, 'limit')
|
|
53
|
+
const folder = dir ? `${dir}/${DOCUMENT_MATERIALS_DIR}` : DOCUMENT_MATERIALS_DIR
|
|
54
|
+
const release = await locks.acquire(dir, 'document:materials')
|
|
55
|
+
try {
|
|
56
|
+
const write = async (): Promise<DocumentMaterialsAnswer> => {
|
|
57
|
+
const names: string[] = []
|
|
58
|
+
for (const file of files) names.push(freeName(plainName(file.name), name => names.includes(name) || existsSync(join(config.root, folder, name))))
|
|
59
|
+
const paths = names.map(name => `${folder}/${name}`)
|
|
60
|
+
if (revisions && await revisions.ignoresAny(paths)) return bad(403, 'forbidden')
|
|
61
|
+
await revisions?.checkpoint(paths)
|
|
62
|
+
const written: string[] = []
|
|
63
|
+
try {
|
|
64
|
+
for (const [index, file] of files.entries()) {
|
|
65
|
+
request.signal.throwIfAborted()
|
|
66
|
+
await writer.create(paths[index]!, new Uint8Array(await file.arrayBuffer()))
|
|
67
|
+
written.push(paths[index]!)
|
|
68
|
+
}
|
|
69
|
+
const revision = revisions ? await revisions.commitWhileLocked({ paths, summary: `Add source material to ${dir || 'the document'}`, body: names.join('\n'), origin: { kind: 'editor', member: ctx.member } }) : undefined
|
|
70
|
+
return { files: names.map(name => `${DOCUMENT_MATERIALS_DIR}/${name}`), ...revision ? { revision } : {} }
|
|
71
|
+
} catch (error) {
|
|
72
|
+
for (const path of written) rmSync(join(config.root, path), { force: true })
|
|
73
|
+
throw error
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return jsonResponse(await (revisions ? revisions.transaction(write) : write()), 201)
|
|
77
|
+
} finally { release() }
|
|
78
|
+
}),
|
|
79
|
+
}
|
|
80
|
+
}
|
|
@@ -21,7 +21,8 @@ export interface DocumentsChange {
|
|
|
21
21
|
}
|
|
22
22
|
|
|
23
23
|
export function documentsDiff(before: string[], after: string[]): DocumentsChange {
|
|
24
|
-
|
|
24
|
+
const was = new Set(before), now = new Set(after)
|
|
25
|
+
return { removed: before.filter(dir => !now.has(dir)), added: after.filter(dir => !was.has(dir)) }
|
|
25
26
|
}
|
|
26
27
|
|
|
27
28
|
export interface DocumentOperationsOptions {
|
|
@@ -66,6 +67,7 @@ export class DocumentOperations {
|
|
|
66
67
|
release ??= claimed?.release
|
|
67
68
|
}
|
|
68
69
|
await prepared?.verify()
|
|
70
|
+
await this.#revisions.checkpoint(touched(operation))
|
|
69
71
|
const head = await this.#revisions.head()
|
|
70
72
|
const before = await this.#writer.checkpoint(touched(operation), operation.op === 'rename' ? { from: operation.dir, to: operation.to } : undefined, prepared?.changes?.map(change => change.path)).catch(error => {
|
|
71
73
|
if (error instanceof DocumentCheckpointRefusal) throw new RequestError(error.status, error.message, error.detail)
|
|
@@ -142,7 +144,7 @@ export class DocumentOperations {
|
|
|
142
144
|
const fresh = (dir: string) => {
|
|
143
145
|
const invalid = invalidDocumentDir(dir)
|
|
144
146
|
if (invalid) throw new RequestError(400, invalid)
|
|
145
|
-
if (!isDocumentDir(config, dir)) throw new RequestError(400, `"${dir}"
|
|
147
|
+
if (!isDocumentDir(config, dir)) throw new RequestError(400, `"${dir}" cannot hold a document`)
|
|
146
148
|
const holder = known.find(doc => doc !== '' && (isWithin(dir, doc) || isWithin(doc, dir)))
|
|
147
149
|
if (holder !== undefined) throw new RequestError(409, `${dir} would hold or be inside the document ${holder}`)
|
|
148
150
|
if (existsSync(join(config.root, dir))) throw new RequestError(409, `${dir} exists already`)
|
|
@@ -75,7 +75,7 @@ async function writeJson(path: string, value: unknown, exclusive = false): Promi
|
|
|
75
75
|
}
|
|
76
76
|
|
|
77
77
|
/** Recognition is an immutable candidate. Only a later, separate authoring action may adopt it. */
|
|
78
|
-
export function createDocumentTranscriptions({ root, editor, audio, speech, services }: Options): DocumentTranscriptions & { close(): Promise<void> } {
|
|
78
|
+
export function createDocumentTranscriptions({ root, editor, audio, speech, services }: Options): DocumentTranscriptions & { busy(): boolean, close(): Promise<void> } {
|
|
79
79
|
const active = new Map<string, Active>()
|
|
80
80
|
const admitting = new Map<string, { document: string, documentId: string, member: string, intent: string, controller: AbortController, finished: Promise<void> }>()
|
|
81
81
|
let closed = false
|
|
@@ -266,6 +266,7 @@ export function createDocumentTranscriptions({ root, editor, audio, speech, serv
|
|
|
266
266
|
}
|
|
267
267
|
}
|
|
268
268
|
return {
|
|
269
|
+
busy: () => active.size > 0 || admitting.size > 0,
|
|
269
270
|
capabilities,
|
|
270
271
|
async list(document, member): Promise<TranscriptionListAnswer> {
|
|
271
272
|
const path = join(dirname(authorize(document, member)), 'transcriptions'), observation = observe(document, member)
|
|
@@ -1,21 +1,36 @@
|
|
|
1
|
-
import { DOCUMENT_ENTRY, fnv1a64, hasRole, speechEngineId } from '@lincyaw/kernel'
|
|
2
|
-
import type { CanonicalSource, DocumentVoiceAuthoring, Finding, Member, SpeechService, VoiceoverExecution, VoiceoverJob } from '@lincyaw/kernel'
|
|
3
|
-
import { createVoiceoverOwner, createVoiceoverRoutes, validateDocumentVoiceCatalogQuery, validateVoicePreviewStart } from '@lincyaw/kernel/node'
|
|
1
|
+
import { DOCUMENT_ENTRY, VOICE_CLONE_MAX_AUDIO_BYTES, fnv1a64, hasRole, speechEngineId } from '@lincyaw/kernel'
|
|
2
|
+
import type { CanonicalSource, DocumentVoiceAuthoring, DocumentVoiceCloneAudio, Finding, Member, PreparedVoiceClone, SpeechService, VoiceoverExecution, VoiceoverJob } from '@lincyaw/kernel'
|
|
3
|
+
import { createVoiceoverOwner, createVoiceoverRoutes, validateDocumentVoiceCatalogQuery, validateDocumentVoiceClone, validateDocumentVoiceCloneQuery, validateVoicePreviewStart } from '@lincyaw/kernel/node'
|
|
4
|
+
import { extname } from 'node:path'
|
|
5
|
+
import { randomBytes } from 'node:crypto'
|
|
6
|
+
import { readDocumentAudioBytes } from './document-audio.ts'
|
|
4
7
|
import { readAuthoringDocument } from './document-editor.ts'
|
|
5
8
|
import { RequestError } from './errors.ts'
|
|
6
9
|
import type { SourceEditor } from './source-editor.ts'
|
|
10
|
+
import type { MediaUploadsOwner } from './media-uploads.ts'
|
|
7
11
|
|
|
8
12
|
export interface DocumentVoiceServices { speech?: SpeechService, voiceover?: { version: 1, preview: true }, voiceoverExecution?: VoiceoverExecution, findings?: Finding[] }
|
|
9
13
|
export interface DocumentVoiceAuthoringOptions {
|
|
10
14
|
editor: SourceEditor
|
|
11
15
|
services(document: string, source: CanonicalSource): Promise<DocumentVoiceServices>
|
|
16
|
+
/** Prepare the current compiled document only for operations that need voice targets and timing. */
|
|
17
|
+
prepareExecution?(document: string, source: CanonicalSource, signal: AbortSignal): Promise<void>
|
|
12
18
|
revision?(document: string): string | undefined
|
|
19
|
+
uploads?: MediaUploadsOwner
|
|
13
20
|
}
|
|
14
21
|
const same = (a: CanonicalSource, b: CanonicalSource) => a.documentId === b.documentId && a.version === b.version && a.fingerprint === b.fingerprint
|
|
15
22
|
|
|
16
|
-
export function createDocumentVoiceAuthoring({ editor, services, revision }: DocumentVoiceAuthoringOptions) {
|
|
23
|
+
export function createDocumentVoiceAuthoring({ editor, services, prepareExecution, revision, uploads }: DocumentVoiceAuthoringOptions) {
|
|
17
24
|
const pending = new Set<{ controller: AbortController, finished: Promise<unknown> }>()
|
|
18
25
|
const owners = new Map<string, ReturnType<typeof createVoiceoverOwner>>()
|
|
26
|
+
const clones = new Map<string, { document: string, member: string, request: string, prepared: PreparedVoiceClone }>()
|
|
27
|
+
const cloneEntry = (document: string, id: string, member: Member) => {
|
|
28
|
+
if (!hasRole(member, 'owner')) throw new RequestError(403, 'voice-clone-permission-denied')
|
|
29
|
+
authorize(document, member)
|
|
30
|
+
const entry = clones.get(id)
|
|
31
|
+
if (entry && (entry.document !== document || entry.member !== member.id)) throw new RequestError(403, 'voice-clone-permission-denied')
|
|
32
|
+
return entry
|
|
33
|
+
}
|
|
19
34
|
let closed = false
|
|
20
35
|
const authorize = (document: string, member: Member) => {
|
|
21
36
|
if (!hasRole(member, 'editor')) throw new RequestError(403, 'voice-authoring-permission-denied')
|
|
@@ -32,7 +47,7 @@ export function createDocumentVoiceAuthoring({ editor, services, revision }: Doc
|
|
|
32
47
|
const opened = readAuthoringDocument(editor, { document, member })
|
|
33
48
|
const source = { documentId: opened.content.id, version: opened.source.version, fingerprint: fnv1a64(opened.source.content) }
|
|
34
49
|
if (expected && !same(source, expected)) throw new RequestError(409, 'document-version-changed', { currentSource: source })
|
|
35
|
-
return { source, lang: opened.
|
|
50
|
+
return { source, lang: opened.effective.metadata.lang }
|
|
36
51
|
}
|
|
37
52
|
const work = <T>(signal: AbortSignal | undefined, run: (signal: AbortSignal) => Promise<T>): Promise<T> => {
|
|
38
53
|
if (closed) throw new RequestError(503, 'voice-authoring-closed')
|
|
@@ -51,9 +66,19 @@ export function createDocumentVoiceAuthoring({ editor, services, revision }: Doc
|
|
|
51
66
|
signal.throwIfAborted(); current(document, member, opened.source)
|
|
52
67
|
return { ...opened, ...loaded }
|
|
53
68
|
}
|
|
69
|
+
// A read that names no version follows the document: a save while it loads (the voice just chosen) is read again,
|
|
70
|
+
// not refused; only a document that keeps changing is.
|
|
71
|
+
const loadLatest = async (document: string, member: Member, signal: AbortSignal) => {
|
|
72
|
+
for (let attempt = 1; ; attempt++) {
|
|
73
|
+
try { return await load(document, member, signal) }
|
|
74
|
+
catch (error) { if (attempt >= 3 || !(error instanceof RequestError && error.status === 409 && error.message === 'document-version-changed')) throw error }
|
|
75
|
+
}
|
|
76
|
+
}
|
|
54
77
|
const execution = (document: string, member: Member) => async (expected: CanonicalSource | undefined, signal: AbortSignal) => {
|
|
55
78
|
const loaded = await load(document, member, signal, expected)
|
|
56
79
|
if (!loaded.voiceoverExecution) throw new RequestError(503, 'voiceover-unavailable')
|
|
80
|
+
await prepareExecution?.(document, loaded.source, signal)
|
|
81
|
+
signal.throwIfAborted(); current(document, member, loaded.source)
|
|
57
82
|
return loaded.voiceoverExecution
|
|
58
83
|
}
|
|
59
84
|
const isCurrent = (document: string, member: Member, job: VoiceoverJob): boolean | 'unknown' => {
|
|
@@ -61,25 +86,108 @@ export function createDocumentVoiceAuthoring({ editor, services, revision }: Doc
|
|
|
61
86
|
catch { return 'unknown' }
|
|
62
87
|
}
|
|
63
88
|
const service: DocumentVoiceAuthoring = {
|
|
89
|
+
prepareClone: (document, value, member, signal) => work(signal, async signal => {
|
|
90
|
+
if (!hasRole(member, 'owner')) throw new RequestError(403, 'voice-clone-permission-denied')
|
|
91
|
+
if (!validateDocumentVoiceClone(value)) throw new RequestError(400, 'voice-clone-invalid')
|
|
92
|
+
if (clones.size >= 4) throw new RequestError(503, 'voice-authoring-busy')
|
|
93
|
+
const request = structuredClone(value), loaded = await load(document, member, signal, request.source)
|
|
94
|
+
const speech = loaded.speech, engine = request.engine ?? await speech?.defaultSynthesisEngine?.()
|
|
95
|
+
const read = async (input: DocumentVoiceCloneAudio) => {
|
|
96
|
+
const path = typeof input === 'string' ? input : undefined
|
|
97
|
+
if (path !== undefined && path.split(/[\\/]/).some(part => part.startsWith('.'))) throw new RequestError(403, 'audio-file-path')
|
|
98
|
+
const uploaded = typeof input !== 'string' ? uploads?.read(document, loaded.source.documentId, member, input.upload, 'audio') : undefined
|
|
99
|
+
if (path === undefined && !uploaded) throw new RequestError(503, 'media-upload-unavailable')
|
|
100
|
+
const types: Record<string, string> = { '.wav': 'audio/wav', '.mp3': 'audio/mpeg', '.webm': 'audio/webm', '.ogg': 'audio/ogg', '.m4a': 'audio/mp4', '.mp4': 'audio/mp4', '.flac': 'audio/flac', '.aac': 'audio/aac' }
|
|
101
|
+
const type = types[extname(path ?? uploaded!.name).toLowerCase()]
|
|
102
|
+
if (!type) throw new RequestError(422, 'voice-clone-audio-type')
|
|
103
|
+
if (path !== undefined) editor.assertEditable({ document, home: false }, path, member)
|
|
104
|
+
const bytes = uploaded?.bytes ?? await readDocumentAudioBytes(editor, { document, member, rest: '' }, path!, signal, VOICE_CLONE_MAX_AUDIO_BYTES)
|
|
105
|
+
if (bytes.length > VOICE_CLONE_MAX_AUDIO_BYTES) throw new RequestError(413, 'production.asset-size')
|
|
106
|
+
return { bytes, type }
|
|
107
|
+
}
|
|
108
|
+
const [sampleRead, statementRead] = await Promise.allSettled([read(request.sample), read(request.consent.statement)])
|
|
109
|
+
if (sampleRead.status === 'rejected') throw sampleRead.reason
|
|
110
|
+
if (statementRead.status === 'rejected') throw statementRead.reason
|
|
111
|
+
const sampleInput = sampleRead.value, statementInput = statementRead.value
|
|
112
|
+
current(document, member, loaded.source); signal.throwIfAborted()
|
|
113
|
+
if (!speech?.cloneVoice || !engine || !(await speech.engines()).some(info => info.id === speechEngineId(engine) && info.clone)) throw new RequestError(409, 'voice-clone-unavailable')
|
|
114
|
+
current(document, member, loaded.source); signal.throwIfAborted()
|
|
115
|
+
// Several readers may finish concurrently; the retained byte budget is checked again before retaining blobs.
|
|
116
|
+
if (clones.size >= 4) throw new RequestError(503, 'voice-authoring-busy')
|
|
117
|
+
let sample: Blob | undefined = new Blob([sampleInput.bytes as Uint8Array<ArrayBuffer>], { type: sampleInput.type })
|
|
118
|
+
let statement: Blob | undefined = new Blob([statementInput.bytes as Uint8Array<ArrayBuffer>], { type: statementInput.type })
|
|
119
|
+
let started: ReturnType<NonNullable<SpeechService['cloneVoice']>> | undefined
|
|
120
|
+
let expired = false
|
|
121
|
+
const id = randomBytes(32).toString('hex')
|
|
122
|
+
const prepared: PreparedVoiceClone = { engine: speechEngineId(engine), voice: request.voice,
|
|
123
|
+
start: startSignal => {
|
|
124
|
+
if (started) return started
|
|
125
|
+
if (expired || !sample || !statement) return Promise.reject(new RequestError(409, 'voice-clone-expired'))
|
|
126
|
+
clearTimeout(timer)
|
|
127
|
+
const exactSample = sample, exactStatement = statement
|
|
128
|
+
started = work(startSignal, async ownedSignal => {
|
|
129
|
+
current(document, member, loaded.source); ownedSignal.throwIfAborted()
|
|
130
|
+
return speech.cloneVoice!({ engine, voice: request.voice, sample: exactSample,
|
|
131
|
+
...request.lang ? { lang: request.lang } : {}, ...request.text ? { text: request.text } : {},
|
|
132
|
+
consent: { speaker: request.consent.speaker, scope: request.consent.scope, statement: exactStatement } }, ownedSignal)
|
|
133
|
+
}).finally(() => prepared.close())
|
|
134
|
+
return started
|
|
135
|
+
},
|
|
136
|
+
close: () => { expired = true; clearTimeout(timer); sample = undefined; statement = undefined; clones.delete(id) },
|
|
137
|
+
}
|
|
138
|
+
const timer = setTimeout(() => prepared.close(), 90000)
|
|
139
|
+
timer.unref()
|
|
140
|
+
clones.set(id, { document, member: member.id, request: JSON.stringify(request), prepared })
|
|
141
|
+
return prepared
|
|
142
|
+
}),
|
|
143
|
+
prepareCloneReference: async (document, request, member, signal) => {
|
|
144
|
+
const prepared = await service.prepareClone!(document, request, member, signal)
|
|
145
|
+
const found = [...clones].find(([, entry]) => entry.prepared === prepared)
|
|
146
|
+
if (!found) { prepared.close(); throw new RequestError(409, 'voice-clone-expired') }
|
|
147
|
+
if (signal?.aborted) { prepared.close(); signal.throwIfAborted() }
|
|
148
|
+
return { id: found[0], engine: prepared.engine, voice: prepared.voice }
|
|
149
|
+
},
|
|
150
|
+
runPreparedClone: (document, id, request, member, signal) => {
|
|
151
|
+
const entry = cloneEntry(document, id, member)
|
|
152
|
+
if (!entry) throw new RequestError(409, 'voice-clone-expired')
|
|
153
|
+
if (entry.request !== JSON.stringify(request)) throw new RequestError(409, 'voice-clone-preparation-changed')
|
|
154
|
+
try { return entry.prepared.start(signal) }
|
|
155
|
+
catch (error) { entry.prepared.close(); throw error }
|
|
156
|
+
},
|
|
157
|
+
releasePreparedClone: (document, id, member) => {
|
|
158
|
+
const entry = cloneEntry(document, id, member)
|
|
159
|
+
entry?.prepared.close()
|
|
160
|
+
return Boolean(entry)
|
|
161
|
+
},
|
|
162
|
+
cloneStatus: (document, query, member, signal) => work(signal, async signal => {
|
|
163
|
+
if (!hasRole(member, 'owner')) throw new RequestError(403, 'voice-clone-permission-denied')
|
|
164
|
+
if (!validateDocumentVoiceCloneQuery(query)) throw new RequestError(400, 'voice-clone-invalid')
|
|
165
|
+
const loaded = await load(document, member, signal), speech = loaded.speech, engine = query.engine ?? await speech?.defaultSynthesisEngine?.()
|
|
166
|
+
if (!speech?.cloneStatus || !engine || !(await speech.engines()).some(info => info.id === speechEngineId(engine) && info.clone)) throw new RequestError(409, 'voice-clone-unavailable')
|
|
167
|
+
current(document, member, loaded.source); signal.throwIfAborted()
|
|
168
|
+
return speech.cloneStatus(engine, query.voice, signal)
|
|
169
|
+
}),
|
|
64
170
|
capabilities: (document, member, signal) => work(signal, async signal => {
|
|
65
|
-
const loaded = await
|
|
171
|
+
const loaded = await loadLatest(document, member, signal)
|
|
66
172
|
const [engines, defaultEngine] = await Promise.all([loaded.speech?.engines() ?? [], loaded.speech?.defaultSynthesisEngine?.()])
|
|
67
|
-
signal.throwIfAborted()
|
|
173
|
+
signal.throwIfAborted()
|
|
68
174
|
const configured = engines.some(engine => engine.tts), unknown = !loaded.speech && loaded.findings?.some(finding => finding.severity === 'error')
|
|
69
175
|
const implemented = Boolean(loaded.voiceoverExecution)
|
|
70
|
-
return { document, source: loaded.source, verification: 'configuration-only', status: configured ? 'configured' : unknown ? 'unknown' : 'unavailable', ...!configured ? { reason: unknown ? 'services-unavailable' : 'not-configured' } as const : {}, voiceover: implemented, preview: implemented, engines, ...defaultEngine ? { defaultEngine } : {}, ...loaded.findings?.length ? { findings: loaded.findings } : {}, actions: { status: implemented, list: true, get: true, start: implemented && configured, cancel: true, quotePreview: implemented, preview: implemented && configured, readPreview: true }, tasks: { idempotency: 'process', limits: ownerOf(document, member).limits } }
|
|
176
|
+
return { document, source: loaded.source, verification: 'configuration-only', status: configured ? 'configured' : unknown ? 'unknown' : 'unavailable', ...!configured ? { reason: unknown ? 'services-unavailable' : 'not-configured' } as const : {}, voiceover: implemented, preview: implemented, engines, ...defaultEngine ? { defaultEngine } : {}, ...loaded.findings?.length ? { findings: loaded.findings } : {}, actions: { status: implemented, list: true, get: true, start: implemented && configured, cancel: true, quotePreview: implemented, preview: implemented && configured, readPreview: true, clone: hasRole(member, 'owner') && Boolean(loaded.speech?.cloneVoice) && engines.some(engine => engine.clone), cloneStatus: hasRole(member, 'owner') && Boolean(loaded.speech?.cloneStatus) && engines.some(engine => engine.clone) }, tasks: { idempotency: 'process', limits: ownerOf(document, member).limits } }
|
|
71
177
|
}),
|
|
72
178
|
catalog: (document, query, member, signal) => work(signal, async signal => {
|
|
73
179
|
if (!validateDocumentVoiceCatalogQuery(query)) throw new RequestError(400, 'voice-catalog-query-invalid')
|
|
74
|
-
|
|
180
|
+
// The voices do not depend on the document's text: only a read pinned to a version is refused when it moves on.
|
|
181
|
+
const loaded = query.source ? await load(document, member, signal, query.source) : await loadLatest(document, member, signal)
|
|
182
|
+
const pinned = () => { signal.throwIfAborted(); if (query.source) current(document, member, loaded.source) }
|
|
75
183
|
const engines = await loaded.speech?.engines() ?? []
|
|
76
|
-
|
|
184
|
+
pinned()
|
|
77
185
|
const preferred = query.engine ?? await loaded.speech?.defaultSynthesisEngine?.()
|
|
78
|
-
|
|
186
|
+
pinned()
|
|
79
187
|
const chosen = preferred ? engines.find(engine => engine.tts && engine.id === speechEngineId(preferred)) : undefined
|
|
80
188
|
const unknown = !loaded.speech && loaded.findings?.some(finding => finding.severity === 'error')
|
|
81
189
|
const catalog = chosen && loaded.speech ? await loaded.speech.voiceCatalog?.(chosen.id, query.lang ?? loaded.lang, signal) ?? { status: 'unavailable' as const, reason: 'unknown' as const, voices: [] } : { status: 'unavailable' as const, reason: unknown ? 'unknown' as const : 'not-configured' as const, voices: [] }
|
|
82
|
-
|
|
190
|
+
pinned()
|
|
83
191
|
return { document, source: loaded.source, engines, catalog, ...catalog.status === 'available' && chosen ? { engine: chosen.id } : {}, ...loaded.findings?.length ? { findings: loaded.findings } : {} }
|
|
84
192
|
}),
|
|
85
193
|
snapshot: (document, query, member, signal) => ownerOf(document, member).snapshot(query, execution(document, member), signal),
|
|
@@ -111,5 +219,5 @@ export function createDocumentVoiceAuthoring({ editor, services, revision }: Doc
|
|
|
111
219
|
},
|
|
112
220
|
readPreview: async (document, id, member) => ownerOf(document, member).readPreview(id),
|
|
113
221
|
}
|
|
114
|
-
return { service, routes: createVoiceoverRoutes(service), async close() { closed = true; for (const operation of pending) operation.controller.abort(); await Promise.allSettled([...owners.values()].map(owner => owner.close())); await Promise.allSettled([...pending].map(operation => operation.finished)); owners.clear() } }
|
|
222
|
+
return { service, routes: createVoiceoverRoutes(service), busy: () => pending.size > 0 || [...owners.values()].some(owner => owner.busy()), async close() { closed = true; for (const { prepared } of clones.values()) prepared.close(); for (const operation of pending) operation.controller.abort(); await Promise.allSettled([...owners.values()].map(owner => owner.close())); await Promise.allSettled([...pending].map(operation => operation.finished)); owners.clear() } }
|
|
115
223
|
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// Runs git commands for the workspace service, in a small process of its own: starting a child process from the
|
|
2
|
+
// service (a large process) held its event loop for tens of milliseconds each time. Messages: { id, args, cwd, env,
|
|
3
|
+
// input?, maxBuffer } in, { id, code, stdout, stderr } out. It ends when the service does.
|
|
4
|
+
import { execFile } from 'node:child_process'
|
|
5
|
+
|
|
6
|
+
process.on('message', ({ id, args, cwd, env, input, maxBuffer }) => {
|
|
7
|
+
let inputError
|
|
8
|
+
const child = execFile('git', args, { cwd, env, encoding: 'buffer', maxBuffer }, (error, stdout, stderr) => {
|
|
9
|
+
const code = inputError ? 1 : !error ? 0 : typeof error.code === 'number' ? error.code : 1
|
|
10
|
+
process.send?.({ id, code, stdout, stderr: stderr.toString('utf8') + (inputError?.message ?? '') })
|
|
11
|
+
})
|
|
12
|
+
if (input !== undefined) {
|
|
13
|
+
if (child.stdin) {
|
|
14
|
+
child.stdin.on('error', (error) => { inputError = error; child.kill() })
|
|
15
|
+
child.stdin.end(Buffer.from(input))
|
|
16
|
+
} else { inputError = new Error('git stdin is unavailable'); child.kill() }
|
|
17
|
+
}
|
|
18
|
+
})
|
|
19
|
+
process.on('disconnect', () => process.exit(0))
|
package/src/node/git.ts
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
|
-
import { execFile, execFileSync } from 'node:child_process'
|
|
2
|
-
import {
|
|
1
|
+
import { execFile, execFileSync, fork } from 'node:child_process'
|
|
2
|
+
import type { ChildProcess } from 'node:child_process'
|
|
3
|
+
import { fileURLToPath } from 'node:url'
|
|
4
|
+
import { existsSync, readdirSync, realpathSync } from 'node:fs'
|
|
5
|
+
import { appendFile, mkdir, readFile } from 'node:fs/promises'
|
|
6
|
+
import { dirname, join, resolve } from 'node:path'
|
|
7
|
+
import { promisify } from 'node:util'
|
|
3
8
|
import { gitConfigArgs, gitEnvironment } from '@lincyaw/kernel'
|
|
4
9
|
|
|
5
10
|
export interface GitResult {
|
|
@@ -8,14 +13,125 @@ export interface GitResult {
|
|
|
8
13
|
stderr: string
|
|
9
14
|
}
|
|
10
15
|
|
|
16
|
+
/**
|
|
17
|
+
* Starting a child process from a large process holds its event loop for milliseconds, tens of them on a busy machine.
|
|
18
|
+
* The git commands are therefore started by a small process of their own (`git-runner.mjs`, started with the first
|
|
19
|
+
* command); this process only exchanges messages with it. Should the runner be unavailable, commands start here, one
|
|
20
|
+
* per turn of the event loop, so that several never add up to one long pause.
|
|
21
|
+
*/
|
|
22
|
+
interface RunRequest { args: string[], cwd: string, env: Record<string, string>, input?: Uint8Array, maxBuffer: number }
|
|
23
|
+
interface Runner { child: ChildProcess, pending: Map<number, { request: RunRequest, done(result: GitResult): void }> }
|
|
24
|
+
let runner: Runner | undefined, nextRequest = 0
|
|
25
|
+
const RUNNER = fileURLToPath(new URL('./git-runner.mjs', import.meta.url))
|
|
26
|
+
|
|
27
|
+
function startRunner(): Runner | undefined {
|
|
28
|
+
if (runner) return runner
|
|
29
|
+
let child: ChildProcess
|
|
30
|
+
try { child = fork(RUNNER, [], { serialization: 'advanced', stdio: ['ignore', 'ignore', 'inherit', 'ipc'], execArgv: [] }) }
|
|
31
|
+
catch { return undefined }
|
|
32
|
+
const started: Runner = { child, pending: new Map() }
|
|
33
|
+
const idle = () => { if (!started.pending.size) { child.unref(); (child.channel as { unref?(): void } | undefined)?.unref?.() } }
|
|
34
|
+
child.on('message', (message: { id: number, code: number, stdout: Uint8Array, stderr: string }) => {
|
|
35
|
+
const waiting = started.pending.get(message.id)
|
|
36
|
+
started.pending.delete(message.id)
|
|
37
|
+
idle()
|
|
38
|
+
waiting?.done({ code: message.code, stdout: Buffer.from(message.stdout.buffer, message.stdout.byteOffset, message.stdout.byteLength), stderr: message.stderr })
|
|
39
|
+
})
|
|
40
|
+
const lost = () => {
|
|
41
|
+
if (runner === started) runner = undefined
|
|
42
|
+
// Commands the runner took but did not answer run here instead.
|
|
43
|
+
for (const { request, done } of started.pending.values()) void runHere(request).then(done)
|
|
44
|
+
started.pending.clear()
|
|
45
|
+
}
|
|
46
|
+
child.on('exit', lost)
|
|
47
|
+
child.on('error', lost)
|
|
48
|
+
idle()
|
|
49
|
+
return runner = started
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
let lastSpawn: Promise<void> = Promise.resolve()
|
|
53
|
+
function spawnTurn(): Promise<void> {
|
|
54
|
+
const turn = lastSpawn.then(() => new Promise<void>(next => setImmediate(next)))
|
|
55
|
+
lastSpawn = turn
|
|
56
|
+
return turn
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function runHere(request: RunRequest): Promise<GitResult> {
|
|
60
|
+
await spawnTurn()
|
|
61
|
+
return new Promise((done) => {
|
|
62
|
+
let inputError: Error | undefined
|
|
63
|
+
const child = execFile('git', request.args, { cwd: request.cwd, encoding: 'buffer', maxBuffer: request.maxBuffer, env: request.env }, (error, stdout, stderr) => {
|
|
64
|
+
const code = inputError ? 1 : !error ? 0 : typeof error.code === 'number' ? error.code : 1
|
|
65
|
+
done({ code, stdout, stderr: stderr.toString('utf8') + (inputError?.message ?? '') })
|
|
66
|
+
})
|
|
67
|
+
if (request.input !== undefined) {
|
|
68
|
+
if (child.stdin) {
|
|
69
|
+
child.stdin.on('error', error => { inputError = error; child.kill() })
|
|
70
|
+
child.stdin.end(request.input)
|
|
71
|
+
} else { inputError = new Error('git stdin is unavailable'); child.kill() }
|
|
72
|
+
}
|
|
73
|
+
})
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function runGit(request: RunRequest): Promise<GitResult> {
|
|
77
|
+
const started = startRunner()
|
|
78
|
+
if (!started?.child.connected) return runHere(request)
|
|
79
|
+
return new Promise((done) => {
|
|
80
|
+
const id = nextRequest++
|
|
81
|
+
started.pending.set(id, { request, done })
|
|
82
|
+
started.child.ref(); (started.child.channel as { ref?(): void } | undefined)?.ref?.()
|
|
83
|
+
try { started.child.send({ id, ...request }) }
|
|
84
|
+
catch { started.pending.delete(id); void runHere(request).then(done) }
|
|
85
|
+
})
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Repositories inside the work tree are left out of Presmium's own histories: git cannot add one without a commit
|
|
90
|
+
* (it stops the whole `git add`), and one with a commit would enter only as a reference to it. `ls-files --others`
|
|
91
|
+
* names each as its directory with a trailing slash, and nothing else that way.
|
|
92
|
+
*/
|
|
93
|
+
export const nestedRepositories = (untracked: string): string[] => untracked.split('\0').filter(path => path.endsWith('/'))
|
|
94
|
+
const reported = new Set<string>()
|
|
95
|
+
/** Pathspecs (git's literal-pathspec setting off) that add `paths` except the nested repositories. */
|
|
96
|
+
export function addPathspecs(paths: string[], nested: string[]): string[] {
|
|
97
|
+
for (const path of nested) if (!reported.has(path)) { reported.add(path); console.warn(`presmium: ${path} is a git repository of its own; its files are not part of the workspace history`) }
|
|
98
|
+
return [...paths.map(path => `:(literal)${path}`), ...nested.map(path => `:(exclude,literal)${path}`)]
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* DeltaBox keeps a session's state in `.deltabox/` and `.deltabox-lite-state/` of the project root it is given; an
|
|
103
|
+
* earlier Presmium gave it the author's workspace, so these may be left there. A live session may still use them,
|
|
104
|
+
* so they are not removed: the project's local `info/exclude` (never a file the author commits) leaves them out.
|
|
105
|
+
* Answers the lines it added.
|
|
106
|
+
*/
|
|
107
|
+
export async function excludeDeltaboxState(root: string): Promise<string[]> {
|
|
108
|
+
const present = ['.deltabox', '.deltabox-lite-state'].filter(name => existsSync(join(root, name)))
|
|
109
|
+
if (!present.length || !Git.isRepository(root)) return []
|
|
110
|
+
const git = new Git(root)
|
|
111
|
+
const prefix = (await git.output(['rev-parse', '--show-prefix'])).trim()
|
|
112
|
+
const file = resolve(root, (await git.output(['rev-parse', '--git-path', 'info/exclude'])).trim())
|
|
113
|
+
const existing = await readFile(file, 'utf8').catch((error: NodeJS.ErrnoException) => { if (error.code === 'ENOENT') return ''; throw error })
|
|
114
|
+
const lines = present.map(name => `/${prefix}${name}/`).filter(line => !existing.split(/\r?\n/).includes(line))
|
|
115
|
+
if (!lines.length) return lines
|
|
116
|
+
await mkdir(dirname(file), { recursive: true })
|
|
117
|
+
await appendFile(file, `${existing && !existing.endsWith('\n') ? '\n' : ''}${lines.join('\n')}\n`)
|
|
118
|
+
return lines
|
|
119
|
+
}
|
|
120
|
+
|
|
11
121
|
export class Git {
|
|
12
122
|
readonly root: string
|
|
13
123
|
readonly top: string
|
|
124
|
+
readonly localHistory: boolean
|
|
125
|
+
readonly #environment: Record<string, string>
|
|
126
|
+
/** The process environment for git, made once: copying `process.env` on every call held the event loop. */
|
|
127
|
+
#base?: Record<string, string>
|
|
14
128
|
#queue: Promise<unknown> = Promise.resolve()
|
|
15
129
|
|
|
16
|
-
constructor(root: string) {
|
|
130
|
+
constructor(root: string, history?: { directory: string, top: string }) {
|
|
17
131
|
this.root = root
|
|
18
|
-
this.
|
|
132
|
+
this.localHistory = Boolean(history)
|
|
133
|
+
this.#environment = history ? { GIT_DIR: history.directory, GIT_WORK_TREE: history.top } : {}
|
|
134
|
+
this.top = history ? realpathSync(history.top) : realpathSync(execFileSync('git', [...gitConfigArgs(), 'rev-parse', '--show-toplevel'], { cwd: root, encoding: 'utf8', env: gitEnvironment(process.env) }).trim())
|
|
19
135
|
}
|
|
20
136
|
|
|
21
137
|
static isRepository(root: string): boolean {
|
|
@@ -26,25 +142,21 @@ export class Git {
|
|
|
26
142
|
}
|
|
27
143
|
}
|
|
28
144
|
|
|
145
|
+
/** Prepare a new, empty authoring workspace; existing content needs its own real history baseline. */
|
|
146
|
+
static async initialize(root: string): Promise<void> {
|
|
147
|
+
if (Git.isRepository(root) || existsSync(join(root, '.git'))) return
|
|
148
|
+
if (readdirSync(root).some(name => name !== '.DS_Store')) return
|
|
149
|
+
await promisify(execFile)('git', [...gitConfigArgs(), 'init', '--quiet', '--initial-branch=main'], { cwd: root, env: gitEnvironment(process.env) })
|
|
150
|
+
const git = new Git(root)
|
|
151
|
+
const tree = await git.run(['hash-object', '-w', '-t', 'tree', '--stdin'], {}, new Uint8Array())
|
|
152
|
+
if (tree.code !== 0) throw new Error(tree.stderr)
|
|
153
|
+
const commit = (await git.output(['-c', 'user.name=Presmium', '-c', 'user.email=workspace@presmium.invalid', 'commit-tree', tree.stdout.toString('utf8').trim(), '-m', 'Initialize workspace history'])).trim()
|
|
154
|
+
const ref = (await git.output(['symbolic-ref', 'HEAD'])).trim()
|
|
155
|
+
await git.output(['update-ref', ref, commit, '0'.repeat(commit.length)])
|
|
156
|
+
}
|
|
157
|
+
|
|
29
158
|
run(command: string[], env: Record<string, string> = {}, input?: Uint8Array): Promise<GitResult> {
|
|
30
|
-
return
|
|
31
|
-
let inputError: Error | undefined
|
|
32
|
-
const child = execFile('git', [...gitConfigArgs(), ...command], {
|
|
33
|
-
cwd: this.root,
|
|
34
|
-
encoding: 'buffer',
|
|
35
|
-
maxBuffer: 1 << 30,
|
|
36
|
-
env: { ...gitEnvironment(process.env), ...env },
|
|
37
|
-
}, (error, stdout, stderr) => {
|
|
38
|
-
const code = inputError ? 1 : !error ? 0 : typeof error.code === 'number' ? error.code : 1
|
|
39
|
-
done({ code, stdout, stderr: stderr.toString('utf8') + (inputError?.message ?? '') })
|
|
40
|
-
})
|
|
41
|
-
if (input !== undefined) {
|
|
42
|
-
if (child.stdin) {
|
|
43
|
-
child.stdin.on('error', error => { inputError = error; child.kill() })
|
|
44
|
-
child.stdin.end(input)
|
|
45
|
-
} else { inputError = new Error('git stdin is unavailable'); child.kill() }
|
|
46
|
-
}
|
|
47
|
-
})
|
|
159
|
+
return runGit({ args: [...gitConfigArgs(), ...command], cwd: this.root, maxBuffer: 1 << 30, env: { ...this.#base ??= { ...gitEnvironment(process.env), ...this.#environment }, ...env }, ...input !== undefined ? { input } : {} })
|
|
48
160
|
}
|
|
49
161
|
|
|
50
162
|
/** The command's output; throws when it fails. */
|
|
@@ -60,6 +172,13 @@ export class Git {
|
|
|
60
172
|
return { ok: result.code === 0, output: result.code === 0 ? result.stdout.toString('utf8') : `${result.stderr}${result.stdout.toString('utf8')}` }
|
|
61
173
|
}
|
|
62
174
|
|
|
175
|
+
/** `git add -A` of `paths` (literal) that skips nested repositories. */
|
|
176
|
+
async addAll(paths: string[], env: Record<string, string> = {}): Promise<void> {
|
|
177
|
+
const literal = { ...env, GIT_LITERAL_PATHSPECS: '1' }
|
|
178
|
+
const nested = nestedRepositories(await this.output(['ls-files', '--others', '--exclude-standard', '-z', '--', ...paths], literal))
|
|
179
|
+
await this.output(['add', '-A', '--', ...addPathspecs(paths, nested)], { ...env, GIT_LITERAL_PATHSPECS: '0' })
|
|
180
|
+
}
|
|
181
|
+
|
|
63
182
|
exclusive<T>(work: () => Promise<T>): Promise<T> {
|
|
64
183
|
const next = this.#queue.then(work, work)
|
|
65
184
|
this.#queue = next.catch(() => undefined)
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** Admission is frozen atomically with the idle check, before releasing the workspace host. */
|
|
2
|
+
export function createHostActivity() {
|
|
3
|
+
let active = 0, stopped = false
|
|
4
|
+
return {
|
|
5
|
+
begin(): (() => void) | undefined {
|
|
6
|
+
if (stopped) return undefined
|
|
7
|
+
active++
|
|
8
|
+
let finished = false
|
|
9
|
+
return () => { if (!finished) { finished = true; active-- } }
|
|
10
|
+
},
|
|
11
|
+
quiesce(): boolean {
|
|
12
|
+
if (active) return false
|
|
13
|
+
stopped = true
|
|
14
|
+
return true
|
|
15
|
+
},
|
|
16
|
+
}
|
|
17
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { isRecord, jsonResponse, problemResponse } from '@lincyaw/kernel'
|
|
2
|
+
import type { Route } from '@lincyaw/kernel'
|
|
3
|
+
import { compareServiceVersion, SERVICE_VERSION } from '@lincyaw/kernel/node'
|
|
4
|
+
import type { DocumentLocks } from './locks.ts'
|
|
5
|
+
import type { Jobs } from './jobs.ts'
|
|
6
|
+
|
|
7
|
+
/** Only the launcher's authenticated owner route can release this host for a newer runtime. */
|
|
8
|
+
export function hostUpgradeRoute(locks: DocumentLocks, jobs: Jobs, quiesce: () => boolean, upgrade: (version: string) => void): Route {
|
|
9
|
+
let upgrading = false
|
|
10
|
+
return { role: 'owner', maxBody: 1024, async handle(request) {
|
|
11
|
+
if (request.method !== 'POST') return problemResponse(405, 'POST')
|
|
12
|
+
const body: unknown = await request.json().catch(() => undefined)
|
|
13
|
+
if (!isRecord(body) || body.pid !== process.pid || typeof body.version !== 'string' || Object.keys(body).some(key => !['pid', 'version'].includes(key))) return problemResponse(400, 'host-upgrade-invalid')
|
|
14
|
+
try {
|
|
15
|
+
if (compareServiceVersion({ version: SERVICE_VERSION }, body.version) >= 0) return problemResponse(409, 'host-upgrade-version')
|
|
16
|
+
} catch { return problemResponse(400, 'host-upgrade-invalid') }
|
|
17
|
+
if (upgrading) return jsonResponse({ upgrading: true })
|
|
18
|
+
if (jobs.list().some(job => job.state === 'running' || job.state === 'queued')) return problemResponse(409, 'host-upgrade-busy')
|
|
19
|
+
const release = locks.claim('', 'upgrade')
|
|
20
|
+
if (!release) return problemResponse(409, 'host-upgrade-busy')
|
|
21
|
+
if (!quiesce()) { release(); return problemResponse(409, 'host-upgrade-busy') }
|
|
22
|
+
// Hold the workspace-wide write lock until the host closes. The response must leave before closing HTTP.
|
|
23
|
+
upgrading = true
|
|
24
|
+
const version = body.version
|
|
25
|
+
setTimeout(() => upgrade(version), 0)
|
|
26
|
+
return jsonResponse({ upgrading: true })
|
|
27
|
+
} }
|
|
28
|
+
}
|