@lincyaw/workspace 1.0.0-rc.50 → 1.0.0-rc.51

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.50",
3
+ "version": "1.0.0-rc.51",
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.50",
38
- "@lincyaw/kernel": "1.0.0-rc.50",
39
- "@lincyaw/server": "1.0.0-rc.50"
37
+ "@lincyaw/compiler": "1.0.0-rc.51",
38
+ "@lincyaw/server": "1.0.0-rc.51",
39
+ "@lincyaw/kernel": "1.0.0-rc.51"
40
40
  },
41
41
  "devDependencies": {
42
42
  "@types/mime-types": "^3.0.1",
43
- "@lincyaw/mcp": "1.0.0-rc.50"
43
+ "@lincyaw/mcp": "1.0.0-rc.51"
44
44
  }
45
45
  }
@@ -0,0 +1,165 @@
1
+ import { randomBytes, randomUUID, createHash } from 'node:crypto'
2
+ import { AUTHORING_CLIENT_MAX_CLIENTS, AUTHORING_CLIENT_MAX_REQUESTS, AUTHORING_CLIENT_MAX_REQUEST_CHARS, AUTHORING_CLIENT_MAX_RESPONSE_CHARS, AUTHORING_CLIENT_REQUEST_TIMEOUT_MS, hasRole, isRecord, jsonResponse, problemResponse, pushStream, sseResponse } from '@lincyaw/kernel'
3
+ import type { AuthoringWindowAcknowledgement, AuthoringWindowDescriptor, AuthoringWindowEvent, AuthoringWindowLease, AuthoringWindowOpen, AuthoringWindowReference, AuthoringWindowReport, AuthoringWindowRequest, AuthoringWindowRequestResult, AuthoringWindows, Member, Route } from '@lincyaw/kernel'
4
+ import { validateAuthoringClientLease, validateAuthoringClientQuery, validateAuthoringClientRequestQuery, validateAuthoringWindowAcknowledgement, validateAuthoringWindowHandle, validateAuthoringWindowOpen, validateAuthoringWindowReport, validateAuthoringWindowRequest } from '@lincyaw/kernel/node'
5
+ import { catchRequestErrors, RequestError } from './errors.ts'
6
+
7
+ type Client = { member: string, credential: string, sequence: number, signature?: string, value: AuthoringWindowDescriptor, send?(event: AuthoringWindowEvent): void, close?(): void }
8
+ type Pending = { member: string, signature: string, request: AuthoringWindowRequest, value: AuthoringWindowRequestResult, timer?: ReturnType<typeof setTimeout> }
9
+ const terminal = (value: Pending) => !['sent', 'executing'].includes(value.value.state)
10
+ const size = (value: unknown) => JSON.stringify(value, null, 2).length
11
+ const digest = (value: unknown) => createHash('sha256').update(JSON.stringify(value, (_, item) => isRecord(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item)).digest('hex')
12
+ const budget = (value: unknown, maximum = AUTHORING_CLIENT_MAX_REQUEST_CHARS) => { if (value === undefined || size(value) > maximum) throw new RequestError(413, 'window-request-too-large') }
13
+
14
+ /** Root window control has its own lifetime, not the currently attached document's authority. */
15
+ export function createAuthoringWindows(target: (document: string, member: Member) => string) {
16
+ const clients = new Map<string, Client>(), requests = new Map<string, Pending>()
17
+ let closed = false
18
+ const authorize = (member: Member) => { if (closed) throw new RequestError(503, 'window-owner-closed'); if (!hasRole(member, 'owner')) throw new RequestError(403, 'window-permission-denied') }
19
+ const clientKey = (member: string, clientId: string) => JSON.stringify([member, clientId])
20
+ const requestKey = (member: string, value: AuthoringWindowReference) => JSON.stringify([member, value.clientId, value.epoch, value.requestId])
21
+ const finish = (pending: Pending, state: AuthoringWindowRequestResult['state'], code?: string) => {
22
+ if (terminal(pending)) return
23
+ clearTimeout(pending.timer); pending.timer = undefined
24
+ pending.value = { ...pending.value, state, ...code ? { error: { code } } : {} }
25
+ if (state === 'expired') clients.get(clientKey(pending.member, pending.request.clientId))?.send?.({ type: 'cancel', requestId: pending.request.requestId, connectionId: pending.request.connectionId })
26
+ }
27
+ const disconnect = (client: Client, connectionId: string) => {
28
+ if (client.value.connectionId !== connectionId) return
29
+ client.value = { ...client.value, connected: false }; client.send = undefined; client.close = undefined
30
+ for (const pending of requests.values()) if (!terminal(pending) && pending.member === client.member && pending.request.clientId === client.value.clientId && pending.request.connectionId === connectionId) finish(pending, 'expired', 'window-disconnected')
31
+ }
32
+ const connection = (lease: AuthoringWindowLease, member: Member) => {
33
+ authorize(member)
34
+ const client = clients.get(clientKey(member.id, lease.clientId))
35
+ if (!client?.value.connected || client.value.epoch !== lease.epoch || client.value.connectionId !== lease.connectionId || client.credential !== lease.credential) throw new RequestError(409, 'window-connection-changed')
36
+ return client
37
+ }
38
+ const targetCurrent = (request: AuthoringWindowRequest, member: Member) => {
39
+ if (request.action.type === 'document.open') {
40
+ if (!request.target || request.target.document !== request.action.document || target(request.target.document, member) !== request.target.documentId) throw new RequestError(409, 'window-target-changed')
41
+ } else if (request.target) throw new RequestError(400, 'window-request-invalid')
42
+ }
43
+ const readResult = (pending: Pending, member: Member): AuthoringWindowRequestResult => {
44
+ const client = clients.get(clientKey(member.id, pending.request.clientId)), value = pending.value
45
+ let current = Boolean(client?.value.connected && client.value.epoch === value.epoch && client.value.connectionId === value.connectionId && value.snapshot && digest(client.value.snapshot) === digest(value.snapshot))
46
+ try { targetCurrent(pending.request, member) } catch { current = false }
47
+ return structuredClone({ ...value, current })
48
+ }
49
+ const report = (client: Client, value: AuthoringWindowReport) => {
50
+ const signature = digest(value)
51
+ if (value.sequence < client.sequence || value.sequence === client.sequence && signature !== client.signature || value.snapshot.revision < client.value.snapshot.revision) throw new RequestError(409, 'window-report-superseded')
52
+ if (value.sequence === client.sequence) return
53
+ client.sequence = value.sequence; client.signature = signature
54
+ client.value = { ...client.value, snapshot: structuredClone(value.snapshot), observedAt: new Date().toISOString() }
55
+ }
56
+ const retained = (reference: AuthoringWindowReference | string, member: Member) => {
57
+ authorize(member); budget(reference)
58
+ if (typeof reference === 'string') {
59
+ if (!validateAuthoringWindowHandle(reference)) throw new RequestError(400, 'window-query-invalid')
60
+ const matches = [...requests.values()].filter(value => value.member === member.id && value.request.requestId === reference)
61
+ if (matches.length > 1) throw new RequestError(409, 'window-query-ambiguous')
62
+ if (!matches[0]) throw new RequestError(404, 'window-request-not-found')
63
+ return matches[0]
64
+ }
65
+ if (!validateAuthoringClientRequestQuery(reference)) throw new RequestError(400, 'window-query-invalid')
66
+ const pending = requests.get(requestKey(member.id, reference))
67
+ if (!pending) throw new RequestError(404, 'window-request-not-found')
68
+ return pending
69
+ }
70
+ const service: AuthoringWindows = {
71
+ async list(query, member) {
72
+ authorize(member); budget(query)
73
+ if (!validateAuthoringClientQuery(query)) throw new RequestError(400, 'window-query-invalid')
74
+ const all = [...clients.values()].filter(client => client.member === member.id && (!query.clientId || client.value.clientId === query.clientId) && (!query.after || client.value.clientId > query.after)).sort((a, b) => a.value.clientId.localeCompare(b.value.clientId))
75
+ const answer = { scope: 'workspace' as const, clients: [] as AuthoringWindowDescriptor[] }
76
+ for (const client of all) {
77
+ const value = structuredClone(client.value), pending = [...requests.values()].find(request => request.member === member.id && request.request.clientId === value.clientId && !terminal(request))
78
+ if (pending) { value.pendingRequest = { requestId: pending.request.requestId, action: pending.request.action.type, ...pending.value.cancellationRequested ? { cancellationRequested: true } : {} }; value.snapshot.actions = [] }
79
+ if (size({ ...answer, clients: [...answer.clients, value], nextAfter: value.clientId }) > AUTHORING_CLIENT_MAX_RESPONSE_CHARS) break
80
+ answer.clients.push(value)
81
+ }
82
+ if (all.length && !answer.clients.length) throw new RequestError(413, 'window-state-too-large')
83
+ return { ...answer, ...answer.clients.length < all.length ? { nextAfter: answer.clients.at(-1)!.clientId } : {} }
84
+ },
85
+ async request(request, member) {
86
+ authorize(member); budget(request)
87
+ if (!validateAuthoringWindowRequest(request)) throw new RequestError(400, 'window-request-invalid')
88
+ const key = requestKey(member.id, request), signature = digest(request), known = requests.get(key)
89
+ if (known) { if (signature !== known.signature) throw new RequestError(409, 'window-request-id-reused'); return readResult(known, member) }
90
+ const client = clients.get(clientKey(member.id, request.clientId)), state = client?.value
91
+ if (!state?.connected || state.epoch !== request.epoch || state.connectionId !== request.connectionId) throw new RequestError(409, 'window-unavailable')
92
+ if (state.snapshot.revision !== request.revision) throw new RequestError(409, 'window-state-changed')
93
+ if (!state.snapshot.actions.includes(request.action.type)) throw new RequestError(409, 'window-action-unavailable')
94
+ if ([...requests.values()].some(value => value.member === member.id && value.request.clientId === request.clientId && !terminal(value))) throw new RequestError(409, 'window-busy')
95
+ targetCurrent(request, member)
96
+ while (requests.size >= AUTHORING_CLIENT_MAX_REQUESTS) { const old = [...requests].find(([, value]) => terminal(value)); if (!old) throw new RequestError(429, 'window-request-capacity'); requests.delete(old[0]) }
97
+ const now = Date.now(), value: AuthoringWindowRequestResult = { clientId: state.clientId, epoch: state.epoch, connectionId: state.connectionId, requestId: request.requestId, action: request.action.type,
98
+ state: 'sent', admittedAt: new Date(now).toISOString(), expiresAt: new Date(now + AUTHORING_CLIENT_REQUEST_TIMEOUT_MS).toISOString(), acknowledged: false, current: false }
99
+ const pending: Pending = { member: member.id, signature, request: structuredClone(request), value }
100
+ pending.timer = setTimeout(() => finish(pending, 'expired', 'window-request-timeout'), AUTHORING_CLIENT_REQUEST_TIMEOUT_MS)
101
+ requests.set(key, pending); client!.send?.({ type: 'request', request: pending.request, expiresAt: value.expiresAt })
102
+ return readResult(pending, member)
103
+ },
104
+ async get(reference, member) { return readResult(retained(reference, member), member) },
105
+ async cancel(reference, member) {
106
+ const pending = retained(reference, member)
107
+ if (!terminal(pending) && !pending.value.cancellationRequested) { pending.value.cancellationRequested = true; clients.get(clientKey(member.id, pending.request.clientId))?.send?.({ type: 'cancel', requestId: pending.request.requestId, connectionId: pending.value.connectionId }) }
108
+ return readResult(pending, member)
109
+ },
110
+ }
111
+ const register = (value: AuthoringWindowOpen, member: Member): AuthoringWindowLease => {
112
+ authorize(member)
113
+ const key = clientKey(member.id, value.clientId), old = clients.get(key)
114
+ if (!old && clients.size >= AUTHORING_CLIENT_MAX_CLIENTS) { const disposable = [...clients].find(([, client]) => !client.value.connected); if (!disposable) throw new RequestError(429, 'window-capacity'); clients.delete(disposable[0]) }
115
+ old?.close?.()
116
+ const credential = randomBytes(32).toString('base64url'), connectionId = randomUUID()
117
+ clients.set(key, { member: member.id, credential, sequence: -1, value: { clientId: value.clientId, epoch: value.epoch, connectionId, connected: false, snapshot: structuredClone(value.snapshot), observedAt: new Date().toISOString() } })
118
+ return { clientId: value.clientId, epoch: value.epoch, connectionId, credential }
119
+ }
120
+ const acknowledge = (lease: AuthoringWindowLease, value: AuthoringWindowAcknowledgement, member: Member) => {
121
+ const client = connection(lease, member), pending = requests.get(requestKey(member.id, { ...lease, requestId: value.requestId }))
122
+ if (pending && Date.now() >= Date.parse(pending.value.expiresAt)) finish(pending, 'expired', 'window-request-timeout')
123
+ if (!pending || terminal(pending) || pending.request.connectionId !== lease.connectionId) throw new RequestError(409, 'window-request-expired')
124
+ if (value.state === 'executing' && pending.value.cancellationRequested) throw new RequestError(409, 'window-request-cancelled')
125
+ if (value.state === 'executing' && pending.value.state !== 'sent' || value.state === 'done' && pending.value.state !== 'executing') throw new RequestError(409, 'window-ack-state-invalid')
126
+ if (value.state !== 'done' && value.outcome !== undefined || (value.state === 'done' || value.state === 'executing') && value.error) throw new RequestError(400, 'window-ack-invalid')
127
+ if (value.state === 'executing' && (value.snapshot.revision !== pending.request.revision || digest(value.snapshot) !== digest(client.value.snapshot))) throw new RequestError(409, 'window-state-changed')
128
+ if (value.state === 'executing' || value.state === 'done') targetCurrent(pending.request, member)
129
+ if (value.state === 'done') {
130
+ const action = pending.request.action, location = value.snapshot.location
131
+ if (value.snapshot.revision < pending.request.revision || action.type === 'window.read' && (value.outcome !== 'observed' || value.snapshot.revision !== pending.request.revision)
132
+ || action.type === 'document.open' && (!['opened', 'unchanged'].includes(value.outcome ?? '') || location.type !== 'document' || location.status !== 'ready' || location.document !== action.document || location.documentId !== pending.request.target?.documentId)
133
+ || action.type === 'document.close' && (!['closed', 'unchanged'].includes(value.outcome ?? '') || location.type !== 'home')) throw new RequestError(409, 'window-action-not-verified')
134
+ }
135
+ report(client, value)
136
+ pending.value = { ...pending.value, snapshot: structuredClone(value.snapshot), ...value.outcome ? { outcome: value.outcome } : {}, ...value.error ? { error: value.error } : {}, acknowledged: true }
137
+ if (value.state === 'executing') pending.value.state = 'executing'; else finish(pending, value.state)
138
+ return { accepted: true }
139
+ }
140
+ const post = (kind: 'register' | 'report' | 'ack'): Route => ({ role: 'owner', maxBody: 16384, handle: (request, ctx) => catchRequestErrors(async () => {
141
+ if (request.method !== 'POST') return problemResponse(405, 'POST')
142
+ const value: unknown = await request.json().catch(() => undefined); budget(value, AUTHORING_CLIENT_MAX_RESPONSE_CHARS)
143
+ if (kind === 'register') { if (!validateAuthoringWindowOpen(value)) throw new RequestError(400, 'window-open-invalid'); return jsonResponse(register(value, ctx.member)) }
144
+ if (!isRecord(value) || Object.keys(value).some(key => !['connection', 'report'].includes(key)) || !validateAuthoringClientLease(value.connection)) throw new RequestError(400, 'window-connection-invalid')
145
+ if (kind === 'ack') { if (!validateAuthoringWindowAcknowledgement(value.report)) throw new RequestError(400, 'window-ack-invalid'); return jsonResponse(acknowledge(value.connection, value.report, ctx.member)) }
146
+ if (!validateAuthoringWindowReport(value.report)) throw new RequestError(400, 'window-report-invalid')
147
+ report(connection(value.connection, ctx.member), value.report); return jsonResponse({ accepted: true })
148
+ }) })
149
+ return { service, routes: {
150
+ 'authoring-windows/register': post('register'), 'authoring-windows/report': post('report'), 'authoring-windows/ack': post('ack'),
151
+ 'authoring-windows/events': { role: 'owner', handle: (request, ctx) => catchRequestErrors(async () => {
152
+ authorize(ctx.member)
153
+ if (request.method !== 'GET') return problemResponse(405, 'GET')
154
+ const query = new URL(request.url).searchParams, lease = { clientId: query.get('clientId'), epoch: query.get('epoch'), connectionId: query.get('connectionId'), credential: request.headers.get('X-Presmium-Authoring-Client') }
155
+ if (!validateAuthoringClientLease(lease)) throw new RequestError(400, 'window-connection-invalid')
156
+ const client = clients.get(clientKey(ctx.member.id, lease.clientId))
157
+ if (!client || client.value.epoch !== lease.epoch || client.credential !== lease.credential) throw new RequestError(409, 'window-connection-changed')
158
+ client.close?.(); const connectionId = randomUUID()
159
+ client.value = { ...client.value, connected: true, connectionId }
160
+ const stream = pushStream<{ event: string, data: AuthoringWindowEvent }>(push => { client.send = data => push({ event: 'authoring-client', data }); return () => disconnect(client, connectionId) }, { signal: request.signal })
161
+ client.close = () => stream.end(); client.send?.({ type: 'connected', connectionId })
162
+ return sseResponse(stream, request.signal)
163
+ }) } satisfies Route,
164
+ }, async close() { closed = true; for (const client of clients.values()) client.close?.(); for (const pending of requests.values()) finish(pending, 'expired', 'window-owner-closed'); clients.clear(); requests.clear() } }
165
+ }
package/src/node/serve.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import { createProjectAuthoring } from './projects.ts'
2
2
  import { createDocumentHistory } from './document-history.ts'
3
3
  import { createAuthoringClients } from './authoring-clients.ts'
4
+ import { createAuthoringWindows } from './authoring-windows.ts'
5
+ import { readAuthoringDocument } from './document-editor.ts'
4
6
  import { createDocumentCapture } from './capture.ts'
5
7
  import { mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'
6
8
  import { stripVTControlCharacters } from 'node:util'
@@ -124,6 +126,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
124
126
  let workspaceChanges: ReturnType<typeof createWorkspaceChanges> | undefined
125
127
  let projectAuthoring: ReturnType<typeof createProjectAuthoring> | undefined
126
128
  let authoringClients: ReturnType<typeof createAuthoringClients> | undefined
129
+ let authoringWindows: ReturnType<typeof createAuthoringWindows> | undefined
127
130
  let transcriptions: ReturnType<typeof createDocumentTranscriptions> | undefined
128
131
  let transcriptionAdoption: ReturnType<typeof createTranscriptionAdoption> | undefined
129
132
  let audioAuthoring: ReturnType<typeof createDocumentAudioAuthoring> | undefined
@@ -205,7 +208,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
205
208
  authoringServicesClosed = true
206
209
  transcriptionAdoption?.close()
207
210
  for (const load of nodeServicePending) load.controller.abort()
208
- await Promise.all([projectAuthoring?.close(), transcriptions?.close(), audioAuthoring?.close(), voiceAuthoring?.close(), documentHistory?.close(), authoringClients?.close(), workspaceRoutesOwner?.close?.()])
211
+ await Promise.all([projectAuthoring?.close(), transcriptions?.close(), audioAuthoring?.close(), voiceAuthoring?.close(), documentHistory?.close(), authoringClients?.close(), authoringWindows?.close(), workspaceRoutesOwner?.close?.()])
209
212
  await Promise.allSettled([...nodeServicePending].map(load => load.promise))
210
213
  nodeServiceLoads.clear()
211
214
  }
@@ -274,6 +277,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
274
277
  get documentHistory() { return documentHistory?.service },
275
278
  get projectAuthoring() { return projectAuthoring?.service },
276
279
  get authoringClients() { return authoringClients?.service },
280
+ get authoringWindows() { return authoringWindows?.service },
277
281
  get audioAuthoring() { return audioAuthoring?.service },
278
282
  get imageAuthoring() { return imageAuthoring?.service },
279
283
  get voiceAuthoring() { return voiceAuthoring?.service },
@@ -399,6 +403,10 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
399
403
  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' })
400
404
  projectAuthoring = createProjectAuthoring({ config, documentEditor, operations: history?.operations, revisions: history?.revisions, git: history?.git })
401
405
  authoringClients = createAuthoringClients(editor, { reviewRequired: config.settings['presmium.assistant']?.review === 'required' })
406
+ authoringWindows = createAuthoringWindows((document, member) => {
407
+ if (!docs().some(value => value.dir === document)) throw new RequestError(404, 'window-target-unavailable')
408
+ return readAuthoringDocument(editor, { document, member }).content.id
409
+ })
402
410
  documentHistory = createDocumentHistory({ config, editor, locks, revisions: history?.revisions, reviewRequired: config.settings['presmium.assistant']?.review === 'required', changed: (before, after) => documentsChanged(documentsDiff(before, after)), reverted: (target, revision) => history?.agentSessionReviews.reverted(target, revision) })
403
411
  transcriptions = createDocumentTranscriptions({ root, editor, services: authoringServices })
404
412
  transcriptionAdoption = createTranscriptionAdoption({ documentEditor, transcriptions })
@@ -415,7 +423,7 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
415
423
  audioAuthoringRoutes: audioAuthoring.routes,
416
424
  imageAuthoringRoutes: imageAuthoring.routes,
417
425
  historyRoutes: documentHistory.routes,
418
- authoringClientRoutes: authoringClients.routes,
426
+ authoringClientRoutes: { ...authoringClients.routes, ...authoringWindows.routes },
419
427
  projectRoutes: projectAuthoring.routes,
420
428
  locks,
421
429
  ...history ? { revisions: history.revisions, operations: history.operations, reviews: history.agentSessionReviews } : {},