@lincyaw/workspace 1.0.0-rc.13 → 1.0.0-rc.130

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.
Files changed (59) hide show
  1. package/README.md +4 -4
  2. package/package.json +8 -5
  3. package/src/domain/paths.ts +0 -15
  4. package/src/node/agent-activity.ts +46 -0
  5. package/src/node/archive.ts +33 -0
  6. package/src/node/authoring-clients.ts +73 -20
  7. package/src/node/authoring-windows.ts +165 -0
  8. package/src/node/build.ts +28 -23
  9. package/src/node/capture.ts +383 -0
  10. package/src/node/config.ts +136 -50
  11. package/src/node/document-assets.ts +2 -2
  12. package/src/node/document-audio.ts +65 -46
  13. package/src/node/document-authoring.ts +30 -15
  14. package/src/node/document-check.ts +36 -0
  15. package/src/node/document-history.ts +32 -5
  16. package/src/node/document-images.ts +24 -14
  17. package/src/node/document-import.ts +123 -0
  18. package/src/node/document-index.ts +644 -0
  19. package/src/node/document-materials.ts +80 -0
  20. package/src/node/document-operations.ts +4 -2
  21. package/src/node/document-transcription.ts +2 -1
  22. package/src/node/document-voice.ts +121 -13
  23. package/src/node/git-runner.mjs +19 -0
  24. package/src/node/git.ts +141 -22
  25. package/src/node/host-activity.ts +17 -0
  26. package/src/node/host-upgrade.ts +28 -0
  27. package/src/node/jobs.ts +40 -8
  28. package/src/node/local-history.ts +84 -0
  29. package/src/node/locks.ts +12 -0
  30. package/src/node/mcp-settings.ts +68 -0
  31. package/src/node/media-upload-messages.ts +4 -0
  32. package/src/node/media-upload-page.ts +57 -0
  33. package/src/node/media-upload.css +4 -0
  34. package/src/node/media-uploads.ts +116 -0
  35. package/src/node/page-delete.ts +0 -1
  36. package/src/node/project-files.ts +2 -2
  37. package/src/node/projects.ts +20 -5
  38. package/src/node/review/agent-session-reviews.ts +194 -63
  39. package/src/node/review/agent-workspace.ts +124 -0
  40. package/src/node/review/git-review.ts +47 -15
  41. package/src/node/review/record.ts +5 -1
  42. package/src/node/review/routes.ts +9 -1
  43. package/src/node/review/workspace-review.ts +87 -0
  44. package/src/node/revision-files.ts +54 -0
  45. package/src/node/revisions.ts +244 -59
  46. package/src/node/routes.ts +52 -59
  47. package/src/node/serve.ts +267 -52
  48. package/src/node/site.ts +5 -5
  49. package/src/node/source-editor.ts +66 -26
  50. package/src/node/speech-settings.ts +6 -8
  51. package/src/node/templates.ts +2 -2
  52. package/src/node/tree-operations.ts +425 -0
  53. package/src/node/tree-routes.ts +94 -0
  54. package/src/node/workbench-api.ts +14 -3
  55. package/src/node/workspace-changes.ts +130 -0
  56. package/src/node/workspace-migrate.ts +54 -0
  57. package/src/node/workspace-source.ts +133 -0
  58. package/src/node/writer.ts +21 -8
  59. package/templates/document/default/{lecture.json → index.pmd} +5 -1
@@ -1,30 +1,32 @@
1
1
  import { createHash } from 'node:crypto'
2
- import { lstatSync, readdirSync, readFileSync, realpathSync } from 'node:fs'
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'
6
- import type { ConflictAnswer, DocumentFileChange, FilesAnswer, Member, Revision, SavedAnswer, SourceAnswer, SourceFile, SourceTransactionAnswer, SourceTransactionChange } from '@lincyaw/kernel'
5
+ import { DOCUMENT_ENTRY, SOURCE_MAX_BYTES, SOURCE_MAX_FILES } from '@lincyaw/kernel'
6
+ import type { ConflictAnswer, DocumentFileChange, FilesAnswer, Member, Revision, SavedAnswer, SourceAnswer, SourceFile, SourceTransactionAnswer, SourceTransactionChange, DocumentDefaults, EffectiveDocument, PresmiumDocument, SettingOrigins } from '@lincyaw/kernel'
7
7
  import { isWithin } from '../domain/paths.ts'
