@lincyaw/kernel 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/kernel",
3
- "version": "1.0.0-rc.116",
3
+ "version": "1.0.0-rc.117",
4
4
  "description": "Presmium's shared kernel: the IR and plugin contracts, the service registry, anchors and checks",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
package/src/node/index.ts CHANGED
@@ -28,7 +28,8 @@ export { validateProjectPlan, validateProjectApply } from './projects.ts'
28
28
  export { validateDocumentWorkspaceImageInspect, validateDocumentWorkspaceImageImport } from './document-image.ts'
29
29
  export { systemLocale } from './locale.ts'
30
30
  export { OperatorSpeechSettings, operatorSpeechSecrets, SpeechSettingsError, validateSpeechSettingsChange } from './operator-speech.ts'
31
- export { devStateFile, findWorkspaceServiceState, readServiceState, removeServiceState, serveStateDir } from './service-state.ts'
31
+ export { devStateFile, findWorkspaceServiceState, readServiceState, removeServiceState, serveStateDir, SERVICE_VERSION } from './service-state.ts'
32
+ export { compareServiceVersion, ServiceUpgradeError, upgradeWorkspaceService } from './service-upgrade.ts'
32
33
  export type { ServiceState } from './service-state.ts'
33
34
  export { tryAcquireServiceHostLease } from './service-lease.ts'
34
35
  export type { ServiceHostLease } from './service-lease.ts'
@@ -1,15 +1,20 @@
1
1
  import { createHash } from 'node:crypto'
2
2
  import { readFileSync, realpathSync, rmSync } from 'node:fs'
3
3
  import { homedir } from 'node:os'
4
+ import { createRequire } from 'node:module'
4
5
  import { dirname, join, resolve } from 'node:path'
5
6
  import { isRecord } from '../errors.ts'
6
7
 
8
+ /** Captured when this runtime loads; replacing the installation must not relabel a running host. */
9
+ export const SERVICE_VERSION = (createRequire(import.meta.url)('../../package.json') as { version: string }).version
10
+
7
11
  /** What a running Presmium server records for local clients: its address, its MCP endpoint and token, its process. */
8
12
  export interface ServiceState {
9
13
  url: string
10
14
  mcp: string
11
15
  token: string
12
16
  pid: number
17
+ version?: string
13
18
  /** Local launcher credential for Studio reuse; never include it in MCP tool results. */
14
19
  launcherToken?: string
15
20
  }
