@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
|
@@ -88,7 +88,7 @@ var ChannelCommands = class {
|
|
|
88
88
|
await this.deps.requestRestart({
|
|
89
89
|
mode: "notify",
|
|
90
90
|
reason: `channel configured: ${channelId}`,
|
|
91
|
-
manualMessage: "
|
|
91
|
+
manualMessage: "渠道配置已保存,请在外部终端运行 nextclaw restart 后生效。"
|
|
92
92
|
});
|
|
93
93
|
};
|
|
94
94
|
requireChannelId = (opts) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"channel-command.controller.js","names":[],"sources":["../../../src/controllers/commands/channel-command.controller.ts"],"sourcesContent":["import { getWorkspacePath, loadConfig, saveConfig } from \"@nextclaw/core\";\nimport { BUILTIN_CHANNEL_IDS } from \"@nextclaw/runtime\";\nimport { listExtensionChannelIds } from \"@nextclaw/kernel\";\nimport { resolveChannelConfigView } from \"@nextclaw-service/utils/channel-config-view.utils.js\";\nimport { ChannelListViewService } from \"@nextclaw-service/services/channel/channel-list-view.service.js\";\nimport type { ChannelsAddOptions, ChannelsListOptions, ChannelsLoginOptions, RequestRestartParams } from \"@nextclaw-service/types/cli.types.js\";\n\nexport { resolveChannelConfigView } from \"@nextclaw-service/utils/channel-config-view.utils.js\";\n\nconst CHANNEL_LABELS: Record<string, string> = {\n telegram: \"Telegram\",\n whatsapp: \"WhatsApp\",\n discord: \"Discord\",\n feishu: \"Feishu\",\n dingtalk: \"DingTalk\",\n wecom: \"WeCom\",\n email: \"Email\",\n slack: \"Slack\",\n qq: \"QQ\",\n weixin: \"Weixin\"\n};\nexport class ChannelCommands {\n private readonly channelListView = new ChannelListViewService();\n\n constructor(\n private deps: {\n requestRestart: (params: RequestRestartParams) => Promise<void>;\n }\n ) {}\n\n status = (): void => {\n const config = loadConfig();\n const workspaceDir = getWorkspacePath(config.agents.defaults.workspace);\n const channelConfig = resolveChannelConfigView(config);\n\n console.log(\"Channel Status\");\n const channels = channelConfig.channels as Record<string, { enabled?: boolean }>;\n for (const channelId of BUILTIN_CHANNEL_IDS) {\n const label = CHANNEL_LABELS[channelId] ?? channelId;\n const enabled = channels[channelId]?.enabled === true;\n console.log(`${label}: ${enabled ? \"✓\" : \"✗\"}`);\n }\n\n const extensionChannels = listExtensionChannelIds({ config, workspace: workspaceDir });\n if (extensionChannels.length > 0) {\n console.log(\"Extension Channels:\");\n for (const channelId of extensionChannels) {\n console.log(`- ${channelId}`);\n }\n }\n };\n\n list = (opts: ChannelsListOptions = {}): void => {\n const output = this.buildChannelListOutput();\n if (opts.json) {\n console.log(JSON.stringify(output, null, 2));\n return;\n }\n\n console.log(\"Channels\");\n for (const channel of output.channels) {\n const flags = [\n channel.enabled ? \"enabled\" : \"disabled\",\n channel.defaultAccountId ? `defaultAccountId=${channel.defaultAccountId}` : undefined,\n ].filter(Boolean);\n console.log(`- ${channel.id} [${flags.join(\", \")}]`);\n }\n };\n\n login = async (opts: ChannelsLoginOptions = {}): Promise<void> => {\n const channelId = opts.channel?.trim();\n if (!channelId) {\n console.error(\"Channel login is handled by the running UI extension auth flow. Pass --channel <id> and use the UI login flow.\");\n process.exit(1);\n }\n\n console.error(`Channel \"${channelId}\" login is handled by the running UI extension auth flow.`);\n process.exit(1);\n };\n\n private buildChannelListOutput = () => {\n const config = loadConfig();\n const workspaceDir = getWorkspacePath(config.agents.defaults.workspace);\n return this.channelListView.build({\n config,\n workspaceDir,\n });\n };\n\n add = async (opts: ChannelsAddOptions): Promise<void> => {\n const channelId = this.requireChannelId(opts);\n const config = loadConfig();\n const next = {\n ...config,\n channels: {\n ...config.channels,\n [channelId]: {\n ...((config.channels as Record<string, Record<string, unknown>>)[channelId] ?? {}),\n ...this.buildChannelSetupInput(opts),\n enabled: true,\n },\n },\n };\n saveConfig(next);\n\n console.log(`Configured channel \"${channelId}\".`);\n await this.deps.requestRestart({\n mode: \"notify\",\n reason: `channel configured: ${channelId}`,\n manualMessage: \"
|
|
1
|
+
{"version":3,"file":"channel-command.controller.js","names":[],"sources":["../../../src/controllers/commands/channel-command.controller.ts"],"sourcesContent":["import { getWorkspacePath, loadConfig, saveConfig } from \"@nextclaw/core\";\nimport { BUILTIN_CHANNEL_IDS } from \"@nextclaw/runtime\";\nimport { listExtensionChannelIds } from \"@nextclaw/kernel\";\nimport { resolveChannelConfigView } from \"@nextclaw-service/utils/channel-config-view.utils.js\";\nimport { ChannelListViewService } from \"@nextclaw-service/services/channel/channel-list-view.service.js\";\nimport type { ChannelsAddOptions, ChannelsListOptions, ChannelsLoginOptions, RequestRestartParams } from \"@nextclaw-service/types/cli.types.js\";\n\nexport { resolveChannelConfigView } from \"@nextclaw-service/utils/channel-config-view.utils.js\";\n\nconst CHANNEL_LABELS: Record<string, string> = {\n telegram: \"Telegram\",\n whatsapp: \"WhatsApp\",\n discord: \"Discord\",\n feishu: \"Feishu\",\n dingtalk: \"DingTalk\",\n wecom: \"WeCom\",\n email: \"Email\",\n slack: \"Slack\",\n qq: \"QQ\",\n weixin: \"Weixin\"\n};\nexport class ChannelCommands {\n private readonly channelListView = new ChannelListViewService();\n\n constructor(\n private deps: {\n requestRestart: (params: RequestRestartParams) => Promise<void>;\n }\n ) {}\n\n status = (): void => {\n const config = loadConfig();\n const workspaceDir = getWorkspacePath(config.agents.defaults.workspace);\n const channelConfig = resolveChannelConfigView(config);\n\n console.log(\"Channel Status\");\n const channels = channelConfig.channels as Record<string, { enabled?: boolean }>;\n for (const channelId of BUILTIN_CHANNEL_IDS) {\n const label = CHANNEL_LABELS[channelId] ?? channelId;\n const enabled = channels[channelId]?.enabled === true;\n console.log(`${label}: ${enabled ? \"✓\" : \"✗\"}`);\n }\n\n const extensionChannels = listExtensionChannelIds({ config, workspace: workspaceDir });\n if (extensionChannels.length > 0) {\n console.log(\"Extension Channels:\");\n for (const channelId of extensionChannels) {\n console.log(`- ${channelId}`);\n }\n }\n };\n\n list = (opts: ChannelsListOptions = {}): void => {\n const output = this.buildChannelListOutput();\n if (opts.json) {\n console.log(JSON.stringify(output, null, 2));\n return;\n }\n\n console.log(\"Channels\");\n for (const channel of output.channels) {\n const flags = [\n channel.enabled ? \"enabled\" : \"disabled\",\n channel.defaultAccountId ? `defaultAccountId=${channel.defaultAccountId}` : undefined,\n ].filter(Boolean);\n console.log(`- ${channel.id} [${flags.join(\", \")}]`);\n }\n };\n\n login = async (opts: ChannelsLoginOptions = {}): Promise<void> => {\n const channelId = opts.channel?.trim();\n if (!channelId) {\n console.error(\"Channel login is handled by the running UI extension auth flow. Pass --channel <id> and use the UI login flow.\");\n process.exit(1);\n }\n\n console.error(`Channel \"${channelId}\" login is handled by the running UI extension auth flow.`);\n process.exit(1);\n };\n\n private buildChannelListOutput = () => {\n const config = loadConfig();\n const workspaceDir = getWorkspacePath(config.agents.defaults.workspace);\n return this.channelListView.build({\n config,\n workspaceDir,\n });\n };\n\n add = async (opts: ChannelsAddOptions): Promise<void> => {\n const channelId = this.requireChannelId(opts);\n const config = loadConfig();\n const next = {\n ...config,\n channels: {\n ...config.channels,\n [channelId]: {\n ...((config.channels as Record<string, Record<string, unknown>>)[channelId] ?? {}),\n ...this.buildChannelSetupInput(opts),\n enabled: true,\n },\n },\n };\n saveConfig(next);\n\n console.log(`Configured channel \"${channelId}\".`);\n await this.deps.requestRestart({\n mode: \"notify\",\n reason: `channel configured: ${channelId}`,\n manualMessage: \"渠道配置已保存,请在外部终端运行 nextclaw restart 后生效。\"\n });\n };\n\n private requireChannelId = (opts: ChannelsAddOptions): string => {\n const channelId = opts.channel?.trim();\n if (!channelId) {\n console.error(\"--channel is required\");\n process.exit(1);\n }\n return channelId;\n };\n\n private buildChannelSetupInput = (opts: ChannelsAddOptions): Record<string, string | undefined> => {\n return {\n name: opts.name,\n token: opts.token,\n code: opts.code,\n url: opts.url,\n httpUrl: opts.httpUrl\n };\n };\n}\n"],"mappings":";;;;;;AASA,MAAM,iBAAyC;CAC7C,UAAU;CACV,UAAU;CACV,SAAS;CACT,QAAQ;CACR,UAAU;CACV,OAAO;CACP,OAAO;CACP,OAAO;CACP,IAAI;CACJ,QAAQ;CACT;AACD,IAAa,kBAAb,MAA6B;CAC3B,kBAAmC,IAAI,wBAAwB;CAE/D,YACE,MAGA;AAHQ,OAAA,OAAA;;CAKV,eAAqB;EACnB,MAAM,SAAS,YAAY;EAC3B,MAAM,eAAe,iBAAiB,OAAO,OAAO,SAAS,UAAU;EACvE,MAAM,gBAAgB,yBAAyB,OAAO;AAEtD,UAAQ,IAAI,iBAAiB;EAC7B,MAAM,WAAW,cAAc;AAC/B,OAAK,MAAM,aAAa,qBAAqB;GAC3C,MAAM,QAAQ,eAAe,cAAc;GAC3C,MAAM,UAAU,SAAS,YAAY,YAAY;AACjD,WAAQ,IAAI,GAAG,MAAM,IAAI,UAAU,MAAM,MAAM;;EAGjD,MAAM,oBAAoB,wBAAwB;GAAE;GAAQ,WAAW;GAAc,CAAC;AACtF,MAAI,kBAAkB,SAAS,GAAG;AAChC,WAAQ,IAAI,sBAAsB;AAClC,QAAK,MAAM,aAAa,kBACtB,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AAM,YAAY,KAAK,SAAS,MAAM;AACtC,MAAI,CAAC,WAAW;AACd,WAAQ,MAAM,wBAAwB;AACtC,WAAQ,KAAK,EAAE;;AAEjB,SAAO;;CAGT,0BAAkC,SAAiE;AACjG,SAAO;GACL,MAAM,KAAK;GACX,OAAO,KAAK;GACZ,MAAM,KAAK;GACX,KAAK,KAAK;GACV,SAAS,KAAK;GACf"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { resolveSkillsInstallWorkdir } from "../../utils/runtime-helpers.utils.js";
|
|
2
|
-
import { buildMarketplacePublishOptions, buildMarketplaceUpdateOptions } from "../../utils/marketplace/marketplace-command-options.utils.js";
|
|
3
1
|
import { installMarketplaceSkill, updateInstalledMarketplaceSkill } from "../../utils/marketplace/marketplace-skill-lifecycle.utils.js";
|
|
4
2
|
import { publishMarketplaceSkill } from "../../utils/marketplace/marketplace.utils.js";
|
|
3
|
+
import { resolveSkillsInstallWorkdir } from "../../utils/runtime-helpers.utils.js";
|
|
4
|
+
import { buildMarketplacePublishOptions, buildMarketplaceUpdateOptions } from "../../utils/marketplace/marketplace-command-options.utils.js";
|
|
5
5
|
import { SkillsQueryService } from "../../services/marketplace/skills-query.service.js";
|
|
6
6
|
import { loadConfig } from "@nextclaw/core";
|
|
7
7
|
//#region src/controllers/commands/marketplace-skill-command.controller.ts
|
|
@@ -144,7 +144,7 @@ var SecretsCommands = class {
|
|
|
144
144
|
prevConfig,
|
|
145
145
|
nextConfig,
|
|
146
146
|
reason: `secrets.configure ${alias}`,
|
|
147
|
-
manualMessage: "Secrets provider updated.
|
|
147
|
+
manualMessage: "Secrets provider updated. Run nextclaw restart in an external terminal if required."
|
|
148
148
|
});
|
|
149
149
|
if (opts.json) {
|
|
150
150
|
console.log(JSON.stringify({
|
|
@@ -168,7 +168,7 @@ var SecretsCommands = class {
|
|
|
168
168
|
prevConfig,
|
|
169
169
|
nextConfig,
|
|
170
170
|
reason: "secrets.apply",
|
|
171
|
-
manualMessage: "Secrets updated.
|
|
171
|
+
manualMessage: "Secrets updated. Run nextclaw restart in an external terminal if required."
|
|
172
172
|
});
|
|
173
173
|
if (opts.json) {
|
|
174
174
|
console.log(JSON.stringify({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"secrets-command.controller.js","names":[],"sources":["../../../src/controllers/commands/secrets-command.controller.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport {\n buildReloadPlan,\n diffConfigPaths,\n getConfigPath,\n loadConfig,\n resolveConfigSecrets,\n saveConfig,\n type Config,\n type SecretRef,\n type SecretSource\n} from \"@nextclaw/core\";\nimport { getAtConfigPath, parseRequiredConfigPath } from \"@nextclaw-service/utils/config-path.utils.js\";\nimport type { RequestRestartParams, SecretsApplyOptions, SecretsAuditOptions, SecretsConfigureOptions, SecretsReloadOptions } from \"@nextclaw-service/types/cli.types.js\";\n\ntype AuditItem = {\n path: string;\n source: SecretSource;\n provider: string;\n id: string;\n ok: boolean;\n detail: string;\n};\n\nconst SECRET_SOURCES: SecretSource[] = [\"env\", \"file\", \"exec\"];\n\nfunction normalizeSecretSource(value: unknown): SecretSource | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const normalized = value.trim().toLowerCase();\n return SECRET_SOURCES.includes(normalized as SecretSource) ? (normalized as SecretSource) : null;\n}\n\nfunction normalizeOptionalString(value: unknown): string | undefined {\n if (typeof value !== \"string\") {\n return undefined;\n }\n const trimmed = value.trim();\n return trimmed || undefined;\n}\n\nfunction parseTimeoutMs(value: unknown): number | undefined {\n if (value === undefined || value === null || value === \"\") {\n return undefined;\n }\n const parsed = Number(value);\n if (!Number.isFinite(parsed) || parsed <= 0) {\n throw new Error(`invalid timeout: ${String(value)}`);\n }\n return Math.trunc(parsed);\n}\n\nfunction inferProviderAlias(config: Config, ref: SecretRef): string {\n const explicit = normalizeOptionalString(ref.provider);\n if (explicit) {\n return explicit;\n }\n const defaultAlias = normalizeOptionalString(config.secrets.defaults[ref.source]);\n if (defaultAlias) {\n return defaultAlias;\n }\n return ref.source;\n}\n\nfunction summarizeAudit(items: AuditItem[]): { total: number; ok: number; failed: number } {\n const ok = items.filter((item) => item.ok).length;\n return {\n total: items.length,\n ok,\n failed: items.length - ok\n };\n}\n\nfunction parseRefsPatch(raw: unknown): Record<string, SecretRef> {\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) {\n throw new Error(\"refs patch must be an object\");\n }\n\n const output: Record<string, SecretRef> = {};\n for (const [path, value] of Object.entries(raw as Record<string, unknown>)) {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(`invalid ref for ${path}`);\n }\n const source = normalizeSecretSource((value as Record<string, unknown>).source);\n const id = normalizeOptionalString((value as Record<string, unknown>).id);\n const provider = normalizeOptionalString((value as Record<string, unknown>).provider);\n if (!source || !id) {\n throw new Error(`invalid ref for ${path}: source/id is required`);\n }\n output[path] = { source, ...(provider ? { provider } : {}), id };\n }\n return output;\n}\n\nfunction parseApplyFile(raw: string): {\n enabled?: boolean;\n defaults?: Config[\"secrets\"][\"defaults\"];\n providers?: Config[\"secrets\"][\"providers\"];\n refs?: Record<string, SecretRef>;\n} {\n const data = JSON.parse(raw) as unknown;\n if (!data || typeof data !== \"object\" || Array.isArray(data)) {\n throw new Error(\"apply file must be an object\");\n }\n const record = data as Record<string, unknown>;\n\n if (record.refs || record.providers || record.defaults || Object.prototype.hasOwnProperty.call(record, \"enabled\")) {\n const patch: {\n enabled?: boolean;\n defaults?: Config[\"secrets\"][\"defaults\"];\n providers?: Config[\"secrets\"][\"providers\"];\n refs?: Record<string, SecretRef>;\n } = {};\n\n if (Object.prototype.hasOwnProperty.call(record, \"enabled\")) {\n patch.enabled = Boolean(record.enabled);\n }\n if (record.defaults && typeof record.defaults === \"object\" && !Array.isArray(record.defaults)) {\n patch.defaults = record.defaults as Config[\"secrets\"][\"defaults\"];\n }\n if (record.providers && typeof record.providers === \"object\" && !Array.isArray(record.providers)) {\n patch.providers = record.providers as Config[\"secrets\"][\"providers\"];\n }\n if (record.refs) {\n patch.refs = parseRefsPatch(record.refs);\n }\n return patch;\n }\n\n return { refs: parseRefsPatch(record) };\n}\n\nexport class SecretsCommands {\n constructor(\n private deps: {\n requestRestart: (params: RequestRestartParams) => Promise<void>;\n }\n ) {}\n\n audit = (opts: SecretsAuditOptions = {}): void => {\n const config = loadConfig();\n const configPath = getConfigPath();\n const refs = config.secrets.refs;\n const items: AuditItem[] = [];\n\n for (const [path, ref] of Object.entries(refs)) {\n const provider = inferProviderAlias(config, ref);\n const scopedConfig = structuredClone(config);\n scopedConfig.secrets.refs = { [path]: ref };\n\n try {\n const resolved = resolveConfigSecrets(scopedConfig, { configPath });\n const parsedPath = parseRequiredConfigPath(path);\n const target = getAtConfigPath(resolved as unknown as Record<string, unknown>, parsedPath);\n if (!target.found) {\n items.push({\n path,\n source: ref.source,\n provider,\n id: ref.id,\n ok: false,\n detail: \"resolved but path not found\"\n });\n continue;\n }\n const resolvedValue = target.value;\n const detail =\n typeof resolvedValue === \"string\"\n ? `resolved (length=${resolvedValue.length})`\n : `resolved (${typeof resolvedValue})`;\n items.push({\n path,\n source: ref.source,\n provider,\n id: ref.id,\n ok: true,\n detail\n });\n } catch (error) {\n items.push({\n path,\n source: ref.source,\n provider,\n id: ref.id,\n ok: false,\n detail: String(error)\n });\n }\n }\n\n const summary = summarizeAudit(items);\n if (opts.json) {\n console.log(JSON.stringify({ summary, items }, null, 2));\n } else if (!items.length) {\n console.log(\"No secret refs configured.\");\n } else {\n for (const item of items) {\n const status = item.ok ? \"OK\" : \"ERROR\";\n console.log(\n `[${status}] ${item.path} <- ${item.source}:${item.provider}:${item.id} (${item.detail})`\n );\n }\n console.log(`Summary: total=${summary.total}, ok=${summary.ok}, failed=${summary.failed}`);\n }\n\n const strict = Boolean(opts.strict);\n if (strict && summary.failed > 0) {\n process.exitCode = 1;\n }\n };\n\n configure = async (opts: SecretsConfigureOptions): Promise<void> => {\n const alias = normalizeOptionalString(opts.provider);\n if (!alias) {\n throw new Error(\"provider alias is required\");\n }\n\n const prevConfig = loadConfig();\n const nextConfig = structuredClone(prevConfig);\n const remove = Boolean(opts.remove);\n\n if (remove) {\n this.removeProvider(nextConfig, alias);\n } else {\n this.configureProvider(nextConfig, alias, opts);\n }\n\n resolveConfigSecrets(nextConfig, { configPath: getConfigPath() });\n saveConfig(nextConfig);\n await this.requestRestartForConfigDiff({\n prevConfig,\n nextConfig,\n reason: `secrets.configure ${alias}`,\n manualMessage: \"Secrets provider updated. Restart the gateway if required.\"\n });\n\n if (opts.json) {\n console.log(JSON.stringify({ ok: true, providers: nextConfig.secrets.providers, defaults: nextConfig.secrets.defaults }, null, 2));\n return;\n }\n console.log(`Secrets provider ${remove ? \"removed\" : \"configured\"}: ${alias}`);\n };\n\n apply = async (opts: SecretsApplyOptions): Promise<void> => {\n const prevConfig = loadConfig();\n const nextConfig = structuredClone(prevConfig);\n\n this.applyEnabledPatch(nextConfig, opts);\n this.applyFilePatch(nextConfig, opts);\n this.applySingleRefPatch(nextConfig, opts);\n\n resolveConfigSecrets(nextConfig, { configPath: getConfigPath() });\n saveConfig(nextConfig);\n await this.requestRestartForConfigDiff({\n prevConfig,\n nextConfig,\n reason: \"secrets.apply\",\n manualMessage: \"Secrets updated. Restart the gateway if required.\"\n });\n\n if (opts.json) {\n console.log(JSON.stringify({ ok: true, secrets: nextConfig.secrets }, null, 2));\n return;\n }\n console.log(\"Secrets applied.\");\n };\n\n reload = async (opts: SecretsReloadOptions = {}): Promise<void> => {\n const config = loadConfig();\n const configPath = getConfigPath();\n resolveConfigSecrets(config, { configPath });\n saveConfig(config);\n\n if (opts.json) {\n console.log(JSON.stringify({ ok: true, message: \"secrets reload signal emitted\" }, null, 2));\n return;\n }\n console.log(\"Secrets reload signal emitted.\");\n };\n\n private removeProvider = (config: Config, alias: string): void => {\n delete config.secrets.providers[alias];\n for (const source of SECRET_SOURCES) {\n if (config.secrets.defaults[source] === alias) {\n delete config.secrets.defaults[source];\n }\n }\n };\n\n private configureProvider = (config: Config, alias: string, opts: SecretsConfigureOptions): void => {\n const source = normalizeSecretSource(opts.source);\n if (!source) {\n throw new Error(\"source is required and must be one of env/file/exec\");\n }\n config.secrets.providers[alias] = this.buildProviderConfig(source, opts);\n if (opts.setDefault) {\n config.secrets.defaults[source] = alias;\n }\n };\n\n private buildProviderConfig = (source: SecretSource, opts: SecretsConfigureOptions): Config[\"secrets\"][\"providers\"][string] => {\n if (source === \"env\") {\n return {\n source,\n ...(normalizeOptionalString(opts.prefix) ? { prefix: normalizeOptionalString(opts.prefix) } : {})\n };\n }\n if (source === \"file\") {\n const path = normalizeOptionalString(opts.path);\n if (!path) {\n throw new Error(\"file source requires --path\");\n }\n return { source, path, format: \"json\" };\n }\n const command = normalizeOptionalString(opts.command);\n if (!command) {\n throw new Error(\"exec source requires --command\");\n }\n return {\n source,\n command,\n args: Array.isArray(opts.arg) ? opts.arg : [],\n ...(normalizeOptionalString(opts.cwd) ? { cwd: normalizeOptionalString(opts.cwd) } : {}),\n timeoutMs: parseTimeoutMs(opts.timeoutMs) ?? 5000\n };\n };\n\n private applyEnabledPatch = (config: Config, opts: SecretsApplyOptions): void => {\n const { disable, enable } = opts;\n if (enable && disable) {\n throw new Error(\"cannot set --enable and --disable at the same time\");\n }\n if (enable || disable) {\n config.secrets.enabled = Boolean(enable);\n }\n };\n\n private applyFilePatch = (config: Config, opts: SecretsApplyOptions): void => {\n if (!opts.file) {\n return;\n }\n const { defaults, providers, refs } = parseApplyFile(readFileSync(opts.file, \"utf-8\"));\n if (defaults) config.secrets.defaults = defaults;\n if (providers) config.secrets.providers = providers;\n if (refs) config.secrets.refs = { ...config.secrets.refs, ...refs };\n };\n\n private applySingleRefPatch = (config: Config, opts: SecretsApplyOptions): void => {\n if (!opts.path) {\n if (opts.remove && !opts.file) {\n throw new Error(\"--remove requires --path\");\n }\n return;\n }\n const path = opts.path.trim();\n if (!path) {\n throw new Error(\"path is empty\");\n }\n if (opts.remove) {\n delete config.secrets.refs[path];\n return;\n }\n const source = normalizeSecretSource(opts.source);\n const id = normalizeOptionalString(opts.id);\n if (!source || !id) {\n throw new Error(\"apply single ref requires --source and --id\");\n }\n const provider = normalizeOptionalString(opts.provider);\n config.secrets.refs[path] = {\n source,\n id,\n ...(provider ? { provider } : {})\n };\n };\n\n private requestRestartForConfigDiff = async (params: {\n prevConfig: Config;\n nextConfig: Config;\n reason: string;\n manualMessage: string;\n }): Promise<void> => {\n const { manualMessage, nextConfig, prevConfig, reason } = 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 });\n };\n}\n"],"mappings":";;;;AAwBA,MAAM,iBAAiC;CAAC;CAAO;CAAQ;CAAO;AAE9D,SAAS,sBAAsB,OAAqC;AAClE,KAAI,OAAO,UAAU,SACnB,QAAO;CAET,MAAM,aAAa,MAAM,MAAM,CAAC,aAAa;AAC7C,QAAO,eAAe,SAAS,WAA2B,GAAI,aAA8B;;AAG9F,SAAS,wBAAwB,OAAoC;AACnE,KAAI,OAAO,UAAU,SACnB;AAGF,QADgB,MAAM,MAAM,IACV,KAAA;;AAGpB,SAAS,eAAe,OAAoC;AAC1D,KAAI,UAAU,KAAA,KAAa,UAAU,QAAQ,UAAU,GACrD;CAEF,MAAM,SAAS,OAAO,MAAM;AAC5B,KAAI,CAAC,OAAO,SAAS,OAAO,IAAI,UAAU,EACxC,OAAM,IAAI,MAAM,oBAAoB,OAAO,MAAM,GAAG;AAEtD,QAAO,KAAK,MAAM,OAAO;;AAG3B,SAAS,mBAAmB,QAAgB,KAAwB;CAClE,MAAM,WAAW,wBAAwB,IAAI,SAAS;AACtD,KAAI,SACF,QAAO;CAET,MAAM,eAAe,wBAAwB,OAAO,QAAQ,SAAS,IAAI,QAAQ;AACj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,SAAS,sBAAsB,KAAK,OAAO;EACjD,MAAM,KAAK,wBAAwB,KAAK,GAAG;AAC3C,MAAI,CAAC,UAAU,CAAC,GACd,OAAM,IAAI,MAAM,8CAA8C;EAEhE,MAAM,WAAW,wBAAwB,KAAK,SAAS;AACvD,SAAO,QAAQ,KAAK,QAAQ;GAC1B;GACA;GACA,GAAI,WAAW,EAAE,UAAU,GAAG,EAAE;GACjC;;CAGH,8BAAsC,OAAO,WAKxB;EACnB,MAAM,EAAE,eAAe,YAAY,YAAY,WAAW;EAC1D,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;GACD,CAAC"}
|
|
1
|
+
{"version":3,"file":"secrets-command.controller.js","names":[],"sources":["../../../src/controllers/commands/secrets-command.controller.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport {\n buildReloadPlan,\n diffConfigPaths,\n getConfigPath,\n loadConfig,\n resolveConfigSecrets,\n saveConfig,\n type Config,\n type SecretRef,\n type SecretSource\n} from \"@nextclaw/core\";\nimport { getAtConfigPath, parseRequiredConfigPath } from \"@nextclaw-service/utils/config-path.utils.js\";\nimport type { RequestRestartParams, SecretsApplyOptions, SecretsAuditOptions, SecretsConfigureOptions, SecretsReloadOptions } from \"@nextclaw-service/types/cli.types.js\";\n\ntype AuditItem = {\n path: string;\n source: SecretSource;\n provider: string;\n id: string;\n ok: boolean;\n detail: string;\n};\n\nconst SECRET_SOURCES: SecretSource[] = [\"env\", \"file\", \"exec\"];\n\nfunction normalizeSecretSource(value: unknown): SecretSource | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const normalized = value.trim().toLowerCase();\n return SECRET_SOURCES.includes(normalized as SecretSource) ? (normalized as SecretSource) : null;\n}\n\nfunction normalizeOptionalString(value: unknown): string | undefined {\n if (typeof value !== \"string\") {\n return undefined;\n }\n const trimmed = value.trim();\n return trimmed || undefined;\n}\n\nfunction parseTimeoutMs(value: unknown): number | undefined {\n if (value === undefined || value === null || value === \"\") {\n return undefined;\n }\n const parsed = Number(value);\n if (!Number.isFinite(parsed) || parsed <= 0) {\n throw new Error(`invalid timeout: ${String(value)}`);\n }\n return Math.trunc(parsed);\n}\n\nfunction inferProviderAlias(config: Config, ref: SecretRef): string {\n const explicit = normalizeOptionalString(ref.provider);\n if (explicit) {\n return explicit;\n }\n const defaultAlias = normalizeOptionalString(config.secrets.defaults[ref.source]);\n if (defaultAlias) {\n return defaultAlias;\n }\n return ref.source;\n}\n\nfunction summarizeAudit(items: AuditItem[]): { total: number; ok: number; failed: number } {\n const ok = items.filter((item) => item.ok).length;\n return {\n total: items.length,\n ok,\n failed: items.length - ok\n };\n}\n\nfunction parseRefsPatch(raw: unknown): Record<string, SecretRef> {\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) {\n throw new Error(\"refs patch must be an object\");\n }\n\n const output: Record<string, SecretRef> = {};\n for (const [path, value] of Object.entries(raw as Record<string, unknown>)) {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(`invalid ref for ${path}`);\n }\n const source = normalizeSecretSource((value as Record<string, unknown>).source);\n const id = normalizeOptionalString((value as Record<string, unknown>).id);\n const provider = normalizeOptionalString((value as Record<string, unknown>).provider);\n if (!source || !id) {\n throw new Error(`invalid ref for ${path}: source/id is required`);\n }\n output[path] = { source, ...(provider ? { provider } : {}), id };\n }\n return output;\n}\n\nfunction parseApplyFile(raw: string): {\n enabled?: boolean;\n defaults?: Config[\"secrets\"][\"defaults\"];\n providers?: Config[\"secrets\"][\"providers\"];\n refs?: Record<string, SecretRef>;\n} {\n const data = JSON.parse(raw) as unknown;\n if (!data || typeof data !== \"object\" || Array.isArray(data)) {\n throw new Error(\"apply file must be an object\");\n }\n const record = data as Record<string, unknown>;\n\n if (record.refs || record.providers || record.defaults || Object.prototype.hasOwnProperty.call(record, \"enabled\")) {\n const patch: {\n enabled?: boolean;\n defaults?: Config[\"secrets\"][\"defaults\"];\n providers?: Config[\"secrets\"][\"providers\"];\n refs?: Record<string, SecretRef>;\n } = {};\n\n if (Object.prototype.hasOwnProperty.call(record, \"enabled\")) {\n patch.enabled = Boolean(record.enabled);\n }\n if (record.defaults && typeof record.defaults === \"object\" && !Array.isArray(record.defaults)) {\n patch.defaults = record.defaults as Config[\"secrets\"][\"defaults\"];\n }\n if (record.providers && typeof record.providers === \"object\" && !Array.isArray(record.providers)) {\n patch.providers = record.providers as Config[\"secrets\"][\"providers\"];\n }\n if (record.refs) {\n patch.refs = parseRefsPatch(record.refs);\n }\n return patch;\n }\n\n return { refs: parseRefsPatch(record) };\n}\n\nexport class SecretsCommands {\n constructor(\n private deps: {\n requestRestart: (params: RequestRestartParams) => Promise<void>;\n }\n ) {}\n\n audit = (opts: SecretsAuditOptions = {}): void => {\n const config = loadConfig();\n const configPath = getConfigPath();\n const refs = config.secrets.refs;\n const items: AuditItem[] = [];\n\n for (const [path, ref] of Object.entries(refs)) {\n const provider = inferProviderAlias(config, ref);\n const scopedConfig = structuredClone(config);\n scopedConfig.secrets.refs = { [path]: ref };\n\n try {\n const resolved = resolveConfigSecrets(scopedConfig, { configPath });\n const parsedPath = parseRequiredConfigPath(path);\n const target = getAtConfigPath(resolved as unknown as Record<string, unknown>, parsedPath);\n if (!target.found) {\n items.push({\n path,\n source: ref.source,\n provider,\n id: ref.id,\n ok: false,\n detail: \"resolved but path not found\"\n });\n continue;\n }\n const resolvedValue = target.value;\n const detail =\n typeof resolvedValue === \"string\"\n ? `resolved (length=${resolvedValue.length})`\n : `resolved (${typeof resolvedValue})`;\n items.push({\n path,\n source: ref.source,\n provider,\n id: ref.id,\n ok: true,\n detail\n });\n } catch (error) {\n items.push({\n path,\n source: ref.source,\n provider,\n id: ref.id,\n ok: false,\n detail: String(error)\n });\n }\n }\n\n const summary = summarizeAudit(items);\n if (opts.json) {\n console.log(JSON.stringify({ summary, items }, null, 2));\n } else if (!items.length) {\n console.log(\"No secret refs configured.\");\n } else {\n for (const item of items) {\n const status = item.ok ? \"OK\" : \"ERROR\";\n console.log(\n `[${status}] ${item.path} <- ${item.source}:${item.provider}:${item.id} (${item.detail})`\n );\n }\n console.log(`Summary: total=${summary.total}, ok=${summary.ok}, failed=${summary.failed}`);\n }\n\n const strict = Boolean(opts.strict);\n if (strict && summary.failed > 0) {\n process.exitCode = 1;\n }\n };\n\n configure = async (opts: SecretsConfigureOptions): Promise<void> => {\n const alias = normalizeOptionalString(opts.provider);\n if (!alias) {\n throw new Error(\"provider alias is required\");\n }\n\n const prevConfig = loadConfig();\n const nextConfig = structuredClone(prevConfig);\n const remove = Boolean(opts.remove);\n\n if (remove) {\n this.removeProvider(nextConfig, alias);\n } else {\n this.configureProvider(nextConfig, alias, opts);\n }\n\n resolveConfigSecrets(nextConfig, { configPath: getConfigPath() });\n saveConfig(nextConfig);\n await this.requestRestartForConfigDiff({\n prevConfig,\n nextConfig,\n reason: `secrets.configure ${alias}`,\n manualMessage: \"Secrets provider updated. Run nextclaw restart in an external terminal if required.\"\n });\n\n if (opts.json) {\n console.log(JSON.stringify({ ok: true, providers: nextConfig.secrets.providers, defaults: nextConfig.secrets.defaults }, null, 2));\n return;\n }\n console.log(`Secrets provider ${remove ? \"removed\" : \"configured\"}: ${alias}`);\n };\n\n apply = async (opts: SecretsApplyOptions): Promise<void> => {\n const prevConfig = loadConfig();\n const nextConfig = structuredClone(prevConfig);\n\n this.applyEnabledPatch(nextConfig, opts);\n this.applyFilePatch(nextConfig, opts);\n this.applySingleRefPatch(nextConfig, opts);\n\n resolveConfigSecrets(nextConfig, { configPath: getConfigPath() });\n saveConfig(nextConfig);\n await this.requestRestartForConfigDiff({\n prevConfig,\n nextConfig,\n reason: \"secrets.apply\",\n manualMessage: \"Secrets updated. Run nextclaw restart in an external terminal if required.\"\n });\n\n if (opts.json) {\n console.log(JSON.stringify({ ok: true, secrets: nextConfig.secrets }, null, 2));\n return;\n }\n console.log(\"Secrets applied.\");\n };\n\n reload = async (opts: SecretsReloadOptions = {}): Promise<void> => {\n const config = loadConfig();\n const configPath = getConfigPath();\n resolveConfigSecrets(config, { configPath });\n saveConfig(config);\n\n if (opts.json) {\n console.log(JSON.stringify({ ok: true, message: \"secrets reload signal emitted\" }, null, 2));\n return;\n }\n console.log(\"Secrets reload signal emitted.\");\n };\n\n private removeProvider = (config: Config, alias: string): void => {\n delete config.secrets.providers[alias];\n for (const source of SECRET_SOURCES) {\n if (config.secrets.defaults[source] === alias) {\n delete config.secrets.defaults[source];\n }\n }\n };\n\n private configureProvider = (config: Config, alias: string, opts: SecretsConfigureOptions): void => {\n const source = normalizeSecretSource(opts.source);\n if (!source) {\n throw new Error(\"source is required and must be one of env/file/exec\");\n }\n config.secrets.providers[alias] = this.buildProviderConfig(source, opts);\n if (opts.setDefault) {\n config.secrets.defaults[source] = alias;\n }\n };\n\n private buildProviderConfig = (source: SecretSource, opts: SecretsConfigureOptions): Config[\"secrets\"][\"providers\"][string] => {\n if (source === \"env\") {\n return {\n source,\n ...(normalizeOptionalString(opts.prefix) ? { prefix: normalizeOptionalString(opts.prefix) } : {})\n };\n }\n if (source === \"file\") {\n const path = normalizeOptionalString(opts.path);\n if (!path) {\n throw new Error(\"file source requires --path\");\n }\n return { source, path, format: \"json\" };\n }\n const command = normalizeOptionalString(opts.command);\n if (!command) {\n throw new Error(\"exec source requires --command\");\n }\n return {\n source,\n command,\n args: Array.isArray(opts.arg) ? opts.arg : [],\n ...(normalizeOptionalString(opts.cwd) ? { cwd: normalizeOptionalString(opts.cwd) } : {}),\n timeoutMs: parseTimeoutMs(opts.timeoutMs) ?? 5000\n };\n };\n\n private applyEnabledPatch = (config: Config, opts: SecretsApplyOptions): void => {\n const { disable, enable } = opts;\n if (enable && disable) {\n throw new Error(\"cannot set --enable and --disable at the same time\");\n }\n if (enable || disable) {\n config.secrets.enabled = Boolean(enable);\n }\n };\n\n private applyFilePatch = (config: Config, opts: SecretsApplyOptions): void => {\n if (!opts.file) {\n return;\n }\n const { defaults, providers, refs } = parseApplyFile(readFileSync(opts.file, \"utf-8\"));\n if (defaults) config.secrets.defaults = defaults;\n if (providers) config.secrets.providers = providers;\n if (refs) config.secrets.refs = { ...config.secrets.refs, ...refs };\n };\n\n private applySingleRefPatch = (config: Config, opts: SecretsApplyOptions): void => {\n if (!opts.path) {\n if (opts.remove && !opts.file) {\n throw new Error(\"--remove requires --path\");\n }\n return;\n }\n const path = opts.path.trim();\n if (!path) {\n throw new Error(\"path is empty\");\n }\n if (opts.remove) {\n delete config.secrets.refs[path];\n return;\n }\n const source = normalizeSecretSource(opts.source);\n const id = normalizeOptionalString(opts.id);\n if (!source || !id) {\n throw new Error(\"apply single ref requires --source and --id\");\n }\n const provider = normalizeOptionalString(opts.provider);\n config.secrets.refs[path] = {\n source,\n id,\n ...(provider ? { provider } : {})\n };\n };\n\n private requestRestartForConfigDiff = async (params: {\n prevConfig: Config;\n nextConfig: Config;\n reason: string;\n manualMessage: string;\n }): Promise<void> => {\n const { manualMessage, nextConfig, prevConfig, reason } = 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 });\n };\n}\n"],"mappings":";;;;AAwBA,MAAM,iBAAiC;CAAC;CAAO;CAAQ;CAAO;AAE9D,SAAS,sBAAsB,OAAqC;AAClE,KAAI,OAAO,UAAU,SACnB,QAAO;CAET,MAAM,aAAa,MAAM,MAAM,CAAC,aAAa;AAC7C,QAAO,eAAe,SAAS,WAA2B,GAAI,aAA8B;;AAG9F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ager } from "@nextclaw/kernel";
|
|
3
3
|
|
|
4
4
|
//#region src/controllers/gateway.controller.d.ts
|
|
5
5
|
type ControllerDeps = {
|
|
6
6
|
configManager: ConfigManager;
|
|
7
|
-
channels: ChannelManager;
|
|
8
|
-
cron: CronService;
|
|
9
7
|
sessionManager?: SessionManager;
|
|
10
8
|
requestRestart?: (options?: {
|
|
11
9
|
delayMs?: number;
|
|
@@ -17,30 +15,19 @@ declare class GatewayControllerImpl implements GatewayController {
|
|
|
17
15
|
constructor(deps: ControllerDeps);
|
|
18
16
|
private normalizeOptionalString;
|
|
19
17
|
private resolveDeliveryContext;
|
|
20
|
-
private
|
|
18
|
+
private writeUpdateRestartSentinelPayload;
|
|
21
19
|
private requestRestart;
|
|
22
|
-
status: () => Record<string, unknown>;
|
|
23
|
-
reloadConfig: (reason?: string) => Promise<string>;
|
|
24
|
-
restart: (options?: {
|
|
25
|
-
delayMs?: number;
|
|
26
|
-
reason?: string;
|
|
27
|
-
sessionKey?: string;
|
|
28
|
-
}) => Promise<string>;
|
|
29
20
|
getConfig: () => Promise<Record<string, unknown>>;
|
|
30
21
|
getConfigSchema: () => Promise<Record<string, unknown>>;
|
|
31
22
|
applyConfig: (params: {
|
|
32
23
|
raw: string;
|
|
33
24
|
baseHash?: string;
|
|
34
25
|
note?: string;
|
|
35
|
-
restartDelayMs?: number;
|
|
36
|
-
sessionKey?: string;
|
|
37
26
|
}) => Promise<Record<string, unknown>>;
|
|
38
27
|
patchConfig: (params: {
|
|
39
28
|
raw: string;
|
|
40
29
|
baseHash?: string;
|
|
41
30
|
note?: string;
|
|
42
|
-
restartDelayMs?: number;
|
|
43
|
-
sessionKey?: string;
|
|
44
31
|
}) => Promise<Record<string, unknown>>;
|
|
45
32
|
updateRun: (params: {
|
|
46
33
|
note?: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gateway.controller.d.ts","names":[],"sources":["../../src/controllers/gateway.controller.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"gateway.controller.d.ts","names":[],"sources":["../../src/controllers/gateway.controller.ts"],"mappings":";;;;KAYK,cAAA;EACH,aAAA,EAAe,aAAA;EACf,cAAA,GAAiB,cAAA;EACjB,cAAA,IAAkB,OAAA;IAAY,OAAA;IAAkB,MAAA;EAAA,MAAsB,OAAA;AAAA;AAAA,cAG3D,qBAAA,YAAiC,iBAAA;EAAA,QACxB,IAAA;cAAA,IAAA,EAAM,cAAA;EAAA,QAElB,uBAAA;EAAA,QAQA,sBAAA;EAAA,QAgDA,iCAAA;EAAA,QA4BA,cAAA;EAcR,SAAA,QAAsB,OAAA,CAAQ,MAAA;EAI9B,eAAA,QAA4B,OAAA,CAAQ,MAAA;EAIpC,WAAA,GAAqB,MAAA;IACnB,GAAA;IACA,QAAA;IACA,IAAA;EAAA,MACE,OAAA,CAAQ,MAAA;EASZ,WAAA,GAAqB,MAAA;IACnB,GAAA;IACA,QAAA;IACA,IAAA;EAAA,MACE,OAAA,CAAQ,MAAA;EASZ,SAAA,GAAmB,MAAA;IACjB,IAAA;IACA,cAAA;IACA,SAAA;IACA,UAAA;EAAA,MACE,OAAA,CAAQ,MAAA;AAAA"}
|
|
@@ -35,13 +35,13 @@ var GatewayControllerImpl = class {
|
|
|
35
35
|
...Object.keys(cachedMetadata).length > 0 ? { metadata: cachedMetadata } : {}
|
|
36
36
|
};
|
|
37
37
|
};
|
|
38
|
-
|
|
39
|
-
const {
|
|
38
|
+
writeUpdateRestartSentinelPayload = async (params) => {
|
|
39
|
+
const { note, reason, sessionKey: rawSessionKey, status, strategy } = params;
|
|
40
40
|
const sessionKey = this.normalizeOptionalString(rawSessionKey);
|
|
41
41
|
const deliveryContext = await this.resolveDeliveryContext(sessionKey);
|
|
42
42
|
try {
|
|
43
43
|
return await writeRestartSentinel({
|
|
44
|
-
kind,
|
|
44
|
+
kind: "update.run",
|
|
45
45
|
status,
|
|
46
46
|
ts: Date.now(),
|
|
47
47
|
sessionKey,
|
|
@@ -68,26 +68,6 @@ var GatewayControllerImpl = class {
|
|
|
68
68
|
process.exit(0);
|
|
69
69
|
}, delay);
|
|
70
70
|
};
|
|
71
|
-
status = () => {
|
|
72
|
-
return {
|
|
73
|
-
channels: this.deps.channels.enabledChannels,
|
|
74
|
-
cron: this.deps.cron.status(),
|
|
75
|
-
configPath: this.deps.configManager.configPath
|
|
76
|
-
};
|
|
77
|
-
};
|
|
78
|
-
reloadConfig = async (reason) => {
|
|
79
|
-
return this.deps.configManager.reloadConfig(reason);
|
|
80
|
-
};
|
|
81
|
-
restart = async (options) => {
|
|
82
|
-
await this.writeRestartSentinelPayload({
|
|
83
|
-
kind: "restart",
|
|
84
|
-
status: "ok",
|
|
85
|
-
sessionKey: options?.sessionKey,
|
|
86
|
-
reason: options?.reason ?? "gateway.restart"
|
|
87
|
-
});
|
|
88
|
-
await this.requestRestart(options);
|
|
89
|
-
return "Restart scheduled";
|
|
90
|
-
};
|
|
91
71
|
getConfig = async () => {
|
|
92
72
|
return this.deps.configManager.getConfigSnapshot({ version: getPackageVersion$1() });
|
|
93
73
|
};
|
|
@@ -126,8 +106,7 @@ var GatewayControllerImpl = class {
|
|
|
126
106
|
};
|
|
127
107
|
const versionAfter = getPackageVersion$1();
|
|
128
108
|
const delayMs = restartDelayMs ?? 0;
|
|
129
|
-
const sentinelPath = await this.
|
|
130
|
-
kind: "update.run",
|
|
109
|
+
const sentinelPath = await this.writeUpdateRestartSentinelPayload({
|
|
131
110
|
status: "ok",
|
|
132
111
|
sessionKey,
|
|
133
112
|
note,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gateway.controller.js","names":["getPackageVersion"],"sources":["../../src/controllers/gateway.controller.ts"],"sourcesContent":["import {\n type GatewayController,\n type CronService,\n} from \"@nextclaw/core\";\nimport type { ChannelManager, ConfigManager, SessionManager } from \"@nextclaw/kernel\";\nimport { getPackageVersion } from \"../utils/cli.utils.js\";\nimport { NpmRuntimeUpdateCommandService } from \"@nextclaw-service/services/runtime/npm-runtime-update-command.service.js\";\nimport {\n parseSessionKey,\n type RestartSentinelDeliveryContext,\n writeRestartSentinel\n} from \"@nextclaw-service/utils/restart-sentinel.utils.js\";\n\ntype ControllerDeps = {\n configManager: ConfigManager;\n channels: ChannelManager;\n cron: CronService;\n sessionManager?: SessionManager;\n requestRestart?: (options?: { delayMs?: number; reason?: string }) => Promise<void> | void;\n};\n\nexport class GatewayControllerImpl implements GatewayController {\n constructor(private deps: ControllerDeps) {}\n\n private normalizeOptionalString = (value: unknown): string | undefined => {\n if (typeof value !== \"string\") {\n return undefined;\n }\n const trimmed = value.trim();\n return trimmed || undefined;\n };\n\n private resolveDeliveryContext = async (sessionKey?: string): Promise<RestartSentinelDeliveryContext | undefined> => {\n const normalizedSessionKey = this.normalizeOptionalString(sessionKey);\n const keyTarget = parseSessionKey(normalizedSessionKey);\n const keyRoute = keyTarget && keyTarget.channel !== \"agent\" ? keyTarget : null;\n const session = normalizedSessionKey\n ? await this.deps.sessionManager?.getSessionRecord(normalizedSessionKey)\n : null;\n const metadata = session?.metadata ?? {};\n const rawContext = metadata.last_delivery_context;\n const cachedContext =\n rawContext && typeof rawContext === \"object\" && !Array.isArray(rawContext)\n ? (rawContext as Record<string, unknown>)\n : null;\n const cachedMetadataRaw = cachedContext?.metadata;\n const cachedMetadata =\n cachedMetadataRaw && typeof cachedMetadataRaw === \"object\" && !Array.isArray(cachedMetadataRaw)\n ? ({ ...(cachedMetadataRaw as Record<string, unknown>) } as Record<string, unknown>)\n : {};\n\n const channel = this.normalizeOptionalString(cachedContext?.channel) ?? keyRoute?.channel;\n const chatId =\n this.normalizeOptionalString(cachedContext?.chatId) ??\n this.normalizeOptionalString(metadata.last_to) ??\n keyRoute?.chatId;\n const replyTo =\n this.normalizeOptionalString(cachedContext?.replyTo) ??\n this.normalizeOptionalString(metadata.last_message_id);\n const accountId =\n this.normalizeOptionalString(cachedContext?.accountId) ??\n this.normalizeOptionalString(metadata.last_account_id);\n\n if (!channel || !chatId) {\n return undefined;\n }\n\n if (accountId && !this.normalizeOptionalString(cachedMetadata.accountId)) {\n cachedMetadata.accountId = accountId;\n }\n\n return {\n channel,\n chatId,\n ...(replyTo ? { replyTo } : {}),\n ...(accountId ? { accountId } : {}),\n ...(Object.keys(cachedMetadata).length > 0 ? { metadata: cachedMetadata } : {})\n };\n };\n\n private writeRestartSentinelPayload = async (params: {\n kind: \"config.apply\" | \"config.patch\" | \"update.run\" | \"restart\";\n status: \"ok\" | \"error\" | \"skipped\";\n sessionKey?: string;\n note?: string;\n reason?: string;\n strategy?: string;\n }): Promise<string | null> => {\n const { kind, note, reason, sessionKey: rawSessionKey, status, strategy } = params;\n const sessionKey = this.normalizeOptionalString(rawSessionKey);\n const deliveryContext = await this.resolveDeliveryContext(sessionKey);\n try {\n return await writeRestartSentinel({\n kind,\n status,\n ts: Date.now(),\n sessionKey,\n deliveryContext,\n message: note ?? null,\n stats: {\n reason: reason ?? null,\n strategy: strategy ?? null\n }\n });\n } catch {\n return null;\n }\n };\n\n private requestRestart = async (options?: { delayMs?: number; reason?: string }): Promise<void> => {\n const { delayMs, reason } = options ?? {};\n if (this.deps.requestRestart) {\n await this.deps.requestRestart(options);\n return;\n }\n const delay =\n typeof delayMs === \"number\" && Number.isFinite(delayMs) ? Math.max(0, delayMs) : 100;\n console.log(`Gateway restart requested via tool${reason ? ` (${reason})` : \"\"}.`);\n setTimeout(() => {\n process.exit(0);\n }, delay);\n };\n\n status = (): Record<string, unknown> => {\n return {\n channels: this.deps.channels.enabledChannels,\n cron: this.deps.cron.status(),\n configPath: this.deps.configManager.configPath\n };\n };\n\n reloadConfig = async (reason?: string): Promise<string> => {\n return this.deps.configManager.reloadConfig(reason);\n };\n\n restart = async (options?: { delayMs?: number; reason?: string; sessionKey?: string }): Promise<string> => {\n await this.writeRestartSentinelPayload({\n kind: \"restart\",\n status: \"ok\",\n sessionKey: options?.sessionKey,\n reason: options?.reason ?? \"gateway.restart\"\n });\n await this.requestRestart(options);\n return \"Restart scheduled\";\n };\n\n getConfig = async (): Promise<Record<string, unknown>> => {\n return this.deps.configManager.getConfigSnapshot({ version: getPackageVersion() });\n };\n\n getConfigSchema = async (): Promise<Record<string, unknown>> => {\n return this.deps.configManager.getConfigSchema({ version: getPackageVersion() });\n };\n\n applyConfig = async (params: {\n raw: string;\n baseHash?: string;\n note?: string;\n restartDelayMs?: number;\n sessionKey?: string;\n }): Promise<Record<string, unknown>> => {\n return this.deps.configManager.applyRawConfig({\n raw: params.raw,\n baseHash: params.baseHash,\n note: params.note,\n version: getPackageVersion()\n });\n };\n\n patchConfig = async (params: {\n raw: string;\n baseHash?: string;\n note?: string;\n restartDelayMs?: number;\n sessionKey?: string;\n }): Promise<Record<string, unknown>> => {\n return this.deps.configManager.patchRawConfig({\n raw: params.raw,\n baseHash: params.baseHash,\n note: params.note,\n version: getPackageVersion()\n });\n };\n\n updateRun = async (params: {\n note?: string;\n restartDelayMs?: number;\n timeoutMs?: number;\n sessionKey?: string;\n }): Promise<Record<string, unknown>> => {\n const { note, restartDelayMs, sessionKey, timeoutMs } = params;\n const versionBefore = getPackageVersion();\n void timeoutMs;\n const snapshot = await new NpmRuntimeUpdateCommandService().runManaged({});\n if (snapshot.status === \"blocked\" || snapshot.status === \"failed\") {\n return {\n ok: false,\n error: snapshot.errorMessage ?? snapshot.blockReason ?? \"update failed\",\n snapshot,\n version: {\n before: versionBefore,\n after: getPackageVersion(),\n changed: false\n }\n };\n }\n\n const versionAfter = getPackageVersion();\n const delayMs = restartDelayMs ?? 0;\n const sentinelPath = await this.writeRestartSentinelPayload({\n kind: \"update.run\",\n status: \"ok\",\n sessionKey,\n note,\n reason: \"update.run\",\n strategy: \"runtime-bundle\"\n });\n await this.requestRestart({ delayMs, reason: \"update.run\" });\n return {\n ok: true,\n note: note ?? null,\n restart: { scheduled: true, delayMs },\n strategy: \"runtime-bundle\",\n snapshot,\n version: {\n before: versionBefore,\n after: versionAfter,\n changed: versionBefore !== versionAfter\n },\n sentinel: sentinelPath ? { path: sentinel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controllers/gateway.controller.ts"],"sourcesContent":["import {\n type GatewayController,\n} from \"@nextclaw/core\";\nimport type { ConfigManager, SessionManager } from \"@nextclaw/kernel\";\nimport { getPackageVersion } from \"../utils/cli.utils.js\";\nimport { NpmRuntimeUpdateCommandService } from \"@nextclaw-service/services/runtime/npm-runtime-update-command.service.js\";\nimport {\n parseSessionKey,\n type RestartSentinelDeliveryContext,\n writeRestartSentinel\n} from \"@nextclaw-service/utils/restart-sentinel.utils.js\";\n\ntype ControllerDeps = {\n configManager: ConfigManager;\n sessionManager?: SessionManager;\n requestRestart?: (options?: { delayMs?: number; reason?: string }) => Promise<void> | void;\n};\n\nexport class GatewayControllerImpl implements GatewayController {\n constructor(private deps: ControllerDeps) {}\n\n private normalizeOptionalString = (value: unknown): string | undefined => {\n if (typeof value !== \"string\") {\n return undefined;\n }\n const trimmed = value.trim();\n return trimmed || undefined;\n };\n\n private resolveDeliveryContext = async (sessionKey?: string): Promise<RestartSentinelDeliveryContext | undefined> => {\n const normalizedSessionKey = this.normalizeOptionalString(sessionKey);\n const keyTarget = parseSessionKey(normalizedSessionKey);\n const keyRoute = keyTarget && keyTarget.channel !== \"agent\" ? keyTarget : null;\n const session = normalizedSessionKey\n ? await this.deps.sessionManager?.getSessionRecord(normalizedSessionKey)\n : null;\n const metadata = session?.metadata ?? {};\n const rawContext = metadata.last_delivery_context;\n const cachedContext =\n rawContext && typeof rawContext === \"object\" && !Array.isArray(rawContext)\n ? (rawContext as Record<string, unknown>)\n : null;\n const cachedMetadataRaw = cachedContext?.metadata;\n const cachedMetadata =\n cachedMetadataRaw && typeof cachedMetadataRaw === \"object\" && !Array.isArray(cachedMetadataRaw)\n ? ({ ...(cachedMetadataRaw as Record<string, unknown>) } as Record<string, unknown>)\n : {};\n\n const channel = this.normalizeOptionalString(cachedContext?.channel) ?? keyRoute?.channel;\n const chatId =\n this.normalizeOptionalString(cachedContext?.chatId) ??\n this.normalizeOptionalString(metadata.last_to) ??\n keyRoute?.chatId;\n const replyTo =\n this.normalizeOptionalString(cachedContext?.replyTo) ??\n this.normalizeOptionalString(metadata.last_message_id);\n const accountId =\n this.normalizeOptionalString(cachedContext?.accountId) ??\n this.normalizeOptionalString(metadata.last_account_id);\n\n if (!channel || !chatId) {\n return undefined;\n }\n\n if (accountId && !this.normalizeOptionalString(cachedMetadata.accountId)) {\n cachedMetadata.accountId = accountId;\n }\n\n return {\n channel,\n chatId,\n ...(replyTo ? { replyTo } : {}),\n ...(accountId ? { accountId } : {}),\n ...(Object.keys(cachedMetadata).length > 0 ? { metadata: cachedMetadata } : {})\n };\n };\n\n private writeUpdateRestartSentinelPayload = async (params: {\n status: \"ok\" | \"error\" | \"skipped\";\n sessionKey?: string;\n note?: string;\n reason?: string;\n strategy?: string;\n }): Promise<string | null> => {\n const { note, reason, sessionKey: rawSessionKey, status, strategy } = params;\n const sessionKey = this.normalizeOptionalString(rawSessionKey);\n const deliveryContext = await this.resolveDeliveryContext(sessionKey);\n try {\n return await writeRestartSentinel({\n kind: \"update.run\",\n status,\n ts: Date.now(),\n sessionKey,\n deliveryContext,\n message: note ?? null,\n stats: {\n reason: reason ?? null,\n strategy: strategy ?? null\n }\n });\n } catch {\n return null;\n }\n };\n\n private requestRestart = async (options?: { delayMs?: number; reason?: string }): Promise<void> => {\n const { delayMs, reason } = options ?? {};\n if (this.deps.requestRestart) {\n await this.deps.requestRestart(options);\n return;\n }\n const delay =\n typeof delayMs === \"number\" && Number.isFinite(delayMs) ? Math.max(0, delayMs) : 100;\n console.log(`Gateway restart requested via tool${reason ? ` (${reason})` : \"\"}.`);\n setTimeout(() => {\n process.exit(0);\n }, delay);\n };\n\n getConfig = async (): Promise<Record<string, unknown>> => {\n return this.deps.configManager.getConfigSnapshot({ version: getPackageVersion() });\n };\n\n getConfigSchema = async (): Promise<Record<string, unknown>> => {\n return this.deps.configManager.getConfigSchema({ version: getPackageVersion() });\n };\n\n applyConfig = async (params: {\n raw: string;\n baseHash?: string;\n note?: string;\n }): Promise<Record<string, unknown>> => {\n return this.deps.configManager.applyRawConfig({\n raw: params.raw,\n baseHash: params.baseHash,\n note: params.note,\n version: getPackageVersion()\n });\n };\n\n patchConfig = async (params: {\n raw: string;\n baseHash?: string;\n note?: string;\n }): Promise<Record<string, unknown>> => {\n return this.deps.configManager.patchRawConfig({\n raw: params.raw,\n baseHash: params.baseHash,\n note: params.note,\n version: getPackageVersion()\n });\n };\n\n updateRun = async (params: {\n note?: string;\n restartDelayMs?: number;\n timeoutMs?: number;\n sessionKey?: string;\n }): Promise<Record<string, unknown>> => {\n const { note, restartDelayMs, sessionKey, timeoutMs } = params;\n const versionBefore = getPackageVersion();\n void timeoutMs;\n const snapshot = await new NpmRuntimeUpdateCommandService().runManaged({});\n if (snapshot.status === \"blocked\" || snapshot.status === \"failed\") {\n return {\n ok: false,\n error: snapshot.errorMessage ?? snapshot.blockReason ?? \"update failed\",\n snapshot,\n version: {\n before: versionBefore,\n after: getPackageVersion(),\n changed: false\n }\n };\n }\n\n const versionAfter = getPackageVersion();\n const delayMs = restartDelayMs ?? 0;\n const sentinelPath = await this.writeUpdateRestartSentinelPayload({\n status: \"ok\",\n sessionKey,\n note,\n reason: \"update.run\",\n strategy: \"runtime-bundle\"\n });\n await this.requestRestart({ delayMs, reason: \"update.run\" });\n return {\n ok: true,\n note: note ?? null,\n restart: { scheduled: true, delayMs },\n strategy: \"runtime-bundle\",\n snapshot,\n version: {\n before: versionBefore,\n after: versionAfter,\n changed: versionBefore !== versionAfter\n },\n sentinel: sentinelPath ? { path: sentinelPath } : null\n };\n };\n}\n"],"mappings":";;;;;;AAkBA,IAAa,wBAAb,MAAgE;CAC9D,YAAY,MAA8B;AAAtB,OAAA,OAAA;;CAEpB,2BAAmC,UAAuC;AACxE,MAAI,OAAO,UAAU,SACnB;AAGF,SADgB,MAAM,MAAM,IACV,KAAA;;CAGpB,yBAAiC,OAAO,eAA6E;EACnH,MAAM,uBAAuB,KAAK,wBAAwB,WAAW;EACrE,MAAM,YAAY,gBAAgB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B,SAAS,eAAe;GACxD;GACA,SAAS;IACP,QAAQ;IACR,OAAOA,qBAAmB;IAC1B,SAAS;IACV;GACF;EAGH,MAAM,eAAeA,qBAAmB;EACxC,MAAM,UAAU,kBAAkB;EAClC,MAAM,eAAe,MAAM,KAAK,kCAAkC;GAChE,QAAQ;GACR;GACA;GACA,QAAQ;GACR,UAAU;GACX,CAAC;AACF,QAAM,KAAK,eAAe;GAAE;GAAS,QAAQ;GAAc,CAAC;AAC5D,SAAO;GACL,IAAI;GACJ,MAAM,QAAQ;GACd,SAAS;IAAE,WAAW;IAAM;IAAS;GACrC,UAAU;GACV;GACA,SAAS;IACP,QAAQ;IACR,OAAO;IACP,SAAS,kBAAkB;IAC5B;GACD,UAAU,eAAe,EAAE,MAAM,cAAc,GAAG;GACnD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"npm-runtime-launcher.service.d.ts","names":[],"sources":["../../src/launcher/npm-runtime-launcher.service.ts"],"mappings":";;;KAUK,yBAAA;EACH,IAAA;EACA,GAAA,GAAM,MAAA,CAAO,UAAA;EACb,MAAA,GAAS,2BAAA;EACT,eAAA;EACA,qBAAA;AAAA;AAAA,cAGW,kBAAA;EAAA,iBAIkB,OAAA;EAAA,iBAHZ,GAAA;EAAA,iBACA,MAAA;cAEY,OAAA,EAAS,yBAAA;EAKtC,GAAA;EAAA,
|
|
1
|
+
{"version":3,"file":"npm-runtime-launcher.service.d.ts","names":[],"sources":["../../src/launcher/npm-runtime-launcher.service.ts"],"mappings":";;;KAUK,yBAAA;EACH,IAAA;EACA,GAAA,GAAM,MAAA,CAAO,UAAA;EACb,MAAA,GAAS,2BAAA;EACT,eAAA;EACA,qBAAA;AAAA;AAAA,cAGW,kBAAA;EAAA,iBAIkB,OAAA;EAAA,iBAHZ,GAAA;EAAA,iBACA,MAAA;cAEY,OAAA,EAAS,yBAAA;EAKtC,GAAA;EAAA,QAiBQ,wBAAA;EAAA,QAgCA,sBAAA;EAAA,QAEA,4BAAA;AAAA"}
|
|
@@ -19,11 +19,15 @@ var NpmRuntimeLauncher = class {
|
|
|
19
19
|
}
|
|
20
20
|
run = () => {
|
|
21
21
|
const runtimeScriptPath = this.resolveRuntimeScriptPath();
|
|
22
|
+
const launcherVersion = this.resolveLauncherVersion();
|
|
23
|
+
const launcherEntrypoint = this.options.argv[1]?.trim();
|
|
22
24
|
const result = spawnSync(process.execPath, [runtimeScriptPath, ...this.options.argv.slice(2)], {
|
|
23
25
|
stdio: "inherit",
|
|
24
26
|
env: {
|
|
25
27
|
...createExternalCommandEnv(this.env),
|
|
26
|
-
NEXTCLAW_RUNTIME_BUNDLE_CHILD: "1"
|
|
28
|
+
NEXTCLAW_RUNTIME_BUNDLE_CHILD: "1",
|
|
29
|
+
NEXTCLAW_NPM_LAUNCHER_VERSION: launcherVersion,
|
|
30
|
+
...launcherEntrypoint ? { NEXTCLAW_NPM_LAUNCHER_ENTRYPOINT: launcherEntrypoint } : {}
|
|
27
31
|
},
|
|
28
32
|
windowsHide: true
|
|
29
33
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"npm-runtime-launcher.service.js","names":["getPackageVersion"],"sources":["../../src/launcher/npm-runtime-launcher.service.ts"],"sourcesContent":["import { spawnSync } from \"node:child_process\";\nimport { fileURLToPath } from \"node:url\";\nimport { dirname, resolve } from \"node:path\";\nimport { createExternalCommandEnv } from \"@nextclaw/core\";\nimport { NpmRuntimeBundleLayoutStore } from \"@nextclaw-service/stores/npm-runtime-bundle-layout.store.js\";\nimport { NpmRuntimeBundleService, shouldPreferPackagedNpmRuntime } from \"@nextclaw-service/services/runtime/npm-runtime-bundle.service.js\";\nimport { inferDefaultNpmRuntimeReleaseChannel } from \"@nextclaw-service/services/runtime/npm-runtime-update-source.service.js\";\nimport { NpmRuntimeUpdateStateStore } from \"@nextclaw-service/stores/npm-runtime-update-state.store.js\";\nimport { getPackageVersion } from \"@nextclaw-service/utils/cli.utils.js\";\n\ntype NpmRuntimeLauncherOptions = {\n argv: string[];\n env?: NodeJS.ProcessEnv;\n layout?: NpmRuntimeBundleLayoutStore;\n launcherVersion?: string;\n packagedAppEntrypoint?: string;\n};\n\nexport class NpmRuntimeLauncher {\n private readonly env: NodeJS.ProcessEnv;\n private readonly layout: NpmRuntimeBundleLayoutStore;\n\n constructor(private readonly options: NpmRuntimeLauncherOptions) {\n this.env = options.env ?? process.env;\n this.layout = options.layout ?? new NpmRuntimeBundleLayoutStore();\n }\n\n run = (): never => {\n const runtimeScriptPath = this.resolveRuntimeScriptPath();\n const result = spawnSync(process.execPath, [runtimeScriptPath, ...this.options.argv.slice(2)], {\n stdio: \"inherit\",\n env: {\n ...createExternalCommandEnv(this.env),\n NEXTCLAW_RUNTIME_BUNDLE_CHILD: \"1\"\n },\n windowsHide: true\n });\n process.exit(typeof result.status === \"number\" ? result.status : 1);\n };\n\n private resolveRuntimeScriptPath = (): string => {\n const launcherVersion = this.resolveLauncherVersion();\n if (this.env.NEXTCLAW_DISABLE_RUNTIME_BUNDLE_LAUNCHER === \"1\" || this.env.NEXTCLAW_RUNTIME_BUNDLE_CHILD === \"1\") {\n return this.resolvePackagedAppEntrypoint();\n }\n const stateStore = new NpmRuntimeUpdateStateStore(this.layout.getStatePath(), {\n defaultChannel: inferDefaultNpmRuntimeReleaseChannel(launcherVersion)\n });\n const bundleService = new NpmRuntimeBundleService({\n layout: this.layout,\n stateStore,\n launcherVersion\n });\n try {\n const currentBundle = bundleService.resolveCurrentBundle();\n if (\n currentBundle &&\n shouldPreferPackagedNpmRuntime({\n launcherVersion,\n currentBundleVersion: currentBundle.manifest.runtimeVersion ?? currentBundle.manifest.bundleVersion\n })\n ) {\n return this.resolvePackagedAppEntrypoint();\n }\n return currentBundle?.runtimeScriptPath ?? this.resolvePackagedAppEntrypoint();\n } catch (error) {\n console.error(`Cannot start current runtime bundle: ${error instanceof Error ? error.message : String(error)}`);\n console.error(\"Falling back to the packaged npm launcher runtime.\");\n return this.resolvePackagedAppEntrypoint();\n }\n };\n\n private resolveLauncherVersion = (): string => this.options.launcherVersion ?? getPackageVersion();\n\n private resolvePackagedAppEntrypoint = (): string => {\n if (this.options.packagedAppEntrypoint) {\n return this.options.packagedAppEntrypoint;\n }\n return resolve(dirname(fileURLToPath(import.meta.url)), \"../app/index.js\");\n };\n}\n"],"mappings":";;;;;;;;;;;AAkBA,IAAa,qBAAb,MAAgC;CAC9B;CACA;CAEA,YAAY,SAAqD;AAApC,OAAA,UAAA;AAC3B,OAAK,MAAM,QAAQ,OAAO,QAAQ;AAClC,OAAK,SAAS,QAAQ,UAAU,IAAI,6BAA6B;;CAGnE,YAAmB;EACjB,MAAM,oBAAoB,KAAK,0BAA0B;EACzD,MAAM,SAAS,UAAU,QAAQ,UAAU,CAAC,mBAAmB,GAAG,KAAK,QAAQ,KAAK,MAAM,EAAE,CAAC,EAAE;GAC7F,OAAO;GACP,KAAK;IACH,GAAG,yBAAyB,KAAK,IAAI;IACrC,+BAA+B;
|
|
1
|
+
{"version":3,"file":"npm-runtime-launcher.service.js","names":["getPackageVersion"],"sources":["../../src/launcher/npm-runtime-launcher.service.ts"],"sourcesContent":["import { spawnSync } from \"node:child_process\";\nimport { fileURLToPath } from \"node:url\";\nimport { dirname, resolve } from \"node:path\";\nimport { createExternalCommandEnv } from \"@nextclaw/core\";\nimport { NpmRuntimeBundleLayoutStore } from \"@nextclaw-service/stores/npm-runtime-bundle-layout.store.js\";\nimport { NpmRuntimeBundleService, shouldPreferPackagedNpmRuntime } from \"@nextclaw-service/services/runtime/npm-runtime-bundle.service.js\";\nimport { inferDefaultNpmRuntimeReleaseChannel } from \"@nextclaw-service/services/runtime/npm-runtime-update-source.service.js\";\nimport { NpmRuntimeUpdateStateStore } from \"@nextclaw-service/stores/npm-runtime-update-state.store.js\";\nimport { getPackageVersion } from \"@nextclaw-service/utils/cli.utils.js\";\n\ntype NpmRuntimeLauncherOptions = {\n argv: string[];\n env?: NodeJS.ProcessEnv;\n layout?: NpmRuntimeBundleLayoutStore;\n launcherVersion?: string;\n packagedAppEntrypoint?: string;\n};\n\nexport class NpmRuntimeLauncher {\n private readonly env: NodeJS.ProcessEnv;\n private readonly layout: NpmRuntimeBundleLayoutStore;\n\n constructor(private readonly options: NpmRuntimeLauncherOptions) {\n this.env = options.env ?? process.env;\n this.layout = options.layout ?? new NpmRuntimeBundleLayoutStore();\n }\n\n run = (): never => {\n const runtimeScriptPath = this.resolveRuntimeScriptPath();\n const launcherVersion = this.resolveLauncherVersion();\n const launcherEntrypoint = this.options.argv[1]?.trim();\n const result = spawnSync(process.execPath, [runtimeScriptPath, ...this.options.argv.slice(2)], {\n stdio: \"inherit\",\n env: {\n ...createExternalCommandEnv(this.env),\n NEXTCLAW_RUNTIME_BUNDLE_CHILD: \"1\",\n NEXTCLAW_NPM_LAUNCHER_VERSION: launcherVersion,\n ...(launcherEntrypoint ? { NEXTCLAW_NPM_LAUNCHER_ENTRYPOINT: launcherEntrypoint } : {})\n },\n windowsHide: true\n });\n process.exit(typeof result.status === \"number\" ? result.status : 1);\n };\n\n private resolveRuntimeScriptPath = (): string => {\n const launcherVersion = this.resolveLauncherVersion();\n if (this.env.NEXTCLAW_DISABLE_RUNTIME_BUNDLE_LAUNCHER === \"1\" || this.env.NEXTCLAW_RUNTIME_BUNDLE_CHILD === \"1\") {\n return this.resolvePackagedAppEntrypoint();\n }\n const stateStore = new NpmRuntimeUpdateStateStore(this.layout.getStatePath(), {\n defaultChannel: inferDefaultNpmRuntimeReleaseChannel(launcherVersion)\n });\n const bundleService = new NpmRuntimeBundleService({\n layout: this.layout,\n stateStore,\n launcherVersion\n });\n try {\n const currentBundle = bundleService.resolveCurrentBundle();\n if (\n currentBundle &&\n shouldPreferPackagedNpmRuntime({\n launcherVersion,\n currentBundleVersion: currentBundle.manifest.runtimeVersion ?? currentBundle.manifest.bundleVersion\n })\n ) {\n return this.resolvePackagedAppEntrypoint();\n }\n return currentBundle?.runtimeScriptPath ?? this.resolvePackagedAppEntrypoint();\n } catch (error) {\n console.error(`Cannot start current runtime bundle: ${error instanceof Error ? error.message : String(error)}`);\n console.error(\"Falling back to the packaged npm launcher runtime.\");\n return this.resolvePackagedAppEntrypoint();\n }\n };\n\n private resolveLauncherVersion = (): string => this.options.launcherVersion ?? getPackageVersion();\n\n private resolvePackagedAppEntrypoint = (): string => {\n if (this.options.packagedAppEntrypoint) {\n return this.options.packagedAppEntrypoint;\n }\n return resolve(dirname(fileURLToPath(import.meta.url)), \"../app/index.js\");\n };\n}\n"],"mappings":";;;;;;;;;;;AAkBA,IAAa,qBAAb,MAAgC;CAC9B;CACA;CAEA,YAAY,SAAqD;AAApC,OAAA,UAAA;AAC3B,OAAK,MAAM,QAAQ,OAAO,QAAQ;AAClC,OAAK,SAAS,QAAQ,UAAU,IAAI,6BAA6B;;CAGnE,YAAmB;EACjB,MAAM,oBAAoB,KAAK,0BAA0B;EACzD,MAAM,kBAAkB,KAAK,wBAAwB;EACrD,MAAM,qBAAqB,KAAK,QAAQ,KAAK,IAAI,MAAM;EACvD,MAAM,SAAS,UAAU,QAAQ,UAAU,CAAC,mBAAmB,GAAG,KAAK,QAAQ,KAAK,MAAM,EAAE,CAAC,EAAE;GAC7F,OAAO;GACP,KAAK;IACH,GAAG,yBAAyB,KAAK,IAAI;IACrC,+BAA+B;IAC/B,+BAA+B;IAC/B,GAAI,qBAAqB,EAAE,kCAAkC,oBAAoB,GAAG,EAAE;IACvF;GACD,aAAa;GACd,CAAC;AACF,UAAQ,KAAK,OAAO,OAAO,WAAW,WAAW,OAAO,SAAS,EAAE;;CAGrE,iCAAiD;EAC/C,MAAM,kBAAkB,KAAK,wBAAwB;AACrD,MAAI,KAAK,IAAI,6CAA6C,OAAO,KAAK,IAAI,kCAAkC,IAC1G,QAAO,KAAK,8BAA8B;EAE5C,MAAM,aAAa,IAAI,2BAA2B,KAAK,OAAO,cAAc,EAAE,EAC5E,gBAAgB,qCAAqC,gBAAgB,EACtE,CAAC;EACF,MAAM,gBAAgB,IAAI,wBAAwB;GAChD,QAAQ,KAAK;GACb;GACA;GACD,CAAC;AACF,MAAI;GACF,MAAM,gBAAgB,cAAc,sBAAsB;AAC1D,OACE,iBACA,+BAA+B;IAC7B;IACA,sBAAsB,cAAc,SAAS,kBAAkB,cAAc,SAAS;IACvF,CAAC,CAEF,QAAO,KAAK,8BAA8B;AAE5C,UAAO,eAAe,qBAAqB,KAAK,8BAA8B;WACvE,OAAO;AACd,WAAQ,MAAM,wCAAwC,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,GAAG;AAC/G,WAAQ,MAAM,qDAAqD;AACnE,UAAO,KAAK,8BAA8B;;;CAI9C,+BAA+C,KAAK,QAAQ,mBAAmBA,qBAAmB;CAElG,qCAAqD;AACnD,MAAI,KAAK,QAAQ,sBACf,QAAO,KAAK,QAAQ;AAEtB,SAAO,QAAQ,QAAQ,cAAc,OAAO,KAAK,IAAI,CAAC,EAAE,kBAAkB"}
|
|
@@ -13,6 +13,7 @@ type RuntimeUpdateManagerOptions = {
|
|
|
13
13
|
updateService: NpmRuntimeUpdateService;
|
|
14
14
|
resolveManifestUrl: (channel: NpmRuntimeReleaseChannel) => string | null;
|
|
15
15
|
launcherVersion?: string;
|
|
16
|
+
runningVersion?: string;
|
|
16
17
|
channel: NpmRuntimeReleaseChannel;
|
|
17
18
|
now?: () => Date;
|
|
18
19
|
};
|
|
@@ -25,6 +26,7 @@ type NpmRuntimeUpdateActionOptions = {
|
|
|
25
26
|
declare class RuntimeUpdateManager {
|
|
26
27
|
private readonly options;
|
|
27
28
|
private readonly launcherVersion;
|
|
29
|
+
private readonly runningVersion;
|
|
28
30
|
private readonly now;
|
|
29
31
|
private availableManifest;
|
|
30
32
|
constructor(options: RuntimeUpdateManagerOptions);
|
|
@@ -37,6 +39,7 @@ declare class RuntimeUpdateManager {
|
|
|
37
39
|
private toSnapshotAfterCheck;
|
|
38
40
|
private syncStateFromCurrentPointer;
|
|
39
41
|
private toSnapshotFromState;
|
|
42
|
+
private requiresRunningVersionRestart;
|
|
40
43
|
}
|
|
41
44
|
//#endregion
|
|
42
45
|
export { RuntimeUpdateManager };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime-update.manager.d.ts","names":[],"sources":["../../src/managers/runtime-update.manager.ts"],"mappings":";;;;;;;;KAUK,2BAAA;EACH,MAAA,EAAQ,2BAAA;EACR,UAAA,EAAY,0BAAA;EACZ,aAAA,EAAe,uBAAA;EACf,aAAA,EAAe,uBAAA;EACf,kBAAA,GAAqB,OAAA,EAAS,wBAAA;EAC9B,eAAA;EACA,OAAA,EAAS,wBAAA;EACT,GAAA,SAAY,IAAA;AAAA;AAAA,KAGT,6BAAA;EACH,KAAA;EACA,kBAAA;EACA,SAAA;EACA,UAAA,IAAc,QAAA,EAAU,cAAA;AAAA;AAAA,cAGb,oBAAA;EAAA,
|
|
1
|
+
{"version":3,"file":"runtime-update.manager.d.ts","names":[],"sources":["../../src/managers/runtime-update.manager.ts"],"mappings":";;;;;;;;KAUK,2BAAA;EACH,MAAA,EAAQ,2BAAA;EACR,UAAA,EAAY,0BAAA;EACZ,aAAA,EAAe,uBAAA;EACf,aAAA,EAAe,uBAAA;EACf,kBAAA,GAAqB,OAAA,EAAS,wBAAA;EAC9B,eAAA;EACA,cAAA;EACA,OAAA,EAAS,wBAAA;EACT,GAAA,SAAY,IAAA;AAAA;AAAA,KAGT,6BAAA;EACH,KAAA;EACA,kBAAA;EACA,SAAA;EACA,UAAA,IAAc,QAAA,EAAU,cAAA;AAAA;AAAA,cAGb,oBAAA;EAAA,iBAMkB,OAAA;EAAA,iBALZ,eAAA;EAAA,iBACA,cAAA;EAAA,iBACA,GAAA;EAAA,QACT,iBAAA;cAEqB,OAAA,EAAS,2BAAA;EAQtC,WAAA,QAAkB,cAAA;EAYlB,GAAA,GAAa,OAAA,GAAS,6BAAA,KAAqC,OAAA,CAAQ,cAAA;EAuBnE,cAAA,QAA2B,OAAA,CAAQ,cAAA;EA+BnC,cAAA,GAAwB,UAAA,IAAc,QAAA,EAAU,cAAA,cAA0B,OAAA,CAAQ,cAAA;EAoBlF,qBAAA,QAA4B,cAAA;EAAA,QAiBpB,uBAAA;EAAA,QAWA,oBAAA;EAAA,QAiEA,2BAAA;EAAA,QAeA,mBAAA;EAAA,QA6BA,6BAAA;AAAA"}
|
|
@@ -4,16 +4,24 @@ import { resolveEffectiveNpmRuntimeVersion } from "../services/runtime/npm-runti
|
|
|
4
4
|
//#region src/managers/runtime-update.manager.ts
|
|
5
5
|
var RuntimeUpdateManager = class {
|
|
6
6
|
launcherVersion;
|
|
7
|
+
runningVersion;
|
|
7
8
|
now;
|
|
8
9
|
availableManifest = null;
|
|
9
10
|
constructor(options) {
|
|
10
11
|
this.options = options;
|
|
11
12
|
this.launcherVersion = options.launcherVersion ?? getPackageVersion();
|
|
13
|
+
this.runningVersion = options.runningVersion ?? getPackageVersion();
|
|
12
14
|
this.now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
13
15
|
this.options.layout.ensureLauncherDirs();
|
|
14
16
|
this.syncStateFromCurrentPointer();
|
|
15
17
|
}
|
|
16
|
-
getSnapshot = () =>
|
|
18
|
+
getSnapshot = () => {
|
|
19
|
+
const state = this.options.stateStore.read();
|
|
20
|
+
return this.toSnapshotFromState(state, {
|
|
21
|
+
status: state.downloadedVersion ? "downloaded" : this.requiresRunningVersionRestart(state) ? "restart-required" : "idle",
|
|
22
|
+
requiresRestart: this.requiresRunningVersionRestart(state)
|
|
23
|
+
});
|
|
24
|
+
};
|
|
17
25
|
run = async (options = {}) => {
|
|
18
26
|
if (options.apply) return this.applyDownloadedUpdate();
|
|
19
27
|
const applyAfterDownload = options.applyAfterDownload ?? true;
|
|
@@ -102,6 +110,17 @@ var RuntimeUpdateManager = class {
|
|
|
102
110
|
requiresRestart: false
|
|
103
111
|
});
|
|
104
112
|
}
|
|
113
|
+
if (this.requiresRunningVersionRestart(state)) {
|
|
114
|
+
this.availableManifest = availableUpdate?.kind === "runtime-bundle-update" ? availableUpdate.manifest : null;
|
|
115
|
+
return this.toSnapshotFromState(state, {
|
|
116
|
+
status: "restart-required",
|
|
117
|
+
availableVersion: availableUpdate?.manifest.latestVersion ?? null,
|
|
118
|
+
minimumHostVersion: availableUpdate?.manifest.minimumLauncherVersion ?? null,
|
|
119
|
+
releaseNotesUrl: availableUpdate?.manifest.releaseNotesUrl ?? null,
|
|
120
|
+
canApplyInApp: false,
|
|
121
|
+
requiresRestart: true
|
|
122
|
+
});
|
|
123
|
+
}
|
|
105
124
|
if (!availableUpdate) {
|
|
106
125
|
this.availableManifest = null;
|
|
107
126
|
return this.toSnapshotFromState(state, {
|
|
@@ -160,7 +179,7 @@ var RuntimeUpdateManager = class {
|
|
|
160
179
|
installationKind: "npm-runtime-bundle",
|
|
161
180
|
channel: state.channel,
|
|
162
181
|
hostVersion: this.launcherVersion,
|
|
163
|
-
currentVersion:
|
|
182
|
+
currentVersion: this.runningVersion,
|
|
164
183
|
availableVersion: null,
|
|
165
184
|
downloadedVersion: state.downloadedVersion,
|
|
166
185
|
minimumHostVersion: null,
|
|
@@ -178,6 +197,11 @@ var RuntimeUpdateManager = class {
|
|
|
178
197
|
status
|
|
179
198
|
};
|
|
180
199
|
};
|
|
200
|
+
requiresRunningVersionRestart = (state) => {
|
|
201
|
+
const targetVersion = state.currentVersion?.trim();
|
|
202
|
+
const runningVersion = this.runningVersion.trim();
|
|
203
|
+
return Boolean(targetVersion && runningVersion && targetVersion !== runningVersion);
|
|
204
|
+
};
|
|
181
205
|
};
|
|
182
206
|
//#endregion
|
|
183
207
|
export { RuntimeUpdateManager };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime-update.manager.js","names":[],"sources":["../../src/managers/runtime-update.manager.ts"],"sourcesContent":["import type { UpdateManifest, UpdateProgress, UpdateSnapshot } from \"@nextclaw/kernel\";\nimport { getPackageVersion } from \"@nextclaw-service/utils/cli.utils.js\";\nimport { resolveEffectiveNpmRuntimeVersion } from \"@nextclaw-service/services/runtime/npm-runtime-bundle.service.js\";\nimport type { NpmRuntimeBundleService } from \"@nextclaw-service/services/runtime/npm-runtime-bundle.service.js\";\nimport type { NpmRuntimeBundleLayoutStore } from \"@nextclaw-service/stores/npm-runtime-bundle-layout.store.js\";\nimport type { NpmRuntimeUpdateService, NpmRuntimeAvailableUpdate } from \"@nextclaw-service/services/runtime/npm-runtime-update.service.js\";\nimport type { NpmRuntimeUpdateStateStore } from \"@nextclaw-service/stores/npm-runtime-update-state.store.js\";\nimport type { NpmRuntimeReleaseChannel } from \"@nextclaw-service/services/runtime/npm-runtime-update-source.service.js\";\nimport type { NpmRuntimeUpdateState } from \"@nextclaw-service/types/npm-runtime-bundle.types.js\";\n\ntype RuntimeUpdateManagerOptions = {\n layout: NpmRuntimeBundleLayoutStore;\n stateStore: NpmRuntimeUpdateStateStore;\n bundleService: NpmRuntimeBundleService;\n updateService: NpmRuntimeUpdateService;\n resolveManifestUrl: (channel: NpmRuntimeReleaseChannel) => string | null;\n launcherVersion?: string;\n channel: NpmRuntimeReleaseChannel;\n now?: () => Date;\n};\n\ntype NpmRuntimeUpdateActionOptions = {\n apply?: boolean;\n applyAfterDownload?: boolean;\n checkOnly?: boolean;\n onProgress?: (progress: UpdateProgress) => void;\n};\n\nexport class RuntimeUpdateManager {\n private readonly launcherVersion: string;\n private readonly now: () => Date;\n private availableManifest: UpdateManifest | null = null;\n\n constructor(private readonly options: RuntimeUpdateManagerOptions) {\n this.launcherVersion = options.launcherVersion ?? getPackageVersion();\n this.now = options.now ?? (() => new Date());\n this.options.layout.ensureLauncherDirs();\n this.syncStateFromCurrentPointer();\n }\n\n getSnapshot = (): UpdateSnapshot => this.toSnapshotFromState(this.options.stateStore.read(), {\n status: this.options.stateStore.read().downloadedVersion ? \"downloaded\" : \"idle\"\n });\n\n run = async (options: NpmRuntimeUpdateActionOptions = {}): Promise<UpdateSnapshot> => {\n if (options.apply) {\n return this.applyDownloadedUpdate();\n }\n\n const applyAfterDownload = options.applyAfterDownload ?? true;\n const checkedSnapshot = await this.checkForUpdate();\n if (options.checkOnly) {\n return checkedSnapshot;\n }\n if (applyAfterDownload && checkedSnapshot.status === \"downloaded\") {\n return this.applyDownloadedUpdate();\n }\n if (checkedSnapshot.status !== \"update-available\") {\n return checkedSnapshot;\n }\n const downloadedSnapshot = await this.downloadUpdate(options.onProgress);\n if (!applyAfterDownload || downloadedSnapshot.status !== \"downloaded\") {\n return downloadedSnapshot;\n }\n return this.applyDownloadedUpdate();\n };\n\n checkForUpdate = async (): Promise<UpdateSnapshot> => {\n const manifestUrl = this.options.resolveManifestUrl(this.options.channel);\n if (!this.options.updateService.hasSignatureVerifier()) {\n return this.toSnapshotFromState(this.options.stateStore.read(), {\n status: \"blocked\",\n installationKind: \"npm-runtime-bundle\",\n blockReason: \"signature-verification-unavailable\",\n recoveryCommand: \"Set NEXTCLAW_UPDATE_BUNDLE_PUBLIC_KEY or NEXTCLAW_UPDATE_BUNDLE_PUBLIC_KEY_PATH\",\n errorMessage: \"Runtime bundle updates require a configured update public key.\"\n });\n }\n if (!manifestUrl) {\n return this.toSnapshotFromState(this.options.stateStore.read(), {\n status: \"blocked\",\n installationKind: \"npm-runtime-bundle\",\n blockReason: \"unsupported-installation\",\n recoveryCommand: \"Set NEXTCLAW_UPDATE_MANIFEST_URL or NEXTCLAW_UPDATE_MANIFEST_BASE_URL\",\n errorMessage: \"Runtime bundle update manifest URL is not configured.\"\n });\n }\n\n const checkedAt = this.now().toISOString();\n const state = this.options.stateStore.update((current) => ({\n ...current,\n channel: this.options.channel,\n lastUpdateCheckAt: checkedAt\n }));\n const availableUpdate = await this.options.updateService.checkForUpdate(manifestUrl, state.currentVersion, state.badVersions);\n return this.toSnapshotAfterCheck(availableUpdate, this.options.stateStore.read());\n };\n\n downloadUpdate = async (onProgress?: (progress: UpdateProgress) => void): Promise<UpdateSnapshot> => {\n const manifest = this.availableManifest ?? await this.ensureAvailableManifest();\n const downloaded = await this.options.updateService.downloadAndInstallUpdate(manifest, onProgress);\n const state = this.options.stateStore.update((current) => ({\n ...current,\n downloadedVersion: downloaded.downloadedVersion,\n downloadedReleaseNotesUrl: downloaded.manifest.releaseNotesUrl\n }));\n await this.options.bundleService.pruneRetainedArtifacts();\n return this.toSnapshotFromState(state, {\n status: \"downloaded\",\n availableVersion: downloaded.downloadedVersion,\n downloadedVersion: downloaded.downloadedVersion,\n minimumHostVersion: downloaded.manifest.minimumLauncherVersion,\n releaseNotesUrl: downloaded.manifest.releaseNotesUrl,\n canApplyInApp: true,\n requiresRestart: false\n });\n };\n\n applyDownloadedUpdate = (): UpdateSnapshot => {\n const downloadedVersion = this.options.stateStore.read().downloadedVersion?.trim();\n if (!downloadedVersion) {\n throw new Error(\"No downloaded npm runtime update is ready to apply.\");\n }\n this.options.bundleService.activateVersion(downloadedVersion);\n this.availableManifest = null;\n return this.toSnapshotFromState(this.options.stateStore.read(), {\n status: \"restart-required\",\n availableVersion: null,\n downloadedVersion: null,\n releaseNotesUrl: null,\n canApplyInApp: false,\n requiresRestart: true\n });\n };\n\n private ensureAvailableManifest = async (): Promise<UpdateManifest> => {\n const snapshot = await this.checkForUpdate();\n if (!this.availableManifest) {\n if (snapshot.downloadedVersion) {\n throw new Error(`Version ${snapshot.downloadedVersion} has already been downloaded and is ready to apply.`);\n }\n throw new Error(\"No npm runtime update is currently available.\");\n }\n return this.availableManifest;\n };\n\n private toSnapshotAfterCheck = (\n availableUpdate: NpmRuntimeAvailableUpdate | null,\n state: NpmRuntimeUpdateState\n ): UpdateSnapshot => {\n if (state.downloadedVersion) {\n this.availableManifest = availableUpdate?.kind === \"runtime-bundle-update\" ? availableUpdate.manifest : this.availableManifest;\n return this.toSnapshotFromState(state, {\n status: \"downloaded\",\n availableVersion: availableUpdate?.kind === \"runtime-bundle-update\" ? availableUpdate.manifest.latestVersion : state.downloadedVersion,\n minimumHostVersion: availableUpdate?.kind === \"runtime-bundle-update\" ? availableUpdate.manifest.minimumLauncherVersion : null,\n canApplyInApp: true,\n requiresRestart: false\n });\n }\n if (!availableUpdate) {\n this.availableManifest = null;\n return this.toSnapshotFromState(state, {\n status: \"up-to-date\",\n availableVersion: null,\n downloadedVersion: null,\n releaseNotesUrl: null\n });\n }\n if (availableUpdate.kind === \"host-update-required\") {\n this.availableManifest = null;\n return this.toSnapshotFromState(state, {\n status: \"blocked\",\n availableVersion: availableUpdate.manifest.latestVersion,\n minimumHostVersion: availableUpdate.manifest.minimumLauncherVersion,\n releaseNotesUrl: availableUpdate.manifest.releaseNotesUrl,\n blockReason: \"host-too-old\",\n recoveryCommand: \"npm install -g nextclaw@latest\",\n errorMessage: `NextClaw npm launcher ${this.launcherVersion} is too old for runtime bundle ${availableUpdate.manifest.latestVersion}.`\n });\n }\n if (availableUpdate.kind === \"quarantined-bad-version\") {\n this.availableManifest = null;\n return this.toSnapshotFromState(state, {\n status: \"failed\",\n availableVersion: availableUpdate.manifest.latestVersion,\n minimumHostVersion: availableUpdate.manifest.minimumLauncherVersion,\n releaseNotesUrl: availableUpdate.manifest.releaseNotesUrl,\n errorMessage: `Version ${availableUpdate.manifest.latestVersion} was quarantined after a failed launch.`\n });\n }\n this.availableManifest = availableUpdate.manifest;\n return this.toSnapshotFromState(state, {\n status: \"update-available\",\n availableVersion: availableUpdate.manifest.latestVersion,\n minimumHostVersion: availableUpdate.manifest.minimumLauncherVersion,\n releaseNotesUrl: availableUpdate.manifest.releaseNotesUrl\n });\n };\n\n private syncStateFromCurrentPointer = (): void => {\n const currentPointer = this.options.layout.readCurrentPointer();\n const effectiveCurrentVersion = resolveEffectiveNpmRuntimeVersion({\n launcherVersion: this.launcherVersion,\n currentBundleVersion: currentPointer?.version ?? null\n });\n if (!effectiveCurrentVersion) {\n return;\n }\n this.options.stateStore.update((state) => ({\n ...state,\n currentVersion: effectiveCurrentVersion\n }));\n };\n\n private toSnapshotFromState = (\n state: NpmRuntimeUpdateState,\n patch: Partial<UpdateSnapshot> & Pick<UpdateSnapshot, \"status\">\n ): UpdateSnapshot => {\n const hasDownloadedVersion = Boolean(state.downloadedVersion);\n const { status } = patch;\n return {\n installationKind: \"npm-runtime-bundle\",\n channel: state.channel,\n hostVersion: this.launcherVersion,\n currentVersion: state.currentVersion,\n availableVersion: null,\n downloadedVersion: state.downloadedVersion,\n minimumHostVersion: null,\n releaseNotesUrl: state.downloadedReleaseNotesUrl,\n lastCheckedAt: state.lastUpdateCheckAt,\n progress: null,\n canApplyInApp: hasDownloadedVersion,\n requiresRestart: false,\n blockReason: null,\n recoveryCommand: null,\n errorMessage: null,\n failureStage: null,\n diagnosticCommand: null,\n ...patch,\n status\n };\n };\n}\n"],"mappings":";;;;AA4BA,IAAa,uBAAb,MAAkC;CAChC;CACA;CACA,oBAAmD;CAEnD,YAAY,SAAuD;AAAtC,OAAA,UAAA;AAC3B,OAAK,kBAAkB,QAAQ,mBAAmB,mBAAmB;AACrE,OAAK,MAAM,QAAQ,8BAAc,IAAI,MAAM;AAC3C,OAAK,QAAQ,OAAO,oBAAoB;AACxC,OAAK,6BAA6B;;CAGpC,oBAAoC,KAAK,oBAAoB,KAAK,QAAQ,WAAW,MAAM,EAAE,EAC3F,QAAQ,KAAK,QAAQ,WAAW,MAAM,CAAC,oBAAoB,eAAe,QAC3E,CAAC;CAEF,MAAM,OAAO,UAAyC,EAAE,KAA8B;AACpF,MAAI,QAAQ,MACV,QAAO,KAAK,uBAAuB;EAGrC,MAAM,qBAAqB,QAAQ,sBAAsB;EACzD,MAAM,kBAAkB,MAAM,KAAK,gBAAgB;AACnD,MAAI,QAAQ,UACV,QAAO;AAET,MAAI,sBAAsB,gBAAgB,WAAW,aACnD,QAAO,KAAK,uBAAuB;AAErC,MAAI,gBAAgB,WAAW,mBAC7B,QAAO;EAET,MAAM,qBAAqB,MAAM,KAAK,eAAe,QAAQ,WAAW;AACxE,MAAI,CAAC,sBAAsB,mBAAmB,WAAW,aACvD,QAAO;AAET,SAAO,KAAK,uBAAuB;;CAGrC,iBAAiB,YAAqC;EACpD,MAAM,cAAc,KAAK,QAAQ,mBAAmB,KAAK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S,cAAc;IACrI,CAAC;;AAEJ,MAAI,gBAAgB,SAAS,2BAA2B;AACtD,QAAK,oBAAoB;AACzB,UAAO,KAAK,oBAAoB,OAAO;IACrC,QAAQ;IACR,kBAAkB,gBAAgB,SAAS;IAC3C,oBAAoB,gBAAgB,SAAS;IAC7C,iBAAiB,gBAAgB,SAAS;IAC1C,cAAc,WAAW,gBAAgB,SAAS,cAAc;IACjE,CAAC;;AAEJ,OAAK,oBAAoB,gBAAgB;AACzC,SAAO,KAAK,oBAAoB,OAAO;GACrC,QAAQ;GACR,kBAAkB,gBAAgB,SAAS;GAC3C,oBAAoB,gBAAgB,SAAS;GAC7C,iBAAiB,gBAAgB,SAAS;GAC3C,CAAC;;CAGJ,oCAAkD;EAChD,MAAM,iBAAiB,KAAK,QAAQ,OAAO,oBAAoB;EAC/D,MAAM,0BAA0B,kCAAkC;GAChE,iBAAiB,KAAK;GACtB,sBAAsB,gBAAgB,WAAW;GAClD,CAAC;AACF,MAAI,CAAC,wBACH;AAEF,OAAK,QAAQ,WAAW,QAAQ,WAAW;GACzC,GAAG;GACH,gBAAgB;GACjB,EAAE;;CAGL,uBACE,OACA,UACmB;EACnB,MAAM,uBAAuB,QAAQ,MAAM,kBAAkB;EAC7D,MAAM,EAAE,WAAW;AACnB,SAAO;GACL,kBAAkB;GAClB,SAAS,MAAM;GACf,aAAa,KAAK;GAClB,gBAAgB,MAAM;GACtB,kBAAkB;GAClB,mBAAmB,MAAM;GACzB,oBAAoB;GACpB,iBAAiB,MAAM;GACvB,eAAe,MAAM;GACrB,UAAU;GACV,eAAe;GACf,iBAAiB;GACjB,aAAa;GACb,iBAAiB;GACjB,cAAc;GACd,cAAc;GACd,mBAAmB;GACnB,GAAG;GACH;GACD"}
|
|
1
|
+
{"version":3,"file":"runtime-update.manager.js","names":[],"sources":["../../src/managers/runtime-update.manager.ts"],"sourcesContent":["import type { UpdateManifest, UpdateProgress, UpdateSnapshot } from \"@nextclaw/kernel\";\nimport { getPackageVersion } from \"@nextclaw-service/utils/cli.utils.js\";\nimport { resolveEffectiveNpmRuntimeVersion } from \"@nextclaw-service/services/runtime/npm-runtime-bundle.service.js\";\nimport type { NpmRuntimeBundleService } from \"@nextclaw-service/services/runtime/npm-runtime-bundle.service.js\";\nimport type { NpmRuntimeBundleLayoutStore } from \"@nextclaw-service/stores/npm-runtime-bundle-layout.store.js\";\nimport type { NpmRuntimeUpdateService, NpmRuntimeAvailableUpdate } from \"@nextclaw-service/services/runtime/npm-runtime-update.service.js\";\nimport type { NpmRuntimeUpdateStateStore } from \"@nextclaw-service/stores/npm-runtime-update-state.store.js\";\nimport type { NpmRuntimeReleaseChannel } from \"@nextclaw-service/services/runtime/npm-runtime-update-source.service.js\";\nimport type { NpmRuntimeUpdateState } from \"@nextclaw-service/types/npm-runtime-bundle.types.js\";\n\ntype RuntimeUpdateManagerOptions = {\n layout: NpmRuntimeBundleLayoutStore;\n stateStore: NpmRuntimeUpdateStateStore;\n bundleService: NpmRuntimeBundleService;\n updateService: NpmRuntimeUpdateService;\n resolveManifestUrl: (channel: NpmRuntimeReleaseChannel) => string | null;\n launcherVersion?: string;\n runningVersion?: string;\n channel: NpmRuntimeReleaseChannel;\n now?: () => Date;\n};\n\ntype NpmRuntimeUpdateActionOptions = {\n apply?: boolean;\n applyAfterDownload?: boolean;\n checkOnly?: boolean;\n onProgress?: (progress: UpdateProgress) => void;\n};\n\nexport class RuntimeUpdateManager {\n private readonly launcherVersion: string;\n private readonly runningVersion: string;\n private readonly now: () => Date;\n private availableManifest: UpdateManifest | null = null;\n\n constructor(private readonly options: RuntimeUpdateManagerOptions) {\n this.launcherVersion = options.launcherVersion ?? getPackageVersion();\n this.runningVersion = options.runningVersion ?? getPackageVersion();\n this.now = options.now ?? (() => new Date());\n this.options.layout.ensureLauncherDirs();\n this.syncStateFromCurrentPointer();\n }\n\n getSnapshot = (): UpdateSnapshot => {\n const state = this.options.stateStore.read();\n return this.toSnapshotFromState(state, {\n status: state.downloadedVersion\n ? \"downloaded\"\n : this.requiresRunningVersionRestart(state)\n ? \"restart-required\"\n : \"idle\",\n requiresRestart: this.requiresRunningVersionRestart(state)\n });\n };\n\n run = async (options: NpmRuntimeUpdateActionOptions = {}): Promise<UpdateSnapshot> => {\n if (options.apply) {\n return this.applyDownloadedUpdate();\n }\n\n const applyAfterDownload = options.applyAfterDownload ?? true;\n const checkedSnapshot = await this.checkForUpdate();\n if (options.checkOnly) {\n return checkedSnapshot;\n }\n if (applyAfterDownload && checkedSnapshot.status === \"downloaded\") {\n return this.applyDownloadedUpdate();\n }\n if (checkedSnapshot.status !== \"update-available\") {\n return checkedSnapshot;\n }\n const downloadedSnapshot = await this.downloadUpdate(options.onProgress);\n if (!applyAfterDownload || downloadedSnapshot.status !== \"downloaded\") {\n return downloadedSnapshot;\n }\n return this.applyDownloadedUpdate();\n };\n\n checkForUpdate = async (): Promise<UpdateSnapshot> => {\n const manifestUrl = this.options.resolveManifestUrl(this.options.channel);\n if (!this.options.updateService.hasSignatureVerifier()) {\n return this.toSnapshotFromState(this.options.stateStore.read(), {\n status: \"blocked\",\n installationKind: \"npm-runtime-bundle\",\n blockReason: \"signature-verification-unavailable\",\n recoveryCommand: \"Set NEXTCLAW_UPDATE_BUNDLE_PUBLIC_KEY or NEXTCLAW_UPDATE_BUNDLE_PUBLIC_KEY_PATH\",\n errorMessage: \"Runtime bundle updates require a configured update public key.\"\n });\n }\n if (!manifestUrl) {\n return this.toSnapshotFromState(this.options.stateStore.read(), {\n status: \"blocked\",\n installationKind: \"npm-runtime-bundle\",\n blockReason: \"unsupported-installation\",\n recoveryCommand: \"Set NEXTCLAW_UPDATE_MANIFEST_URL or NEXTCLAW_UPDATE_MANIFEST_BASE_URL\",\n errorMessage: \"Runtime bundle update manifest URL is not configured.\"\n });\n }\n\n const checkedAt = this.now().toISOString();\n const state = this.options.stateStore.update((current) => ({\n ...current,\n channel: this.options.channel,\n lastUpdateCheckAt: checkedAt\n }));\n const availableUpdate = await this.options.updateService.checkForUpdate(manifestUrl, state.currentVersion, state.badVersions);\n return this.toSnapshotAfterCheck(availableUpdate, this.options.stateStore.read());\n };\n\n downloadUpdate = async (onProgress?: (progress: UpdateProgress) => void): Promise<UpdateSnapshot> => {\n const manifest = this.availableManifest ?? await this.ensureAvailableManifest();\n const downloaded = await this.options.updateService.downloadAndInstallUpdate(manifest, onProgress);\n const state = this.options.stateStore.update((current) => ({\n ...current,\n downloadedVersion: downloaded.downloadedVersion,\n downloadedReleaseNotesUrl: downloaded.manifest.releaseNotesUrl\n }));\n await this.options.bundleService.pruneRetainedArtifacts();\n return this.toSnapshotFromState(state, {\n status: \"downloaded\",\n availableVersion: downloaded.downloadedVersion,\n downloadedVersion: downloaded.downloadedVersion,\n minimumHostVersion: downloaded.manifest.minimumLauncherVersion,\n releaseNotesUrl: downloaded.manifest.releaseNotesUrl,\n canApplyInApp: true,\n requiresRestart: false\n });\n };\n\n applyDownloadedUpdate = (): UpdateSnapshot => {\n const downloadedVersion = this.options.stateStore.read().downloadedVersion?.trim();\n if (!downloadedVersion) {\n throw new Error(\"No downloaded npm runtime update is ready to apply.\");\n }\n this.options.bundleService.activateVersion(downloadedVersion);\n this.availableManifest = null;\n return this.toSnapshotFromState(this.options.stateStore.read(), {\n status: \"restart-required\",\n availableVersion: null,\n downloadedVersion: null,\n releaseNotesUrl: null,\n canApplyInApp: false,\n requiresRestart: true\n });\n };\n\n private ensureAvailableManifest = async (): Promise<UpdateManifest> => {\n const snapshot = await this.checkForUpdate();\n if (!this.availableManifest) {\n if (snapshot.downloadedVersion) {\n throw new Error(`Version ${snapshot.downloadedVersion} has already been downloaded and is ready to apply.`);\n }\n throw new Error(\"No npm runtime update is currently available.\");\n }\n return this.availableManifest;\n };\n\n private toSnapshotAfterCheck = (\n availableUpdate: NpmRuntimeAvailableUpdate | null,\n state: NpmRuntimeUpdateState\n ): UpdateSnapshot => {\n if (state.downloadedVersion) {\n this.availableManifest = availableUpdate?.kind === \"runtime-bundle-update\" ? availableUpdate.manifest : this.availableManifest;\n return this.toSnapshotFromState(state, {\n status: \"downloaded\",\n availableVersion: availableUpdate?.kind === \"runtime-bundle-update\" ? availableUpdate.manifest.latestVersion : state.downloadedVersion,\n minimumHostVersion: availableUpdate?.kind === \"runtime-bundle-update\" ? availableUpdate.manifest.minimumLauncherVersion : null,\n canApplyInApp: true,\n requiresRestart: false\n });\n }\n if (this.requiresRunningVersionRestart(state)) {\n this.availableManifest = availableUpdate?.kind === \"runtime-bundle-update\" ? availableUpdate.manifest : null;\n return this.toSnapshotFromState(state, {\n status: \"restart-required\",\n availableVersion: availableUpdate?.manifest.latestVersion ?? null,\n minimumHostVersion: availableUpdate?.manifest.minimumLauncherVersion ?? null,\n releaseNotesUrl: availableUpdate?.manifest.releaseNotesUrl ?? null,\n canApplyInApp: false,\n requiresRestart: true\n });\n }\n if (!availableUpdate) {\n this.availableManifest = null;\n return this.toSnapshotFromState(state, {\n status: \"up-to-date\",\n availableVersion: null,\n downloadedVersion: null,\n releaseNotesUrl: null\n });\n }\n if (availableUpdate.kind === \"host-update-required\") {\n this.availableManifest = null;\n return this.toSnapshotFromState(state, {\n status: \"blocked\",\n availableVersion: availableUpdate.manifest.latestVersion,\n minimumHostVersion: availableUpdate.manifest.minimumLauncherVersion,\n releaseNotesUrl: availableUpdate.manifest.releaseNotesUrl,\n blockReason: \"host-too-old\",\n recoveryCommand: \"npm install -g nextclaw@latest\",\n errorMessage: `NextClaw npm launcher ${this.launcherVersion} is too old for runtime bundle ${availableUpdate.manifest.latestVersion}.`\n });\n }\n if (availableUpdate.kind === \"quarantined-bad-version\") {\n this.availableManifest = null;\n return this.toSnapshotFromState(state, {\n status: \"failed\",\n availableVersion: availableUpdate.manifest.latestVersion,\n minimumHostVersion: availableUpdate.manifest.minimumLauncherVersion,\n releaseNotesUrl: availableUpdate.manifest.releaseNotesUrl,\n errorMessage: `Version ${availableUpdate.manifest.latestVersion} was quarantined after a failed launch.`\n });\n }\n this.availableManifest = availableUpdate.manifest;\n return this.toSnapshotFromState(state, {\n status: \"update-available\",\n availableVersion: availableUpdate.manifest.latestVersion,\n minimumHostVersion: availableUpdate.manifest.minimumLauncherVersion,\n releaseNotesUrl: availableUpdate.manifest.releaseNotesUrl\n });\n };\n\n private syncStateFromCurrentPointer = (): void => {\n const currentPointer = this.options.layout.readCurrentPointer();\n const effectiveCurrentVersion = resolveEffectiveNpmRuntimeVersion({\n launcherVersion: this.launcherVersion,\n currentBundleVersion: currentPointer?.version ?? null\n });\n if (!effectiveCurrentVersion) {\n return;\n }\n this.options.stateStore.update((state) => ({\n ...state,\n currentVersion: effectiveCurrentVersion\n }));\n };\n\n private toSnapshotFromState = (\n state: NpmRuntimeUpdateState,\n patch: Partial<UpdateSnapshot> & Pick<UpdateSnapshot, \"status\">\n ): UpdateSnapshot => {\n const hasDownloadedVersion = Boolean(state.downloadedVersion);\n const { status } = patch;\n return {\n installationKind: \"npm-runtime-bundle\",\n channel: state.channel,\n hostVersion: this.launcherVersion,\n currentVersion: this.runningVersion,\n availableVersion: null,\n downloadedVersion: state.downloadedVersion,\n minimumHostVersion: null,\n releaseNotesUrl: state.downloadedReleaseNotesUrl,\n lastCheckedAt: state.lastUpdateCheckAt,\n progress: null,\n canApplyInApp: hasDownloadedVersion,\n requiresRestart: false,\n blockReason: null,\n recoveryCommand: null,\n errorMessage: null,\n failureStage: null,\n diagnosticCommand: null,\n ...patch,\n status\n };\n };\n\n private requiresRunningVersionRestart = (state: NpmRuntimeUpdateState): boolean => {\n const targetVersion = state.currentVersion?.trim();\n const runningVersion = this.runningVersion.trim();\n return Boolean(targetVersion && runningVersion && targetVersion !== runningVersion);\n };\n}\n"],"mappings":";;;;AA6BA,IAAa,uBAAb,MAAkC;CAChC;CACA;CACA;CACA,oBAAmD;CAEnD,YAAY,SAAuD;AAAtC,OAAA,UAAA;AAC3B,OAAK,kBAAkB,QAAQ,mBAAmB,mBAAmB;AACrE,OAAK,iBAAiB,QAAQ,kBAAkB,mBAAmB;AACnE,OAAK,MAAM,QA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BAAoB,gBAAgB,SAAS;IAC7C,iBAAiB,gBAAgB,SAAS;IAC1C,cAAc,WAAW,gBAAgB,SAAS,cAAc;IACjE,CAAC;;AAEJ,OAAK,oBAAoB,gBAAgB;AACzC,SAAO,KAAK,oBAAoB,OAAO;GACrC,QAAQ;GACR,kBAAkB,gBAAgB,SAAS;GAC3C,oBAAoB,gBAAgB,SAAS;GAC7C,iBAAiB,gBAAgB,SAAS;GAC3C,CAAC;;CAGJ,oCAAkD;EAChD,MAAM,iBAAiB,KAAK,QAAQ,OAAO,oBAAoB;EAC/D,MAAM,0BAA0B,kCAAkC;GAChE,iBAAiB,KAAK;GACtB,sBAAsB,gBAAgB,WAAW;GAClD,CAAC;AACF,MAAI,CAAC,wBACH;AAEF,OAAK,QAAQ,WAAW,QAAQ,WAAW;GACzC,GAAG;GACH,gBAAgB;GACjB,EAAE;;CAGL,uBACE,OACA,UACmB;EACnB,MAAM,uBAAuB,QAAQ,MAAM,kBAAkB;EAC7D,MAAM,EAAE,WAAW;AACnB,SAAO;GACL,kBAAkB;GAClB,SAAS,MAAM;GACf,aAAa,KAAK;GAClB,gBAAgB,KAAK;GACrB,kBAAkB;GAClB,mBAAmB,MAAM;GACzB,oBAAoB;GACpB,iBAAiB,MAAM;GACvB,eAAe,MAAM;GACrB,UAAU;GACV,eAAe;GACf,iBAAiB;GACjB,aAAa;GACb,iBAAiB;GACjB,cAAc;GACd,cAAc;GACd,mBAAmB;GACnB,GAAG;GACH;GACD;;CAGH,iCAAyC,UAA0C;EACjF,MAAM,gBAAgB,MAAM,gBAAgB,MAAM;EAClD,MAAM,iBAAiB,KAAK,eAAe,MAAM;AACjD,SAAO,QAAQ,iBAAiB,kBAAkB,kBAAkB,eAAe"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"service-gateway.manager.d.ts","names":[],"sources":["../../src/managers/service-gateway.manager.ts"],"mappings":";;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"service-gateway.manager.d.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EACjB,SAAA,EAAW,eAAA;EAAA,SACF,YAAA,EAAY,0BAAA;EAAA,QACb,sBAAA;cAGW,IAAA,EAAM,kBAAA,EACN,OAAA,EAAS,qBAAA;EAkE5B,KAAA,QAAkB,OAAA;EAAA,QAcV,KAAA;EAAA,QAOA,qBAAA;EAAA,QAOA,uBAAA;EAAA,QAIA,cAAA;EAAA,QAiCA,qBAAA;EAAA,QAmBA,cAAA;EAAA,QAmBA,oBAAA;EAAA,SAKC,qBAAA,QAAkC,OAAA;EAAA,iBAI1B,aAAA;EAAA,QAWT,iBAAA;EAAA,SASC,IAAA,QAAiB,OAAA;EAAA,QAQlB,kBAAA;EAAA,QAKA,uBAAA;EAAA,QAmBA,oBAAA;EAAA,QAgBA,sBAAA;EAAA,QAiBA,wBAAA;AAAA"}
|
|
@@ -25,6 +25,7 @@ import { setImmediate } from "node:timers/promises";
|
|
|
25
25
|
//#region src/managers/service-gateway.manager.ts
|
|
26
26
|
const { getConfigPath: getConfigPath$1, getDataDir: getDataDir$1, getWorkspacePath: getWorkspacePath$1 } = NextclawCore;
|
|
27
27
|
function resolveApplyRestartMode(uiPort) {
|
|
28
|
+
if (process.env.NEXTCLAW_PROCESS_SUPERVISOR === "systemd") return "supervised-process-restart";
|
|
28
29
|
const serviceState = managedServiceStateStore.read();
|
|
29
30
|
if (serviceState?.pid === process.pid) return "managed-service-restart";
|
|
30
31
|
if (process.env.NEXTCLAW_RUNTIME_BUNDLE_CHILD === "1" && typeof serviceState?.uiPort === "number" && serviceState.uiPort === uiPort) return "managed-service-restart";
|
|
@@ -62,7 +63,9 @@ var ServiceGatewayManager = class {
|
|
|
62
63
|
const configPath = getConfigPath$1();
|
|
63
64
|
this.kernel = measureStartupSync("service.gateway.kernel", () => new NextclawKernel({
|
|
64
65
|
homeDir: getDataDir$1(),
|
|
65
|
-
configPath
|
|
66
|
+
configPath,
|
|
67
|
+
builtInAppsDirectory: this.distribution.builtInAppsDirectory,
|
|
68
|
+
productVersion: this.distribution.version
|
|
66
69
|
}));
|
|
67
70
|
this.configManager = this.kernel.configManager;
|
|
68
71
|
const config = this.configManager.config;
|
|
@@ -231,13 +234,11 @@ var ServiceGatewayManager = class {
|
|
|
231
234
|
createGatewayController = () => {
|
|
232
235
|
return measureStartupSync("service.gateway.gateway_controller", () => new GatewayControllerImpl({
|
|
233
236
|
configManager: this.configManager,
|
|
234
|
-
channels: this.kernel.channels,
|
|
235
|
-
cron: this.automation,
|
|
236
237
|
sessionManager: this.sessionManager,
|
|
237
238
|
requestRestart: async (options) => {
|
|
238
239
|
await this.deps.requestRestart({
|
|
239
|
-
reason: options?.reason ?? "gateway
|
|
240
|
-
manualMessage: "
|
|
240
|
+
reason: options?.reason ?? "gateway update relaunch",
|
|
241
|
+
manualMessage: "Run nextclaw restart in an external terminal.",
|
|
241
242
|
strategy: "background-service-or-exit",
|
|
242
243
|
delayMs: options?.delayMs,
|
|
243
244
|
silentOnServiceRestart: true
|
|
@@ -266,7 +267,7 @@ var ServiceGatewayManager = class {
|
|
|
266
267
|
onRestartRequired: (paths) => {
|
|
267
268
|
this.deps.requestRestart({
|
|
268
269
|
changedPaths: paths,
|
|
269
|
-
manualMessage:
|
|
270
|
+
manualMessage: `已保存以下改动,请在外部终端运行 nextclaw restart 后生效:${paths.join(", ")}`,
|
|
270
271
|
mode: "notify",
|
|
271
272
|
reason: `config reload requires restart: ${paths.join(", ")}`,
|
|
272
273
|
strategy: "background-service-or-manual"
|