@lincyaw/kernel 1.0.0-rc.6 → 1.0.0-rc.61

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.
Files changed (57) hide show
  1. package/README.md +1 -1
  2. package/package.json +4 -2
  3. package/src/authoring.ts +2 -0
  4. package/src/contracts/authoring-actions.ts +3 -3
  5. package/src/contracts/authoring-clients.ts +94 -6
  6. package/src/contracts/authoring-windows.ts +47 -0
  7. package/src/contracts/authoring.ts +1 -1
  8. package/src/contracts/capture.ts +148 -0
  9. package/src/contracts/document-audio.ts +8 -6
  10. package/src/contracts/document-image.ts +7 -5
  11. package/src/contracts/document-voice.ts +35 -2
  12. package/src/contracts/document.ts +16 -1
  13. package/src/contracts/media-uploads.ts +28 -0
  14. package/src/contracts/plugin.ts +1 -3
  15. package/src/contracts/preview.ts +3 -3
  16. package/src/contracts/projects.ts +4 -1
  17. package/src/contracts/speech-settings.ts +13 -0
  18. package/src/contracts/speech.ts +16 -0
  19. package/src/contracts/voiceover-execution.ts +25 -1
  20. package/src/contracts/workspace-changes.ts +27 -0
  21. package/src/contracts/workspace-review.ts +39 -0
  22. package/src/contracts/workspace-source.ts +38 -0
  23. package/src/contracts/workspace.ts +2 -0
  24. package/src/contracts.ts +6 -0
  25. package/src/document-authoring-actions.ts +23 -4
  26. package/src/document-caption-scale.ts +17 -0
  27. package/src/document-comments.ts +30 -37
  28. package/src/document-components.ts +4 -12
  29. package/src/document-narrations.ts +57 -0
  30. package/src/document-operations.ts +32 -2
  31. package/src/document-pages.ts +8 -1
  32. package/src/document-places.ts +92 -0
  33. package/src/document-schema.ts +3 -3
  34. package/src/document.ts +13 -1
  35. package/src/embed.ts +26 -0
  36. package/src/escape-html.ts +4 -0
  37. package/src/html.ts +1 -4
  38. package/src/index.ts +15 -6
  39. package/src/ir.ts +23 -48
  40. package/src/lower-myst.ts +3 -12
  41. package/src/myst-marks.ts +15 -0
  42. package/src/node/authoring-actions.ts +3 -1
  43. package/src/node/authoring-windows.ts +11 -0
  44. package/src/node/document-voice.ts +6 -2
  45. package/src/node/fonts.ts +6 -3
  46. package/src/node/index.ts +9 -3
  47. package/src/node/operator-speech.ts +4 -0
  48. package/src/node/packages.ts +25 -0
  49. package/src/node/service-state.ts +52 -0
  50. package/src/node/workspace-changes.ts +7 -0
  51. package/src/node/workspace-review.ts +9 -0
  52. package/src/node/workspace-source.ts +10 -0
  53. package/src/preview-events.ts +6 -4
  54. package/src/preview-frame-connect.ts +1105 -0
  55. package/src/preview-frame.ts +30 -1120
  56. package/src/random-uuid.ts +8 -0
  57. package/src/stale-module.ts +15 -0
@@ -1,7 +1,8 @@
1
1
  import type { CanonicalSource } from '../ir.ts'
2
+ import type { Schema } from '@cfworker/json-schema'
2
3
  import type { Finding } from './checks.ts'
3
4
  import type { Member } from './server.ts'
4
- import type { SpeechEngineInfo } from './speech.ts'
5
+ import type { SpeechEngineInfo, VoiceCloneRequest, VoiceCloneStatus } from './speech.ts'
5
6
  import type { VoiceCatalogAnswer, VoiceoverCancellation } from './voice.ts'
6
7
  import type { DocumentVoiceTasks, VoiceoverJobQuery, VoiceoverStart, VoicePreviewStart } from './voiceover-execution.ts'
7
8
 
@@ -16,13 +17,29 @@ export interface DocumentVoiceCapabilities {
16
17
  preview: boolean
17
18
  engines: SpeechEngineInfo[]
18
19
  defaultEngine?: string
19
- actions: { status: boolean, list: true, get: true, start: boolean, cancel: true, quotePreview: boolean, preview: boolean, readPreview: true }
20
+ actions: { status: boolean, list: true, get: true, start: boolean, cancel: true, quotePreview: boolean, preview: boolean, readPreview: true, clone?: boolean, cloneStatus?: boolean }
20
21
  tasks: { idempotency: 'process', limits: { intents: number, recentJobs: number, concurrent: number, quotes: number, quoteLifetimeMs: number, previewBytes: number, previewResources: number, retainedPreviewBytes: number } }
21
22
  findings?: Finding[]
22
23
  }
23
24
  export interface DocumentVoiceCatalogQuery { source?: CanonicalSource, engine?: string, lang?: string }
24
25
  export interface DocumentVoiceCatalogAnswer extends VoiceCatalogAnswer { document: string, source: CanonicalSource, findings?: Finding[] }
25
26
 
27
+ export const VOICE_CLONE_MAX_AUDIO_BYTES = 10 << 20
28
+ /** Files are scoped workspace paths; the service reads and fixes their bytes before spending approval. */
29
+ export type DocumentVoiceCloneRequest = Omit<VoiceCloneRequest, 'sample' | 'consent'> & {
30
+ source?: CanonicalSource
31
+ sample: string
32
+ consent: { speaker: string, scope: string, statement: string }
33
+ }
34
+ export interface DocumentVoiceCloneQuery { engine?: string, voice: string }
35
+ /** A process-local capability for this call, never a model argument or a retained plan. */
36
+ export interface PreparedVoiceClone {
37
+ engine: string
38
+ voice: string
39
+ start(signal?: AbortSignal): Promise<VoiceCloneStatus>
40
+ close(): void
41
+ }
42
+
26
43
  /** Shared voice discovery and explicitly authorized tasks; discovery never compiles or synthesizes. */
