@lincyaw/workspace 1.0.0-rc.44 → 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 +5 -5
- package/src/node/projects.ts +18 -3
- 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 +8 -0
- package/src/node/source-editor.ts +32 -12
- package/src/node/templates.ts +2 -2
- package/src/node/workspace-source.ts +133 -0
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.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/compiler": "1.0.0-rc.
|
|
38
|
-
"@lincyaw/
|
|
39
|
-
"@lincyaw/
|
|
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.
|
|
43
|
+
"@lincyaw/mcp": "1.0.0-rc.46"
|
|
44
44
|
}
|
|
45
45
|
}
|
package/src/node/projects.ts
CHANGED
|
@@ -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
|
-
|
|
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)
|
|
@@ -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,8 @@ 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'
|
|
27
|
+
import { createWorkspaceSource } from './workspace-source.ts'
|
|
26
28
|
import { createTaskReviewService } from './review/task-reviews.ts'
|
|
27
29
|
import { Revisions } from './revisions.ts'
|
|
28
30
|
import { WORKSPACE_ID, authorizeWorkspaceRoutes, workspaceRoutes, workspaceRoutesPlugin } from './routes.ts'
|
|
@@ -116,6 +118,8 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
|
|
|
116
118
|
let history: WorkspaceHistory | undefined
|
|
117
119
|
let documentEditor: DocumentEditor | undefined
|
|
118
120
|
let documentHistory: ReturnType<typeof createDocumentHistory> | undefined
|
|
121
|
+
let workspaceReview: ReturnType<typeof createWorkspaceReview> | undefined
|
|
122
|
+
let workspaceSource: ReturnType<typeof createWorkspaceSource> | undefined
|
|
119
123
|
let projectAuthoring: ReturnType<typeof createProjectAuthoring> | undefined
|
|
120
124
|
let authoringClients: ReturnType<typeof createAuthoringClients> | undefined
|
|
121
125
|
let transcriptions: ReturnType<typeof createDocumentTranscriptions> | undefined
|
|
@@ -272,6 +276,8 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
|
|
|
272
276
|
get imageAuthoring() { return imageAuthoring?.service },
|
|
273
277
|
get voiceAuthoring() { return voiceAuthoring?.service },
|
|
274
278
|
speechSettings,
|
|
279
|
+
get workspaceReview() { return workspaceReview },
|
|
280
|
+
get workspaceSource() { return workspaceSource },
|
|
275
281
|
get transcriptions() { return transcriptions },
|
|
276
282
|
get transcriptionAdoption() { return transcriptionAdoption?.service },
|
|
277
283
|
get capture() { return capture?.service },
|
|
@@ -384,6 +390,8 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
|
|
|
384
390
|
voiceAuthoring = createDocumentVoiceAuthoring({ editor, services: authoringServices, revision: document => { const latest = compileSessions.get(document)?.latest; return latest ? irRevision(latest.doc) : undefined } })
|
|
385
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) })
|
|
386
392
|
history = openHistory()
|
|
393
|
+
workspaceSource = createWorkspaceSource({ config, editor, revisions: history?.revisions })
|
|
394
|
+
workspaceReview = history && createWorkspaceReview(history.agentSessionReviews)
|
|
387
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' })
|
|
388
396
|
projectAuthoring = createProjectAuthoring({ config, documentEditor, operations: history?.operations, revisions: history?.revisions, git: history?.git })
|
|
389
397
|
authoringClients = createAuthoringClients(editor, { reviewRequired: config.settings['presmium.assistant']?.review === 'required' })
|
|
@@ -1,8 +1,8 @@
|
|
|
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'
|
|
@@ -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 =
|
|
16
|
-
export const MAX_SOURCE_CHANGES =
|
|
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
|
|
157
|
-
|
|
158
|
-
|
|
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
|
|
229
|
-
|
|
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 } : {} })))
|
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
|
}
|
|
@@ -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
|
+
}
|