@lincyaw/workspace 1.0.0-rc.121 → 1.0.0-rc.123

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.121",
3
+ "version": "1.0.0-rc.123",
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,13 +34,13 @@
34
34
  "mime-types": "3.0.2",
35
35
  "playwright-chromium": "1.64.1",
36
36
  "yaml": "^2.9.1",
37
- "@lincyaw/server": "1.0.0-rc.121",
38
- "@lincyaw/design": "1.0.0-rc.121",
39
- "@lincyaw/compiler": "1.0.0-rc.121",
40
- "@lincyaw/kernel": "1.0.0-rc.121"
37
+ "@lincyaw/compiler": "1.0.0-rc.123",
38
+ "@lincyaw/kernel": "1.0.0-rc.123",
39
+ "@lincyaw/server": "1.0.0-rc.123",
40
+ "@lincyaw/design": "1.0.0-rc.123"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@types/mime-types": "^3.0.1",
44
- "@lincyaw/mcp": "1.0.0-rc.121"
44
+ "@lincyaw/mcp": "1.0.0-rc.123"
45
45
  }
46
46
  }
@@ -1,9 +1,9 @@
1
1
  import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs'
2
2
  import { join, resolve } from 'node:path'
3
- import { effectiveDocumentIn, providedDocuments, inheritedSettingsIn, WORKSPACE_CONFIG, workspaceDefaults, workspaceDocuments, workspaceSettings } from '@lincyaw/compiler'
3
+ import { effectiveDocumentIn, providedDocuments, inheritedSettingsIn, settingOriginsIn, WORKSPACE_CONFIG, workspaceDefaults, workspaceDocuments, workspaceSettings } from '@lincyaw/compiler'
4
4
  import type { OperatorSettings, WorkspaceDocuments } from '@lincyaw/compiler'
5
5
  import { APPROVAL_KINDS, DOCUMENT_ENTRY, errorMessage, isRecord } from '@lincyaw/kernel'
6
- import type { ApprovalKind, DocumentDefaults, DocumentSummary, EffectiveDocument, PresmiumDocument } from '@lincyaw/kernel'
6
+ import type { ApprovalKind, DocumentDefaults, DocumentSummary, EffectiveDocument, PresmiumDocument, SettingOrigins } from '@lincyaw/kernel'
7
7
  import type { ApprovalPolicy } from '@lincyaw/server'
8
8
  import { parse as parseYaml } from 'yaml'
9
9
 
