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,405 +1,339 @@
1
- 'use strict';
2
-
3
- const { createHash, randomUUID } = require('node:crypto');
4
- const fs = require('node:fs');
5
- const path = require('node:path');
6
- const { renamePrivateStaging, copyTelegramFiles } = require('./rename-private-staging.cjs');
7
- const { copySelectedAgentSpinePluginAsync, selectedAgentSpineRoot, describeAgentSpineSelection, copySelectedAgentSpinePlugin } = require('./managed-plugin-selection.cjs');
8
-
9
- const {
10
- ensurePrivateDirectory,
11
- securePrivateFile,
12
- writePrivateFile,
13
- } = require('./private-paths');
14
-
15
- function isObject(value) {
16
- return typeof value === 'object' && value !== null && !Array.isArray(value);
17
- }
18
-
19
- function readInstalledPlugins(filePath) {
20
- if (!fs.existsSync(filePath)) return { version: 1, plugins: [] };
21
-
22
- const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8'));
23
- if (!isObject(parsed) || parsed.version !== 1 || !Array.isArray(parsed.plugins)
24
- || !parsed.plugins.every(isObject)) {
25
- throw new Error(`Ungültige Plugin-Konfiguration: ${filePath}`);
26
- }
27
- return parsed;
28
- }
29
-
30
- function updatedInstalledPlugins(installed, pluginRoot, now, pluginId = 'telegram') {
31
- const previous = installed.plugins.find((plugin) => plugin.id === pluginId);
32
- const previousCapabilities = isObject(previous?.capabilities) ? previous.capabilities : {};
33
- const previousMcpServers = isObject(previousCapabilities.mcpServers)
34
- ? previousCapabilities.mcpServers : {};
35
- const previousTelegramMcp = isObject(previousMcpServers[pluginId])
36
- ? previousMcpServers[pluginId] : {};
37
- const telegram = {
38
- ...previous,
39
- id: pluginId,
40
- root: pluginRoot,
41
- source: 'local-path',
42
- enabled: true,
43
- installedAt: typeof previous?.installedAt === 'string' && previous.installedAt.length > 0
44
- ? previous.installedAt : now,
45
- updatedAt: now,
46
- capabilities: {
47
- ...previousCapabilities,
48
- mcpServers: {
49
- ...previousMcpServers,
50
- [pluginId]: { ...previousTelegramMcp, enabled: previousTelegramMcp.enabled === false && pluginId === 'agent-spine' ? false : true },
51
- },
52
- },
53
- };
54
-
55
- const plugins = [];
56
- let replaced = false;
57
- for (const plugin of installed.plugins) {
58
- if (plugin.id !== pluginId) {
59
- plugins.push(plugin);
60
- } else if (!replaced) {
61
- plugins.push(telegram);
62
- replaced = true;
63
- }
64
- }
65
- if (!replaced) plugins.push(telegram);
66
- return { ...installed, version: 1, plugins };
67
- }
68
-
69
- function writeInstalledPlugins(filePath, installed) {
70
- const temporaryPath = path.join(
71
- path.dirname(filePath),
72
- `.${path.basename(filePath)}.${process.pid}.${randomUUID()}.tmp`,
73
- );
74
- try {
75
- writePrivateFile(temporaryPath, `${JSON.stringify(installed, null, 2)}\n`);
76
- fs.renameSync(temporaryPath, filePath);
77
- } catch (error) {
78
- fs.rmSync(temporaryPath, { force: true });
79
- throw error;
80
- }
81
- }
82
-
83
- // Only reuse the exact shipped payload, never a linked/replaced/foreign tree.
84
- // This bounded payload check does not enumerate any profile-history directory.
85
- function verifyReusableTelegram(pluginRoot, sourceRoot, identity) {
86
- const same = (a, b) => process.platform === 'win32'
87
- ? path.resolve(a).toLowerCase() === path.resolve(b).toLowerCase()
88
- : path.resolve(a) === path.resolve(b);
89
- const verify = (source, target, expected) => {
90
- const before = fs.lstatSync(target);
91
- if (before.isSymbolicLink() || !same(fs.realpathSync(target), target)
92
- || (expected && (before.dev !== expected.dev || before.ino !== expected.ino))) {
93
- throw new Error('Managed Telegram identity changed; refusing locked reuse');
94
- }
95
- if (fs.lstatSync(source).isDirectory()) {
96
- if (!before.isDirectory()) throw new Error('Invalid managed Telegram directory');
97
- for (const name of fs.readdirSync(source)) verify(path.join(source, name), path.join(target, name));
98
- } else {
99
- if (!before.isFile() || before.nlink !== 1
100
- || !fs.readFileSync(source).equals(fs.readFileSync(target))) {
101
- throw new Error('Managed Telegram payload differs; refusing locked reuse');
102
- }
103
- }
104
- const after = fs.lstatSync(target);
105
- if (after.dev !== before.dev || after.ino !== before.ino || after.isSymbolicLink()
106
- || !same(fs.realpathSync(target), target)) throw new Error('Managed Telegram identity changed');
107
- };
108
- verify(sourceRoot, pluginRoot, identity);
109
- }
110
-
111
- // Hash only the bounded shipped manifest; target checks retain identity, realpath,
112
- // reparse and hardlink rejection. Never trust a user-writable signature marker.
113
- const TELEGRAM_MANIFEST = '.blun-telegram-payload.json';
114
- function telegramManifest(sourceRoot) {
115
- const result=[];
116
- function visit(current, relative='') {
117
- if(result.length>=4096 || relative.split('/').length>64) throw new Error('Telegram payload limit');
118
- const before=fs.lstatSync(current);
119
- if(before.isSymbolicLink() || path.resolve(fs.realpathSync(current)).toLowerCase()!==path.resolve(current).toLowerCase()) throw new Error('Telegram identity changed');
120
- if(before.isDirectory()) {
121
- result.push({path:relative,type:'D'});
122
- for(const name of fs.readdirSync(current).sort()) {
123
- if(name===TELEGRAM_MANIFEST) throw new Error('Reserved Telegram payload name');
124
- visit(path.join(current,name),relative?relative+'/'+name:name);
125
- }
126
- } else if(before.isFile() && before.nlink===1) result.push({path:relative,type:'F'});
127
- else throw new Error('Invalid Telegram source');
128
- const after=fs.lstatSync(current);
129
- if(before.dev!==after.dev || before.ino!==after.ino || after.isSymbolicLink()) throw new Error('Telegram identity changed');
130
- }
131
- visit(sourceRoot);return result;
132
- }
133
- function telegramDigest(sourceRoot, manifest=telegramManifest(sourceRoot)) {
134
- if(!Array.isArray(manifest) || manifest.length<1 || manifest.length>4096) throw new Error('Invalid Telegram manifest');
135
- const hash=createHash('sha256'),seen=new Set();
136
- for(const entry of manifest) {
137
- if(!entry || typeof entry.path!=='string' || !['D','F'].includes(entry.type)
138
- || entry.path.split('/').length>64 || entry.path.includes('\\') || entry.path.includes(':')
139
- || (entry.path!=='' && entry.path.split('/').some(p=>!p || p==='.' || p==='..' || /[ .]$/.test(p)))
140
- || seen.has(entry.path.toLowerCase()) || (entry.path!=='' && !seen.has((path.posix.dirname(entry.path)==='.'?'':path.posix.dirname(entry.path)).toLowerCase()))) throw new Error('Invalid Telegram manifest path');
141
- if(entry.path==='' && (seen.size!==0 || entry.type!=='D')) throw new Error('Invalid Telegram manifest root');
142
- seen.add(entry.path.toLowerCase());
143
- const current=path.join(sourceRoot,...entry.path.split('/')),stat=fs.lstatSync(current);
144
- if(stat.isSymbolicLink() || path.resolve(fs.realpathSync(current)).toLowerCase()!==path.resolve(current).toLowerCase()) throw new Error('Telegram identity changed');
145
- // Preserve the original digest byte grammar (including native separators).
146
- const relative=entry.path.split('/').join(path.sep);
147
- if(entry.type==='D') {if(!stat.isDirectory())throw new Error('Invalid Telegram directory');hash.update('D\0'+relative+'\0');}
148
- else {
149
- if(!stat.isFile() || stat.nlink!==1) throw new Error('Invalid Telegram file');
150
- const data=fs.readFileSync(current);hash.update('F\0'+relative+'\0'+data.length+'\0');hash.update(data);
151
- }
152
- const after=fs.lstatSync(current);
153
- if(after.dev!==stat.dev || after.ino!==stat.ino || after.isSymbolicLink() || (entry.type==='F' && after.nlink!==1)) throw new Error('Telegram identity changed');
154
- }
155
- return hash.digest('hex');
156
- }
157
- function telegramVersion(pluginRoot) {
158
- return /^telegram-([a-f0-9]{64})(?:-([a-f0-9-]{36}))?$/.exec(path.basename(pluginRoot));
159
- }
160
- function verifyPreviousTelegram(pluginRoot,sourceRoot,digest,manifest) {
161
- const version=telegramVersion(pluginRoot);
162
- if(version && version[1]===digest) {
163
- if(telegramDigest(pluginRoot,manifest)!==digest)throw new Error('Telegram digest mismatch');
164
- return true;
165
- }
166
- if(!version) return telegramDigest(pluginRoot,manifest)===digest;
167
- const manifestFile=path.join(pluginRoot,TELEGRAM_MANIFEST);
168
- let previous;
169
- if(fs.existsSync(manifestFile)) {
170
- const before=fs.lstatSync(manifestFile);
171
- if(!before.isFile() || before.isSymbolicLink() || before.nlink!==1 || before.size>1048576) throw new Error('Invalid Telegram manifest');
172
- previous=JSON.parse(fs.readFileSync(manifestFile,'utf8'));
173
- const after=fs.lstatSync(manifestFile);
174
- if(before.dev!==after.dev || before.ino!==after.ino || after.nlink!==1)throw new Error('Telegram manifest identity changed');
175
- }
176
- if(telegramDigest(pluginRoot,previous)!==version[1])throw new Error('Telegram digest mismatch');
177
- return false;
178
- }
179
- function publishTelegram(stagingRoot,desiredRoot,sourceRoot,digest,manifest,blunDir) {
180
- try {renamePrivateStaging(stagingRoot,desiredRoot);return desiredRoot;}
181
- catch(error) {
182
- // Windows may report an existing nonempty destination as EPERM/EACCES;
183
- // the retry helper can also reject before rename. Existence is not trust.
184
- if(!fs.existsSync(desiredRoot)) throw error;
185
- assertTelegramScope(blunDir,desiredRoot);
186
- try {
187
- verifyReusableTelegram(desiredRoot,sourceRoot,fs.lstatSync(desiredRoot));
188
- if(telegramDigest(desiredRoot,manifest)!==digest)throw new Error('Telegram digest mismatch');
189
- return desiredRoot;
190
- } catch(conflict) {
191
- process.emitWarning('BLUN_MANAGED_TELEGRAM_PUBLISH_CONFLICT '+desiredRoot,{code:'BLUN_MANAGED_TELEGRAM_PUBLISH_CONFLICT'});
192
- const ownRoot=desiredRoot+'-'+randomUUID();
193
- assertTelegramScope(blunDir,ownRoot);
194
- renamePrivateStaging(stagingRoot,ownRoot);return ownRoot;
195
- }
196
- }
197
- }
198
- function assertTelegramScope(blunDir, pluginRoot) {
199
- const managed = path.resolve(blunDir,'plugins','managed');
200
- if (path.dirname(path.resolve(pluginRoot)) !== managed || !(path.basename(pluginRoot)==='telegram' || telegramVersion(pluginRoot))) throw new Error('Invalid Telegram root');
201
- for (const directory of [blunDir,path.dirname(managed),managed]) {
202
- const stat = fs.lstatSync(directory);
203
- if (!stat.isDirectory() || stat.isSymbolicLink() || path.resolve(fs.realpathSync(directory)).toLowerCase() !== path.resolve(directory).toLowerCase()) throw new Error('Invalid Telegram parent identity');
204
- }
205
- }
206
- function installedUnchanged(installed, updated) {
207
- const strip = doc => ({ ...doc, plugins: doc.plugins.map(({ updatedAt, ...record }) => record) });
208
- return JSON.stringify(strip(installed)) === JSON.stringify(strip(updated));
209
- }
210
- function warnBusy(error) {
211
- if (!['EBUSY','EPERM','EACCES'].includes(error.code)) throw error;
212
- process.emitWarning('Der gehaltene alte Telegram-Ordner bleibt unverändert erhalten.', {code:'BLUN_MANAGED_TELEGRAM_BUSY_REUSED'});
213
- }
214
- function installManagedTelegramPlugin({ packageRoot, blunDir, now = new Date().toISOString() }) {
215
- const sourceRoot=path.join(packageRoot,'telegram-plugin');
216
- const pluginsDir=path.join(blunDir,'plugins'),managedDir=path.join(pluginsDir,'managed');
217
- const installedFile=path.join(pluginsDir,'installed.json');
218
- ensurePrivateDirectory(blunDir);ensurePrivateDirectory(pluginsDir);
219
- const installed=readInstalledPlugins(installedFile);
220
- const records=installed.plugins.filter(p=>p.id==='telegram');
221
- if(records.length>1) throw new Error('Ambiguous Telegram registration');
222
- const manifest=telegramManifest(sourceRoot),digest=telegramDigest(sourceRoot,manifest);
223
- const previousRoot=records[0]?.root || path.join(managedDir,'telegram');
224
- if(fs.existsSync(previousRoot)) {
225
- assertTelegramScope(blunDir,previousRoot);
226
- // An old immutable version may differ from the current source, but must
227
- // still have its name-bound digest. Legacy trees are reused only if shipped
228
- // bytes match; otherwise the safe new version is installed beside them.
229
- if(verifyPreviousTelegram(previousRoot,sourceRoot,digest,manifest)) {
230
- verifyReusableTelegram(previousRoot,sourceRoot,fs.lstatSync(previousRoot));
231
- const updated=updatedInstalledPlugins(installed,previousRoot,now);
232
- if(!installedUnchanged(installed,updated)) writeInstalledPlugins(installedFile,updated);
233
- return {installedFile,pluginRoot:previousRoot,reused:true};
234
- }
235
- }
236
- ensurePrivateDirectory(pluginsDir);ensurePrivateDirectory(managedDir);
237
- let pluginRoot=path.join(managedDir,`telegram-${digest}`);
238
- assertTelegramScope(blunDir,pluginRoot);
239
- if(fs.existsSync(pluginRoot)) {
240
- try {verifyReusableTelegram(pluginRoot,sourceRoot,fs.lstatSync(pluginRoot));}
241
- catch(error) {
242
- process.emitWarning('BLUN_MANAGED_TELEGRAM_PUBLISH_CONFLICT '+pluginRoot,{code:'BLUN_MANAGED_TELEGRAM_PUBLISH_CONFLICT'});
243
- pluginRoot+='-'+randomUUID();assertTelegramScope(blunDir,pluginRoot);
244
- }
245
- }
246
- if(!fs.existsSync(pluginRoot)) {
247
- const stagingRoot=path.join(managedDir,`.telegram-${process.pid}-${randomUUID()}.tmp`);
248
- try {
249
- copyTelegramFiles(sourceRoot,stagingRoot);
250
- verifyReusableTelegram(stagingRoot,sourceRoot,fs.lstatSync(stagingRoot));
251
- if(telegramDigest(stagingRoot)!==digest) throw new Error('Telegram source changed');
252
- writePrivateFile(path.join(stagingRoot,TELEGRAM_MANIFEST),JSON.stringify(manifest));
253
- pluginRoot=publishTelegram(stagingRoot,pluginRoot,sourceRoot,digest,manifest,blunDir);
254
- verifyReusableTelegram(pluginRoot,sourceRoot,fs.lstatSync(pluginRoot));
255
- } finally {if(fs.existsSync(stagingRoot)) {try {fs.rmSync(stagingRoot,{recursive:true,force:true});}catch(error){warnBusy(error);}}}
256
- }
257
- const updated=updatedInstalledPlugins(installed,pluginRoot,now);
258
- if(!installedUnchanged(installed,updated)) writeInstalledPlugins(installedFile,updated);
259
- // Old trees may still be executed by another King. Retain, never rename or
260
- // recursively delete them on the startup critical path; explicit maintenance.
261
- if(previousRoot!==pluginRoot && fs.existsSync(previousRoot)) process.emitWarning('Das bisherige Telegram-Plugin bleibt für laufende Sitzungen erhalten.',{code:'BLUN_MANAGED_TELEGRAM_OLD_RETAINED'});
262
- return {installedFile,pluginRoot,reused:false};
263
- }
264
-
265
- function installManagedAgentSpinePlugin({ packageRoot, blunDir, now = new Date().toISOString() }) {
266
- const installedFile = path.join(blunDir, 'plugins', 'installed.json');
267
- ensurePrivateDirectory(blunDir);
268
- ensurePrivateDirectory(path.dirname(installedFile));
269
- if (fs.existsSync(installedFile)) securePrivateFile(installedFile);
270
- const installed = readInstalledPlugins(installedFile);
271
- const records = installed.plugins.filter(plugin => plugin.id === 'agent-spine');
272
- if (records.length > 1) throw new Error('Ambiguous AgentSpine registration');
273
- const selected = selectedAgentSpineRoot({ installed, blunDir });
274
- if (selected) return { installedFile, pluginRoot: selected, reused: true, selected: true };
275
- if (records[0]?.enabled === false) {
276
- return { installedFile, pluginRoot: records[0].root, reused: true, disabled: true };
277
- }
278
- if (records[0]) {
279
- const currentRoot = records[0].root;
280
- if (typeof currentRoot !== 'string' || !path.isAbsolute(currentRoot)) {
281
- throw new Error('Invalid AgentSpine registration root');
282
- }
283
- const managed = path.resolve(blunDir, 'plugins', 'managed');
284
- const sameDirectory = (left, right) => process.platform === 'win32'
285
- ? left.toLowerCase() === right.toLowerCase() : left === right;
286
- if (!sameDirectory(path.dirname(path.resolve(currentRoot)), managed)
287
- || !/^agent-spine-[a-f0-9]{64}$/.test(path.basename(currentRoot))) {
288
- return { installedFile, pluginRoot: currentRoot, reused: true, custom: true };
289
- }
290
- // An upgrade must not conceal changes to the previous immutable default.
291
- describeAgentSpineSelection({ blunDir, pluginRoot: currentRoot });
292
- }
293
- const pluginRoot = copySelectedAgentSpinePlugin({ blunDir, sourceRoot: path.join(packageRoot, 'agent-spine-plugin') });
294
- if (records[0]?.root === pluginRoot) return { installedFile, pluginRoot, reused: true };
295
- writeInstalledPlugins(installedFile, updatedInstalledPlugins(installed, pluginRoot, now, 'agent-spine'));
296
- return { installedFile, pluginRoot, reused: false };
297
- }
298
-
299
- async function writeInstalledPluginsAsync(filePath, installed, io) {
300
- const temporaryPath = path.join(
301
- path.dirname(filePath),
302
- `.${path.basename(filePath)}.${process.pid}.${randomUUID()}.tmp`,
303
- );
304
- try {
305
- await io.writePrivateFile(temporaryPath, `${JSON.stringify(installed, null, 2)}\n`);
306
- fs.renameSync(temporaryPath, filePath);
307
- } catch (error) {
308
- fs.rmSync(temporaryPath, { force: true });
309
- throw error;
310
- }
311
- }
312
-
313
- // Only reuse the exact shipped payload, never a linked/replaced/foreign tree.
314
- // This bounded payload check does not enumerate any profile-history directory.
315
- async function installManagedTelegramPluginAsync({ packageRoot, blunDir, now = new Date().toISOString(), io }) {
316
- const sourceRoot=path.join(packageRoot,'telegram-plugin');
317
- const pluginsDir=path.join(blunDir,'plugins'),managedDir=path.join(pluginsDir,'managed');
318
- const installedFile=path.join(pluginsDir,'installed.json');
319
- await io.ensurePrivateDirectory(blunDir);await io.ensurePrivateDirectory(pluginsDir);
320
- const installed=readInstalledPlugins(installedFile);
321
- const records=installed.plugins.filter(p=>p.id==='telegram');
322
- if(records.length>1) throw new Error('Ambiguous Telegram registration');
323
- const manifest=telegramManifest(sourceRoot),digest=telegramDigest(sourceRoot,manifest);
324
- const previousRoot=records[0]?.root || path.join(managedDir,'telegram');
325
- if(fs.existsSync(previousRoot)) {
326
- assertTelegramScope(blunDir,previousRoot);
327
- // An old immutable version may differ from the current source, but must
328
- // still have its name-bound digest. Legacy trees are reused only if shipped
329
- // bytes match; otherwise the safe new version is installed beside them.
330
- if(verifyPreviousTelegram(previousRoot,sourceRoot,digest,manifest)) {
331
- verifyReusableTelegram(previousRoot,sourceRoot,fs.lstatSync(previousRoot));
332
- const updated=updatedInstalledPlugins(installed,previousRoot,now);
333
- if(!installedUnchanged(installed,updated)) await writeInstalledPluginsAsync(installedFile,updated,io);
334
- return {installedFile,pluginRoot:previousRoot,reused:true};
335
- }
336
- }
337
- await io.ensurePrivateDirectory(pluginsDir);await io.ensurePrivateDirectory(managedDir);
338
- let pluginRoot=path.join(managedDir,`telegram-${digest}`);
339
- assertTelegramScope(blunDir,pluginRoot);
340
- if(fs.existsSync(pluginRoot)) {
341
- try {verifyReusableTelegram(pluginRoot,sourceRoot,fs.lstatSync(pluginRoot));}
342
- catch(error) {
343
- process.emitWarning('BLUN_MANAGED_TELEGRAM_PUBLISH_CONFLICT '+pluginRoot,{code:'BLUN_MANAGED_TELEGRAM_PUBLISH_CONFLICT'});
344
- pluginRoot+='-'+randomUUID();assertTelegramScope(blunDir,pluginRoot);
345
- }
346
- }
347
- if(!fs.existsSync(pluginRoot)) {
348
- const stagingRoot=path.join(managedDir,`.telegram-${process.pid}-${randomUUID()}.tmp`);
349
- try {
350
- await io.copyPayload(sourceRoot,stagingRoot);
351
- verifyReusableTelegram(stagingRoot,sourceRoot,fs.lstatSync(stagingRoot));
352
- if(telegramDigest(stagingRoot)!==digest) throw new Error('Telegram source changed');
353
- await io.writePrivateFile(path.join(stagingRoot,TELEGRAM_MANIFEST),JSON.stringify(manifest));
354
- pluginRoot=publishTelegram(stagingRoot,pluginRoot,sourceRoot,digest,manifest,blunDir);
355
- verifyReusableTelegram(pluginRoot,sourceRoot,fs.lstatSync(pluginRoot));
356
- } finally {if(fs.existsSync(stagingRoot)) {try {fs.rmSync(stagingRoot,{recursive:true,force:true});}catch(error){warnBusy(error);}}}
357
- }
358
- const updated=updatedInstalledPlugins(installed,pluginRoot,now);
359
- if(!installedUnchanged(installed,updated)) await writeInstalledPluginsAsync(installedFile,updated,io);
360
- // Old trees may still be executed by another King. Retain, never rename or
361
- // recursively delete them on the startup critical path; explicit maintenance.
362
- if(previousRoot!==pluginRoot && fs.existsSync(previousRoot)) process.emitWarning('Das bisherige Telegram-Plugin bleibt für laufende Sitzungen erhalten.',{code:'BLUN_MANAGED_TELEGRAM_OLD_RETAINED'});
363
- return {installedFile,pluginRoot,reused:false};
364
- }
365
-
366
- async function installManagedAgentSpinePluginAsync({ packageRoot, blunDir, now = new Date().toISOString(), io }) {
367
- const installedFile = path.join(blunDir, 'plugins', 'installed.json');
368
- await io.ensurePrivateDirectory(blunDir);
369
- await io.ensurePrivateDirectory(path.dirname(installedFile));
370
- const installed = readInstalledPlugins(installedFile);
371
- const records = installed.plugins.filter(plugin => plugin.id === 'agent-spine');
372
- if (records.length > 1) throw new Error('Ambiguous AgentSpine registration');
373
- const selected = selectedAgentSpineRoot({ installed, blunDir });
374
- if (selected) return { installedFile, pluginRoot: selected, reused: true, selected: true };
375
- if (records[0]?.enabled === false) {
376
- return { installedFile, pluginRoot: records[0].root, reused: true, disabled: true };
377
- }
378
- if (records[0]) {
379
- const currentRoot = records[0].root;
380
- if (typeof currentRoot !== 'string' || !path.isAbsolute(currentRoot)) {
381
- throw new Error('Invalid AgentSpine registration root');
382
- }
383
- const managed = path.resolve(blunDir, 'plugins', 'managed');
384
- const sameDirectory = (left, right) => process.platform === 'win32'
385
- ? left.toLowerCase() === right.toLowerCase() : left === right;
386
- if (!sameDirectory(path.dirname(path.resolve(currentRoot)), managed)
387
- || !/^agent-spine-[a-f0-9]{64}$/.test(path.basename(currentRoot))) {
388
- return { installedFile, pluginRoot: currentRoot, reused: true, custom: true };
389
- }
390
- // An upgrade must not conceal changes to the previous immutable default.
391
- describeAgentSpineSelection({ blunDir, pluginRoot: currentRoot });
392
- }
393
- const pluginRoot = await copySelectedAgentSpinePluginAsync({ blunDir, io, sourceRoot: path.join(packageRoot, 'agent-spine-plugin') });
394
- if (records[0]?.root === pluginRoot) return { installedFile, pluginRoot, reused: true };
395
- await writeInstalledPluginsAsync(installedFile, updatedInstalledPlugins(installed, pluginRoot, now, 'agent-spine'), io);
396
- return { installedFile, pluginRoot, reused: false };
397
- }
398
-
399
- module.exports = {
400
- installManagedAgentSpinePluginAsync,
401
- installManagedTelegramPluginAsync,
402
- installManagedAgentSpinePlugin,
403
- installManagedTelegramPlugin,
404
- readInstalledPlugins,
405
- };
1
+ 'use strict';
2
+
3
+ const { createHash, randomUUID } = require('node:crypto');
4
+ const fs = require('node:fs');
5
+ const path = require('node:path');
6
+ const { renamePrivateStaging, copyTelegramFiles } = require('./rename-private-staging.cjs');
7
+
8
+ const {
9
+ ensurePrivateDirectory,
10
+ securePrivateFile,
11
+ writePrivateFile,
12
+ } = require('./private-paths');
13
+
14
+ function isObject(value) {
15
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
16
+ }
17
+
18
+ function readInstalledPlugins(filePath) {
19
+ if (!fs.existsSync(filePath)) return { version: 1, plugins: [] };
20
+
21
+ const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8'));
22
+ if (!isObject(parsed) || parsed.version !== 1 || !Array.isArray(parsed.plugins)
23
+ || !parsed.plugins.every(isObject)) {
24
+ throw new Error(`Ungültige Plugin-Konfiguration: ${filePath}`);
25
+ }
26
+ return parsed;
27
+ }
28
+
29
+ function updatedInstalledPlugins(installed, pluginRoot, now, pluginId = 'telegram') {
30
+ const previous = installed.plugins.find((plugin) => plugin.id === pluginId);
31
+ const previousCapabilities = isObject(previous?.capabilities) ? previous.capabilities : {};
32
+ const previousMcpServers = isObject(previousCapabilities.mcpServers)
33
+ ? previousCapabilities.mcpServers : {};
34
+ const previousTelegramMcp = isObject(previousMcpServers[pluginId])
35
+ ? previousMcpServers[pluginId] : {};
36
+ const telegram = {
37
+ ...previous,
38
+ id: pluginId,
39
+ root: pluginRoot,
40
+ source: 'local-path',
41
+ enabled: true,
42
+ installedAt: typeof previous?.installedAt === 'string' && previous.installedAt.length > 0
43
+ ? previous.installedAt : now,
44
+ updatedAt: now,
45
+ capabilities: {
46
+ ...previousCapabilities,
47
+ mcpServers: {
48
+ ...previousMcpServers,
49
+ [pluginId]: { ...previousTelegramMcp, enabled: true },
50
+ },
51
+ },
52
+ };
53
+
54
+ const plugins = [];
55
+ let replaced = false;
56
+ for (const plugin of installed.plugins) {
57
+ if (plugin.id !== pluginId) {
58
+ plugins.push(plugin);
59
+ } else if (!replaced) {
60
+ plugins.push(telegram);
61
+ replaced = true;
62
+ }
63
+ }
64
+ if (!replaced) plugins.push(telegram);
65
+ return { ...installed, version: 1, plugins };
66
+ }
67
+
68
+ function writeInstalledPlugins(filePath, installed) {
69
+ const temporaryPath = path.join(
70
+ path.dirname(filePath),
71
+ `.${path.basename(filePath)}.${process.pid}.${randomUUID()}.tmp`,
72
+ );
73
+ try {
74
+ writePrivateFile(temporaryPath, `${JSON.stringify(installed, null, 2)}\n`);
75
+ fs.renameSync(temporaryPath, filePath);
76
+ } catch (error) {
77
+ fs.rmSync(temporaryPath, { force: true });
78
+ throw error;
79
+ }
80
+ }
81
+
82
+ // Only reuse the exact shipped payload, never a linked/replaced/foreign tree.
83
+ // This bounded payload check does not enumerate any profile-history directory.
84
+ function verifyReusableTelegram(pluginRoot, sourceRoot, identity) {
85
+ const same = (a, b) => process.platform === 'win32'
86
+ ? path.resolve(a).toLowerCase() === path.resolve(b).toLowerCase()
87
+ : path.resolve(a) === path.resolve(b);
88
+ const verify = (source, target, expected) => {
89
+ const before = fs.lstatSync(target);
90
+ if (before.isSymbolicLink() || !same(fs.realpathSync(target), target)
91
+ || (expected && (before.dev !== expected.dev || before.ino !== expected.ino))) {
92
+ throw new Error('Managed Telegram identity changed; refusing locked reuse');
93
+ }
94
+ if (fs.lstatSync(source).isDirectory()) {
95
+ if (!before.isDirectory()) throw new Error('Invalid managed Telegram directory');
96
+ for (const name of fs.readdirSync(source)) verify(path.join(source, name), path.join(target, name));
97
+ } else {
98
+ if (!before.isFile() || before.nlink !== 1
99
+ || !fs.readFileSync(source).equals(fs.readFileSync(target))) {
100
+ throw new Error('Managed Telegram payload differs; refusing locked reuse');
101
+ }
102
+ }
103
+ const after = fs.lstatSync(target);
104
+ if (after.dev !== before.dev || after.ino !== before.ino || after.isSymbolicLink()
105
+ || !same(fs.realpathSync(target), target)) throw new Error('Managed Telegram identity changed');
106
+ };
107
+ verify(sourceRoot, pluginRoot, identity);
108
+ }
109
+
110
+ // Hash only the bounded shipped manifest; target checks retain identity, realpath,
111
+ // reparse and hardlink rejection. Never trust a user-writable signature marker.
112
+ const TELEGRAM_MANIFEST = '.blun-telegram-payload.json';
113
+ function telegramManifest(sourceRoot) {
114
+ const result=[];
115
+ function visit(current, relative='') {
116
+ if(result.length>=4096 || relative.split('/').length>64) throw new Error('Telegram payload limit');
117
+ const before=fs.lstatSync(current);
118
+ if(before.isSymbolicLink() || path.resolve(fs.realpathSync(current)).toLowerCase()!==path.resolve(current).toLowerCase()) throw new Error('Telegram identity changed');
119
+ if(before.isDirectory()) {
120
+ result.push({path:relative,type:'D'});
121
+ for(const name of fs.readdirSync(current).sort()) {
122
+ if(name===TELEGRAM_MANIFEST) throw new Error('Reserved Telegram payload name');
123
+ visit(path.join(current,name),relative?relative+'/'+name:name);
124
+ }
125
+ } else if(before.isFile() && before.nlink===1) result.push({path:relative,type:'F'});
126
+ else throw new Error('Invalid Telegram source');
127
+ const after=fs.lstatSync(current);
128
+ if(before.dev!==after.dev || before.ino!==after.ino || after.isSymbolicLink()) throw new Error('Telegram identity changed');
129
+ }
130
+ visit(sourceRoot);return result;
131
+ }
132
+ function telegramDigest(sourceRoot, manifest=telegramManifest(sourceRoot)) {
133
+ if(!Array.isArray(manifest) || manifest.length<1 || manifest.length>4096) throw new Error('Invalid Telegram manifest');
134
+ const hash=createHash('sha256'),seen=new Set();
135
+ for(const entry of manifest) {
136
+ if(!entry || typeof entry.path!=='string' || !['D','F'].includes(entry.type)
137
+ || entry.path.split('/').length>64 || entry.path.includes('\\') || entry.path.includes(':')
138
+ || (entry.path!=='' && entry.path.split('/').some(p=>!p || p==='.' || p==='..' || /[ .]$/.test(p)))
139
+ || seen.has(entry.path.toLowerCase()) || (entry.path!=='' && !seen.has((path.posix.dirname(entry.path)==='.'?'':path.posix.dirname(entry.path)).toLowerCase()))) throw new Error('Invalid Telegram manifest path');
140
+ if(entry.path==='' && (seen.size!==0 || entry.type!=='D')) throw new Error('Invalid Telegram manifest root');
141
+ seen.add(entry.path.toLowerCase());
142
+ const current=path.join(sourceRoot,...entry.path.split('/')),stat=fs.lstatSync(current);
143
+ if(stat.isSymbolicLink() || path.resolve(fs.realpathSync(current)).toLowerCase()!==path.resolve(current).toLowerCase()) throw new Error('Telegram identity changed');
144
+ // Preserve the original digest byte grammar (including native separators).
145
+ const relative=entry.path.split('/').join(path.sep);
146
+ if(entry.type==='D') {if(!stat.isDirectory())throw new Error('Invalid Telegram directory');hash.update('D\0'+relative+'\0');}
147
+ else {
148
+ if(!stat.isFile() || stat.nlink!==1) throw new Error('Invalid Telegram file');
149
+ const data=fs.readFileSync(current);hash.update('F\0'+relative+'\0'+data.length+'\0');hash.update(data);
150
+ }
151
+ const after=fs.lstatSync(current);
152
+ if(after.dev!==stat.dev || after.ino!==stat.ino || after.isSymbolicLink() || (entry.type==='F' && after.nlink!==1)) throw new Error('Telegram identity changed');
153
+ }
154
+ return hash.digest('hex');
155
+ }
156
+ function telegramVersion(pluginRoot) {
157
+ return /^telegram-([a-f0-9]{64})(?:-([a-f0-9-]{36}))?$/.exec(path.basename(pluginRoot));
158
+ }
159
+ function verifyPreviousTelegram(pluginRoot,sourceRoot,digest,manifest) {
160
+ const version=telegramVersion(pluginRoot);
161
+ if(version && version[1]===digest) {
162
+ if(telegramDigest(pluginRoot,manifest)!==digest)throw new Error('Telegram digest mismatch');
163
+ return true;
164
+ }
165
+ if(!version) return telegramDigest(pluginRoot,manifest)===digest;
166
+ const manifestFile=path.join(pluginRoot,TELEGRAM_MANIFEST);
167
+ let previous;
168
+ if(fs.existsSync(manifestFile)) {
169
+ const before=fs.lstatSync(manifestFile);
170
+ if(!before.isFile() || before.isSymbolicLink() || before.nlink!==1 || before.size>1048576) throw new Error('Invalid Telegram manifest');
171
+ previous=JSON.parse(fs.readFileSync(manifestFile,'utf8'));
172
+ const after=fs.lstatSync(manifestFile);
173
+ if(before.dev!==after.dev || before.ino!==after.ino || after.nlink!==1)throw new Error('Telegram manifest identity changed');
174
+ }
175
+ if(telegramDigest(pluginRoot,previous)!==version[1])throw new Error('Telegram digest mismatch');
176
+ return false;
177
+ }
178
+ function publishTelegram(stagingRoot,desiredRoot,sourceRoot,digest,manifest,blunDir) {
179
+ try {renamePrivateStaging(stagingRoot,desiredRoot);return desiredRoot;}
180
+ catch(error) {
181
+ // Windows may report an existing nonempty destination as EPERM/EACCES;
182
+ // the retry helper can also reject before rename. Existence is not trust.
183
+ if(!fs.existsSync(desiredRoot)) throw error;
184
+ assertTelegramScope(blunDir,desiredRoot);
185
+ try {
186
+ verifyReusableTelegram(desiredRoot,sourceRoot,fs.lstatSync(desiredRoot));
187
+ if(telegramDigest(desiredRoot,manifest)!==digest)throw new Error('Telegram digest mismatch');
188
+ return desiredRoot;
189
+ } catch(conflict) {
190
+ process.emitWarning('BLUN_MANAGED_TELEGRAM_PUBLISH_CONFLICT '+desiredRoot,{code:'BLUN_MANAGED_TELEGRAM_PUBLISH_CONFLICT'});
191
+ const ownRoot=desiredRoot+'-'+randomUUID();
192
+ assertTelegramScope(blunDir,ownRoot);
193
+ renamePrivateStaging(stagingRoot,ownRoot);return ownRoot;
194
+ }
195
+ }
196
+ }
197
+ function assertTelegramScope(blunDir, pluginRoot) {
198
+ const managed = path.resolve(blunDir,'plugins','managed');
199
+ if (path.dirname(path.resolve(pluginRoot)) !== managed || !(path.basename(pluginRoot)==='telegram' || telegramVersion(pluginRoot))) throw new Error('Invalid Telegram root');
200
+ for (const directory of [blunDir,path.dirname(managed),managed]) {
201
+ const stat = fs.lstatSync(directory);
202
+ if (!stat.isDirectory() || stat.isSymbolicLink() || path.resolve(fs.realpathSync(directory)).toLowerCase() !== path.resolve(directory).toLowerCase()) throw new Error('Invalid Telegram parent identity');
203
+ }
204
+ }
205
+ function installedUnchanged(installed, updated) {
206
+ const strip = doc => ({ ...doc, plugins: doc.plugins.map(({ updatedAt, ...record }) => record) });
207
+ return JSON.stringify(strip(installed)) === JSON.stringify(strip(updated));
208
+ }
209
+ function warnBusy(error) {
210
+ if (!['EBUSY','EPERM','EACCES'].includes(error.code)) throw error;
211
+ process.emitWarning('Der gehaltene alte Telegram-Ordner bleibt unverändert erhalten.', {code:'BLUN_MANAGED_TELEGRAM_BUSY_REUSED'});
212
+ }
213
+ function installManagedTelegramPlugin({ packageRoot, blunDir, now = new Date().toISOString() }) {
214
+ const sourceRoot=path.join(packageRoot,'telegram-plugin');
215
+ const pluginsDir=path.join(blunDir,'plugins'),managedDir=path.join(pluginsDir,'managed');
216
+ const installedFile=path.join(pluginsDir,'installed.json');
217
+ ensurePrivateDirectory(blunDir);ensurePrivateDirectory(pluginsDir);
218
+ const installed=readInstalledPlugins(installedFile);
219
+ const records=installed.plugins.filter(p=>p.id==='telegram');
220
+ if(records.length>1) throw new Error('Ambiguous Telegram registration');
221
+ const manifest=telegramManifest(sourceRoot),digest=telegramDigest(sourceRoot,manifest);
222
+ const previousRoot=records[0]?.root || path.join(managedDir,'telegram');
223
+ if(fs.existsSync(previousRoot)) {
224
+ assertTelegramScope(blunDir,previousRoot);
225
+ // An old immutable version may differ from the current source, but must
226
+ // still have its name-bound digest. Legacy trees are reused only if shipped
227
+ // bytes match; otherwise the safe new version is installed beside them.
228
+ if(verifyPreviousTelegram(previousRoot,sourceRoot,digest,manifest)) {
229
+ verifyReusableTelegram(previousRoot,sourceRoot,fs.lstatSync(previousRoot));
230
+ const updated=updatedInstalledPlugins(installed,previousRoot,now);
231
+ if(!installedUnchanged(installed,updated)) writeInstalledPlugins(installedFile,updated);
232
+ return {installedFile,pluginRoot:previousRoot,reused:true};
233
+ }
234
+ }
235
+ ensurePrivateDirectory(pluginsDir);ensurePrivateDirectory(managedDir);
236
+ let pluginRoot=path.join(managedDir,`telegram-${digest}`);
237
+ assertTelegramScope(blunDir,pluginRoot);
238
+ if(fs.existsSync(pluginRoot)) {
239
+ try {verifyReusableTelegram(pluginRoot,sourceRoot,fs.lstatSync(pluginRoot));}
240
+ catch(error) {
241
+ process.emitWarning('BLUN_MANAGED_TELEGRAM_PUBLISH_CONFLICT '+pluginRoot,{code:'BLUN_MANAGED_TELEGRAM_PUBLISH_CONFLICT'});
242
+ pluginRoot+='-'+randomUUID();assertTelegramScope(blunDir,pluginRoot);
243
+ }
244
+ }
245
+ if(!fs.existsSync(pluginRoot)) {
246
+ const stagingRoot=path.join(managedDir,`.telegram-${process.pid}-${randomUUID()}.tmp`);
247
+ try {
248
+ copyTelegramFiles(sourceRoot,stagingRoot);
249
+ verifyReusableTelegram(stagingRoot,sourceRoot,fs.lstatSync(stagingRoot));
250
+ if(telegramDigest(stagingRoot)!==digest) throw new Error('Telegram source changed');
251
+ writePrivateFile(path.join(stagingRoot,TELEGRAM_MANIFEST),JSON.stringify(manifest));
252
+ pluginRoot=publishTelegram(stagingRoot,pluginRoot,sourceRoot,digest,manifest,blunDir);
253
+ verifyReusableTelegram(pluginRoot,sourceRoot,fs.lstatSync(pluginRoot));
254
+ } finally {if(fs.existsSync(stagingRoot)) {try {fs.rmSync(stagingRoot,{recursive:true,force:true});}catch(error){warnBusy(error);}}}
255
+ }
256
+ const updated=updatedInstalledPlugins(installed,pluginRoot,now);
257
+ if(!installedUnchanged(installed,updated)) writeInstalledPlugins(installedFile,updated);
258
+ // Old trees may still be executed by another King. Retain, never rename or
259
+ // recursively delete them on the startup critical path; explicit maintenance.
260
+ if(previousRoot!==pluginRoot && fs.existsSync(previousRoot)) process.emitWarning('Das bisherige Telegram-Plugin bleibt für laufende Sitzungen erhalten.',{code:'BLUN_MANAGED_TELEGRAM_OLD_RETAINED'});
261
+ return {installedFile,pluginRoot,reused:false};
262
+ }
263
+
264
+
265
+
266
+ async function writeInstalledPluginsAsync(filePath, installed, io) {
267
+ const temporaryPath = path.join(
268
+ path.dirname(filePath),
269
+ `.${path.basename(filePath)}.${process.pid}.${randomUUID()}.tmp`,
270
+ );
271
+ try {
272
+ await io.writePrivateFile(temporaryPath, `${JSON.stringify(installed, null, 2)}\n`);
273
+ fs.renameSync(temporaryPath, filePath);
274
+ } catch (error) {
275
+ fs.rmSync(temporaryPath, { force: true });
276
+ throw error;
277
+ }
278
+ }
279
+
280
+ // Only reuse the exact shipped payload, never a linked/replaced/foreign tree.
281
+ // This bounded payload check does not enumerate any profile-history directory.
282
+ async function installManagedTelegramPluginAsync({ packageRoot, blunDir, now = new Date().toISOString(), io }) {
283
+ const sourceRoot=path.join(packageRoot,'telegram-plugin');
284
+ const pluginsDir=path.join(blunDir,'plugins'),managedDir=path.join(pluginsDir,'managed');
285
+ const installedFile=path.join(pluginsDir,'installed.json');
286
+ await io.ensurePrivateDirectory(blunDir);await io.ensurePrivateDirectory(pluginsDir);
287
+ const installed=readInstalledPlugins(installedFile);
288
+ const records=installed.plugins.filter(p=>p.id==='telegram');
289
+ if(records.length>1) throw new Error('Ambiguous Telegram registration');
290
+ const manifest=telegramManifest(sourceRoot),digest=telegramDigest(sourceRoot,manifest);
291
+ const previousRoot=records[0]?.root || path.join(managedDir,'telegram');
292
+ if(fs.existsSync(previousRoot)) {
293
+ assertTelegramScope(blunDir,previousRoot);
294
+ // An old immutable version may differ from the current source, but must
295
+ // still have its name-bound digest. Legacy trees are reused only if shipped
296
+ // bytes match; otherwise the safe new version is installed beside them.
297
+ if(verifyPreviousTelegram(previousRoot,sourceRoot,digest,manifest)) {
298
+ verifyReusableTelegram(previousRoot,sourceRoot,fs.lstatSync(previousRoot));
299
+ const updated=updatedInstalledPlugins(installed,previousRoot,now);
300
+ if(!installedUnchanged(installed,updated)) await writeInstalledPluginsAsync(installedFile,updated,io);
301
+ return {installedFile,pluginRoot:previousRoot,reused:true};
302
+ }
303
+ }
304
+ await io.ensurePrivateDirectory(pluginsDir);await io.ensurePrivateDirectory(managedDir);
305
+ let pluginRoot=path.join(managedDir,`telegram-${digest}`);
306
+ assertTelegramScope(blunDir,pluginRoot);
307
+ if(fs.existsSync(pluginRoot)) {
308
+ try {verifyReusableTelegram(pluginRoot,sourceRoot,fs.lstatSync(pluginRoot));}
309
+ catch(error) {
310
+ process.emitWarning('BLUN_MANAGED_TELEGRAM_PUBLISH_CONFLICT '+pluginRoot,{code:'BLUN_MANAGED_TELEGRAM_PUBLISH_CONFLICT'});
311
+ pluginRoot+='-'+randomUUID();assertTelegramScope(blunDir,pluginRoot);
312
+ }
313
+ }
314
+ if(!fs.existsSync(pluginRoot)) {
315
+ const stagingRoot=path.join(managedDir,`.telegram-${process.pid}-${randomUUID()}.tmp`);
316
+ try {
317
+ await io.copyPayload(sourceRoot,stagingRoot);
318
+ verifyReusableTelegram(stagingRoot,sourceRoot,fs.lstatSync(stagingRoot));
319
+ if(telegramDigest(stagingRoot)!==digest) throw new Error('Telegram source changed');
320
+ await io.writePrivateFile(path.join(stagingRoot,TELEGRAM_MANIFEST),JSON.stringify(manifest));
321
+ pluginRoot=publishTelegram(stagingRoot,pluginRoot,sourceRoot,digest,manifest,blunDir);
322
+ verifyReusableTelegram(pluginRoot,sourceRoot,fs.lstatSync(pluginRoot));
323
+ } finally {if(fs.existsSync(stagingRoot)) {try {fs.rmSync(stagingRoot,{recursive:true,force:true});}catch(error){warnBusy(error);}}}
324
+ }
325
+ const updated=updatedInstalledPlugins(installed,pluginRoot,now);
326
+ if(!installedUnchanged(installed,updated)) await writeInstalledPluginsAsync(installedFile,updated,io);
327
+ // Old trees may still be executed by another King. Retain, never rename or
328
+ // recursively delete them on the startup critical path; explicit maintenance.
329
+ if(previousRoot!==pluginRoot && fs.existsSync(previousRoot)) process.emitWarning('Das bisherige Telegram-Plugin bleibt für laufende Sitzungen erhalten.',{code:'BLUN_MANAGED_TELEGRAM_OLD_RETAINED'});
330
+ return {installedFile,pluginRoot,reused:false};
331
+ }
332
+
333
+
334
+
335
+ module.exports = {
336
+ installManagedTelegramPluginAsync,
337
+ installManagedTelegramPlugin,
338
+ readInstalledPlugins,
339
+ };