@lincyaw/workspace 1.0.0-rc.45 → 1.0.0-rc.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lincyaw/workspace",
3
- "version": "1.0.0-rc.45",
3
+ "version": "1.0.0-rc.46",
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/kernel": "1.0.0-rc.45",
38
- "@lincyaw/compiler": "1.0.0-rc.45",
39
- "@lincyaw/server": "1.0.0-rc.45"
37
+ "@lincyaw/compiler": "1.0.0-rc.46",
38
+ "@lincyaw/kernel": "1.0.0-rc.46",
39
+ "@lincyaw/server": "1.0.0-rc.46"
40
40
  },
41
41
  "devDependencies": {
42
42
  "@types/mime-types": "^3.0.1",
43
- "@lincyaw/mcp": "1.0.0-rc.45"
43
+ "@lincyaw/mcp": "1.0.0-rc.46"
44
44
  }
45
45
  }
@@ -13,6 +13,7 @@ import type { Revisions } from './revisions.ts'
13
13
  import { DOCUMENT_OPERATION_MAX_BACKUP_BYTES, DOCUMENT_OPERATION_MAX_BACKUP_ENTRIES, documentDirOf } from './writer.ts'
14
14
  import { catchRequestErrors, RequestError } from './errors.ts'
15
15
  import { projectConfiguration, projectDigest, projectMaterial } from './project-files.ts'
16
+ import { listTemplates } from './templates.ts'
16
17
 
17
18
  type Admission = { signature: string, admission: Promise<ProjectPlan> }
18
19
  type Stored = { member: string, origin: ProjectCaller['origin'], signature: string, plan: ProjectPlan, material?: ReturnType<typeof projectMaterial>, canonical?: { change: DocumentChange, planId: string, source: CanonicalSource }, receipt?: ProjectApplied, work?: Promise<ProjectApplied> }
