@lincyaw/workspace 1.0.0-rc.116 → 1.0.0-rc.117

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.116",
3
+ "version": "1.0.0-rc.117",
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/compiler": "1.0.0-rc.116",
38
- "@lincyaw/server": "1.0.0-rc.116",
39
- "@lincyaw/kernel": "1.0.0-rc.116",
40
- "@lincyaw/design": "1.0.0-rc.116"
37
+ "@lincyaw/server": "1.0.0-rc.117",
38
+ "@lincyaw/kernel": "1.0.0-rc.117",
39
+ "@lincyaw/design": "1.0.0-rc.117",
40
+ "@lincyaw/compiler": "1.0.0-rc.117"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@types/mime-types": "^3.0.1",
44
- "@lincyaw/mcp": "1.0.0-rc.116"
44
+ "@lincyaw/mcp": "1.0.0-rc.117"
45
45
  }
46
46
  }
@@ -59,7 +59,7 @@ export async function readDocumentAudioBytes(editor: SourceEditor, ctx: RequestC
59
59
  }
60
60
 
61
61
  /** Owns the canonical transaction and receipts; plugin services only inspect actual media. */
62
- export function createDocumentAudioAuthoring({ root, editor, revisions, audio, services, reviewRequired = false, uploads }: DocumentAudioAuthoringOptions): { service: DocumentAudioAuthoring, routes: Record<string, Route>, close(): Promise<void> } {
62
+ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, services, reviewRequired = false, uploads }: DocumentAudioAuthoringOptions): { service: DocumentAudioAuthoring, routes: Record<string, Route>, busy(): boolean, close(): Promise<void> } {
63
63
  const receipts = new Map<string, Receipt>(), imports = new Map<string, { signature: string, source: CanonicalSource, promise: Promise<VerifiedDocumentAudioImport> }>(), operations = new Set<Operation>()
64
64
  const clipChanges = new Map<string, { signature: string, promise: Promise<VerifiedDocumentMediaClipChange> }>()
65
65
  const recordingChanges = new Map<string, { signature: string, promise: Promise<VerifiedDocumentRecordingAdoption> }>()
@@ -488,5 +488,5 @@ export function createDocumentAudioAuthoring({ root, editor, revisions, audio, s
488
488
  }),
489
489
  },
490
490
  }
491
- return { service, routes, async close() { closed = true; for (const operation of operations) operation.controller.abort(); await Promise.allSettled([...operations].map(operation => operation.finished)); receipts.clear() } }
491
+ return { service, routes, busy: () => operations.size > 0, async close() { closed = true; for (const operation of operations) operation.controller.abort(); await Promise.allSettled([...operations].map(operation => operation.finished)); receipts.clear() } }
492
492
  }
@@ -35,7 +35,7 @@ function inspect(bytes: Uint8Array) {
35
35
  }
36
36
 
37
37
  /** Original bytes and the canonical asset bank are committed or rolled back together. */
38
- export function createDocumentImageAuthoring({ root, editor, revisions, reviewRequired = false, uploads }: Options): { service: DocumentImageAuthoring, routes: Record<string, Route> } {
38
+ export function createDocumentImageAuthoring({ root, editor, revisions, reviewRequired = false, uploads }: Options): { service: DocumentImageAuthoring, routes: Record<string, Route>, busy(): boolean } {
39
39
  const receipts = new Map<string, Receipt>(), pending = new Map<string, { signature: string, done: Promise<DocumentImageImportAnswer> }>()
40
40
  const binding = (current: ReturnType<typeof readAuthoringDocument>): CanonicalSource => ({ documentId: current.content.id, version: current.source.version, fingerprint: fnv1a64(current.source.content) })
41
41
  const opened = (ctx: RequestContext, version?: string, source?: CanonicalSource) => {
@@ -247,5 +247,5 @@ export function createDocumentImageAuthoring({ root, editor, revisions, reviewRe
247
247
  return jsonResponse(await apply(ctx, change, title, bytes, image, hash, request.signal, 'editor'))
248
248
  }) },
249
249
  }
250
- return { service, routes }
250
+ return { service, routes, busy: () => active > 0 || pending.size > 0 }
251
251
  }
@@ -75,7 +75,7 @@ async function writeJson(path: string, value: unknown, exclusive = false): Promi
75
75
  }
76
76
 
77
77
  /** Recognition is an immutable candidate. Only a later, separate authoring action may adopt it. */
