@lincyaw/workspace 1.0.0-rc.42 → 1.0.0-rc.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lincyaw/workspace",
3
- "version": "1.0.0-rc.42",
3
+ "version": "1.0.0-rc.44",
4
4
  "description": "Presmium's workspace service (presmium serve): documents, their history, reviews and the workspace site",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -34,12 +34,12 @@
34
34
  "mime-types": "3.0.2",
35
35
  "playwright-chromium": "1.64.1",
36
36
  "yaml": "^2.9.1",
37
- "@lincyaw/compiler": "1.0.0-rc.42",
38
- "@lincyaw/kernel": "1.0.0-rc.42",
39
- "@lincyaw/server": "1.0.0-rc.42"
37
+ "@lincyaw/compiler": "1.0.0-rc.44",
38
+ "@lincyaw/server": "1.0.0-rc.44",
39
+ "@lincyaw/kernel": "1.0.0-rc.44"
40
40
  },
41
41
  "devDependencies": {
42
42
  "@types/mime-types": "^3.0.1",
43
- "@lincyaw/mcp": "1.0.0-rc.42"
43
+ "@lincyaw/mcp": "1.0.0-rc.44"
44
44
  }
45
45
  }
@@ -1,5 +1,5 @@
1
1
  import { randomBytes, randomUUID, createHash } from 'node:crypto'
2
- import { AUTHORING_CLIENT_ACK_MAX_BYTES, AUTHORING_CLIENT_MAX_CLIENTS, AUTHORING_CLIENT_MAX_REQUESTS, AUTHORING_CLIENT_MAX_REQUEST_CHARS, AUTHORING_CLIENT_MAX_RESPONSE_CHARS, AUTHORING_CLIENT_REQUEST_TIMEOUT_MS, authoringClientResultFits, DOCUMENT_ENTRY, fnv1a64, hasRole, isRecord, jsonResponse, problemResponse, pushStream, sseResponse } from '@lincyaw/kernel'
2
+ import { AUTHORING_CLIENT_ACK_MAX_BYTES, AUTHORING_CLIENT_MAX_CLIENTS, AUTHORING_CLIENT_MAX_REQUESTS, AUTHORING_CLIENT_MAX_REQUEST_CHARS, AUTHORING_CLIENT_MAX_RESPONSE_CHARS, AUTHORING_CLIENT_REQUEST_TIMEOUT_MS, authoringClientActionChangesSource, authoringClientResultFits, DOCUMENT_ENTRY, fnv1a64, hasRole, isRecord, jsonResponse, problemResponse, pushStream, sseResponse } from '@lincyaw/kernel'
3
3
  import type { AuthoringClientAcknowledgement, AuthoringClientConnection, AuthoringClientDescriptor, AuthoringClientEvent, AuthoringClientLease, AuthoringClientOpen, AuthoringClientReport, AuthoringClientRequest, AuthoringClientRequestResult, AuthoringClients, CanonicalSource, Member, PushStream, Route } from '@lincyaw/kernel'
4
4
  import { validateAuthoringClientAcknowledgement, validateAuthoringClientLease, validateAuthoringClientOpen, validateAuthoringClientQuery, validateAuthoringClientReport, validateAuthoringClientRequest, validateAuthoringClientRequestQuery } from '@lincyaw/kernel/node'
5
5
  import { readAuthoringDocument } from './document-editor.ts'