8
- import { listDocumentEntries, readDocumentSummary } from './config.ts'
8
+ import { effectiveContent, inheritedContent, inheritedOrigins, 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'
11
+ import { checkDocumentText } from './document-check.ts'
12
12
  import type { DocumentLocks } from './locks.ts'
13
13
  import { documentDirOf, FilesError, writeChanges } from './writer.ts'
14
14
  import type { DocumentWriter } from './writer.ts'
15
15
 
16
- export const MAX_SOURCE = 2 << 20
17
- export const MAX_SOURCE_CHANGES = 16
16
+ export const MAX_SOURCE = SOURCE_MAX_BYTES
17
+ export const MAX_SOURCE_CHANGES = SOURCE_MAX_FILES
18
18
  const MAX_FILES = 2000
19
19
  const HIDDEN_FROM_EDITOR = new Set(['node_modules', 'dist', '.git', '.presmium'])
20
20
  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
21
21
 
22
+ function validateSourceText(path: string, content: unknown): asserts content is string {
23
+ if (typeof content !== 'string' || BINARY.test(path) || content.includes('\0')) throw new RequestError(415, `${path} is not a text file`)
24
+ }
25
+
22
26
  export function validateDocumentSource(path: string, content: string, before?: Uint8Array): void {
23
27
  if (path !== DOCUMENT_ENTRY && !path.endsWith(`/${DOCUMENT_ENTRY}`)) return
24
- let value: unknown
25
- try { value = JSON.parse(content.replace(/^\uFEFF/, '')) }
26
- catch { throw new RequestError(422, 'document-invalid', { issues: [{ path: '', code: 'json-syntax', message: 'The document is not valid JSON.', severity: 'error' }] }) }
27
- const checked = validateDocument(value)
28
+ const checked = checkDocumentText(content)
29
+ if (checked.syntax) throw new RequestError(422, 'document-invalid', { issues: [{ path: '', code: 'json-syntax', message: 'The document is not valid JSON.', severity: 'error' }] })
28
30
  if (!checked.document || checked.issues.some(issue => issue.severity === 'error')) throw new RequestError(422, 'document-invalid', { issues: checked.issues })
29
31
  if (before) {
30
32
  let previous: unknown
@@ -41,6 +43,7 @@ export interface SourceEditorOptions {
41
43
  config: WorkspaceConfig
42
44
  writer: DocumentWriter
43
45
  locks?: DocumentLocks
46
+ beforeWrite?(paths: string[], historyLocked: boolean): Promise<void>
44
47
  }
45
48
 
46
49
  interface Scope {
@@ -49,6 +52,8 @@ interface Scope {
49
52
  }
50
53
 
51
54
  export interface SourceTransactionHistory {
55
+ /** Runs on final locked preimages, before any file is created or changed. */
56
+ check?(files: readonly { path: string, before?: Uint8Array }[]): void
52
57
  run<T>(work: () => Promise<T>): Promise<T>
53
58
  commit(paths: string[], lang: string | undefined): Promise<Revision | undefined>
54
59
  }
@@ -59,11 +64,28 @@ export class SourceEditor {
59
64
  readonly #config: WorkspaceConfig
60
65
  readonly #writer: DocumentWriter
61
66
  readonly #locks?: DocumentLocks
67
+ readonly #beforeWrite?: SourceEditorOptions['beforeWrite']
62
68
 
63
69
  constructor(options: SourceEditorOptions) {
64
70
  this.#config = options.config
65
71
  this.#writer = options.writer
66
72
  this.#locks = options.locks
73
+ this.#beforeWrite = options.beforeWrite
74
+ }
75
+
76
+ /** The document in `document` with its inherited settings filled in, for decisions; never saved. */
77
+ effective(document: string, content: PresmiumDocument): EffectiveDocument {
78
+ return effectiveContent(this.#config, document, content)
79
+ }
80
+
81
+ /** What the document in `document` inherits from its ancestors and the workspace defaults. */
82
+ inherited(document: string, content: PresmiumDocument): DocumentDefaults {
83
+ return inheritedContent(this.#config, document, content)
84
+ }
85
+
86
+ /** Which ancestor (or the workspace defaults, null) each setting the document in `document` inherits comes from. */
87
+ inheritedFrom(document: string, content: PresmiumDocument): SettingOrigins {
88
+ return inheritedOrigins(this.#config, document, content)
67
89
  }
68
90
 
69
91
  scope(document: string): Scope {
@@ -154,9 +176,20 @@ export class SourceEditor {
154
176
 
155
177
  #readBytes(scope: Scope, path: string, member: Member, documents?: readonly DocumentEntry[]): Buffer {
156
178
  const file = this.#readableFile(scope, path, member, documents)
157
- const bytes = readFileSync(file)
158
- if (bytes.byteLength > MAX_SOURCE) throw new RequestError(413, `${path} is larger than the editor opens (${MAX_SOURCE} bytes)`)
159
- return bytes
179
+ const before = lstatSync(file)
180
+ const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)
181
+ try {
182
+ const opened = fstatSync(fd)
183
+ if (!opened.isFile() || opened.dev !== before.dev || opened.ino !== before.ino) throw new RequestError(409, 'source-file-changed')
184
+ if (opened.size > MAX_SOURCE) throw new RequestError(413, `${path} is larger than the editor opens (${MAX_SOURCE} bytes)`)
185
+ const bytes = Buffer.alloc(opened.size + 1)
186
+ let length = 0, count = 0
187
+ while (length < bytes.length && (count = readSync(fd, bytes, length, bytes.length - length, null)) > 0) length += count
188
+ const after = fstatSync(fd), current = lstatSync(file)
189
+ if (length !== opened.size || after.size !== opened.size || after.mtimeMs !== opened.mtimeMs || after.ctimeMs !== opened.ctimeMs
190
+ || current.dev !== opened.dev || current.ino !== opened.ino || realpathSync(file) !== file) throw new RequestError(409, 'source-file-changed')
191
+ return bytes.subarray(0, length)
192
+ } finally { closeSync(fd) }
160
193
  }
161
194
 
162
195
  read(scope: Scope, path: string, member: Member): SourceAnswer {
@@ -178,8 +211,7 @@ export class SourceEditor {
178
211
  if (BINARY.test(path)) throw new RequestError(415, `${path} is not a text file`)
179
212
  const document = this.#documentHolding(path, documents)?.dir
180
213
  const scopeDir = document ?? ''
181
- const release = this.#locks ? this.#locks.claim(scopeDir, 'editor:create') : () => {}
182
- if (!release) throw lockedError(scopeDir, this.#locks!.holder(scopeDir)!)
214
+ const release = this.#locks ? await this.#locks.acquire(scopeDir, 'editor:create') : () => {}
183
215
  try {
184
216
  await this.#writer.create(path, Buffer.alloc(0), document === undefined)
185
217
  return { path, content: '', version: versionOf('') }
@@ -219,7 +251,7 @@ export class SourceEditor {
219
251
  if (paths.has(change.path)) throw new RequestError(400, `a source path occurs twice: ${change.path}`)
220
252
  paths.add(change.path)
221
253
  if (change.path !== binaryPath) {
222
- if (typeof change.content !== 'string' || BINARY.test(change.path) || change.content.includes('\0')) throw new RequestError(415, `${change.path} is not a text file`)
254
+ validateSourceText(change.path, change.content)
223
255
  bytes += Buffer.byteLength(change.content, 'utf8')
224
256
  }
225
257
  return this.#documentHolding(change.path, known)
@@ -227,11 +259,16 @@ export class SourceEditor {
227
259
  if (bytes > MAX_SOURCE) throw new RequestError(413, `the transaction is larger than the editor saves (${MAX_SOURCE} bytes)`)
228
260
  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
261
  const document = documents[0]
230
- if (!document || documents.some(found => found?.dir !== document.dir)) throw new RequestError(400, 'a source transaction must stay in one document')
231
- const scopeDir = document.dir
232
- const release = this.#locks ? this.#locks.claim(scopeDir, 'editor:transaction') : () => {}
233
- if (!release) throw lockedError(scopeDir, this.#locks!.holder(scopeDir)!)
262
+ 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')
263
+ if (!document && changes.some(change => change.path === DOCUMENT_ENTRY || change.path.endsWith(`/${DOCUMENT_ENTRY}`))) throw new RequestError(422, 'create-a-document-with-valid-content')
264
+ const scopeDir = document?.dir ?? ''
265
+ const release = this.#locks ? await this.#locks.acquire(scopeDir, 'editor:transaction') : () => {}
234
266
  const work = async (): Promise<SourceTransactionAnswer> => {
267
+ const current = listDocumentEntries(this.#config)
268
+ for (const [index, change] of changes.entries()) {
269
+ this.#assertEditable(scope, change.path, member, current)
270
+ if (this.#documentHolding(change.path, current)?.dir !== documents[index]?.dir) throw new RequestError(409, 'source-scope-changed')
271
+ }
235
272
  // Read every preimage before creating directories or writing any file.
236
273
  const snapshots = changes.map(change => {
237
274
  const written = typeof change.content === 'string' ? Buffer.from(change.content, 'utf8') : Buffer.from(change.content)
@@ -256,16 +293,18 @@ export class SourceEditor {
256
293
  return { path: change.path, before: undefined, written, executable: false }
257
294
  })
258
295
  for (const snapshot of snapshots) if (snapshot.path !== binaryPath) validateDocumentSource(snapshot.path, snapshot.written.toString('utf8'), snapshot.before)
296
+ history?.check?.(snapshots)
259
297
  if (dryRun) return { versions: snapshots.map(snapshot => ({ path: snapshot.path, version: versionOf(snapshot.written) })) }
260
298
  const created: string[] = []
261
299
  const edited = snapshots.filter(snapshot => snapshot.before && !snapshot.written.equals(snapshot.before))
262
300
  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)
301
+ if (touched.length) await this.#beforeWrite?.(touched, Boolean(history))
302
+ const lang = history && touched.length && document ? readDocumentSummary(this.#config, document).lang : undefined
303
+ const write = async (next: DocumentFileChange[]) => document ? await this.#writer.write(next) : writeChanges(this.#config, next, true)
265
304
  try {
266
305
  // Exclusive creation prevents replacing a file created outside serve after validation.
267
306
  for (const snapshot of snapshots) if (!snapshot.before) {
268
- await this.#writer.create(snapshot.path, snapshot.written)
307
+ await this.#writer.create(snapshot.path, snapshot.written, document === undefined)
269
308
  created.push(snapshot.path)
270
309
  }
271
310
  if (edited.length) await write(edited.map(snapshot => ({ path: snapshot.path, content: snapshot.written, ...snapshot.executable ? { executable: true } : {} })))
@@ -299,8 +338,7 @@ export class SourceEditor {
299
338
  const document = this.#documentHolding(path, documents)
300
339
  const outside = document === undefined
301
340
  const scopeDir = document?.dir ?? ''
302
- const release = this.#locks ? this.#locks.claim(scopeDir, 'editor:save') : () => {}
303
- if (!release) throw lockedError(scopeDir, this.#locks!.holder(scopeDir)!)
341
+ const release = this.#locks ? await this.#locks.acquire(scopeDir, 'editor:save') : () => {}
304
342
  try {
305
343
  const bytes = this.#readBytes(scope, path, member, documents)
306
344
  const now = versionOf(bytes)
@@ -308,12 +346,14 @@ export class SourceEditor {
308
346
  const conflict: Omit<ConflictAnswer, 'error'> = { conflict: { version: now, content: bytes.toString('utf8') } }
309
347
  throw new RequestError(409, `${path} changed since it was opened`, conflict)
310
348
  }
349
+ validateSourceText(path, content)
311
350
  const written = Buffer.from(content, 'utf8')
312
351
  validateDocumentSource(path, content, bytes)
313
352
  if (written.byteLength > MAX_SOURCE) throw new RequestError(413, `the text is larger than the editor saves (${MAX_SOURCE} bytes)`)
314
353
  const change: DocumentFileChange = { path, content: written, ...(lstatSync(join(this.#config.root, path)).mode & 0o111) !== 0 ? { executable: true } : {} }
315
354
  const lang = commit && !written.equals(bytes) && document ? readDocumentSummary(this.#config, document).lang : undefined
316
355
  const write = async (next: DocumentFileChange) => (outside ? writeChanges(this.#config, [next], true) : await this.#writer.write([next]))
356
+ if (!written.equals(bytes)) await this.#beforeWrite?.([path], false)
317
357
  await write(change)
318
358
  let revision: Revision | undefined
319
359
  if (commit && !written.equals(bytes)) {
@@ -1,18 +1,16 @@
1
- import { isRecord, jsonResponse, problemResponse } from '@lincyaw/kernel'
2
- import type { Route, SpeechSettingsChange } from '@lincyaw/kernel'
3
- import { OperatorSpeechSettings, SpeechSettingsError } from '@lincyaw/kernel/node'
1
+ import { jsonResponse, problemResponse } from '@lincyaw/kernel'
2
+ import type { Route, SpeechSettings } from '@lincyaw/kernel'
3
+ import { SpeechSettingsError, validateSpeechSettingsChange } from '@lincyaw/kernel/node'
4
4
 
5
5
  /** Global operator route: works before opening a document and never returns credential values. */
6
- export function speechSettingsRoute(directory: string, fallback: (name: string) => string | undefined): Route {
7
- const settings = new OperatorSpeechSettings(directory, fallback)
6
+ export function speechSettingsRoute(settings: SpeechSettings): Route {
8
7
  return { role: 'owner', maxBody: 16384, handle: async request => {
9
8
  try {
10
9
  if (request.method === 'GET') return jsonResponse(settings.read(), 200, { 'cache-control': 'no-store' })
11
10
  if (request.method !== 'POST') return problemResponse(405, 'GET or POST')
12
11
  const body: unknown = await request.json().catch(() => undefined)
13
- if (!isRecord(body) || typeof body.revision !== 'string' || !['save', 'clear'].includes(String(body.action)) || Object.keys(body).some(key => !['action', 'revision', 'apiKey', 'appId'].includes(key))
14
- || body.action === 'save' && (body.apiKey !== undefined && typeof body.apiKey !== 'string' || body.appId !== undefined && typeof body.appId !== 'string')) return problemResponse(400, 'speech-settings-invalid')
15
- return jsonResponse(await settings.change(body as unknown as SpeechSettingsChange), 200, { 'cache-control': 'no-store' })
12
+ if (!validateSpeechSettingsChange(body)) return problemResponse(400, 'speech-settings-invalid')
13
+ return jsonResponse(await settings.change(body), 200, { 'cache-control': 'no-store' })
16
14
  } catch (error) {
17
15
  const code = error instanceof SpeechSettingsError ? error.code : 'speech-settings-unavailable'
18
16
  return problemResponse(code === 'speech-settings-invalid' ? 400 : code === 'speech-settings-conflict' || code === 'speech-settings-busy' ? 409 : 503, code)
@@ -1,4 +1,4 @@
1
- import { existsSync, lstatSync, readdirSync, statSync } from 'node:fs'
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 => statSync(join(dir, name)).isDirectory()).sort()
17
+ return readdirSync(dir).filter(name => findTemplate(config, name) !== undefined).sort()
18
18
  } catch {
19
19
  return []
20
20
  }