78
- export function createDocumentTranscriptions({ root, editor, audio, speech, services }: Options): DocumentTranscriptions & { close(): Promise<void> } {
78
+ export function createDocumentTranscriptions({ root, editor, audio, speech, services }: Options): DocumentTranscriptions & { busy(): boolean, close(): Promise<void> } {
79
79
  const active = new Map<string, Active>()
80
80
  const admitting = new Map<string, { document: string, documentId: string, member: string, intent: string, controller: AbortController, finished: Promise<void> }>()
81
81
  let closed = false
@@ -266,6 +266,7 @@ export function createDocumentTranscriptions({ root, editor, audio, speech, serv
266
266
  }
267
267
  }
268
268
  return {
269
+ busy: () => active.size > 0 || admitting.size > 0,
269
270
  capabilities,
270
271
  async list(document, member): Promise<TranscriptionListAnswer> {
271
272
  const path = join(dirname(authorize(document, member)), 'transcriptions'), observation = observe(document, member)
@@ -209,5 +209,5 @@ export function createDocumentVoiceAuthoring({ editor, services, prepareExecutio
209
209
  },
210
210
  readPreview: async (document, id, member) => ownerOf(document, member).readPreview(id),
211
211
  }
212
- return { service, routes: createVoiceoverRoutes(service), async close() { closed = true; for (const { prepared } of clones.values()) prepared.close(); for (const operation of pending) operation.controller.abort(); await Promise.allSettled([...owners.values()].map(owner => owner.close())); await Promise.allSettled([...pending].map(operation => operation.finished)); owners.clear() } }
212
+ return { service, routes: createVoiceoverRoutes(service), busy: () => pending.size > 0 || [...owners.values()].some(owner => owner.busy()), async close() { closed = true; for (const { prepared } of clones.values()) prepared.close(); for (const operation of pending) operation.controller.abort(); await Promise.allSettled([...owners.values()].map(owner => owner.close())); await Promise.allSettled([...pending].map(operation => operation.finished)); owners.clear() } }
213
213
  }
@@ -0,0 +1,17 @@
1
+ /** Admission is frozen atomically with the idle check, before releasing the workspace host. */
2
+ export function createHostActivity() {
3
+ let active = 0, stopped = false
4
+ return {
5
+ begin(): (() => void) | undefined {
6
+ if (stopped) return undefined
7
+ active++
8
+ let finished = false
9
+ return () => { if (!finished) { finished = true; active-- } }
10
+ },
11
+ quiesce(): boolean {
12
+ if (active) return false
13
+ stopped = true
14
+ return true
15
+ },
16
+ }
17
+ }
@@ -0,0 +1,28 @@
1
+ import { isRecord, jsonResponse, problemResponse } from '@lincyaw/kernel'
2
+ import type { Route } from '@lincyaw/kernel'
3
+ import { compareServiceVersion, SERVICE_VERSION } from '@lincyaw/kernel/node'
4
+ import type { DocumentLocks } from './locks.ts'
5
+ import type { Jobs } from './jobs.ts'
6
+
7
+ /** Only the launcher's authenticated owner route can release this host for a newer runtime. */
8
+ export function hostUpgradeRoute(locks: DocumentLocks, jobs: Jobs, quiesce: () => boolean, upgrade: (version: string) => void): Route {
9
+ let upgrading = false
10
+ return { role: 'owner', maxBody: 1024, async handle(request) {
11
+ if (request.method !== 'POST') return problemResponse(405, 'POST')
12
+ const body: unknown = await request.json().catch(() => undefined)
13
+ if (!isRecord(body) || body.pid !== process.pid || typeof body.version !== 'string' || Object.keys(body).some(key => !['pid', 'version'].includes(key))) return problemResponse(400, 'host-upgrade-invalid')
14
+ try {
15
+ if (compareServiceVersion({ version: SERVICE_VERSION }, body.version) >= 0) return problemResponse(409, 'host-upgrade-version')
16
+ } catch { return problemResponse(400, 'host-upgrade-invalid') }
17
+ if (upgrading) return jsonResponse({ upgrading: true })
18
+ if (jobs.list().some(job => job.state === 'running' || job.state === 'queued')) return problemResponse(409, 'host-upgrade-busy')
19
+ const release = locks.claim('', 'upgrade')
20
+ if (!release) return problemResponse(409, 'host-upgrade-busy')
21
+ if (!quiesce()) { release(); return problemResponse(409, 'host-upgrade-busy') }
22
+ // Hold the workspace-wide write lock until the host closes. The response must leave before closing HTTP.
23
+ upgrading = true
24
+ const version = body.version
25
+ setTimeout(() => upgrade(version), 0)
26
+ return jsonResponse({ upgrading: true })
27
+ } }
28
+ }
@@ -67,6 +67,7 @@ export interface WorkspaceRoutesOptions {
67
67
  changesRoutes?: Record<string, Route>
68
68
  /** Shared mutable allow-list; a later local Studio may register its preview origin. */
69
69
  previewOrigins?: string[]
70
+ hostUpgrade?: Route
70
71
  }
71
72
 
72
73
  function toRendererIds(body: unknown): string[] | undefined {
@@ -91,6 +92,7 @@ export function workspaceRoutes(options: WorkspaceRoutesOptions): ServerContribu
91
92
  const transcriptions = options.transcriptions ?? ownedTranscriptions!
92
93
  const ownedAudio = options.audioAuthoringRoutes ? undefined : createDocumentAudioAuthoring({ root: config.root, editor, revisions, audio: options.audio, reviewRequired: config.settings['presmium.assistant']?.review === 'required' })
93
94
  const routes: Record<string, Route> = {
95
+ ...options.hostUpgrade ? { 'host-upgrade': options.hostUpgrade } : {},
94
96
  ...options.previewOrigins ? { 'preview-origins': {
95
97
  role: 'owner', maxBody: 8192,
96
98
  handle: async (request: Request) => {
package/src/node/serve.ts CHANGED
@@ -14,7 +14,7 @@ import { join, relative, resolve } from 'node:path'
14
14
  import { Compiler, operatorDir as resolveOperatorDir, pluginLogger, runBlock, workspacePlugins } from '@lincyaw/compiler'
15
15
  import type { Compilation, CompilerOptions } from '@lincyaw/compiler'
16
16
  import { CHANGE_REVIEW, DOCUMENT_FILES, DOCUMENT_LOCKS, DOCUMENT_VOICE_TASKS, errorMessage, PreviewPreparing, PRODUCTION_AUDIO_AUTHORING, REVISIONS, SPEECH, VOICEOVER, VOICEOVER_EXECUTION } from '@lincyaw/kernel'
17
- import { irRevision, OperatorSpeechSettings, readServiceState, removeServiceState, serveStateDir, tryAcquireServiceHostLease } from '@lincyaw/kernel/node'
17
+ import { compareServiceVersion, irRevision, OperatorSpeechSettings, readServiceState, removeServiceState, serveStateDir, SERVICE_VERSION, tryAcquireServiceHostLease, upgradeWorkspaceService } from '@lincyaw/kernel/node'
18
18
  import type { ServiceHostLease } from '@lincyaw/kernel/node'
19
19
  import { createMcpSettings } from './mcp-settings.ts'
20
20
  import { speechSettingsRoute } from './speech-settings.ts'
@@ -51,6 +51,8 @@ import { createWorkbenchBackend } from './workbench-api.ts'
51
51
  import type { WorkbenchBackend } from './workbench-api.ts'
52
52
  import { localWriter } from './writer.ts'
53
53
  import { documentImportRoute } from './document-import.ts'
54
+ import { hostUpgradeRoute } from './host-upgrade.ts'
55
+ import { createHostActivity } from './host-activity.ts'
54
56
 
55
57
  export interface ServeOptions {
56
58
  dir: string
@@ -70,6 +72,8 @@ export interface ServeOptions {
70
72
  /** A launcher may reserve the shared workspace host before starting it. Released after close. */
71
73
  hostLease?: ServiceHostLease
72
74
  signal?: AbortSignal
75
+ /** A CLI host ends its process after a graceful upgrade; stdio relays remain separate. */
76
+ onUpgrade?(version: string): void
73
77
  }
74
78
 
75
79
  export interface WorkspaceServer {
@@ -102,7 +106,11 @@ function makeStateDir(root: string, env: NodeJS.ProcessEnv): string {
102
106
 
103
107
  export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceServer> {
104
108
  const root = realpathSync(resolve(options.dir)), env = options.env ?? process.env
105
- const advertised = readServiceState(join(serveStateDir(root, env), 'server.json'))
109
+ let advertised = readServiceState(join(serveStateDir(root, env), 'server.json'))
110
+ if (advertised && compareServiceVersion(advertised, SERVICE_VERSION) < 0) {
111
+ await upgradeWorkspaceService(root, advertised, SERVICE_VERSION, env, options.signal)
112
+ advertised = readServiceState(join(serveStateDir(root, env), 'server.json'))
113
+ }
106
114
  if (advertised) throw Object.assign(new Error('workspace-service-already-running'), { code: 'workspace-service-already-running', url: advertised.url })
107
115
  const lease = options.hostLease ?? await tryAcquireServiceHostLease(root, env)
108
116
  if (!lease) {
@@ -124,7 +132,10 @@ export async function serveWorkspace(options: ServeOptions): Promise<WorkspaceSe
124
132
  try {
125
133
  lease.signal.throwIfAborted()
126
134
  options.signal?.throwIfAborted()
127
- running = await startWorkspace(options)
135
+ running = await startWorkspace({ ...options, onUpgrade: version => {
136
+ options.onUpgrade?.(version)
137
+ void close().catch(error => (options.log ?? pluginLogger('presmium serve')).error(errorMessage(error)))
138
+ } })
128
139
  lease.signal.throwIfAborted()
129
140
  options.signal?.throwIfAborted()
130
141
  lease.signal.addEventListener('abort', compromised, { once: true })
@@ -153,6 +164,7 @@ async function startWorkspace(options: ServeOptions): Promise<WorkspaceServer> {
153
164
  const compileSessions = new Map<string, CompileSession>()
154
165
  const agentToolListeners = new Set<(document: string) => void>()
155
166
  const locks = new DocumentLocks()
167
+ const activity = createHostActivity()
156
168
  const writer = localWriter(config)
157
169
  const editor = new SourceEditor({ config, writer, locks, beforeWrite: (paths, historyLocked) => historyLocked ? captureLocalBaseline(historyGit, paths) : historyGit.exclusive(() => captureLocalBaseline(historyGit, paths)) })
158
170
  const check = options.check ?? (compilation => compilation.check())
@@ -324,6 +336,7 @@ async function startWorkspace(options: ServeOptions): Promise<WorkspaceServer> {
324
336
  const ready = new Promise<void>(resolve => started = resolve)
325
337
 
326
338
  const serverHost: ServerHost = {
339
+ beginOperation: route => route?.plugin === WORKSPACE_ID && route.path === 'host-upgrade' ? () => {} : activity.begin(),
327
340
  agentActivity: agentActivity.service,
328
341
  workspaceRoot: root,
329
342
  get authoring() { return documentEditor },
@@ -502,6 +515,7 @@ async function startWorkspace(options: ServeOptions): Promise<WorkspaceServer> {
502
515
  workbench,
503
516
  jobs,
504
517
  previewOrigins: preview.origins,
518
+ hostUpgrade: hostUpgradeRoute(locks, jobs, () => !transcriptions?.busy() && !voiceAuthoring?.busy() && !audioAuthoring?.busy() && !imageAuthoring?.busy() && activity.quiesce(), version => options.onUpgrade?.(version)),
505
519
  ...launcherToken ? { launcherToken } : {},
506
520
  }
507
521
  workspaceRoutesOwner = workspaceRoutes(routeOptions)
@@ -559,7 +573,7 @@ async function startWorkspace(options: ServeOptions): Promise<WorkspaceServer> {
559
573
  site = await startWorkspaceSite({ root, spec, basePath, bundled: options.bundled, stateDir, compile: compileForSite, stampPreviewRevision: (compilation, doc) => workbench!.stampPreviewRevision(compilation, doc), diagnostics: running.diagnostics, preview, log })
560
574
  options.signal?.throwIfAborted()
561
575
  // Publish only the fully assembled authoring host. Another MCP client may discover it immediately.
562
- writeFileSync(stateFile, `${JSON.stringify({ url: running.url, mcp: `${running.url}/mcp`, token: running.mcpToken, pid: process.pid, launcherToken }, null, 2)}\n`, { mode: 0o600 })
576
+ writeFileSync(stateFile, `${JSON.stringify({ url: running.url, mcp: `${running.url}/mcp`, token: running.mcpToken, pid: process.pid, launcherToken, version: SERVICE_VERSION }, null, 2)}\n`, { mode: 0o600 })
563
577
  chmodSync(stateFile, 0o600)
564
578
  } catch (error) {
565
579
  await closeHost()