@@ -15,7 +15,8 @@ const digest = (value: unknown) => createHash('sha256').update(JSON.stringify(va
15
15
  const terminal = (pending: Pending) => !['sent', 'executing'].includes(pending.value.state)
16
16
 
17
17
  /** Ephemeral live-client control. It owns no document writer, compilation or durable task ledger. */
18
- export function createAuthoringClients(editor: SourceEditor) {
18
+ export function createAuthoringClients(editor: SourceEditor, options: { reviewRequired?: boolean } = {}) {
19
+ const requiresReview = (type: import('@lincyaw/kernel').AuthoringClientActionType) => options.reviewRequired && authoringClientActionChangesSource(type) && type !== 'source.flush'
19
20
  const clients = new Map<string, Client>(), requests = new Map<string, Pending>()
20
21
  let closed = false
21
22
  const clientKey = (member: string, clientId: string) => JSON.stringify([member, clientId])
@@ -69,9 +70,15 @@ export function createAuthoringClients(editor: SourceEditor) {
69
70
  if (!validateAuthoringClientQuery(query)) throw new RequestError(400, 'client-query-invalid')
70
71
  const all = [...clients.values()].filter(client => client.member === member.id && client.value.document === document && (!query.clientId || client.value.clientId === query.clientId)
71
72
  && (!query.after || client.value.clientId > query.after)).sort((a, b) => a.value.clientId.localeCompare(b.value.clientId))
72
- const answer = { document, clients: [] as AuthoringClientDescriptor[], unavailable: ['recording', 'new-comment-restore', 'active-comment-discard', 'timing-drafts', 'recording-drafts', 'review', 'open-document'] }
73
+ const answer = { document, clients: [] as AuthoringClientDescriptor[], unavailable: ['new-comment-restore', 'active-comment-discard', 'timing-drafts', 'recording-range-drafts', 'review', 'open-document', ...options.reviewRequired ? ['source-writes-require-review'] : []] }
73
74
  for (const client of all) {
74
75
  const row = structuredClone(client.value)
76
+ row.snapshot.actions = row.snapshot.actions.filter(type => !requiresReview(type))
77
+ const pending = [...requests.values()].find(pending => pending.member === member.id && pending.value.document === document && pending.value.clientId === row.clientId && pending.value.epoch === row.epoch && !terminal(pending))
78
+ if (pending) {
79
+ row.pendingRequest = { requestId: pending.value.requestId, action: pending.value.action, ...pending.value.cancellationRequested ? { cancellationRequested: true } : {} }
80
+ row.snapshot.actions = []
81
+ }
75
82
  if (size({ ...answer, clients: [...answer.clients, row], nextAfter: row.clientId }) > AUTHORING_CLIENT_MAX_RESPONSE_CHARS) break
76
83
  answer.clients.push(row)
77
84
  }
@@ -81,6 +88,7 @@ export function createAuthoringClients(editor: SourceEditor) {
81
88
  async request(document, request, member) {
82
89
  const actual = current(document, member); budget(request)
83
90
  if (!validateAuthoringClientRequest(request)) throw new RequestError(400, 'client-request-invalid')
91
+ if (requiresReview(request.action.type)) throw new RequestError(409, 'authoring-review-required')
84
92
  const key = requestKey(member.id, document, request), signature = digest(request), known = requests.get(key)
85
93
  if (known) { if (known.signature !== signature) throw new RequestError(409, 'client-request-id-reused'); return readResult(known, actual) }
86
94
  const client = clients.get(clientKey(member.id, request.clientId)), state = client?.value
@@ -113,6 +121,21 @@ export function createAuthoringClients(editor: SourceEditor) {
113
121
  try { actual = current(document, member) } catch { /* An old receipt stays readable if the current source is invalid. */ }
114
122
  return readResult(pending, actual)
115
123
  },
124
+ async cancel(document, query, member) {
125
+ if (closed) throw new RequestError(503, 'client-owner-closed')
126
+ if (!hasRole(member, 'editor')) throw new RequestError(403, 'client-permission-denied')
127
+ budget(query)
128
+ if (!validateAuthoringClientRequestQuery(query)) throw new RequestError(400, 'client-request-query-invalid')
129
+ const pending = requests.get(requestKey(member.id, document, query))
130
+ if (!pending) throw new RequestError(404, 'client-request-not-found')
131
+ if (!terminal(pending) && !pending.value.cancellationRequested) {
132
+ pending.value.cancellationRequested = true
133
+ clients.get(clientKey(member.id, query.clientId))?.send?.({ type: 'cancel', requestId: query.requestId, connectionId: pending.value.connectionId })
134
+ }
135
+ let actual: CanonicalSource | undefined
136
+ try { actual = current(document, member) } catch { /* Cancelling the caller's original request does not require a valid new source. */ }
137
+ return readResult(pending, actual)
138
+ },
116
139
  }
117
140
  const register = (document: string, value: AuthoringClientOpen, member: Member): AuthoringClientLease => {
118
141
  const source = current(document, member)
@@ -150,7 +173,7 @@ export function createAuthoringClients(editor: SourceEditor) {
150
173
  if (pending && Date.now() >= Date.parse(pending.value.expiresAt)) finish(pending, 'expired', 'client-request-timeout')
151
174
  if (!pending || terminal(pending) || pending.request.expectedClientState.connectionId !== lease.connectionId) throw new RequestError(409, 'client-request-expired')
152
175
  if (ack.state === 'executing' && pending.value.state !== 'sent' || ack.state === 'done' && pending.value.state !== 'executing') throw new RequestError(409, 'client-ack-state-invalid')
153
- if ((ack.state === 'executing' || ack.state === 'done') && !sameSource(ack.snapshot.source, pending.request.source) && !(ack.state === 'done' && pending.request.action.type === 'source.flush' && ack.snapshot.source.documentId === pending.request.source.documentId)) throw new RequestError(409, 'client-source-changed')
176
+ if ((ack.state === 'executing' || ack.state === 'done') && !sameSource(ack.snapshot.source, pending.request.source) && !(ack.state === 'done' && authoringClientActionChangesSource(pending.request.action.type) && ack.snapshot.source.documentId === pending.request.source.documentId)) throw new RequestError(409, 'client-source-changed')
154
177
  const actual = ack.state === 'executing' || ack.state === 'done' ? current(document, member) : undefined
155
178
  if (ack.state === 'executing' && (ack.snapshot.revision !== pending.request.expectedClientState.revision || !actual || !sameSource(actual, pending.request.source))) throw new RequestError(409, 'client-state-changed')
156
179
  if (ack.state === 'done' && (!actual || !sameSource(actual, ack.snapshot.source))) throw new RequestError(409, 'client-source-changed')
@@ -29,6 +29,33 @@ const binding = (current: ReturnType<typeof readAuthoringDocument>): CanonicalSo
29
29
  const titleOf = (name: string) => [...(name.replaceAll('\\', '/').split('/').at(-1) ?? '').replace(/[\u0000-\u001f\u007f-\u009f]/g, '').trim()].slice(0, ASSET_TITLE_MAX_LENGTH).join('')
30
30
  const stamp = (stat: Awaited<ReturnType<Awaited<ReturnType<typeof open>>['stat']>>) => [stat.dev, stat.ino, stat.size, stat.mtimeMs, stat.ctimeMs].join(':')
31
31
 
32
+ /** Scoped bounded audio reads are shared by import, inspection and voice cloning. */
33
+ export async function readDocumentAudioBytes(editor: SourceEditor, ctx: RequestContext, path: string, signal?: AbortSignal, maxBytes = DOCUMENT_AUDIO_MAX_BYTES): Promise<Uint8Array> {
34
+ signal?.throwIfAborted()
35
+ const file = editor.readableFile({ document: ctx.document, home: false }, path, ctx.member)
36
+ const handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK).catch(error => {
37
+ if (error.code === 'ELOOP') throw new RequestError(403, 'audio-file-path')
38
+ if (error.code === 'ENOENT' || error.code === 'ENOTDIR') throw new RequestError(404, 'audio-file-missing')
39
+ throw error
40
+ })
41
+ try {
42
+ const before = await handle.stat(), named = await lstat(editor.readableFile({ document: ctx.document, home: false }, path, ctx.member))
43
+ if (!before.isFile() || before.dev !== named.dev || before.ino !== named.ino) throw new RequestError(403, 'audio-file-path')
44
+ if (!before.size || before.size > maxBytes) throw new RequestError(413, 'production.asset-size')
45
+ const bytes = new Uint8Array(before.size + 1); let length = 0
46
+ while (length < bytes.length) {
47
+ signal?.throwIfAborted()
48
+ const read = await handle.read(bytes, length, bytes.length - length, length)
49
+ if (!read.bytesRead) break
50
+ length += read.bytesRead
51
+ }
52
+ const after = await handle.stat(), current = await lstat(editor.readableFile({ document: ctx.document, home: false }, path, ctx.member))
53
+ if (length !== before.size || stamp(before) !== stamp(after) || after.dev !== current.dev || after.ino !== current.ino) throw new RequestError(409, 'audio-file-changed')
54
+ signal?.throwIfAborted()
55
+ return bytes.slice(0, length)
56
+ } finally { await handle.close() }
57
+ }
58
+
32
59
  /** Owns the canonical transaction and receipts; plugin services only inspect actual media. */
33
60
  export function createDocumentAudioAuthoring({ root, editor, revisions, audio, services, reviewRequired = false }: DocumentAudioAuthoringOptions): { service: DocumentAudioAuthoring, routes: Record<string, Route>, close(): Promise<void> } {
34
61
  const receipts = new Map<string, Receipt>(), imports = new Map<string, { signature: string, source: CanonicalSource, promise: Promise<VerifiedDocumentAudioImport> }>(), operations = new Set<Operation>()
@@ -64,31 +91,7 @@ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, s
64
91
  editor.assertEditable(scopeOf(document), path, member)
65
92
  if (path.split('/').some(part => part.startsWith('.'))) throw new RequestError(403, 'audio-file-path')
66
93
  }
67
- const reader = async (ctx: RequestContext, path: string, signal?: AbortSignal): Promise<Uint8Array> => {
68
- signal?.throwIfAborted()
69
- const file = editor.readableFile(scopeOf(ctx.document), path, ctx.member)
70
- const handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK).catch(error => {
71
- if (error.code === 'ELOOP') throw new RequestError(403, 'audio-file-path')
72
- if (error.code === 'ENOENT' || error.code === 'ENOTDIR') throw new RequestError(404, 'audio-file-missing')
73
- throw error
74
- })
75
- try {
76
- const before = await handle.stat(), named = await lstat(editor.readableFile(scopeOf(ctx.document), path, ctx.member))
77
- if (!before.isFile() || before.dev !== named.dev || before.ino !== named.ino) throw new RequestError(403, 'audio-file-path')
78
- if (!before.size || before.size > DOCUMENT_AUDIO_MAX_BYTES) throw new RequestError(413, 'production.asset-size')
79
- const bytes = new Uint8Array(before.size + 1); let length = 0
80
- while (length < bytes.length) {
81
- signal?.throwIfAborted()
82
- const read = await handle.read(bytes, length, bytes.length - length, length)
83
- if (!read.bytesRead) break
84
- length += read.bytesRead
85
- }
86
- const after = await handle.stat(), current = await lstat(editor.readableFile(scopeOf(ctx.document), path, ctx.member))
87
- if (length !== before.size || stamp(before) !== stamp(after) || after.dev !== current.dev || after.ino !== current.ino) throw new RequestError(409, 'audio-file-changed')
88
- signal?.throwIfAborted()
89
- return bytes.slice(0, length)
90
- } finally { await handle.close() }
91
- }
94
+ const reader = (ctx: RequestContext, path: string, signal?: AbortSignal) => readDocumentAudioBytes(editor, ctx, path, signal)
92
95
  const pathOf = (ctx: RequestContext, asset: Asset) => {
93
96
  const file = productionAssetFile(join(root, ctx.document), asset.location)
94
97
  if (!file) throw new RequestError(422, 'production.asset-path')
@@ -1,6 +1,8 @@
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, 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 { readDocumentAudioBytes } from './document-audio.ts'
4
6
  import { readAuthoringDocument } from './document-editor.ts'
5
7
  import { RequestError } from './errors.ts'
6
8
  import type { SourceEditor } from './source-editor.ts'
@@ -16,6 +18,7 @@ const same = (a: CanonicalSource, b: CanonicalSource) => a.documentId === b.docu
16
18
  export function createDocumentVoiceAuthoring({ editor, services, revision }: DocumentVoiceAuthoringOptions) {
17
19
  const pending = new Set<{ controller: AbortController, finished: Promise<unknown> }>()
18
20
  const owners = new Map<string, ReturnType<typeof createVoiceoverOwner>>()
21
+ const clones = new Set<PreparedVoiceClone>()
19
22
  let closed = false
20
23
  const authorize = (document: string, member: Member) => {
21
24
  if (!hasRole(member, 'editor')) throw new RequestError(403, 'voice-authoring-permission-denied')
@@ -61,13 +64,67 @@ export function createDocumentVoiceAuthoring({ editor, services, revision }: Doc
61
64
  catch { return 'unknown' }
62
65
  }
63
66
  const service: DocumentVoiceAuthoring = {
67
+ prepareClone: (document, value, member, signal) => work(signal, async signal => {
68
+ if (!hasRole(member, 'owner')) throw new RequestError(403, 'voice-clone-permission-denied')
69
+ if (!validateDocumentVoiceClone(value)) throw new RequestError(400, 'voice-clone-invalid')
70
+ if (clones.size >= 4) throw new RequestError(503, 'voice-authoring-busy')
71
+ const request = structuredClone(value), loaded = await load(document, member, signal, request.source)
72
+ const speech = loaded.speech, engine = request.engine ?? await speech?.defaultSynthesisEngine?.()
73
+ const mime = (path: string) => {
74
+ if (path.split(/[\\/]/).some(part => part.startsWith('.'))) throw new RequestError(403, 'audio-file-path')
75
+ 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' }
76
+ const type = types[extname(path).toLowerCase()]
77
+ if (!type) throw new RequestError(422, 'voice-clone-audio-type')
78
+ editor.assertEditable({ document, home: false }, path, member)
79
+ return type
80
+ }
81
+ const sampleType = mime(request.sample), statementType = mime(request.consent.statement)
82
+ const [sampleBytes, statementBytes] = await Promise.all([request.sample, request.consent.statement].map(path => readDocumentAudioBytes(editor, { document, member, rest: '' }, path, signal, VOICE_CLONE_MAX_AUDIO_BYTES)))
83
+ current(document, member, loaded.source); signal.throwIfAborted()
84
+ if (!speech?.cloneVoice || !engine || !(await speech.engines()).some(info => info.id === speechEngineId(engine) && info.clone)) throw new RequestError(409, 'voice-clone-unavailable')
85
+ current(document, member, loaded.source); signal.throwIfAborted()
86
+ // Several readers may finish concurrently; the retained byte budget is checked again before retaining blobs.
87
+ if (clones.size >= 4) throw new RequestError(503, 'voice-authoring-busy')
88
+ let sample: Blob | undefined = new Blob([sampleBytes! as Uint8Array<ArrayBuffer>], { type: sampleType })
89
+ let statement: Blob | undefined = new Blob([statementBytes! as Uint8Array<ArrayBuffer>], { type: statementType })
90
+ let started: ReturnType<NonNullable<SpeechService['cloneVoice']>> | undefined
91
+ let expired = false
92
+ const prepared: PreparedVoiceClone = { engine: speechEngineId(engine), voice: request.voice,
93
+ start: startSignal => {
94
+ if (started) return started
95
+ if (expired || !sample || !statement) return Promise.reject(new RequestError(409, 'voice-clone-expired'))
96
+ clearTimeout(timer)
97
+ const exactSample = sample, exactStatement = statement
98
+ started = work(startSignal, async ownedSignal => {
99
+ current(document, member, loaded.source); ownedSignal.throwIfAborted()
100
+ return speech.cloneVoice!({ engine, voice: request.voice, sample: exactSample,
101
+ ...request.lang ? { lang: request.lang } : {}, ...request.text ? { text: request.text } : {},
102
+ consent: { speaker: request.consent.speaker, scope: request.consent.scope, statement: exactStatement } }, ownedSignal)
103
+ }).finally(() => prepared.close())
104
+ return started
105
+ },
106
+ close: () => { expired = true; clearTimeout(timer); sample = undefined; statement = undefined; clones.delete(prepared) },
107
+ }
108
+ const timer = setTimeout(() => prepared.close(), 90000)
109
+ timer.unref()
110
+ clones.add(prepared)
111
+ return prepared
112
+ }),
113
+ cloneStatus: (document, query, member, signal) => work(signal, async signal => {
114
+ if (!hasRole(member, 'owner')) throw new RequestError(403, 'voice-clone-permission-denied')
115
+ if (!validateDocumentVoiceCloneQuery(query)) throw new RequestError(400, 'voice-clone-invalid')
116
+ const loaded = await load(document, member, signal), speech = loaded.speech, engine = query.engine ?? await speech?.defaultSynthesisEngine?.()
117
+ if (!speech?.cloneStatus || !engine || !(await speech.engines()).some(info => info.id === speechEngineId(engine) && info.clone)) throw new RequestError(409, 'voice-clone-unavailable')
118
+ current(document, member, loaded.source); signal.throwIfAborted()
119
+ return speech.cloneStatus(engine, query.voice, signal)
120
+ }),
64
121
  capabilities: (document, member, signal) => work(signal, async signal => {
65
122
  const loaded = await load(document, member, signal)
66
123
  const [engines, defaultEngine] = await Promise.all([loaded.speech?.engines() ?? [], loaded.speech?.defaultSynthesisEngine?.()])
67
124
  signal.throwIfAborted(); current(document, member, loaded.source)
68
125
  const configured = engines.some(engine => engine.tts), unknown = !loaded.speech && loaded.findings?.some(finding => finding.severity === 'error')
69
126
  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 } }
127
+ 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
128
  }),
72
129
  catalog: (document, query, member, signal) => work(signal, async signal => {
73
130
  if (!validateDocumentVoiceCatalogQuery(query)) throw new RequestError(400, 'voice-catalog-query-invalid')
@@ -111,5 +168,5 @@ export function createDocumentVoiceAuthoring({ editor, services, revision }: Doc
111
168
  },
112
169
  readPreview: async (document, id, member) => ownerOf(document, member).readPreview(id),
113
170
  }
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() } }
171
+ return { service, routes: createVoiceoverRoutes(service), async close() { closed = true; for (const prepared of clones) 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
172
  }
package/src/node/serve.ts CHANGED
@@ -9,7 +9,7 @@ import { join, relative } from 'node:path'
9
9
  import { Compiler, operatorDir as resolveOperatorDir, pluginLogger, runBlock, workspacePlugins } from '@lincyaw/compiler'
10
10
  import type { Compilation, CompilerOptions } from '@lincyaw/compiler'
11
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
+ import { irRevision, OperatorSpeechSettings, serveStateDir } from '@lincyaw/kernel/node'
13
13
  import { speechSettingsRoute } from './speech-settings.ts'
14
14
  import type { ApprovalKind, CanonicalSource, ChangeReviewService, Finding, IRDocument, Logger, ProductionAudioAuthoring, ServiceToken, SiteSpec, SpeechService } from '@lincyaw/kernel'
15
15
  import { serverConfigKey, servedDocument, startServer } from '@lincyaw/server'
@@ -91,6 +91,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
91
91
  if (env.PRESMIUM_AGENT_CANDIDATE === '1') config.settings['presmium.assistant'] = { ...config.settings['presmium.assistant'], review: 'auto' }
92
92
  const { root } = config
93
93
  const operatorDirectory = resolveOperatorDir(root, options.operatorDir ?? env.PRESMIUM_OPERATOR_DIR)
94
+ const speechSettings = new OperatorSpeechSettings(operatorDirectory, name => env[name])
94
95
  const stateDir = makeStateDir(root, env)
95
96
  const docs = () => listDocuments(config)
96
97
  const compileSessions = new Map<string, CompileSession>()
@@ -170,7 +171,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
170
171
  services: [...serverServices, ...workspaceServices],
171
172
  bundled: options.bundled,
172
173
  operatorDir: operatorDirectory,
173
- secret: operatorSpeechSecrets(operatorDirectory, name => env[name]),
174
+ secret: speechSettings.secret,
174
175
  })
175
176
 
176
177
  // Coalesce only in-flight discovery. A later read reassembles actual services and problems;
@@ -270,6 +271,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
270
271
  get audioAuthoring() { return audioAuthoring?.service },
271
272
  get imageAuthoring() { return imageAuthoring?.service },
272
273
  get voiceAuthoring() { return voiceAuthoring?.service },
274
+ speechSettings,
273
275
  get transcriptions() { return transcriptions },
274
276
  get transcriptionAdoption() { return transcriptionAdoption?.service },
275
277
  get capture() { return capture?.service },
@@ -384,14 +386,14 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
384
386
  history = openHistory()
385
387
  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' })
386
388
  projectAuthoring = createProjectAuthoring({ config, documentEditor, operations: history?.operations, revisions: history?.revisions, git: history?.git })
387
- authoringClients = createAuthoringClients(editor)
389
+ authoringClients = createAuthoringClients(editor, { reviewRequired: config.settings['presmium.assistant']?.review === 'required' })
388
390
  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) })
389
391
  transcriptions = createDocumentTranscriptions({ root, editor, services: authoringServices })
390
392
  transcriptionAdoption = createTranscriptionAdoption({ documentEditor, transcriptions })
391
393
  audioAuthoring = createDocumentAudioAuthoring({ root, editor, revisions: history?.revisions, services: authoringServices, reviewRequired: config.settings['presmium.assistant']?.review === 'required' })
392
394
  imageAuthoring = createDocumentImageAuthoring({ root, editor, revisions: history?.revisions, reviewRequired: config.settings['presmium.assistant']?.review === 'required' })
393
395
  const routeOptions = {
394
- speechSettings: speechSettingsRoute(operatorDirectory, name => env[name]),
396
+ speechSettings: speechSettingsRoute(speechSettings),
395
397
  config,
396
398
  editor,
397
399
  documentEditor,
@@ -1,18 +1,16 @@
1
- import { isRecord, jsonResponse, problemResponse } from '@lincyaw/kernel'
2
- import type { Route, SpeechSettingsChange } from '@lincyaw/kernel'
3
- import { OperatorSpeechSettings, SpeechSettingsError } from '@lincyaw/kernel/node'
1
+ import { jsonResponse, problemResponse } from '@lincyaw/kernel'
2
+ import type { Route, SpeechSettings } from '@lincyaw/kernel'
3
+ import { SpeechSettingsError, validateSpeechSettingsChange } from '@lincyaw/kernel/node'
4
4
 
5
5
  /** Global operator route: works before opening a document and never returns credential values. */
6
- export function speechSettingsRoute(directory: string, fallback: (name: string) => string | undefined): Route {
7
- const settings = new OperatorSpeechSettings(directory, fallback)
6
+ export function speechSettingsRoute(settings: SpeechSettings): Route {
8
7
  return { role: 'owner', maxBody: 16384, handle: async request => {
9
8
  try {
10
9
  if (request.method === 'GET') return jsonResponse(settings.read(), 200, { 'cache-control': 'no-store' })
11
10
  if (request.method !== 'POST') return problemResponse(405, 'GET or POST')
12
11
  const body: unknown = await request.json().catch(() => undefined)
13
- if (!isRecord(body) || typeof body.revision !== 'string' || !['save', 'clear'].includes(String(body.action)) || Object.keys(body).some(key => !['action', 'revision', 'apiKey', 'appId'].includes(key))
14
- || body.action === 'save' && (body.apiKey !== undefined && typeof body.apiKey !== 'string' || body.appId !== undefined && typeof body.appId !== 'string')) return problemResponse(400, 'speech-settings-invalid')
15
- return jsonResponse(await settings.change(body as unknown as SpeechSettingsChange), 200, { 'cache-control': 'no-store' })
12
+ if (!validateSpeechSettingsChange(body)) return problemResponse(400, 'speech-settings-invalid')
13
+ return jsonResponse(await settings.change(body), 200, { 'cache-control': 'no-store' })
16
14
  } catch (error) {
17
15
  const code = error instanceof SpeechSettingsError ? error.code : 'speech-settings-unavailable'
18
16
  return problemResponse(code === 'speech-settings-invalid' ? 400 : code === 'speech-settings-conflict' || code === 'speech-settings-busy' ? 409 : 503, code)