blun-king-cli 9.1.643 → 9.1.644

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.
Files changed (266) hide show
  1. package/LIESMICH.txt +18 -0
  2. package/README.md +20 -6
  3. package/bin/blun.js +3 -3
  4. package/bin/king.js +3 -3
  5. package/bin/launcher-mode.js +125 -126
  6. package/bin/launcher-runtime.js +603 -616
  7. package/bin/plugin-bootstrap.js +339 -405
  8. package/bin/rename-private-staging.cjs +2 -2
  9. package/bin/retired-bundled-plugins.cjs +84 -0
  10. package/bin/startup-security-host.cjs +105 -0
  11. package/bin/startup-security.cjs +9 -105
  12. package/bin/startup-warning-policy.cjs +22 -0
  13. package/bin/update-lease-installer.cjs +125 -0
  14. package/bin/update-lease-sockets.cjs +228 -0
  15. package/bin/update-lease.js +22 -327
  16. package/bin/verify-bundled-agent-sources.cjs +2 -4
  17. package/blun.mjs +18 -179
  18. package/bundled-agent-sources.json +1 -552
  19. package/package.json +1 -5
  20. package/tool-liveness642/receipt.json +1 -1
  21. package/worker-host.mjs +3 -119
  22. package/agent-spine-plugin/.claude-plugin/marketplace.json +0 -20
  23. package/agent-spine-plugin/.claude-plugin/plugin.json +0 -14
  24. package/agent-spine-plugin/.codex-plugin/plugin.json +0 -47
  25. package/agent-spine-plugin/.mcp.json +0 -8
  26. package/agent-spine-plugin/CHANGELOG.md +0 -1614
  27. package/agent-spine-plugin/LICENSE +0 -186
  28. package/agent-spine-plugin/README.md +0 -432
  29. package/agent-spine-plugin/assets/agentspine-banner.svg +0 -32
  30. package/agent-spine-plugin/bin/agentspine-mcp.js +0 -4
  31. package/agent-spine-plugin/bin/agentspine.js +0 -7
  32. package/agent-spine-plugin/blun.plugin.json +0 -68
  33. package/agent-spine-plugin/docs/acceptance.md +0 -61
  34. package/agent-spine-plugin/docs/artifact-evaluation.md +0 -93
  35. package/agent-spine-plugin/docs/host-integration.md +0 -193
  36. package/agent-spine-plugin/docs/preflight-recall.md +0 -71
  37. package/agent-spine-plugin/docs/preservation-contract.md +0 -53
  38. package/agent-spine-plugin/docs/quality-gates.md +0 -50
  39. package/agent-spine-plugin/docs/session-timeline.md +0 -112
  40. package/agent-spine-plugin/docs/source-roots.md +0 -113
  41. package/agent-spine-plugin/docs/world-model.md +0 -119
  42. package/agent-spine-plugin/hooks/codex.json +0 -47
  43. package/agent-spine-plugin/hooks/hooks.json +0 -106
  44. package/agent-spine-plugin/hooks/version.json +0 -5
  45. package/agent-spine-plugin/package.json +0 -77
  46. package/agent-spine-plugin/scripts/check-codex-install.js +0 -226
  47. package/agent-spine-plugin/scripts/check-hosts.js +0 -208
  48. package/agent-spine-plugin/scripts/check-install-hook.js +0 -227
  49. package/agent-spine-plugin/scripts/check-install-selfstarter.js +0 -154
  50. package/agent-spine-plugin/scripts/check-install.js +0 -478
  51. package/agent-spine-plugin/scripts/check-line-budget.js +0 -58
  52. package/agent-spine-plugin/scripts/check-syntax.js +0 -29
  53. package/agent-spine-plugin/scripts/github-actions.js +0 -11
  54. package/agent-spine-plugin/scripts/hermetic-process.js +0 -191
  55. package/agent-spine-plugin/scripts/release-check.js +0 -150
  56. package/agent-spine-plugin/scripts/run-acceptance.js +0 -19
  57. package/agent-spine-plugin/scripts/run-checks.js +0 -50
  58. package/agent-spine-plugin/scripts/run-tests-hermetic.js +0 -112
  59. package/agent-spine-plugin/skills/agent-spine/SKILL.md +0 -99
  60. package/agent-spine-plugin/spine-example/1-identity.md +0 -12
  61. package/agent-spine-plugin/spine-example/2-voice.md +0 -6
  62. package/agent-spine-plugin/spine-example/3-conduct.md +0 -8
  63. package/agent-spine-plugin/spine-example/4-history.md +0 -4
  64. package/agent-spine-plugin/src/cli-agent.js +0 -315
  65. package/agent-spine-plugin/src/cli-attention.js +0 -95
  66. package/agent-spine-plugin/src/cli-autonomy.js +0 -36
  67. package/agent-spine-plugin/src/cli-common.js +0 -71
  68. package/agent-spine-plugin/src/cli-continuity.js +0 -116
  69. package/agent-spine-plugin/src/cli-core.js +0 -128
  70. package/agent-spine-plugin/src/cli-diagnostics.js +0 -291
  71. package/agent-spine-plugin/src/cli-host.js +0 -21
  72. package/agent-spine-plugin/src/cli-learning.js +0 -320
  73. package/agent-spine-plugin/src/cli-premortem.js +0 -16
  74. package/agent-spine-plugin/src/cli-sharing.js +0 -230
  75. package/agent-spine-plugin/src/cli.js +0 -181
  76. package/agent-spine-plugin/src/codex-reader-launcher.js +0 -182
  77. package/agent-spine-plugin/src/hook.js +0 -500
  78. package/agent-spine-plugin/src/index.js +0 -108
  79. package/agent-spine-plugin/src/lib/acceptance.js +0 -435
  80. package/agent-spine-plugin/src/lib/action-lesson-recall.js +0 -118
  81. package/agent-spine-plugin/src/lib/attention-context.js +0 -167
  82. package/agent-spine-plugin/src/lib/attention-events.js +0 -113
  83. package/agent-spine-plugin/src/lib/attention-privacy.js +0 -72
  84. package/agent-spine-plugin/src/lib/attention-schema.js +0 -164
  85. package/agent-spine-plugin/src/lib/attention-storage.js +0 -93
  86. package/agent-spine-plugin/src/lib/attention.js +0 -164
  87. package/agent-spine-plugin/src/lib/audit-premortem.js +0 -223
  88. package/agent-spine-plugin/src/lib/audit.js +0 -401
  89. package/agent-spine-plugin/src/lib/authentication.js +0 -515
  90. package/agent-spine-plugin/src/lib/autonomy-policy.js +0 -110
  91. package/agent-spine-plugin/src/lib/autonomy-store.js +0 -202
  92. package/agent-spine-plugin/src/lib/autonomy.js +0 -8
  93. package/agent-spine-plugin/src/lib/briefing.js +0 -493
  94. package/agent-spine-plugin/src/lib/catalog-document-read.js +0 -51
  95. package/agent-spine-plugin/src/lib/catalog.js +0 -167
  96. package/agent-spine-plugin/src/lib/channel-continuity.js +0 -19
  97. package/agent-spine-plugin/src/lib/channel-runtime.js +0 -665
  98. package/agent-spine-plugin/src/lib/codex-installation.js +0 -231
  99. package/agent-spine-plugin/src/lib/codex-skill-installation.js +0 -211
  100. package/agent-spine-plugin/src/lib/context.js +0 -156
  101. package/agent-spine-plugin/src/lib/continuity.js +0 -338
  102. package/agent-spine-plugin/src/lib/coordination.js +0 -577
  103. package/agent-spine-plugin/src/lib/delivery-agent-usage.js +0 -231
  104. package/agent-spine-plugin/src/lib/delivery-assignment.js +0 -220
  105. package/agent-spine-plugin/src/lib/delivery-command-actions.js +0 -462
  106. package/agent-spine-plugin/src/lib/delivery-knowledge.js +0 -78
  107. package/agent-spine-plugin/src/lib/delivery-premortem-binding.js +0 -107
  108. package/agent-spine-plugin/src/lib/delivery-premortem-closure.js +0 -171
  109. package/agent-spine-plugin/src/lib/delivery-premortem-codec.js +0 -45
  110. package/agent-spine-plugin/src/lib/delivery-premortem-correction.js +0 -101
  111. package/agent-spine-plugin/src/lib/delivery-premortem-file.js +0 -21
  112. package/agent-spine-plugin/src/lib/delivery-premortem-index.js +0 -493
  113. package/agent-spine-plugin/src/lib/delivery-premortem-inspection.js +0 -37
  114. package/agent-spine-plugin/src/lib/delivery-premortem-recovery.js +0 -120
  115. package/agent-spine-plugin/src/lib/delivery-premortem-rejection.js +0 -65
  116. package/agent-spine-plugin/src/lib/delivery-premortem-results.js +0 -28
  117. package/agent-spine-plugin/src/lib/delivery-premortem-session-guard.js +0 -46
  118. package/agent-spine-plugin/src/lib/delivery-premortem-write-ledger.js +0 -285
  119. package/agent-spine-plugin/src/lib/delivery-premortem.js +0 -499
  120. package/agent-spine-plugin/src/lib/delivery-shell-heredoc.js +0 -115
  121. package/agent-spine-plugin/src/lib/delivery-shell-substitutions.js +0 -111
  122. package/agent-spine-plugin/src/lib/delivery-shell-wrapper.js +0 -64
  123. package/agent-spine-plugin/src/lib/delivery-target.js +0 -73
  124. package/agent-spine-plugin/src/lib/delivery-verification.js +0 -445
  125. package/agent-spine-plugin/src/lib/documents.js +0 -239
  126. package/agent-spine-plugin/src/lib/feed-transport.js +0 -499
  127. package/agent-spine-plugin/src/lib/filesystem-retry.js +0 -34
  128. package/agent-spine-plugin/src/lib/gateway-common.js +0 -68
  129. package/agent-spine-plugin/src/lib/gateway-control.js +0 -370
  130. package/agent-spine-plugin/src/lib/gateway-delivery.js +0 -103
  131. package/agent-spine-plugin/src/lib/gateway-execution.js +0 -350
  132. package/agent-spine-plugin/src/lib/gateway-group-response.js +0 -128
  133. package/agent-spine-plugin/src/lib/gateway-host-fencing.js +0 -92
  134. package/agent-spine-plugin/src/lib/gateway-host-lifecycle.js +0 -193
  135. package/agent-spine-plugin/src/lib/gateway-inspection.js +0 -85
  136. package/agent-spine-plugin/src/lib/gateway-knowledge.js +0 -129
  137. package/agent-spine-plugin/src/lib/gateway-policy-provenance.js +0 -197
  138. package/agent-spine-plugin/src/lib/gateway-premortem-disposition.js +0 -82
  139. package/agent-spine-plugin/src/lib/gateway-premortem.js +0 -363
  140. package/agent-spine-plugin/src/lib/gateway-prepared-host.js +0 -28
  141. package/agent-spine-plugin/src/lib/gateway-runs.js +0 -345
  142. package/agent-spine-plugin/src/lib/gateway-runtime-identity.js +0 -31
  143. package/agent-spine-plugin/src/lib/gateway-runtime-records.js +0 -21
  144. package/agent-spine-plugin/src/lib/gateway-runtime.js +0 -18
  145. package/agent-spine-plugin/src/lib/gateway-state-transaction.js +0 -356
  146. package/agent-spine-plugin/src/lib/gateway-state.js +0 -344
  147. package/agent-spine-plugin/src/lib/graph.js +0 -337
  148. package/agent-spine-plugin/src/lib/hook-artifact-guards.js +0 -356
  149. package/agent-spine-plugin/src/lib/hook-audit.js +0 -43
  150. package/agent-spine-plugin/src/lib/hook-briefing-use.js +0 -78
  151. package/agent-spine-plugin/src/lib/hook-context.js +0 -441
  152. package/agent-spine-plugin/src/lib/hook-final-message.js +0 -26
  153. package/agent-spine-plugin/src/lib/hook-input.js +0 -27
  154. package/agent-spine-plugin/src/lib/hook-output.js +0 -284
  155. package/agent-spine-plugin/src/lib/hook-premortem.js +0 -257
  156. package/agent-spine-plugin/src/lib/hook-process-advisory.js +0 -36
  157. package/agent-spine-plugin/src/lib/hook-protection.js +0 -95
  158. package/agent-spine-plugin/src/lib/hook-stop-verification.js +0 -84
  159. package/agent-spine-plugin/src/lib/hook-timeline.js +0 -102
  160. package/agent-spine-plugin/src/lib/host-instruction-budget.js +0 -11
  161. package/agent-spine-plugin/src/lib/https-transport.js +0 -392
  162. package/agent-spine-plugin/src/lib/identifier-analysis.js +0 -446
  163. package/agent-spine-plugin/src/lib/indexed-memory-offline.js +0 -40
  164. package/agent-spine-plugin/src/lib/indexed-memory.js +0 -298
  165. package/agent-spine-plugin/src/lib/knowledge-evidence.js +0 -431
  166. package/agent-spine-plugin/src/lib/learning-applications.js +0 -441
  167. package/agent-spine-plugin/src/lib/learning-artifact-evaluator.js +0 -114
  168. package/agent-spine-plugin/src/lib/learning-candidates.js +0 -274
  169. package/agent-spine-plugin/src/lib/learning-context.js +0 -137
  170. package/agent-spine-plugin/src/lib/learning-delivery-contracts.js +0 -310
  171. package/agent-spine-plugin/src/lib/learning-evaluation-contracts.js +0 -350
  172. package/agent-spine-plugin/src/lib/learning-evaluation-registration.js +0 -372
  173. package/agent-spine-plugin/src/lib/learning-evaluation-revocation.js +0 -292
  174. package/agent-spine-plugin/src/lib/learning-evidence-contracts.js +0 -321
  175. package/agent-spine-plugin/src/lib/learning-findings.js +0 -458
  176. package/agent-spine-plugin/src/lib/learning-measurement-contracts.js +0 -285
  177. package/agent-spine-plugin/src/lib/learning-measurements.js +0 -265
  178. package/agent-spine-plugin/src/lib/learning-outcome-contracts.js +0 -165
  179. package/agent-spine-plugin/src/lib/learning-outcomes.js +0 -343
  180. package/agent-spine-plugin/src/lib/learning-reconciliation.js +0 -290
  181. package/agent-spine-plugin/src/lib/learning-retry-contracts.js +0 -188
  182. package/agent-spine-plugin/src/lib/learning-schema.js +0 -229
  183. package/agent-spine-plugin/src/lib/learning-scope-targets.js +0 -424
  184. package/agent-spine-plugin/src/lib/learning-state-upgrade.js +0 -477
  185. package/agent-spine-plugin/src/lib/learning-status-configuration.js +0 -476
  186. package/agent-spine-plugin/src/lib/learning-storage.js +0 -203
  187. package/agent-spine-plugin/src/lib/learning-trial-recovery.js +0 -218
  188. package/agent-spine-plugin/src/lib/learning-validation-contracts.js +0 -375
  189. package/agent-spine-plugin/src/lib/learning-validation-renewal.js +0 -298
  190. package/agent-spine-plugin/src/lib/learning-validation-runtime.js +0 -234
  191. package/agent-spine-plugin/src/lib/learning.js +0 -36
  192. package/agent-spine-plugin/src/lib/lesson-recall-session.js +0 -172
  193. package/agent-spine-plugin/src/lib/mcp-autonomy-tools.js +0 -37
  194. package/agent-spine-plugin/src/lib/mcp-delivery-completion.js +0 -124
  195. package/agent-spine-plugin/src/lib/mcp-delivery-tools.js +0 -45
  196. package/agent-spine-plugin/src/lib/mcp-premortem.js +0 -68
  197. package/agent-spine-plugin/src/lib/mcp-runtime.js +0 -355
  198. package/agent-spine-plugin/src/lib/mcp-source-context.js +0 -61
  199. package/agent-spine-plugin/src/lib/mcp-timeline-tools.js +0 -240
  200. package/agent-spine-plugin/src/lib/mcp-world-tools.js +0 -52
  201. package/agent-spine-plugin/src/lib/object-transport.js +0 -206
  202. package/agent-spine-plugin/src/lib/owned-file-lock.js +0 -182
  203. package/agent-spine-plugin/src/lib/paths.js +0 -109
  204. package/agent-spine-plugin/src/lib/peer-transport.js +0 -283
  205. package/agent-spine-plugin/src/lib/persona-runtime.js +0 -581
  206. package/agent-spine-plugin/src/lib/pre-answer-timeline-recall.js +0 -104
  207. package/agent-spine-plugin/src/lib/preflight-delivery-id.js +0 -27
  208. package/agent-spine-plugin/src/lib/preflight.js +0 -688
  209. package/agent-spine-plugin/src/lib/project-portfolio.js +0 -176
  210. package/agent-spine-plugin/src/lib/runtime.js +0 -13
  211. package/agent-spine-plugin/src/lib/selfstarter-core.js +0 -382
  212. package/agent-spine-plugin/src/lib/selfstarter-jobs.js +0 -149
  213. package/agent-spine-plugin/src/lib/selfstarter-lease.js +0 -204
  214. package/agent-spine-plugin/src/lib/selfstarter-policy.js +0 -90
  215. package/agent-spine-plugin/src/lib/selfstarter-workspace.js +0 -111
  216. package/agent-spine-plugin/src/lib/selfstarter.js +0 -11
  217. package/agent-spine-plugin/src/lib/session-timeline-auth.js +0 -316
  218. package/agent-spine-plugin/src/lib/session-timeline-codex.js +0 -69
  219. package/agent-spine-plugin/src/lib/session-timeline-contract.js +0 -56
  220. package/agent-spine-plugin/src/lib/session-timeline-enrollment-source.js +0 -38
  221. package/agent-spine-plugin/src/lib/session-timeline-enrollment-storage.js +0 -128
  222. package/agent-spine-plugin/src/lib/session-timeline-enrollment-transport.js +0 -15
  223. package/agent-spine-plugin/src/lib/session-timeline-enrollment.js +0 -478
  224. package/agent-spine-plugin/src/lib/session-timeline-event-extract.js +0 -186
  225. package/agent-spine-plugin/src/lib/session-timeline-host-origin.js +0 -73
  226. package/agent-spine-plugin/src/lib/session-timeline-host-receipt.js +0 -117
  227. package/agent-spine-plugin/src/lib/session-timeline-invocation.js +0 -201
  228. package/agent-spine-plugin/src/lib/session-timeline-king.js +0 -93
  229. package/agent-spine-plugin/src/lib/session-timeline-prior.js +0 -57
  230. package/agent-spine-plugin/src/lib/session-timeline-provider.js +0 -36
  231. package/agent-spine-plugin/src/lib/session-timeline-query.js +0 -56
  232. package/agent-spine-plugin/src/lib/session-timeline-results.js +0 -56
  233. package/agent-spine-plugin/src/lib/session-timeline-root.js +0 -11
  234. package/agent-spine-plugin/src/lib/session-timeline-search.js +0 -82
  235. package/agent-spine-plugin/src/lib/session-timeline-sid-acl.js +0 -213
  236. package/agent-spine-plugin/src/lib/session-timeline-source-open.js +0 -30
  237. package/agent-spine-plugin/src/lib/session-timeline-source.js +0 -80
  238. package/agent-spine-plugin/src/lib/session-timeline-state.js +0 -45
  239. package/agent-spine-plugin/src/lib/session-timeline-transport.js +0 -42
  240. package/agent-spine-plugin/src/lib/session-timeline-windows-acl.js +0 -145
  241. package/agent-spine-plugin/src/lib/session-timeline.js +0 -462
  242. package/agent-spine-plugin/src/lib/sharing.js +0 -969
  243. package/agent-spine-plugin/src/lib/source-roots.js +0 -475
  244. package/agent-spine-plugin/src/lib/source-tree-scan.js +0 -178
  245. package/agent-spine-plugin/src/lib/sqlite-transport.js +0 -501
  246. package/agent-spine-plugin/src/lib/task-knowledge-context.js +0 -99
  247. package/agent-spine-plugin/src/lib/telegram-adapter.js +0 -119
  248. package/agent-spine-plugin/src/lib/timeline-continuation-update.js +0 -100
  249. package/agent-spine-plugin/src/lib/timeline-tool-guard.js +0 -225
  250. package/agent-spine-plugin/src/lib/timeline-user-feedback.js +0 -216
  251. package/agent-spine-plugin/src/lib/timeline-world-capture.js +0 -233
  252. package/agent-spine-plugin/src/lib/voice-runtime.js +0 -39
  253. package/agent-spine-plugin/src/lib/world-knowledge.js +0 -306
  254. package/agent-spine-plugin/src/lib/world-model.js +0 -333
  255. package/agent-spine-plugin/src/mcp.js +0 -456
  256. package/agent-spine-plugin/src/version.js +0 -1
  257. package/agent-spine-plugin/src/worker.js +0 -257
  258. package/bin/agentspine-king-goal-inbox.mjs +0 -127
  259. package/bin/agentspine-king-goal-intake.mjs +0 -106
  260. package/bin/agentspine-king-host-runner.mjs +0 -109
  261. package/bin/agentspine-king-snapshot-policy.cjs +0 -80
  262. package/bin/agentspine-king-status-policy.mjs +0 -226
  263. package/bin/agentspine-king-worker-host.mjs +0 -160
  264. package/bin/managed-plugin-selection.cjs +0 -141
  265. package/bin/verify-agent-behavior.cjs +0 -122
  266. package/bin/verify-agent-components.cjs +0 -104
