@lincyaw/workspace 1.0.0-rc.43 → 1.0.0-rc.45
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 +5 -5
- package/src/node/authoring-clients.ts +27 -4
- package/src/node/document-audio.ts +28 -25
- package/src/node/document-voice.ts +62 -5
- package/src/node/review/agent-session-reviews.ts +68 -19
- package/src/node/review/agent-workspace.ts +5 -4
- package/src/node/review/git-review.ts +37 -9
- package/src/node/review/workspace-review.ts +87 -0
- package/src/node/serve.ts +5 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lincyaw/workspace",
|
|
3
|
-
"version": "1.0.0-rc.
|
|
3
|
+
"version": "1.0.0-rc.45",
|
|
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/
|
|
38
|
-
"@lincyaw/
|
|
39
|
-
"@lincyaw/server": "1.0.0-rc.
|
|
37
|
+
"@lincyaw/kernel": "1.0.0-rc.45",
|
|
38
|
+
"@lincyaw/compiler": "1.0.0-rc.45",
|
|
39
|
+
"@lincyaw/server": "1.0.0-rc.45"
|
|
40
40
|
},
|
|
41
41
|
"devDependencies": {
|
|
42
42
|
"@types/mime-types": "^3.0.1",
|
|
43
|
-
"@lincyaw/mcp": "1.0.0-rc.
|
|
43
|
+
"@lincyaw/mcp": "1.0.0-rc.45"
|
|
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: ['
|
|
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
|
|
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 =
|
|
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
|
}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { randomUUID } from 'node:crypto'
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
2
2
|
import { existsSync } from 'node:fs'
|
|
3
3
|
import { join } from 'node:path'
|
|
4
4
|
import { errorMessage, pushStream } from '@lincyaw/kernel'
|
|
5
|
-
import type { DocumentFiles, Logger, Member, ReviewEnd, ReviewSnapshot, ReviewUpdate } from '@lincyaw/kernel'
|
|
5
|
+
import type { DocumentFiles, Logger, Member, ReviewChange, ReviewEnd, ReviewSnapshot, ReviewUpdate } from '@lincyaw/kernel'
|
|
6
6
|
import { trailers } from '../../domain/commit-message.ts'
|
|
7
7
|
import type { WorkspaceConfig } from '../config.ts'
|
|
8
8
|
import { listDocuments } from '../config.ts'
|
|
@@ -149,12 +149,47 @@ export class AgentSessionReviews {
|
|
|
149
149
|
})
|
|
150
150
|
}
|
|
151
151
|
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
152
|
+
snapshot(): Promise<ReviewSnapshot | undefined> {
|
|
153
|
+
return this.#serial(async () => this.#open && await this.#snapshotOf(this.#open))
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
inspect(): Promise<{ snapshot: string, review: ReviewSnapshot } | undefined> {
|
|
157
|
+
return this.#serial(async () => { if (!this.#open) return; const { snapshot, review } = await this.#inspect(this.#open); return { snapshot, review } })
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
async #inspect(open: OpenReview) {
|
|
161
|
+
const { tree, version, changes } = await open.review.inspect()
|
|
162
|
+
const review = await this.#snapshotOf(open, changes)
|
|
163
|
+
review.steps = review.steps.map(step => ({ ...step, changes: step.changes.map(({ diff: _diff, ...change }) => change) }))
|
|
164
|
+
return { tree, review, snapshot: createHash('sha256').update(JSON.stringify([version, review])).digest('hex') }
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async #expected(open: OpenReview, expected: string | undefined, signal?: AbortSignal): Promise<void> {
|
|
168
|
+
signal?.throwIfAborted()
|
|
169
|
+
if (expected === undefined) return
|
|
170
|
+
if (open.running) throw new RequestError(409, 'workspace-review-running')
|
|
171
|
+
if ((await this.#inspect(open)).snapshot !== expected) throw new RequestError(409, 'workspace-review-changed')
|
|
172
|
+
signal?.throwIfAborted()
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
check(expected: string): Promise<void> {
|
|
176
|
+
return this.#serial(async () => this.#expected(this.#requireOpen('', expected), expected))
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
readDiff(expected: string, path: string, step?: string): Promise<ReviewChange | undefined> {
|
|
180
|
+
return this.#serial(async () => {
|
|
181
|
+
const open = this.#requireOpen('', expected)
|
|
182
|
+
const current = await this.#inspect(open)
|
|
183
|
+
if (current.snapshot !== expected) throw new RequestError(409, 'workspace-review-changed')
|
|
184
|
+
const files = step === undefined ? current.review.changes : current.review.steps.find(value => value.id === step)?.changes
|
|
185
|
+
if (!files?.some(file => file.path === path)) return
|
|
186
|
+
const value = await open.review.diffFile(path, step)
|
|
187
|
+
if ((await this.#inspect(open)).snapshot !== expected) throw new RequestError(409, 'workspace-review-changed')
|
|
188
|
+
return value
|
|
189
|
+
})
|
|
155
190
|
}
|
|
156
191
|
|
|
157
|
-
async #snapshotOf(open: OpenReview): Promise<ReviewSnapshot> {
|
|
192
|
+
async #snapshotOf(open: OpenReview, changes?: ReviewChange[]): Promise<ReviewSnapshot> {
|
|
158
193
|
return {
|
|
159
194
|
id: open.review.task,
|
|
160
195
|
document: open.document,
|
|
@@ -166,7 +201,7 @@ export class AgentSessionReviews {
|
|
|
166
201
|
mode: reviewSettings(this.#options.config).mode,
|
|
167
202
|
opened: open.opened,
|
|
168
203
|
steps: [...open.review.steps()],
|
|
169
|
-
changes: await open.review.diff(),
|
|
204
|
+
changes: changes ?? await open.review.diff(),
|
|
170
205
|
}
|
|
171
206
|
}
|
|
172
207
|
|
|
@@ -267,10 +302,11 @@ export class AgentSessionReviews {
|
|
|
267
302
|
})
|
|
268
303
|
}
|
|
269
304
|
|
|
270
|
-
accept(document: string, body: { reject?: string[], message?: string }): Promise<ReviewEnd> {
|
|
305
|
+
accept(document: string, body: { reject?: string[], message?: string, expected?: string }, signal?: AbortSignal): Promise<ReviewEnd> {
|
|
271
306
|
return this.#serial(async () => {
|
|
272
|
-
const open = this.#requireOpen(document)
|
|
273
|
-
|
|
307
|
+
const open = this.#requireOpen(document, body.expected)
|
|
308
|
+
await this.#expected(open, body.expected, signal)
|
|
309
|
+
try { return await this.#accept(open, body.reject ?? [], body.message, signal, body.expected) }
|
|
274
310
|
catch (error) {
|
|
275
311
|
if (error instanceof RequestError && error.message === 'agent-source-changed') {
|
|
276
312
|
await open.review.close()
|
|
@@ -282,10 +318,13 @@ export class AgentSessionReviews {
|
|
|
282
318
|
})
|
|
283
319
|
}
|
|
284
320
|
|
|
285
|
-
async #accept(open: OpenReview, reject: string[], message: string | undefined): Promise<ReviewEnd> {
|
|
321
|
+
async #accept(open: OpenReview, reject: string[], message: string | undefined, signal?: AbortSignal, expected?: string): Promise<ReviewEnd> {
|
|
322
|
+
const captured = await this.#inspect(open)
|
|
323
|
+
if (expected !== undefined && captured.snapshot !== expected) throw new RequestError(409, 'workspace-review-changed')
|
|
286
324
|
const rejected = new Set(reject)
|
|
287
|
-
for (const change of
|
|
288
|
-
const files =
|
|
325
|
+
for (const change of captured.review.changes) if (isInGitDir(change.path)) rejected.add(change.path)
|
|
326
|
+
const files = captured.review.changes.filter(change => !rejected.has(change.path)).map(change => change.path)
|
|
327
|
+
const material = await open.review.readTree(captured.tree, files)
|
|
289
328
|
if (!open.workspace) throw new RequestError(409, 'agent-workspace-unavailable')
|
|
290
329
|
const lang = listDocuments(this.#options.config).find(doc => doc.dir === open.document)?.lang
|
|
291
330
|
const steps = open.review.steps().map(step => `- ${step.label}`).slice(0, 20)
|
|
@@ -294,7 +333,14 @@ export class AgentSessionReviews {
|
|
|
294
333
|
let revision
|
|
295
334
|
try {
|
|
296
335
|
revision = await this.#options.revisions.transaction(async () => {
|
|
297
|
-
|
|
336
|
+
signal?.throwIfAborted()
|
|
337
|
+
if ((await this.#inspect(open)).snapshot !== captured.snapshot) throw new RequestError(409, 'workspace-review-changed')
|
|
338
|
+
const selected = await open.review.prepareAccept([...rejected])
|
|
339
|
+
if (JSON.stringify(selected) !== JSON.stringify(files)) throw new RequestError(409, 'workspace-review-changed')
|
|
340
|
+
try { await open.review.assertTree(captured.tree, [...rejected]) }
|
|
341
|
+
catch { throw new RequestError(409, 'workspace-review-changed') }
|
|
342
|
+
signal?.throwIfAborted()
|
|
343
|
+
const prepared = open.workspace!.prepare(files, material)
|
|
298
344
|
try {
|
|
299
345
|
open.workspace!.write(prepared.changes)
|
|
300
346
|
return await this.#options.revisions.commitWhileLocked({ paths: files, summary: message?.trim() || commitSummary(files, lang), body: steps.join('\n'), origin: { kind: 'agent', task: open.review.task, member: open.member }, trailers: [[AGENT_SESSION_TRAILER, open.session], [TURN_TRAILER, `${open.turns.from}-${open.turns.to}`]] })
|
|
@@ -308,9 +354,10 @@ export class AgentSessionReviews {
|
|
|
308
354
|
return ended
|
|
309
355
|
}
|
|
310
356
|
|
|
311
|
-
reject(document: string, body: { paths?: string[] }): Promise<ReviewUpdate> {
|
|
357
|
+
reject(document: string, body: { paths?: string[], expected?: string }, signal?: AbortSignal): Promise<ReviewUpdate> {
|
|
312
358
|
return this.#serial(async () => {
|
|
313
|
-
const open = this.#requireOpen(document)
|
|
359
|
+
const open = this.#requireOpen(document, body.expected)
|
|
360
|
+
await this.#expected(open, body.expected, signal)
|
|
314
361
|
if (body.paths) {
|
|
315
362
|
await open.review.restoreFiles(body.paths)
|
|
316
363
|
if ((await open.review.diff()).length > 0) return { document, review: await this.#publish(open) }
|
|
@@ -323,9 +370,10 @@ export class AgentSessionReviews {
|
|
|
323
370
|
})
|
|
324
371
|
}
|
|
325
372
|
|
|
326
|
-
restore(document: string, body: { step: string }): Promise<ReviewSnapshot> {
|
|
373
|
+
restore(document: string, body: { step: string, expected?: string }, signal?: AbortSignal): Promise<ReviewSnapshot> {
|
|
327
374
|
return this.#serial(async () => {
|
|
328
|
-
const open = this.#requireOpen(document)
|
|
375
|
+
const open = this.#requireOpen(document, body.expected)
|
|
376
|
+
await this.#expected(open, body.expected, signal)
|
|
329
377
|
try {
|
|
330
378
|
await open.review.restoreTo!(body.step)
|
|
331
379
|
} catch (error) {
|
|
@@ -364,8 +412,9 @@ export class AgentSessionReviews {
|
|
|
364
412
|
return open
|
|
365
413
|
}
|
|
366
414
|
|
|
367
|
-
#requireOpen(document: string): OpenReview {
|
|
415
|
+
#requireOpen(document: string, expected?: string): OpenReview {
|
|
368
416
|
const open = this.#open
|
|
417
|
+
if (!open && expected !== undefined) throw new RequestError(409, 'workspace-review-changed')
|
|
369
418
|
if (!open) throw new RequestError(404, `no review of ${document || '.'} is open`)
|
|
370
419
|
return open
|
|
371
420
|
}
|
|
@@ -85,16 +85,17 @@ export class AgentWorkspace {
|
|
|
85
85
|
}
|
|
86
86
|
|
|
87
87
|
/** Caller holds the original workspace's mutation lock and history transaction. */
|
|
88
|
-
prepare(paths: string[]): { changes: DocumentFileChange[], restore: DocumentFileChange[] } {
|
|
88
|
+
prepare(paths: string[], fixed?: DocumentFileChange[]): { changes: DocumentFileChange[], restore: DocumentFileChange[] } {
|
|
89
|
+
if (fixed && (fixed.length !== paths.length || fixed.some((change, index) => change.path !== paths[index]))) throw new RequestError(409, 'workspace-review-changed')
|
|
89
90
|
const conflicts = paths.filter(path => !same(stamp(join(this.#config.root, path)), this.record.base[path]))
|
|
90
91
|
if (conflicts.length) throw new RequestError(409, 'agent-source-changed', { paths: conflicts, next: 'The author changed these files. Read the current author files again and retry your change. Nothing was published.' })
|
|
91
92
|
const changes: DocumentFileChange[] = [], restore: DocumentFileChange[] = []
|
|
92
|
-
for (const path of paths) {
|
|
93
|
+
for (const [index, path] of paths.entries()) {
|
|
93
94
|
if (!path || path.split('/').some(part => !part || part === '.' || part === '..' || part === '.git') || path.startsWith('.presmium/agent-workspaces/')) throw new RequestError(403, 'agent-source-path-invalid')
|
|
94
|
-
const before = stamp(join(this.#config.root, path)), after = stamp(join(this.root, path))
|
|
95
|
+
const before = stamp(join(this.#config.root, path)), after = fixed ? undefined : stamp(join(this.root, path))
|
|
95
96
|
const read = (root: string, value: FileStamp | undefined): DocumentFileChange => !value ? { path, remove: true }
|
|
96
97
|
: value.link ? { path, link: readlinkSync(join(root, path)) } : { path, content: readFileSync(join(root, path)), ...value.executable ? { executable: true } : {} }
|
|
97
|
-
const change = read(this.root, after)
|
|
98
|
+
const change = fixed?.[index] ?? read(this.root, after)
|
|
98
99
|
if ('content' in change) validateDocumentSource(path, Buffer.from(change.content).toString('utf8'), before && !before.link ? readFileSync(join(this.#config.root, path)) : undefined)
|
|
99
100
|
changes.push(change); restore.push(read(this.#config.root, before))
|
|
100
101
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { execFile } from 'node:child_process'
|
|
2
|
+
import { createHash } from 'node:crypto'
|
|
2
3
|
import { mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmdirSync, rmSync, writeFileSync } from 'node:fs'
|
|
3
4
|
import { tmpdir } from 'node:os'
|
|
4
5
|
import { dirname, join, relative, resolve, sep } from 'node:path'
|
|
@@ -12,6 +13,10 @@ import type { AgentSessionRecord, ReviewRecord } from './record.ts'
|
|
|
12
13
|
|
|
13
14
|
export interface GitReview extends ChangeReview {
|
|
14
15
|
readonly task: string
|
|
16
|
+
inspect(details?: boolean): Promise<{ tree: string, version: string, changes: ReviewChange[] }>
|
|
17
|
+
diffFile(path: string, step?: string): Promise<ReviewChange | undefined>
|
|
18
|
+
readTree(tree: string, paths: string[]): Promise<DocumentFileChange[]>
|
|
19
|
+
assertTree(tree: string, except: string[]): Promise<void>
|
|
15
20
|
restoreFiles(paths: string[]): Promise<void>
|
|
16
21
|
noteSession(session: Omit<AgentSessionRecord, 'checkpoints' | 'steps'>): void
|
|
17
22
|
suspend(): void
|
|
@@ -137,13 +142,14 @@ class ReviewTrees {
|
|
|
137
142
|
.map(this.fromGit).sort((a, b) => a.localeCompare(b))
|
|
138
143
|
}
|
|
139
144
|
|
|
140
|
-
async compare(from: string, to: string): Promise<ReviewChange[]> {
|
|
145
|
+
async compare(from: string, to: string, details = true, only?: string): Promise<ReviewChange[]> {
|
|
141
146
|
if (from === to) return []
|
|
142
|
-
const
|
|
147
|
+
const paths = only === undefined ? [] : ['--', this.toGit(only)]
|
|
148
|
+
const status = (await this.#text([...DIFF, '--name-status', '-z', from, to, ...paths])).split('\0').filter(Boolean)
|
|
143
149
|
const kinds = new Map<string, ReviewChangeKind>()
|
|
144
150
|
for (let i = 0; i + 1 < status.length; i += 2) kinds.set(status[i + 1]!, status[i]!.startsWith('A') ? 'added' : status[i]!.startsWith('D') ? 'deleted' : 'modified')
|
|
145
151
|
const counts = new Map<string, { added: number, removed: number, binary: boolean }>()
|
|
146
|
-
for (const entry of (await this.#text([...DIFF, '--numstat', '-z', from, to])).split('\0').filter(Boolean)) {
|
|
152
|
+
for (const entry of (await this.#text([...DIFF, '--numstat', '-z', from, to, ...paths])).split('\0').filter(Boolean)) {
|
|
147
153
|
const [added = '0', removed = '0', ...path] = entry.split('\t')
|
|
148
154
|
const binary = added === '-'
|
|
149
155
|
counts.set(path.join('\t'), { added: binary ? 0 : Number(added), removed: binary ? 0 : Number(removed), binary })
|
|
@@ -152,7 +158,7 @@ class ReviewTrees {
|
|
|
152
158
|
for (const [path, kind] of kinds) {
|
|
153
159
|
const count = counts.get(path) ?? { added: 0, removed: 0, binary: false }
|
|
154
160
|
const change: ReviewChange = { path: this.fromGit(path), kind, ...count }
|
|
155
|
-
if (!count.binary && changes.filter(c => c.diff).length < MAX_DIFFS) {
|
|
161
|
+
if (details && !count.binary && changes.filter(c => c.diff).length < MAX_DIFFS) {
|
|
156
162
|
const diff = await this.#text([...DIFF, from, to, '--', path])
|
|
157
163
|
if (diff.length <= MAX_DIFF) change.diff = diff
|
|
158
164
|
}
|
|
@@ -190,10 +196,11 @@ class ReviewTrees {
|
|
|
190
196
|
}
|
|
191
197
|
}
|
|
192
198
|
|
|
193
|
-
async
|
|
199
|
+
async read(tree: string, paths: string[]): Promise<DocumentFileChange[]> {
|
|
194
200
|
const entries = new Map<string, { mode: string, oid: string }>()
|
|
195
201
|
for (const entry of (await this.#text(['ls-tree', '-r', '-z', tree, '--', ...paths])).split('\0').filter(Boolean)) {
|
|
196
|
-
const
|
|
202
|
+
const separator = entry.indexOf('\t')
|
|
203
|
+
const meta = entry.slice(0, separator), path = entry.slice(separator + 1)
|
|
197
204
|
const [mode = '', , oid = ''] = meta.split(' ')
|
|
198
205
|
entries.set(path, { mode, oid })
|
|
199
206
|
}
|
|
@@ -208,7 +215,11 @@ class ReviewTrees {
|
|
|
208
215
|
const blob = await this.#git(['cat-file', 'blob', entry.oid])
|
|
209
216
|
changes.push(entry.mode === '120000' ? { path: this.fromGit(path), link: blob.toString('utf8') } : { path: this.fromGit(path), content: blob, ...entry.mode === '100755' ? { executable: true } : {} })
|
|
210
217
|
}
|
|
211
|
-
|
|
218
|
+
return changes
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
async #write(tree: string, paths: string[]): Promise<void> {
|
|
222
|
+
await this.#files!.write(await this.read(tree, paths))
|
|
212
223
|
}
|
|
213
224
|
|
|
214
225
|
async reset(tree: string): Promise<void> {
|
|
@@ -351,6 +362,12 @@ function createGitReview(open: { scopeDir: string, trees: ReviewTrees, restoreGi
|
|
|
351
362
|
await trees.restore(snapshot, [...rejected])
|
|
352
363
|
return changes.filter(path => !rejected.has(path))
|
|
353
364
|
}
|
|
365
|
+
const inspect = async (details = false) => {
|
|
366
|
+
live()
|
|
367
|
+
restoreGitDir()
|
|
368
|
+
const tree = await trees.tree()
|
|
369
|
+
return { tree, version: createHash('sha256').update(JSON.stringify([snapshot, tree, checkpoints])).digest('hex'), changes: await trees.compare(snapshot, tree, details) }
|
|
370
|
+
}
|
|
354
371
|
|
|
355
372
|
return {
|
|
356
373
|
root: scopeDir,
|
|
@@ -374,10 +391,21 @@ function createGitReview(open: { scopeDir: string, trees: ReviewTrees, restoreGi
|
|
|
374
391
|
return step
|
|
375
392
|
},
|
|
376
393
|
steps: () => steps,
|
|
377
|
-
|
|
394
|
+
inspect,
|
|
395
|
+
readTree: (tree, paths) => { live(); return trees.read(tree, paths.map(trees.toGit)) },
|
|
396
|
+
async assertTree(tree, except) {
|
|
397
|
+
live()
|
|
398
|
+
if ((await trees.changedPaths(tree, await trees.tree())).some(path => !except.includes(path))) throw new Error('workspace-review-changed')
|
|
399
|
+
},
|
|
400
|
+
diff: async () => (await inspect(true)).changes,
|
|
401
|
+
async diffFile(path, step) {
|
|
378
402
|
live()
|
|
379
403
|
restoreGitDir()
|
|
380
|
-
|
|
404
|
+
const at = step === undefined ? -1 : steps.findIndex(value => value.id === step)
|
|
405
|
+
if (step !== undefined && at < 0) return
|
|
406
|
+
const from = at < 0 ? snapshot : checkpoints[at]!, to = at < 0 ? await trees.tree() : checkpoints[at + 1]!
|
|
407
|
+
if (!(await trees.compare(from, to, false, path)).some(change => change.path === path)) return
|
|
408
|
+
return (await trees.compare(from, to, true, path)).find(change => change.path === path)
|
|
381
409
|
},
|
|
382
410
|
async restoreTo(stepId) {
|
|
383
411
|
live()
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
import { hasRole, WORKSPACE_REVIEW_FRAGMENT_CHARS, WORKSPACE_REVIEW_MAX_REQUEST_CHARS, WORKSPACE_REVIEW_MAX_RESPONSE_CHARS } from '@lincyaw/kernel'
|
|
3
|
+
import type { Member, WorkspaceReview, WorkspaceReviewAnswer, WorkspaceReviewChange } from '@lincyaw/kernel'
|
|
4
|
+
import { validateWorkspaceReviewChange, validateWorkspaceReviewQuery } from '@lincyaw/kernel/node'
|
|
5
|
+
import { RequestError } from '../errors.ts'
|
|
6
|
+
import type { AgentSessionReviews } from './agent-session-reviews.ts'
|
|
7
|
+
|
|
8
|
+
const size = (value: unknown) => JSON.stringify(value).length
|
|
9
|
+
const authorize = (member: Member) => { if (!hasRole(member, 'owner')) throw new RequestError(403, 'workspace-review-permission-denied') }
|
|
10
|
+
const budget = (value: unknown) => { if (size(value) > WORKSPACE_REVIEW_MAX_REQUEST_CHARS) throw new RequestError(413, 'workspace-review-request-too-large') }
|
|
11
|
+
const fits = (value: unknown) => size(value) <= WORKSPACE_REVIEW_MAX_RESPONSE_CHARS
|
|
12
|
+
|
|
13
|
+
/** Bounded publication interface over the same review queue, candidate trees and writer used by Web. */
|
|
14
|
+
export function createWorkspaceReview(reviews: AgentSessionReviews): WorkspaceReview {
|
|
15
|
+
const inspect = async (change: WorkspaceReviewChange, member: Member) => {
|
|
16
|
+
authorize(member); budget(change)
|
|
17
|
+
if (!validateWorkspaceReviewChange(change)) throw new RequestError(400, 'workspace-review-change-invalid')
|
|
18
|
+
const state = await reviews.inspect()
|
|
19
|
+
if (!state || state.snapshot !== change.snapshot) throw new RequestError(409, 'workspace-review-changed')
|
|
20
|
+
if (state.review.running) throw new RequestError(409, 'workspace-review-running')
|
|
21
|
+
if (change.action === 'restore') {
|
|
22
|
+
if (!state.review.steps.some(step => step.id === change.step)) throw new RequestError(404, 'workspace-review-step-not-found')
|
|
23
|
+
} else {
|
|
24
|
+
const selected = change.action === 'accept' ? change.reject : change.paths
|
|
25
|
+
if (selected?.some(path => !state.review.changes.some(file => file.path === path))) throw new RequestError(409, 'workspace-review-path-changed')
|
|
26
|
+
}
|
|
27
|
+
return state
|
|
28
|
+
}
|
|
29
|
+
return {
|
|
30
|
+
async read(query, member) {
|
|
31
|
+
authorize(member); budget(query)
|
|
32
|
+
if (!validateWorkspaceReviewQuery(query)) throw new RequestError(400, 'workspace-review-query-invalid')
|
|
33
|
+
const part = query.part ?? 'summary', offset = query.offset ?? 0
|
|
34
|
+
if ((query.path !== undefined || query.step !== undefined) && part !== 'diff' || offset > 0 && !query.snapshot || part === 'summary' && offset !== 0) throw new RequestError(400, 'workspace-review-query-invalid')
|
|
35
|
+
const state = await reviews.inspect()
|
|
36
|
+
if (query.snapshot !== undefined && state?.snapshot !== query.snapshot) throw new RequestError(409, 'workspace-review-changed')
|
|
37
|
+
if (!state) {
|
|
38
|
+
if (part !== 'summary') throw new RequestError(404, 'workspace-review-not-found')
|
|
39
|
+
return { review: null }
|
|
40
|
+
}
|
|
41
|
+
const { review, snapshot } = state
|
|
42
|
+
const answer: WorkspaceReviewAnswer = { review: { id: review.id, document: review.document, running: review.running, mode: review.mode, files: review.changes.length, steps: review.steps.length }, snapshot }
|
|
43
|
+
if (!fits(answer)) throw new RequestError(413, 'workspace-review-response-too-large')
|
|
44
|
+
if (part === 'summary') return answer
|
|
45
|
+
if (part === 'diff') {
|
|
46
|
+
if (!query.path) throw new RequestError(400, 'workspace-review-query-invalid')
|
|
47
|
+
if (query.step && !review.steps.some(step => step.id === query.step)) throw new RequestError(404, 'workspace-review-step-not-found')
|
|
48
|
+
const change = await reviews.readDiff(snapshot, query.path, query.step)
|
|
49
|
+
if (!change) throw new RequestError(404, 'workspace-review-file-not-found')
|
|
50
|
+
if (change.diff === undefined) throw new RequestError(409, 'workspace-review-diff-unavailable')
|
|
51
|
+
const totalChars = change.diff.length
|
|
52
|
+
if (offset > totalChars) throw new RequestError(400, 'workspace-review-query-invalid')
|
|
53
|
+
answer.diff = { path: query.path, ...query.step ? { step: query.step } : {}, text: change.diff.slice(offset, offset + WORKSPACE_REVIEW_FRAGMENT_CHARS), offset, totalChars, sha256: createHash('sha256').update(change.diff).digest('hex') }
|
|
54
|
+
const cursor = () => { if (offset + answer.diff!.text.length < totalChars) answer.nextOffset = offset + answer.diff!.text.length; else delete answer.nextOffset }
|
|
55
|
+
cursor()
|
|
56
|
+
while (!fits(answer) && answer.diff.text.length) { answer.diff.text = answer.diff.text.slice(0, Math.floor(answer.diff.text.length / 2)); cursor() }
|
|
57
|
+
if (!fits(answer) || !answer.diff.text.length && offset < totalChars) throw new RequestError(413, 'workspace-review-response-too-large')
|
|
58
|
+
return answer
|
|
59
|
+
}
|
|
60
|
+
const rows = part === 'files' ? review.changes : review.steps.map(({ changes, ...step }) => ({ ...step, label: step.label.slice(0, 240), ...step.tool ? { tool: step.tool.slice(0, 100) } : {}, files: changes.length }))
|
|
61
|
+
if (offset > rows.length) throw new RequestError(400, 'workspace-review-query-invalid')
|
|
62
|
+
const selected: unknown[] = []
|
|
63
|
+
for (const row of rows.slice(offset, offset + 20)) {
|
|
64
|
+
if (!fits({ ...answer, [part]: [...selected, row], nextOffset: offset + selected.length + 1 })) break
|
|
65
|
+
selected.push(row)
|
|
66
|
+
}
|
|
67
|
+
if (!selected.length && offset < rows.length) throw new RequestError(413, 'workspace-review-response-too-large')
|
|
68
|
+
Object.assign(answer, { [part]: selected }, offset + selected.length < rows.length ? { nextOffset: offset + selected.length } : {})
|
|
69
|
+
return answer
|
|
70
|
+
},
|
|
71
|
+
async check(change, member) { await inspect(change, member); await reviews.check(change.snapshot) },
|
|
72
|
+
async change(change, member, signal) {
|
|
73
|
+
const state = await inspect(change, member)
|
|
74
|
+
signal?.throwIfAborted()
|
|
75
|
+
if (change.action === 'accept') {
|
|
76
|
+
const ended = await reviews.accept(state.review.document, { reject: change.reject, message: change.message, expected: change.snapshot }, signal)
|
|
77
|
+
return { outcome: ended.outcome === 'accepted' ? 'accepted' : 'empty', ...ended.revision ? { revision: ended.revision.id } : {}, files: ended.files.length }
|
|
78
|
+
}
|
|
79
|
+
if (change.action === 'reject') {
|
|
80
|
+
const result = await reviews.reject(state.review.document, { paths: change.paths, expected: change.snapshot }, signal)
|
|
81
|
+
return result.ended ? { outcome: 'rejected', files: result.ended.files.length } : { outcome: 'updated', remainingFiles: result.review?.changes.length ?? 0 }
|
|
82
|
+
}
|
|
83
|
+
const result = await reviews.restore(state.review.document, { step: change.step, expected: change.snapshot }, signal)
|
|
84
|
+
return { outcome: 'restored', remainingFiles: result.changes.length }
|
|
85
|
+
},
|
|
86
|
+
}
|
|
87
|
+
}
|
package/src/node/serve.ts
CHANGED
|
@@ -23,6 +23,7 @@ import { Git } from './git.ts'
|
|
|
23
23
|
import { createJobs, OUTPUTS_PATH } from './jobs.ts'
|
|
24
24
|
import { DocumentLocks } from './locks.ts'
|
|
25
25
|
import { AgentSessionReviews } from './review/agent-session-reviews.ts'
|
|
26
|
+
import { createWorkspaceReview } from './review/workspace-review.ts'
|
|
26
27
|
import { createTaskReviewService } from './review/task-reviews.ts'
|
|
27
28
|
import { Revisions } from './revisions.ts'
|
|
28
29
|
import { WORKSPACE_ID, authorizeWorkspaceRoutes, workspaceRoutes, workspaceRoutesPlugin } from './routes.ts'
|
|
@@ -116,6 +117,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
|
|
|
116
117
|
let history: WorkspaceHistory | undefined
|
|
117
118
|
let documentEditor: DocumentEditor | undefined
|
|
118
119
|
let documentHistory: ReturnType<typeof createDocumentHistory> | undefined
|
|
120
|
+
let workspaceReview: ReturnType<typeof createWorkspaceReview> | undefined
|
|
119
121
|
let projectAuthoring: ReturnType<typeof createProjectAuthoring> | undefined
|
|
120
122
|
let authoringClients: ReturnType<typeof createAuthoringClients> | undefined
|
|
121
123
|
let transcriptions: ReturnType<typeof createDocumentTranscriptions> | undefined
|
|
@@ -272,6 +274,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
|
|
|
272
274
|
get imageAuthoring() { return imageAuthoring?.service },
|
|
273
275
|
get voiceAuthoring() { return voiceAuthoring?.service },
|
|
274
276
|
speechSettings,
|
|
277
|
+
get workspaceReview() { return workspaceReview },
|
|
275
278
|
get transcriptions() { return transcriptions },
|
|
276
279
|
get transcriptionAdoption() { return transcriptionAdoption?.service },
|
|
277
280
|
get capture() { return capture?.service },
|
|
@@ -384,9 +387,10 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
|
|
|
384
387
|
voiceAuthoring = createDocumentVoiceAuthoring({ editor, services: authoringServices, revision: document => { const latest = compileSessions.get(document)?.latest; return latest ? irRevision(latest.doc) : undefined } })
|
|
385
388
|
workbench = createWorkbenchBackend({ root, compileSessionOf, serverHost, voices: voiceAuthoring.service, diagnostics: running.diagnostics, url: () => options.publicUrl ? new URL(options.publicUrl).origin : running.url, basePath, preview, log, warmSite: dir => site?.warm(dir) ?? Promise.resolve(), viewerPage: (dir, wait) => site?.app(dir, wait) ?? Promise.resolve(undefined) })
|
|
386
389
|
history = openHistory()
|
|
390
|
+
workspaceReview = history && createWorkspaceReview(history.agentSessionReviews)
|
|
387
391
|
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' })
|
|
388
392
|
projectAuthoring = createProjectAuthoring({ config, documentEditor, operations: history?.operations, revisions: history?.revisions, git: history?.git })
|
|
389
|
-
authoringClients = createAuthoringClients(editor)
|
|
393
|
+
authoringClients = createAuthoringClients(editor, { reviewRequired: config.settings['presmium.assistant']?.review === 'required' })
|
|
390
394
|
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) })
|
|
391
395
|
transcriptions = createDocumentTranscriptions({ root, editor, services: authoringServices })
|
|
392
396
|
transcriptionAdoption = createTranscriptionAdoption({ documentEditor, transcriptions })
|