@@ -39,7 +44,7 @@ export function readServiceState(file: string): ServiceState | undefined {
39
44
  try {
40
45
  const state: unknown = JSON.parse(readFileSync(file, 'utf8'))
41
46
  if (!isRecord(state) || typeof state.url !== 'string' || typeof state.mcp !== 'string' || typeof state.token !== 'string' || typeof state.pid !== 'number') return undefined
42
- return alive(state.pid) ? { url: state.url, mcp: state.mcp, token: state.token, pid: state.pid, ...typeof state.launcherToken === 'string' && state.launcherToken ? { launcherToken: state.launcherToken } : {} } : undefined
47
+ return alive(state.pid) ? { url: state.url, mcp: state.mcp, token: state.token, pid: state.pid, ...typeof state.version === 'string' ? { version: state.version } : {}, ...typeof state.launcherToken === 'string' && state.launcherToken ? { launcherToken: state.launcherToken } : {} } : undefined
43
48
  } catch {
44
49
  return undefined
45
50
  }
@@ -0,0 +1,68 @@
1
+ import { join } from 'node:path'
2
+ import { setTimeout as delay } from 'node:timers/promises'
3
+ import semver from 'semver'
4
+ import { readServiceState, serveStateDir } from './service-state.ts'
5
+ import type { ServiceState } from './service-state.ts'
6
+ import { tryAcquireServiceHostLease } from './service-lease.ts'
7
+
8
+ export class ServiceUpgradeError extends Error {
9
+ readonly reason: 'busy' | 'newer' | 'unavailable'
10
+ readonly version?: string
11
+ constructor(reason: 'busy' | 'newer' | 'unavailable', version?: string) {
12
+ super(`workspace-service-upgrade-${reason}`)
13
+ this.reason = reason
14
+ this.version = version
15
+ }
16
+ }
17
+
18
+ /** A newer stdio relay can use the current host; a Studio must match its host's version. */
19
+ export function compareServiceVersion(state: Pick<ServiceState, 'version'>, version: string): number {
20
+ return state.version && semver.valid(state.version) ? semver.compare(state.version, version) : -1
21
+ }
22
+
23
+ /** Release one older local host before electing its replacement. Never kill a replacement or bypass its lease. */
24
+ export async function upgradeWorkspaceService(root: string, state: ServiceState, version: string, env: NodeJS.ProcessEnv = process.env, signal?: AbortSignal): Promise<void> {
25
+ if (compareServiceVersion(state, version) >= 0) throw new ServiceUpgradeError('newer', state.version)
26
+ const file = join(serveStateDir(root, env), 'server.json')
27
+ const same = () => { const current = readServiceState(file); return current?.pid === state.pid && current.token === state.token }
28
+ const url = new URL(state.url)
29
+ if (url.protocol !== 'http:' || !['127.0.0.1', '[::1]', 'localhost'].includes(url.hostname) || url.username || url.password || !state.launcherToken) throw new ServiceUpgradeError('unavailable')
30
+ const timeout = AbortSignal.any([AbortSignal.timeout(30_000), ...signal ? [signal] : []])
31
+ const request = (path: string, body: unknown) => fetch(`${state.url.replace(/\/$/, '')}/__presmium/presmium.workspace/${path}`, {
32
+ method: 'POST', headers: { authorization: `Bearer ${state.launcherToken}`, 'content-type': 'application/json' },
33
+ body: JSON.stringify(body), signal: timeout, redirect: 'error',
34
+ })
35
+ try {
36
+ let response: Response | undefined
37
+ while (same()) {
38
+ response = await request('host-upgrade', { pid: state.pid, version })
39
+ await response.arrayBuffer()
40
+ if (response.status !== 409) break
41
+ try { await delay(100, undefined, { signal: timeout }) } catch { throw new ServiceUpgradeError('busy') }
42
+ }
43
+ if (response?.status === 404 || response?.status === 405) {
44
+ // Hosts released before the handover protocol require a graceful process stop. Authenticate the
45
+ // published launcher first, and recheck its identity immediately before signalling that exact process.
46
+ const legacy = await request('preview-origins', { origins: [] })
47
+ await legacy.arrayBuffer()
48
+ if (!legacy.ok) throw new ServiceUpgradeError('unavailable')
49
+ if (same()) process.kill(state.pid, 'SIGTERM')
50
+ } else if (response && !response.ok) throw new ServiceUpgradeError('unavailable')
51
+ } catch (error) {
52
+ if (same()) {
53
+ if (error instanceof ServiceUpgradeError) throw error
54
+ throw new ServiceUpgradeError('unavailable')
55
+ }
56
+ }
57
+ try {
58
+ for (;;) {
59
+ const current = readServiceState(file)
60
+ if (current && !same()) return
61
+ if (!current) {
62
+ const lease = await tryAcquireServiceHostLease(root, env)
63
+ if (lease) { await lease.release(); return }
64
+ }
65
+ await delay(50, undefined, { signal: timeout })
66
+ }
67
+ } catch { throw new ServiceUpgradeError('unavailable') }
68
+ }
@@ -65,6 +65,7 @@ export function createVoiceoverOwner() {
65
65
  const find = (query: VoiceoverJobQuery): Intent | undefined => 'intent' in query ? intents.get(query.intent) : [...intents.values()].find(intent => intent.job?.job.id === query.id)
66
66
  const observation = (id: string, intent: Intent): VoiceoverObservation => ({ intent: id, state: intent.job?.job.state ?? (intent.state === 'preparing' ? 'queued' : intent.state), ...intent.job ? { job: structuredClone(intent.job.job) } : {}, ...intent.error ? { error: intent.error } : {} })
67
67
  return {
68
+ busy: () => operations.size > 0 || [...jobs.values()].some(entry => ['queued', 'running', 'cancelling'].includes(entry.job.state)),
68
69
  limits: { intents: MAX_INTENTS, recentJobs: RECENT_JOBS, concurrent: MAX_OPERATIONS, quotes: MAX_QUOTES, quoteLifetimeMs: QUOTE_MS, previewBytes: 8 << 20, previewResources: MAX_PREVIEWS, retainedPreviewBytes: MAX_MEDIA_BYTES },
69
70
  snapshot(query: VoiceoverStatusQuery, load: Load, signal?: AbortSignal) {
70
71
  if (!validateVoiceoverStatus(query)) throw new VoiceoverOperationError(400, 'voice-status-invalid')