@@ -1,51 +1,49 @@
1
- 'use strict';
2
- /*
3
- * BLUN CLI Launcher (npm) — Erststart richtet alles ein:
4
- * 1. King richtet das Telegram-Plugin im BLUN_HOME ein
5
- * Danach: TUI starten. Anmeldung und Modellkatalog kommen ueber BLUN OAuth.
6
- */
7
- const fs = require('node:fs');
8
- const path = require('node:path');
9
- const os = require('node:os');
10
- const { spawn } = require('node:child_process');
11
- const {
12
- LAUNCHER_MODES,
13
- createLauncherEnvironment,
14
- isNpmPackageUpdateRequest,
15
- isStandaloneHelpRequest,
16
- isReadOnlyInspectionRequest,
17
- launcherHelpText,
18
- launcherModeFromArgv,
19
- } = require('./launcher-mode');
20
- const { installManagedTelegramPluginAsync, installManagedAgentSpinePluginAsync } = require('./plugin-bootstrap');
21
- const {
22
- availableStandardToolNames,
23
- seedStandardDesignSkillAsync,
24
- seedStandardTools,
25
- seedStandardToolsAsync,
26
- } = require('./standard-tools-bootstrap');
27
- const { CORE_LOADED_MESSAGE } = require('./core-bootstrap');
28
- const {
29
- appendLauncherStatus, claimLauncherRestart, consumeIntentionalStopMarker,
30
- isAbnormalCoreExit, restartDelayMs,
31
- } = require('./launcher-restart-policy.cjs');
32
- const { recordRuntimeExit } = require('./runtime-exit-ledger.cjs');
33
- const { prepareManagedNodeRuntime } = require('./node-runtime');
34
- const { unsupportedNodeMessage } = require('./node-version');
35
- const { repairConfiguredNativeModules } = require('./native-module-repair');
36
- const { acquireSharedRuntimeLease, tryAcquireUpdateLease } = require('./update-lease');
37
- const { runExplicitUpdate, runUpdateNotice } = require('./update-notice');
38
- const {
39
- createStartupSecurity,
40
- ensurePrivateDirectory,
41
- securePrivateFile,
42
- writePrivateFile,
43
- } = require('./private-paths');
44
-
45
- const { writeTelegramTemplate } = require('./rename-private-staging.cjs');
46
- const PKG = path.resolve(__dirname, '..');
47
- const { parseProfileLaunchArgs, resolveSelectedProfile } = require('./profile-launch.cjs');
48
-
1
+ 'use strict';
2
+ /*
3
+ * BLUN CLI Launcher (npm) — Erststart richtet alles ein:
4
+ * 1. King richtet das Telegram-Plugin im BLUN_HOME ein
5
+ * Danach: TUI starten. Anmeldung und Modellkatalog kommen ueber BLUN OAuth.
6
+ */
7
+ const fs = require('node:fs');
8
+ const path = require('node:path');
9
+ const os = require('node:os');
10
+ const { spawn } = require('node:child_process');
11
+ const {
12
+ LAUNCHER_MODES,
13
+ createLauncherEnvironment,
14
+ isNpmPackageUpdateRequest,
15
+ isStandaloneHelpRequest,
16
+ isReadOnlyInspectionRequest,
17
+ launcherHelpText,
18
+ launcherModeFromArgv,
19
+ } = require('./launcher-mode');
20
+ const { installManagedTelegramPluginAsync } = require('./plugin-bootstrap');
21
+ const {
22
+ availableStandardToolNames,
23
+ seedStandardTools,
24
+ } = require('./standard-tools-bootstrap');
25
+ const { CORE_LOADED_MESSAGE } = require('./core-bootstrap');
26
+ const {
27
+ appendLauncherStatus, claimLauncherRestart, consumeIntentionalStopMarker,
28
+ isAbnormalCoreExit, restartDelayMs,
29
+ } = require('./launcher-restart-policy.cjs');
30
+ const { recordRuntimeExit } = require('./runtime-exit-ledger.cjs');
31
+ const { prepareManagedNodeRuntime } = require('./node-runtime');
32
+ const { unsupportedNodeMessage } = require('./node-version');
33
+ const { repairConfiguredNativeModules } = require('./native-module-repair');
34
+ const { acquireSharedRuntimeLease, tryAcquireUpdateLease } = require('./update-lease');
35
+ const { runExplicitUpdate, runUpdateNotice } = require('./update-notice');
36
+ const {
37
+ createStartupSecurity,
38
+ ensurePrivateDirectory,
39
+ securePrivateFile,
40
+ writePrivateFile,
41
+ } = require('./private-paths');
42
+
43
+ const { writeTelegramTemplate } = require('./rename-private-staging.cjs');
44
+ const PKG = path.resolve(__dirname, '..');
45
+ const { parseProfileLaunchArgs, resolveSelectedProfile } = require('./profile-launch.cjs');
46
+
49
47
  // Generated from actual 628 Commander registrations; see GRAMMAR-628.json.
