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

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.44",
3
+ "version": "1.0.0-rc.45",
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.44",
38
- "@lincyaw/server": "1.0.0-rc.44",
39
- "@lincyaw/kernel": "1.0.0-rc.44"
37
+ "@lincyaw/kernel": "1.0.0-rc.45",
38
+ "@lincyaw/compiler": "1.0.0-rc.45",
39
+ "@lincyaw/server": "1.0.0-rc.45"
40
40
  },
41
41
  "devDependencies": {
42
42
  "@types/mime-types": "^3.0.1",
43
- "@lincyaw/mcp": "1.0.0-rc.44"
43
+ "@lincyaw/mcp": "1.0.0-rc.45"
44
44
  }
45
45
  }
@@ -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
- async snapshot(): Promise<ReviewSnapshot | undefined> {
153
- const open = this.#open
154
- return open && await this.#snapshotOf(open)
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
- try { return await this.#accept(open, body.reject ?? [], body.message) }
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 await open.review.diff()) if (isInGitDir(change.path)) rejected.add(change.path)
288
- const files = await open.review.prepareAccept([...rejected])
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
- const prepared = open.workspace!.prepare(files)
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 status = (await this.#text([...DIFF, '--name-status', '-z', from, to])).split('\0').filter(Boolean)
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 #write(tree: string, paths: string[]): Promise<void> {
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 [meta = '', path = ''] = entry.split('\t')
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
- await this.#files!.write(changes)
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
- async diff() {
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
- return trees.compare(snapshot, await trees.tree())
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,7 @@ 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'
26
27
  import { createTaskReviewService } from './review/task-reviews.ts'
27
28
  import { Revisions } from './revisions.ts'
28
29
  import { WORKSPACE_ID, authorizeWorkspaceRoutes, workspaceRoutes, workspaceRoutesPlugin } from './routes.ts'
@@ -116,6 +117,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
116
117
  let history: WorkspaceHistory | undefined
117
118
  let documentEditor: DocumentEditor | undefined
118
119
  let documentHistory: ReturnType<typeof createDocumentHistory> | undefined
120
+ let workspaceReview: ReturnType<typeof createWorkspaceReview> | undefined
119
121
  let projectAuthoring: ReturnType<typeof createProjectAuthoring> | undefined
120
122
  let authoringClients: ReturnType<typeof createAuthoringClients> | undefined
121
123
  let transcriptions: ReturnType<typeof createDocumentTranscriptions> | undefined
@@ -272,6 +274,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
272
274
  get imageAuthoring() { return imageAuthoring?.service },
273
275
  get voiceAuthoring() { return voiceAuthoring?.service },
274
276
  speechSettings,
277
+ get workspaceReview() { return workspaceReview },
275
278
  get transcriptions() { return transcriptions },
276
279
  get transcriptionAdoption() { return transcriptionAdoption?.service },
277
280
  get capture() { return capture?.service },
@@ -384,6 +387,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
384
387
  voiceAuthoring = createDocumentVoiceAuthoring({ editor, services: authoringServices, revision: document => { const latest = compileSessions.get(document)?.latest; return latest ? irRevision(latest.doc) : undefined } })
385
388
  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
389
  history = openHistory()
390
+ workspaceReview = history && createWorkspaceReview(history.agentSessionReviews)
387
391
  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
392
  projectAuthoring = createProjectAuthoring({ config, documentEditor, operations: history?.operations, revisions: history?.revisions, git: history?.git })
389
393
  authoringClients = createAuthoringClients(editor, { reviewRequired: config.settings['presmium.assistant']?.review === 'required' })