@@ -59,14 +60,28 @@ export function createProjectAuthoring(options: { config: WorkspaceConfig, opera
59
60
  }
60
61
  const key = (request: ProjectPlanRequest, caller: ProjectCaller) => JSON.stringify([caller.member.id, caller.origin, request.id])
61
62
  const service: ProjectAuthoring = {
62
- async capabilities(caller) {
63
+ async capabilities(caller, query = {}) {
63
64
  if (closed) throw new RequestError(503, 'project-owner-closed')
65
+ const offset = query.templatesOffset ?? 0
66
+ if (!Number.isSafeInteger(offset) || offset < 0 || Object.keys(query).some(key => key !== 'templatesOffset')) throw new RequestError(400, 'project-request-invalid')
64
67
  const observed = await observation(), directory = reasons(caller), metadata = reasons(caller, { op: 'retitle', dir: caller.boundDocument ?? '', title: 'capability' })
65
68
  if (!observed.snapshot && !directory.includes('project-git-unavailable')) directory.push('project-head-unavailable')
66
69
  const actions = Object.fromEntries(['create', 'copy', 'rename', 'delete', 'retitle'].map(op => { const unavailable = op === 'retitle' ? metadata : directory; return [op, { available: unavailable.length === 0, reasons: unavailable }] })) as import('@lincyaw/kernel').ProjectCapabilities['actions']
67
70
  const available = Object.values(actions).some(action => action.available)
68
- return bounded({ available, actions, reasons: available ? [] : [...new Set([...directory, ...metadata])], observation: observed, verification: 'configuration-only', rootDirectoryOperations: false,
69
- limits: { requestChars: PROJECT_MAX_REQUEST_CHARS, responseChars: PROJECT_MAX_RESPONSE_CHARS, backupEntries: DOCUMENT_OPERATION_MAX_BACKUP_ENTRIES, backupBytes: DOCUMENT_OPERATION_MAX_BACKUP_BYTES, plans: PROJECT_MAX_PLANS, ttlMs: PROJECT_PLAN_TTL_MS } })
71
+ const answer: import('@lincyaw/kernel').ProjectCapabilities = { available, actions, reasons: available ? [] : [...new Set([...directory, ...metadata])], observation: observed, verification: 'configuration-only', rootDirectoryOperations: false,
72
+ limits: { requestChars: PROJECT_MAX_REQUEST_CHARS, responseChars: PROJECT_MAX_RESPONSE_CHARS, backupEntries: DOCUMENT_OPERATION_MAX_BACKUP_ENTRIES, backupBytes: DOCUMENT_OPERATION_MAX_BACKUP_BYTES, plans: PROJECT_MAX_PLANS, ttlMs: PROJECT_PLAN_TTL_MS } }
73
+ if (caller.boundDocument === undefined) {
74
+ const templates = listTemplates(config)
75
+ if (offset > templates.length) throw new RequestError(400, 'project-request-invalid')
76
+ answer.templates = []
77
+ for (const template of templates.slice(offset, offset + 20)) {
78
+ if (JSON.stringify({ ...answer, templates: [...answer.templates, template], nextTemplatesOffset: offset + answer.templates.length + 1 }).length > PROJECT_MAX_RESPONSE_CHARS) break
79
+ answer.templates.push(template)
80
+ }
81
+ if (!answer.templates.length && offset < templates.length) throw new RequestError(413, 'project-response-too-large')
82
+ if (offset + answer.templates.length < templates.length) answer.nextTemplatesOffset = offset + answer.templates.length
83
+ } else if (offset) throw new RequestError(403, 'project-workspace-scope-required')
84
+ return bounded(answer)
70
85
  },
71
86
  async plan(request, caller) {
72
87
  budget(request)
package/src/node/serve.ts CHANGED
@@ -24,6 +24,7 @@ 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
26
  import { createWorkspaceReview } from './review/workspace-review.ts'
27
+ import { createWorkspaceSource } from './workspace-source.ts'
27
28
  import { createTaskReviewService } from './review/task-reviews.ts'
28
29
  import { Revisions } from './revisions.ts'
29
30
  import { WORKSPACE_ID, authorizeWorkspaceRoutes, workspaceRoutes, workspaceRoutesPlugin } from './routes.ts'
@@ -118,6 +119,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
118
119
  let documentEditor: DocumentEditor | undefined
119
120
  let documentHistory: ReturnType<typeof createDocumentHistory> | undefined
120
121
  let workspaceReview: ReturnType<typeof createWorkspaceReview> | undefined
122
+ let workspaceSource: ReturnType<typeof createWorkspaceSource> | undefined
121
123
  let projectAuthoring: ReturnType<typeof createProjectAuthoring> | undefined
122
124
  let authoringClients: ReturnType<typeof createAuthoringClients> | undefined
123
125
  let transcriptions: ReturnType<typeof createDocumentTranscriptions> | undefined
@@ -275,6 +277,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
275
277
  get voiceAuthoring() { return voiceAuthoring?.service },
276
278
  speechSettings,
277
279
  get workspaceReview() { return workspaceReview },
280
+ get workspaceSource() { return workspaceSource },
278
281
  get transcriptions() { return transcriptions },
279
282
  get transcriptionAdoption() { return transcriptionAdoption?.service },
280
283
  get capture() { return capture?.service },
@@ -387,6 +390,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
387
390
  voiceAuthoring = createDocumentVoiceAuthoring({ editor, services: authoringServices, revision: document => { const latest = compileSessions.get(document)?.latest; return latest ? irRevision(latest.doc) : undefined } })
388
391
  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) })
389
392
  history = openHistory()
393
+ workspaceSource = createWorkspaceSource({ config, editor, revisions: history?.revisions })
390
394
  workspaceReview = history && createWorkspaceReview(history.agentSessionReviews)
391
395
  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' })
392
396
  projectAuthoring = createProjectAuthoring({ config, documentEditor, operations: history?.operations, revisions: history?.revisions, git: history?.git })
@@ -1,8 +1,8 @@
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'
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'
@@ -12,8 +12,8 @@ import type { DocumentLocks } from './locks.ts'
12
12
  import { documentDirOf, FilesError, writeChanges } from './writer.ts'
13
13
  import type { DocumentWriter } from './writer.ts'
14
14
 
15
- export const MAX_SOURCE = 2 << 20
16
- export const MAX_SOURCE_CHANGES = 16
15
+ export const MAX_SOURCE = SOURCE_MAX_BYTES
16
+ export const MAX_SOURCE_CHANGES = SOURCE_MAX_FILES
17
17
  const MAX_FILES = 2000
18
18
  const HIDDEN_FROM_EDITOR = new Set(['node_modules', 'dist', '.git', '.presmium'])
19
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
@@ -48,6 +48,8 @@ interface Scope {
48
48
  }
49
49
 
50
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
51
53
  run<T>(work: () => Promise<T>): Promise<T>
52
54
  commit(paths: string[], lang: string | undefined): Promise<Revision | undefined>
53
55
  }
