@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.
- package/README.md +4 -4
- package/package.json +8 -5
- package/src/domain/paths.ts +0 -15
- package/src/node/agent-activity.ts +46 -0
- package/src/node/archive.ts +33 -0
- package/src/node/authoring-clients.ts +73 -20
- package/src/node/authoring-windows.ts +165 -0
- package/src/node/build.ts +28 -23
- package/src/node/capture.ts +383 -0
- package/src/node/config.ts +136 -50
- package/src/node/document-assets.ts +2 -2
- package/src/node/document-audio.ts +65 -46
- package/src/node/document-authoring.ts +30 -15
- package/src/node/document-check.ts +36 -0
- package/src/node/document-history.ts +32 -5
- package/src/node/document-images.ts +24 -14
- package/src/node/document-import.ts +123 -0
- package/src/node/document-index.ts +644 -0
- package/src/node/document-materials.ts +80 -0
- package/src/node/document-operations.ts +4 -2
- package/src/node/document-transcription.ts +2 -1
- package/src/node/document-voice.ts +121 -13
- package/src/node/git-runner.mjs +19 -0
- package/src/node/git.ts +141 -22
- package/src/node/host-activity.ts +17 -0
- package/src/node/host-upgrade.ts +28 -0
- package/src/node/jobs.ts +40 -8
- package/src/node/local-history.ts +84 -0
- package/src/node/locks.ts +12 -0
- package/src/node/mcp-settings.ts +68 -0
- package/src/node/media-upload-messages.ts +4 -0
- package/src/node/media-upload-page.ts +57 -0
- package/src/node/media-upload.css +4 -0
- package/src/node/media-uploads.ts +116 -0
- package/src/node/page-delete.ts +0 -1
- package/src/node/project-files.ts +2 -2
- package/src/node/projects.ts +20 -5
- package/src/node/review/agent-session-reviews.ts +194 -63
- package/src/node/review/agent-workspace.ts +124 -0
- package/src/node/review/git-review.ts +47 -15
- package/src/node/review/record.ts +5 -1
- package/src/node/review/routes.ts +9 -1
- package/src/node/review/workspace-review.ts +87 -0
- package/src/node/revision-files.ts +54 -0
- package/src/node/revisions.ts +244 -59
- package/src/node/routes.ts +52 -59
- package/src/node/serve.ts +267 -52
- package/src/node/site.ts +5 -5
- package/src/node/source-editor.ts +66 -26
- package/src/node/speech-settings.ts +6 -8
- package/src/node/templates.ts +2 -2
- package/src/node/tree-operations.ts +425 -0
- package/src/node/tree-routes.ts +94 -0
- package/src/node/workbench-api.ts +14 -3
- package/src/node/workspace-changes.ts +130 -0
- package/src/node/workspace-migrate.ts +54 -0
- package/src/node/workspace-source.ts +133 -0
- package/src/node/writer.ts +21 -8
- package/templates/document/default/{lecture.json → index.pmd} +5 -1
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { randomUUID } from 'node:crypto'
|
|
2
|
-
import { existsSync
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
2
|
+
import { existsSync } from 'node:fs'
|
|
3
3
|
import { join } from 'node:path'
|
|
4
|
-
import {
|
|
5
|
-
import type { DocumentFiles, Logger, Member, ReviewEnd, ReviewSnapshot, ReviewUpdate } from '@lincyaw/kernel'
|
|
4
|
+
import { errorMessage, pushStream } 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'
|
|
@@ -11,12 +11,12 @@ import { lockedError } from '../locks.ts'
|
|
|
11
11
|
import type { DocumentLocks } from '../locks.ts'
|
|
12
12
|
import type { Revisions } from '../revisions.ts'
|
|
13
13
|
import { writeChanges } from '../writer.ts'
|
|
14
|
-
import {
|
|
14
|
+
import { openGitReview, pendingAgentSessionReview, resumeGitReview } from './git-review.ts'
|
|
15
15
|
import type { GitReview } from './git-review.ts'
|
|
16
16
|
import { readRecord } from './record.ts'
|
|
17
17
|
import type { ReviewRecord } from './record.ts'
|
|
18
18
|
import { rollBackLeftTaskReview } from './task-reviews.ts'
|
|
19
|
-
import {
|
|
19
|
+
import { AgentWorkspace } from './agent-workspace.ts'
|
|
20
20
|
|
|
21
21
|
export const AGENT_SESSION_TRAILER = 'Presmium-Session'
|
|
22
22
|
export const TURN_TRAILER = 'Presmium-Turn'
|
|
@@ -32,6 +32,7 @@ export interface AgentSessionReviewsOptions {
|
|
|
32
32
|
/** How a plugin's task writes, for rolling back the tasks a process left. */
|
|
33
33
|
files?: DocumentFiles
|
|
34
34
|
log: Logger
|
|
35
|
+
flush?(documents: string[], member: Member): Promise<void>
|
|
35
36
|
}
|
|
36
37
|
|
|
37
38
|
interface OpenReview {
|
|
@@ -42,7 +43,9 @@ interface OpenReview {
|
|
|
42
43
|
turns: { from: number, to: number }
|
|
43
44
|
running: boolean
|
|
44
45
|
opened: string
|
|
45
|
-
|
|
46
|
+
backend?: 'deltabox'
|
|
47
|
+
awaitingDeltabox?: boolean
|
|
48
|
+
workspace?: AgentWorkspace
|
|
46
49
|
timer?: ReturnType<typeof setTimeout>
|
|
47
50
|
}
|
|
48
51
|
|
|
@@ -69,21 +72,21 @@ function commitSummary(files: string[], lang: string | undefined): string {
|
|
|
69
72
|
}
|
|
70
73
|
|
|
71
74
|
/**
|
|
72
|
-
*
|
|
73
|
-
*
|
|
75
|
+
* A dsh session reviews its private candidate; only publication briefly locks the author's workspace.
|
|
76
|
+
* A review that no page watches drops its candidate changes after the configured time.
|
|
74
77
|
*/
|
|
75
78
|
export class AgentSessionReviews {
|
|
76
79
|
readonly #options: AgentSessionReviewsOptions
|
|
77
80
|
#open?: OpenReview
|
|
78
81
|
#queue: Promise<unknown> = Promise.resolve()
|
|
79
|
-
readonly #workspaceFiles: DocumentFiles
|
|
80
82
|
readonly #watchers = new Set<(update: ReviewUpdate) => void>()
|
|
81
83
|
readonly #listeners = new Set<(event: ReviewEvent) => void>()
|
|
82
84
|
#closed = false
|
|
85
|
+
readonly #workspaces = new Map<string, AgentWorkspace>()
|
|
86
|
+
readonly #retired = new Set<string>()
|
|
83
87
|
|
|
84
88
|
constructor(options: AgentSessionReviewsOptions) {
|
|
85
89
|
this.#options = options
|
|
86
|
-
this.#workspaceFiles = { write: async changes => writeChanges(options.config, changes, true) }
|
|
87
90
|
}
|
|
88
91
|
|
|
89
92
|
/** Takes up the reviews a process that has ended left: resumes its agent session's review, rolls back its tasks' reviews. */
|
|
@@ -102,6 +105,7 @@ export class AgentSessionReviews {
|
|
|
102
105
|
}
|
|
103
106
|
await rollBackLeftTaskReview(this.#options, document)
|
|
104
107
|
} catch (error) {
|
|
108
|
+
if (readRecord(scopeDir)?.session) throw error
|
|
105
109
|
log.warn(`the review left in ${document || '.'} was not taken up: ${errorMessage(error)}`)
|
|
106
110
|
}
|
|
107
111
|
}
|
|
@@ -110,30 +114,106 @@ export class AgentSessionReviews {
|
|
|
110
114
|
async #resume(pending: ReviewRecord): Promise<void> {
|
|
111
115
|
const { config, log } = this.#options
|
|
112
116
|
const session = pending.session!
|
|
113
|
-
const
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
}
|
|
117
|
+
const workspace = pending.workspace ? AgentWorkspace.resume(config, pending.workspace) : undefined
|
|
118
|
+
const root = workspace?.root ?? config.root
|
|
119
|
+
const review = await resumeGitReview(pending, { workspaceRoot: root, files: { write: async changes => writeChanges({ ...config, root }, changes, true) }, onRestore: paths => log.warn(`session ${session.session}: the agent changed the git directory, put back: ${paths.join(', ')}`) })
|
|
120
|
+
const empty = (await review.diff()).length === 0
|
|
121
|
+
if (empty && session.backend !== 'deltabox') { await review.close(); workspace?.dispose(); return }
|
|
122
|
+
if (!workspace) { review.suspend(); throw new Error('A legacy review needs to be accepted or rejected with the version that created it before concurrent editing can start.') }
|
|
123
|
+
this.#workspaces.set(session.session, workspace)
|
|
124
|
+
const open: OpenReview = { review, document: session.document, session: session.session, member: session.member, turns: session.turns, running: session.backend === 'deltabox', opened: session.opened, workspace, backend: session.backend, awaitingDeltabox: session.backend === 'deltabox' }
|
|
125
|
+
this.#open = open
|
|
126
|
+
log.info(`the review of session ${session.session} in ${session.document || '.'} (turns ${session.turns.from}-${session.turns.to}) waits for its author again`)
|
|
127
|
+
this.#scheduleRollback(open)
|
|
125
128
|
}
|
|
126
129
|
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
+
workspace(session: string): Promise<{ root: string }> {
|
|
131
|
+
return this.#serial(async () => {
|
|
132
|
+
this.#retired.delete(session)
|
|
133
|
+
let workspace = this.#workspaces.get(session)
|
|
134
|
+
if (!workspace) { workspace = await AgentWorkspace.create(this.#options.config); this.#workspaces.set(session, workspace) }
|
|
135
|
+
return { root: workspace.root }
|
|
136
|
+
})
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
refreshWorkspace(session: string): Promise<boolean> {
|
|
140
|
+
return this.#serial(async () => {
|
|
141
|
+
const workspace = this.#workspaces.get(session)
|
|
142
|
+
return workspace && this.#open?.session !== session ? workspace.refresh() : false
|
|
143
|
+
})
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** The DSH adapter has adopted and staged any orphaned native review before this is called. */
|
|
147
|
+
resumeWorkspace(session: string): Promise<void> {
|
|
148
|
+
return this.#serial(async () => {
|
|
149
|
+
const open = this.#open
|
|
150
|
+
if (!open || open.session !== session || !open.awaitingDeltabox) return
|
|
151
|
+
open.awaitingDeltabox = false
|
|
152
|
+
open.running = false
|
|
153
|
+
if ((await open.review.diff()).length === 0) {
|
|
154
|
+
await open.review.close()
|
|
155
|
+
await this.#end(open, { outcome: 'empty', files: [] })
|
|
156
|
+
} else {
|
|
157
|
+
await this.#publish(open)
|
|
158
|
+
this.#scheduleRollback(open)
|
|
159
|
+
}
|
|
160
|
+
})
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
closeWorkspace(session: string): Promise<void> {
|
|
164
|
+
return this.#serial(async () => {
|
|
165
|
+
if (this.#open?.session === session) { this.#retired.add(session); return }
|
|
166
|
+
const workspace = this.#workspaces.get(session)
|
|
167
|
+
this.#workspaces.delete(session)
|
|
168
|
+
workspace?.dispose()
|
|
169
|
+
})
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
snapshot(): Promise<ReviewSnapshot | undefined> {
|
|
173
|
+
return this.#serial(async () => this.#open && await this.#snapshotOf(this.#open))
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
inspect(): Promise<{ snapshot: string, review: ReviewSnapshot } | undefined> {
|
|
177
|
+
return this.#serial(async () => { if (!this.#open) return; const { snapshot, review } = await this.#inspect(this.#open); return { snapshot, review } })
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
async #inspect(open: OpenReview) {
|
|
181
|
+
const { tree, version, changes } = await open.review.inspect()
|
|
182
|
+
const review = await this.#snapshotOf(open, changes)
|
|
183
|
+
review.steps = review.steps.map(step => ({ ...step, changes: step.changes.map(({ diff: _diff, ...change }) => change) }))
|
|
184
|
+
return { tree, review, snapshot: createHash('sha256').update(JSON.stringify([version, review])).digest('hex') }
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
async #expected(open: OpenReview, expected: string | undefined, signal?: AbortSignal): Promise<void> {
|
|
188
|
+
signal?.throwIfAborted()
|
|
189
|
+
if (expected === undefined) return
|
|
190
|
+
if (open.running) throw new RequestError(409, 'workspace-review-running')
|
|
191
|
+
if ((await this.#inspect(open)).snapshot !== expected) throw new RequestError(409, 'workspace-review-changed')
|
|
192
|
+
signal?.throwIfAborted()
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
check(expected: string): Promise<void> {
|
|
196
|
+
return this.#serial(async () => this.#expected(this.#requireOpen('', expected), expected))
|
|
130
197
|
}
|
|
131
198
|
|
|
132
|
-
|
|
199
|
+
readDiff(expected: string, path: string, step?: string): Promise<ReviewChange | undefined> {
|
|
200
|
+
return this.#serial(async () => {
|
|
201
|
+
const open = this.#requireOpen('', expected)
|
|
202
|
+
const current = await this.#inspect(open)
|
|
203
|
+
if (current.snapshot !== expected) throw new RequestError(409, 'workspace-review-changed')
|
|
204
|
+
const files = step === undefined ? current.review.changes : current.review.steps.find(value => value.id === step)?.changes
|
|
205
|
+
if (!files?.some(file => file.path === path)) return
|
|
206
|
+
const value = await open.review.diffFile(path, step)
|
|
207
|
+
if ((await this.#inspect(open)).snapshot !== expected) throw new RequestError(409, 'workspace-review-changed')
|
|
208
|
+
return value
|
|
209
|
+
})
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
async #snapshotOf(open: OpenReview, changes?: ReviewChange[]): Promise<ReviewSnapshot> {
|
|
133
213
|
return {
|
|
134
214
|
id: open.review.task,
|
|
135
215
|
document: open.document,
|
|
136
|
-
engine:
|
|
216
|
+
engine: 'git-candidate',
|
|
137
217
|
session: open.session,
|
|
138
218
|
holder: lockHolder(open.session),
|
|
139
219
|
turns: { ...open.turns },
|
|
@@ -141,7 +221,7 @@ export class AgentSessionReviews {
|
|
|
141
221
|
mode: reviewSettings(this.#options.config).mode,
|
|
142
222
|
opened: open.opened,
|
|
143
223
|
steps: [...open.review.steps()],
|
|
144
|
-
changes: await open.review.diff(),
|
|
224
|
+
changes: changes ?? await open.review.diff(),
|
|
145
225
|
}
|
|
146
226
|
}
|
|
147
227
|
|
|
@@ -167,30 +247,32 @@ export class AgentSessionReviews {
|
|
|
167
247
|
}, { signal })
|
|
168
248
|
}
|
|
169
249
|
|
|
170
|
-
open(document: string, body: { session: string, turn?: number }, member: Member): Promise<ReviewSnapshot> {
|
|
250
|
+
open(document: string, body: { session: string, turn?: number, backend?: 'deltabox' }, member: Member): Promise<ReviewSnapshot> {
|
|
171
251
|
return this.#serial(async () => {
|
|
172
252
|
if (this.#closed) throw new RequestError(503, 'the workspace service is closing')
|
|
173
253
|
let open = this.#open
|
|
174
254
|
if (open && open.session !== body.session) throw lockedError(document, lockHolder(open.session))
|
|
175
255
|
if (!open) {
|
|
176
|
-
const release = this.#options.locks.claim('', lockHolder(body.session))
|
|
177
|
-
if (!release) throw lockedError(document, this.#options.locks.holder('')!)
|
|
178
256
|
const { config, log } = this.#options
|
|
179
257
|
const turn = body.turn ?? 0
|
|
180
258
|
const opened = new Date().toISOString()
|
|
259
|
+
let workspace = this.#workspaces.get(body.session)
|
|
260
|
+
if (!workspace) { workspace = await AgentWorkspace.create(config); this.#workspaces.set(body.session, workspace) }
|
|
261
|
+
const root = workspace.root
|
|
181
262
|
try {
|
|
182
263
|
const review = await openGitReview({
|
|
183
|
-
workspaceRoot:
|
|
184
|
-
scopeDir:
|
|
264
|
+
workspaceRoot: root,
|
|
265
|
+
scopeDir: root,
|
|
266
|
+
recordRoot: config.root,
|
|
267
|
+
workspace: workspace.record,
|
|
185
268
|
task: randomUUID(),
|
|
186
|
-
files:
|
|
269
|
+
files: { write: async changes => writeChanges({ ...config, root }, changes, true) },
|
|
187
270
|
onRestore: paths => log.warn(`session ${body.session}: the agent changed the git directory, put back: ${paths.join(', ')}`),
|
|
188
271
|
warn: message => log.warn(`session ${body.session}: ${message}`),
|
|
189
|
-
session: { session: body.session, document, member, turns: { from: turn, to: turn }, opened },
|
|
272
|
+
session: { session: body.session, document, member, turns: { from: turn, to: turn }, opened, backend: body.backend },
|
|
190
273
|
})
|
|
191
|
-
open = { review, document, session: body.session, member, turns: { from: turn, to: turn }, running: true, opened,
|
|
274
|
+
open = { review, document, session: body.session, member, turns: { from: turn, to: turn }, running: true, opened, workspace, backend: body.backend }
|
|
192
275
|
} catch (error) {
|
|
193
|
-
release()
|
|
194
276
|
throw new RequestError(409, `the review of ${document || '.'} did not open: ${errorMessage(error)}`)
|
|
195
277
|
}
|
|
196
278
|
this.#open = open
|
|
@@ -204,11 +286,24 @@ export class AgentSessionReviews {
|
|
|
204
286
|
|
|
205
287
|
step(document: string, body: { session: string, turn?: number, label?: string, tool?: string, end?: boolean }): Promise<ReviewSnapshot | undefined> {
|
|
206
288
|
return this.#serial(async () => {
|
|
289
|
+
if (!this.#open && body.end) return undefined
|
|
207
290
|
const open = this.#requireSession(document, body.session)
|
|
208
291
|
this.#noteTurn(open, body.turn)
|
|
209
292
|
if (body.label) await open.review.step(body.label, body.tool)
|
|
210
293
|
if (!body.end) {
|
|
211
|
-
open.running =
|
|
294
|
+
open.running = false
|
|
295
|
+
if (reviewSettings(this.#options.config).mode === 'auto') {
|
|
296
|
+
try { await this.#accept(open, [], undefined) }
|
|
297
|
+
catch (error) {
|
|
298
|
+
if (error instanceof RequestError && error.message === 'agent-source-changed') {
|
|
299
|
+
await open.review.close()
|
|
300
|
+
await this.#end(open, { outcome: 'rejected', files: [] })
|
|
301
|
+
if (this.#workspaces.has(open.session)) await open.workspace!.refresh()
|
|
302
|
+
}
|
|
303
|
+
throw error
|
|
304
|
+
}
|
|
305
|
+
return undefined
|
|
306
|
+
}
|
|
212
307
|
return await this.#publish(open)
|
|
213
308
|
}
|
|
214
309
|
open.running = false
|
|
@@ -227,36 +322,65 @@ export class AgentSessionReviews {
|
|
|
227
322
|
})
|
|
228
323
|
}
|
|
229
324
|
|
|
230
|
-
accept(document: string, body: { reject?: string[], message?: string }): Promise<ReviewEnd> {
|
|
231
|
-
return this.#serial(() =>
|
|
325
|
+
accept(document: string, body: { reject?: string[], message?: string, expected?: string }, signal?: AbortSignal): Promise<ReviewEnd> {
|
|
326
|
+
return this.#serial(async () => {
|
|
327
|
+
const open = this.#requireOpen(document, body.expected)
|
|
328
|
+
if (open.awaitingDeltabox) throw new RequestError(409, 'workspace-review-running')
|
|
329
|
+
await this.#expected(open, body.expected, signal)
|
|
330
|
+
try { return await this.#accept(open, body.reject ?? [], body.message, signal, body.expected) }
|
|
331
|
+
catch (error) {
|
|
332
|
+
if (error instanceof RequestError && error.message === 'agent-source-changed') {
|
|
333
|
+
await open.review.close()
|
|
334
|
+
await this.#end(open, { outcome: 'rejected', files: [] })
|
|
335
|
+
if (this.#workspaces.has(open.session)) await open.workspace!.refresh()
|
|
336
|
+
}
|
|
337
|
+
throw error
|
|
338
|
+
}
|
|
339
|
+
})
|
|
232
340
|
}
|
|
233
341
|
|
|
234
|
-
async #accept(open: OpenReview, reject: string[], message: string | undefined): Promise<ReviewEnd> {
|
|
342
|
+
async #accept(open: OpenReview, reject: string[], message: string | undefined, signal?: AbortSignal, expected?: string): Promise<ReviewEnd> {
|
|
343
|
+
const captured = await this.#inspect(open)
|
|
344
|
+
if (expected !== undefined && captured.snapshot !== expected) throw new RequestError(409, 'workspace-review-changed')
|
|
235
345
|
const rejected = new Set(reject)
|
|
236
|
-
for (const change of
|
|
237
|
-
const files =
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
const file = join(this.#options.config.root, path)
|
|
241
|
-
if (existsSync(file)) validateDocumentSource(path, readFileSync(file, 'utf8'))
|
|
242
|
-
}
|
|
346
|
+
for (const change of captured.review.changes) if (isInGitDir(change.path)) rejected.add(change.path)
|
|
347
|
+
const files = captured.review.changes.filter(change => !rejected.has(change.path)).map(change => change.path)
|
|
348
|
+
const material = await open.review.readTree(captured.tree, files)
|
|
349
|
+
if (!open.workspace) throw new RequestError(409, 'agent-workspace-unavailable')
|
|
243
350
|
const lang = listDocuments(this.#options.config).find(doc => doc.dir === open.document)?.lang
|
|
244
351
|
const steps = open.review.steps().map(step => `- ${step.label}`).slice(0, 20)
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
352
|
+
if (files.length) await this.#options.flush?.(listDocuments(this.#options.config).map(document => document.dir), open.member)
|
|
353
|
+
const release = await this.#options.locks.acquire('', lockHolder(open.session))
|
|
354
|
+
let revision
|
|
355
|
+
try {
|
|
356
|
+
revision = await this.#options.revisions.transaction(async () => {
|
|
357
|
+
signal?.throwIfAborted()
|
|
358
|
+
if ((await this.#inspect(open)).snapshot !== captured.snapshot) throw new RequestError(409, 'workspace-review-changed')
|
|
359
|
+
const selected = await open.review.prepareAccept([...rejected])
|
|
360
|
+
if (JSON.stringify(selected) !== JSON.stringify(files)) throw new RequestError(409, 'workspace-review-changed')
|
|
361
|
+
try { await open.review.assertTree(captured.tree, [...rejected]) }
|
|
362
|
+
catch { throw new RequestError(409, 'workspace-review-changed') }
|
|
363
|
+
signal?.throwIfAborted()
|
|
364
|
+
const prepared = open.workspace!.prepare(files, material)
|
|
365
|
+
await this.#options.revisions.checkpoint(files)
|
|
366
|
+
try {
|
|
367
|
+
open.workspace!.write(prepared.changes)
|
|
368
|
+
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}`]] })
|
|
369
|
+
} catch (error) { open.workspace!.write(prepared.restore); throw error }
|
|
370
|
+
})
|
|
371
|
+
} finally { release() }
|
|
251
372
|
open.review.finish()
|
|
252
373
|
const ended: ReviewEnd = { outcome: 'accepted', ...revision ? { revision } : {}, files }
|
|
253
374
|
await this.#end(open, ended)
|
|
375
|
+
if (this.#workspaces.has(open.session)) await open.workspace.refresh()
|
|
254
376
|
return ended
|
|
255
377
|
}
|
|
256
378
|
|
|
257
|
-
reject(document: string, body: { paths?: string[] }): Promise<ReviewUpdate> {
|
|
379
|
+
reject(document: string, body: { paths?: string[], expected?: string }, signal?: AbortSignal): Promise<ReviewUpdate> {
|
|
258
380
|
return this.#serial(async () => {
|
|
259
|
-
const open = this.#requireOpen(document)
|
|
381
|
+
const open = this.#requireOpen(document, body.expected)
|
|
382
|
+
if (open.awaitingDeltabox) throw new RequestError(409, 'workspace-review-running')
|
|
383
|
+
await this.#expected(open, body.expected, signal)
|
|
260
384
|
if (body.paths) {
|
|
261
385
|
await open.review.restoreFiles(body.paths)
|
|
262
386
|
if ((await open.review.diff()).length > 0) return { document, review: await this.#publish(open) }
|
|
@@ -269,9 +393,11 @@ export class AgentSessionReviews {
|
|
|
269
393
|
})
|
|
270
394
|
}
|
|
271
395
|
|
|
272
|
-
restore(document: string, body: { step: string }): Promise<ReviewSnapshot> {
|
|
396
|
+
restore(document: string, body: { step: string, expected?: string }, signal?: AbortSignal): Promise<ReviewSnapshot> {
|
|
273
397
|
return this.#serial(async () => {
|
|
274
|
-
const open = this.#requireOpen(document)
|
|
398
|
+
const open = this.#requireOpen(document, body.expected)
|
|
399
|
+
if (open.awaitingDeltabox) throw new RequestError(409, 'workspace-review-running')
|
|
400
|
+
await this.#expected(open, body.expected, signal)
|
|
275
401
|
try {
|
|
276
402
|
await open.review.restoreTo!(body.step)
|
|
277
403
|
} catch (error) {
|
|
@@ -298,9 +424,10 @@ export class AgentSessionReviews {
|
|
|
298
424
|
if (open) {
|
|
299
425
|
clearTimeout(open.timer)
|
|
300
426
|
open.review.suspend()
|
|
301
|
-
open.release()
|
|
302
427
|
}
|
|
303
428
|
this.#open = undefined
|
|
429
|
+
for (const [session, workspace] of this.#workspaces) if (session !== open?.session) workspace.dispose()
|
|
430
|
+
this.#workspaces.clear()
|
|
304
431
|
}
|
|
305
432
|
|
|
306
433
|
#requireSession(document: string, session: string): OpenReview {
|
|
@@ -309,8 +436,9 @@ export class AgentSessionReviews {
|
|
|
309
436
|
return open
|
|
310
437
|
}
|
|
311
438
|
|
|
312
|
-
#requireOpen(document: string): OpenReview {
|
|
439
|
+
#requireOpen(document: string, expected?: string): OpenReview {
|
|
313
440
|
const open = this.#open
|
|
441
|
+
if (!open && expected !== undefined) throw new RequestError(409, 'workspace-review-changed')
|
|
314
442
|
if (!open) throw new RequestError(404, `no review of ${document || '.'} is open`)
|
|
315
443
|
return open
|
|
316
444
|
}
|
|
@@ -318,7 +446,7 @@ export class AgentSessionReviews {
|
|
|
318
446
|
#noteTurn(open: OpenReview, turn: number | undefined): void {
|
|
319
447
|
if (turn === undefined || !Number.isInteger(turn) || turn < 0) return
|
|
320
448
|
open.turns = { from: open.turns.from === 0 ? turn : Math.min(open.turns.from, turn), to: Math.max(open.turns.to, turn) }
|
|
321
|
-
open.review.noteSession({ session: open.session, document: open.document, member: open.member, turns: open.turns, opened: open.opened })
|
|
449
|
+
open.review.noteSession({ session: open.session, document: open.document, member: open.member, turns: open.turns, opened: open.opened, backend: open.backend })
|
|
322
450
|
}
|
|
323
451
|
|
|
324
452
|
async #publish(open: OpenReview): Promise<ReviewSnapshot> {
|
|
@@ -331,7 +459,10 @@ export class AgentSessionReviews {
|
|
|
331
459
|
async #end(open: OpenReview, ended: ReviewEnd): Promise<void> {
|
|
332
460
|
clearTimeout(open.timer)
|
|
333
461
|
this.#open = undefined
|
|
334
|
-
open.
|
|
462
|
+
if (this.#retired.delete(open.session)) {
|
|
463
|
+
this.#workspaces.delete(open.session)
|
|
464
|
+
open.workspace?.dispose()
|
|
465
|
+
}
|
|
335
466
|
this.#sendToWatchers({ document: open.document, ended })
|
|
336
467
|
this.#emit({ type: 'review', document: open.document, session: open.session, ended })
|
|
337
468
|
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process'
|
|
2
|
+
import { existsSync, lstatSync, readFileSync, readlinkSync, rmSync } from 'node:fs'
|
|
3
|
+
import { cp, lstat, mkdir, mkdtemp, readFile, readlink, rm, symlink, writeFile } from 'node:fs/promises'
|
|
4
|
+
import { dirname, join, resolve } from 'node:path'
|
|
5
|
+
import { gitConfigArgs, gitEnvironment } from '@lincyaw/kernel'
|
|
6
|
+
import type { DocumentFileChange } from '@lincyaw/kernel'
|
|
7
|
+
import type { WorkspaceConfig } from '../config.ts'
|
|
8
|
+
import { RequestError } from '../errors.ts'
|
|
9
|
+
import { validateDocumentSource, versionOf } from '../source-editor.ts'
|
|
10
|
+
import { writeChanges } from '../writer.ts'
|
|
11
|
+
import { openLocalHistory } from '../local-history.ts'
|
|
12
|
+
import { Git } from '../git.ts'
|
|
13
|
+
|
|
14
|
+
interface FileStamp { version: string, executable?: boolean, link?: true }
|
|
15
|
+
export interface AgentWorkspaceRecord { root: string, original: string, base: Record<string, FileStamp> }
|
|
16
|
+
|
|
17
|
+
function git(root: string, args: string[]): Promise<string> {
|
|
18
|
+
return new Promise((done, fail) => execFile('git', [...gitConfigArgs(), ...args], { cwd: root, env: gitEnvironment(process.env), maxBuffer: 32 << 20 }, (error, out, stderr) => error ? fail(new Error(stderr || error.message)) : done(out)))
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function stamp(file: string): FileStamp | undefined {
|
|
22
|
+
const stat = lstatSync(file, { throwIfNoEntry: false })
|
|
23
|
+
if (!stat) return
|
|
24
|
+
if (stat.isSymbolicLink()) return { version: versionOf(readlinkSync(file)), link: true }
|
|
25
|
+
if (!stat.isFile()) throw new RequestError(409, 'agent-source-type-changed')
|
|
26
|
+
return { version: versionOf(readFileSync(file)), ...stat.mode & 0o111 ? { executable: true } : {} }
|
|
27
|
+
}
|
|
28
|
+
const SANDBOX_STATE = new Set(['.deltabox', '.deltabox-lite-state'])
|
|
29
|
+
/**
|
|
30
|
+
* What a candidate copies of the author's listing: not the candidates themselves, not a sandbox's state (its live
|
|
31
|
+
* tree is a repository of its own), and not another repository inside the workspace, which git lists as `dir/`.
|
|
32
|
+
*/
|
|
33
|
+
const isAuthorFile = (path: string) => !!path && !path.endsWith('/') && !path.startsWith('.presmium/agent-workspaces/')
|
|
34
|
+
&& !path.split('/').some(part => SANDBOX_STATE.has(part))
|
|
35
|
+
const same = (a: FileStamp | undefined, b: FileStamp | undefined) => JSON.stringify(a) === JSON.stringify(b)
|
|
36
|
+
async function sourceStamp(file: string): Promise<FileStamp | undefined> {
|
|
37
|
+
let stat
|
|
38
|
+
try { stat = await lstat(file) } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return; throw error }
|
|
39
|
+
if (stat.isSymbolicLink()) return { version: versionOf(await readlink(file)), link: true }
|
|
40
|
+
if (!stat.isFile()) throw new RequestError(409, 'agent-source-type-changed')
|
|
41
|
+
return { version: versionOf(await readFile(file)), ...stat.mode & 0o111 ? { executable: true } : {} }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** An agent edits its own files; only a version-checked publication changes the author's workspace. */
|
|
45
|
+
export class AgentWorkspace {
|
|
46
|
+
readonly record: AgentWorkspaceRecord
|
|
47
|
+
readonly #config: WorkspaceConfig
|
|
48
|
+
|
|
49
|
+
private constructor(config: WorkspaceConfig, record: AgentWorkspaceRecord) { this.#config = config; this.record = record }
|
|
50
|
+
get root(): string { return this.record.root }
|
|
51
|
+
|
|
52
|
+
static async create(config: WorkspaceConfig): Promise<AgentWorkspace> {
|
|
53
|
+
const pool = join(config.root, '.presmium', 'agent-workspaces')
|
|
54
|
+
await mkdir(pool, { recursive: true })
|
|
55
|
+
await writeFile(join(pool, '.gitignore'), '*\n')
|
|
56
|
+
const root = join(await mkdtemp(join(pool, 'session-')), 'workspace')
|
|
57
|
+
await mkdir(root)
|
|
58
|
+
const workspace = new AgentWorkspace(config, { root, original: config.root, base: {} })
|
|
59
|
+
await git(root, ['init', '-q'])
|
|
60
|
+
await writeFile(join(root, '.git', 'info', 'exclude'), '.presmium/\nnode_modules/\ndist/\n.deltabox/\n.deltabox-lite-state/\n')
|
|
61
|
+
await workspace.refresh()
|
|
62
|
+
return workspace
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
static resume(config: WorkspaceConfig, record: AgentWorkspaceRecord): AgentWorkspace {
|
|
66
|
+
if (resolve(record.original) !== config.root || !resolve(record.root).startsWith(`${join(config.root, '.presmium', 'agent-workspaces')}/`) || !existsSync(join(record.root, '.git'))) throw new RequestError(409, 'agent-workspace-unavailable')
|
|
67
|
+
return new AgentWorkspace(config, record)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async refresh(): Promise<boolean> {
|
|
71
|
+
const listing = ['ls-files', '--cached', '--others', '--exclude-standard', '-z', '--', '.']
|
|
72
|
+
const listed = Git.isRepository(this.#config.root) ? await git(this.#config.root, listing) : await (await openLocalHistory(this.#config.root)).output(listing)
|
|
73
|
+
const paths = listed.split('\0').filter(isAuthorFile)
|
|
74
|
+
const next: Record<string, FileStamp> = {}
|
|
75
|
+
for (const path of new Set(paths)) {
|
|
76
|
+
const current = await sourceStamp(join(this.#config.root, path))
|
|
77
|
+
if (!current) continue
|
|
78
|
+
next[path] = current
|
|
79
|
+
if (same(current, this.record.base[path])) continue
|
|
80
|
+
const target = join(this.root, path)
|
|
81
|
+
if (same(await sourceStamp(target), current)) continue
|
|
82
|
+
await mkdir(dirname(target), { recursive: true })
|
|
83
|
+
await rm(target, { force: true, recursive: true })
|
|
84
|
+
await cp(join(this.#config.root, path), target, { dereference: false, verbatimSymlinks: true })
|
|
85
|
+
if (!same(await sourceStamp(join(this.#config.root, path)), current)) throw new RequestError(409, 'agent-source-changed', { paths: [path], next: 'The author changed a file while the candidate was refreshed. Read the current author files and retry.' })
|
|
86
|
+
}
|
|
87
|
+
for (const path of Object.keys(this.record.base)) if (!next[path]) await rm(join(this.root, path), { force: true, recursive: true })
|
|
88
|
+
const changed = JSON.stringify(next) !== JSON.stringify(this.record.base)
|
|
89
|
+
this.record.base = next
|
|
90
|
+
const dependencyDirs = new Set(['', ...paths.filter(path => path.endsWith('package.json')).map(dirname)])
|
|
91
|
+
for (const dir of dependencyDirs) {
|
|
92
|
+
let source = join(this.#config.root, dir)
|
|
93
|
+
while (!existsSync(join(source, 'node_modules')) && dirname(source) !== source) source = dirname(source)
|
|
94
|
+
const target = join(this.root, dir, 'node_modules')
|
|
95
|
+
if (existsSync(join(source, 'node_modules')) && !existsSync(target) && existsSync(dirname(target))) await symlink(join(source, 'node_modules'), target, 'dir')
|
|
96
|
+
}
|
|
97
|
+
if (changed || !(await git(this.root, ['rev-parse', '--verify', 'HEAD']).catch(() => '')).trim()) {
|
|
98
|
+
await git(this.root, ['add', '-A'])
|
|
99
|
+
await git(this.root, ['-c', 'user.name=Presmium', '-c', 'user.email=presmium@localhost', 'commit', '-q', '--allow-empty', '-m', 'Author workspace snapshot'])
|
|
100
|
+
}
|
|
101
|
+
return changed
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Caller holds the original workspace's mutation lock and history transaction. */
|
|
105
|
+
prepare(paths: string[], fixed?: DocumentFileChange[]): { changes: DocumentFileChange[], restore: DocumentFileChange[] } {
|
|
106
|
+
if (fixed && (fixed.length !== paths.length || fixed.some((change, index) => change.path !== paths[index]))) throw new RequestError(409, 'workspace-review-changed')
|
|
107
|
+
const conflicts = paths.filter(path => !same(stamp(join(this.#config.root, path)), this.record.base[path]))
|
|
108
|
+
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.' })
|
|
109
|
+
const changes: DocumentFileChange[] = [], restore: DocumentFileChange[] = []
|
|
110
|
+
for (const [index, path] of paths.entries()) {
|
|
111
|
+
if (!path || path.split('/').some(part => !part || part === '.' || part === '..' || part === '.git') || path.startsWith('.presmium/agent-workspaces/')) throw new RequestError(403, 'agent-source-path-invalid')
|
|
112
|
+
const before = stamp(join(this.#config.root, path)), after = fixed ? undefined : stamp(join(this.root, path))
|
|
113
|
+
const read = (root: string, value: FileStamp | undefined): DocumentFileChange => !value ? { path, remove: true }
|
|
114
|
+
: value.link ? { path, link: readlinkSync(join(root, path)) } : { path, content: readFileSync(join(root, path)), ...value.executable ? { executable: true } : {} }
|
|
115
|
+
const change = fixed?.[index] ?? read(this.root, after)
|
|
116
|
+
if ('content' in change) validateDocumentSource(path, Buffer.from(change.content).toString('utf8'), before && !before.link ? readFileSync(join(this.#config.root, path)) : undefined)
|
|
117
|
+
changes.push(change); restore.push(read(this.#config.root, before))
|
|
118
|
+
}
|
|
119
|
+
return { changes, restore }
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
write(changes: DocumentFileChange[]): void { writeChanges(this.#config, changes, true) }
|
|
123
|
+
dispose(): void { rmSync(dirname(this.root), { recursive: true, force: true }) }
|
|
124
|
+
}
|