@lincyaw/workspace 1.0.0-rc.8 → 1.0.0-rc.81
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 +7 -5
- package/src/node/authoring-clients.ts +73 -20
- package/src/node/authoring-windows.ts +165 -0
- package/src/node/build.ts +54 -24
- package/src/node/capture.ts +356 -0
- package/src/node/config.ts +1 -0
- package/src/node/document-audio.ts +60 -41
- package/src/node/document-authoring.ts +7 -1
- package/src/node/document-images.ts +20 -10
- package/src/node/document-voice.ts +100 -6
- package/src/node/locks.ts +12 -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/projects.ts +18 -3
- package/src/node/review/agent-session-reviews.ts +167 -60
- package/src/node/review/agent-workspace.ts +107 -0
- package/src/node/review/git-review.ts +41 -11
- package/src/node/review/record.ts +4 -1
- package/src/node/review/routes.ts +7 -0
- package/src/node/review/workspace-review.ts +87 -0
- package/src/node/revision-files.ts +54 -0
- package/src/node/revisions.ts +217 -56
- package/src/node/routes.ts +29 -57
- package/src/node/serve.ts +167 -42
- package/src/node/site.ts +1 -1
- package/src/node/source-editor.ts +35 -19
- package/src/node/speech-settings.ts +6 -8
- package/src/node/templates.ts +2 -2
- package/src/node/workbench-api.ts +14 -3
- package/src/node/workspace-changes.ts +130 -0
- package/src/node/workspace-source.ts +133 -0
- package/src/node/writer.ts +3 -3
|
@@ -1,20 +1,19 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto'
|
|
2
|
-
import { lstatSync,
|
|
2
|
+
import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, readdirSync, realpathSync } from 'node:fs'
|
|
3
3
|
import { join } from 'node:path'
|
|
4
4
|
import { WORKSPACE_CONFIG } from '@lincyaw/compiler'
|
|
5
|
-
import { DOCUMENT_ENTRY, validateDocument } from '@lincyaw/kernel'
|
|
5
|
+
import { DOCUMENT_ENTRY, SOURCE_MAX_BYTES, SOURCE_MAX_FILES, validateDocument } from '@lincyaw/kernel'
|
|
6
6
|
import type { ConflictAnswer, DocumentFileChange, FilesAnswer, Member, Revision, SavedAnswer, SourceAnswer, SourceFile, SourceTransactionAnswer, SourceTransactionChange } from '@lincyaw/kernel'
|
|
7
7
|
import { isWithin } from '../domain/paths.ts'
|
|
8
8
|
import { listDocumentEntries, readDocumentSummary } from './config.ts'
|
|
9
9
|
import type { DocumentEntry, WorkspaceConfig } from './config.ts'
|
|
10
10
|
import { RequestError } from './errors.ts'
|
|
11
|
-
import { lockedError } from './locks.ts'
|
|
12
11
|
import type { DocumentLocks } from './locks.ts'
|
|
13
12
|
import { documentDirOf, FilesError, writeChanges } from './writer.ts'
|
|
14
13
|
import type { DocumentWriter } from './writer.ts'
|
|
15
14
|
|
|
16
|
-
export const MAX_SOURCE =
|
|
17
|
-
export const MAX_SOURCE_CHANGES =
|
|
15
|
+
export const MAX_SOURCE = SOURCE_MAX_BYTES
|
|
16
|
+
export const MAX_SOURCE_CHANGES = SOURCE_MAX_FILES
|
|
18
17
|
const MAX_FILES = 2000
|
|
19
18
|
const HIDDEN_FROM_EDITOR = new Set(['node_modules', 'dist', '.git', '.presmium'])
|
|
20
19
|
const BINARY = /\.(?:png|jpe?g|gif|webp|avif|ico|bmp|pdf|wasm|zip|gz|tgz|bz2|xz|7z|woff2?|ttf|otf|eot|mp3|mp4|m4a|wav|ogg|oga|webm|mov|avi|mkv|bin|so|dylib|dll|exe|pyc|xlsx?|docx?|pptx?|parquet|npy|npz|pkl|db|sqlite)$/i
|
|
@@ -49,6 +48,8 @@ interface Scope {
|
|
|
49
48
|
}
|
|
50
49
|
|
|
51
50
|
export interface SourceTransactionHistory {
|
|
51
|
+
/** Runs on final locked preimages, before any file is created or changed. */
|
|
52
|
+
check?(files: readonly { path: string, before?: Uint8Array }[]): void
|
|
52
53
|
run<T>(work: () => Promise<T>): Promise<T>
|
|
53
54
|
commit(paths: string[], lang: string | undefined): Promise<Revision | undefined>
|
|
54
55
|
}
|
|
@@ -154,9 +155,20 @@ export class SourceEditor {
|
|
|
154
155
|
|
|
155
156
|
#readBytes(scope: Scope, path: string, member: Member, documents?: readonly DocumentEntry[]): Buffer {
|
|
156
157
|
const file = this.#readableFile(scope, path, member, documents)
|
|
157
|
-
const
|
|
158
|
-
|
|
159
|
-
|
|
158
|
+
const before = lstatSync(file)
|
|
159
|
+
const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)
|
|
160
|
+
try {
|
|
161
|
+
const opened = fstatSync(fd)
|
|
162
|
+
if (!opened.isFile() || opened.dev !== before.dev || opened.ino !== before.ino) throw new RequestError(409, 'source-file-changed')
|
|
163
|
+
if (opened.size > MAX_SOURCE) throw new RequestError(413, `${path} is larger than the editor opens (${MAX_SOURCE} bytes)`)
|
|
164
|
+
const bytes = Buffer.alloc(opened.size + 1)
|
|
165
|
+
let length = 0, count = 0
|
|
166
|
+
while (length < bytes.length && (count = readSync(fd, bytes, length, bytes.length - length, null)) > 0) length += count
|
|
167
|
+
const after = fstatSync(fd), current = lstatSync(file)
|
|
168
|
+
if (length !== opened.size || after.size !== opened.size || after.mtimeMs !== opened.mtimeMs || after.ctimeMs !== opened.ctimeMs
|
|
169
|
+
|| current.dev !== opened.dev || current.ino !== opened.ino || realpathSync(file) !== file) throw new RequestError(409, 'source-file-changed')
|
|
170
|
+
return bytes.subarray(0, length)
|
|
171
|
+
} finally { closeSync(fd) }
|
|
160
172
|
}
|
|
161
173
|
|
|
162
174
|
read(scope: Scope, path: string, member: Member): SourceAnswer {
|
|
@@ -178,8 +190,7 @@ export class SourceEditor {
|
|
|
178
190
|
if (BINARY.test(path)) throw new RequestError(415, `${path} is not a text file`)
|
|
179
191
|
const document = this.#documentHolding(path, documents)?.dir
|
|
180
192
|
const scopeDir = document ?? ''
|
|
181
|
-
const release = this.#locks ? this.#locks.
|
|
182
|
-
if (!release) throw lockedError(scopeDir, this.#locks!.holder(scopeDir)!)
|
|
193
|
+
const release = this.#locks ? await this.#locks.acquire(scopeDir, 'editor:create') : () => {}
|
|
183
194
|
try {
|
|
184
195
|
await this.#writer.create(path, Buffer.alloc(0), document === undefined)
|
|
185
196
|
return { path, content: '', version: versionOf('') }
|
|
@@ -227,11 +238,16 @@ export class SourceEditor {
|
|
|
227
238
|
if (bytes > MAX_SOURCE) throw new RequestError(413, `the transaction is larger than the editor saves (${MAX_SOURCE} bytes)`)
|
|
228
239
|
for (const path of paths) if ([...paths].some(other => path !== other && path.startsWith(`${other}/`))) throw new RequestError(400, `a source file cannot also be a parent directory: ${path}`)
|
|
229
240
|
const document = documents[0]
|
|
230
|
-
if (!document || documents.some(found => found?.dir !== document
|
|
231
|
-
|
|
232
|
-
const
|
|
233
|
-
|
|
241
|
+
if ((!document && !(scope.home && member.roles.includes('owner'))) || documents.some(found => found?.dir !== document?.dir)) throw new RequestError(400, 'a source transaction must stay in one document or the owner workspace scope')
|
|
242
|
+
if (!document && changes.some(change => change.path === DOCUMENT_ENTRY || change.path.endsWith(`/${DOCUMENT_ENTRY}`))) throw new RequestError(422, 'create-a-document-with-valid-content')
|
|
243
|
+
const scopeDir = document?.dir ?? ''
|
|
244
|
+
const release = this.#locks ? await this.#locks.acquire(scopeDir, 'editor:transaction') : () => {}
|
|
234
245
|
const work = async (): Promise<SourceTransactionAnswer> => {
|
|
246
|
+
const current = listDocumentEntries(this.#config)
|
|
247
|
+
for (const [index, change] of changes.entries()) {
|
|
248
|
+
this.#assertEditable(scope, change.path, member, current)
|
|
249
|
+
if (this.#documentHolding(change.path, current)?.dir !== documents[index]?.dir) throw new RequestError(409, 'source-scope-changed')
|
|
250
|
+
}
|
|
235
251
|
// Read every preimage before creating directories or writing any file.
|
|
236
252
|
const snapshots = changes.map(change => {
|
|
237
253
|
const written = typeof change.content === 'string' ? Buffer.from(change.content, 'utf8') : Buffer.from(change.content)
|
|
@@ -256,16 +272,17 @@ export class SourceEditor {
|
|
|
256
272
|
return { path: change.path, before: undefined, written, executable: false }
|
|
257
273
|
})
|
|
258
274
|
for (const snapshot of snapshots) if (snapshot.path !== binaryPath) validateDocumentSource(snapshot.path, snapshot.written.toString('utf8'), snapshot.before)
|
|
275
|
+
history?.check?.(snapshots)
|
|
259
276
|
if (dryRun) return { versions: snapshots.map(snapshot => ({ path: snapshot.path, version: versionOf(snapshot.written) })) }
|
|
260
277
|
const created: string[] = []
|
|
261
278
|
const edited = snapshots.filter(snapshot => snapshot.before && !snapshot.written.equals(snapshot.before))
|
|
262
279
|
const touched = snapshots.filter(snapshot => !snapshot.before || !snapshot.written.equals(snapshot.before)).map(snapshot => snapshot.path)
|
|
263
|
-
const lang = history && touched.length ? readDocumentSummary(this.#config, document).lang : undefined
|
|
264
|
-
const write = (next: DocumentFileChange[]) => this.#writer.write(next)
|
|
280
|
+
const lang = history && touched.length && document ? readDocumentSummary(this.#config, document).lang : undefined
|
|
281
|
+
const write = async (next: DocumentFileChange[]) => document ? await this.#writer.write(next) : writeChanges(this.#config, next, true)
|
|
265
282
|
try {
|
|
266
283
|
// Exclusive creation prevents replacing a file created outside serve after validation.
|
|
267
284
|
for (const snapshot of snapshots) if (!snapshot.before) {
|
|
268
|
-
await this.#writer.create(snapshot.path, snapshot.written)
|
|
285
|
+
await this.#writer.create(snapshot.path, snapshot.written, document === undefined)
|
|
269
286
|
created.push(snapshot.path)
|
|
270
287
|
}
|
|
271
288
|
if (edited.length) await write(edited.map(snapshot => ({ path: snapshot.path, content: snapshot.written, ...snapshot.executable ? { executable: true } : {} })))
|
|
@@ -299,8 +316,7 @@ export class SourceEditor {
|
|
|
299
316
|
const document = this.#documentHolding(path, documents)
|
|
300
317
|
const outside = document === undefined
|
|
301
318
|
const scopeDir = document?.dir ?? ''
|
|
302
|
-
const release = this.#locks ? this.#locks.
|
|
303
|
-
if (!release) throw lockedError(scopeDir, this.#locks!.holder(scopeDir)!)
|
|
319
|
+
const release = this.#locks ? await this.#locks.acquire(scopeDir, 'editor:save') : () => {}
|
|
304
320
|
try {
|
|
305
321
|
const bytes = this.#readBytes(scope, path, member, documents)
|
|
306
322
|
const now = versionOf(bytes)
|
|
@@ -1,18 +1,16 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import type { Route,
|
|
3
|
-
import {
|
|
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(
|
|
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 (!
|
|
14
|
-
|
|
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)
|
package/src/node/templates.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { existsSync, lstatSync, readdirSync
|
|
1
|
+
import { existsSync, lstatSync, readdirSync } from 'node:fs'
|
|
2
2
|
import { join } from 'node:path'
|
|
3
3
|
import { fileURLToPath } from 'node:url'
|
|
4
4
|
import type { WorkspaceConfig } from './config.ts'
|
|
@@ -14,7 +14,7 @@ function templatesDir(config: WorkspaceConfig): string {
|
|
|
14
14
|
export function listTemplates(config: WorkspaceConfig): string[] {
|
|
15
15
|
const dir = templatesDir(config)
|
|
16
16
|
try {
|
|
17
|
-
return readdirSync(dir).filter(name =>
|
|
17
|
+
return readdirSync(dir).filter(name => findTemplate(config, name) !== undefined).sort()
|
|
18
18
|
} catch {
|
|
19
19
|
return []
|
|
20
20
|
}
|
|
@@ -33,7 +33,7 @@ export interface WorkbenchApi {
|
|
|
33
33
|
* `prefetch`: the workbench prepares the document ahead of the author's click, answered at once. A build still running
|
|
34
34
|
* after the wait is answered with 503 `preview-preparing` and `Retry-After`.
|
|
35
35
|
*/
|
|
36
|
-
preview(document: string, renderer?: PreviewRenderer, prefetch?: boolean): Promise<PreviewAnswer>
|
|
36
|
+
preview(document: string, renderer?: PreviewRenderer, prefetch?: boolean, browserOrigin?: string): Promise<PreviewAnswer>
|
|
37
37
|
build(document: string, to?: string[]): Promise<BuildAnswer>
|
|
38
38
|
check(document: string): Promise<CheckAnswer>
|
|
39
39
|
}
|
|
@@ -80,6 +80,17 @@ export function createWorkbenchBackend(options: WorkbenchBackendOptions): Workbe
|
|
|
80
80
|
const { root, log } = options
|
|
81
81
|
const irRevisions = new WeakMap<Compilation, string>()
|
|
82
82
|
const relativeDocs = new WeakMap<Compilation, IRDocument>()
|
|
83
|
+
const previewBase = (base: string, browserOrigin: string | undefined): string => {
|
|
84
|
+
if (!browserOrigin) return base
|
|
85
|
+
try {
|
|
86
|
+
const preview = new URL(base), browser = new URL(browserOrigin)
|
|
87
|
+
if (preview.protocol !== browser.protocol || !['localhost', '127.0.0.1', '[::1]'].includes(preview.hostname)) return base
|
|
88
|
+
preview.hostname = browser.hostname
|
|
89
|
+
return base.endsWith('/') ? preview.href : preview.href.replace(/\/$/, '')
|
|
90
|
+
} catch {
|
|
91
|
+
return base
|
|
92
|
+
}
|
|
93
|
+
}
|
|
83
94
|
const irRevisionOf = (compilation: Compilation) => {
|
|
84
95
|
let known = irRevisions.get(compilation)
|
|
85
96
|
if (!known) irRevisions.set(compilation, known = irRevision(compilation.doc))
|
|
@@ -119,7 +130,7 @@ export function createWorkbenchBackend(options: WorkbenchBackendOptions): Workbe
|
|
|
119
130
|
return () => own.delete(listener)
|
|
120
131
|
}, { signal })
|
|
121
132
|
},
|
|
122
|
-
async preview(document, renderer, prefetch = false) {
|
|
133
|
+
async preview(document, renderer, prefetch = false, browserOrigin) {
|
|
123
134
|
const request = ++previewRequest
|
|
124
135
|
const started = Date.now()
|
|
125
136
|
const label = `[preview ${request}] document=${JSON.stringify(document || '.')} renderer=${renderer ?? 'all'} prefetch=${prefetch}`
|
|
@@ -127,7 +138,7 @@ export function createWorkbenchBackend(options: WorkbenchBackendOptions): Workbe
|
|
|
127
138
|
let outcome = 'failed'
|
|
128
139
|
log.info(`${label} state=started`)
|
|
129
140
|
try {
|
|
130
|
-
const base = options.url()
|
|
141
|
+
const base = previewBase(options.url(), browserOrigin)
|
|
131
142
|
// The viewer app's page once it has what the document needs (an opened document waits for it a while), else the
|
|
132
143
|
// document's page on the site.
|
|
133
144
|
const page = await options.viewerPage?.(document, !prefetch).catch((error: unknown) => {
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { CHANGES_MAX_REQUEST_CHARS, CHANGES_MAX_RESPONSE_CHARS, DOCUMENT_ENTRY, hasRole, jsonResponse, problemResponse } from '@lincyaw/kernel'
|
|
2
|
+
import type { ChangesCaller, WorkspaceChanges, WorkspaceChangesResult } from '@lincyaw/kernel'
|
|
3
|
+
import { validateChangesQuery, validateWorkspaceChangesRequest } from '@lincyaw/kernel/node'
|
|
4
|
+
import { listDocuments } from './config.ts'
|
|
5
|
+
import type { WorkspaceConfig } from './config.ts'
|
|
6
|
+
import { catchRequestErrors, RequestError } from './errors.ts'
|
|
7
|
+
import { documentsDiff } from './document-operations.ts'
|
|
8
|
+
import type { DocumentsChange } from './document-operations.ts'
|
|
9
|
+
import type { DocumentLocks } from './locks.ts'
|
|
10
|
+
import type { Revisions } from './revisions.ts'
|
|
11
|
+
import { MAX_SOURCE, validateDocumentSource } from './source-editor.ts'
|
|
12
|
+
import type { SourceEditor } from './source-editor.ts'
|
|
13
|
+
import { documentDirOf, isGeneratedPath } from './writer.ts'
|
|
14
|
+
import type { Route } from '@lincyaw/kernel'
|
|
15
|
+
|
|
16
|
+
const size = (value: unknown) => JSON.stringify(value).length
|
|
17
|
+
async function bounded<T>(work: () => Promise<T>): Promise<T> {
|
|
18
|
+
try { return await work() }
|
|
19
|
+
catch (error) {
|
|
20
|
+
const value = error as { message?: string, status?: number }
|
|
21
|
+
if (value.message?.startsWith('changes-') || value.message === 'authoring-review-required') throw error
|
|
22
|
+
throw new RequestError(value.status ?? 409, value.message === 'document-invalid' ? 'changes-document-invalid' : 'changes-operation-failed')
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/** Web and MCP share the same capture, policy, document locks and frozen Revisions application. */
|
|
26
|
+
export function createWorkspaceChanges(options: { config: WorkspaceConfig, editor: SourceEditor, locks: DocumentLocks, revisions?: Revisions, changed(change: DocumentsChange): Promise<void> | void }) {
|
|
27
|
+
const { config, editor, locks, revisions } = options
|
|
28
|
+
const scope = (document: string | undefined, caller: ChangesCaller) => {
|
|
29
|
+
if (!hasRole(caller.member, 'editor')) throw new RequestError(403, 'changes-permission-denied')
|
|
30
|
+
if (caller.boundDocument !== undefined) {
|
|
31
|
+
if (document !== undefined && document !== caller.boundDocument) throw new RequestError(403, 'changes-permission-denied')
|
|
32
|
+
return { document: caller.boundDocument, home: false }
|
|
33
|
+
}
|
|
34
|
+
return editor.scope(document ?? '')
|
|
35
|
+
}
|
|
36
|
+
const writer = (caller: ChangesCaller) => {
|
|
37
|
+
if (!hasRole(caller.member, 'editor') || caller.origin === 'agent' && (!hasRole(caller.member, 'owner') || caller.boundDocument !== undefined || caller.confirmed)) throw new RequestError(403, 'changes-permission-denied')
|
|
38
|
+
if (caller.origin === 'agent' && config.settings['presmium.assistant']?.review === 'required') throw new RequestError(409, 'authoring-review-required')
|
|
39
|
+
}
|
|
40
|
+
const budget = (value: unknown) => { if (size(value) > CHANGES_MAX_REQUEST_CHARS) throw new RequestError(413, 'changes-request-too-large') }
|
|
41
|
+
const service: WorkspaceChanges = {
|
|
42
|
+
list: (query, caller) => bounded(async () => {
|
|
43
|
+
budget(query)
|
|
44
|
+
if (!validateChangesQuery(query)) throw new RequestError(400, 'changes-request-invalid')
|
|
45
|
+
const owned = scope(query.document, caller)
|
|
46
|
+
if (!revisions) return { available: false, files: [] }
|
|
47
|
+
const state = await revisions.observeChanges(editor.roots(owned)), offset = query.offset ?? 0
|
|
48
|
+
if (query.snapshot !== undefined && query.snapshot !== state.snapshot || offset > 0 && !query.snapshot) throw new RequestError(409, 'changes-state-changed')
|
|
49
|
+
if (offset > state.files.length) throw new RequestError(400, 'changes-request-invalid')
|
|
50
|
+
const raw = new Map(state.raw.map(file => [file.path, file]))
|
|
51
|
+
const files = [] as import('@lincyaw/kernel').WorkspaceChangesAnswer['files']
|
|
52
|
+
for (const file of state.files.slice(offset, offset + 20)) {
|
|
53
|
+
if (!editor.canEdit(owned, file.path, caller.member)) throw new RequestError(403, 'changes-permission-denied')
|
|
54
|
+
const row = { ...file, ...raw.get(file.path)?.mode === 'unsupported' ? { unsupported: true as const } : {} }
|
|
55
|
+
if (size({ available: true, snapshot: state.snapshot, files: [...files, row], nextOffset: offset + files.length + 1 }) > CHANGES_MAX_RESPONSE_CHARS) break
|
|
56
|
+
files.push(row)
|
|
57
|
+
}
|
|
58
|
+
if (!files.length && offset < state.files.length) throw new RequestError(413, 'changes-response-too-large')
|
|
59
|
+
return { available: true, snapshot: state.snapshot, files, ...offset + files.length < state.files.length ? { nextOffset: offset + files.length } : {} }
|
|
60
|
+
}),
|
|
61
|
+
prepare: (request, caller) => bounded(async () => {
|
|
62
|
+
budget(request); writer(caller)
|
|
63
|
+
if (!validateWorkspaceChangesRequest(request) || request.action === 'commit' && !request.message.trim()) throw new RequestError(400, 'changes-request-invalid')
|
|
64
|
+
const action = request.action, message = request.action === 'commit' ? request.message.trim() : undefined
|
|
65
|
+
const owned = scope(request.document, caller)
|
|
66
|
+
if (!revisions) throw new RequestError(409, 'changes-git-unavailable')
|
|
67
|
+
const observed = await revisions.observeChanges(editor.roots(owned))
|
|
68
|
+
if (request.snapshot !== undefined && request.snapshot !== observed.snapshot) throw new RequestError(409, 'changes-state-changed')
|
|
69
|
+
const chosen = new Set(request.paths ?? observed.files.map(file => file.path))
|
|
70
|
+
if (!chosen.size) throw new RequestError(409, 'changes-empty')
|
|
71
|
+
const known = new Set(observed.files.map(file => file.path))
|
|
72
|
+
if ([...chosen].some(path => !known.has(path))) throw new RequestError(409, 'changes-selection-changed')
|
|
73
|
+
const paths = observed.files.filter(file => chosen.has(file.path)).map(file => file.path)
|
|
74
|
+
let captured = { ...observed, files: observed.files.filter(file => chosen.has(file.path)), raw: observed.raw.filter(file => chosen.has(file.path)) }
|
|
75
|
+
if (captured.raw.some(file => !file.change)) throw new RequestError(409, 'changes-file-unsupported')
|
|
76
|
+
const owners = paths.map(path => documentDirOf(config, path))
|
|
77
|
+
const check = () => {
|
|
78
|
+
writer(caller)
|
|
79
|
+
for (const [index, path] of paths.entries()) {
|
|
80
|
+
if (!editor.canEdit(owned, path, caller.member) || isGeneratedPath(path)) throw new RequestError(403, 'changes-permission-denied')
|
|
81
|
+
if (documentDirOf(config, path) !== owners[index]) throw new RequestError(409, 'changes-state-changed')
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
check()
|
|
85
|
+
if (action === 'commit') for (const file of captured.raw) {
|
|
86
|
+
if (file.path === DOCUMENT_ENTRY || file.path.endsWith(`/${DOCUMENT_ENTRY}`)) {
|
|
87
|
+
if (!file.change || !('content' in file.change)) throw new RequestError(409, 'changes-document-invalid')
|
|
88
|
+
if (Buffer.byteLength(file.change.content) > MAX_SOURCE) throw new RequestError(413, 'changes-selection-too-large')
|
|
89
|
+
let text: string
|
|
90
|
+
try { text = new TextDecoder('utf-8', { fatal: true }).decode(file.change.content) } catch { throw new RequestError(422, 'changes-document-invalid') }
|
|
91
|
+
validateDocumentSource(file.path, text)
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
if (action === 'commit') captured = await revisions.freezeCommit(captured)
|
|
95
|
+
let pending: Promise<WorkspaceChangesResult> | undefined
|
|
96
|
+
return { paths: Object.freeze([...paths]), change: signal => pending ??= bounded(async () => {
|
|
97
|
+
signal?.throwIfAborted(); check()
|
|
98
|
+
const claim = locks.claimAll(owners.map(owner => owner ?? ''), `editor:${action}`)
|
|
99
|
+
if ('holder' in claim) throw new RequestError(409, 'changes-workspace-busy')
|
|
100
|
+
const before = listDocuments(config).map(document => document.dir)
|
|
101
|
+
try {
|
|
102
|
+
const revision = await revisions.applyChanges(action, captured, action === 'commit' ? { paths, summary: message!.split('\n')[0]!, body: message!.split('\n').slice(1).join('\n'), origin: { kind: caller.origin === 'agent' ? 'agent' : 'editor', member: caller.member } } : undefined, () => { signal?.throwIfAborted(); check() })
|
|
103
|
+
let refreshed: false | undefined
|
|
104
|
+
if (action === 'discard') {
|
|
105
|
+
try { await options.changed(documentsDiff(before, listDocuments(config).map(document => document.dir))) } catch { refreshed = false }
|
|
106
|
+
}
|
|
107
|
+
return { ...refreshed === false ? { refreshed } : {}, action, files: paths.length, ...action === 'commit' ? { committed: Boolean(revision), ...revision ? { revision } : {} } : {} }
|
|
108
|
+
} finally { claim.release() }
|
|
109
|
+
}) }
|
|
110
|
+
}),
|
|
111
|
+
}
|
|
112
|
+
const routes: Record<string, Route> = {
|
|
113
|
+
changes: { role: 'editor', handle: (request, ctx) => catchRequestErrors(async () => {
|
|
114
|
+
if (request.method !== 'GET') return problemResponse(405, 'GET')
|
|
115
|
+
if (!revisions) return jsonResponse({ files: [] })
|
|
116
|
+
const files = await revisions.uncommittedFiles(editor.roots(editor.scope(ctx.document)))
|
|
117
|
+
return jsonResponse({ files })
|
|
118
|
+
}) },
|
|
119
|
+
...Object.fromEntries((['commit', 'discard'] as const).map(action => [`changes/${action}`, { role: 'editor', handle: (request, ctx) => catchRequestErrors(async () => {
|
|
120
|
+
if (request.method !== 'POST') return problemResponse(405, 'POST')
|
|
121
|
+
const body: unknown = await request.json().catch(() => undefined)
|
|
122
|
+
if (!body || typeof body !== 'object' || Array.isArray(body)) throw new RequestError(400, 'changes-request-invalid')
|
|
123
|
+
const input = body as Record<string, unknown>
|
|
124
|
+
const prepared = await service.prepare({ ...input, document: ctx.document, action, ...action === 'discard' ? { confirm: true } : {} } as import('@lincyaw/kernel').WorkspaceChangesRequest, { member: ctx.member, origin: 'editor' })
|
|
125
|
+
const result = await prepared.change(request.signal)
|
|
126
|
+
return jsonResponse({ paths: prepared.paths, ...result.refreshed === false ? { refreshed: false } : {}, ...result.revision ? { revision: result.revision } : {} })
|
|
127
|
+
}) } satisfies Route])),
|
|
128
|
+
}
|
|
129
|
+
return { service, routes }
|
|
130
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
import { DOCUMENT_ENTRY, hasRole, SOURCE_FRAGMENT_CHARS, SOURCE_MAX_REQUEST_CHARS, SOURCE_MAX_RESPONSE_CHARS } from '@lincyaw/kernel'
|
|
3
|
+
import type { SourceCaller, SourceSaved, WorkspaceSource } from '@lincyaw/kernel'
|
|
4
|
+
import { validateSourceEdit, validateSourceList, validateSourceRead } from '@lincyaw/kernel/node'
|
|
5
|
+
import { listDocumentEntries } from './config.ts'
|
|
6
|
+
import type { WorkspaceConfig } from './config.ts'
|
|
7
|
+
import { RequestError } from './errors.ts'
|
|
8
|
+
import { saveSummary } from '../domain/commit-message.ts'
|
|
9
|
+
import type { Revisions } from './revisions.ts'
|
|
10
|
+
import { validateDocumentSource } from './source-editor.ts'
|
|
11
|
+
import type { SourceEditor } from './source-editor.ts'
|
|
12
|
+
|
|
13
|
+
const size = (value: unknown) => JSON.stringify(value).length
|
|
14
|
+
const fits = (value: unknown) => size(value) <= SOURCE_MAX_RESPONSE_CHARS
|
|
15
|
+
const digest = (value: string) => createHash('sha256').update(value).digest('hex')
|
|
16
|
+
const canonical = (path: string) => path === DOCUMENT_ENTRY || path.endsWith(`/${DOCUMENT_ENTRY}`)
|
|
17
|
+
/** SourceEditor keeps detailed conflicts for Web; MCP never returns full conflicting file contents. */
|
|
18
|
+
async function bounded<T>(work: () => Promise<T>): Promise<T> {
|
|
19
|
+
try { return await work() }
|
|
20
|
+
catch (error) {
|
|
21
|
+
const value = error as { message?: string, status?: number, code?: string, detail?: { conflict?: { version?: string }, exists?: boolean, issues?: { path?: string, code?: string, message?: string, severity?: string }[] } }
|
|
22
|
+
if (error instanceof Error && error.name === 'AbortError') throw error
|
|
23
|
+
if (value.message?.startsWith('source-') || value.message === 'authoring-review-required') throw error
|
|
24
|
+
if (value.message === 'document-invalid') {
|
|
25
|
+
const issues = value.detail?.issues?.slice(0, 4).map(issue => ({ path: issue.path?.slice(0, 500) ?? '', code: issue.code?.slice(0, 100) ?? 'document-invalid', message: issue.message?.slice(0, 240) ?? '', severity: issue.severity === 'warning' ? 'warning' : 'error' })) ?? []
|
|
26
|
+
while (size({ issues }) > SOURCE_MAX_RESPONSE_CHARS - 1024 && issues.length) issues.pop()
|
|
27
|
+
throw new RequestError(422, 'document-invalid', { issues })
|
|
28
|
+
}
|
|
29
|
+
if (value.message === 'document-identity-changed') throw new RequestError(422, 'document-identity-changed')
|
|
30
|
+
if (value.status === 409) throw new RequestError(409, value.detail?.exists ? 'source-file-exists' : 'source-version-changed', value.detail?.conflict?.version ? { version: value.detail.conflict.version } : undefined)
|
|
31
|
+
const status = value.status ?? ({ ENOENT: 404, EEXIST: 409, ELOOP: 403, EACCES: 403, EISDIR: 415 } as Record<string, number>)[value.code ?? ''] ?? 500
|
|
32
|
+
throw new RequestError(status, status === 404 ? 'source-file-not-found' : status === 409 ? 'source-file-exists' : status === 403 ? 'source-file-forbidden' : status === 413 ? 'source-file-too-large' : status === 415 ? 'source-text-required' : status < 500 ? 'source-request-invalid' : 'source-operation-failed')
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** A bounded adapter over the native source scope, preflight, transaction and history owner. */
|
|
37
|
+
export function createWorkspaceSource(options: { config: WorkspaceConfig, editor: SourceEditor, revisions?: Revisions }): WorkspaceSource {
|
|
38
|
+
const { config, editor, revisions } = options
|
|
39
|
+
const scope = (document: string | undefined, caller: SourceCaller) => {
|
|
40
|
+
if (!hasRole(caller.member, 'editor')) throw new RequestError(403, 'source-file-forbidden')
|
|
41
|
+
if (caller.boundDocument !== undefined) {
|
|
42
|
+
if (document !== undefined && document !== caller.boundDocument) throw new RequestError(403, 'source-file-forbidden')
|
|
43
|
+
return { document: caller.boundDocument, home: false }
|
|
44
|
+
}
|
|
45
|
+
if (document && !listDocumentEntries(config).some(entry => entry.dir === document)) throw new RequestError(404, 'source-file-not-found')
|
|
46
|
+
return editor.scope(document ?? '')
|
|
47
|
+
}
|
|
48
|
+
const request = (value: unknown) => { if (size(value) > SOURCE_MAX_REQUEST_CHARS) throw new RequestError(413, 'source-request-too-large') }
|
|
49
|
+
const writer = (caller: SourceCaller) => {
|
|
50
|
+
if (!hasRole(caller.member, 'owner') || caller.boundDocument !== undefined || caller.confirmed) throw new RequestError(403, 'source-file-forbidden')
|
|
51
|
+
if (caller.origin === 'agent' && config.settings['presmium.assistant']?.review === 'required') throw new RequestError(409, 'authoring-review-required')
|
|
52
|
+
}
|
|
53
|
+
const repair = (path: string, before: Uint8Array | undefined) => {
|
|
54
|
+
if (!canonical(path)) return
|
|
55
|
+
if (!before || !listDocumentEntries(config).some(entry => entry.entry === path)) throw new RequestError(409, 'source-canonical-edit-required')
|
|
56
|
+
try { validateDocumentSource(path, Buffer.from(before).toString('utf8')) }
|
|
57
|
+
catch (error) { if ((error as Error).message === 'document-invalid') return; throw error }
|
|
58
|
+
throw new RequestError(409, 'source-canonical-edit-required')
|
|
59
|
+
}
|
|
60
|
+
return {
|
|
61
|
+
list: (query, caller) => bounded(async () => {
|
|
62
|
+
request(query)
|
|
63
|
+
if (!validateSourceList(query)) throw new RequestError(400, 'source-request-invalid')
|
|
64
|
+
const owned = scope(query.document, caller), listed = editor.files(owned, caller.member)
|
|
65
|
+
const files = listed.files.filter(file => !query.query || file.path.toLowerCase().includes(query.query.toLowerCase()))
|
|
66
|
+
const snapshot = digest(JSON.stringify([owned, query.query ?? '', files, listed.truncated ?? false])), offset = query.offset ?? 0
|
|
67
|
+
if (offset > 0 && !query.snapshot || query.snapshot !== undefined && query.snapshot !== snapshot) throw new RequestError(409, 'source-list-changed')
|
|
68
|
+
if (offset > files.length) throw new RequestError(400, 'source-request-invalid')
|
|
69
|
+
const answer = { files: [] as typeof files, snapshot, ...listed.truncated ? { truncated: true as const } : {} }
|
|
70
|
+
for (const file of files.slice(offset, offset + 20)) {
|
|
71
|
+
if (!fits({ ...answer, files: [...answer.files, file], nextOffset: offset + answer.files.length + 1 })) break
|
|
72
|
+
answer.files.push(file)
|
|
73
|
+
}
|
|
74
|
+
if (!answer.files.length && offset < files.length) throw new RequestError(413, 'source-response-too-large')
|
|
75
|
+
return { ...answer, ...offset + answer.files.length < files.length ? { nextOffset: offset + answer.files.length } : {} }
|
|
76
|
+
}),
|
|
77
|
+
read: (query, caller) => bounded(async () => {
|
|
78
|
+
request(query)
|
|
79
|
+
if (!validateSourceRead(query)) throw new RequestError(400, 'source-request-invalid')
|
|
80
|
+
const value = editor.read(scope(query.document, caller), query.path, caller.member), offset = query.offset ?? 0
|
|
81
|
+
if (offset > 0 && !query.version || query.version !== undefined && query.version !== value.version) throw new RequestError(409, 'source-version-changed')
|
|
82
|
+
if (offset > value.content.length) throw new RequestError(400, 'source-request-invalid')
|
|
83
|
+
const answer = { path: value.path, version: value.version, text: value.content.slice(offset, offset + SOURCE_FRAGMENT_CHARS), offset, totalChars: value.content.length, nextOffset: 0 }
|
|
84
|
+
const cursor = () => answer.nextOffset = offset + answer.text.length
|
|
85
|
+
cursor()
|
|
86
|
+
while (!fits(answer) && answer.text.length) { answer.text = answer.text.slice(0, Math.floor(answer.text.length / 2)); cursor() }
|
|
87
|
+
if (!fits(answer) || !answer.text.length && offset < value.content.length) throw new RequestError(413, 'source-response-too-large')
|
|
88
|
+
const { nextOffset, ...part } = answer
|
|
89
|
+
return { ...part, ...nextOffset < value.content.length ? { nextOffset } : {} }
|
|
90
|
+
}),
|
|
91
|
+
prepare: (edit, caller) => bounded(async () => {
|
|
92
|
+
request(edit); writer(caller)
|
|
93
|
+
if (!validateSourceEdit(edit)) throw new RequestError(400, 'source-request-invalid')
|
|
94
|
+
const document = edit.document, owned = scope(document, caller), edits = 'edits' in edit ? edit.edits : [edit]
|
|
95
|
+
const captured = edits.map(file => {
|
|
96
|
+
const creating = 'create' in file && file.create === true
|
|
97
|
+
if (creating && (canonical(file.path) || file.version !== undefined)) throw new RequestError(409, 'source-canonical-edit-required')
|
|
98
|
+
const before = creating ? undefined : editor.read(owned, file.path, caller.member)
|
|
99
|
+
if (file.version !== undefined && before?.version !== file.version) throw new RequestError(409, 'source-version-changed')
|
|
100
|
+
repair(file.path, before && Buffer.from(before.content))
|
|
101
|
+
let content: string
|
|
102
|
+
if ('content' in file) content = file.content
|
|
103
|
+
else {
|
|
104
|
+
const first = before!.content.indexOf(file.find)
|
|
105
|
+
if (first < 0 || before!.content.indexOf(file.find, first + 1) >= 0) throw new RequestError(409, 'source-find-not-unique')
|
|
106
|
+
content = before!.content.slice(0, first) + file.replace + before!.content.slice(first + file.find.length)
|
|
107
|
+
}
|
|
108
|
+
return { path: file.path, content, base: before?.version ?? null, changed: creating || before!.content !== content }
|
|
109
|
+
})
|
|
110
|
+
const changes = captured.map(({ changed: _changed, ...file }) => file)
|
|
111
|
+
await editor.planTransaction(owned, changes, caller.member)
|
|
112
|
+
let work: Promise<SourceSaved> | undefined
|
|
113
|
+
return { change: (signal?: AbortSignal) => work ??= bounded(async () => {
|
|
114
|
+
const result = await editor.transaction(owned, changes, caller.member, {
|
|
115
|
+
check: files => {
|
|
116
|
+
signal?.throwIfAborted(); writer(caller)
|
|
117
|
+
if (JSON.stringify(scope(document, caller)) !== JSON.stringify(owned)) throw new RequestError(409, 'source-scope-changed')
|
|
118
|
+
for (const file of files) repair(file.path, file.before)
|
|
119
|
+
},
|
|
120
|
+
run: task => revisions ? revisions.transaction(task) : task(),
|
|
121
|
+
commit: async (paths, lang) => {
|
|
122
|
+
if (!revisions) return
|
|
123
|
+
if ((await Promise.all(paths.map(path => revisions.ignores(path)))).some(Boolean)) throw new RequestError(409, 'source-ignored-file')
|
|
124
|
+
return revisions.commitWhileLocked({ paths, summary: saveSummary(paths[0]!, lang), body: '', origin: { kind: caller.origin === 'agent' ? 'agent' : 'editor', member: caller.member } })
|
|
125
|
+
},
|
|
126
|
+
})
|
|
127
|
+
let current = false
|
|
128
|
+
try { current = result.versions.every(value => editor.read(owned, value.path, caller.member).version === value.version) } catch { /* A successful write is not safely retryable when readback changes or fails. */ }
|
|
129
|
+
return { saved: true as const, changed: captured.some(file => file.changed), ...captured.length === 1 ? { path: captured[0]!.path } : { files: captured.length }, ...result.revision ? { revision: result.revision.id } : {}, ...!current ? { current: false as const } : {} }
|
|
130
|
+
}) }
|
|
131
|
+
}),
|
|
132
|
+
}
|
|
133
|
+
}
|
package/src/node/writer.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { closeSync, constants, cpSync, fstatSync, lstatSync, mkdirSync, mkdtempS
|
|
|
3
3
|
import type { Stats } from 'node:fs'
|
|
4
4
|
import { tmpdir } from 'node:os'
|
|
5
5
|
import { dirname, join } from 'node:path'
|
|
6
|
-
import { DOCUMENT_ENTRY, validateDocument } from '@lincyaw/kernel'
|
|
6
|
+
import { CHANGES_MAX_BYTES, CHANGES_MAX_FILES, DOCUMENT_ENTRY, validateDocument } from '@lincyaw/kernel'
|
|
7
7
|
import type { DocumentFileChange, DocumentFiles } from '@lincyaw/kernel'
|
|
8
8
|
import { isWithin, rewriteLinks } from '../domain/paths.ts'
|
|
9
9
|
import { isDocumentDir, listDocuments } from './config.ts'
|
|
@@ -11,8 +11,8 @@ import type { WorkspaceConfig } from './config.ts'
|
|
|
11
11
|
import { findTemplate } from './templates.ts'
|
|
12
12
|
|
|
13
13
|
const NOT_COPIED = new Set(['node_modules', 'dist', '.git'])
|
|
14
|
-
export const DOCUMENT_OPERATION_MAX_BACKUP_ENTRIES =
|
|
15
|
-
export const DOCUMENT_OPERATION_MAX_BACKUP_BYTES =
|
|
14
|
+
export const DOCUMENT_OPERATION_MAX_BACKUP_ENTRIES = CHANGES_MAX_FILES
|
|
15
|
+
export const DOCUMENT_OPERATION_MAX_BACKUP_BYTES = CHANGES_MAX_BYTES
|
|
16
16
|
|
|
17
17
|
export class FilesError extends Error {}
|
|
18
18
|
export class DocumentCheckpointRefusal extends FilesError {
|