@@ -153,9 +155,20 @@ export class SourceEditor {
153
155
 
154
156
  #readBytes(scope: Scope, path: string, member: Member, documents?: readonly DocumentEntry[]): Buffer {
155
157
  const file = this.#readableFile(scope, path, member, documents)
156
- const bytes = readFileSync(file)
157
- if (bytes.byteLength > MAX_SOURCE) throw new RequestError(413, `${path} is larger than the editor opens (${MAX_SOURCE} bytes)`)
158
- return bytes
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) }
159
172
  }
160
173
 
161
174
  read(scope: Scope, path: string, member: Member): SourceAnswer {
@@ -225,10 +238,16 @@ export class SourceEditor {
225
238
  if (bytes > MAX_SOURCE) throw new RequestError(413, `the transaction is larger than the editor saves (${MAX_SOURCE} bytes)`)
226
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}`)
227
240
  const document = documents[0]
228
- if (!document || documents.some(found => found?.dir !== document.dir)) throw new RequestError(400, 'a source transaction must stay in one document')
229
- const scopeDir = document.dir
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 ?? ''
230
244
  const release = this.#locks ? await this.#locks.acquire(scopeDir, 'editor:transaction') : () => {}
231
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
+ }
232
251
  // Read every preimage before creating directories or writing any file.
233
252
  const snapshots = changes.map(change => {
234
253
  const written = typeof change.content === 'string' ? Buffer.from(change.content, 'utf8') : Buffer.from(change.content)
@@ -253,16 +272,17 @@ export class SourceEditor {
253
272
  return { path: change.path, before: undefined, written, executable: false }
254
273
  })
255
274
  for (const snapshot of snapshots) if (snapshot.path !== binaryPath) validateDocumentSource(snapshot.path, snapshot.written.toString('utf8'), snapshot.before)
275
+ history?.check?.(snapshots)
256
276
  if (dryRun) return { versions: snapshots.map(snapshot => ({ path: snapshot.path, version: versionOf(snapshot.written) })) }
257
277
  const created: string[] = []
258
278
  const edited = snapshots.filter(snapshot => snapshot.before && !snapshot.written.equals(snapshot.before))
259
279
  const touched = snapshots.filter(snapshot => !snapshot.before || !snapshot.written.equals(snapshot.before)).map(snapshot => snapshot.path)
260
- const lang = history && touched.length ? readDocumentSummary(this.#config, document).lang : undefined
261
- 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)
262
282
  try {
263
283
  // Exclusive creation prevents replacing a file created outside serve after validation.
264
284
  for (const snapshot of snapshots) if (!snapshot.before) {
265
- await this.#writer.create(snapshot.path, snapshot.written)
285
+ await this.#writer.create(snapshot.path, snapshot.written, document === undefined)
266
286
  created.push(snapshot.path)
267
287
  }
268
288
  if (edited.length) await write(edited.map(snapshot => ({ path: snapshot.path, content: snapshot.written, ...snapshot.executable ? { executable: true } : {} })))
@@ -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
  }
@@ -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
+ }