blun-king-cli 9.1.631 → 9.1.633

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.
@@ -17,11 +17,12 @@ const {
17
17
  launcherHelpText,
18
18
  launcherModeFromArgv,
19
19
  } = require('./launcher-mode');
20
- const { installManagedTelegramPlugin, installManagedAgentSpinePlugin } = require('./plugin-bootstrap');
20
+ const { installManagedTelegramPluginAsync, installManagedAgentSpinePluginAsync } = require('./plugin-bootstrap');
21
21
  const {
22
22
  availableStandardToolNames,
23
- seedStandardDesignSkill,
23
+ seedStandardDesignSkillAsync,
24
24
  seedStandardTools,
25
+ seedStandardToolsAsync,
25
26
  } = require('./standard-tools-bootstrap');
26
27
  const { CORE_LOADED_MESSAGE } = require('./core-bootstrap');
27
28
  const {
@@ -35,6 +36,7 @@ const { repairConfiguredNativeModules } = require('./native-module-repair');
35
36
  const { acquireSharedRuntimeLease, tryAcquireUpdateLease } = require('./update-lease');
36
37
  const { runExplicitUpdate, runUpdateNotice } = require('./update-notice');
37
38
  const {
39
+ createStartupSecurity,
38
40
  ensurePrivateDirectory,
39
41
  securePrivateFile,
40
42
  writePrivateFile,
@@ -418,17 +420,17 @@ function exitCodeForChild(result, loaded) {
418
420
  return 1;
419
421
  }
420
422
 
421
- function installTelegramForProfile(packageRoot, blunDir) {
422
- installManagedTelegramPlugin({ packageRoot, blunDir });
423
+ async function installTelegramForProfile(packageRoot, blunDir, io) {
424
+ await installManagedTelegramPluginAsync({ packageRoot, blunDir, io });
423
425
  const channelsDir = path.join(blunDir, 'channels');
424
426
  const channelDir = path.join(channelsDir, 'telegram');
425
- ensurePrivateDirectory(channelsDir);
426
- ensurePrivateDirectory(channelDir);
427
+ await io.ensurePrivateDirectory(channelsDir);
428
+ await io.ensurePrivateDirectory(channelDir);
427
429
  const envFile = path.join(channelDir, '.env');
428
430
  if (!fs.existsSync(envFile)) {
429
- writeTelegramTemplate(envFile, 'BLUN_TELEGRAM_BOT_TOKEN=HIER_DEIN_BOT_TOKEN_EINFUEGEN\n');
431
+ await io.writePrivateFile(envFile, 'BLUN_TELEGRAM_BOT_TOKEN=HIER_DEIN_BOT_TOKEN_EINFUEGEN\n');
430
432
  } else {
431
- securePrivateFile(envFile);
433
+ await io.securePrivateFile(envFile);
432
434
  }
433
435
  }
434
436
 
@@ -527,7 +529,8 @@ async function runLauncher(options = {}) {
527
529
  });
528
530
  }
529
531
  if (selected.includes('telegram')) {
530
- installTelegramForProfile(PKG, privatePaths.blunHome);
532
+ const io = createStartupSecurity();
533
+ try { await installTelegramForProfile(PKG, privatePaths.blunHome, io); } finally { await io.close(); }
531
534
  }
532
535
  process.stdout.write(`${selected.join('\n')}\n`);
533
536
  return;
@@ -621,12 +624,16 @@ async function runLauncher(options = {}) {
621
624
  }
622
625
 
623
626
  const blunDir = getPrivatePaths().blunHome;
624
- ensurePrivateDirectory(blunDir);
625
627
 
628
+
629
+ const startupSecurity = createStartupSecurity();
630
+ try {
631
+ await startupSecurity.ensurePrivateDirectory(blunDir);
626
632
  // --- 1. Oeffentlicher npm-Update-Dialog. -------------------------------
627
633
  const updateResult = options.skipUpdateNotice === true
628
634
  ? { kind: 'continue', reason: 'notice_busy' }
629
635
  : await runUpdateNotice({
636
+ startupSecurity,
630
637
  currentVersion: readPackageVersion(),
631
638
  argv: ARGS,
632
639
  env: process.env,
@@ -653,27 +660,30 @@ async function runLauncher(options = {}) {
653
660
  // Ein frischer Start bleibt absichtlich ohne statischen Anbieter. /login
654
661
  // provisioniert King ueber den BLUN-OAuth-Server.
655
662
  const cfgFile = path.join(blunDir, 'config.toml');
656
- if (fs.existsSync(cfgFile)) securePrivateFile(cfgFile);
663
+ if (fs.existsSync(cfgFile)) await startupSecurity.securePrivateFile(cfgFile);
657
664
  require('./verify-bundled-agent-sources.cjs').verifyBundledAgentSources(PKG);
658
665
 
659
666
  // --- 3. BLUN-Standard-MCPs additiv im Benutzerprofil einrichten ---------
660
667
  const standardMcpNames = availableStandardToolNames({ packageRoot: PKG })
661
668
  .filter((name) => name !== 'telegram');
662
- seedStandardTools({
669
+ await seedStandardToolsAsync({
670
+ io: startupSecurity,
663
671
  packageRoot: PKG,
664
672
  blunDir,
665
673
  names: standardMcpNames,
666
674
  });
667
675
 
668
676
  // --- 4. Eigenes BLUN-Grunddesign als einzigen Standard-Skill installieren
669
- seedStandardDesignSkill({ packageRoot: PKG, blunDir });
670
- installManagedAgentSpinePlugin({ packageRoot: PKG, blunDir });
677
+ await seedStandardDesignSkillAsync({ packageRoot: PKG, blunDir, io: startupSecurity });
678
+ await installManagedAgentSpinePluginAsync({ packageRoot: PKG, blunDir, io: startupSecurity });
671
679
 
672
680
  // --- 5. Telegram-Plugin + Token-Vorlage (nur King) -----------------------
673
681
  if (mode === LAUNCHER_MODES.KING) {
674
- installTelegramForProfile(PKG, blunDir);
682
+ await installTelegramForProfile(PKG, blunDir, startupSecurity);
675
683
  }
676
684
 
685
+ } finally { await startupSecurity.close(); }
686
+
677
687
  const nativeOwner = new AbortController();
678
688
  let nativeStopSignal;
679
689
  const nativeSignals = new Map();
@@ -111,6 +111,31 @@ function copySelectedAgentSpinePlugin({ blunDir, sourceRoot }) {
111
111
  fs.rmSync(staging, { recursive: true, force: true });
112
112
  }
113
113
  }
114
+ async function copySelectedAgentSpinePluginAsync({ blunDir, sourceRoot, io }) {
115
+ const plugins = path.resolve(blunDir, 'plugins');
116
+ const managed = path.join(plugins, 'managed');
117
+ await io.ensurePrivateDirectory(plugins);
118
+ await io.ensurePrivateDirectory(managed);
119
+ const digest = digestPluginEntries(snapshotPluginTree(sourceRoot));
120
+ const pluginRoot = path.join(managed, `agent-spine-${digest}`);
121
+ if (fs.existsSync(pluginRoot)) {
122
+ describeAgentSpineSelection({ blunDir, pluginRoot });
123
+ return pluginRoot;
124
+ }
125
+ const staging = path.join(managed, `.agent-spine-selected-${process.pid}-${randomUUID()}.tmp`);
126
+ try {
127
+ await io.copyPayload(sourceRoot,staging);
128
+ if (digestPluginEntries(snapshotPluginTree(staging)) !== digest) throw new Error('AgentSpine source changed during installation');
129
+ renamePrivateStaging(staging, pluginRoot);
130
+ describeAgentSpineSelection({ blunDir, pluginRoot });
131
+ return pluginRoot;
132
+ } finally {
133
+ if (!samePath(path.dirname(staging), managed) || !path.basename(staging).startsWith('.agent-spine-selected-')) {
134
+ throw new Error('Invalid AgentSpine staging cleanup path');
135
+ }
136
+ fs.rmSync(staging, { recursive: true, force: true });
137
+ }
138
+ }
114
139
 
115
- module.exports = { snapshotPluginTree, digestPluginEntries, describeAgentSpineSelection,
140
+ module.exports = { copySelectedAgentSpinePluginAsync, snapshotPluginTree, digestPluginEntries, describeAgentSpineSelection,
116
141
  selectedAgentSpineRoot, copySelectedAgentSpinePlugin };
@@ -1,10 +1,10 @@
1
1
  'use strict';
2
2
 
3
- const { randomUUID } = require('node:crypto');
3
+ const { createHash, randomUUID } = require('node:crypto');
4
4
  const fs = require('node:fs');
5
5
  const path = require('node:path');
6
6
  const { renamePrivateStaging, copyTelegramFiles } = require('./rename-private-staging.cjs');
7
- const { selectedAgentSpineRoot, describeAgentSpineSelection, copySelectedAgentSpinePlugin } = require('./managed-plugin-selection.cjs');
7
+ const { copySelectedAgentSpinePluginAsync, selectedAgentSpineRoot, describeAgentSpineSelection, copySelectedAgentSpinePlugin } = require('./managed-plugin-selection.cjs');
8
8
 
9
9
  const {
10
10
  ensurePrivateDirectory,
@@ -80,51 +80,191 @@ function writeInstalledPlugins(filePath, installed) {
80
80
  }
81
81
  }
82
82
 
83
- function installManagedTelegramPlugin({ packageRoot, blunDir, now = new Date().toISOString() }) {
84
- const sourceRoot = path.join(packageRoot, 'telegram-plugin');
85
- const pluginsDir = path.join(blunDir, 'plugins');
86
- const managedDir = path.join(pluginsDir, 'managed');
87
- const pluginRoot = path.join(managedDir, 'telegram');
88
- const installedFile = path.join(pluginsDir, 'installed.json');
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
+ }
89
110
 
90
- ensurePrivateDirectory(pluginsDir);
91
- if (fs.existsSync(installedFile)) securePrivateFile(installedFile);
92
- const installed = readInstalledPlugins(installedFile);
93
- const updatedInstalled = updatedInstalledPlugins(installed, pluginRoot, now);
94
- ensurePrivateDirectory(managedDir);
95
- const nonce = `${process.pid}-${randomUUID()}`;
96
- const stagingRoot = path.join(managedDir, `.telegram-${nonce}.tmp`);
97
- const backupRoot = path.join(managedDir, `.telegram-${nonce}.bak`);
98
- let hadPreviousPlugin = false;
99
- let installedNewPlugin = false;
100
- try {
101
- if (fs.existsSync(pluginRoot)) {
102
- ensurePrivateDirectory(pluginRoot);
103
- hadPreviousPlugin = true;
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);
104
151
  }
105
- copyTelegramFiles(sourceRoot, stagingRoot);
106
- if (hadPreviousPlugin) fs.renameSync(pluginRoot, backupRoot);
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);
107
186
  try {
108
- renamePrivateStaging(stagingRoot, pluginRoot);
109
- installedNewPlugin = true;
110
- writeInstalledPlugins(installedFile, updatedInstalled);
111
- } catch (error) {
112
- if (installedNewPlugin) fs.rmSync(pluginRoot, { recursive: true, force: true });
113
- if (hadPreviousPlugin && fs.existsSync(backupRoot)) {
114
- fs.renameSync(backupRoot, pluginRoot);
115
- }
116
- throw error;
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;
117
195
  }
118
- if (hadPreviousPlugin) fs.rmSync(backupRoot, { recursive: true, force: true });
119
- } finally {
120
- fs.rmSync(stagingRoot, { recursive: true, force: true });
121
196
  }
122
-
123
- return { installedFile, pluginRoot };
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};
124
263
  }
125
264
 
126
265
  function installManagedAgentSpinePlugin({ packageRoot, blunDir, now = new Date().toISOString() }) {
127
266
  const installedFile = path.join(blunDir, 'plugins', 'installed.json');
267
+ ensurePrivateDirectory(blunDir);
128
268
  ensurePrivateDirectory(path.dirname(installedFile));
129
269
  if (fs.existsSync(installedFile)) securePrivateFile(installedFile);
130
270
  const installed = readInstalledPlugins(installedFile);
@@ -156,7 +296,109 @@ function installManagedAgentSpinePlugin({ packageRoot, blunDir, now = new Date()
156
296
  return { installedFile, pluginRoot, reused: false };
157
297
  }
158
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
+
159
399
  module.exports = {
400
+ installManagedAgentSpinePluginAsync,
401
+ installManagedTelegramPluginAsync,
160
402
  installManagedAgentSpinePlugin,
161
403
  installManagedTelegramPlugin,
162
404
  readInstalledPlugins,