@@ -220,3 +220,8 @@ export function effectiveContent(config: WorkspaceConfig, dir: string, content:
220
220
  export function inheritedContent(config: WorkspaceConfig, dir: string, content: PresmiumDocument): DocumentDefaults {
221
221
  return inheritedSettingsIn(config.root, join(config.root, dir ? `${dir}/${DOCUMENT_ENTRY}` : DOCUMENT_ENTRY), content)
222
222
  }
223
+
224
+ /** Which ancestor (or the workspace defaults, null) each setting the document in `dir` inherits comes from. */
225
+ export function inheritedOrigins(config: WorkspaceConfig, dir: string, content: PresmiumDocument): SettingOrigins {
226
+ return settingOriginsIn(config.root, join(config.root, dir ? `${dir}/${DOCUMENT_ENTRY}` : DOCUMENT_ENTRY), content)
227
+ }
@@ -61,7 +61,7 @@ export function createDocumentEditor({ editor, revisions, reviewRequired = false
61
61
  }
62
62
  const read = async (document: string, member: Member): Promise<DocumentAnswer> => {
63
63
  const { source, content, effective, issues } = readAuthoringDocument(editor, { document, member })
64
- return { document, version: source.version, fingerprint: fnv1a64(source.content), content, settings: documentSettings(effective), inherited: editor.inherited(document, content), issues }
64
+ return { document, version: source.version, fingerprint: fnv1a64(source.content), content, settings: documentSettings(effective), inherited: editor.inherited(document, content), inheritedFrom: editor.inheritedFrom(document, content), issues }
65
65
  }
66
66
  const readSelection = <T>(document: string, expected: CanonicalSource | undefined, member: Member, select: (content: PresmiumDocument, source: CanonicalSource) => T): T => {
67
67
  if (!hasRole(member, 'editor')) throw new RequestError(403, 'authoring-permission-denied')
@@ -6,7 +6,7 @@ import { setImmediate as yieldToEvents } from 'node:timers/promises'
6
6
  import { provideDocumentEntries } from '@lincyaw/compiler'
7
7
  import type { ScannedDocument } from '@lincyaw/compiler'
8
8
  import { blockFirstText, blockSubtree, DOCUMENT_ENTRY, documentCitationSites, documentSearchText, documentTree, isRecord, targetExcerpt } from '@lincyaw/kernel'
9
- import type { BlockId, DocumentCitation, DocumentId, DocumentLinks, DocumentPlacement, DocumentPreview, DocumentSearchHit, DocumentTree, EmbedSource, OutgoingLink, PlacementTree, PresmiumDocument, ReferenceTarget, SectionId, TrashEntry, TreeIssue, TreeNode } from '@lincyaw/kernel'
9
+ import type { AttentionCount, BlockId, DocumentCitation, DocumentId, DocumentLinks, DocumentPlacement, DocumentPreview, DocumentSearchHit, DocumentTree, EmbedSource, OutgoingLink, PlacementTree, PresmiumDocument, ReferenceTarget, SectionId, TrashEntry, TreeIssue, TreeNode, WorkspaceAttention } from '@lincyaw/kernel'
10
10
  import { primeDocumentHead } from './config.ts'
11
11
  import type { WorkspaceConfig } from './config.ts'
12
12
 
@@ -128,6 +128,9 @@ export class DocumentIndex {
128
128
  readonly #watchers = new Map<string, FSWatcher>()
129
129
  readonly #listeners = new Set<() => void>()
130
130
  readonly #titleListeners = new Set<(changed: DocumentId[]) => void>()
131
+ readonly #attentionListeners = new Set<() => void>()
132
+ /** The attention summary of one generation of the index, with its text to tell a change. */
133
+ #attention?: { generation: number, value: WorkspaceAttention, text: string }
131
134
  #derived?: Derived
132
135
  #dirty = new Set<string>()
133
136
  readonly #folders = new Set<string>()
@@ -166,6 +169,7 @@ export class DocumentIndex {
166
169
  this.#watchers.clear()
167
170
  this.#listeners.clear()
168
171
  this.#titleListeners.clear()
172
+ this.#attentionListeners.clear()
169
173
  }
170
174
 
171
175
  /** Resolves once everything known to have changed has been read. */
@@ -355,6 +359,11 @@ export class DocumentIndex {
355
359
  const titleChanged = changes.flatMap(change => change.after && change.before?.titleKey !== change.after.titleKey ? [change.after.id] : [])
356
360
  if (before && treeChanged) for (const listener of [...this.#listeners]) listener()
357
361
  if (before && titleChanged.length) for (const listener of [...this.#titleListeners]) listener(titleChanged)
362
+ if (before && this.#attentionListeners.size) {
363
+ const was = this.#attention?.text
364
+ this.attention()
365
+ if (this.#attention!.text !== was) for (const listener of [...this.#attentionListeners]) listener()
366
+ }
358
367
  }
359
368
 
360
369
  /** One document changed without changing the tree: only its own entries are replaced. */
@@ -473,7 +482,10 @@ export class DocumentIndex {
473
482
  for (const node of tree.order) {
474
483
  nodes[node.id] = { id: node.id, title: node.title, path: dirOf(node.path), parent: node.parent, rank: node.placement.rank, depth: node.depth, children: [...tree.children.get(node.id) ?? []], ...issues.has(node.id) ? { issues: issues.get(node.id) } : {} }
475
484
  }
476
- const trash: TrashEntry[] = [...this.#trash.values()].filter(entry => !entry.record.with).map(entry => ({ id: entry.id, title: entry.title, deletedAt: entry.record.deletedAt, from: entry.record.from, parent: entry.record.parent, children: entry.record.children }))
485
+ const trash: TrashEntry[] = [...this.#trash.values()].filter(entry => !entry.record.with).map((entry) => {
486
+ const parent = entry.record.parent
487
+ return { id: entry.id, title: entry.title, deletedAt: entry.record.deletedAt, from: entry.record.from, parent, children: entry.record.children, ...parent !== null && !documents.has(parent) && this.#trash.has(parent) ? { parentTrashed: true } : {} }
488
+ })
477
489
  trash.sort((a, b) => a.deletedAt < b.deletedAt ? 1 : a.deletedAt > b.deletedAt ? -1 : 0)
478
490
  return derived.clientTree = { roots: [...tree.children.get(null) ?? []], nodes, trash }
479
491
  }
@@ -566,6 +578,36 @@ export class DocumentIndex {
566
578
  return { document: id, title: document.metadata.title, block, blocks, ...Object.keys(assets).length ? { assets } : {}, ...states ? { states } : {}, ...located.trashed ? { trashed: true } : {} }
567
579
  }
568
580
 
581
+ /**
582
+ * References and synced blocks whose target is gone or in the trash, counted across the workspace. One pass over the
583
+ * references the index keeps, at most once per change of the index.
584
+ */
585
+ attention(): WorkspaceAttention {
586
+ const { documents, order } = this.#now()
587
+ if (this.#attention?.generation === this.#generation) return this.#attention.value
588
+ const counts = { reference: undefined as AttentionCount | undefined, embed: undefined as AttentionCount | undefined }
589
+ for (const id of order) {
590
+ const entry = documents.get(id)
591
+ if (!entry) continue
592
+ const counted = new Set<'reference' | 'embed'>()
593
+ for (const site of entry.sites) {
594
+ if (this.titleOf(site.target, true) !== undefined) continue
595
+ const count = counts[site.kind] ??= { places: 0, documents: 0, first: { document: id, ...site.section !== undefined ? { section: site.section } : {}, block: site.block } }
596
+ count.places++
597
+ if (!counted.has(site.kind)) { counted.add(site.kind); count.documents++ }
598
+ }
599
+ }
600
+ const value: WorkspaceAttention = { ...counts.reference ? { references: counts.reference } : {}, ...counts.embed ? { embeds: counts.embed } : {} }
601
+ this.#attention = { generation: this.#generation, value, text: JSON.stringify(value) }
602
+ return value
603
+ }
604
+
605
+ /** Called whenever what `attention` answers has changed. */
606
+ onAttention(listener: () => void): () => void {
607
+ this.#attentionListeners.add(listener)
608
+ return () => { this.#attentionListeners.delete(listener) }
609
+ }
610
+
569
611
  /** The documents whose references may show an outdated fallback after the titles of `changed` changed: those citing them, and themselves. */
570
612
  citing(changed: DocumentId[]): IndexEntry[] {
571
613
  const { documents, incoming } = this.#now()
@@ -0,0 +1,80 @@
1
+ import { existsSync, rmSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import { DOCUMENT_ENTRY, DOCUMENT_MATERIALS_DIR, DOCUMENT_MATERIALS_MAX_BYTES, DOCUMENT_MATERIALS_MAX_FILES, hasRole, jsonResponse } from '@lincyaw/kernel'
4
+ import type { DocumentMaterialsAnswer, Route } from '@lincyaw/kernel'
5
+ import type { WorkspaceConfig } from './config.ts'
6
+ import { catchRequestErrors, RequestError } from './errors.ts'
7
+ import type { DocumentLocks } from './locks.ts'
8
+ import type { Revisions } from './revisions.ts'
9
+ import type { DocumentWriter } from './writer.ts'
10
+
11
+ const NAME_MAX = 120
12
+ const bad = (status: number, code: string): never => { throw new RequestError(status, `document-materials-${code}`) }
13
+
14
+ /** A file name that stays one plain name in the materials folder: no folders, control characters or leading dots. */
15
+ function plainName(name: string): string {
16
+ const base = (name.split(/[\\/]/).at(-1) ?? '').replace(/[\u0000-\u001f\u007f:*?"<>|]/g, '').replace(/^[.\s]+/, '').trim()
17
+ if (!base) return 'material'
18
+ if ([...base].length <= NAME_MAX) return base
19
+ const dot = base.lastIndexOf('.'), extension = dot > 0 && base.length - dot <= 12 ? base.slice(dot) : ''
20
+ return [...base.slice(0, base.length - extension.length)].slice(0, NAME_MAX - extension.length).join('') + extension
21
+ }
22
+
23
+ /** `name`, or `name (2)`, `name (3)`… before its extension, whichever is not taken yet. */
24
+ function freeName(name: string, taken: (name: string) => boolean): string {
25
+ if (!taken(name)) return name
26
+ const dot = name.lastIndexOf('.'), stem = dot > 0 ? name.slice(0, dot) : name, extension = dot > 0 ? name.slice(dot) : ''
27
+ for (let n = 2; ; n++) {
28
+ const next = `${stem} (${n})${extension}`
29
+ if (!taken(next)) return next
30
+ }
31
+ }
32
+
33
+ /**
34
+ * Adds the author's source material (PDF, Word, slides, pictures, text…) to a document: the files are kept as they
35
+ * are in the document's `materials/` folder, under its lock and recorded as one revision, for the AI to write the
36
+ * document from. Nothing in the document refers to them.
37
+ */
38
+ export function documentMaterialsRoute(options: { config: WorkspaceConfig, writer: DocumentWriter, locks: DocumentLocks, revisions?: Revisions }): Route {
39
+ const { config, writer, locks, revisions } = options
40
+ return {
41
+ role: 'editor',
42
+ maxBody: DOCUMENT_MATERIALS_MAX_BYTES + (1 << 20),
43
+ handle: (request, ctx) => catchRequestErrors(async () => {
44
+ if (request.method !== 'POST') return bad(405, 'method')
45
+ if (!hasRole(ctx.member, 'editor')) return bad(403, 'forbidden')
46
+ const dir = ctx.document
47
+ if (!existsSync(join(config.root, dir, DOCUMENT_ENTRY))) return bad(404, 'document')
48
+ const form = await request.formData().catch(() => bad(400, 'invalid'))
49
+ const uploads = form.getAll('files')
50
+ if (uploads.length === 0 || uploads.some(file => typeof file === 'string')) return bad(400, 'invalid')
51
+ const files = uploads as File[]
52
+ if (files.length > DOCUMENT_MATERIALS_MAX_FILES || files.reduce((sum, file) => sum + file.size, 0) > DOCUMENT_MATERIALS_MAX_BYTES) return bad(413, 'limit')
53
+ const folder = dir ? `${dir}/${DOCUMENT_MATERIALS_DIR}` : DOCUMENT_MATERIALS_DIR
54
+ const release = await locks.acquire(dir, 'document:materials')
55
+ try {
56
+ const write = async (): Promise<DocumentMaterialsAnswer> => {
57
+ const names: string[] = []
58
+ for (const file of files) names.push(freeName(plainName(file.name), name => names.includes(name) || existsSync(join(config.root, folder, name))))
59
+ const paths = names.map(name => `${folder}/${name}`)
60
+ if (revisions && await revisions.ignoresAny(paths)) return bad(403, 'forbidden')
61
+ await revisions?.checkpoint(paths)
62
+ const written: string[] = []
63
+ try {
64
+ for (const [index, file] of files.entries()) {
65
+ request.signal.throwIfAborted()
66
+ await writer.create(paths[index]!, new Uint8Array(await file.arrayBuffer()))
67
+ written.push(paths[index]!)
68
+ }
69
+ const revision = revisions ? await revisions.commitWhileLocked({ paths, summary: `Add source material to ${dir || 'the document'}`, body: names.join('\n'), origin: { kind: 'editor', member: ctx.member } }) : undefined
70
+ return { files: names.map(name => `${DOCUMENT_MATERIALS_DIR}/${name}`), ...revision ? { revision } : {} }
71
+ } catch (error) {
72
+ for (const path of written) rmSync(join(config.root, path), { force: true })
73
+ throw error
74
+ }
75
+ }
76
+ return jsonResponse(await (revisions ? revisions.transaction(write) : write()), 201)
77
+ } finally { release() }
78
+ }),
79
+ }
80
+ }
@@ -66,6 +66,7 @@ export interface WorkspaceRoutesOptions {
66
66
  authoringClientRoutes?: Record<string, Route>
67
67
  projectRoutes?: Record<string, Route>
68
68
  documentImport?: Route
69
+ documentMaterials?: Route
69
70
  workspaceMigrate?: Route
70
71
  mcpSettings?: Route
71
72
  speechSettings?: Route
@@ -144,6 +145,7 @@ export function workspaceRoutes(options: WorkspaceRoutesOptions): ServerContribu
144
145
  ...options.authoringClientRoutes,
145
146
  ...options.projectRoutes,
146
147
  ...options.documentImport ? { 'documents/import': options.documentImport } : {},
148
+ ...options.documentMaterials ? { 'document/materials': options.documentMaterials } : {},
147
149
  ...options.workspaceMigrate ? { 'workspace/migrate': options.workspaceMigrate } : {},
148
150
  'files': {
149
151
  role: 'editor',
package/src/node/serve.ts CHANGED
@@ -53,6 +53,7 @@ import { localWriter } from './writer.ts'
53
53
  import { DocumentIndex } from './document-index.ts'
54
54
  import { TreeOperations } from './tree-operations.ts'
55
55
  import { documentImportRoute } from './document-import.ts'
56
+ import { documentMaterialsRoute } from './document-materials.ts'
56
57
  import { workspaceMigrateRoute } from './workspace-migrate.ts'
57
58
  import { hostUpgradeRoute } from './host-upgrade.ts'
58
59
  import { createHostActivity } from './host-activity.ts'
@@ -527,6 +528,7 @@ async function startWorkspace(options: ServeOptions): Promise<WorkspaceServer> {
527
528
  authoringClientRoutes: { ...authoringClients.routes, ...authoringWindows.routes, ...agentActivity.routes },
528
529
  projectRoutes: projectAuthoring.routes,
529
530
  documentImport: documentImportRoute({ config, writer, locks, revisions: history?.revisions, changed: documentsChanged }),
531
+ documentMaterials: documentMaterialsRoute({ config, writer, locks, revisions: history?.revisions }),
530
532
  workspaceMigrate: workspaceMigrateRoute({ config, locks, revisions: history?.revisions, changed: documentsChanged }),
531
533
  locks,
532
534
  ...history ? { revisions: history.revisions, operations: history.operations, reviews: history.agentSessionReviews } : {},
@@ -3,9 +3,9 @@ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, readdir
3
3
  import { join } from 'node:path'
4
4
  import { WORKSPACE_CONFIG } from '@lincyaw/compiler'
5
5
  import { DOCUMENT_ENTRY, SOURCE_MAX_BYTES, SOURCE_MAX_FILES } from '@lincyaw/kernel'
6
- import type { ConflictAnswer, DocumentFileChange, FilesAnswer, Member, Revision, SavedAnswer, SourceAnswer, SourceFile, SourceTransactionAnswer, SourceTransactionChange, DocumentDefaults, EffectiveDocument, PresmiumDocument } from '@lincyaw/kernel'
6
+ import type { ConflictAnswer, DocumentFileChange, FilesAnswer, Member, Revision, SavedAnswer, SourceAnswer, SourceFile, SourceTransactionAnswer, SourceTransactionChange, DocumentDefaults, EffectiveDocument, PresmiumDocument, SettingOrigins } from '@lincyaw/kernel'
7
7
  import { isWithin } from '../domain/paths.ts'
8
- import { effectiveContent, inheritedContent, listDocumentEntries, readDocumentSummary } from './config.ts'
8
+ import { effectiveContent, inheritedContent, inheritedOrigins, listDocumentEntries, readDocumentSummary } from './config.ts'
9
9
  import type { DocumentEntry, WorkspaceConfig } from './config.ts'
10
10
  import { RequestError } from './errors.ts'
11
11
  import { checkDocumentText } from './document-check.ts'
@@ -83,6 +83,11 @@ export class SourceEditor {
83
83
  return inheritedContent(this.#config, document, content)
84
84
  }
85
85
 
86
+ /** Which ancestor (or the workspace defaults, null) each setting the document in `document` inherits comes from. */
87
+ inheritedFrom(document: string, content: PresmiumDocument): SettingOrigins {
88
+ return inheritedOrigins(this.#config, document, content)
89
+ }
90
+
86
91
  scope(document: string): Scope {
87
92
  return { document, home: document === '' && !this.#config.singleDeck }
88
93
  }
@@ -189,7 +189,7 @@ export class TreeOperations {
189
189
  * Runs the operation's changes under the documents' locks and the history's lock, then records them as one revision;
190
190
  * on any failure every change is undone and nothing is recorded.
191
191
  */
192
- async #run(kind: TreeOperation['type'], locked: string[], member: Member, origin: 'editor' | 'agent', work: (journal: Journal) => Promise<{ summary: string, body?: string, documents: DocumentId[], created?: DocumentId, converted?: TreeOperationResult['converted'] }>, automatic = false): Promise<TreeOperationResult> {
192
+ async #run(kind: TreeOperation['type'], locked: string[], member: Member, origin: 'editor' | 'agent', work: (journal: Journal) => Promise<{ summary: string, body?: string, documents: DocumentId[], created?: DocumentId, converted?: TreeOperationResult['converted'], toTopLevel?: TreeOperationResult['toTopLevel'] }>, automatic = false): Promise<TreeOperationResult> {
193
193
  const { locks, revisions, index } = this.#options
194
194
  await index.ready()
195
195
  const before = this.#dirs()
@@ -219,6 +219,7 @@ export class TreeOperations {
219
219
  ...done.created ? { created: done.created } : {},
220
220
  revisions: done.revision ? done.documents.map(document => ({ document, revision: done.revision! })) : [],
221
221
  ...done.converted?.length ? { converted: done.converted } : {},
222
+ ...done.toTopLevel?.length ? { toTopLevel: done.toTopLevel } : {},
222
223
  }
223
224
  }
224
225
 
@@ -308,6 +309,7 @@ export class TreeOperations {
308
309
  const live = index.scan().documents
309
310
  const taken = this.#dirs()
310
311
  const restored = new Set(ids)
312
+ const toTopLevel: NonNullable<TreeOperationResult['toTopLevel']> = []
311
313
  for (const id of ids) {
312
314
  const item = trashed.get(id)!
313
315
  const free = (dir: string) => isDocumentDir(this.#options.config, dir) && !existsSync(join(this.#root, dir)) && !taken.some(other => other !== '' && (isWithin(dir, other) || isWithin(other, dir)))
@@ -321,9 +323,10 @@ export class TreeOperations {
321
323
  const document = this.#read(dir)
322
324
  document.placement = { parent: null, rank: this.#rankAfter(null, (index.scan().tree?.children.get(null) ?? []).at(-1)) }
323
325
  await this.#write(journal, dir, document)
326
+ toTopLevel.push({ document: id, parent: trashed.has(parent) ? 'trashed' : 'missing' })
324
327
  }
325
328
  }
326
- return { summary: `Restore document ${entry.title}`, documents: ids }
329
+ return { summary: `Restore document ${entry.title}`, documents: ids, toTopLevel }
327
330
  })
328
331
  }
329
332
  case 'purge': {
@@ -29,8 +29,9 @@ export function treeOperationOf(body: unknown): TreeOperation | undefined {
29
29
 
30
30
  /**
31
31
  * The document tree's routes (`docs/authoring-actions.md`): the tree with its trash, tree operations, a document's
32
- * references in both directions, search, a reference's preview card, a synced block's source, and `tree/events`, which
33
- * sends `{ type: 'tree' }` (event `tree`) whenever the tree or the trash changes.
32
+ * references in both directions, search, a reference's preview card, a synced block's source, what needs attention
33
+ * across the workspace, and `tree/events`, which sends `{ type: 'tree' }` (event `tree`) whenever the tree or the trash
34
+ * changes and `{ type: 'attention' }` whenever what `tree/attention` answers changes.
34
35
  */
35
36
  export function treeRoutes(index: DocumentIndex, operations: TreeOperations | undefined): Record<string, Route> {
36
37
  const params = (request: Request) => new URL(request.url).searchParams
@@ -76,11 +77,16 @@ export function treeRoutes(index: DocumentIndex, operations: TreeOperations | un
76
77
  }),
77
78
  'document/preview': get(request => index.preview(required(request, 'id'), { ...optional(request, 'section') !== undefined ? { section: optional(request, 'section') } : {}, ...optional(request, 'block') !== undefined ? { block: optional(request, 'block') } : {} })),
78
79
  'embed/source': get(request => index.embedSource(required(request, 'document'), required(request, 'block'))),
80
+ 'tree/attention': get(() => index.attention()),
79
81
  'tree/events': {
80
82
  role: 'reader',
81
83
  handle: async (request) => {
82
84
  if (request.method !== 'GET') return jsonResponse({ error: 'GET' }, 405)
83
- const stream = pushStream<{ event: string, data: { type: 'tree' } }>(push => index.subscribe(() => push({ event: 'tree', data: { type: 'tree' } })), { signal: request.signal })
85
+ const stream = pushStream<{ event: string, data: { type: 'tree' | 'attention' } }>((push) => {
86
+ const offTree = index.subscribe(() => push({ event: 'tree', data: { type: 'tree' } }))
87
+ const offAttention = index.onAttention(() => push({ event: 'tree', data: { type: 'attention' } }))
88
+ return () => { offTree(); offAttention() }
89
+ }, { signal: request.signal })
84
90
  return sseResponse(stream, request.signal)
85
91
  },
86
92
  },