50
48
  // No subcommand option arity table: subcommand tails belong to Core.
51
49
  const ROOT_OPTION_ARITY = Object.freeze({
@@ -165,571 +163,560 @@ function parseExplicitProfileArgs(args, mode) {
165
163
  return { args: remaining, name };
166
164
  }
167
165
 
168
- const PROFILE = parseExplicitProfileArgs(process.argv.slice(2), launcherModeFromArgv(process.argv));
169
- const ARGS = PROFILE.args;
170
-
171
- function applyProfileEnvironment(env, paths) {
172
- env.BLUN_HOME = paths.blunHome;
173
- if (PROFILE.name !== undefined) {
174
- env.BLUN_SHARED_HOME = paths.sharedHome;
175
- env.BLUN_PROFILE = PROFILE.name;
176
- } else if (String(env.BLUN_STATE_DIR || '').trim()) {
177
- env.BLUN_SHARED_HOME = paths.blunHome;
178
- }
179
- return env;
180
- }
181
-
182
- function normalizeWindowsPath(value) {
183
- return path.win32.normalize(value).replace(/\\+$/u, '').toLowerCase();
184
- }
185
-
186
- function resolveLauncherPrivatePaths(options = {}) {
187
- const env = options.env || process.env;
188
- const platform = options.platform || process.platform;
189
- const configuredHome = String(env.BLUN_HOME || '').trim();
190
- const selectedProfile = options.profileName ?? PROFILE.name;
191
- const stateDir = String(env.BLUN_STATE_DIR || '').trim();
192
- if (stateDir) {
193
- const paths = platform === 'win32' ? path.win32 : path.posix;
194
- if (!paths.isAbsolute(stateDir) || (platform === 'win32' && !/^[A-Za-z]:[\\/]/u.test(stateDir))) {
195
- throw new Error('BLUN_STATE_DIR must be an absolute local path.');
196
- }
197
- const blunHome = paths.resolve(stateDir);
198
- const fsImpl = options.fsImpl || fs;
199
- let ancestor = blunHome;
200
- for (;;) {
201
- try {
202
- const stat = fsImpl.lstatSync(ancestor);
203
- const realpath = fsImpl.realpathSync.native || fsImpl.realpathSync;
204
- const canonical = realpath(ancestor);
205
- const normalize = platform === 'win32' ? normalizeWindowsPath : paths.normalize;
206
- if (!stat.isDirectory() || stat.isSymbolicLink() || normalize(canonical) !== normalize(ancestor)) {
207
- throw new Error('BLUN_STATE_DIR must not traverse a symbolic link or junction.');
208
- }
209
- break;
210
- } catch (error) {
211
- if (error.code !== 'ENOENT') throw error;
212
- const parent = paths.dirname(ancestor);
213
- if (parent === ancestor) throw error;
214
- ancestor = parent;
215
- }
216
- }
217
- if (selectedProfile !== undefined) {
218
- // A state override cannot bypass the canonical OS-home/profile guards.
219
- const profileEnv = { ...env };
220
- delete profileEnv.BLUN_STATE_DIR;
221
- const selected = resolveLauncherPrivatePaths({ ...options, env: profileEnv, profileName: selectedProfile });
222
- const normalize = platform === 'win32' ? normalizeWindowsPath : paths.normalize;
223
- if (normalize(blunHome) !== normalize(selected.blunHome)) {
224
- throw new Error('BLUN_STATE_DIR widerspricht dem ausgewaehlten Profil.');
225
- }
226
- return selected;
227
- }
228
- return { blunHome, userHome: (options.homedir || os.homedir)() };
229
- }
230
- if (platform !== 'win32') {
231
- const posix = path.posix;
232
- const userHome = (options.homedir || os.homedir)();
233
- if (selectedProfile !== undefined) {
234
- const configuredShared = String(env.BLUN_SHARED_HOME || '').trim();
235
- const sharedHome = configuredShared
236
- ? posix.resolve(configuredShared)
237
- : configuredHome && posix.basename(posix.dirname(configuredHome)) === 'profile'
238
- ? posix.resolve(configuredHome, '..', '..')
239
- : configuredHome ? posix.resolve(configuredHome) : posix.join(userHome, '.blun');
240
- const blunHome = resolveSelectedProfile(sharedHome, selectedProfile, posix);
241
- if (configuredShared && configuredHome && posix.resolve(configuredHome) !== blunHome) {
242
- throw new Error(`BLUN_HOME passt nicht zum Profil ${selectedProfile}: ${blunHome}`);
243
- }
244
- return { blunHome, sharedHome, userHome };
245
- }
246
- return {
247
- blunHome: configuredHome ? path.resolve(configuredHome) : path.join(userHome, '.blun'),
248
- userHome,
249
- };
250
- }
251
-
252
- const fsImpl = options.fsImpl || fs;
253
- const userInfo = (options.userInfo || os.userInfo)();
254
- const reportedHome = String(userInfo?.homedir || '').trim();
255
- if (!path.win32.isAbsolute(reportedHome) || reportedHome.startsWith('\\\\')) {
256
- throw new Error('Das lokale Windows-Benutzerprofil konnte nicht sicher bestimmt werden.');
257
- }
258
- const resolvedHome = path.win32.resolve(reportedHome);
259
- const stat = fsImpl.lstatSync(resolvedHome);
260
- if (!stat.isDirectory() || stat.isSymbolicLink()) {
261
- throw new Error('Das lokale Windows-Benutzerprofil ist kein vertrauenswuerdiges Verzeichnis.');
262
- }
263
- const realpath = fsImpl.realpathSync.native || fsImpl.realpathSync;
264
- const userHome = path.win32.normalize(realpath(resolvedHome));
265
- const volumeRoot = path.win32.parse(userHome).root;
266
- if (!/^[A-Za-z]:\\$/u.test(volumeRoot)
267
- || normalizeWindowsPath(userHome) !== normalizeWindowsPath(resolvedHome)) {
268
- throw new Error('Das lokale Windows-Benutzerprofil ist kein kanonischer lokaler Pfad.');
269
- }
270
-
271
- const blunHome = path.win32.join(userHome, '.blun');
272
- if (selectedProfile !== undefined) {
273
- const profileHome = resolveSelectedProfile(blunHome, selectedProfile, path.win32);
274
- const configuredShared = String(env.BLUN_SHARED_HOME || '').trim();
275
- if (configuredShared && normalizeWindowsPath(path.win32.resolve(configuredShared)) !== normalizeWindowsPath(blunHome)) {
276
- throw new Error(`BLUN_SHARED_HOME muss unter Windows exakt im Windows-Benutzerprofil liegen: ${blunHome}`);
277
- }
278
- if (configuredHome && normalizeWindowsPath(path.win32.resolve(configuredHome)) !== normalizeWindowsPath(profileHome)
279
- && normalizeWindowsPath(path.win32.resolve(configuredHome)) !== normalizeWindowsPath(blunHome)) {
280
- throw new Error(`BLUN_HOME passt nicht zum Profil ${selectedProfile}: ${profileHome}`);
281
- }
282
- return { blunHome: profileHome, sharedHome: blunHome, userHome };
283
- }
284
-
285
- if (configuredHome
286
- && normalizeWindowsPath(path.win32.resolve(configuredHome)) !== normalizeWindowsPath(blunHome)) {
287
- throw new Error(`BLUN_HOME muss unter Windows exakt im Windows-Benutzerprofil liegen: ${blunHome}`);
288
- }
289
- return { blunHome, userHome };
290
- }
291
-
292
- function readPackageVersion() {
293
- const { version } = JSON.parse(fs.readFileSync(path.join(PKG, 'package.json'), 'utf8'));
294
- if (typeof version !== 'string' || version.length === 0) {
295
- throw new Error('Ungueltige Paketversion in package.json');
296
- }
297
- return version;
298
- }
299
-
300
- function shouldDetachProtectedCore(options = {}) {
301
- const platform = options.platform || process.platform;
302
- const stdinIsTTY = Object.hasOwn(options, 'stdinIsTTY')
303
- ? options.stdinIsTTY
304
- : process.stdin.isTTY;
305
- return platform !== 'win32' || stdinIsTTY !== true;
306
- }
307
-
308
- function spawnProtectedCore(args, env, cwd) {
309
- const terminalOwner = process.platform === 'win32' && process.stdin.isTTY === true;
310
- const child = spawn(
311
- process.execPath,
312
- [path.join(PKG, 'bin', 'core-bootstrap.js'), ...args],
313
- {
314
- cwd,
315
- detached: shouldDetachProtectedCore(),
316
- env: { ...env, BLUN_TERMINAL_OWNER: terminalOwner ? '1' : '0' },
317
- stdio: ['inherit', 'inherit', 'inherit', 'ipc'],
318
- windowsHide: true,
319
- },
320
- );
321
- let loadedSettled = false;
322
- let completedSettled = false;
323
- let operatorSignal;
324
- let resolveLoaded;
325
- let resolveCompleted;
326
- const loaded = new Promise((resolve) => { resolveLoaded = resolve; });
327
- const completed = new Promise((resolve) => { resolveCompleted = resolve; });
328
- const settleLoaded = (value) => {
329
- if (loadedSettled) return;
330
- loadedSettled = true;
331
- resolveLoaded(value);
332
- };
333
- const settleCompleted = (result) => {
334
- if (completedSettled) return;
335
- completedSettled = true;
336
- for (const [signal, handler] of signalHandlers) process.removeListener(signal, handler);
337
- settleLoaded(false);
338
- resolveCompleted(operatorSignal === undefined ? result : { ...result, signal: operatorSignal });
339
- };
340
- const signalHandlers = new Map();
341
- for (const signal of ['SIGHUP', 'SIGINT', 'SIGTERM']) {
342
- const handler = () => {
343
- operatorSignal = signal;
344
- try {
345
- child.kill(signal);
346
- } catch {}
347
- };
348
- signalHandlers.set(signal, handler);
349
- process.once(signal, handler);
350
- }
351
- child.on('message', (message) => {
352
- if (message?.type !== CORE_LOADED_MESSAGE) return;
353
- settleLoaded(true);
354
- if (terminalOwner) return;
355
- try {
356
- child.disconnect();
357
- } catch {}
358
- });
359
- child.once('error', (error) => settleCompleted({ error }));
360
- child.once('exit', (code, signal) => settleCompleted({ code, signal }));
361
- return { child, completed, loaded };
362
- }
363
-
364
- async function runInformationalCore(args, env, cwd, releaseNotice) {
365
- const core = spawnProtectedCore(args, env, cwd);
366
- await core.loaded;
367
- await releaseNotice();
368
- const result = await core.completed;
369
- if (result.error) throw result.error;
370
- return Number.isInteger(result.code) ? result.code : exitCodeForChild(result, false);
371
- }
372
-
373
- async function superviseProtectedCore(args, env, cwd, releaseNotice) {
374
- let noticeReleased = false;
375
- for (;;) {
376
- const core = spawnProtectedCore(args, env, cwd);
377
- const loaded = await core.loaded;
378
- if (!noticeReleased) {
379
- noticeReleased = true;
380
- await releaseNotice();
381
- }
382
- const result = await core.completed;
383
- const exitCode = result.error ? 1 : exitCodeForChild(result, loaded);
384
- const intentionalStop = consumeIntentionalStopMarker({
385
- homeDir: env.BLUN_HOME, childPid: core.child.pid, nowMs: Date.now(),
386
- });
387
- recordRuntimeExit({
388
- homeDir: env.BLUN_HOME, source: 'launcher', kind: result.error ? 'child-error' : 'child-exit',
389
- exitCode, signal: result.signal, phase: loaded ? 'runtime' : 'startup',
390
- cliVersion: env.BLUN_PUBLIC_PACKAGE_VERSION, profile: env.BLUN_PROFILE,
391
- loaded, childPid: core.child.pid, error: result.error,
392
- });
393
- if (intentionalStop || !isAbnormalCoreExit(result, loaded)) {
394
- if (result.error) throw result.error;
395
- return exitCode;
396
- }
397
- const claim = claimLauncherRestart({ homeDir: env.BLUN_HOME, nowMs: Date.now() });
398
- try {
399
- appendLauncherStatus({
400
- homeDir: env.BLUN_HOME,
401
- stateDir: env.BLUN_TELEGRAM_STATE_DIR
402
- || path.join(env.BLUN_SHARED_HOME || env.BLUN_HOME, 'channels', 'telegram'),
403
- nowMs: Date.now(), attempt: claim.attempt, limit: claim.limit, exitCode, signal: result.signal,
404
- kind: claim.allowed ? 'launcher-restart' : 'launcher-restart-exhausted',
405
- });
406
- } catch {}
407
- if (!claim.allowed) {
408
- if (result.error) throw result.error;
409
- return exitCode;
410
- }
411
- await new Promise((resolve) => setTimeout(resolve, restartDelayMs(claim.attempt)));
412
- }
413
- }
414
-
415
- function exitCodeForChild(result, loaded) {
416
- if (!loaded && result.code === 75) return 0;
417
- if (Number.isInteger(result.code)) return result.code;
418
- if (result.signal === 'SIGINT') return 130;
419
- if (result.signal === 'SIGTERM') return 143;
420
- return 1;
421
- }
422
-
423
- async function installTelegramForProfile(packageRoot, blunDir, io) {
424
- await installManagedTelegramPluginAsync({ packageRoot, blunDir, io });
425
- const channelsDir = path.join(blunDir, 'channels');
426
- const channelDir = path.join(channelsDir, 'telegram');
427
- await io.ensurePrivateDirectory(channelsDir);
428
- await io.ensurePrivateDirectory(channelDir);
429
- const envFile = path.join(channelDir, '.env');
430
- if (!fs.existsSync(envFile)) {
431
- await io.writePrivateFile(envFile, 'BLUN_TELEGRAM_BOT_TOKEN=HIER_DEIN_BOT_TOKEN_EINFUEGEN\n');
432
- } else {
433
- await io.securePrivateFile(envFile);
434
- }
435
- }
436
-
437
- function spawnManagedLauncher(binary, cwd) {
438
- return new Promise((resolve, reject) => {
439
- const child = spawn(binary, process.argv.slice(1), {
440
- cwd,
441
- env: process.env,
442
- stdio: 'inherit',
443
- windowsHide: true,
444
- });
445
- child.once('error', reject);
446
- child.once('exit', (code, signal) => {
447
- if (Number.isInteger(code)) {
448
- resolve(code);
449
- return;
450
- }
451
- if (signal === 'SIGINT') {
452
- resolve(130);
453
- return;
454
- }
455
- if (signal === 'SIGTERM') {
456
- resolve(143);
457
- return;
458
- }
459
- resolve(1);
460
- });
461
- });
462
- }
463
-
464
- async function runLauncher(options = {}) {
465
- const callerCwd = process.cwd();
466
- const mode = options.mode || launcherModeFromArgv(process.argv);
467
- if (PROFILE.name !== undefined) {
468
- applyProfileEnvironment(process.env, resolveLauncherPrivatePaths());
469
- }
470
- const explicitUpdateRequest = isNpmPackageUpdateRequest(ARGS);
471
- const explicitToolsRequest = String(ARGS[0] || '').toLowerCase() === 'tools';
472
- const noticeResult = options.skipUpdateNotice === true
473
- ? { acquired: true, lease: { assertOwned() {}, async release() {} } }
474
- : options.noticeLease
475
- ? { acquired: true, lease: options.noticeLease }
476
- : await tryAcquireUpdateLease({ packageRoot: PKG, role: 'notice' });
477
- if (!noticeResult.acquired) {
478
- if (explicitUpdateRequest) {
479
- process.stderr.write('Das Update konnte nicht verifiziert werden.\n');
480
- process.exitCode = 1;
481
- }
482
- return;
483
- }
484
- const noticeLease = noticeResult.lease;
485
- let runtimeLease = options.runtimeLease;
486
- let noticeReleased = false;
487
- const releaseNotice = async () => {
488
- if (noticeReleased) return;
489
- noticeReleased = true;
490
- await noticeLease.release();
491
- await runtimeLease?.release();
492
- };
493
-
494
- try {
495
- if (!runtimeLease && !explicitUpdateRequest) {
496
- const installProbe = await tryAcquireUpdateLease({ packageRoot: PKG, role: 'install' });
497
- if (!installProbe.acquired) {
498
- process.stderr.write(explicitUpdateRequest
499
- ? 'Das Update konnte nicht verifiziert werden.\n'
500
- : 'Der geschuetzte BLUN-Start ist gerade nicht verfuegbar.\n');
501
- process.exitCode = 1;
502
- return;
503
- }
504
- await installProbe.lease.release();
505
- }
506
-
507
- if (explicitToolsRequest) {
508
- const action = String(ARGS[1] || '').toLowerCase();
509
- const available = availableStandardToolNames({ packageRoot: PKG });
510
- if (action === 'list' && ARGS.length === 2) {
511
- process.stdout.write(`${available.join('\n')}\n`);
512
- return;
513
- }
514
- if (action === 'enable' && ARGS.length > 2) {
515
- const privatePaths = resolveLauncherPrivatePaths();
516
- const selected = [...new Set(ARGS.slice(2))];
517
- const unknown = selected.find((name) => !available.includes(name));
518
- if (unknown) {
519
- process.stderr.write(`Unbekanntes Standard-Tool: ${unknown}\n`);
520
- process.exitCode = 1;
521
- return;
522
- }
523
- const mcpNames = selected.filter((name) => name !== 'telegram');
524
- if (mcpNames.length > 0) {
525
- seedStandardTools({
526
- packageRoot: PKG,
527
- blunDir: privatePaths.blunHome,
528
- names: mcpNames,
529
- });
530
- }
531
- if (selected.includes('telegram')) {
532
- const io = createStartupSecurity();
533
- try { await installTelegramForProfile(PKG, privatePaths.blunHome, io); } finally { await io.close(); }
534
- }
535
- process.stdout.write(`${selected.join('\n')}\n`);
536
- return;
537
- }
538
- process.stderr.write('Usage: blun tools list | blun tools enable <name...>\n');
539
- process.exitCode = 1;
540
- return;
541
- }
542
- if (ARGS.some((arg) => arg === '--version' || arg === '-V')) {
543
- process.stdout.write(`${readPackageVersion()}\n`);
544
- return;
545
- }
546
-
547
- if (explicitUpdateRequest) {
548
- const privatePaths = resolveLauncherPrivatePaths();
549
- const result = await runExplicitUpdate({
550
- currentVersion: readPackageVersion(),
551
- env: process.env,
552
- stdin: process.stdin,
553
- stdout: process.stdout,
554
- stderr: process.stderr,
555
- blunDir: privatePaths.blunHome,
556
- packageRoot: PKG,
557
- noticeLease,
558
- request: ARGS[0],
559
- });
560
- if (result.kind === 'failed') process.exitCode = result.exitCode || 1;
561
- return;
562
- }
563
-
564
- if (isStandaloneHelpRequest(ARGS)) {
565
- const compatibilityError = unsupportedNodeMessage(process.versions.node, process.platform);
566
- if (compatibilityError !== null) {
567
- process.stderr.write(`${compatibilityError}\n`);
568
- process.exitCode = 1;
569
- return;
570
- }
571
- process.stdout.write(launcherHelpText());
572
- const env = createLauncherEnvironment(process.env, mode, readPackageVersion());
573
- const informationalEnv = { ...process.env };
574
- delete informationalEnv.BLUN_HOME;
575
- applyProfileEnvironment(env, resolveLauncherPrivatePaths({ env: informationalEnv }));
576
- process.exitCode = await runInformationalCore(ARGS, env, callerCwd, releaseNotice);
577
- return;
578
- }
579
-
580
- if (isReadOnlyInspectionRequest(ARGS)) {
581
- const compatibilityError = unsupportedNodeMessage(process.versions.node, process.platform);
582
- if (compatibilityError !== null) {
583
- process.stderr.write(`${compatibilityError}\n`);
584
- process.exitCode = 1;
585
- return;
586
- }
587
- const inspectionPaths = resolveLauncherPrivatePaths();
588
- const blunDir = inspectionPaths.blunHome;
589
- require('./verify-bundled-agent-sources.cjs').verifyBundledAgentSources(PKG);
590
- const env = createLauncherEnvironment(process.env, LAUNCHER_MODES.BLUN, readPackageVersion(), blunDir);
591
- applyProfileEnvironment(env, inspectionPaths);
592
- process.exitCode = await runInformationalCore(ARGS, env, callerCwd, releaseNotice);
593
- return;
594
- }
595
-
596
- let privatePaths;
597
- const getPrivatePaths = () => {
598
- privatePaths ||= resolveLauncherPrivatePaths();
599
- return privatePaths;
600
- };
601
- const nodeRuntime = await prepareManagedNodeRuntime({
602
- getBlunDir: () => getPrivatePaths().blunHome,
603
- });
604
- if (nodeRuntime.kind === 'failed') {
605
- process.stderr.write(`${nodeRuntime.message}\n`);
606
- process.exitCode = 1;
607
- return;
608
- }
609
- if (nodeRuntime.kind === 'managed') {
610
- process.stdout.write('BLUN hat die passende Node.js-Laufzeit eingerichtet.\n');
611
- await releaseNotice();
612
- process.exitCode = await spawnManagedLauncher(nodeRuntime.binary, callerCwd);
613
- return;
614
- }
615
-
616
- if (ARGS.some((arg) => arg === '--help' || arg === '-h')) {
617
- process.stdout.write(launcherHelpText());
618
- const env = createLauncherEnvironment(process.env, mode, readPackageVersion());
619
- const informationalEnv = { ...process.env };
620
- delete informationalEnv.BLUN_HOME;
621
- applyProfileEnvironment(env, resolveLauncherPrivatePaths({ env: informationalEnv }));
622
- process.exitCode = await superviseProtectedCore(ARGS, env, callerCwd, releaseNotice);
623
- return;
624
- }
625
-
626
- const blunDir = getPrivatePaths().blunHome;
627
-
628
-
629
- const startupSecurity = createStartupSecurity();
630
- try {
631
- await startupSecurity.ensurePrivateDirectory(blunDir);
632
- // --- 1. Oeffentlicher npm-Update-Dialog. -------------------------------
633
- const updateResult = options.skipUpdateNotice === true
634
- ? { kind: 'continue', reason: 'notice_busy' }
635
- : await runUpdateNotice({
636
- startupSecurity,
637
- currentVersion: readPackageVersion(),
638
- argv: ARGS,
639
- env: process.env,
640
- stdin: process.stdin,
641
- stdout: process.stdout,
642
- stderr: process.stderr,
643
- blunDir,
644
- packageRoot: PKG,
645
- noticeLease,
646
- });
647
- if (updateResult.kind === 'installed' || updateResult.kind === 'update_in_progress') return;
648
-
649
- if (!runtimeLease) {
650
- const runtimeResult = await acquireSharedRuntimeLease({ packageRoot: PKG });
651
- if (!runtimeResult.acquired) {
652
- process.stderr.write('Der geschuetzte BLUN-Start ist gerade nicht verfuegbar.\n');
653
- process.exitCode = 1;
654
- return;
655
- }
656
- runtimeLease = runtimeResult.lease;
657
- }
658
-
659
- // --- 2. Bestehende Konfiguration absichern -------------------------------
660
- // Ein frischer Start bleibt absichtlich ohne statischen Anbieter. /login
661
- // provisioniert King ueber den BLUN-OAuth-Server.
662
- const cfgFile = path.join(blunDir, 'config.toml');
663
- if (fs.existsSync(cfgFile)) await startupSecurity.securePrivateFile(cfgFile);
664
- require('./verify-bundled-agent-sources.cjs').verifyBundledAgentSources(PKG);
665
-
666
- // --- 3. BLUN-Standard-MCPs additiv im Benutzerprofil einrichten ---------
667
- const standardMcpNames = availableStandardToolNames({ packageRoot: PKG })
668
- .filter((name) => name !== 'telegram');
669
- await seedStandardToolsAsync({
670
- io: startupSecurity,
671
- packageRoot: PKG,
672
- blunDir,
673
- names: standardMcpNames,
674
- });
675
-
676
- // --- 4. Eigenes BLUN-Grunddesign als einzigen Standard-Skill installieren
677
- await seedStandardDesignSkillAsync({ packageRoot: PKG, blunDir, io: startupSecurity });
678
- await installManagedAgentSpinePluginAsync({ packageRoot: PKG, blunDir, io: startupSecurity });
679
-
680
- // --- 5. Telegram-Plugin + Token-Vorlage (nur King) -----------------------
681
- if (mode === LAUNCHER_MODES.KING) {
682
- await installTelegramForProfile(PKG, blunDir, startupSecurity);
683
- }
684
-
685
- } finally { await startupSecurity.close(); }
686
-
687
- const nativeOwner = new AbortController();
688
- let nativeStopSignal;
689
- const nativeSignals = new Map();
690
- for (const signal of ['SIGHUP', 'SIGINT', 'SIGTERM']) {
691
- const handler = () => { nativeStopSignal = signal; nativeOwner.abort(); };
692
- nativeSignals.set(signal, handler);
693
- process.once(signal, handler);
694
- }
695
- let nativeModules;
696
- try {
697
- nativeModules = await repairConfiguredNativeModules({
698
- blunDir,
699
- callerCwd,
700
- signal: nativeOwner.signal,
701
- onRepairStart() {
702
- process.stdout.write('BLUN richtet native Node.js-Module fuer die neue Laufzeit ein.\n');
703
- },
704
- });
705
- } catch (error) {
706
- if (!nativeOwner.signal.aborted) throw error;
707
- process.exitCode = nativeStopSignal === 'SIGINT' ? 130 : nativeStopSignal === 'SIGHUP' ? 129 : 143;
708
- return;
709
- } finally {
710
- for (const [signal, handler] of nativeSignals) process.removeListener(signal, handler);
711
- }
712
- if (nativeModules.repaired.length > 0) {
713
- process.stdout.write('Native Node.js-Module sind wieder einsatzbereit.\n');
714
- }
715
-
716
- // --- 6. Start -----------------------------------------------------------
717
- const env = createLauncherEnvironment(process.env, mode, readPackageVersion(), blunDir);
718
- applyProfileEnvironment(env, getPrivatePaths());
719
- process.exitCode = await superviseProtectedCore(
720
- ARGS,
721
- env,
722
- callerCwd,
723
- releaseNotice,
724
- );
725
- } finally {
726
- await releaseNotice();
727
- }
728
- }
729
-
730
- module.exports = {
731
- resolveLauncherPrivatePaths,
732
- runLauncher,
733
- shouldDetachProtectedCore,
734
- spawnManagedLauncher,
735
- };
166
+ const PROFILE = parseExplicitProfileArgs(process.argv.slice(2), launcherModeFromArgv(process.argv));
167
+ const ARGS = PROFILE.args;
168
+
169
+ function applyProfileEnvironment(env, paths) {
170
+ env.BLUN_HOME = paths.blunHome;
171
+ if (PROFILE.name !== undefined) {
172
+ env.BLUN_SHARED_HOME = paths.sharedHome;
173
+ env.BLUN_PROFILE = PROFILE.name;
174
+ } else if (String(env.BLUN_STATE_DIR || '').trim()) {
175
+ env.BLUN_SHARED_HOME = paths.blunHome;
176
+ }
177
+ return env;
178
+ }
179
+
180
+ function normalizeWindowsPath(value) {
181
+ return path.win32.normalize(value).replace(/\\+$/u, '').toLowerCase();
182
+ }
183
+
184
+ function resolveLauncherPrivatePaths(options = {}) {
185
+ const env = options.env || process.env;
186
+ const platform = options.platform || process.platform;
187
+ const configuredHome = String(env.BLUN_HOME || '').trim();
188
+ const selectedProfile = options.profileName ?? PROFILE.name;
189
+ const stateDir = String(env.BLUN_STATE_DIR || '').trim();
190
+ if (stateDir) {
191
+ const paths = platform === 'win32' ? path.win32 : path.posix;
192
+ if (!paths.isAbsolute(stateDir) || (platform === 'win32' && !/^[A-Za-z]:[\\/]/u.test(stateDir))) {
193
+ throw new Error('BLUN_STATE_DIR must be an absolute local path.');
194
+ }
195
+ const blunHome = paths.resolve(stateDir);
196
+ const fsImpl = options.fsImpl || fs;
197
+ let ancestor = blunHome;
198
+ for (;;) {
199
+ try {
200
+ const stat = fsImpl.lstatSync(ancestor);
201
+ const realpath = fsImpl.realpathSync.native || fsImpl.realpathSync;
202
+ const canonical = realpath(ancestor);
203
+ const normalize = platform === 'win32' ? normalizeWindowsPath : paths.normalize;
204
+ if (!stat.isDirectory() || stat.isSymbolicLink() || normalize(canonical) !== normalize(ancestor)) {
205
+ throw new Error('BLUN_STATE_DIR must not traverse a symbolic link or junction.');
206
+ }
207
+ break;
208
+ } catch (error) {
209
+ if (error.code !== 'ENOENT') throw error;
210
+ const parent = paths.dirname(ancestor);
211
+ if (parent === ancestor) throw error;
212
+ ancestor = parent;
213
+ }
214
+ }
215
+ if (selectedProfile !== undefined) {
216
+ // A state override cannot bypass the canonical OS-home/profile guards.
217
+ const profileEnv = { ...env };
218
+ delete profileEnv.BLUN_STATE_DIR;
219
+ const selected = resolveLauncherPrivatePaths({ ...options, env: profileEnv, profileName: selectedProfile });
220
+ const normalize = platform === 'win32' ? normalizeWindowsPath : paths.normalize;
221
+ if (normalize(blunHome) !== normalize(selected.blunHome)) {
222
+ throw new Error('BLUN_STATE_DIR widerspricht dem ausgewaehlten Profil.');
223
+ }
224
+ return selected;
225
+ }
226
+ return { blunHome, userHome: (options.homedir || os.homedir)() };
227
+ }
228
+ if (platform !== 'win32') {
229
+ const posix = path.posix;
230
+ const userHome = (options.homedir || os.homedir)();
231
+ if (selectedProfile !== undefined) {
232
+ const configuredShared = String(env.BLUN_SHARED_HOME || '').trim();
233
+ const sharedHome = configuredShared
234
+ ? posix.resolve(configuredShared)
235
+ : configuredHome && posix.basename(posix.dirname(configuredHome)) === 'profile'
236
+ ? posix.resolve(configuredHome, '..', '..')
237
+ : configuredHome ? posix.resolve(configuredHome) : posix.join(userHome, '.blun');
238
+ const blunHome = resolveSelectedProfile(sharedHome, selectedProfile, posix);
239
+ if (configuredShared && configuredHome && posix.resolve(configuredHome) !== blunHome) {
240
+ throw new Error(`BLUN_HOME passt nicht zum Profil ${selectedProfile}: ${blunHome}`);
241
+ }
242
+ return { blunHome, sharedHome, userHome };
243
+ }
244
+ return {
245
+ blunHome: configuredHome ? path.resolve(configuredHome) : path.join(userHome, '.blun'),
246
+ userHome,
247
+ };
248
+ }
249
+
250
+ const fsImpl = options.fsImpl || fs;
251
+ const userInfo = (options.userInfo || os.userInfo)();
252
+ const reportedHome = String(userInfo?.homedir || '').trim();
253
+ if (!path.win32.isAbsolute(reportedHome) || reportedHome.startsWith('\\\\')) {
254
+ throw new Error('Das lokale Windows-Benutzerprofil konnte nicht sicher bestimmt werden.');
255
+ }
256
+ const resolvedHome = path.win32.resolve(reportedHome);
257
+ const stat = fsImpl.lstatSync(resolvedHome);
258
+ if (!stat.isDirectory() || stat.isSymbolicLink()) {
259
+ throw new Error('Das lokale Windows-Benutzerprofil ist kein vertrauenswuerdiges Verzeichnis.');
260
+ }
261
+ const realpath = fsImpl.realpathSync.native || fsImpl.realpathSync;
262
+ const userHome = path.win32.normalize(realpath(resolvedHome));
263
+ const volumeRoot = path.win32.parse(userHome).root;
264
+ if (!/^[A-Za-z]:\\$/u.test(volumeRoot)
265
+ || normalizeWindowsPath(userHome) !== normalizeWindowsPath(resolvedHome)) {
266
+ throw new Error('Das lokale Windows-Benutzerprofil ist kein kanonischer lokaler Pfad.');
267
+ }
268
+
269
+ const blunHome = path.win32.join(userHome, '.blun');
270
+ if (selectedProfile !== undefined) {
271
+ const profileHome = resolveSelectedProfile(blunHome, selectedProfile, path.win32);
272
+ const configuredShared = String(env.BLUN_SHARED_HOME || '').trim();
273
+ if (configuredShared && normalizeWindowsPath(path.win32.resolve(configuredShared)) !== normalizeWindowsPath(blunHome)) {
274
+ throw new Error(`BLUN_SHARED_HOME muss unter Windows exakt im Windows-Benutzerprofil liegen: ${blunHome}`);
275
+ }
276
+ if (configuredHome && normalizeWindowsPath(path.win32.resolve(configuredHome)) !== normalizeWindowsPath(profileHome)
277
+ && normalizeWindowsPath(path.win32.resolve(configuredHome)) !== normalizeWindowsPath(blunHome)) {
278
+ throw new Error(`BLUN_HOME passt nicht zum Profil ${selectedProfile}: ${profileHome}`);
279
+ }
280
+ return { blunHome: profileHome, sharedHome: blunHome, userHome };
281
+ }
282
+
283
+ if (configuredHome
284
+ && normalizeWindowsPath(path.win32.resolve(configuredHome)) !== normalizeWindowsPath(blunHome)) {
285
+ throw new Error(`BLUN_HOME muss unter Windows exakt im Windows-Benutzerprofil liegen: ${blunHome}`);
286
+ }
287
+ return { blunHome, userHome };
288
+ }
289
+
290
+ function readPackageVersion() {
291
+ const { version } = JSON.parse(fs.readFileSync(path.join(PKG, 'package.json'), 'utf8'));
292
+ if (typeof version !== 'string' || version.length === 0) {
293
+ throw new Error('Ungueltige Paketversion in package.json');
294
+ }
295
+ return version;
296
+ }
297
+
298
+ function shouldDetachProtectedCore(options = {}) {
299
+ const platform = options.platform || process.platform;
300
+ const stdinIsTTY = Object.hasOwn(options, 'stdinIsTTY')
301
+ ? options.stdinIsTTY
302
+ : process.stdin.isTTY;
303
+ return platform !== 'win32' || stdinIsTTY !== true;
304
+ }
305
+
306
+ function spawnProtectedCore(args, env, cwd) {
307
+ const terminalOwner = process.platform === 'win32' && process.stdin.isTTY === true;
308
+ const child = spawn(
309
+ process.execPath,
310
+ [path.join(PKG, 'bin', 'core-bootstrap.js'), ...args],
311
+ {
312
+ cwd,
313
+ detached: shouldDetachProtectedCore(),
314
+ env: { ...env, BLUN_TERMINAL_OWNER: terminalOwner ? '1' : '0' },
315
+ stdio: ['inherit', 'inherit', 'inherit', 'ipc'],
316
+ windowsHide: true,
317
+ },
318
+ );
319
+ let loadedSettled = false;
320
+ let completedSettled = false;
321
+ let operatorSignal;
322
+ let resolveLoaded;
323
+ let resolveCompleted;
324
+ const loaded = new Promise((resolve) => { resolveLoaded = resolve; });
325
+ const completed = new Promise((resolve) => { resolveCompleted = resolve; });
326
+ const settleLoaded = (value) => {
327
+ if (loadedSettled) return;
328
+ loadedSettled = true;
329
+ resolveLoaded(value);
330
+ };
331
+ const settleCompleted = (result) => {
332
+ if (completedSettled) return;
333
+ completedSettled = true;
334
+ for (const [signal, handler] of signalHandlers) process.removeListener(signal, handler);
335
+ settleLoaded(false);
336
+ resolveCompleted(operatorSignal === undefined ? result : { ...result, signal: operatorSignal });
337
+ };
338
+ const signalHandlers = new Map();
339
+ for (const signal of ['SIGHUP', 'SIGINT', 'SIGTERM']) {
340
+ const handler = () => {
341
+ operatorSignal = signal;
342
+ try {
343
+ child.kill(signal);
344
+ } catch {}
345
+ };
346
+ signalHandlers.set(signal, handler);
347
+ process.once(signal, handler);
348
+ }
349
+ child.on('message', (message) => {
350
+ if (message?.type !== CORE_LOADED_MESSAGE) return;
351
+ settleLoaded(true);
352
+ if (terminalOwner) return;
353
+ try {
354
+ child.disconnect();
355
+ } catch {}
356
+ });
357
+ child.once('error', (error) => settleCompleted({ error }));
358
+ child.once('exit', (code, signal) => settleCompleted({ code, signal }));
359
+ return { child, completed, loaded };
360
+ }
361
+
362
+ async function runInformationalCore(args, env, cwd, releaseNotice) {
363
+ const core = spawnProtectedCore(args, env, cwd);
364
+ await core.loaded;
365
+ await releaseNotice();
366
+ const result = await core.completed;
367
+ if (result.error) throw result.error;
368
+ return Number.isInteger(result.code) ? result.code : exitCodeForChild(result, false);
369
+ }
370
+
371
+ async function superviseProtectedCore(args, env, cwd, releaseNotice) {
372
+ let noticeReleased = false;
373
+ for (;;) {
374
+ const core = spawnProtectedCore(args, env, cwd);
375
+ const loaded = await core.loaded;
376
+ if (!noticeReleased) {
377
+ noticeReleased = true;
378
+ await releaseNotice();
379
+ }
380
+ const result = await core.completed;
381
+ const exitCode = result.error ? 1 : exitCodeForChild(result, loaded);
382
+ const intentionalStop = consumeIntentionalStopMarker({
383
+ homeDir: env.BLUN_HOME, childPid: core.child.pid, nowMs: Date.now(),
384
+ });
385
+ recordRuntimeExit({
386
+ homeDir: env.BLUN_HOME, source: 'launcher', kind: result.error ? 'child-error' : 'child-exit',
387
+ exitCode, signal: result.signal, phase: loaded ? 'runtime' : 'startup',
388
+ cliVersion: env.BLUN_PUBLIC_PACKAGE_VERSION, profile: env.BLUN_PROFILE,
389
+ loaded, childPid: core.child.pid, error: result.error,
390
+ });
391
+ if (intentionalStop || !isAbnormalCoreExit(result, loaded)) {
392
+ if (result.error) throw result.error;
393
+ return exitCode;
394
+ }
395
+ const claim = claimLauncherRestart({ homeDir: env.BLUN_HOME, nowMs: Date.now() });
396
+ try {
397
+ appendLauncherStatus({
398
+ homeDir: env.BLUN_HOME,
399
+ stateDir: env.BLUN_TELEGRAM_STATE_DIR
400
+ || path.join(env.BLUN_SHARED_HOME || env.BLUN_HOME, 'channels', 'telegram'),
401
+ nowMs: Date.now(), attempt: claim.attempt, limit: claim.limit, exitCode, signal: result.signal,
402
+ kind: claim.allowed ? 'launcher-restart' : 'launcher-restart-exhausted',
403
+ });
404
+ } catch {}
405
+ if (!claim.allowed) {
406
+ if (result.error) throw result.error;
407
+ return exitCode;
408
+ }
409
+ await new Promise((resolve) => setTimeout(resolve, restartDelayMs(claim.attempt)));
410
+ }
411
+ }
412
+
413
+ function exitCodeForChild(result, loaded) {
414
+ if (!loaded && result.code === 75) return 0;
415
+ if (Number.isInteger(result.code)) return result.code;
416
+ if (result.signal === 'SIGINT') return 130;
417
+ if (result.signal === 'SIGTERM') return 143;
418
+ return 1;
419
+ }
420
+
421
+ async function installTelegramForProfile(packageRoot, blunDir, io) {
422
+ await installManagedTelegramPluginAsync({ packageRoot, blunDir, io });
423
+ const channelsDir = path.join(blunDir, 'channels');
424
+ const channelDir = path.join(channelsDir, 'telegram');
425
+ await io.ensurePrivateDirectory(channelsDir);
426
+ await io.ensurePrivateDirectory(channelDir);
427
+ const envFile = path.join(channelDir, '.env');
428
+ if (!fs.existsSync(envFile)) {
429
+ await io.writePrivateFile(envFile, 'BLUN_TELEGRAM_BOT_TOKEN=HIER_DEIN_BOT_TOKEN_EINFUEGEN\n');
430
+ } else {
431
+ await io.securePrivateFile(envFile);
432
+ }
433
+ }
434
+
435
+ function spawnManagedLauncher(binary, cwd) {
436
+ return new Promise((resolve, reject) => {
437
+ const child = spawn(binary, process.argv.slice(1), {
438
+ cwd,
439
+ env: process.env,
440
+ stdio: 'inherit',
441
+ windowsHide: true,
442
+ });
443
+ child.once('error', reject);
444
+ child.once('exit', (code, signal) => {
445
+ if (Number.isInteger(code)) {
446
+ resolve(code);
447
+ return;
448
+ }
449
+ if (signal === 'SIGINT') {
450
+ resolve(130);
451
+ return;
452
+ }
453
+ if (signal === 'SIGTERM') {
454
+ resolve(143);
455
+ return;
456
+ }
457
+ resolve(1);
458
+ });
459
+ });
460
+ }
461
+
462
+ async function runLauncher(options = {}) {
463
+ const callerCwd = process.cwd();
464
+ const mode = options.mode || launcherModeFromArgv(process.argv);
465
+ if (PROFILE.name !== undefined) {
466
+ applyProfileEnvironment(process.env, resolveLauncherPrivatePaths());
467
+ }
468
+ const explicitUpdateRequest = isNpmPackageUpdateRequest(ARGS);
469
+ const explicitToolsRequest = String(ARGS[0] || '').toLowerCase() === 'tools';
470
+ const noticeResult = options.skipUpdateNotice === true
471
+ ? { acquired: true, lease: { assertOwned() {}, async release() {} } }
472
+ : options.noticeLease
473
+ ? { acquired: true, lease: options.noticeLease }
474
+ : await tryAcquireUpdateLease({ packageRoot: PKG, role: 'notice' });
475
+ if (!noticeResult.acquired) {
476
+ if (explicitUpdateRequest) {
477
+ process.stderr.write('Das Update konnte nicht verifiziert werden.\n');
478
+ process.exitCode = 1;
479
+ }
480
+ return;
481
+ }
482
+ const noticeLease = noticeResult.lease;
483
+ let runtimeLease = options.runtimeLease;
484
+ let noticeReleased = false;
485
+ const releaseNotice = async () => {
486
+ if (noticeReleased) return;
487
+ noticeReleased = true;
488
+ await noticeLease.release();
489
+ await runtimeLease?.release();
490
+ };
491
+
492
+ try {
493
+ if (!runtimeLease && !explicitUpdateRequest) {
494
+ const installProbe = await tryAcquireUpdateLease({ packageRoot: PKG, role: 'install' });
495
+ if (!installProbe.acquired) {
496
+ process.stderr.write(explicitUpdateRequest
497
+ ? 'Das Update konnte nicht verifiziert werden.\n'
498
+ : 'Der geschützte BLUN-Start ist gerade nicht verfügbar.\n');
499
+ process.exitCode = 1;
500
+ return;
501
+ }
502
+ await installProbe.lease.release();
503
+ }
504
+
505
+ if (explicitToolsRequest) {
506
+ const action = String(ARGS[1] || '').toLowerCase();
507
+ const available = availableStandardToolNames({ packageRoot: PKG });
508
+ if (action === 'list' && ARGS.length === 2) {
509
+ process.stdout.write(`${available.join('\n')}\n`);
510
+ return;
511
+ }
512
+ if (action === 'enable' && ARGS.length > 2) {
513
+ const privatePaths = resolveLauncherPrivatePaths();
514
+ const selected = [...new Set(ARGS.slice(2))];
515
+ const unknown = selected.find((name) => !available.includes(name));
516
+ if (unknown) {
517
+ process.stderr.write(`Unbekanntes Standard-Tool: ${unknown}\n`);
518
+ process.exitCode = 1;
519
+ return;
520
+ }
521
+ const mcpNames = selected.filter((name) => name !== 'telegram');
522
+ if (mcpNames.length > 0) {
523
+ seedStandardTools({
524
+ packageRoot: PKG,
525
+ blunDir: privatePaths.blunHome,
526
+ names: mcpNames,
527
+ });
528
+ }
529
+ if (selected.includes('telegram')) {
530
+ const io = createStartupSecurity();
531
+ try { await installTelegramForProfile(PKG, privatePaths.blunHome, io); } finally { await io.close(); }
532
+ }
533
+ process.stdout.write(`${selected.join('\n')}\n`);
534
+ return;
535
+ }
536
+ process.stderr.write('Usage: blun tools list | blun tools enable <name...>\n');
537
+ process.exitCode = 1;
538
+ return;
539
+ }
540
+ if (ARGS.some((arg) => arg === '--version' || arg === '-V')) {
541
+ process.stdout.write(`${readPackageVersion()}\n`);
542
+ return;
543
+ }
544
+
545
+ if (explicitUpdateRequest) {
546
+ const privatePaths = resolveLauncherPrivatePaths();
547
+ const result = await runExplicitUpdate({
548
+ currentVersion: readPackageVersion(),
549
+ env: process.env,
550
+ stdin: process.stdin,
551
+ stdout: process.stdout,
552
+ stderr: process.stderr,
553
+ blunDir: privatePaths.blunHome,
554
+ packageRoot: PKG,
555
+ noticeLease,
556
+ request: ARGS[0],
557
+ });
558
+ if (result.kind === 'failed') process.exitCode = result.exitCode || 1;
559
+ return;
560
+ }
561
+
562
+ if (isStandaloneHelpRequest(ARGS)) {
563
+ const compatibilityError = unsupportedNodeMessage(process.versions.node, process.platform);
564
+ if (compatibilityError !== null) {
565
+ process.stderr.write(`${compatibilityError}\n`);
566
+ process.exitCode = 1;
567
+ return;
568
+ }
569
+ process.stdout.write(launcherHelpText());
570
+ const env = createLauncherEnvironment(process.env, mode, readPackageVersion());
571
+ const informationalEnv = { ...process.env };
572
+ delete informationalEnv.BLUN_HOME;
573
+ applyProfileEnvironment(env, resolveLauncherPrivatePaths({ env: informationalEnv }));
574
+ process.exitCode = await runInformationalCore(ARGS, env, callerCwd, releaseNotice);
575
+ return;
576
+ }
577
+
578
+ if (isReadOnlyInspectionRequest(ARGS)) {
579
+ const compatibilityError = unsupportedNodeMessage(process.versions.node, process.platform);
580
+ if (compatibilityError !== null) {
581
+ process.stderr.write(`${compatibilityError}\n`);
582
+ process.exitCode = 1;
583
+ return;
584
+ }
585
+ const inspectionPaths = resolveLauncherPrivatePaths();
586
+ const blunDir = inspectionPaths.blunHome;
587
+ require('./verify-bundled-agent-sources.cjs').verifyBundledAgentSources(PKG);
588
+ const env = createLauncherEnvironment(process.env, LAUNCHER_MODES.BLUN, readPackageVersion(), blunDir);
589
+ applyProfileEnvironment(env, inspectionPaths);
590
+ process.exitCode = await runInformationalCore(ARGS, env, callerCwd, releaseNotice);
591
+ return;
592
+ }
593
+
594
+ let privatePaths;
595
+ const getPrivatePaths = () => {
596
+ privatePaths ||= resolveLauncherPrivatePaths();
597
+ return privatePaths;
598
+ };
599
+ const nodeRuntime = await prepareManagedNodeRuntime({
600
+ getBlunDir: () => getPrivatePaths().blunHome,
601
+ });
602
+ if (nodeRuntime.kind === 'failed') {
603
+ process.stderr.write(`${nodeRuntime.message}\n`);
604
+ process.exitCode = 1;
605
+ return;
606
+ }
607
+ if (nodeRuntime.kind === 'managed') {
608
+ process.stdout.write('BLUN hat die passende Node.js-Laufzeit eingerichtet.\n');
609
+ await releaseNotice();
610
+ process.exitCode = await spawnManagedLauncher(nodeRuntime.binary, callerCwd);
611
+ return;
612
+ }
613
+
614
+ if (ARGS.some((arg) => arg === '--help' || arg === '-h')) {
615
+ process.stdout.write(launcherHelpText());
616
+ const env = createLauncherEnvironment(process.env, mode, readPackageVersion());
617
+ const informationalEnv = { ...process.env };
618
+ delete informationalEnv.BLUN_HOME;
619
+ applyProfileEnvironment(env, resolveLauncherPrivatePaths({ env: informationalEnv }));
620
+ process.exitCode = await superviseProtectedCore(ARGS, env, callerCwd, releaseNotice);
621
+ return;
622
+ }
623
+
624
+ const blunDir = getPrivatePaths().blunHome;
625
+
626
+
627
+ const startupSecurity = createStartupSecurity();
628
+ try {
629
+ await startupSecurity.ensurePrivateDirectory(blunDir);
630
+ // --- 1. Oeffentlicher npm-Update-Dialog. -------------------------------
631
+ const updateResult = options.skipUpdateNotice === true
632
+ ? { kind: 'continue', reason: 'notice_busy' }
633
+ : await runUpdateNotice({
634
+ startupSecurity,
635
+ currentVersion: readPackageVersion(),
636
+ argv: ARGS,
637
+ env: process.env,
638
+ stdin: process.stdin,
639
+ stdout: process.stdout,
640
+ stderr: process.stderr,
641
+ blunDir,
642
+ packageRoot: PKG,
643
+ noticeLease,
644
+ });
645
+ if (updateResult.kind === 'installed' || updateResult.kind === 'update_in_progress') return;
646
+
647
+ if (!runtimeLease) {
648
+ const runtimeResult = await acquireSharedRuntimeLease({ packageRoot: PKG });
649
+ if (!runtimeResult.acquired) {
650
+ process.stderr.write('Der geschützte BLUN-Start ist gerade nicht verfügbar.\n');
651
+ process.exitCode = 1;
652
+ return;
653
+ }
654
+ runtimeLease = runtimeResult.lease;
655
+ }
656
+
657
+ // --- 2. Bestehende Konfiguration absichern -------------------------------
658
+ // Ein frischer Start bleibt absichtlich ohne statischen Anbieter. /login
659
+ // provisioniert King ueber den BLUN-OAuth-Server.
660
+ const cfgFile = path.join(blunDir, 'config.toml');
661
+ if (fs.existsSync(cfgFile)) await startupSecurity.securePrivateFile(cfgFile);
662
+ require('./verify-bundled-agent-sources.cjs').verifyBundledAgentSources(PKG);
663
+
664
+ // --- 3. BLUN-Standard-MCPs additiv im Benutzerprofil einrichten ---------
665
+ await require('./retired-bundled-plugins.cjs').retireBundledPlugins({ blunDir, io: startupSecurity });
666
+
667
+ // --- 5. Telegram-Plugin + Token-Vorlage (nur King) -----------------------
668
+ if (mode === LAUNCHER_MODES.KING) {
669
+ await installTelegramForProfile(PKG, blunDir, startupSecurity);
670
+ }
671
+
672
+ } finally { await startupSecurity.close(); }
673
+
674
+ const nativeOwner = new AbortController();
675
+ let nativeStopSignal;
676
+ const nativeSignals = new Map();
677
+ for (const signal of ['SIGHUP', 'SIGINT', 'SIGTERM']) {
678
+ const handler = () => { nativeStopSignal = signal; nativeOwner.abort(); };
679
+ nativeSignals.set(signal, handler);
680
+ process.once(signal, handler);
681
+ }
682
+ let nativeModules;
683
+ try {
684
+ nativeModules = await repairConfiguredNativeModules({
685
+ blunDir,
686
+ callerCwd,
687
+ signal: nativeOwner.signal,
688
+ onRepairStart() {
689
+ process.stdout.write('BLUN richtet native Node.js-Module fuer die neue Laufzeit ein.\n');
690
+ },
691
+ });
692
+ } catch (error) {
693
+ if (!nativeOwner.signal.aborted) throw error;
694
+ process.exitCode = nativeStopSignal === 'SIGINT' ? 130 : nativeStopSignal === 'SIGHUP' ? 129 : 143;
695
+ return;
696
+ } finally {
697
+ for (const [signal, handler] of nativeSignals) process.removeListener(signal, handler);
698
+ }
699
+ if (nativeModules.repaired.length > 0) {
700
+ process.stdout.write('Native Node.js-Module sind wieder einsatzbereit.\n');
701
+ }
702
+
703
+ // --- 6. Start -----------------------------------------------------------
704
+ const env = createLauncherEnvironment(process.env, mode, readPackageVersion(), blunDir);
705
+ applyProfileEnvironment(env, getPrivatePaths());
706
+ process.exitCode = await superviseProtectedCore(
707
+ ARGS,
708
+ env,
709
+ callerCwd,
710
+ releaseNotice,
711
+ );
712
+ } finally {
713
+ await releaseNotice();
714
+ }
715
+ }
716
+
717
+ module.exports = {
718
+ resolveLauncherPrivatePaths,
719
+ runLauncher,
720
+ shouldDetachProtectedCore,
721
+ spawnManagedLauncher,
722
+ };