27
44
  export interface DocumentVoiceAuthoring extends DocumentVoiceTasks {
28
45
  capabilities(document: string, member: Member, signal?: AbortSignal): Promise<DocumentVoiceCapabilities>
@@ -32,6 +49,8 @@ export interface DocumentVoiceAuthoring extends DocumentVoiceTasks {
32
49
  checkPreview(document: string, request: VoicePreviewStart, member: Member, signal?: AbortSignal): Promise<void>
33
50
  /** Undefined when there is something to cancel; otherwise the unchanged state that cancel would report. */
34
51
  checkCancel(document: string, query: VoiceoverJobQuery, member: Member): Promise<VoiceoverCancellation | undefined>
52
+ prepareClone?(document: string, request: DocumentVoiceCloneRequest, member: Member, signal?: AbortSignal): Promise<PreparedVoiceClone>
53
+ cloneStatus?(document: string, query: DocumentVoiceCloneQuery, member: Member, signal?: AbortSignal): Promise<VoiceCloneStatus>
35
54
  }
36
55
 
37
56
  export const DOCUMENT_VOICE_CATALOG_SCHEMA = {
@@ -42,3 +61,17 @@ export const DOCUMENT_VOICE_CATALOG_SCHEMA = {
42
61
  lang: { type: 'string', minLength: 1, maxLength: 100 },
43
62
  },
44
63
  } as const
64
+
65
+ const cloneText = { type: 'string', minLength: 1, maxLength: 200 } as const
66
+ export const DOCUMENT_VOICE_CLONE_QUERY_SCHEMA: Schema = {
67
+ type: 'object', additionalProperties: false, properties: { engine: cloneText, voice: cloneText }, required: ['voice'],
68
+ }
69
+ export const DOCUMENT_VOICE_CLONE_SCHEMA: Schema = {
70
+ type: 'object', additionalProperties: false,
71
+ properties: {
72
+ source: structuredClone(DOCUMENT_VOICE_CATALOG_SCHEMA.properties.source) as unknown as Schema, engine: cloneText, voice: cloneText,
73
+ sample: { type: 'string', minLength: 1, maxLength: 1024 },
74
+ consent: { type: 'object', additionalProperties: false, properties: { speaker: cloneText, scope: { type: 'string', minLength: 1, maxLength: 2000 }, statement: { type: 'string', minLength: 1, maxLength: 1024 } }, required: ['speaker', 'scope', 'statement'] },
75
+ lang: { type: 'string', minLength: 1, maxLength: 100 }, text: { type: 'string', maxLength: 4000 },
76
+ }, required: ['voice', 'sample', 'consent'],
77
+ }
@@ -194,11 +194,24 @@ export interface Production {
194
194
  cueTimings?: Record<string, { pauseMs: number }>
195
195
  /** Stale mappings remain inspectable but never retime audio or replace changed narration. */
196
196
  captionTimings?: Record<StepId, CaptionTiming>
197
+ /** How large the captions are, in the presentation and burned into a lecture video; absent is the default size. */
198
+ captions?: CaptionStyle
197
199
  mediaClips: MediaClip[]
198
200
  }
201
+ /** `scale` multiplies the captions' default size, from `CAPTION_SCALE_MIN` to `CAPTION_SCALE_MAX` (Studio offers tenths). */
202
+ export interface CaptionStyle { scale: number }
203
+ export const CAPTION_SCALE_MIN = 0.7
204
+ export const CAPTION_SCALE_MAX = 1.6
199
205
 
200
206
  /** A stable rich-text/code ID, or `page:${sectionId}` reserved for an existing section title. */
201
207
  export interface DocumentTextPoint { blockId: string, offset: number }
208
+ export interface DocumentTextAnchor { from: DocumentTextPoint, to: DocumentTextPoint }
209
+ /** A stable block, optionally at one step that renders it; the step belongs to the block's section. */
210
+ export interface DocumentPlaceAnchor { blockId: BlockId, stepId?: StepId }
211
+ export type DocumentThreadAnchor = DocumentTextAnchor | DocumentPlaceAnchor
212
+ /** A text range and a place are disjoint shapes; read the shape instead of guessing from offsets. */
213
+ export const isDocumentTextAnchor = (anchor: DocumentThreadAnchor | undefined): anchor is DocumentTextAnchor => Boolean(anchor && 'from' in anchor && 'to' in anchor)
214
+ export const isDocumentPlaceAnchor = (anchor: DocumentThreadAnchor | undefined): anchor is DocumentPlaceAnchor => Boolean(anchor && 'blockId' in anchor && !('from' in anchor))
202
215
  export interface DocumentComment {
203
216
  id: string
204
217
  type: 'comment'
@@ -220,7 +233,7 @@ export interface DocumentThread {
220
233
  resolvedBy?: string
221
234
  metadata?: JsonObject
222
235
  deletedAt?: string
223
- anchor?: { from: DocumentTextPoint, to: DocumentTextPoint }
236
+ anchor?: DocumentThreadAnchor
224
237
  comments: DocumentComment[]
225
238
  }
226
239
 
@@ -236,5 +249,7 @@ export type DocumentEditOperation =
236
249
  | { type: 'updateSection', sectionId: SectionId, title?: string, layout?: Layout }
237
250
  | { type: 'setStepState', stepId: StepId, visuals: VisualState[], inherits?: StepId }
238
251
  | { type: 'setNarration', narration: Narration, stepId?: StepId, index?: number }
252
+ | { type: 'removeNarration', stepId: StepId, narrationId: NarrationId }
253
+ | { type: 'setStepNarrations', stepId: StepId, narrationIds: NarrationId[] }
239
254
  | { type: 'setTiming', stepId?: StepId, sectionId?: SectionId, value: StepProduction }
240
255
  | { type: 'replaceAsset', asset: Asset }
@@ -0,0 +1,28 @@
1
+ import type { Member } from './server.ts'
2
+
3
+ export const MEDIA_UPLOAD_PATH = '/__presmium/presmium.media-upload'
4
+ export const MEDIA_UPLOAD_KINDS = ['image', 'audio'] as const
5
+ export type MediaUploadKind = typeof MEDIA_UPLOAD_KINDS[number]
6
+ export interface MediaUpload {
7
+ upload: string
8
+ kind: MediaUploadKind
9
+ url: string
10
+ expiresAt: string
11
+ maxBytes: number
12
+ state: 'empty' | 'uploading' | 'ready'
13
+ name?: string
14
+ byteLength?: number
15
+ }
16
+ /** Temporary input only; canonical imports retain their existing authoring permission and transaction. */
17
+ export interface DocumentMediaUploads {
18
+ prepare(document: string, kind: MediaUploadKind, member: Member): Promise<MediaUpload>
19
+ status(document: string, upload: string, member: Member): Promise<MediaUpload>
20
+ }
21
+ export type DocumentMediaLocation = { path: string, upload?: never } | { upload: string, path?: never }
22
+ export type DocumentMediaFile = ({ path: string, upload?: never, name?: never } | { upload: string, name: string, path?: never }) & { sha256: string, byteLength: number }
23
+ export const MEDIA_LOCATION_PROPERTIES = { path: { type: 'string', minLength: 1, maxLength: 1024 }, upload: { type: 'string', pattern: '^[a-f0-9]{64}$' } } as const
24
+ export const MEDIA_LOCATION_CHOICES = [{ required: ['path'], not: { required: ['upload'] } }, { required: ['upload'], not: { required: ['path'] } }] as const
25
+ export const mediaFileSchema = (maxBytes: number) => ({ type: 'object', additionalProperties: false,
26
+ properties: { ...MEDIA_LOCATION_PROPERTIES, name: { type: 'string', minLength: 1, maxLength: 200 }, sha256: { type: 'string', pattern: '^[a-f\\d]{64}$' }, byteLength: { type: 'integer', minimum: 1, maximum: maxBytes } },
27
+ required: ['sha256', 'byteLength'], oneOf: [{ required: ['path'], not: { anyOf: [{ required: ['upload'] }, { required: ['name'] }] } }, { required: ['upload', 'name'], not: { required: ['path'] } }],
28
+ } as const)
@@ -1,4 +1,4 @@
1
- import type { CanonicalSource, DirectiveSpec, IRDocument, IRPass, Renderer, RendererContribution, RoleSpec } from '../ir.ts'
1
+ import type { CanonicalSource, IRDocument, IRPass, Renderer, RendererContribution } from '../ir.ts'
2
2
  import type { AgentTool } from './agent.ts'
3
3
  import type { AnchorResolver, AnchorString } from './anchors.ts'
4
4
  import type { Check, CheckContext } from './checks.ts'
@@ -159,7 +159,6 @@ export interface PresmiumNodePlugin {
159
159
  resolvers?: AnchorResolver[]
160
160
  checks?: Check[]
161
161
  anchors?(ctx: CheckContext): AnchorString[] | Promise<AnchorString[]>
162
- directives?: DirectiveSpec[]
163
162
  passes?: IRPass[]
164
163
  executors?: Executor[]
165
164
  renderer?: Renderer
@@ -177,7 +176,6 @@ export interface PresmiumNodePlugin {
177
176
  services?(ctx: NodeServiceContext): [ServiceToken<unknown>, unknown][]
178
177
  environments?: Record<string, EnvironmentProvider>
179
178
  server?(ctx: ServerContext): ServerContribution | Promise<ServerContribution>
180
- roles?: RoleSpec[]
181
179
  tools?: AgentTool[]
182
180
  operator?: boolean
183
181
  }
@@ -10,6 +10,9 @@ export const PREVIEW_PARAM = 'presmium-preview'
10
10
  /** The workbench's appearance when it loads a preview (`dark` or `light`), so that the page's first paint matches it. */
11
11
  export const PREVIEW_APPEARANCE_PARAM = 'presmium-appearance'
12
12
 
13
+ /** `?captions=off` starts a presentation with its captions off (a reader turns them on again with the captions button). */
14
+ export const CAPTIONS_PARAM = 'captions'
15
+
13
16
  export const PREVIEW_REVISION = 'presmiumRevision'
14
17
 
15
18
  export const AUTHOR_MARKS_CLASS = 'pm-author-marks'
@@ -201,8 +204,6 @@ export type PreviewReport =
201
204
  | { type: 'selection', selection: (PreviewAnchor & { text: string, rect?: PreviewRect, obstacles?: PreviewRect[] }) | null }
202
205
  /** Where the picked block or the selection is after the page scrolled or resized; null when it is out of sight. */
203
206
  | { type: 'rect', rect: PreviewRect | null, obstacles?: PreviewRect[] }
204
- /** Where the blocks the AI changed are in the preview's viewport while they blink, and again as the page scrolls (at most 16). */
205
- | { type: 'flashed', rects: PreviewRect[] }
206
207
  | { type: 'editing', target: PreviewAnchor, active: boolean }
207
208
  /** The text of a block edited in place, before and after (its `textContent`); sent only when it changed. */
208
209
  | { type: 'edited', target: PreviewAnchor, before: string, after: string, request?: number, revision?: string, binding?: string }
@@ -371,7 +372,6 @@ export function toPreviewReport(data: unknown, nonce: string): PreviewReport | u
371
372
  ? { type: 'selection', selection: { ...toAnchor(selected), text: selected.text, ...selected.rect ? { rect: toRect(selected.rect as PreviewRect) } : {}, ...selected.obstacles !== undefined ? { obstacles: (selected.obstacles as PreviewRect[]).map(toRect) } : {} } }
372
373
  : undefined
373
374
  }
374
- case 'flashed': return Array.isArray(m.rects) && m.rects.length <= 16 && m.rects.every(rect) ? { type: 'flashed', rects: (m.rects as PreviewRect[]).map(toRect) } : undefined
375
375
  case 'rect': return (m.rect === null || rect(m.rect)) && optional(m.obstacles, obstacles) ? { type: 'rect', rect: m.rect === null ? null : toRect(m.rect), ...m.obstacles !== undefined ? { obstacles: (m.obstacles as PreviewRect[]).map(toRect) } : {} } : undefined
376
376
  case 'editing': return anchor(m.target) && typeof m.active === 'boolean' ? { type: 'editing', target: toAnchor(m.target), active: m.active } : undefined
377
377
  case 'edited': return anchor(m.target) && text(m.before) && text(m.after) && m.before.length <= MAX_EDITED && m.after.length <= MAX_EDITED && editedRequest(m) ? { type: 'edited', target: toAnchor(m.target), before: m.before, after: m.after, ...m.request === undefined ? {} : { request: m.request as number, revision: m.revision as string, binding: m.binding as string } } : undefined
@@ -10,6 +10,8 @@ export type ProjectOperation = DocumentOperation | { op: 'retitle', dir: string,
10
10
  export interface ProjectCaller { member: Member, origin: 'editor' | 'agent', boundDocument?: string }
11
11
  export interface ProjectObservation { snapshot?: string, configuration: string }
12
12
  export interface ProjectCapabilities {
13
+ templates?: string[]
14
+ nextTemplatesOffset?: number
13
15
  available: boolean
14
16
  actions: Record<ProjectOperation['op'], { available: boolean, reasons: string[] }>
15
17
  reasons: string[]
@@ -45,7 +47,7 @@ export interface ProjectApplied extends OperationAnswer {
45
47
  }
46
48
  /** Directory management borrows the Web writer; metadata retitle borrows canonical document CAS. */
47
49
  export interface ProjectAuthoring {
48
- capabilities(caller: ProjectCaller): Promise<ProjectCapabilities>
50
+ capabilities(caller: ProjectCaller, query?: { templatesOffset?: number }): Promise<ProjectCapabilities>
49
51
  plan(request: ProjectPlanRequest, caller: ProjectCaller): Promise<ProjectPlan>
50
52
  readPlan(request: ProjectApply, caller: ProjectCaller): Promise<ProjectPlan>
51
53
  apply(request: ProjectApply, caller: ProjectCaller, signal?: AbortSignal): Promise<ProjectApplied>
@@ -57,3 +59,4 @@ export const PROJECT_PLAN_SCHEMA = { type: 'object', additionalProperties: false
57
59
  id: text, operation: { oneOf: [operation('create', { title: text, template: text }, []), operation('copy', { to: text, title: text }, ['to']), operation('rename', { to: text }, ['to']), operation('delete', {}, []), operation('retitle', { title: text }, ['title'])] },
58
60
  } } as const
59
61
  export const PROJECT_APPLY_SCHEMA = { type: 'object', additionalProperties: false, required: ['planId', 'digest'], properties: { planId: text, digest: { type: 'string', pattern: '^[a-f0-9]{64}$' }, confirmDeletion: { const: true } } } as const
62
+ export const PROJECT_CAPABILITIES_SCHEMA = { type: 'object', additionalProperties: false, properties: { templatesOffset: { type: 'integer', minimum: 0 } } } as const
@@ -1,3 +1,5 @@
1
+ import type { Schema } from '@cfworker/json-schema'
2
+
1
3
  /** Operator configuration is separate from document voice choices. Secret values are write-only. */
2
4
  export interface SpeechSettingsAnswer {
3
5
  provider: 'volcengine'
@@ -14,3 +16,14 @@ export interface SpeechSettingsAnswer {
14
16
  export type SpeechSettingsChange =
15
17
  | { action: 'save', revision: string, apiKey?: string, appId?: string }
16
18
  | { action: 'clear', revision: string }
19
+
20
+ export interface SpeechSettings {
21
+ read(): SpeechSettingsAnswer
22
+ change(change: SpeechSettingsChange): Promise<SpeechSettingsAnswer>
23
+ }
24
+
25
+ export const SPEECH_SETTINGS_CHANGE_SCHEMA: Schema = {
26
+ type: 'object', additionalProperties: false,
27
+ properties: { action: { enum: ['save', 'clear'] }, revision: { type: 'string', maxLength: 200 }, apiKey: { type: 'string', maxLength: 8192 }, appId: { type: 'string', maxLength: 32 } },
28
+ required: ['action', 'revision'],
29
+ }
@@ -103,6 +103,15 @@ export interface VoiceCloneStatus {
103
103
  message?: string
104
104
  }
105
105
 
106
+ export interface SpeechCachePrune {
107
+ /** Entries some request uses. */
108
+ kept: number
109
+ /** Entries no request uses, with the bytes of their files. */
110
+ unused: { key: string, bytes: number }[]
111
+ /** Whether the unused entries were deleted. */
112
+ removed: boolean
113
+ }
114
+
106
115
  export interface TranscriptionRequest {
107
116
  engine?: string
108
117
  audio: Blob
@@ -124,6 +133,13 @@ export interface SpeechService {
124
133
  cached?(key: string, signal?: AbortSignal): Promise<Synthesis | undefined>
125
134
  alignWords?(key: string, options: { lang: string, transcribe?: boolean }, signal?: AbortSignal): Promise<SpeechWord[] | undefined>
126
135
  pruneLock?(keep: ReadonlySet<string>): Promise<number>
136
+ /**
137
+ * The document's cached audio that no request of `keep` (every sentence the document says) uses: kept is any entry
138
+ * made for the same request under any configuration of the voice service. With `remove`, deletes the unused entries
139
+ * with their alignments and speech lock entries. Throws `speech-prune-engine-unknown` when a request names no engine
140
+ * and no default engine is configured, since its entries cannot be told apart then.
141
+ */
142
+ pruneCache?(keep: readonly SynthesisRequest[], options?: { remove?: boolean, signal?: AbortSignal }): Promise<SpeechCachePrune>
127
143
  transcribe(request: TranscriptionRequest, signal?: AbortSignal): Promise<Transcript>
128
144
  /** Registers the consent, then starts training; only for the document's owner. Absent: the service cannot clone. */
129
145
  cloneVoice?(request: VoiceCloneRequest, signal?: AbortSignal): Promise<VoiceCloneStatus>
@@ -1,9 +1,31 @@
1
1
  import type { CanonicalSource } from '../ir.ts'
2
2
  import type { Member } from './server.ts'
3
- import type { VoiceoverCancellation, VoiceoverJob, VoiceoverRequest, VoiceoverSnapshot, VoicePreviewAnswer, VoicePreviewQuery, VoicePreviewQuote, VoicePreviewRequest } from './voice.ts'
3
+ import type { SpeechVoice, SynthesisRequest } from './speech.ts'
4
+ import type { VoiceoverCancellation, VoiceoverJob, VoiceoverRequest, VoiceoverSnapshot, VoicePreviewAnswer, VoicePreviewQuery, VoicePreviewQuote, VoicePreviewRequest, VoiceTarget } from './voice.ts'
4
5
  import { defineService } from './service.ts'
5
6
 
6
7
  export interface VoiceoverStatusQuery { source?: CanonicalSource, revision?: string }
8
+ export interface VoiceoverSentencesQuery extends VoiceoverStatusQuery {
9
+ /** Answer as if this were the document's default voice: sentences that inherit the default, or have no voice, use it. */
10
+ defaultVoice?: SpeechVoice
11
+ }
12
+ /** One sentence that a document-scope generation processes, in reading order. */
13
+ export interface VoiceoverSentence {
14
+ section: string
15
+ step: number
16
+ stepId?: string
17
+ /** The step binding for a `steps` scope; absent when the sentence cannot be generated by step (it crosses steps). */
18
+ target?: VoiceTarget
19
+ /** The spoken text, which the voice service receives (and a cloud provider charges for). */
20
+ text: string
21
+ /** The exact synthesis request; absent when the sentence has no usable voice. */
22
+ request?: SynthesisRequest
23
+ /** Exact audio for the request is in the speech cache. */
24
+ cached: boolean
25
+ /** Why it cannot be generated now: no voice, or the voice service or voice is unavailable. */
26
+ reason?: string
27
+ }
28
+ export interface VoiceoverSentences { source: CanonicalSource, revision: string, sentences: VoiceoverSentence[] }
7
29
  export type VoiceoverStart = Omit<VoiceoverRequest, 'confirmed'>
8
30
  export type VoicePreviewStart = Omit<VoicePreviewRequest, 'confirmed'>
9
31
  export type VoicePreviewCheck = VoicePreviewQuery & { source?: CanonicalSource }
@@ -23,6 +45,8 @@ export interface VoicePreviewMedia extends Omit<VoicePreviewAnswer, 'audio'> { b
23
45
  /** Stateless plugin execution. The host owns intents and jobs; discovery creates neither. */
24
46
  export interface VoiceoverExecution {
25
47
  status(query: VoiceoverStatusQuery, signal: AbortSignal): Promise<Omit<VoiceoverSnapshot, 'jobs'>>
48
+ /** Every sentence with its request and cache state; reads the cache and the voice catalog, never generates. */
49
+ sentences?(query: VoiceoverSentencesQuery, signal: AbortSignal): Promise<VoiceoverSentences>
26
50
  prepare(request: VoiceoverStart, signal: AbortSignal): Promise<PreparedVoiceover>
27
51
  quote(query: VoicePreviewCheck, signal: AbortSignal): Promise<VoicePreviewQuote>
28
52
  preview(request: VoicePreviewStart, signal: AbortSignal): Promise<VoicePreviewMedia>
@@ -0,0 +1,27 @@
1
+ import type { Member } from './server.ts'
2
+ import type { Revision, UncommittedFile } from './workspace.ts'
3
+ export const CHANGES_MAX_REQUEST_CHARS = 1 << 20
4
+ export const CHANGES_MAX_RESPONSE_CHARS = 7168
5
+ export const CHANGES_MAX_FILES = 16_384
6
+ export const CHANGES_MAX_BYTES = 512 << 20
7
+ export interface ChangesCaller { member: Member, origin: 'editor' | 'agent', boundDocument?: string, confirmed?: boolean }
8
+ export interface ChangesQuery { document?: string, offset?: number, snapshot?: string }
9
+ export interface WorkspaceChangesAnswer { available: boolean, files: (UncommittedFile & { unsupported?: true })[], snapshot?: string, nextOffset?: number }
10
+ export type WorkspaceChangesRequest = { document?: string, paths?: string[], snapshot?: string } & (
11
+ | { action: 'commit', message: string }
12
+ | { action: 'discard', confirm: true }
13
+ )
14
+ export interface WorkspaceChangesResult { action: 'commit' | 'discard', files: number, refreshed?: false, revision?: Revision, committed?: boolean }
15
+ export interface PreparedWorkspaceChanges { readonly paths: readonly string[], change(signal?: AbortSignal): Promise<WorkspaceChangesResult> }
16
+ export interface WorkspaceChanges {
17
+ list(query: ChangesQuery, caller: ChangesCaller): Promise<WorkspaceChangesAnswer>
18
+ prepare(request: WorkspaceChangesRequest, caller: ChangesCaller): Promise<PreparedWorkspaceChanges>
19
+ }
20
+ const document = { type: 'string', maxLength: 500 } as const
21
+ const snapshot = { type: 'string', pattern: '^[a-f0-9]{64}$' } as const
22
+ const paths = { type: 'array', minItems: 1, maxItems: CHANGES_MAX_FILES, uniqueItems: true, items: { type: 'string', minLength: 1, maxLength: 500 } } as const
23
+ export const CHANGES_QUERY_SCHEMA = { type: 'object', additionalProperties: false, properties: { document, snapshot, offset: { type: 'integer', minimum: 0 } } } as const
24
+ export const CHANGES_REQUEST_SCHEMA = { oneOf: [
25
+ { type: 'object', additionalProperties: false, required: ['action', 'message'], properties: { document, paths, snapshot, action: { const: 'commit' }, message: { type: 'string', minLength: 1, maxLength: 4000 } } },
26
+ { type: 'object', additionalProperties: false, required: ['action', 'confirm'], properties: { document, paths, snapshot, action: { const: 'discard' }, confirm: { const: true } } },
27
+ ] } as const
@@ -0,0 +1,39 @@
1
+ import type { Member } from './server.ts'
2
+ import type { ReviewChange, ReviewStep } from './workspace.ts'
3
+
4
+ export const WORKSPACE_REVIEW_MAX_REQUEST_CHARS = 8192
5
+ export const WORKSPACE_REVIEW_MAX_RESPONSE_CHARS = 7168
6
+ export const WORKSPACE_REVIEW_FRAGMENT_CHARS = 4000
7
+ export interface WorkspaceReviewQuery { part?: 'summary' | 'files' | 'steps' | 'diff', path?: string, step?: string, offset?: number, snapshot?: string }
8
+ export interface WorkspaceReviewSummary { id: string, document: string, running: boolean, mode: 'required' | 'auto', files: number, steps: number }
9
+ export interface WorkspaceReviewAnswer {
10
+ review: WorkspaceReviewSummary | null
11
+ snapshot?: string
12
+ files?: Omit<ReviewChange, 'diff'>[]
13
+ steps?: (Omit<ReviewStep, 'changes'> & { files: number })[]
14
+ nextOffset?: number
15
+ diff?: { path: string, step?: string, text: string, offset: number, totalChars: number, sha256: string }
16
+ }
17
+ export type WorkspaceReviewChange =
18
+ | { action: 'accept', snapshot: string, reject?: string[], message?: string }
19
+ | { action: 'reject', snapshot: string, paths?: string[], confirm: true }
20
+ | { action: 'restore', snapshot: string, step: string, confirm: true }
21
+ export interface WorkspaceReviewChanged { outcome: 'accepted' | 'rejected' | 'restored' | 'updated' | 'empty', revision?: string, files?: number, remainingFiles?: number }
22
+ /** Workspace publication authority; document-scoped agent credentials must never receive this service. */
23
+ export interface WorkspaceReview {
24
+ read(query: WorkspaceReviewQuery, member: Member): Promise<WorkspaceReviewAnswer>
25
+ check(change: WorkspaceReviewChange, member: Member): Promise<void>
26
+ change(change: WorkspaceReviewChange, member: Member, signal?: AbortSignal): Promise<WorkspaceReviewChanged>
27
+ }
28
+ const path = { type: 'string', minLength: 1, maxLength: 500 } as const
29
+ const snapshot = { type: 'string', pattern: '^[a-f0-9]{64}$' } as const
30
+ const step = { type: 'string', minLength: 1, maxLength: 100 } as const
31
+ const paths = { type: 'array', minItems: 1, maxItems: 200, uniqueItems: true, items: path } as const
32
+ export const WORKSPACE_REVIEW_QUERY_SCHEMA = { type: 'object', additionalProperties: false, properties: {
33
+ part: { enum: ['summary', 'files', 'steps', 'diff'] }, path, step, offset: { type: 'integer', minimum: 0 }, snapshot,
34
+ } } as const
35
+ export const WORKSPACE_REVIEW_CHANGE_SCHEMA = { oneOf: [
36
+ { type: 'object', additionalProperties: false, required: ['action', 'snapshot'], properties: { action: { const: 'accept' }, snapshot, reject: paths, message: { type: 'string', minLength: 1, maxLength: 4000 } } },
37
+ { type: 'object', additionalProperties: false, required: ['action', 'snapshot', 'confirm'], properties: { action: { const: 'reject' }, snapshot, paths, confirm: { const: true } } },
38
+ { type: 'object', additionalProperties: false, required: ['action', 'snapshot', 'step', 'confirm'], properties: { action: { const: 'restore' }, snapshot, step, confirm: { const: true } } },
39
+ ] } as const
@@ -0,0 +1,38 @@
1
+ import type { Member } from './server.ts'
2
+ import type { SourceFile } from './workspace.ts'
3
+
4
+ export const SOURCE_MAX_BYTES = 2 << 20
5
+ export const SOURCE_MAX_FILES = 16
6
+ export const SOURCE_MAX_REQUEST_CHARS = SOURCE_MAX_BYTES * 3 + 8192
7
+ export const SOURCE_MAX_RESPONSE_CHARS = 7168
8
+ export const SOURCE_FRAGMENT_CHARS = 4000
9
+ /** Supplied by an adapter, never accepted as model arguments. */
10
+ export interface SourceCaller { member: Member, boundDocument?: string, confirmed?: boolean, origin: 'editor' | 'agent' }
11
+ export interface SourceListQuery { document?: string, query?: string, offset?: number, snapshot?: string }
12
+ export interface SourceListAnswer { files: SourceFile[], snapshot: string, nextOffset?: number, truncated?: true }
13
+ export interface SourceReadQuery { document?: string, path: string, offset?: number, version?: string }
14
+ export interface SourceReadAnswer { path: string, version: string, text: string, offset: number, totalChars: number, nextOffset?: number }
15
+ export type SourceEditFile = { path: string, version?: string } & ({ content: string, create?: true } | { find: string, replace: string })
16
+ export type SourceEdit = ({ document?: string } & SourceEditFile) | { document?: string, edits: SourceEditFile[] }
17
+ export interface SourceSaved { saved: true, changed: boolean, path?: string, files?: number, revision?: string, current?: false }
18
+ export interface PreparedSourceEdit { change(signal?: AbortSignal): Promise<SourceSaved> }
19
+ /** Current source editor scope and transaction owner; invalid IR is readable and repairable. */
20
+ export interface WorkspaceSource {
21
+ list(query: SourceListQuery, caller: SourceCaller): Promise<SourceListAnswer>
22
+ read(query: SourceReadQuery, caller: SourceCaller): Promise<SourceReadAnswer>
23
+ prepare(edit: SourceEdit, caller: SourceCaller): Promise<PreparedSourceEdit>
24
+ }
25
+ const document = { type: 'string', maxLength: 500 } as const
26
+ const path = { type: 'string', minLength: 1, maxLength: 500 } as const
27
+ const version = { type: 'string', pattern: '^[a-f0-9]{20}$' } as const
28
+ const offset = { type: 'integer', minimum: 0 } as const
29
+ export const SOURCE_LIST_SCHEMA = { type: 'object', additionalProperties: false, properties: { document, query: { type: 'string', maxLength: 200 }, offset, snapshot: { type: 'string', pattern: '^[a-f0-9]{64}$' } } } as const
30
+ export const SOURCE_READ_SCHEMA = { type: 'object', additionalProperties: false, required: ['path'], properties: { document, path, offset, version } } as const
31
+ const fileSchema = { oneOf: [
32
+ { type: 'object', additionalProperties: false, required: ['path', 'content'], properties: { path, version, content: { type: 'string', maxLength: SOURCE_MAX_BYTES }, create: { const: true } } },
33
+ { type: 'object', additionalProperties: false, required: ['path', 'find', 'replace'], properties: { path, version, find: { type: 'string', minLength: 1, maxLength: SOURCE_MAX_BYTES }, replace: { type: 'string', maxLength: SOURCE_MAX_BYTES } } },
34
+ ] } as const
35
+ export const SOURCE_EDIT_SCHEMA = { oneOf: [
36
+ ...fileSchema.oneOf.map(schema => ({ ...schema, properties: { document, ...schema.properties } })),
37
+ { type: 'object', additionalProperties: false, required: ['edits'], properties: { document, edits: { type: 'array', minItems: 1, maxItems: SOURCE_MAX_FILES, items: fileSchema } } },
38
+ ] } as const
@@ -94,6 +94,8 @@ export interface DocumentSummary {
94
94
  description?: string
95
95
  lang?: string
96
96
  tags?: string[]
97
+ /** Whether its metadata asks for a presentation (`renderers.slides`), which a site serves below its pages. */
98
+ slides?: boolean
97
99
  }
98
100
 
99
101
  /** @experimental The workspace service's answer to `documents`. */
package/src/contracts.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export * from './contracts/agent.ts'
2
2
  export * from './contracts/authoring.ts'
3
+ export * from './contracts/capture.ts'
3
4
  export * from './contracts/document-reads.ts'
4
5
  export * from './contracts/anchors.ts'
5
6
  export * from './contracts/checks.ts'
@@ -22,6 +23,9 @@ export * from './contracts/server.ts'
22
23
  export * from './contracts/service.ts'
23
24
  export * from './contracts/speech.ts'
24
25
  export * from './contracts/speech-settings.ts'
26
+ export * from './contracts/workspace-review.ts'
27
+ export * from './contracts/workspace-source.ts'
28
+ export * from './contracts/workspace-changes.ts'
25
29
  export * from './contracts/transcription.ts'
26
30
  export * from './contracts/transcription-adoption.ts'
27
31
  export * from './contracts/voice.ts'
@@ -31,5 +35,7 @@ export * from './contracts/document-comments.ts'
31
35
  export * from './contracts/authoring-actions.ts'
32
36
  export * from './contracts/document-history.ts'
33
37
  export * from './contracts/authoring-clients.ts'
38
+ export * from './contracts/authoring-windows.ts'
34
39
  export * from './contracts/projects.ts'
35
40
  export * from './contracts/document-image.ts'
41
+ export * from './contracts/media-uploads.ts'
@@ -1,15 +1,31 @@
1
1
  import { applyDocumentCaptionTiming } from './document-caption-timings.ts'
2
+ import { captionScale, changeDocumentCaptionScale } from './document-caption-scale.ts'
2
3
  import { hasRole } from './access.ts'
3
- import { applyDocumentCommentAction, DocumentCommentError, validateDocumentCommentAnchor } from './document-comments.ts'
4
+ import { applyDocumentCommentAction, degradeDocumentCommentAnchor, DocumentCommentError, validateDocumentCommentAnchor } from './document-comments.ts'
5
+ import { documentAnchorKey } from './document-places.ts'
4
6
  import { changeDocumentVoice, documentVoiceStepIds, previewDocumentVoiceChange } from './document-voices.ts'
5
7
  import { applyDocumentComponentAction } from './document-components.ts'
6
8
  import type { DocumentAuthoringAction, DocumentAuthoringActionEffect } from './contracts/authoring-actions.ts'
7
9
  import type { DocumentCommentContext } from './contracts/document-comments.ts'
8
10
  import type { TeachingDocument } from './contracts/document.ts'
9
11
 
12
+ export function enableDocumentProduction(document: TeachingDocument): TeachingDocument {
13
+ const plugins = [...new Set([...(document.metadata.plugins ?? []), '@lincyaw/addon-lecture', '@lincyaw/addon-speech'])]
14
+ if (JSON.stringify(plugins) === JSON.stringify(document.metadata.plugins) && document.metadata.renderers?.lecture) return document
15
+ return { ...document, metadata: { ...document.metadata, plugins, renderers: { ...document.metadata.renderers, lecture: document.metadata.renderers?.lecture ?? {} } } }
16
+ }
17
+
10
18
  /** Fixed context is supplied by the owning adapter exactly once per semantic plan. */
11
19
  export function applyDocumentAuthoringAction(document: TeachingDocument, action: DocumentAuthoringAction, context: DocumentCommentContext): { content: TeachingDocument, effect: DocumentAuthoringActionEffect } {
12
20
  if (!context.member || !hasRole(context.member, 'editor')) throw new DocumentCommentError(403, 'authoring-permission-denied')
21
+ if (action.type === 'production.enable') {
22
+ const content = enableDocumentProduction(document)
23
+ return { content, effect: { kind: 'production', value: { enabled: true, changed: content !== document } } }
24
+ }
25
+ if (action.type === 'caption.scale.set') {
26
+ const content = changeDocumentCaptionScale(document, action.scale)
27
+ return { content, effect: { kind: 'caption-scale', value: { scale: captionScale(content.production), changed: content !== document } } }
28
+ }
13
29
  if (action.type === 'component.parameters.patch' || action.type === 'component.step-parameters.patch' || action.type === 'component.step-parameters.reset' || action.type === 'component.definition.use') {
14
30
  const { content, effect } = applyDocumentComponentAction(document, action)
15
31
  return { content, effect: { kind: 'component', value: effect } }
@@ -29,17 +45,20 @@ export function applyDocumentAuthoringAction(document: TeachingDocument, action:
29
45
  return { content, effect: { kind: 'voice', scope: action.scope.kind, value: previewDocumentVoiceChange(document, action.scope, action.source, { replaceOverrides: action.replaceOverrides }), recordings } }
30
46
  }
31
47
  if (action.type === 'comment.create') validateDocumentCommentAnchor(document, action.anchor ?? undefined)
32
- let source = document.comments ?? {}, detached = false
48
+ let source = document.comments ?? {}, detached = false, degraded = false
33
49
  if (action.type !== 'comment.create' && Object.hasOwn(source, action.threadId)) {
34
50
  const thread = source[action.threadId]!
35
- try { validateDocumentCommentAnchor(document, thread.anchor) } catch (error) {
36
- if (!(error instanceof DocumentCommentError) || error.status !== 422) throw error
51
+ const anchor = degradeDocumentCommentAnchor(document, thread.anchor)
52
+ if (thread.anchor && !anchor) {
37
53
  const { anchor: _anchor, ...unanchored } = thread
38
54
  source = { ...source, [thread.id]: unanchored }; detached = true
55
+ } else if (anchor && documentAnchorKey(anchor) !== documentAnchorKey(thread.anchor)) {
56
+ source = { ...source, [thread.id]: { ...thread, anchor } }; degraded = true
39
57
  }
40
58
  }
41
59
  const { threads, effect } = applyDocumentCommentAction(source, action, context)
42
60
  if (detached) { effect.anchorDetached = true; effect.changed = true }
61
+ else if (degraded) effect.changed = true
43
62
  const content = { ...document }
44
63
  if (Object.keys(threads).length) content.comments = threads
45
64
  else delete content.comments
@@ -0,0 +1,17 @@
1
+ import { CAPTION_SCALE_MAX, CAPTION_SCALE_MIN } from './contracts/document.ts'
2
+ import type { Production, TeachingDocument } from './contracts/document.ts'
3
+
4
+ /** The caption size a document sets (`production.captions.scale`); 1 when it sets none or one out of range. */
5
+ export function captionScale(production: Pick<Production, 'captions'> | undefined): number {
6
+ const scale = production?.captions?.scale
7
+ return typeof scale === 'number' && scale >= CAPTION_SCALE_MIN && scale <= CAPTION_SCALE_MAX ? scale : 1
8
+ }
9
+
10
+ /** Sets the caption size, kept in range and rounded to a tenth; the default size 1 removes the setting. */
11
+ export function changeDocumentCaptionScale(document: TeachingDocument, scale: number): TeachingDocument {
12
+ if (!Number.isFinite(scale)) throw new Error('document-caption-scale')
13
+ const value = Math.round(Math.min(CAPTION_SCALE_MAX, Math.max(CAPTION_SCALE_MIN, scale)) * 10) / 10
14
+ if (value === captionScale(document.production)) return document
15
+ const { captions: _captions, ...production } = document.production
16
+ return { ...document, production: value === 1 ? production : { ...production, captions: { scale: value } } }
17
+ }
@@ -1,6 +1,10 @@
1
1
  import { hasRole } from './access.ts'
2
2
  import type { DocumentCommentAction, DocumentCommentContext, DocumentCommentEffect } from './contracts/document-comments.ts'
3
- import type { DocumentComment, DocumentThread, InlineNode, JsonObject, ListItemNode, RichTextNode, TableCellNode, TableRowNode, TeachingDocument } from './contracts/document.ts'
3
+ import { isDocumentPlaceAnchor, isDocumentTextAnchor } from './contracts/document.ts'
4
+ import { documentBlockSection, documentCommentTargets } from './document-places.ts'
5
+ import type { DocumentComment, DocumentThread, DocumentThreadAnchor, JsonObject, ListItemNode, RichTextNode, TableCellNode, TableRowNode, TeachingDocument } from './contracts/document.ts'
6
+
7
+ export { documentCommentTargets, isDocumentTextLink } from './document-places.ts'
4
8
 
5
9
  export class DocumentCommentError extends Error {
6
10
  readonly status: number
@@ -8,45 +12,19 @@ export class DocumentCommentError extends Error {
8
12
  }
9
13
  function fail(status: number, code: string): never { throw new DocumentCommentError(status, code) }
10
14
 
11
- /** Canonical anchor v1 expands only nonempty styled-text links; other inline values are atoms. */
12
- export function isDocumentTextLink(node: InlineNode): node is Extract<InlineNode, { type: 'link' }> & { children: Extract<InlineNode, { type: 'text' | 'break' }>[] } {
13
- return node.type === 'link' && node.children.length > 0 && node.children.every(child => child.type === 'text' || child.type === 'break')
14
- }
15
- function inlineText(nodes: readonly InlineNode[]): string {
16
- return nodes.map(node => node.type === 'text' ? node.text : node.type === 'break' ? '\n' : isDocumentTextLink(node) ? inlineText(node.children) : '\uFFFC').join('')
17
- }
18
-
19
- /** Only addressable canonical text identities, in native document order; opaque data is never traversed. */
20
- export function documentCommentTargets(document: TeachingDocument): Map<string, { order: number, text: string }> {
21
- const targets = new Map<string, { order: number, text: string }>()
22
- const add = (id: string, text: string) => { targets.set(id, { order: targets.size, text }) }
23
- const rich = (node: RichTextNode): void => {
24
- if (node.type === 'paragraph' || node.type === 'heading') add(node.id, inlineText(node.children))
25
- else if (node.type === 'code') add(node.id, node.value)
26
- else if (node.type === 'list') for (const item of node.children) {
27
- const [first, ...rest] = item.children
28
- add(item.id, first?.type === 'paragraph' ? inlineText(first.children) : '')
29
- ;(first?.type === 'paragraph' ? rest : item.children).forEach(rich)
30
- }
31
- else if (node.type === 'blockquote') {
32
- const [first, ...rest] = node.children
33
- if (first?.type === 'paragraph') { add(node.id, inlineText(first.children)); rest.forEach(rich) }
34
- else node.children.forEach(rich)
35
- } else if (node.type === 'table') for (const row of node.children) for (const cell of row.children) add(cell.id, inlineText(cell.children))
36
- }
37
- const block = (id: string): void => {
38
- const value = document.blocks[id]
39
- if (value?.type === 'text') value.content.forEach(rich)
40
- else if (value?.type === 'code' && value.value !== undefined) add(id, value.value)
41
- else if (value?.type === 'container' || value?.type === 'component') value.children?.forEach(block)
42
- }
43
- for (const id of document.sectionOrder) { const page = document.sections[id]!; add(`page:${id}`, page.title); page.children.forEach(block) }
44
- return targets
45
- }
46
-
47
15
  /** No ordinal, offset clamping, surrogate splitting or guessed fallback identity. */
48
16
  export function validateDocumentCommentAnchor(document: TeachingDocument, anchor: DocumentThread['anchor']): void {
49
17
  if (!anchor) return
18
+ if (isDocumentPlaceAnchor(anchor)) {
19
+ if (!Object.hasOwn(document.blocks, anchor.blockId)) fail(422, 'comment-anchor-target-unavailable')
20
+ if (anchor.stepId !== undefined) {
21
+ const step = Object.hasOwn(document.steps, anchor.stepId) ? document.steps[anchor.stepId] : undefined
22
+ const section = step ? document.sections[step.sectionId] : undefined
23
+ if (!step || !section || !section.stepOrder.includes(anchor.stepId) || step.sectionId !== documentBlockSection(document, anchor.blockId)) fail(422, 'comment-anchor-target-unavailable')
24
+ }
25
+ return
26
+ }
27
+ if (!isDocumentTextAnchor(anchor)) fail(422, 'comment-anchor-target-unavailable')
50
28
  const targets = documentCommentTargets(document), a = targets.get(anchor.from.blockId), b = targets.get(anchor.to.blockId)
51
29
  if (!a || !b) fail(422, 'comment-anchor-target-unavailable')
52
30
  for (const [point, target] of [[anchor.from, a], [anchor.to, b]] as const) {
@@ -57,6 +35,21 @@ export function validateDocumentCommentAnchor(document: TeachingDocument, anchor
57
35
  if (a.order > b.order || a.order === b.order && anchor.from.offset >= anchor.to.offset) fail(422, 'comment-anchor-range-invalid')
58
36
  }
59
37
 
38
+ /**
39
+ * The strongest still-valid anchor. A place whose step no longer exists keeps the block; a missing block or an
40
+ * unmappable text range leaves the discussion explicitly unanchored rather than silently pointing elsewhere.
41
+ */
42
+ export function degradeDocumentCommentAnchor(document: TeachingDocument, anchor: DocumentThreadAnchor | undefined): DocumentThreadAnchor | undefined {
43
+ if (!anchor) return undefined
44
+ try { validateDocumentCommentAnchor(document, anchor); return anchor }
45
+ catch (error) { if (!(error instanceof DocumentCommentError) || error.status !== 422) throw error }
46
+ if (isDocumentPlaceAnchor(anchor) && anchor.stepId !== undefined && Object.hasOwn(document.blocks, anchor.blockId)) {
47
+ const place: DocumentThreadAnchor = { blockId: anchor.blockId }
48
+ try { validateDocumentCommentAnchor(document, place); return place } catch { /* The block itself is not addressable. */ }
49
+ }
50
+ return undefined
51
+ }
52
+
60
53
  /** Shared native/editor permissions: editors may delete any discussion, but edit their own comment; a document owner may manage earlier authors. */
61
54
  export function applyDocumentCommentAction(source: NonNullable<TeachingDocument['comments']>, action: DocumentCommentAction, context: DocumentCommentContext): { threads: NonNullable<TeachingDocument['comments']>, effect: DocumentCommentEffect } {
62
55
  const member = context.member