@nextclaw/service 0.3.24 → 0.3.26
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/dist/controllers/commands/channel-command.controller.js +1 -1
- package/dist/controllers/commands/channel-command.controller.js.map +1 -1
- package/dist/controllers/commands/marketplace-skill-command.controller.js +2 -2
- package/dist/controllers/commands/secrets-command.controller.js +2 -2
- package/dist/controllers/commands/secrets-command.controller.js.map +1 -1
- package/dist/controllers/gateway.controller.d.ts +3 -16
- package/dist/controllers/gateway.controller.d.ts.map +1 -1
- package/dist/controllers/gateway.controller.js +4 -25
- package/dist/controllers/gateway.controller.js.map +1 -1
- package/dist/launcher/npm-runtime-launcher.service.d.ts.map +1 -1
- package/dist/launcher/npm-runtime-launcher.service.js +5 -1
- package/dist/launcher/npm-runtime-launcher.service.js.map +1 -1
- package/dist/managers/runtime-update.manager.d.ts +3 -0
- package/dist/managers/runtime-update.manager.d.ts.map +1 -1
- package/dist/managers/runtime-update.manager.js +26 -2
- package/dist/managers/runtime-update.manager.js.map +1 -1
- package/dist/managers/service-gateway.manager.d.ts.map +1 -1
- package/dist/managers/service-gateway.manager.js +7 -6
- package/dist/managers/service-gateway.manager.js.map +1 -1
- package/dist/services/autostart/host-autostart-runtime.service.d.ts +1 -0
- package/dist/services/autostart/host-autostart-runtime.service.d.ts.map +1 -1
- package/dist/services/autostart/host-autostart-runtime.service.js +1 -1
- package/dist/services/autostart/host-autostart-runtime.service.js.map +1 -1
- package/dist/services/autostart/linux-systemd-autostart.service.d.ts.map +1 -1
- package/dist/services/autostart/linux-systemd-autostart.service.js +2 -1
- package/dist/services/autostart/linux-systemd-autostart.service.js.map +1 -1
- package/dist/services/config/config-commands.service.js +2 -2
- package/dist/services/config/config-commands.service.js.map +1 -1
- package/dist/services/marketplace/service-marketplace-installer.service.d.ts.map +1 -1
- package/dist/services/marketplace/service-marketplace-installer.service.js +15 -6
- package/dist/services/marketplace/service-marketplace-installer.service.js.map +1 -1
- package/dist/services/restart/restart-coordinator.service.js +1 -1
- package/dist/services/restart/restart-coordinator.service.js.map +1 -1
- package/dist/services/runtime/npm-runtime-update-host.service.d.ts +4 -2
- package/dist/services/runtime/npm-runtime-update-host.service.d.ts.map +1 -1
- package/dist/services/runtime/npm-runtime-update-host.service.js +13 -3
- package/dist/services/runtime/npm-runtime-update-host.service.js.map +1 -1
- package/dist/types/distribution.types.d.ts +1 -0
- package/dist/types/distribution.types.d.ts.map +1 -1
- package/dist/utils/marketplace/marketplace-skill-lifecycle.utils.d.ts +10 -1
- package/dist/utils/marketplace/marketplace-skill-lifecycle.utils.d.ts.map +1 -1
- package/dist/utils/marketplace/marketplace-skill-lifecycle.utils.js +13 -2
- package/dist/utils/marketplace/marketplace-skill-lifecycle.utils.js.map +1 -1
- package/dist/utils/marketplace/marketplace.utils.d.ts +2 -2
- package/dist/utils/marketplace/marketplace.utils.d.ts.map +1 -1
- package/dist/utils/marketplace/marketplace.utils.js +2 -2
- package/dist/utils/marketplace/marketplace.utils.js.map +1 -1
- package/package.json +26 -26
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"service-gateway.manager.js","names":["getConfigPath","getDataDir","getWorkspacePath","waitForNextTick"],"sources":["../../src/managers/service-gateway.manager.ts"],"sourcesContent":["import * as NextclawCore from \"@nextclaw/core\";\nimport {\n AgentRunClient,\n NextclawKernel,\n resolveAutomaticUpdateCheckIntervalMs,\n runGatewayInboundLoop,\n type AutomationManager,\n type ConfigManager,\n type LlmProviderManager,\n type SessionManager,\n} from \"@nextclaw/kernel\";\nimport type { EventBus, Ingress } from \"@nextclaw/shared\";\nimport {\n startUiServer,\n type MarketplaceApiConfig,\n type UiRouterOptions,\n type UiRuntimeControlHost,\n} from \"@nextclaw/server\";\nimport { resolve } from \"node:path\";\nimport { setImmediate as waitForNextTick } from \"node:timers/promises\";\nimport { GatewayControllerImpl } from \"@nextclaw-service/controllers/gateway.controller.js\";\nimport { GatewayExtensionManager } from \"@nextclaw-service/managers/gateway-extension.manager.js\";\nimport { GatewayRemoteManager } from \"@nextclaw-service/managers/gateway-remote.manager.js\";\nimport { GatewayRestartWakeService } from \"@nextclaw-service/services/gateway/gateway-restart-wake.service.js\";\nimport { createCronJobHandler } from \"@nextclaw-service/utils/gateway-cron-job-handler.utils.js\";\nimport { companionRuntimeService } from \"@nextclaw-service/services/ui/companion-runtime.service.js\";\nimport { handleGatewayDeferredStartupError } from \"@nextclaw-service/utils/gateway-runtime-lifecycle.utils.js\";\nimport { NextclawApp, type UiStartupHandle } from \"@nextclaw-service/services/gateway/nextclaw-app.service.js\";\nimport { NextclawDistributionService } from \"@nextclaw-service/services/runtime/nextclaw-distribution.service.js\";\nimport { ServiceBootstrapStatusStore } from \"@nextclaw-service/services/gateway/service-bootstrap-status.service.js\";\nimport { GatewayRuntimeSupportService, ServiceFileWatcherRegistry, markLocalUiRuntimeIfStarted, watchServiceConfigFile } from \"@nextclaw-service/services/gateway/service-startup-support.service.js\";\nimport { ServiceMarketplaceInstaller } from \"@nextclaw-service/services/marketplace/service-marketplace-installer.service.js\";\nimport { NpmRuntimeUpdateHost } from \"@nextclaw-service/services/runtime/npm-runtime-update-host.service.js\";\nimport { createRuntimeControlHost } from \"@nextclaw-service/services/ui/runtime-control-host.service.js\";\nimport { localUiRuntimeStore } from \"@nextclaw-service/stores/local-ui-runtime.store.js\";\nimport { managedServiceStateStore } from \"@nextclaw-service/stores/managed-service-state.store.js\";\nimport type { RequestRestartParams } from \"@nextclaw-service/types/cli.types.js\";\nimport { openBrowser, resolveUiConfig, resolveUiStaticDir } from \"@nextclaw-service/utils/cli.utils.js\";\nimport { readPanelAppClientSdkScript } from \"@nextclaw-service/utils/panel-app-client-sdk/panel-app-client-sdk-script.utils.js\";\nimport { logStartupTrace, measureStartupAsync, measureStartupSync } from \"@nextclaw-service/utils/startup-trace.utils.js\";\n\nconst {\n getConfigPath,\n getDataDir,\n getWorkspacePath,\n} = NextclawCore;\n\nfunction resolveApplyRestartMode(uiPort: number): \"managed-service-restart\" | \"manual-process-restart\" {\n const serviceState = managedServiceStateStore.read();\n if (serviceState?.pid === process.pid) {\n return \"managed-service-restart\";\n }\n if (\n process.env.NEXTCLAW_RUNTIME_BUNDLE_CHILD === \"1\" &&\n typeof serviceState?.uiPort === \"number\" &&\n serviceState.uiPort === uiPort\n ) {\n return \"managed-service-restart\";\n }\n return \"manual-process-restart\";\n}\n\ntype Config = NextclawCore.Config;\ntype MessageBus = NextclawCore.MessageBus;\n\ntype GatewayRuntimeOptions = {\n uiOverrides?: Partial<Config[\"ui\"]>;\n uiStaticDir?: string | null;\n};\n\nexport type GatewayRuntimeDeps = {\n requestRestart: (params: RequestRestartParams) => Promise<void>;\n initializeAgentHomeDirectory: (homeDirectory: string) => void;\n startService: (options: { uiOverrides: Record<string, unknown>; open: boolean }) => Promise<void>;\n stopService: () => Promise<void>;\n runCliSubcommand: (args: string[]) => Promise<string>;\n installBuiltinMarketplaceSkill: (slug: string, force: boolean | undefined) => { message: string; output?: string } | null;\n};\n\nexport class ServiceGatewayManager {\n readonly kernel: NextclawKernel;\n readonly appEventBus: EventBus;\n readonly messageBus: MessageBus;\n readonly sessionManager: SessionManager;\n readonly automation: AutomationManager;\n readonly agentRunClient: AgentRunClient;\n readonly runtimeControl: UiRuntimeControlHost;\n readonly runtimeUpdate: NpmRuntimeUpdateHost | null;\n readonly ingress: Ingress;\n readonly distribution = NextclawDistributionService.get();\n readonly productVersion: string;\n readonly providerManager: LlmProviderManager;\n readonly gatewayController: GatewayControllerImpl;\n\n readonly configManager: ConfigManager;\n readonly uiConfig: Config[\"ui\"];\n readonly uiStaticDir: string | null;\n readonly workspace: string;\n readonly remoteManager: GatewayRemoteManager;\n readonly marketplace: MarketplaceApiConfig;\n readonly extensions: GatewayExtensionManager;\n readonly restartWake: GatewayRestartWakeService;\n bootstrapStatus: ServiceBootstrapStatusStore;\n uiStartup: UiStartupHandle;\n readonly fileWatchers = new ServiceFileWatcherRegistry();\n private deferredChannelStarter: () => Promise<void>;\n\n constructor(\n private readonly deps: GatewayRuntimeDeps,\n private readonly options: GatewayRuntimeOptions,\n ) {\n const configPath = getConfigPath();\n this.kernel = measureStartupSync(\n \"service.gateway.kernel\",\n () => new NextclawKernel({\n homeDir: getDataDir(),\n configPath,\n }),\n );\n this.configManager = this.kernel.configManager;\n const config = this.configManager.config;\n this.uiConfig = resolveUiConfig(config, options.uiOverrides);\n this.uiStaticDir = options.uiStaticDir === undefined ? resolveUiStaticDir(this.distribution.uiDistDir) : options.uiStaticDir;\n this.workspace = getWorkspacePath(config.agents.defaults.workspace);\n this.appEventBus = this.kernel.eventBus;\n this.ingress = this.kernel.ingress;\n this.agentRunClient = new AgentRunClient({\n eventBus: this.kernel.eventBus,\n ingress: this.kernel.ingress,\n });\n this.messageBus = this.kernel.messageBus;\n this.sessionManager = this.kernel.sessionManager;\n this.automation = this.kernel.automation;\n this.productVersion = this.distribution.version;\n this.extensions = new GatewayExtensionManager(this);\n this.providerManager = this.kernel.llmProviders;\n this.installConfigHostHooks();\n this.restartWake = new GatewayRestartWakeService(this);\n this.bootstrapStatus = this.createBootstrapStatus();\n this.uiStartup = this.createDisabledUiStartup();\n this.remoteManager = new GatewayRemoteManager({\n deps: this.deps,\n configManager: this.configManager,\n uiConfig: this.uiConfig,\n onRemoteStateChange: (state) => this.bootstrapStatus.syncRemoteRuntimeState(state),\n });\n this.marketplace = this.createMarketplace();\n this.runtimeControl = createRuntimeControlHost({\n serviceCommands: this.deps,\n requestRestart: this.deps.requestRestart,\n uiConfig: this.uiConfig,\n });\n this.runtimeUpdate =\n process.env.NEXTCLAW_DISABLE_RUNTIME_UPDATE_HOST === \"1\"\n ? null\n : new NpmRuntimeUpdateHost({\n eventBus: this.appEventBus,\n applyRestartMode: resolveApplyRestartMode(this.uiConfig.port),\n requestRestart: this.deps.requestRestart,\n uiConfig: this.uiConfig,\n automaticCheckIntervalMs: resolveAutomaticUpdateCheckIntervalMs({\n verificationMode: process.env.NEXTCLAW_UPDATE_VERIFICATION_MODE === \"1\",\n verificationIntervalMs: process.env.NEXTCLAW_UPDATE_VERIFICATION_INTERVAL_MS,\n }),\n });\n this.gatewayController = this.createGatewayController();\n this.kernel.provideGatewayController(this.gatewayController);\n this.deferredChannelStarter = this.startChannels;\n this.automation.onJob = createCronJobHandler({\n agentRunClient: this.agentRunClient,\n });\n }\n\n start = async (): Promise<void> => {\n logStartupTrace(\"service.start_gateway.begin\");\n await this.reset();\n this.runtimeUpdate?.start();\n this.configureIngressHandlers();\n this.uiStartup = await this.startUiRuntime();\n await companionRuntimeService.applyConfig(this.configManager.config);\n await this.markUiRuntimeReady();\n await this.startSupportServices();\n await this.runRuntimeLoop();\n await companionRuntimeService.ensureStopped();\n logStartupTrace(\"service.start_gateway.end\");\n };\n\n private reset = async (): Promise<void> => {\n await this.fileWatchers.clear();\n this.bootstrapStatus = this.createBootstrapStatus();\n this.uiStartup = this.createDisabledUiStartup();\n this.deferredChannelStarter = this.startChannels;\n };\n\n private createBootstrapStatus = (): ServiceBootstrapStatusStore => {\n const bootstrapStatus = new ServiceBootstrapStatusStore();\n bootstrapStatus.markChannelsPending();\n bootstrapStatus.setRemoteState(this.configManager.config.remote.enabled ? \"pending\" : \"disabled\");\n return bootstrapStatus;\n };\n\n private createDisabledUiStartup = (): UiStartupHandle => ({\n endpoint: \"\",\n });\n\n private startUiRuntime = async (): Promise<UiStartupHandle> => {\n const uiStartup = await measureStartupAsync(\"service.start_ui_runtime\", async () => {\n logStartupTrace(\"service.start_ui_runtime.begin\");\n if (!this.uiConfig.enabled) {\n return this.createDisabledUiStartup();\n }\n const uiServer = await startUiServer(this.createUiRouterOptions());\n const uiUrl = NextclawCore.resolveLocalUiBaseUrl({\n host: uiServer.host,\n port: uiServer.port,\n });\n console.log(`✓ UI API: ${uiUrl}/api`);\n if (this.uiStaticDir) {\n console.log(`✓ UI frontend: ${uiUrl}`);\n }\n if (this.uiConfig.open) {\n openBrowser(uiUrl);\n }\n logStartupTrace(\"service.start_ui_runtime.ready\", {\n host: uiServer.host,\n port: uiServer.port,\n });\n return {\n endpoint: uiUrl,\n };\n });\n markLocalUiRuntimeIfStarted({\n uiStartup: this.uiConfig.enabled ? uiStartup : null,\n uiConfig: this.uiConfig,\n });\n return uiStartup;\n };\n\n private createUiRouterOptions = (): UiRouterOptions => ({\n kernel: this.kernel,\n configPath: this.configManager.configPath,\n appEventBus: this.appEventBus,\n uiConfig: this.uiConfig,\n uiStaticDir: this.uiStaticDir,\n panelAppClientSdkScript: readPanelAppClientSdkScript,\n productVersion: this.productVersion,\n applyLiveConfigReload: this.configManager.applyLiveConfigReload,\n initializeAgentHomeDirectory: this.deps.initializeAgentHomeDirectory,\n marketplace: this.marketplace,\n cron: this.automation,\n remoteAccess: this.remoteManager.remoteAccess,\n runtimeControl: this.runtimeControl,\n ...(this.runtimeUpdate ? { runtimeUpdate: this.runtimeUpdate } : {}),\n bootstrapStatus: this.bootstrapStatus,\n extensions: this.extensions,\n });\n\n private runRuntimeLoop = async (): Promise<void> => {\n logStartupTrace(\"service.start_gateway.runtime_loop_begin\");\n let startupTask: Promise<void> | null = null;\n try {\n const runtimeLoopTask = runGatewayInboundLoop(this);\n startupTask = this.startDeferredRuntime();\n void startupTask.catch((error) => handleGatewayDeferredStartupError({\n bootstrapStatus: this.bootstrapStatus,\n error,\n }));\n await runtimeLoopTask;\n } finally {\n if (startupTask) {\n await startupTask.catch(() => undefined);\n }\n await this.stop();\n }\n };\n\n private startDeferredRuntime = async (): Promise<void> => {\n const app = new NextclawApp(this);\n await app.start();\n };\n\n readonly startDeferredChannels = async (): Promise<void> => {\n await this.deferredChannelStarter();\n };\n\n private readonly startChannels = async (): Promise<void> => {\n await this.kernel.channels.start();\n const enabledChannels = this.kernel.channels.enabledChannels;\n if (enabledChannels.length > 0) {\n console.log(`✓ Channels enabled: ${enabledChannels.join(\", \")}`);\n } else {\n console.log(\"Warning: No channels enabled\");\n }\n this.bootstrapStatus.markChannelsReady(enabledChannels);\n };\n\n private createMarketplace = (): MarketplaceApiConfig => ({\n apiBaseUrl: process.env.NEXTCLAW_MARKETPLACE_API_BASE,\n installer: new ServiceMarketplaceInstaller({\n applyLiveConfigReload: this.configManager.applyLiveConfigReload,\n runCliSubcommand: this.deps.runCliSubcommand,\n installBuiltinSkill: this.deps.installBuiltinMarketplaceSkill,\n }).createInstaller(),\n });\n\n readonly stop = async (): Promise<void> => {\n localUiRuntimeStore.clearIfOwnedByProcess();\n this.runtimeUpdate?.dispose();\n await this.fileWatchers.clear();\n await this.kernel.extensions.stop();\n await this.remoteManager.stop();\n };\n\n private markUiRuntimeReady = async (): Promise<void> => {\n this.bootstrapStatus.markShellReady();\n await waitForNextTick();\n };\n\n private createGatewayController = (): GatewayControllerImpl => {\n return measureStartupSync(\n \"service.gateway.gateway_controller\",\n () => new GatewayControllerImpl({\n configManager: this.configManager,\n channels: this.kernel.channels,\n cron: this.automation,\n sessionManager: this.sessionManager,\n requestRestart: async (options) => {\n await this.deps.requestRestart({\n reason: options?.reason ?? \"gateway tool restart\",\n manualMessage: \"Restart the gateway to apply changes.\",\n strategy: \"background-service-or-exit\",\n delayMs: options?.delayMs,\n silentOnServiceRestart: true,\n });\n },\n })\n );\n };\n\n private startSupportServices = async (): Promise<void> => {\n this.extensions.publishConfigChanges();\n await measureStartupAsync(\"service.start_gateway_support_services\", async () =>\n await new GatewayRuntimeSupportService({\n automation: this.automation,\n remoteModule: this.remoteManager.remoteModule,\n watchConfigFile: () => watchServiceConfigFile({\n configPath: resolve(getConfigPath()),\n watcherRegistry: this.fileWatchers,\n scheduleReload: (reason) => this.configManager.scheduleReload(reason)\n }),\n watcherRegistry: this.fileWatchers\n }).start()\n );\n };\n\n private installConfigHostHooks = (): void => {\n this.configManager.installRuntimeHooks({\n reloadCompanion: async ({ config: nextConfig }) => {\n await companionRuntimeService.applyConfig(nextConfig);\n },\n onRestartRequired: (paths) => {\n void this.deps.requestRestart({\n changedPaths: paths,\n manualMessage: `已保存以下改动,等待你手动重启后生效:${paths.join(\", \")}`,\n mode: \"notify\",\n reason: `config reload requires restart: ${paths.join(\", \")}`,\n strategy: \"background-service-or-manual\",\n });\n },\n });\n };\n\n private configureIngressHandlers = (): void => {\n this.kernel.extensions.registerIngressHandlers();\n };\n\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,MAAM,EACJ,eAAA,iBACA,YAAA,cACA,kBAAA,uBACE;AAEJ,SAAS,wBAAwB,QAAsE;CACrG,MAAM,eAAe,yBAAyB,MAAM;AACpD,KAAI,cAAc,QAAQ,QAAQ,IAChC,QAAO;AAET,KACE,QAAQ,IAAI,kCAAkC,OAC9C,OAAO,cAAc,WAAW,YAChC,aAAa,WAAW,OAExB,QAAO;AAET,QAAO;;AAoBT,IAAa,wBAAb,MAAmC;CACjC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,eAAwB,4BAA4B,KAAK;CACzD;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,eAAwB,IAAI,4BAA4B;CACxD;CAEA,YACE,MACA,SACA;AAFiB,OAAA,OAAA;AACA,OAAA,UAAA;EAEjB,MAAM,aAAaA,iBAAe;AAClC,OAAK,SAAS,mBACZ,gCACM,IAAI,eAAe;GACvB,SAASC,cAAY;GACrB;GACD,CAAC,CACH;AACD,OAAK,gBAAgB,KAAK,OAAO;EACjC,MAAM,SAAS,KAAK,cAAc;AAClC,OAAK,WAAW,gBAAgB,QAAQ,QAAQ,YAAY;AAC5D,OAAK,cAAc,QAAQ,gBAAgB,KAAA,IAAY,mBAAmB,KAAK,aAAa,UAAU,GAAG,QAAQ;AACjH,OAAK,YAAYC,mBAAiB,OAAO,OAAO,SAAS,UAAU;AACnE,OAAK,cAAc,KAAK,OAAO;AAC/B,OAAK,UAAU,KAAK,OAAO;AAC3B,OAAK,iBAAiB,IAAI,eAAe;GACvC,UAAU,KAAK,OAAO;GACtB,SAAS,KAAK,OAAO;GACtB,CAAC;AACF,OA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,MAAM;AACnC,QAAM,KAAK,cAAc,MAAM;;CAGjC,qBAA6B,YAA2B;AACtD,OAAK,gBAAgB,gBAAgB;AACrC,QAAMC,cAAiB;;CAGzB,gCAA+D;AAC7D,SAAO,mBACL,4CACM,IAAI,sBAAsB;GAC9B,eAAe,KAAK;GACpB,UAAU,KAAK,OAAO;GACtB,MAAM,KAAK;GACX,gBAAgB,KAAK;GACrB,gBAAgB,OAAO,YAAY;AACjC,UAAM,KAAK,KAAK,eAAe;KAC7B,QAAQ,SAAS,UAAU;KAC3B,eAAe;KACf,UAAU;KACV,SAAS,SAAS;KAClB,wBAAwB;KACzB,CAAC;;GAEL,CAAC,CACH;;CAGH,uBAA+B,YAA2B;AACxD,OAAK,WAAW,sBAAsB;AACtC,QAAM,oBAAoB,0CAA0C,YAClE,MAAM,IAAI,6BAA6B;GACrC,YAAY,KAAK;GACjB,cAAc,KAAK,cAAc;GACjC,uBAAuB,uBAAuB;IAC5C,YAAY,QAAQH,iBAAe,CAAC;IACpC,iBAAiB,KAAK;IACtB,iBAAiB,WAAW,KAAK,cAAc,eAAe,OAAO;IACtE,CAAC;GACF,iBAAiB,KAAK;GACvB,CAAC,CAAC,OAAO,CACX;;CAGH,+BAA6C;AAC3C,OAAK,cAAc,oBAAoB;GACrC,iBAAiB,OAAO,EAAE,QAAQ,iBAAiB;AACjD,UAAM,wBAAwB,YAAY,WAAW;;GAEvD,oBAAoB,UAAU;AACvB,SAAK,KAAK,eAAe;KAC5B,cAAc;KACd,eAAe,sBAAsB,MAAM,KAAK,KAAK;KACrD,MAAM;KACN,QAAQ,mCAAmC,MAAM,KAAK,KAAK;KAC3D,UAAU;KACX,CAAC;;GAEL,CAAC;;CAGJ,iCAA+C;AAC7C,OAAK,OAAO,WAAW,yBAAyB"}
|
|
1
|
+
{"version":3,"file":"service-gateway.manager.js","names":["getConfigPath","getDataDir","getWorkspacePath","waitForNextTick"],"sources":["../../src/managers/service-gateway.manager.ts"],"sourcesContent":["import * as NextclawCore from \"@nextclaw/core\";\nimport {\n AgentRunClient,\n NextclawKernel,\n resolveAutomaticUpdateCheckIntervalMs,\n runGatewayInboundLoop,\n type AutomationManager,\n type ConfigManager,\n type LlmProviderManager,\n type SessionManager,\n} from \"@nextclaw/kernel\";\nimport type { EventBus, Ingress } from \"@nextclaw/shared\";\nimport {\n startUiServer,\n type MarketplaceApiConfig,\n type UiRouterOptions,\n type UiRuntimeControlHost,\n} from \"@nextclaw/server\";\nimport { resolve } from \"node:path\";\nimport { setImmediate as waitForNextTick } from \"node:timers/promises\";\nimport { GatewayControllerImpl } from \"@nextclaw-service/controllers/gateway.controller.js\";\nimport { GatewayExtensionManager } from \"@nextclaw-service/managers/gateway-extension.manager.js\";\nimport { GatewayRemoteManager } from \"@nextclaw-service/managers/gateway-remote.manager.js\";\nimport { GatewayRestartWakeService } from \"@nextclaw-service/services/gateway/gateway-restart-wake.service.js\";\nimport { createCronJobHandler } from \"@nextclaw-service/utils/gateway-cron-job-handler.utils.js\";\nimport { companionRuntimeService } from \"@nextclaw-service/services/ui/companion-runtime.service.js\";\nimport { handleGatewayDeferredStartupError } from \"@nextclaw-service/utils/gateway-runtime-lifecycle.utils.js\";\nimport { NextclawApp, type UiStartupHandle } from \"@nextclaw-service/services/gateway/nextclaw-app.service.js\";\nimport { NextclawDistributionService } from \"@nextclaw-service/services/runtime/nextclaw-distribution.service.js\";\nimport { ServiceBootstrapStatusStore } from \"@nextclaw-service/services/gateway/service-bootstrap-status.service.js\";\nimport { GatewayRuntimeSupportService, ServiceFileWatcherRegistry, markLocalUiRuntimeIfStarted, watchServiceConfigFile } from \"@nextclaw-service/services/gateway/service-startup-support.service.js\";\nimport { ServiceMarketplaceInstaller } from \"@nextclaw-service/services/marketplace/service-marketplace-installer.service.js\";\nimport {\n NpmRuntimeUpdateHost,\n type NpmRuntimeUpdateApplyRestartMode,\n} from \"@nextclaw-service/services/runtime/npm-runtime-update-host.service.js\";\nimport { createRuntimeControlHost } from \"@nextclaw-service/services/ui/runtime-control-host.service.js\";\nimport { localUiRuntimeStore } from \"@nextclaw-service/stores/local-ui-runtime.store.js\";\nimport { managedServiceStateStore } from \"@nextclaw-service/stores/managed-service-state.store.js\";\nimport type { RequestRestartParams } from \"@nextclaw-service/types/cli.types.js\";\nimport { openBrowser, resolveUiConfig, resolveUiStaticDir } from \"@nextclaw-service/utils/cli.utils.js\";\nimport { readPanelAppClientSdkScript } from \"@nextclaw-service/utils/panel-app-client-sdk/panel-app-client-sdk-script.utils.js\";\nimport { logStartupTrace, measureStartupAsync, measureStartupSync } from \"@nextclaw-service/utils/startup-trace.utils.js\";\n\nconst {\n getConfigPath,\n getDataDir,\n getWorkspacePath,\n} = NextclawCore;\n\nfunction resolveApplyRestartMode(uiPort: number): NpmRuntimeUpdateApplyRestartMode {\n if (process.env.NEXTCLAW_PROCESS_SUPERVISOR === \"systemd\") {\n return \"supervised-process-restart\";\n }\n const serviceState = managedServiceStateStore.read();\n if (serviceState?.pid === process.pid) {\n return \"managed-service-restart\";\n }\n if (\n process.env.NEXTCLAW_RUNTIME_BUNDLE_CHILD === \"1\" &&\n typeof serviceState?.uiPort === \"number\" &&\n serviceState.uiPort === uiPort\n ) {\n return \"managed-service-restart\";\n }\n return \"manual-process-restart\";\n}\n\ntype Config = NextclawCore.Config;\ntype MessageBus = NextclawCore.MessageBus;\n\ntype GatewayRuntimeOptions = {\n uiOverrides?: Partial<Config[\"ui\"]>;\n uiStaticDir?: string | null;\n};\n\nexport type GatewayRuntimeDeps = {\n requestRestart: (params: RequestRestartParams) => Promise<void>;\n initializeAgentHomeDirectory: (homeDirectory: string) => void;\n startService: (options: { uiOverrides: Record<string, unknown>; open: boolean }) => Promise<void>;\n stopService: () => Promise<void>;\n runCliSubcommand: (args: string[]) => Promise<string>;\n installBuiltinMarketplaceSkill: (slug: string, force: boolean | undefined) => { message: string; output?: string } | null;\n};\n\nexport class ServiceGatewayManager {\n readonly kernel: NextclawKernel;\n readonly appEventBus: EventBus;\n readonly messageBus: MessageBus;\n readonly sessionManager: SessionManager;\n readonly automation: AutomationManager;\n readonly agentRunClient: AgentRunClient;\n readonly runtimeControl: UiRuntimeControlHost;\n readonly runtimeUpdate: NpmRuntimeUpdateHost | null;\n readonly ingress: Ingress;\n readonly distribution = NextclawDistributionService.get();\n readonly productVersion: string;\n readonly providerManager: LlmProviderManager;\n readonly gatewayController: GatewayControllerImpl;\n\n readonly configManager: ConfigManager;\n readonly uiConfig: Config[\"ui\"];\n readonly uiStaticDir: string | null;\n readonly workspace: string;\n readonly remoteManager: GatewayRemoteManager;\n readonly marketplace: MarketplaceApiConfig;\n readonly extensions: GatewayExtensionManager;\n readonly restartWake: GatewayRestartWakeService;\n bootstrapStatus: ServiceBootstrapStatusStore;\n uiStartup: UiStartupHandle;\n readonly fileWatchers = new ServiceFileWatcherRegistry();\n private deferredChannelStarter: () => Promise<void>;\n\n constructor(\n private readonly deps: GatewayRuntimeDeps,\n private readonly options: GatewayRuntimeOptions,\n ) {\n const configPath = getConfigPath();\n this.kernel = measureStartupSync(\n \"service.gateway.kernel\",\n () => new NextclawKernel({\n homeDir: getDataDir(),\n configPath,\n builtInAppsDirectory: this.distribution.builtInAppsDirectory,\n productVersion: this.distribution.version,\n }),\n );\n this.configManager = this.kernel.configManager;\n const config = this.configManager.config;\n this.uiConfig = resolveUiConfig(config, options.uiOverrides);\n this.uiStaticDir = options.uiStaticDir === undefined ? resolveUiStaticDir(this.distribution.uiDistDir) : options.uiStaticDir;\n this.workspace = getWorkspacePath(config.agents.defaults.workspace);\n this.appEventBus = this.kernel.eventBus;\n this.ingress = this.kernel.ingress;\n this.agentRunClient = new AgentRunClient({\n eventBus: this.kernel.eventBus,\n ingress: this.kernel.ingress,\n });\n this.messageBus = this.kernel.messageBus;\n this.sessionManager = this.kernel.sessionManager;\n this.automation = this.kernel.automation;\n this.productVersion = this.distribution.version;\n this.extensions = new GatewayExtensionManager(this);\n this.providerManager = this.kernel.llmProviders;\n this.installConfigHostHooks();\n this.restartWake = new GatewayRestartWakeService(this);\n this.bootstrapStatus = this.createBootstrapStatus();\n this.uiStartup = this.createDisabledUiStartup();\n this.remoteManager = new GatewayRemoteManager({\n deps: this.deps,\n configManager: this.configManager,\n uiConfig: this.uiConfig,\n onRemoteStateChange: (state) => this.bootstrapStatus.syncRemoteRuntimeState(state),\n });\n this.marketplace = this.createMarketplace();\n this.runtimeControl = createRuntimeControlHost({\n serviceCommands: this.deps,\n requestRestart: this.deps.requestRestart,\n uiConfig: this.uiConfig,\n });\n this.runtimeUpdate =\n process.env.NEXTCLAW_DISABLE_RUNTIME_UPDATE_HOST === \"1\"\n ? null\n : new NpmRuntimeUpdateHost({\n eventBus: this.appEventBus,\n applyRestartMode: resolveApplyRestartMode(this.uiConfig.port),\n requestRestart: this.deps.requestRestart,\n uiConfig: this.uiConfig,\n automaticCheckIntervalMs: resolveAutomaticUpdateCheckIntervalMs({\n verificationMode: process.env.NEXTCLAW_UPDATE_VERIFICATION_MODE === \"1\",\n verificationIntervalMs: process.env.NEXTCLAW_UPDATE_VERIFICATION_INTERVAL_MS,\n }),\n });\n this.gatewayController = this.createGatewayController();\n this.kernel.provideGatewayController(this.gatewayController);\n this.deferredChannelStarter = this.startChannels;\n this.automation.onJob = createCronJobHandler({\n agentRunClient: this.agentRunClient,\n });\n }\n\n start = async (): Promise<void> => {\n logStartupTrace(\"service.start_gateway.begin\");\n await this.reset();\n this.runtimeUpdate?.start();\n this.configureIngressHandlers();\n this.uiStartup = await this.startUiRuntime();\n await companionRuntimeService.applyConfig(this.configManager.config);\n await this.markUiRuntimeReady();\n await this.startSupportServices();\n await this.runRuntimeLoop();\n await companionRuntimeService.ensureStopped();\n logStartupTrace(\"service.start_gateway.end\");\n };\n\n private reset = async (): Promise<void> => {\n await this.fileWatchers.clear();\n this.bootstrapStatus = this.createBootstrapStatus();\n this.uiStartup = this.createDisabledUiStartup();\n this.deferredChannelStarter = this.startChannels;\n };\n\n private createBootstrapStatus = (): ServiceBootstrapStatusStore => {\n const bootstrapStatus = new ServiceBootstrapStatusStore();\n bootstrapStatus.markChannelsPending();\n bootstrapStatus.setRemoteState(this.configManager.config.remote.enabled ? \"pending\" : \"disabled\");\n return bootstrapStatus;\n };\n\n private createDisabledUiStartup = (): UiStartupHandle => ({\n endpoint: \"\",\n });\n\n private startUiRuntime = async (): Promise<UiStartupHandle> => {\n const uiStartup = await measureStartupAsync(\"service.start_ui_runtime\", async () => {\n logStartupTrace(\"service.start_ui_runtime.begin\");\n if (!this.uiConfig.enabled) {\n return this.createDisabledUiStartup();\n }\n const uiServer = await startUiServer(this.createUiRouterOptions());\n const uiUrl = NextclawCore.resolveLocalUiBaseUrl({\n host: uiServer.host,\n port: uiServer.port,\n });\n console.log(`✓ UI API: ${uiUrl}/api`);\n if (this.uiStaticDir) {\n console.log(`✓ UI frontend: ${uiUrl}`);\n }\n if (this.uiConfig.open) {\n openBrowser(uiUrl);\n }\n logStartupTrace(\"service.start_ui_runtime.ready\", {\n host: uiServer.host,\n port: uiServer.port,\n });\n return {\n endpoint: uiUrl,\n };\n });\n markLocalUiRuntimeIfStarted({\n uiStartup: this.uiConfig.enabled ? uiStartup : null,\n uiConfig: this.uiConfig,\n });\n return uiStartup;\n };\n\n private createUiRouterOptions = (): UiRouterOptions => ({\n kernel: this.kernel,\n configPath: this.configManager.configPath,\n appEventBus: this.appEventBus,\n uiConfig: this.uiConfig,\n uiStaticDir: this.uiStaticDir,\n panelAppClientSdkScript: readPanelAppClientSdkScript,\n productVersion: this.productVersion,\n applyLiveConfigReload: this.configManager.applyLiveConfigReload,\n initializeAgentHomeDirectory: this.deps.initializeAgentHomeDirectory,\n marketplace: this.marketplace,\n cron: this.automation,\n remoteAccess: this.remoteManager.remoteAccess,\n runtimeControl: this.runtimeControl,\n ...(this.runtimeUpdate ? { runtimeUpdate: this.runtimeUpdate } : {}),\n bootstrapStatus: this.bootstrapStatus,\n extensions: this.extensions,\n });\n\n private runRuntimeLoop = async (): Promise<void> => {\n logStartupTrace(\"service.start_gateway.runtime_loop_begin\");\n let startupTask: Promise<void> | null = null;\n try {\n const runtimeLoopTask = runGatewayInboundLoop(this);\n startupTask = this.startDeferredRuntime();\n void startupTask.catch((error) => handleGatewayDeferredStartupError({\n bootstrapStatus: this.bootstrapStatus,\n error,\n }));\n await runtimeLoopTask;\n } finally {\n if (startupTask) {\n await startupTask.catch(() => undefined);\n }\n await this.stop();\n }\n };\n\n private startDeferredRuntime = async (): Promise<void> => {\n const app = new NextclawApp(this);\n await app.start();\n };\n\n readonly startDeferredChannels = async (): Promise<void> => {\n await this.deferredChannelStarter();\n };\n\n private readonly startChannels = async (): Promise<void> => {\n await this.kernel.channels.start();\n const enabledChannels = this.kernel.channels.enabledChannels;\n if (enabledChannels.length > 0) {\n console.log(`✓ Channels enabled: ${enabledChannels.join(\", \")}`);\n } else {\n console.log(\"Warning: No channels enabled\");\n }\n this.bootstrapStatus.markChannelsReady(enabledChannels);\n };\n\n private createMarketplace = (): MarketplaceApiConfig => ({\n apiBaseUrl: process.env.NEXTCLAW_MARKETPLACE_API_BASE,\n installer: new ServiceMarketplaceInstaller({\n applyLiveConfigReload: this.configManager.applyLiveConfigReload,\n runCliSubcommand: this.deps.runCliSubcommand,\n installBuiltinSkill: this.deps.installBuiltinMarketplaceSkill,\n }).createInstaller(),\n });\n\n readonly stop = async (): Promise<void> => {\n localUiRuntimeStore.clearIfOwnedByProcess();\n this.runtimeUpdate?.dispose();\n await this.fileWatchers.clear();\n await this.kernel.extensions.stop();\n await this.remoteManager.stop();\n };\n\n private markUiRuntimeReady = async (): Promise<void> => {\n this.bootstrapStatus.markShellReady();\n await waitForNextTick();\n };\n\n private createGatewayController = (): GatewayControllerImpl => {\n return measureStartupSync(\n \"service.gateway.gateway_controller\",\n () => new GatewayControllerImpl({\n configManager: this.configManager,\n sessionManager: this.sessionManager,\n requestRestart: async (options) => {\n await this.deps.requestRestart({\n reason: options?.reason ?? \"gateway update relaunch\",\n manualMessage: \"Run nextclaw restart in an external terminal.\",\n strategy: \"background-service-or-exit\",\n delayMs: options?.delayMs,\n silentOnServiceRestart: true,\n });\n },\n })\n );\n };\n\n private startSupportServices = async (): Promise<void> => {\n this.extensions.publishConfigChanges();\n await measureStartupAsync(\"service.start_gateway_support_services\", async () =>\n await new GatewayRuntimeSupportService({\n automation: this.automation,\n remoteModule: this.remoteManager.remoteModule,\n watchConfigFile: () => watchServiceConfigFile({\n configPath: resolve(getConfigPath()),\n watcherRegistry: this.fileWatchers,\n scheduleReload: (reason) => this.configManager.scheduleReload(reason)\n }),\n watcherRegistry: this.fileWatchers\n }).start()\n );\n };\n\n private installConfigHostHooks = (): void => {\n this.configManager.installRuntimeHooks({\n reloadCompanion: async ({ config: nextConfig }) => {\n await companionRuntimeService.applyConfig(nextConfig);\n },\n onRestartRequired: (paths) => {\n void this.deps.requestRestart({\n changedPaths: paths,\n manualMessage: `已保存以下改动,请在外部终端运行 nextclaw restart 后生效:${paths.join(\", \")}`,\n mode: \"notify\",\n reason: `config reload requires restart: ${paths.join(\", \")}`,\n strategy: \"background-service-or-manual\",\n });\n },\n });\n };\n\n private configureIngressHandlers = (): void => {\n this.kernel.extensions.registerIngressHandlers();\n };\n\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,MAAM,EACJ,eAAA,iBACA,YAAA,cACA,kBAAA,uBACE;AAEJ,SAAS,wBAAwB,QAAkD;AACjF,KAAI,QAAQ,IAAI,gCAAgC,UAC9C,QAAO;CAET,MAAM,eAAe,yBAAyB,MAAM;AACpD,KAAI,cAAc,QAAQ,QAAQ,IAChC,QAAO;AAET,KACE,QAAQ,IAAI,kCAAkC,OAC9C,OAAO,cAAc,WAAW,YAChC,aAAa,WAAW,OAExB,QAAO;AAET,QAAO;;AAoBT,IAAa,wBAAb,MAAmC;CACjC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,eAAwB,4BAA4B,KAAK;CACzD;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;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e,CAAC;IACpC,iBAAiB,KAAK;IACtB,iBAAiB,WAAW,KAAK,cAAc,eAAe,OAAO;IACtE,CAAC;GACF,iBAAiB,KAAK;GACvB,CAAC,CAAC,OAAO,CACX;;CAGH,+BAA6C;AAC3C,OAAK,cAAc,oBAAoB;GACrC,iBAAiB,OAAO,EAAE,QAAQ,iBAAiB;AACjD,UAAM,wBAAwB,YAAY,WAAW;;GAEvD,oBAAoB,UAAU;AACvB,SAAK,KAAK,eAAe;KAC5B,cAAc;KACd,eAAe,yCAAyC,MAAM,KAAK,KAAK;KACxE,MAAM;KACN,QAAQ,mCAAmC,MAAM,KAAK,KAAK;KAC3D,UAAU;KACX,CAAC;;GAEL,CAAC;;CAGJ,iCAA+C;AAC7C,OAAK,OAAO,WAAW,yBAAyB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"host-autostart-runtime.service.d.ts","names":[],"sources":["../../../src/services/autostart/host-autostart-runtime.service.ts"],"mappings":";KAKK,kCAAA;EACH,QAAA;EACA,SAAA;EACA,aAAA;EACA,UAAA;AAAA;AAAA,KAGU,uBAAA;EACV,OAAA;EACA,OAAA;EACA,IAAA;AAAA;AAAA,cAkBW,2BAAA;EAAA,iBACM,QAAA;EAAA,iBACA,SAAA;EAAA,iBACA,aAAA;EAAA,iBACA,kBAAA;cAEL,OAAA,GAAS,kCAAA;
|
|
1
|
+
{"version":3,"file":"host-autostart-runtime.service.d.ts","names":[],"sources":["../../../src/services/autostart/host-autostart-runtime.service.ts"],"mappings":";KAKK,kCAAA;EACH,QAAA;EACA,SAAA;EACA,GAAA,GAAM,MAAA,CAAO,UAAA;EACb,aAAA;EACA,UAAA;AAAA;AAAA,KAGU,uBAAA;EACV,OAAA;EACA,OAAA;EACA,IAAA;AAAA;AAAA,cAkBW,2BAAA;EAAA,iBACM,QAAA;EAAA,iBACA,SAAA;EAAA,iBACA,aAAA;EAAA,iBACA,kBAAA;cAEL,OAAA,GAAS,kCAAA;EAUrB,4BAAA,QAAmC,uBAAA;EAAA,QAW3B,eAAA;AAAA"}
|
|
@@ -24,7 +24,7 @@ var HostAutostartRuntimeService = class {
|
|
|
24
24
|
getResolvedDataDir;
|
|
25
25
|
constructor(options = {}) {
|
|
26
26
|
this.nodePath = options.nodePath ?? process.execPath;
|
|
27
|
-
this.argvEntry = options.argvEntry ?? process.argv[1];
|
|
27
|
+
this.argvEntry = options.argvEntry ?? options.env?.NEXTCLAW_NPM_LAUNCHER_ENTRYPOINT ?? process.env.NEXTCLAW_NPM_LAUNCHER_ENTRYPOINT ?? process.argv[1];
|
|
28
28
|
this.importMetaUrl = options.importMetaUrl ?? import.meta.url;
|
|
29
29
|
this.getResolvedDataDir = options.getDataDir ?? getDataDir;
|
|
30
30
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"host-autostart-runtime.service.js","names":["windowsPath"],"sources":["../../../src/services/autostart/host-autostart-runtime.service.ts"],"sourcesContent":["import { createRequire } from \"node:module\";\nimport { extname, isAbsolute, resolve, win32 as windowsPath } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { getDataDir } from \"@nextclaw/core\";\n\ntype HostAutostartRuntimeServiceOptions = {\n nodePath?: string;\n argvEntry?: string;\n importMetaUrl?: string;\n getDataDir?: () => string;\n};\n\nexport type HostAutostartLaunchPlan = {\n homeDir: string;\n command: string;\n args: string[];\n};\n\nconst TYPESCRIPT_EXTENSIONS = new Set([\".ts\", \".tsx\", \".mts\", \".cts\"]);\nconst require = createRequire(import.meta.url);\n\nconst resolveCliAppEntryFromImportMeta = (importMetaUrl: string): string => {\n const modulePath = fileURLToPath(importMetaUrl);\n const normalizedPath = modulePath.replace(/\\\\/g, \"/\");\n const cliRootIndex = normalizedPath.lastIndexOf(\"/cli/\");\n if (cliRootIndex === -1) {\n return fileURLToPath(new URL(\"../../../app/index.js\", importMetaUrl));\n }\n const extension = extname(modulePath) || \".js\";\n const cliRootPath = modulePath.slice(0, cliRootIndex + \"/cli/\".length);\n return resolve(cliRootPath, \"app\", `index${extension}`);\n};\n\nexport class HostAutostartRuntimeService {\n private readonly nodePath: string;\n private readonly argvEntry: string | undefined;\n private readonly importMetaUrl: string;\n private readonly getResolvedDataDir: () => string;\n\n constructor(options: HostAutostartRuntimeServiceOptions = {}) {\n this.nodePath = options.nodePath ?? process.execPath;\n this.argvEntry = options.argvEntry ?? process.argv[1];\n this.importMetaUrl = options.importMetaUrl ?? import.meta.url;\n this.getResolvedDataDir = options.getDataDir ?? getDataDir;\n }\n\n resolveForegroundServeLaunch = (): HostAutostartLaunchPlan => {\n const cliEntry = this.resolveCliEntry();\n return {\n homeDir: this.getResolvedDataDir(),\n command: this.nodePath,\n args: TYPESCRIPT_EXTENSIONS.has(extname(cliEntry).toLowerCase())\n ? [require.resolve(\"tsx/cli\"), cliEntry, \"serve\"]\n : [cliEntry, \"serve\"],\n };\n };\n\n private resolveCliEntry = (): string => {\n const argvEntry = this.argvEntry?.trim();\n if (argvEntry) {\n if (isAbsolute(argvEntry) || windowsPath.isAbsolute(argvEntry)) {\n return argvEntry;\n }\n return resolve(argvEntry);\n }\n return resolveCliAppEntryFromImportMeta(this.importMetaUrl);\n };\n}\n"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"host-autostart-runtime.service.js","names":["windowsPath"],"sources":["../../../src/services/autostart/host-autostart-runtime.service.ts"],"sourcesContent":["import { createRequire } from \"node:module\";\nimport { extname, isAbsolute, resolve, win32 as windowsPath } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { getDataDir } from \"@nextclaw/core\";\n\ntype HostAutostartRuntimeServiceOptions = {\n nodePath?: string;\n argvEntry?: string;\n env?: NodeJS.ProcessEnv;\n importMetaUrl?: string;\n getDataDir?: () => string;\n};\n\nexport type HostAutostartLaunchPlan = {\n homeDir: string;\n command: string;\n args: string[];\n};\n\nconst TYPESCRIPT_EXTENSIONS = new Set([\".ts\", \".tsx\", \".mts\", \".cts\"]);\nconst require = createRequire(import.meta.url);\n\nconst resolveCliAppEntryFromImportMeta = (importMetaUrl: string): string => {\n const modulePath = fileURLToPath(importMetaUrl);\n const normalizedPath = modulePath.replace(/\\\\/g, \"/\");\n const cliRootIndex = normalizedPath.lastIndexOf(\"/cli/\");\n if (cliRootIndex === -1) {\n return fileURLToPath(new URL(\"../../../app/index.js\", importMetaUrl));\n }\n const extension = extname(modulePath) || \".js\";\n const cliRootPath = modulePath.slice(0, cliRootIndex + \"/cli/\".length);\n return resolve(cliRootPath, \"app\", `index${extension}`);\n};\n\nexport class HostAutostartRuntimeService {\n private readonly nodePath: string;\n private readonly argvEntry: string | undefined;\n private readonly importMetaUrl: string;\n private readonly getResolvedDataDir: () => string;\n\n constructor(options: HostAutostartRuntimeServiceOptions = {}) {\n this.nodePath = options.nodePath ?? process.execPath;\n this.argvEntry = options.argvEntry\n ?? options.env?.NEXTCLAW_NPM_LAUNCHER_ENTRYPOINT\n ?? process.env.NEXTCLAW_NPM_LAUNCHER_ENTRYPOINT\n ?? process.argv[1];\n this.importMetaUrl = options.importMetaUrl ?? import.meta.url;\n this.getResolvedDataDir = options.getDataDir ?? getDataDir;\n }\n\n resolveForegroundServeLaunch = (): HostAutostartLaunchPlan => {\n const cliEntry = this.resolveCliEntry();\n return {\n homeDir: this.getResolvedDataDir(),\n command: this.nodePath,\n args: TYPESCRIPT_EXTENSIONS.has(extname(cliEntry).toLowerCase())\n ? [require.resolve(\"tsx/cli\"), cliEntry, \"serve\"]\n : [cliEntry, \"serve\"],\n };\n };\n\n private resolveCliEntry = (): string => {\n const argvEntry = this.argvEntry?.trim();\n if (argvEntry) {\n if (isAbsolute(argvEntry) || windowsPath.isAbsolute(argvEntry)) {\n return argvEntry;\n }\n return resolve(argvEntry);\n }\n return resolveCliAppEntryFromImportMeta(this.importMetaUrl);\n };\n}\n"],"mappings":";;;;;AAmBA,MAAM,wBAAwB,IAAI,IAAI;CAAC;CAAO;CAAQ;CAAQ;CAAO,CAAC;AACtE,MAAM,UAAU,cAAc,OAAO,KAAK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AAM,MAAA,CAAO,UAAA;EACb,UAAA;EACA,UAAA,IAAc,IAAA;EACd,SAAA,UAAmB,SAAA;EACnB,aAAA,UAAuB,aAAA;EACvB,MAAA,UAAgB,MAAA;EAChB,UAAA,GAAa,uBAAA;EACb,cAAA,GAAiB,2BAAA;AAAA;AAAA,cAWN,4BAAA;EAAA,iBACM,QAAA;EAAA,iBACA,GAAA;EAAA,iBACA,UAAA;EAAA,iBACA,UAAA;EAAA,iBACA,SAAA;EAAA,iBACA,SAAA;EAAA,iBACA,UAAA;EAAA,iBACA,cAAA;EAAA,iBACA,cAAA;cAEL,OAAA,GAAS,mCAAA;EAYrB,OAAA,GAAiB,KAAA,EAAO,kBAAA,EAAoB,OAAA;IAAW,MAAA;EAAA,MAA0B,OAAA,CAAQ,0BAAA;EA6DzF,SAAA,GAAmB,KAAA,EAAO,kBAAA,EAAoB,OAAA;IAAW,MAAA;EAAA,MAA0B,OAAA,CAAQ,4BAAA;EAgF3F,MAAA,GAAgB,cAAA,GAAiB,kBAAA,KAAqB,OAAA,CAAQ,mBAAA;EA6D9D,MAAA,GAAgB,cAAA,GAAiB,kBAAA,KAAqB,OAAA,CAAQ,yBAAA;EAAA,QAuDtD,WAAA;EAAA,QAIA,oBAAA;EAAA,QAIA,uBAAA;EAAA,QAiBA,8BAAA;EAAA,QAiBA,mBAAA;EAAA,QAqBA,SAAA;EAAA,
|
|
1
|
+
{"version":3,"file":"linux-systemd-autostart.service.d.ts","names":[],"sources":["../../../src/services/autostart/linux-systemd-autostart.service.ts"],"mappings":";;;;;KAsBK,mCAAA;EACH,QAAA,GAAW,MAAA,CAAO,QAAA;EAClB,GAAA,GAAM,MAAA,CAAO,UAAA;EACb,UAAA;EACA,UAAA,IAAc,IAAA;EACd,SAAA,UAAmB,SAAA;EACnB,aAAA,UAAuB,aAAA;EACvB,MAAA,UAAgB,MAAA;EAChB,UAAA,GAAa,uBAAA;EACb,cAAA,GAAiB,2BAAA;AAAA;AAAA,cAWN,4BAAA;EAAA,iBACM,QAAA;EAAA,iBACA,GAAA;EAAA,iBACA,UAAA;EAAA,iBACA,UAAA;EAAA,iBACA,SAAA;EAAA,iBACA,SAAA;EAAA,iBACA,UAAA;EAAA,iBACA,cAAA;EAAA,iBACA,cAAA;cAEL,OAAA,GAAS,mCAAA;EAYrB,OAAA,GAAiB,KAAA,EAAO,kBAAA,EAAoB,OAAA;IAAW,MAAA;EAAA,MAA0B,OAAA,CAAQ,0BAAA;EA6DzF,SAAA,GAAmB,KAAA,EAAO,kBAAA,EAAoB,OAAA;IAAW,MAAA;EAAA,MAA0B,OAAA,CAAQ,4BAAA;EAgF3F,MAAA,GAAgB,cAAA,GAAiB,kBAAA,KAAqB,OAAA,CAAQ,mBAAA;EA6D9D,MAAA,GAAgB,cAAA,GAAiB,kBAAA,KAAqB,OAAA,CAAQ,yBAAA;EAAA,QAuDtD,WAAA;EAAA,QAIA,oBAAA;EAAA,QAIA,uBAAA;EAAA,QAiBA,8BAAA;EAAA,QAiBA,mBAAA;EAAA,QAqBA,SAAA;EAAA,QA6CA,WAAA;EAAA,QASA,kBAAA;EAAA,QAOA,aAAA;EAAA,QAIA,iBAAA;AAAA"}
|
|
@@ -367,8 +367,9 @@ var LinuxSystemdAutostartService = class {
|
|
|
367
367
|
"Type=simple",
|
|
368
368
|
`WorkingDirectory=${this.escapeSystemdValue(homeDir)}`,
|
|
369
369
|
`Environment=NEXTCLAW_HOME=${this.escapeSystemdValue(homeDir)}`,
|
|
370
|
+
"Environment=NEXTCLAW_PROCESS_SUPERVISOR=systemd",
|
|
370
371
|
`ExecStart=${command}`,
|
|
371
|
-
"Restart=
|
|
372
|
+
"Restart=always",
|
|
372
373
|
"RestartSec=2",
|
|
373
374
|
"",
|
|
374
375
|
"[Install]",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"linux-systemd-autostart.service.js","names":[],"sources":["../../../src/services/autostart/linux-systemd-autostart.service.ts"],"sourcesContent":["import { existsSync, mkdirSync, rmSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { spawn } from \"node:child_process\";\nimport type {\n HostAutostartCheck,\n HostAutostartDoctorReport,\n HostAutostartInstallResult,\n HostAutostartOwner,\n HostAutostartRunCommand,\n HostAutostartRunCommandResult,\n HostAutostartScope,\n HostAutostartStatus,\n HostAutostartUninstallResult,\n} from \"@nextclaw-service/types/host-autostart.types.js\";\nimport { HostAutostartRuntimeService } from \"./host-autostart-runtime.service.js\";\n\ntype CheckedCommandParams = {\n command: string;\n args: string[];\n};\n\ntype LinuxSystemdAutostartServiceOptions = {\n platform?: NodeJS.Platform;\n env?: NodeJS.ProcessEnv;\n getHomeDir?: () => string;\n existsSync?: (path: string) => boolean;\n mkdirSync?: typeof mkdirSync;\n writeFileSync?: typeof writeFileSync;\n rmSync?: typeof rmSync;\n runCommand?: HostAutostartRunCommand;\n runtimeService?: HostAutostartRuntimeService;\n};\n\ntype ResolvedScopeStatus = {\n scope: HostAutostartScope | null;\n reasonIfUnavailable: string | null;\n};\n\nconst DEFAULT_SYSTEMD_SERVICE_NAME = \"nextclaw.service\";\nconst SUPPORTED_PLATFORM = \"linux\";\n\nexport class LinuxSystemdAutostartService {\n private readonly platform: NodeJS.Platform;\n private readonly env: NodeJS.ProcessEnv;\n private readonly getHomeDir: () => string;\n private readonly pathExists: (path: string) => boolean;\n private readonly ensureDir: typeof mkdirSync;\n private readonly writeFile: typeof writeFileSync;\n private readonly removeFile: typeof rmSync;\n private readonly runCommandImpl: HostAutostartRunCommand;\n private readonly runtimeService: HostAutostartRuntimeService;\n\n constructor(options: LinuxSystemdAutostartServiceOptions = {}) {\n this.platform = options.platform ?? process.platform;\n this.env = options.env ?? process.env;\n this.getHomeDir = options.getHomeDir ?? homedir;\n this.pathExists = options.existsSync ?? existsSync;\n this.ensureDir = options.mkdirSync ?? mkdirSync;\n this.writeFile = options.writeFileSync ?? writeFileSync;\n this.removeFile = options.rmSync ?? rmSync;\n this.runCommandImpl = options.runCommand ?? defaultRunCommand;\n this.runtimeService = options.runtimeService ?? new HostAutostartRuntimeService();\n }\n\n install = async (scope: HostAutostartScope, options: { dryRun?: boolean } = {}): Promise<HostAutostartInstallResult> => {\n if (!this.isSupported()) {\n return this.createUnsupportedInstallResult(scope, Boolean(options.dryRun));\n }\n\n const plan = this.buildPlan(scope);\n const actions = [\n `write unit file ${plan.resourcePath}`,\n `run ${this.formatCommand(plan.systemctlCommand, [...plan.systemctlScopeArgs, \"daemon-reload\"])}`,\n `run ${this.formatCommand(plan.systemctlCommand, [...plan.systemctlScopeArgs, \"enable\", plan.resourceName])}`,\n `run ${this.formatCommand(plan.systemctlCommand, [...plan.systemctlScopeArgs, \"restart\", plan.resourceName])}`,\n ];\n\n try {\n if (!options.dryRun) {\n this.ensureDir(dirname(plan.resourcePath), { recursive: true });\n this.writeFile(plan.resourcePath, plan.unitContent);\n await this.runCheckedCommand({\n command: plan.systemctlCommand,\n args: [...plan.systemctlScopeArgs, \"daemon-reload\"],\n });\n await this.runCheckedCommand({\n command: plan.systemctlCommand,\n args: [...plan.systemctlScopeArgs, \"enable\", plan.resourceName],\n });\n await this.runCheckedCommand({\n command: plan.systemctlCommand,\n args: [...plan.systemctlScopeArgs, \"restart\", plan.resourceName],\n });\n }\n } catch (error) {\n return {\n ok: false,\n dryRun: Boolean(options.dryRun),\n scope,\n hostOwner: plan.hostOwner,\n resourceName: plan.resourceName,\n resourcePath: plan.resourcePath,\n homeDir: plan.homeDir,\n command: plan.command,\n logHint: plan.logHint,\n actions,\n reasonIfUnavailable: error instanceof Error ? error.message : \"systemd autostart install failed.\",\n };\n }\n\n return {\n ok: true,\n dryRun: Boolean(options.dryRun),\n scope,\n hostOwner: plan.hostOwner,\n resourceName: plan.resourceName,\n resourcePath: plan.resourcePath,\n homeDir: plan.homeDir,\n command: plan.command,\n logHint: plan.logHint,\n actions,\n reasonIfUnavailable: null,\n };\n };\n\n uninstall = async (scope: HostAutostartScope, options: { dryRun?: boolean } = {}): Promise<HostAutostartUninstallResult> => {\n const plan = this.buildPlan(scope);\n if (!this.isSupported()) {\n return {\n ok: false,\n dryRun: Boolean(options.dryRun),\n scope,\n hostOwner: plan.hostOwner,\n resourceName: plan.resourceName,\n resourcePath: plan.resourcePath,\n removed: false,\n logHint: plan.logHint,\n actions: [],\n reasonIfUnavailable: this.getUnsupportedReason(),\n };\n }\n\n const installed = this.pathExists(plan.resourcePath);\n const actions: string[] = [];\n\n if (!installed) {\n return {\n ok: true,\n dryRun: Boolean(options.dryRun),\n scope,\n hostOwner: plan.hostOwner,\n resourceName: plan.resourceName,\n resourcePath: plan.resourcePath,\n removed: false,\n logHint: plan.logHint,\n actions: [\"no installed unit file found\"],\n reasonIfUnavailable: null,\n };\n }\n\n actions.push(`run ${this.formatCommand(plan.systemctlCommand, [...plan.systemctlScopeArgs, \"disable\", \"--now\", plan.resourceName])}`);\n actions.push(`remove unit file ${plan.resourcePath}`);\n actions.push(`run ${this.formatCommand(plan.systemctlCommand, [...plan.systemctlScopeArgs, \"daemon-reload\"])}`);\n\n try {\n if (!options.dryRun) {\n await this.runCheckedCommand({\n command: plan.systemctlCommand,\n args: [...plan.systemctlScopeArgs, \"disable\", \"--now\", plan.resourceName],\n });\n this.removeFile(plan.resourcePath, { force: true });\n await this.runCheckedCommand({\n command: plan.systemctlCommand,\n args: [...plan.systemctlScopeArgs, \"daemon-reload\"],\n });\n }\n } catch (error) {\n return {\n ok: false,\n dryRun: Boolean(options.dryRun),\n scope,\n hostOwner: plan.hostOwner,\n resourceName: plan.resourceName,\n resourcePath: plan.resourcePath,\n removed: false,\n logHint: plan.logHint,\n actions,\n reasonIfUnavailable: error instanceof Error ? error.message : \"systemd autostart uninstall failed.\",\n };\n }\n\n return {\n ok: true,\n dryRun: Boolean(options.dryRun),\n scope,\n hostOwner: plan.hostOwner,\n resourceName: plan.resourceName,\n resourcePath: plan.resourcePath,\n removed: true,\n logHint: plan.logHint,\n actions,\n reasonIfUnavailable: null,\n };\n };\n\n status = async (requestedScope?: HostAutostartScope): Promise<HostAutostartStatus> => {\n if (!this.isSupported()) {\n return this.createUnsupportedStatus();\n }\n\n const resolvedScope = this.resolveScopeForRead(requestedScope);\n if (!resolvedScope.scope) {\n return {\n supported: true,\n installed: false,\n enabled: null,\n active: null,\n scope: null,\n hostOwner: null,\n resourceName: null,\n resourcePath: null,\n homeDir: null,\n command: null,\n logHint: null,\n reasonIfUnavailable: resolvedScope.reasonIfUnavailable,\n };\n }\n\n const plan = this.buildPlan(resolvedScope.scope);\n const installed = this.pathExists(plan.resourcePath);\n if (!installed) {\n return {\n supported: true,\n installed: false,\n enabled: false,\n active: false,\n scope: resolvedScope.scope,\n hostOwner: plan.hostOwner,\n resourceName: plan.resourceName,\n resourcePath: plan.resourcePath,\n homeDir: plan.homeDir,\n command: plan.command,\n logHint: plan.logHint,\n reasonIfUnavailable: null,\n };\n }\n\n const enabledResult = await this.runCommandImpl(plan.systemctlCommand, [...plan.systemctlScopeArgs, \"is-enabled\", plan.resourceName]);\n const activeResult = await this.runCommandImpl(plan.systemctlCommand, [...plan.systemctlScopeArgs, \"is-active\", plan.resourceName]);\n\n return {\n supported: true,\n installed: true,\n enabled: enabledResult.code === 0,\n active: activeResult.code === 0,\n scope: resolvedScope.scope,\n hostOwner: plan.hostOwner,\n resourceName: plan.resourceName,\n resourcePath: plan.resourcePath,\n homeDir: plan.homeDir,\n command: plan.command,\n logHint: plan.logHint,\n reasonIfUnavailable: null,\n };\n };\n\n doctor = async (requestedScope?: HostAutostartScope): Promise<HostAutostartDoctorReport> => {\n const status = await this.status(requestedScope);\n const checks: HostAutostartCheck[] = [];\n const launchPlan = this.runtimeService.resolveForegroundServeLaunch();\n\n checks.push({\n name: \"platform\",\n status: status.supported ? \"pass\" : \"fail\",\n detail: status.supported ? \"linux supported\" : (status.reasonIfUnavailable ?? \"unsupported platform\"),\n });\n\n checks.push({\n name: \"unit-file\",\n status: status.installed ? \"pass\" : \"warn\",\n detail: status.resourcePath ?? \"no unit path\",\n });\n\n checks.push({\n name: \"exec-path\",\n status: this.pathExists(launchPlan.command) ? \"pass\" : \"fail\",\n detail: launchPlan.command,\n });\n\n checks.push({\n name: \"home-dir\",\n status: this.pathExists(launchPlan.homeDir) ? \"pass\" : \"warn\",\n detail: launchPlan.homeDir,\n });\n\n if (status.installed) {\n checks.push({\n name: \"enabled\",\n status: status.enabled ? \"pass\" : \"warn\",\n detail: status.enabled ? \"systemd unit enabled\" : \"systemd unit not enabled\",\n });\n checks.push({\n name: \"active\",\n status: status.active ? \"pass\" : \"warn\",\n detail: status.active ? \"systemd unit active\" : \"systemd unit not active\",\n });\n }\n\n const exitCode = checks.some((check) => check.status === \"fail\")\n ? 1\n : checks.some((check) => check.status === \"warn\")\n ? 1\n : 0;\n\n return {\n status,\n checks,\n exitCode,\n };\n };\n\n private isSupported = (): boolean => {\n return this.platform === SUPPORTED_PLATFORM;\n };\n\n private getUnsupportedReason = (): string => {\n return \"systemd autostart currently supports Linux only.\";\n };\n\n private createUnsupportedStatus = (): HostAutostartStatus => {\n return {\n supported: false,\n installed: false,\n enabled: null,\n active: null,\n scope: null,\n hostOwner: null,\n resourceName: null,\n resourcePath: null,\n homeDir: null,\n command: null,\n logHint: null,\n reasonIfUnavailable: this.getUnsupportedReason(),\n };\n };\n\n private createUnsupportedInstallResult = (scope: HostAutostartScope, dryRun: boolean): HostAutostartInstallResult => {\n const plan = this.buildPlan(scope);\n return {\n ok: false,\n dryRun,\n scope,\n hostOwner: plan.hostOwner,\n resourceName: plan.resourceName,\n resourcePath: plan.resourcePath,\n homeDir: plan.homeDir,\n command: plan.command,\n logHint: plan.logHint,\n actions: [],\n reasonIfUnavailable: this.getUnsupportedReason(),\n };\n };\n\n private resolveScopeForRead = (requestedScope?: HostAutostartScope): ResolvedScopeStatus => {\n if (requestedScope) {\n return { scope: requestedScope, reasonIfUnavailable: null };\n }\n const userInstalled = this.pathExists(this.getUnitPath(\"user\"));\n const systemInstalled = this.pathExists(this.getUnitPath(\"system\"));\n if (userInstalled && systemInstalled) {\n return {\n scope: null,\n reasonIfUnavailable: \"Both user and system units are installed. Re-run with --user or --system.\",\n };\n }\n if (userInstalled) {\n return { scope: \"user\", reasonIfUnavailable: null };\n }\n if (systemInstalled) {\n return { scope: \"system\", reasonIfUnavailable: null };\n }\n return { scope: \"user\", reasonIfUnavailable: null };\n };\n\n private buildPlan = (scope: HostAutostartScope) => {\n const launch = this.runtimeService.resolveForegroundServeLaunch();\n const command = this.formatCommand(launch.command, launch.args);\n const resourceName = DEFAULT_SYSTEMD_SERVICE_NAME;\n const resourcePath = this.getUnitPath(scope);\n const homeDir = launch.homeDir;\n const hostOwner: HostAutostartOwner = scope === \"user\" ? \"systemd-user-service\" : \"systemd-system-service\";\n const systemctlScopeArgs = scope === \"user\" ? [\"--user\"] : [];\n const logHint = scope === \"user\"\n ? `journalctl --user -u ${resourceName} -f`\n : `journalctl -u ${resourceName} -f`;\n const wantedBy = scope === \"user\" ? \"default.target\" : \"multi-user.target\";\n\n return {\n scope,\n resourceName,\n resourcePath,\n homeDir,\n hostOwner,\n command,\n logHint,\n unitContent: [\n \"[Unit]\",\n \"Description=NextClaw managed local service\",\n \"After=network-online.target\",\n \"Wants=network-online.target\",\n \"\",\n \"[Service]\",\n \"Type=simple\",\n `WorkingDirectory=${this.escapeSystemdValue(homeDir)}`,\n `Environment=NEXTCLAW_HOME=${this.escapeSystemdValue(homeDir)}`,\n `ExecStart=${command}`,\n \"Restart=on-failure\",\n \"RestartSec=2\",\n \"\",\n \"[Install]\",\n `WantedBy=${wantedBy}`,\n \"\",\n ].join(\"\\n\"),\n systemctlCommand: \"systemctl\",\n systemctlScopeArgs,\n };\n };\n\n private getUnitPath = (scope: HostAutostartScope): string => {\n if (scope === \"system\") {\n return \"/etc/systemd/system/nextclaw.service\";\n }\n const xdgConfigHome = this.env.XDG_CONFIG_HOME?.trim();\n const configHome = xdgConfigHome || join(this.getHomeDir(), \".config\");\n return resolve(configHome, \"systemd\", \"user\", \"nextclaw.service\");\n };\n\n private escapeSystemdValue = (value: string): string => {\n if (/^[A-Za-z0-9_./:@%+=,-]+$/.test(value)) {\n return value;\n }\n return `\"${value.replace(/([\"\\\\])/g, \"\\\\$1\")}\"`;\n };\n\n private formatCommand = (command: string, args: string[]): string => {\n return [command, ...args].map((value) => this.escapeSystemdValue(value)).join(\" \");\n };\n\n private runCheckedCommand = async ({ command, args }: CheckedCommandParams): Promise<void> => {\n const result = await this.runCommandImpl(command, args);\n if (result.code === 0) {\n return;\n }\n const detail = result.stderr || result.stdout || `exit code ${result.code}`;\n throw new Error(`Command failed: ${this.formatCommand(command, args)} (${detail})`);\n };\n}\n\nconst defaultRunCommand = async (command: string, args: string[]): Promise<HostAutostartRunCommandResult> => {\n return await new Promise<HostAutostartRunCommandResult>((resolvePromise, rejectPromise) => {\n const child = spawn(command, args, {\n env: process.env,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n\n let stdout = \"\";\n let stderr = \"\";\n child.stdout?.setEncoding(\"utf-8\");\n child.stderr?.setEncoding(\"utf-8\");\n child.stdout?.on(\"data\", (chunk: string) => {\n stdout += chunk;\n });\n child.stderr?.on(\"data\", (chunk: string) => {\n stderr += chunk;\n });\n child.on(\"error\", (error) => {\n rejectPromise(error);\n });\n child.on(\"close\", (code) => {\n resolvePromise({\n code: code ?? 1,\n stdout: stdout.trim(),\n stderr: stderr.trim(),\n });\n });\n });\n};\n"],"mappings":";;;;;;AAuCA,MAAM,+BAA+B;AACrC,MAAM,qBAAqB;AAE3B,IAAa,+BAAb,MAA0C;CACxC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA,YAAY,UAA+C,EAAE,EAAE;AAC7D,OAAK,WAAW,QAAQ,YAAY,QAAQ;AAC5C,OAAK,MAAM,QAAQ,OAAO,QAAQ;AAClC,OAAK,aAAa,QAAQ,cAAc;AACxC,OAAK,aAAa,QAAQ,cAAc;AACxC,OAAK,YAAY,QAAQ,aAAa;AACtC,OA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M,SAAS,MAAM;GACjC,KAAK,QAAQ;GACb,OAAO;IAAC;IAAU;IAAQ;IAAO;GAClC,CAAC;EAEF,IAAI,SAAS;EACb,IAAI,SAAS;AACb,QAAM,QAAQ,YAAY,QAAQ;AAClC,QAAM,QAAQ,YAAY,QAAQ;AAClC,QAAM,QAAQ,GAAG,SAAS,UAAkB;AAC1C,aAAU;IACV;AACF,QAAM,QAAQ,GAAG,SAAS,UAAkB;AAC1C,aAAU;IACV;AACF,QAAM,GAAG,UAAU,UAAU;AAC3B,iBAAc,MAAM;IACpB;AACF,QAAM,GAAG,UAAU,SAAS;AAC1B,kBAAe;IACb,MAAM,QAAQ;IACd,QAAQ,OAAO,MAAM;IACrB,QAAQ,OAAO,MAAM;IACtB,CAAC;IACF;GACF"}
|
|
1
|
+
{"version":3,"file":"linux-systemd-autostart.service.js","names":[],"sources":["../../../src/services/autostart/linux-systemd-autostart.service.ts"],"sourcesContent":["import { existsSync, mkdirSync, rmSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { spawn } from \"node:child_process\";\nimport type {\n HostAutostartCheck,\n HostAutostartDoctorReport,\n HostAutostartInstallResult,\n HostAutostartOwner,\n HostAutostartRunCommand,\n HostAutostartRunCommandResult,\n HostAutostartScope,\n HostAutostartStatus,\n HostAutostartUninstallResult,\n} from \"@nextclaw-service/types/host-autostart.types.js\";\nimport { HostAutostartRuntimeService } from \"./host-autostart-runtime.service.js\";\n\ntype CheckedCommandParams = {\n command: string;\n args: string[];\n};\n\ntype LinuxSystemdAutostartServiceOptions = {\n platform?: NodeJS.Platform;\n env?: NodeJS.ProcessEnv;\n getHomeDir?: () => string;\n existsSync?: (path: string) => boolean;\n mkdirSync?: typeof mkdirSync;\n writeFileSync?: typeof writeFileSync;\n rmSync?: typeof rmSync;\n runCommand?: HostAutostartRunCommand;\n runtimeService?: HostAutostartRuntimeService;\n};\n\ntype ResolvedScopeStatus = {\n scope: HostAutostartScope | null;\n reasonIfUnavailable: string | null;\n};\n\nconst DEFAULT_SYSTEMD_SERVICE_NAME = \"nextclaw.service\";\nconst SUPPORTED_PLATFORM = \"linux\";\n\nexport class LinuxSystemdAutostartService {\n private readonly platform: NodeJS.Platform;\n private readonly env: NodeJS.ProcessEnv;\n private readonly getHomeDir: () => string;\n private readonly pathExists: (path: string) => boolean;\n private readonly ensureDir: typeof mkdirSync;\n private readonly writeFile: typeof writeFileSync;\n private readonly removeFile: typeof rmSync;\n private readonly runCommandImpl: HostAutostartRunCommand;\n private readonly runtimeService: HostAutostartRuntimeService;\n\n constructor(options: LinuxSystemdAutostartServiceOptions = {}) {\n this.platform = options.platform ?? process.platform;\n this.env = options.env ?? process.env;\n this.getHomeDir = options.getHomeDir ?? homedir;\n this.pathExists = options.existsSync ?? existsSync;\n this.ensureDir = options.mkdirSync ?? mkdirSync;\n this.writeFile = options.writeFileSync ?? writeFileSync;\n this.removeFile = options.rmSync ?? rmSync;\n this.runCommandImpl = options.runCommand ?? defaultRunCommand;\n this.runtimeService = options.runtimeService ?? new HostAutostartRuntimeService();\n }\n\n install = async (scope: HostAutostartScope, options: { dryRun?: boolean } = {}): Promise<HostAutostartInstallResult> => {\n if (!this.isSupported()) {\n return this.createUnsupportedInstallResult(scope, Boolean(options.dryRun));\n }\n\n const plan = this.buildPlan(scope);\n const actions = [\n `write unit file ${plan.resourcePath}`,\n `run ${this.formatCommand(plan.systemctlCommand, [...plan.systemctlScopeArgs, \"daemon-reload\"])}`,\n `run ${this.formatCommand(plan.systemctlCommand, [...plan.systemctlScopeArgs, \"enable\", plan.resourceName])}`,\n `run ${this.formatCommand(plan.systemctlCommand, [...plan.systemctlScopeArgs, \"restart\", plan.resourceName])}`,\n ];\n\n try {\n if (!options.dryRun) {\n this.ensureDir(dirname(plan.resourcePath), { recursive: true });\n this.writeFile(plan.resourcePath, plan.unitContent);\n await this.runCheckedCommand({\n command: plan.systemctlCommand,\n args: [...plan.systemctlScopeArgs, \"daemon-reload\"],\n });\n await this.runCheckedCommand({\n command: plan.systemctlCommand,\n args: [...plan.systemctlScopeArgs, \"enable\", plan.resourceName],\n });\n await this.runCheckedCommand({\n command: plan.systemctlCommand,\n args: [...plan.systemctlScopeArgs, \"restart\", plan.resourceName],\n });\n }\n } catch (error) {\n return {\n ok: false,\n dryRun: Boolean(options.dryRun),\n scope,\n hostOwner: plan.hostOwner,\n resourceName: plan.resourceName,\n resourcePath: plan.resourcePath,\n homeDir: plan.homeDir,\n command: plan.command,\n logHint: plan.logHint,\n actions,\n reasonIfUnavailable: error instanceof Error ? error.message : \"systemd autostart install failed.\",\n };\n }\n\n return {\n ok: true,\n dryRun: Boolean(options.dryRun),\n scope,\n hostOwner: plan.hostOwner,\n resourceName: plan.resourceName,\n resourcePath: plan.resourcePath,\n homeDir: plan.homeDir,\n command: plan.command,\n logHint: plan.logHint,\n actions,\n reasonIfUnavailable: null,\n };\n };\n\n uninstall = async (scope: HostAutostartScope, options: { dryRun?: boolean } = {}): Promise<HostAutostartUninstallResult> => {\n const plan = this.buildPlan(scope);\n if (!this.isSupported()) {\n return {\n ok: false,\n dryRun: Boolean(options.dryRun),\n scope,\n hostOwner: plan.hostOwner,\n resourceName: plan.resourceName,\n resourcePath: plan.resourcePath,\n removed: false,\n logHint: plan.logHint,\n actions: [],\n reasonIfUnavailable: this.getUnsupportedReason(),\n };\n }\n\n const installed = this.pathExists(plan.resourcePath);\n const actions: string[] = [];\n\n if (!installed) {\n return {\n ok: true,\n dryRun: Boolean(options.dryRun),\n scope,\n hostOwner: plan.hostOwner,\n resourceName: plan.resourceName,\n resourcePath: plan.resourcePath,\n removed: false,\n logHint: plan.logHint,\n actions: [\"no installed unit file found\"],\n reasonIfUnavailable: null,\n };\n }\n\n actions.push(`run ${this.formatCommand(plan.systemctlCommand, [...plan.systemctlScopeArgs, \"disable\", \"--now\", plan.resourceName])}`);\n actions.push(`remove unit file ${plan.resourcePath}`);\n actions.push(`run ${this.formatCommand(plan.systemctlCommand, [...plan.systemctlScopeArgs, \"daemon-reload\"])}`);\n\n try {\n if (!options.dryRun) {\n await this.runCheckedCommand({\n command: plan.systemctlCommand,\n args: [...plan.systemctlScopeArgs, \"disable\", \"--now\", plan.resourceName],\n });\n this.removeFile(plan.resourcePath, { force: true });\n await this.runCheckedCommand({\n command: plan.systemctlCommand,\n args: [...plan.systemctlScopeArgs, \"daemon-reload\"],\n });\n }\n } catch (error) {\n return {\n ok: false,\n dryRun: Boolean(options.dryRun),\n scope,\n hostOwner: plan.hostOwner,\n resourceName: plan.resourceName,\n resourcePath: plan.resourcePath,\n removed: false,\n logHint: plan.logHint,\n actions,\n reasonIfUnavailable: error instanceof Error ? error.message : \"systemd autostart uninstall failed.\",\n };\n }\n\n return {\n ok: true,\n dryRun: Boolean(options.dryRun),\n scope,\n hostOwner: plan.hostOwner,\n resourceName: plan.resourceName,\n resourcePath: plan.resourcePath,\n removed: true,\n logHint: plan.logHint,\n actions,\n reasonIfUnavailable: null,\n };\n };\n\n status = async (requestedScope?: HostAutostartScope): Promise<HostAutostartStatus> => {\n if (!this.isSupported()) {\n return this.createUnsupportedStatus();\n }\n\n const resolvedScope = this.resolveScopeForRead(requestedScope);\n if (!resolvedScope.scope) {\n return {\n supported: true,\n installed: false,\n enabled: null,\n active: null,\n scope: null,\n hostOwner: null,\n resourceName: null,\n resourcePath: null,\n homeDir: null,\n command: null,\n logHint: null,\n reasonIfUnavailable: resolvedScope.reasonIfUnavailable,\n };\n }\n\n const plan = this.buildPlan(resolvedScope.scope);\n const installed = this.pathExists(plan.resourcePath);\n if (!installed) {\n return {\n supported: true,\n installed: false,\n enabled: false,\n active: false,\n scope: resolvedScope.scope,\n hostOwner: plan.hostOwner,\n resourceName: plan.resourceName,\n resourcePath: plan.resourcePath,\n homeDir: plan.homeDir,\n command: plan.command,\n logHint: plan.logHint,\n reasonIfUnavailable: null,\n };\n }\n\n const enabledResult = await this.runCommandImpl(plan.systemctlCommand, [...plan.systemctlScopeArgs, \"is-enabled\", plan.resourceName]);\n const activeResult = await this.runCommandImpl(plan.systemctlCommand, [...plan.systemctlScopeArgs, \"is-active\", plan.resourceName]);\n\n return {\n supported: true,\n installed: true,\n enabled: enabledResult.code === 0,\n active: activeResult.code === 0,\n scope: resolvedScope.scope,\n hostOwner: plan.hostOwner,\n resourceName: plan.resourceName,\n resourcePath: plan.resourcePath,\n homeDir: plan.homeDir,\n command: plan.command,\n logHint: plan.logHint,\n reasonIfUnavailable: null,\n };\n };\n\n doctor = async (requestedScope?: HostAutostartScope): Promise<HostAutostartDoctorReport> => {\n const status = await this.status(requestedScope);\n const checks: HostAutostartCheck[] = [];\n const launchPlan = this.runtimeService.resolveForegroundServeLaunch();\n\n checks.push({\n name: \"platform\",\n status: status.supported ? \"pass\" : \"fail\",\n detail: status.supported ? \"linux supported\" : (status.reasonIfUnavailable ?? \"unsupported platform\"),\n });\n\n checks.push({\n name: \"unit-file\",\n status: status.installed ? \"pass\" : \"warn\",\n detail: status.resourcePath ?? \"no unit path\",\n });\n\n checks.push({\n name: \"exec-path\",\n status: this.pathExists(launchPlan.command) ? \"pass\" : \"fail\",\n detail: launchPlan.command,\n });\n\n checks.push({\n name: \"home-dir\",\n status: this.pathExists(launchPlan.homeDir) ? \"pass\" : \"warn\",\n detail: launchPlan.homeDir,\n });\n\n if (status.installed) {\n checks.push({\n name: \"enabled\",\n status: status.enabled ? \"pass\" : \"warn\",\n detail: status.enabled ? \"systemd unit enabled\" : \"systemd unit not enabled\",\n });\n checks.push({\n name: \"active\",\n status: status.active ? \"pass\" : \"warn\",\n detail: status.active ? \"systemd unit active\" : \"systemd unit not active\",\n });\n }\n\n const exitCode = checks.some((check) => check.status === \"fail\")\n ? 1\n : checks.some((check) => check.status === \"warn\")\n ? 1\n : 0;\n\n return {\n status,\n checks,\n exitCode,\n };\n };\n\n private isSupported = (): boolean => {\n return this.platform === SUPPORTED_PLATFORM;\n };\n\n private getUnsupportedReason = (): string => {\n return \"systemd autostart currently supports Linux only.\";\n };\n\n private createUnsupportedStatus = (): HostAutostartStatus => {\n return {\n supported: false,\n installed: false,\n enabled: null,\n active: null,\n scope: null,\n hostOwner: null,\n resourceName: null,\n resourcePath: null,\n homeDir: null,\n command: null,\n logHint: null,\n reasonIfUnavailable: this.getUnsupportedReason(),\n };\n };\n\n private createUnsupportedInstallResult = (scope: HostAutostartScope, dryRun: boolean): HostAutostartInstallResult => {\n const plan = this.buildPlan(scope);\n return {\n ok: false,\n dryRun,\n scope,\n hostOwner: plan.hostOwner,\n resourceName: plan.resourceName,\n resourcePath: plan.resourcePath,\n homeDir: plan.homeDir,\n command: plan.command,\n logHint: plan.logHint,\n actions: [],\n reasonIfUnavailable: this.getUnsupportedReason(),\n };\n };\n\n private resolveScopeForRead = (requestedScope?: HostAutostartScope): ResolvedScopeStatus => {\n if (requestedScope) {\n return { scope: requestedScope, reasonIfUnavailable: null };\n }\n const userInstalled = this.pathExists(this.getUnitPath(\"user\"));\n const systemInstalled = this.pathExists(this.getUnitPath(\"system\"));\n if (userInstalled && systemInstalled) {\n return {\n scope: null,\n reasonIfUnavailable: \"Both user and system units are installed. Re-run with --user or --system.\",\n };\n }\n if (userInstalled) {\n return { scope: \"user\", reasonIfUnavailable: null };\n }\n if (systemInstalled) {\n return { scope: \"system\", reasonIfUnavailable: null };\n }\n return { scope: \"user\", reasonIfUnavailable: null };\n };\n\n private buildPlan = (scope: HostAutostartScope) => {\n const launch = this.runtimeService.resolveForegroundServeLaunch();\n const command = this.formatCommand(launch.command, launch.args);\n const resourceName = DEFAULT_SYSTEMD_SERVICE_NAME;\n const resourcePath = this.getUnitPath(scope);\n const homeDir = launch.homeDir;\n const hostOwner: HostAutostartOwner = scope === \"user\" ? \"systemd-user-service\" : \"systemd-system-service\";\n const systemctlScopeArgs = scope === \"user\" ? [\"--user\"] : [];\n const logHint = scope === \"user\"\n ? `journalctl --user -u ${resourceName} -f`\n : `journalctl -u ${resourceName} -f`;\n const wantedBy = scope === \"user\" ? \"default.target\" : \"multi-user.target\";\n\n return {\n scope,\n resourceName,\n resourcePath,\n homeDir,\n hostOwner,\n command,\n logHint,\n unitContent: [\n \"[Unit]\",\n \"Description=NextClaw managed local service\",\n \"After=network-online.target\",\n \"Wants=network-online.target\",\n \"\",\n \"[Service]\",\n \"Type=simple\",\n `WorkingDirectory=${this.escapeSystemdValue(homeDir)}`,\n `Environment=NEXTCLAW_HOME=${this.escapeSystemdValue(homeDir)}`,\n \"Environment=NEXTCLAW_PROCESS_SUPERVISOR=systemd\",\n `ExecStart=${command}`,\n \"Restart=always\",\n \"RestartSec=2\",\n \"\",\n \"[Install]\",\n `WantedBy=${wantedBy}`,\n \"\",\n ].join(\"\\n\"),\n systemctlCommand: \"systemctl\",\n systemctlScopeArgs,\n };\n };\n\n private getUnitPath = (scope: HostAutostartScope): string => {\n if (scope === \"system\") {\n return \"/etc/systemd/system/nextclaw.service\";\n }\n const xdgConfigHome = this.env.XDG_CONFIG_HOME?.trim();\n const configHome = xdgConfigHome || join(this.getHomeDir(), \".config\");\n return resolve(configHome, \"systemd\", \"user\", \"nextclaw.service\");\n };\n\n private escapeSystemdValue = (value: string): string => {\n if (/^[A-Za-z0-9_./:@%+=,-]+$/.test(value)) {\n return value;\n }\n return `\"${value.replace(/([\"\\\\])/g, \"\\\\$1\")}\"`;\n };\n\n private formatCommand = (command: string, args: string[]): string => {\n return [command, ...args].map((value) => this.escapeSystemdValue(value)).join(\" \");\n };\n\n private runCheckedCommand = async ({ command, args }: CheckedCommandParams): Promise<void> => {\n const result = await this.runCommandImpl(command, args);\n if (result.code === 0) {\n return;\n }\n const detail = result.stderr || result.stdout || `exit code ${result.code}`;\n throw new Error(`Command failed: ${this.formatCommand(command, args)} (${detail})`);\n };\n}\n\nconst defaultRunCommand = async (command: string, args: string[]): Promise<HostAutostartRunCommandResult> => {\n return await new Promise<HostAutostartRunCommandResult>((resolvePromise, rejectPromise) => {\n const child = spawn(command, args, {\n env: process.env,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n\n let stdout = \"\";\n let stderr = \"\";\n child.stdout?.setEncoding(\"utf-8\");\n child.stderr?.setEncoding(\"utf-8\");\n child.stdout?.on(\"data\", (chunk: string) => {\n stdout += chunk;\n });\n child.stderr?.on(\"data\", (chunk: string) => {\n stderr += chunk;\n });\n child.on(\"error\", (error) => {\n rejectPromise(error);\n });\n child.on(\"close\", (code) => {\n resolvePromise({\n code: code ?? 1,\n stdout: stdout.trim(),\n stderr: stderr.trim(),\n });\n });\n });\n};\n"],"mappings":";;;;;;AAuCA,MAAM,+BAA+B;AACrC,MAAM,qBAAqB;AAE3B,IAAa,+BAAb,MAA0C;CACxC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA,YAAY,UAA+C,EAAE,EAAE;AAC7D,OAAK,WAAW,QAAQ,YAAY,QAAQ;AAC5C,OAAK,MAAM,QAAQ,OAAO,QAAQ;AAClC,OAAK,aAAa,QAAQ,cAAc;AACxC,OAAK,aAAa,QAAQ,cAAc;AACxC,OAAK,YAAY,QAAQ,aAAa;AACtC,OAAK,YAAY,QAAQ,iBAAiB;AAC1C,OAAK,aAAa,QAAQ,UAAU;AACpC,OAAK,iBAAiB,QAAQ,cAAc;AAC5C,OAAK,iBAAiB,QAAQ,kBAAkB,IAAI,6BAA6B;;CAGnF,UAAU,OAAO,OAA2B,UAAgC,EAAE,KAA0C;AACtH,MAAI,CAAC,KAAK,aAAa,CACrB,QAAO,KAAK,+BAA+B,OAAO,QAAQ,QAAQ,OAAO,CAAC;EAG5E,MAAM,OAAO,KAAK,UAAU,MAAM;EAClC,MAAM,UAAU;GACd,mBAAmB,KAAK;GACxB,OAAO,KAAK,cAAc,KAAK,kBAAkB,CAAC,GAAG,KAAK,oBAAoB,gBAAgB,CAAC;GAC/F,OAAO,KAAK,cAAc,KAAK,kBAAkB;IAAC,GAAG,KAAK;IAAoB;IAAU,KAAK;IAAa,CAAC;GAC3G,OAAO,KAAK,cAAc,KAAK,kBAAkB;IAAC,GAAG,KAAK;IAAoB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.set ${pathExpr}`,
|
|
68
|
-
manualMessage: `Updated ${pathExpr}.
|
|
68
|
+
manualMessage: `Updated ${pathExpr}. Run nextclaw restart in an external terminal to apply.`,
|
|
69
69
|
silentRestartNotice: opts.silentRestartNotice
|
|
70
70
|
});
|
|
71
71
|
};
|
|
@@ -91,7 +91,7 @@ var ConfigCommands = class {
|
|
|
91
91
|
prevConfig,
|
|
92
92
|
nextConfig,
|
|
93
93
|
reason: `config.unset ${pathExpr}`,
|
|
94
|
-
manualMessage: `Removed ${pathExpr}.
|
|
94
|
+
manualMessage: `Removed ${pathExpr}. Run nextclaw restart in an external terminal to apply.`
|
|
95
95
|
});
|
|
96
96
|
};
|
|
97
97
|
resolveReadConfigView = (config, parsedPath) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config-commands.service.js","names":[],"sources":["../../../src/services/config/config-commands.service.ts"],"sourcesContent":["import { buildReloadPlan, diffConfigPaths, loadConfig, saveConfig, type Config } from \"@nextclaw/core\";\nimport { getAtConfigPath, parseConfigSetValue, parseRequiredConfigPath, setAtConfigPath, unsetAtConfigPath } from \"@nextclaw-service/utils/config-path.utils.js\";\nimport { resolveChannelConfigView } from \"@nextclaw-service/controllers/commands/channel-command.controller.js\";\nimport type { ConfigGetOptions, ConfigSetOptions, RequestRestartParams } from \"@nextclaw-service/types/cli.types.js\";\n\nexport class ConfigCommands {\n constructor(\n private deps: {\n requestRestart: (params: RequestRestartParams) => Promise<void>;\n }\n ) {}\n\n get = (pathExpr: string, opts: ConfigGetOptions = {}): void => {\n let parsedPath: string[];\n try {\n parsedPath = parseRequiredConfigPath(pathExpr);\n } catch (error) {\n console.error(String(error));\n process.exit(1);\n return;\n }\n\n const config = loadConfig();\n const resolvedConfig = this.resolveReadConfigView(config, parsedPath) as unknown as Record<string, unknown>;\n const result = getAtConfigPath(resolvedConfig, parsedPath);\n if (!result.found) {\n console.error(`Config path not found: ${pathExpr}`);\n process.exit(1);\n return;\n }\n\n if (opts.json) {\n console.log(JSON.stringify(result.value ?? null, null, 2));\n return;\n }\n\n if (\n typeof result.value === \"string\" ||\n typeof result.value === \"number\" ||\n typeof result.value === \"boolean\"\n ) {\n console.log(String(result.value));\n return;\n }\n\n console.log(JSON.stringify(result.value ?? null, null, 2));\n };\n\n set = async (pathExpr: string, value: string, opts: ConfigSetOptions = {}): Promise<void> => {\n let parsedPath: string[];\n try {\n parsedPath = parseRequiredConfigPath(pathExpr);\n } catch (error) {\n console.error(String(error));\n process.exit(1);\n return;\n }\n\n let parsedValue: unknown;\n try {\n parsedValue = parseConfigSetValue(value, opts);\n } catch (error) {\n console.error(`Failed to parse config value: ${String(error)}`);\n process.exit(1);\n return;\n }\n\n const prevConfig = loadConfig();\n const nextConfigTarget = structuredClone(prevConfig) as unknown as Record<string, unknown>;\n try {\n setAtConfigPath(nextConfigTarget, parsedPath, parsedValue);\n } catch (error) {\n console.error(String(error));\n process.exit(1);\n return;\n }\n\n const nextConfig = nextConfigTarget as Config;\n saveConfig(nextConfig as Config);\n await this.requestRestartForConfigDiff({\n prevConfig,\n nextConfig: nextConfig as Config,\n reason: `config.set ${pathExpr}`,\n manualMessage: `Updated ${pathExpr}.
|
|
1
|
+
{"version":3,"file":"config-commands.service.js","names":[],"sources":["../../../src/services/config/config-commands.service.ts"],"sourcesContent":["import { buildReloadPlan, diffConfigPaths, loadConfig, saveConfig, type Config } from \"@nextclaw/core\";\nimport { getAtConfigPath, parseConfigSetValue, parseRequiredConfigPath, setAtConfigPath, unsetAtConfigPath } from \"@nextclaw-service/utils/config-path.utils.js\";\nimport { resolveChannelConfigView } from \"@nextclaw-service/controllers/commands/channel-command.controller.js\";\nimport type { ConfigGetOptions, ConfigSetOptions, RequestRestartParams } from \"@nextclaw-service/types/cli.types.js\";\n\nexport class ConfigCommands {\n constructor(\n private deps: {\n requestRestart: (params: RequestRestartParams) => Promise<void>;\n }\n ) {}\n\n get = (pathExpr: string, opts: ConfigGetOptions = {}): void => {\n let parsedPath: string[];\n try {\n parsedPath = parseRequiredConfigPath(pathExpr);\n } catch (error) {\n console.error(String(error));\n process.exit(1);\n return;\n }\n\n const config = loadConfig();\n const resolvedConfig = this.resolveReadConfigView(config, parsedPath) as unknown as Record<string, unknown>;\n const result = getAtConfigPath(resolvedConfig, parsedPath);\n if (!result.found) {\n console.error(`Config path not found: ${pathExpr}`);\n process.exit(1);\n return;\n }\n\n if (opts.json) {\n console.log(JSON.stringify(result.value ?? null, null, 2));\n return;\n }\n\n if (\n typeof result.value === \"string\" ||\n typeof result.value === \"number\" ||\n typeof result.value === \"boolean\"\n ) {\n console.log(String(result.value));\n return;\n }\n\n console.log(JSON.stringify(result.value ?? null, null, 2));\n };\n\n set = async (pathExpr: string, value: string, opts: ConfigSetOptions = {}): Promise<void> => {\n let parsedPath: string[];\n try {\n parsedPath = parseRequiredConfigPath(pathExpr);\n } catch (error) {\n console.error(String(error));\n process.exit(1);\n return;\n }\n\n let parsedValue: unknown;\n try {\n parsedValue = parseConfigSetValue(value, opts);\n } catch (error) {\n console.error(`Failed to parse config value: ${String(error)}`);\n process.exit(1);\n return;\n }\n\n const prevConfig = loadConfig();\n const nextConfigTarget = structuredClone(prevConfig) as unknown as Record<string, unknown>;\n try {\n setAtConfigPath(nextConfigTarget, parsedPath, parsedValue);\n } catch (error) {\n console.error(String(error));\n process.exit(1);\n return;\n }\n\n const nextConfig = nextConfigTarget as Config;\n saveConfig(nextConfig as Config);\n await this.requestRestartForConfigDiff({\n prevConfig,\n nextConfig: nextConfig as Config,\n reason: `config.set ${pathExpr}`,\n manualMessage: `Updated ${pathExpr}. Run nextclaw restart in an external terminal to apply.`,\n silentRestartNotice: opts.silentRestartNotice,\n });\n };\n\n unset = async (pathExpr: string): Promise<void> => {\n let parsedPath: string[];\n try {\n parsedPath = parseRequiredConfigPath(pathExpr);\n } catch (error) {\n console.error(String(error));\n process.exit(1);\n return;\n }\n\n const prevConfig = loadConfig();\n const nextConfigTarget = structuredClone(prevConfig) as unknown as Record<string, unknown>;\n const removed = unsetAtConfigPath(nextConfigTarget, parsedPath);\n if (!removed) {\n console.error(`Config path not found: ${pathExpr}`);\n process.exit(1);\n return;\n }\n\n const nextConfig = nextConfigTarget as Config;\n saveConfig(nextConfig as Config);\n await this.requestRestartForConfigDiff({\n prevConfig,\n nextConfig: nextConfig as Config,\n reason: `config.unset ${pathExpr}`,\n manualMessage: `Removed ${pathExpr}. Run nextclaw restart in an external terminal to apply.`\n });\n };\n\n private resolveReadConfigView = (config: Config, parsedPath: string[]): Config => {\n if (parsedPath[0] !== \"channels\") {\n return config;\n }\n return resolveChannelConfigView(config);\n };\n\n private requestRestartForConfigDiff = async (params: {\n prevConfig: Config;\n nextConfig: Config;\n reason: string;\n manualMessage: string;\n silentRestartNotice?: boolean;\n }): Promise<void> => {\n const {\n manualMessage,\n nextConfig,\n prevConfig,\n reason,\n silentRestartNotice,\n } = params;\n const changedPaths = diffConfigPaths(prevConfig, nextConfig);\n if (!changedPaths.length) {\n return;\n }\n const plan = buildReloadPlan(changedPaths);\n if (plan.restartRequired.length === 0) {\n return;\n }\n await this.deps.requestRestart({\n changedPaths: plan.restartRequired,\n mode: \"notify\",\n reason: `${reason} (${plan.restartRequired.join(\", \")})`,\n manualMessage,\n silentNotification: silentRestartNotice,\n });\n };\n}\n"],"mappings":";;;;;AAKA,IAAa,iBAAb,MAA4B;CAC1B,YACE,MAGA;AAHQ,OAAA,OAAA;;CAKV,OAAO,UAAkB,OAAyB,EAAE,KAAW;EAC7D,IAAI;AACJ,MAAI;AACF,gBAAa,wBAAwB,SAAS;WACvC,OAAO;AACd,WAAQ,MAAM,OAAO,MAAM,CAAC;AAC5B,WAAQ,KAAK,EAAE;AACf;;EAGF,MAAM,SAAS,YAAY;EAE3B,MAAM,SAAS,gBADQ,KAAK,sBAAsB,QAAQ,WAAW,EACtB,WAAW;AAC1D,MAAI,CAAC,OAAO,OAAO;AACjB,WAAQ,MAAM,0BAA0B,WAAW;AACnD,WAAQ,KAAK,EAAE;AACf;;AAG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AACZ,WAAQ,MAAM,0BAA0B,WAAW;AACnD,WAAQ,KAAK,EAAE;AACf;;EAGF,MAAM,aAAa;AACnB,aAAW,WAAqB;AAChC,QAAM,KAAK,4BAA4B;GACrC;GACY;GACZ,QAAQ,gBAAgB;GACxB,eAAe,WAAW,SAAS;GACpC,CAAC;;CAGJ,yBAAiC,QAAgB,eAAiC;AAChF,MAAI,WAAW,OAAO,WACpB,QAAO;AAET,SAAO,yBAAyB,OAAO;;CAGzC,8BAAsC,OAAO,WAMxB;EACnB,MAAM,EACJ,eACA,YACA,YACA,QACA,wBACE;EACJ,MAAM,eAAe,gBAAgB,YAAY,WAAW;AAC5D,MAAI,CAAC,aAAa,OAChB;EAEF,MAAM,OAAO,gBAAgB,aAAa;AAC1C,MAAI,KAAK,gBAAgB,WAAW,EAClC;AAEF,QAAM,KAAK,KAAK,eAAe;GAC7B,cAAc,KAAK;GACnB,MAAM;GACN,QAAQ,GAAG,OAAO,IAAI,KAAK,gBAAgB,KAAK,KAAK,CAAC;GACtD;GACA,oBAAoB;GACrB,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"service-marketplace-installer.service.d.ts","names":[],"sources":["../../../src/services/marketplace/service-marketplace-installer.service.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"service-marketplace-installer.service.d.ts","names":[],"sources":["../../../src/services/marketplace/service-marketplace-installer.service.ts"],"mappings":";;;KAqBK,gBAAA;EACH,OAAA;EACA,MAAA;AAAA;AAAA,KAGG,yBAAA,GAA4B,gBAAA;AAAA,cAEpB,2BAAA;EAAA,iBAEQ,IAAA;cAAA,IAAA;IACf,qBAAA,SAA8B,OAAA;IAC9B,gBAAA,GAAmB,IAAA,eAAmB,OAAA;IACtC,mBAAA,GAAsB,IAAA,UAAc,KAAA,eAAoB,yBAAA;EAAA;EAI5D,eAAA,QAAsB,oBAAA;EAAA,QAad,YAAA;EAAA,QAkCA,UAAA;EAAA,QAIA,WAAA;EAAA,QAwBA,cAAA;EAAA,QAkBA,SAAA;EAAA,QAIA,UAAA;EAAA,QAIA,SAAA;EAAA,QAIA,SAAA;EAAA,QAIA,uBAAA;AAAA"}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { buildMarketplaceSkillInstallArgs, buildMarketplaceSkillUpdateArgs, pickUserFacingCommandSummary } from "../../utils/marketplace/service-marketplace-helpers.utils.js";
|
|
2
2
|
import { validateSkillSlug } from "../../utils/marketplace/marketplace-identity.utils.js";
|
|
3
3
|
import { ServiceMcpMarketplaceOps } from "./service-mcp-marketplace-ops.service.js";
|
|
4
|
+
import { MarketplaceSkillLocalChangesError } from "../../utils/marketplace/marketplace-skill-lifecycle.utils.js";
|
|
5
|
+
import "../../utils/marketplace/marketplace.utils.js";
|
|
4
6
|
import { getSkillsPath, getWorkspacePath, loadConfig } from "@nextclaw/core";
|
|
5
7
|
import { existsSync, rmSync } from "node:fs";
|
|
6
8
|
import { dirname, resolve } from "node:path";
|
|
@@ -46,14 +48,21 @@ var ServiceMarketplaceInstaller = class {
|
|
|
46
48
|
return await this.createMcpMarketplaceOps().install(params);
|
|
47
49
|
};
|
|
48
50
|
updateSkill = async (params) => {
|
|
51
|
+
const { force, slug } = params;
|
|
49
52
|
const workspace = getWorkspacePath(loadConfig().agents.defaults.workspace);
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
53
|
+
let output;
|
|
54
|
+
try {
|
|
55
|
+
output = await this.deps.runCliSubcommand(buildMarketplaceSkillUpdateArgs({
|
|
56
|
+
slug,
|
|
57
|
+
workspace,
|
|
58
|
+
force
|
|
59
|
+
}));
|
|
60
|
+
} catch (error) {
|
|
61
|
+
if (!force && error instanceof Error && error.message.includes("Local skill files changed since install:")) throw new MarketplaceSkillLocalChangesError(slug);
|
|
62
|
+
throw error;
|
|
63
|
+
}
|
|
55
64
|
return {
|
|
56
|
-
message: pickUserFacingCommandSummary(output, `Updated skill: ${
|
|
65
|
+
message: pickUserFacingCommandSummary(output, `Updated skill: ${slug}`),
|
|
57
66
|
output
|
|
58
67
|
};
|
|
59
68
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"service-marketplace-installer.service.js","names":[],"sources":["../../../src/services/marketplace/service-marketplace-installer.service.ts"],"sourcesContent":["import { getSkillsPath, getWorkspacePath, loadConfig } from \"@nextclaw/core\";\nimport type {\n MarketplaceInstallSkillParams,\n MarketplaceInstaller,\n MarketplaceMcpDoctorResult,\n MarketplaceMcpInstallRequest\n} from \"@nextclaw/server\";\nimport { existsSync, rmSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\nimport {\n buildMarketplaceSkillInstallArgs,\n buildMarketplaceSkillUpdateArgs,\n pickUserFacingCommandSummary\n} from \"@nextclaw-service/utils/marketplace/service-marketplace-helpers.utils.js\";\nimport { validateSkillSlug } from \"@nextclaw-service/utils/marketplace/marketplace-identity.utils.js\";\nimport { ServiceMcpMarketplaceOps } from \"@nextclaw-service/services/marketplace/service-mcp-marketplace-ops.service.js\";\n\ntype UserFacingResult = {\n message: string;\n output?: string;\n};\n\ntype BuiltinSkillInstallResult = UserFacingResult | null;\n\nexport class ServiceMarketplaceInstaller {\n constructor(\n private readonly deps: {\n applyLiveConfigReload?: () => Promise<void>;\n runCliSubcommand: (args: string[]) => Promise<string>;\n installBuiltinSkill: (slug: string, force?: boolean) => BuiltinSkillInstallResult;\n }\n ) {}\n\n createInstaller = (): MarketplaceInstaller => {\n return {\n installSkill: this.installSkill,\n updateSkill: this.updateSkill,\n installMcp: this.installMcp,\n uninstallSkill: this.uninstallSkill,\n enableMcp: this.enableMcp,\n disableMcp: this.disableMcp,\n removeMcp: this.removeMcp,\n doctorMcp: this.doctorMcp\n };\n };\n\n private installSkill = async (params: MarketplaceInstallSkillParams): Promise<UserFacingResult> => {\n const { force, kind, slug } = params;\n if (kind === \"builtin\") {\n const result = this.deps.installBuiltinSkill(slug, force);\n if (!result) {\n throw new Error(`Builtin skill not found: ${slug}`);\n }\n return result;\n }\n\n if (kind && kind !== \"marketplace\") {\n throw new Error(`Unsupported marketplace skill kind: ${kind}`);\n }\n\n const workspace = getWorkspacePath(loadConfig().agents.defaults.workspace);\n const args = buildMarketplaceSkillInstallArgs({\n slug,\n workspace,\n force\n });\n\n try {\n const output = await this.deps.runCliSubcommand(args);\n const summary = pickUserFacingCommandSummary(output, `Installed skill: ${slug}`);\n return { message: summary };\n } catch (error) {\n const fallback = this.deps.installBuiltinSkill(slug, force);\n if (!fallback) {\n throw error;\n }\n return fallback;\n }\n };\n\n private installMcp = async (params: MarketplaceMcpInstallRequest): Promise<{ name: string; message: string; output?: string }> => {\n return await this.createMcpMarketplaceOps().install(params);\n };\n\n private updateSkill = async (params: MarketplaceInstallSkillParams): Promise<UserFacingResult> => {\n const workspace = getWorkspacePath(loadConfig().agents.defaults.workspace);\n
|
|
1
|
+
{"version":3,"file":"service-marketplace-installer.service.js","names":[],"sources":["../../../src/services/marketplace/service-marketplace-installer.service.ts"],"sourcesContent":["import { getSkillsPath, getWorkspacePath, loadConfig } from \"@nextclaw/core\";\nimport type {\n MarketplaceInstallSkillParams,\n MarketplaceInstaller,\n MarketplaceMcpDoctorResult,\n MarketplaceMcpInstallRequest\n} from \"@nextclaw/server\";\nimport { existsSync, rmSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\nimport {\n buildMarketplaceSkillInstallArgs,\n buildMarketplaceSkillUpdateArgs,\n pickUserFacingCommandSummary\n} from \"@nextclaw-service/utils/marketplace/service-marketplace-helpers.utils.js\";\nimport { validateSkillSlug } from \"@nextclaw-service/utils/marketplace/marketplace-identity.utils.js\";\nimport { ServiceMcpMarketplaceOps } from \"@nextclaw-service/services/marketplace/service-mcp-marketplace-ops.service.js\";\nimport {\n MARKETPLACE_SKILL_LOCAL_CHANGES_MESSAGE_PREFIX,\n MarketplaceSkillLocalChangesError\n} from \"@nextclaw-service/utils/marketplace/marketplace.utils.js\";\n\ntype UserFacingResult = {\n message: string;\n output?: string;\n};\n\ntype BuiltinSkillInstallResult = UserFacingResult | null;\n\nexport class ServiceMarketplaceInstaller {\n constructor(\n private readonly deps: {\n applyLiveConfigReload?: () => Promise<void>;\n runCliSubcommand: (args: string[]) => Promise<string>;\n installBuiltinSkill: (slug: string, force?: boolean) => BuiltinSkillInstallResult;\n }\n ) {}\n\n createInstaller = (): MarketplaceInstaller => {\n return {\n installSkill: this.installSkill,\n updateSkill: this.updateSkill,\n installMcp: this.installMcp,\n uninstallSkill: this.uninstallSkill,\n enableMcp: this.enableMcp,\n disableMcp: this.disableMcp,\n removeMcp: this.removeMcp,\n doctorMcp: this.doctorMcp\n };\n };\n\n private installSkill = async (params: MarketplaceInstallSkillParams): Promise<UserFacingResult> => {\n const { force, kind, slug } = params;\n if (kind === \"builtin\") {\n const result = this.deps.installBuiltinSkill(slug, force);\n if (!result) {\n throw new Error(`Builtin skill not found: ${slug}`);\n }\n return result;\n }\n\n if (kind && kind !== \"marketplace\") {\n throw new Error(`Unsupported marketplace skill kind: ${kind}`);\n }\n\n const workspace = getWorkspacePath(loadConfig().agents.defaults.workspace);\n const args = buildMarketplaceSkillInstallArgs({\n slug,\n workspace,\n force\n });\n\n try {\n const output = await this.deps.runCliSubcommand(args);\n const summary = pickUserFacingCommandSummary(output, `Installed skill: ${slug}`);\n return { message: summary };\n } catch (error) {\n const fallback = this.deps.installBuiltinSkill(slug, force);\n if (!fallback) {\n throw error;\n }\n return fallback;\n }\n };\n\n private installMcp = async (params: MarketplaceMcpInstallRequest): Promise<{ name: string; message: string; output?: string }> => {\n return await this.createMcpMarketplaceOps().install(params);\n };\n\n private updateSkill = async (params: MarketplaceInstallSkillParams): Promise<UserFacingResult> => {\n const { force, slug } = params;\n const workspace = getWorkspacePath(loadConfig().agents.defaults.workspace);\n let output: string;\n try {\n output = await this.deps.runCliSubcommand(buildMarketplaceSkillUpdateArgs({\n slug,\n workspace,\n force\n }));\n } catch (error) {\n if (\n !force\n && error instanceof Error\n && error.message.includes(MARKETPLACE_SKILL_LOCAL_CHANGES_MESSAGE_PREFIX)\n ) {\n throw new MarketplaceSkillLocalChangesError(slug);\n }\n throw error;\n }\n const summary = pickUserFacingCommandSummary(output, `Updated skill: ${slug}`);\n return { message: summary, output };\n };\n\n private uninstallSkill = async (slug: string): Promise<UserFacingResult> => {\n const skillsRoot = getSkillsPath(getWorkspacePath(loadConfig().agents.defaults.workspace));\n const targetDir = resolve(skillsRoot, validateSkillSlug(slug.trim(), \"slug\"));\n if (dirname(targetDir) !== skillsRoot) {\n throw new Error(`Skill uninstall target must be a direct workspace skill: ${slug}`);\n }\n\n if (!existsSync(resolve(targetDir, \"SKILL.md\"))) {\n throw new Error(`Skill not installed in workspace: ${slug}`);\n }\n\n rmSync(targetDir, { recursive: true });\n\n return {\n message: `Uninstalled skill: ${slug}`\n };\n };\n\n private enableMcp = async (name: string): Promise<UserFacingResult> => {\n return await this.createMcpMarketplaceOps().enable(name);\n };\n\n private disableMcp = async (name: string): Promise<UserFacingResult> => {\n return await this.createMcpMarketplaceOps().disable(name);\n };\n\n private removeMcp = async (name: string): Promise<UserFacingResult> => {\n return await this.createMcpMarketplaceOps().remove(name);\n };\n\n private doctorMcp = async (name: string): Promise<MarketplaceMcpDoctorResult> => {\n return await this.createMcpMarketplaceOps().doctor(name);\n };\n\n private createMcpMarketplaceOps = (): ServiceMcpMarketplaceOps => {\n return new ServiceMcpMarketplaceOps({\n applyLiveConfigReload: this.deps.applyLiveConfigReload\n });\n };\n}\n"],"mappings":";;;;;;;;;AA4BA,IAAa,8BAAb,MAAyC;CACvC,YACE,MAKA;AALiB,OAAA,OAAA;;CAOnB,wBAA8C;AAC5C,SAAO;GACL,cAAc,KAAK;GACnB,aAAa,KAAK;GAClB,YAAY,KAAK;GACjB,gBAAgB,KAAK;GACrB,WAAW,KAAK;GAChB,YAAY,KAAK;GACjB,WAAW,KAAK;GAChB,WAAW,KAAK;GACjB;;CAGH,eAAuB,OAAO,WAAqE;EACjG,MAAM,EAAE,O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IAAI,MAAM,4DAA4D,OAAO;AAGrF,MAAI,CAAC,WAAW,QAAQ,WAAW,WAAW,CAAC,CAC7C,OAAM,IAAI,MAAM,qCAAqC,OAAO;AAG9D,SAAO,WAAW,EAAE,WAAW,MAAM,CAAC;AAEtC,SAAO,EACL,SAAS,sBAAsB,QAChC;;CAGH,YAAoB,OAAO,SAA4C;AACrE,SAAO,MAAM,KAAK,yBAAyB,CAAC,OAAO,KAAK;;CAG1D,aAAqB,OAAO,SAA4C;AACtE,SAAO,MAAM,KAAK,yBAAyB,CAAC,QAAQ,KAAK;;CAG3D,YAAoB,OAAO,SAA4C;AACrE,SAAO,MAAM,KAAK,yBAAyB,CAAC,OAAO,KAAK;;CAG1D,YAAoB,OAAO,SAAsD;AAC/E,SAAO,MAAM,KAAK,yBAAyB,CAAC,OAAO,KAAK;;CAG1D,gCAAkE;AAChE,SAAO,IAAI,yBAAyB,EAClC,uBAAuB,KAAK,KAAK,uBAClC,CAAC"}
|
|
@@ -43,7 +43,7 @@ var RestartCoordinator = class {
|
|
|
43
43
|
}
|
|
44
44
|
return {
|
|
45
45
|
status: "manual-required",
|
|
46
|
-
message: request.manualMessage ?? "
|
|
46
|
+
message: request.manualMessage ?? "Run nextclaw restart in an external terminal to apply changes."
|
|
47
47
|
};
|
|
48
48
|
};
|
|
49
49
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"restart-coordinator.service.js","names":[],"sources":["../../../src/services/restart/restart-coordinator.service.ts"],"sourcesContent":["import type { ManagedServiceState } from \"@nextclaw-service/stores/managed-service-state.store.js\";\n\nexport type RestartStrategy = \"background-service-or-manual\" | \"background-service-or-exit\" | \"exit-process\";\n\nexport type RestartRequest = {\n reason: string;\n strategy?: RestartStrategy;\n delayMs?: number;\n manualMessage?: string;\n};\n\nexport type RestartResult = {\n status: \"service-restarted\" | \"restart-in-progress\" | \"exit-scheduled\" | \"manual-required\";\n message: string;\n};\n\ntype RestartCoordinatorDeps = {\n readServiceState: () => ManagedServiceState | null;\n isProcessRunning: (pid: number) => boolean;\n currentPid: () => number;\n restartBackgroundService: (reason: string) => Promise<boolean>;\n scheduleProcessExit: (delayMs: number, reason: string) => void;\n};\n\nexport class RestartCoordinator {\n private restartingService = false;\n private exitScheduled = false;\n\n constructor(private deps: RestartCoordinatorDeps) {}\n\n readonly requestRestart = async (request: RestartRequest): Promise<RestartResult> => {\n const reason = request.reason.trim() || \"config changed\";\n const strategy = request.strategy ?? \"background-service-or-manual\";\n\n if (strategy !== \"exit-process\") {\n const state = this.deps.readServiceState();\n const serviceRunning = Boolean(state && this.deps.isProcessRunning(state.pid));\n const managedByCurrentProcess = Boolean(state && state.pid === this.deps.currentPid());\n\n if (serviceRunning && !managedByCurrentProcess) {\n if (this.restartingService) {\n return {\n status: \"restart-in-progress\",\n message: \"Restart already in progress; skipping duplicate request.\"\n };\n }\n this.restartingService = true;\n try {\n const restarted = await this.deps.restartBackgroundService(reason);\n if (restarted) {\n return {\n status: \"service-restarted\",\n message: `Restarted background service to apply changes (${reason}).`\n };\n }\n } finally {\n this.restartingService = false;\n }\n }\n }\n\n if (strategy === \"background-service-or-exit\" || strategy === \"exit-process\") {\n if (this.exitScheduled) {\n return {\n status: \"exit-scheduled\",\n message: \"Restart already scheduled; skipping duplicate request.\"\n };\n }\n const delay =\n typeof request.delayMs === \"number\" && Number.isFinite(request.delayMs) ? Math.max(0, Math.floor(request.delayMs)) : 100;\n this.exitScheduled = true;\n this.deps.scheduleProcessExit(delay, reason);\n return {\n status: \"exit-scheduled\",\n message: `Restart scheduled (${reason}).`\n };\n }\n\n return {\n status: \"manual-required\",\n message: request.manualMessage ?? \"
|
|
1
|
+
{"version":3,"file":"restart-coordinator.service.js","names":[],"sources":["../../../src/services/restart/restart-coordinator.service.ts"],"sourcesContent":["import type { ManagedServiceState } from \"@nextclaw-service/stores/managed-service-state.store.js\";\n\nexport type RestartStrategy = \"background-service-or-manual\" | \"background-service-or-exit\" | \"exit-process\";\n\nexport type RestartRequest = {\n reason: string;\n strategy?: RestartStrategy;\n delayMs?: number;\n manualMessage?: string;\n};\n\nexport type RestartResult = {\n status: \"service-restarted\" | \"restart-in-progress\" | \"exit-scheduled\" | \"manual-required\";\n message: string;\n};\n\ntype RestartCoordinatorDeps = {\n readServiceState: () => ManagedServiceState | null;\n isProcessRunning: (pid: number) => boolean;\n currentPid: () => number;\n restartBackgroundService: (reason: string) => Promise<boolean>;\n scheduleProcessExit: (delayMs: number, reason: string) => void;\n};\n\nexport class RestartCoordinator {\n private restartingService = false;\n private exitScheduled = false;\n\n constructor(private deps: RestartCoordinatorDeps) {}\n\n readonly requestRestart = async (request: RestartRequest): Promise<RestartResult> => {\n const reason = request.reason.trim() || \"config changed\";\n const strategy = request.strategy ?? \"background-service-or-manual\";\n\n if (strategy !== \"exit-process\") {\n const state = this.deps.readServiceState();\n const serviceRunning = Boolean(state && this.deps.isProcessRunning(state.pid));\n const managedByCurrentProcess = Boolean(state && state.pid === this.deps.currentPid());\n\n if (serviceRunning && !managedByCurrentProcess) {\n if (this.restartingService) {\n return {\n status: \"restart-in-progress\",\n message: \"Restart already in progress; skipping duplicate request.\"\n };\n }\n this.restartingService = true;\n try {\n const restarted = await this.deps.restartBackgroundService(reason);\n if (restarted) {\n return {\n status: \"service-restarted\",\n message: `Restarted background service to apply changes (${reason}).`\n };\n }\n } finally {\n this.restartingService = false;\n }\n }\n }\n\n if (strategy === \"background-service-or-exit\" || strategy === \"exit-process\") {\n if (this.exitScheduled) {\n return {\n status: \"exit-scheduled\",\n message: \"Restart already scheduled; skipping duplicate request.\"\n };\n }\n const delay =\n typeof request.delayMs === \"number\" && Number.isFinite(request.delayMs) ? Math.max(0, Math.floor(request.delayMs)) : 100;\n this.exitScheduled = true;\n this.deps.scheduleProcessExit(delay, reason);\n return {\n status: \"exit-scheduled\",\n message: `Restart scheduled (${reason}).`\n };\n }\n\n return {\n status: \"manual-required\",\n message: request.manualMessage ?? \"Run nextclaw restart in an external terminal to apply changes.\"\n };\n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
11
11
|
uiConfig: Pick<Config["ui"], "port">;
|
|
12
|
-
applyRestartMode:
|
|
12
|
+
applyRestartMode: NpmRuntimeUpdateApplyRestartMode;
|
|
13
13
|
automaticCheckIntervalMs?: number;
|
|
14
14
|
};
|
|
15
|
+
type NpmRuntimeUpdateApplyRestartMode = "managed-service-restart" | "supervised-process-restart" | "manual-process-restart";
|
|
15
16
|
declare class NpmRuntimeUpdateHost implements UiRuntimeUpdateHost {
|
|
16
17
|
private readonly deps;
|
|
17
18
|
private readonly source;
|
|
18
19
|
private readonly layout;
|
|
19
20
|
private readonly launcherVersion;
|
|
21
|
+
private readonly runningVersion;
|
|
20
22
|
private readonly stateStore;
|
|
21
23
|
private readonly bundleService;
|
|
22
24
|
private readonly updateService;
|
|
@@ -46,5 +48,5 @@ declare class NpmRuntimeUpdateHost implements UiRuntimeUpdateHost {
|
|
|
46
48
|
private setSnapshot;
|
|
47
49
|
}
|
|
48
50
|
//#endregion
|
|
49
|
-
export { NpmRuntimeUpdateHost };
|
|
51
|
+
export { NpmRuntimeUpdateApplyRestartMode, NpmRuntimeUpdateHost };
|
|
50
52
|
//# sourceMappingURL=npm-runtime-update-host.service.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"npm-runtime-update-host.service.d.ts","names":[],"sources":["../../../src/services/runtime/npm-runtime-update-host.service.ts"],"mappings":";;;;;;KA2BK,wBAAA;EACH,QAAA,EAAU,QAAA;EACV,MAAA,GAAS,IAAA,CAAK,SAAA;EACd,cAAA,GAAiB,MAAA,EAAQ,oBAAA,KAAyB,OAAA;EAClD,QAAA,EAAU,IAAA,CAAK,MAAA;EACf,gBAAA;
|
|
1
|
+
{"version":3,"file":"npm-runtime-update-host.service.d.ts","names":[],"sources":["../../../src/services/runtime/npm-runtime-update-host.service.ts"],"mappings":";;;;;;KA2BK,wBAAA;EACH,QAAA,EAAU,QAAA;EACV,MAAA,GAAS,IAAA,CAAK,SAAA;EACd,cAAA,GAAiB,MAAA,EAAQ,oBAAA,KAAyB,OAAA;EAClD,QAAA,EAAU,IAAA,CAAK,MAAA;EACf,gBAAA,EAAkB,gCAAA;EAClB,wBAAA;AAAA;AAAA,KAGU,gCAAA;AAAA,cAKC,oBAAA,YAAgC,mBAAA;EAAA,iBAcd,IAAA;EAAA,iBAbZ,MAAA;EAAA,iBACA,MAAA;EAAA,iBACA,eAAA;EAAA,iBACA,cAAA;EAAA,iBACA,UAAA;EAAA,iBACA,aAAA;EAAA,iBACA,aAAA;EAAA,QACT,QAAA;EAAA,QACA,UAAA;EAAA,QACA,mBAAA;EAAA,QACA,OAAA;EAAA,iBACS,MAAA;cAEY,IAAA,EAAM,wBAAA;EA0BnC,QAAA,QAAqB,OAAA,CAAQ,cAAA;EAI7B,eAAA,QAA4B,OAAA,CAAQ,cAAA;EAQpC,cAAA,QAA2B,OAAA,CAAQ,cAAA;EAInC,qBAAA,QAAkC,OAAA,CAAQ,cAAA;EA0C1C,aAAA,GAAuB,OAAA,EAAS,cAAA,gBAA4B,OAAA,CAAQ,cAAA;EAgBpE,KAAA;EAQA,OAAA;EAAA,QAKQ,iBAAA;EAAA,YAUI,wBAAA,CAAA;EAAA,QAIJ,0BAAA;EAAA,QAQA,wBAAA;EAAA,QAOA,UAAA;EAAA,QAuBA,aAAA;EAAA,QAsBA,eAAA;EAAA,QAYA,aAAA;EAAA,QAaA,gBAAA;EAAA,QAaA,eAAA;EAAA,QAgBA,WAAA;AAAA"}
|
|
@@ -19,6 +19,7 @@ var NpmRuntimeUpdateHost = class {
|
|
|
19
19
|
source;
|
|
20
20
|
layout;
|
|
21
21
|
launcherVersion;
|
|
22
|
+
runningVersion;
|
|
22
23
|
stateStore;
|
|
23
24
|
bundleService;
|
|
24
25
|
updateService;
|
|
@@ -33,7 +34,8 @@ var NpmRuntimeUpdateHost = class {
|
|
|
33
34
|
const distribution = NextclawDistributionService.get();
|
|
34
35
|
this.source = new NpmRuntimeUpdateSourceService({ packagedPublicKeyPath: distribution.runtimeUpdatePublicKeyPath });
|
|
35
36
|
this.layout = new NpmRuntimeBundleLayoutStore();
|
|
36
|
-
this.launcherVersion = distribution.version;
|
|
37
|
+
this.launcherVersion = process.env.NEXTCLAW_NPM_LAUNCHER_VERSION?.trim() || distribution.version;
|
|
38
|
+
this.runningVersion = distribution.version;
|
|
37
39
|
this.stateStore = new NpmRuntimeUpdateStateStore(this.layout.getStatePath(), { defaultChannel: this.source.resolveChannel(void 0, this.launcherVersion) });
|
|
38
40
|
this.bundleService = new NpmRuntimeBundleService({
|
|
39
41
|
layout: this.layout,
|
|
@@ -71,14 +73,21 @@ var NpmRuntimeUpdateHost = class {
|
|
|
71
73
|
});
|
|
72
74
|
try {
|
|
73
75
|
const snapshot = this.createManager().applyDownloadedUpdate();
|
|
74
|
-
this.setSnapshot(this.deps.applyRestartMode === "
|
|
76
|
+
this.setSnapshot(this.deps.applyRestartMode === "manual-process-restart" ? {
|
|
75
77
|
...snapshot,
|
|
76
78
|
recoveryCommand: "Restart this NextClaw process to launch the downloaded runtime."
|
|
77
|
-
});
|
|
79
|
+
} : snapshot);
|
|
78
80
|
if (this.deps.applyRestartMode === "managed-service-restart") await requestManagedServiceRestart(this.deps.requestRestart, {
|
|
79
81
|
reason: "runtime update apply",
|
|
80
82
|
uiPort: this.deps.uiConfig.port
|
|
81
83
|
});
|
|
84
|
+
else if (this.deps.applyRestartMode === "supervised-process-restart") await this.deps.requestRestart({
|
|
85
|
+
reason: "runtime update apply",
|
|
86
|
+
manualMessage: "Restart the supervised NextClaw process to apply the runtime update.",
|
|
87
|
+
strategy: "exit-process",
|
|
88
|
+
delayMs: 500,
|
|
89
|
+
silentNotification: true
|
|
90
|
+
});
|
|
82
91
|
return this.snapshot;
|
|
83
92
|
} catch (error) {
|
|
84
93
|
this.setSnapshot(this.toFailedSnapshot("apply", error));
|
|
@@ -192,6 +201,7 @@ var NpmRuntimeUpdateHost = class {
|
|
|
192
201
|
updateService: this.updateService,
|
|
193
202
|
resolveManifestUrl: (resolvedChannel) => this.source.resolveManifestUrl(resolvedChannel),
|
|
194
203
|
launcherVersion: this.launcherVersion,
|
|
204
|
+
runningVersion: this.runningVersion,
|
|
195
205
|
channel
|
|
196
206
|
});
|
|
197
207
|
};
|