blun-king-cli 9.1.643 → 9.1.645

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 (268) hide show
  1. package/CHANGELOG.md +19 -123
  2. package/LIESMICH.txt +17 -45
  3. package/README.md +15 -76
  4. package/RELEASE-9.1.645.md +29 -0
  5. package/bin/blun.js +3 -3
  6. package/bin/king.js +3 -3
  7. package/bin/launcher-mode.js +125 -126
  8. package/bin/launcher-runtime.js +603 -616
  9. package/bin/plugin-bootstrap.js +339 -405
  10. package/bin/rename-private-staging.cjs +2 -2
  11. package/bin/retired-bundled-plugins.cjs +84 -0
  12. package/bin/startup-security-host.cjs +105 -0
  13. package/bin/startup-security.cjs +9 -105
  14. package/bin/startup-warning-policy.cjs +22 -0
  15. package/bin/update-lease-installer.cjs +125 -0
  16. package/bin/update-lease-sockets.cjs +228 -0
  17. package/bin/update-lease.js +22 -327
  18. package/bin/verify-bundled-agent-sources.cjs +2 -4
  19. package/blun.mjs +77 -180
  20. package/bundled-agent-sources.json +1 -552
  21. package/package.json +3 -6
  22. package/tool-liveness642/receipt.json +1 -1
  23. package/worker-host.mjs +62 -120
  24. package/agent-spine-plugin/.claude-plugin/marketplace.json +0 -20
  25. package/agent-spine-plugin/.claude-plugin/plugin.json +0 -14
  26. package/agent-spine-plugin/.codex-plugin/plugin.json +0 -47
  27. package/agent-spine-plugin/.mcp.json +0 -8
  28. package/agent-spine-plugin/CHANGELOG.md +0 -1614
  29. package/agent-spine-plugin/LICENSE +0 -186
  30. package/agent-spine-plugin/README.md +0 -432
  31. package/agent-spine-plugin/assets/agentspine-banner.svg +0 -32
  32. package/agent-spine-plugin/bin/agentspine-mcp.js +0 -4
  33. package/agent-spine-plugin/bin/agentspine.js +0 -7
  34. package/agent-spine-plugin/blun.plugin.json +0 -68
  35. package/agent-spine-plugin/docs/acceptance.md +0 -61
  36. package/agent-spine-plugin/docs/artifact-evaluation.md +0 -93
  37. package/agent-spine-plugin/docs/host-integration.md +0 -193
  38. package/agent-spine-plugin/docs/preflight-recall.md +0 -71
  39. package/agent-spine-plugin/docs/preservation-contract.md +0 -53
  40. package/agent-spine-plugin/docs/quality-gates.md +0 -50
  41. package/agent-spine-plugin/docs/session-timeline.md +0 -112
  42. package/agent-spine-plugin/docs/source-roots.md +0 -113
  43. package/agent-spine-plugin/docs/world-model.md +0 -119
  44. package/agent-spine-plugin/hooks/codex.json +0 -47
  45. package/agent-spine-plugin/hooks/hooks.json +0 -106
  46. package/agent-spine-plugin/hooks/version.json +0 -5
  47. package/agent-spine-plugin/package.json +0 -77
  48. package/agent-spine-plugin/scripts/check-codex-install.js +0 -226
  49. package/agent-spine-plugin/scripts/check-hosts.js +0 -208
  50. package/agent-spine-plugin/scripts/check-install-hook.js +0 -227
  51. package/agent-spine-plugin/scripts/check-install-selfstarter.js +0 -154
  52. package/agent-spine-plugin/scripts/check-install.js +0 -478
  53. package/agent-spine-plugin/scripts/check-line-budget.js +0 -58
  54. package/agent-spine-plugin/scripts/check-syntax.js +0 -29
  55. package/agent-spine-plugin/scripts/github-actions.js +0 -11
  56. package/agent-spine-plugin/scripts/hermetic-process.js +0 -191
  57. package/agent-spine-plugin/scripts/release-check.js +0 -150
  58. package/agent-spine-plugin/scripts/run-acceptance.js +0 -19
  59. package/agent-spine-plugin/scripts/run-checks.js +0 -50
  60. package/agent-spine-plugin/scripts/run-tests-hermetic.js +0 -112
  61. package/agent-spine-plugin/skills/agent-spine/SKILL.md +0 -99
  62. package/agent-spine-plugin/spine-example/1-identity.md +0 -12
  63. package/agent-spine-plugin/spine-example/2-voice.md +0 -6
  64. package/agent-spine-plugin/spine-example/3-conduct.md +0 -8
  65. package/agent-spine-plugin/spine-example/4-history.md +0 -4
  66. package/agent-spine-plugin/src/cli-agent.js +0 -315
  67. package/agent-spine-plugin/src/cli-attention.js +0 -95
  68. package/agent-spine-plugin/src/cli-autonomy.js +0 -36
  69. package/agent-spine-plugin/src/cli-common.js +0 -71
  70. package/agent-spine-plugin/src/cli-continuity.js +0 -116
  71. package/agent-spine-plugin/src/cli-core.js +0 -128
  72. package/agent-spine-plugin/src/cli-diagnostics.js +0 -291
  73. package/agent-spine-plugin/src/cli-host.js +0 -21
  74. package/agent-spine-plugin/src/cli-learning.js +0 -320
  75. package/agent-spine-plugin/src/cli-premortem.js +0 -16
  76. package/agent-spine-plugin/src/cli-sharing.js +0 -230
  77. package/agent-spine-plugin/src/cli.js +0 -181
  78. package/agent-spine-plugin/src/codex-reader-launcher.js +0 -182
  79. package/agent-spine-plugin/src/hook.js +0 -500
  80. package/agent-spine-plugin/src/index.js +0 -108
  81. package/agent-spine-plugin/src/lib/acceptance.js +0 -435
  82. package/agent-spine-plugin/src/lib/action-lesson-recall.js +0 -118
  83. package/agent-spine-plugin/src/lib/attention-context.js +0 -167
  84. package/agent-spine-plugin/src/lib/attention-events.js +0 -113
  85. package/agent-spine-plugin/src/lib/attention-privacy.js +0 -72
  86. package/agent-spine-plugin/src/lib/attention-schema.js +0 -164
  87. package/agent-spine-plugin/src/lib/attention-storage.js +0 -93
  88. package/agent-spine-plugin/src/lib/attention.js +0 -164
  89. package/agent-spine-plugin/src/lib/audit-premortem.js +0 -223
  90. package/agent-spine-plugin/src/lib/audit.js +0 -401
  91. package/agent-spine-plugin/src/lib/authentication.js +0 -515
  92. package/agent-spine-plugin/src/lib/autonomy-policy.js +0 -110
  93. package/agent-spine-plugin/src/lib/autonomy-store.js +0 -202
  94. package/agent-spine-plugin/src/lib/autonomy.js +0 -8
  95. package/agent-spine-plugin/src/lib/briefing.js +0 -493
  96. package/agent-spine-plugin/src/lib/catalog-document-read.js +0 -51
  97. package/agent-spine-plugin/src/lib/catalog.js +0 -167
  98. package/agent-spine-plugin/src/lib/channel-continuity.js +0 -19
  99. package/agent-spine-plugin/src/lib/channel-runtime.js +0 -665
  100. package/agent-spine-plugin/src/lib/codex-installation.js +0 -231
  101. package/agent-spine-plugin/src/lib/codex-skill-installation.js +0 -211
  102. package/agent-spine-plugin/src/lib/context.js +0 -156
  103. package/agent-spine-plugin/src/lib/continuity.js +0 -338
  104. package/agent-spine-plugin/src/lib/coordination.js +0 -577
  105. package/agent-spine-plugin/src/lib/delivery-agent-usage.js +0 -231
  106. package/agent-spine-plugin/src/lib/delivery-assignment.js +0 -220
  107. package/agent-spine-plugin/src/lib/delivery-command-actions.js +0 -462
  108. package/agent-spine-plugin/src/lib/delivery-knowledge.js +0 -78
  109. package/agent-spine-plugin/src/lib/delivery-premortem-binding.js +0 -107
  110. package/agent-spine-plugin/src/lib/delivery-premortem-closure.js +0 -171
  111. package/agent-spine-plugin/src/lib/delivery-premortem-codec.js +0 -45
  112. package/agent-spine-plugin/src/lib/delivery-premortem-correction.js +0 -101
  113. package/agent-spine-plugin/src/lib/delivery-premortem-file.js +0 -21
  114. package/agent-spine-plugin/src/lib/delivery-premortem-index.js +0 -493
  115. package/agent-spine-plugin/src/lib/delivery-premortem-inspection.js +0 -37
  116. package/agent-spine-plugin/src/lib/delivery-premortem-recovery.js +0 -120
  117. package/agent-spine-plugin/src/lib/delivery-premortem-rejection.js +0 -65
  118. package/agent-spine-plugin/src/lib/delivery-premortem-results.js +0 -28
  119. package/agent-spine-plugin/src/lib/delivery-premortem-session-guard.js +0 -46
  120. package/agent-spine-plugin/src/lib/delivery-premortem-write-ledger.js +0 -285
  121. package/agent-spine-plugin/src/lib/delivery-premortem.js +0 -499
  122. package/agent-spine-plugin/src/lib/delivery-shell-heredoc.js +0 -115
  123. package/agent-spine-plugin/src/lib/delivery-shell-substitutions.js +0 -111
  124. package/agent-spine-plugin/src/lib/delivery-shell-wrapper.js +0 -64
  125. package/agent-spine-plugin/src/lib/delivery-target.js +0 -73
  126. package/agent-spine-plugin/src/lib/delivery-verification.js +0 -445
  127. package/agent-spine-plugin/src/lib/documents.js +0 -239
  128. package/agent-spine-plugin/src/lib/feed-transport.js +0 -499
  129. package/agent-spine-plugin/src/lib/filesystem-retry.js +0 -34
  130. package/agent-spine-plugin/src/lib/gateway-common.js +0 -68
  131. package/agent-spine-plugin/src/lib/gateway-control.js +0 -370
  132. package/agent-spine-plugin/src/lib/gateway-delivery.js +0 -103
  133. package/agent-spine-plugin/src/lib/gateway-execution.js +0 -350
  134. package/agent-spine-plugin/src/lib/gateway-group-response.js +0 -128
  135. package/agent-spine-plugin/src/lib/gateway-host-fencing.js +0 -92
  136. package/agent-spine-plugin/src/lib/gateway-host-lifecycle.js +0 -193
  137. package/agent-spine-plugin/src/lib/gateway-inspection.js +0 -85
  138. package/agent-spine-plugin/src/lib/gateway-knowledge.js +0 -129
  139. package/agent-spine-plugin/src/lib/gateway-policy-provenance.js +0 -197
  140. package/agent-spine-plugin/src/lib/gateway-premortem-disposition.js +0 -82
  141. package/agent-spine-plugin/src/lib/gateway-premortem.js +0 -363
  142. package/agent-spine-plugin/src/lib/gateway-prepared-host.js +0 -28
  143. package/agent-spine-plugin/src/lib/gateway-runs.js +0 -345
  144. package/agent-spine-plugin/src/lib/gateway-runtime-identity.js +0 -31
  145. package/agent-spine-plugin/src/lib/gateway-runtime-records.js +0 -21
  146. package/agent-spine-plugin/src/lib/gateway-runtime.js +0 -18
  147. package/agent-spine-plugin/src/lib/gateway-state-transaction.js +0 -356
  148. package/agent-spine-plugin/src/lib/gateway-state.js +0 -344
  149. package/agent-spine-plugin/src/lib/graph.js +0 -337
  150. package/agent-spine-plugin/src/lib/hook-artifact-guards.js +0 -356
  151. package/agent-spine-plugin/src/lib/hook-audit.js +0 -43
  152. package/agent-spine-plugin/src/lib/hook-briefing-use.js +0 -78
  153. package/agent-spine-plugin/src/lib/hook-context.js +0 -441
  154. package/agent-spine-plugin/src/lib/hook-final-message.js +0 -26
  155. package/agent-spine-plugin/src/lib/hook-input.js +0 -27
  156. package/agent-spine-plugin/src/lib/hook-output.js +0 -284
  157. package/agent-spine-plugin/src/lib/hook-premortem.js +0 -257
  158. package/agent-spine-plugin/src/lib/hook-process-advisory.js +0 -36
  159. package/agent-spine-plugin/src/lib/hook-protection.js +0 -95
  160. package/agent-spine-plugin/src/lib/hook-stop-verification.js +0 -84
  161. package/agent-spine-plugin/src/lib/hook-timeline.js +0 -102
  162. package/agent-spine-plugin/src/lib/host-instruction-budget.js +0 -11
  163. package/agent-spine-plugin/src/lib/https-transport.js +0 -392
  164. package/agent-spine-plugin/src/lib/identifier-analysis.js +0 -446
  165. package/agent-spine-plugin/src/lib/indexed-memory-offline.js +0 -40
  166. package/agent-spine-plugin/src/lib/indexed-memory.js +0 -298
  167. package/agent-spine-plugin/src/lib/knowledge-evidence.js +0 -431
  168. package/agent-spine-plugin/src/lib/learning-applications.js +0 -441
  169. package/agent-spine-plugin/src/lib/learning-artifact-evaluator.js +0 -114
  170. package/agent-spine-plugin/src/lib/learning-candidates.js +0 -274
  171. package/agent-spine-plugin/src/lib/learning-context.js +0 -137
  172. package/agent-spine-plugin/src/lib/learning-delivery-contracts.js +0 -310
  173. package/agent-spine-plugin/src/lib/learning-evaluation-contracts.js +0 -350
  174. package/agent-spine-plugin/src/lib/learning-evaluation-registration.js +0 -372
  175. package/agent-spine-plugin/src/lib/learning-evaluation-revocation.js +0 -292
  176. package/agent-spine-plugin/src/lib/learning-evidence-contracts.js +0 -321
  177. package/agent-spine-plugin/src/lib/learning-findings.js +0 -458
  178. package/agent-spine-plugin/src/lib/learning-measurement-contracts.js +0 -285
  179. package/agent-spine-plugin/src/lib/learning-measurements.js +0 -265
  180. package/agent-spine-plugin/src/lib/learning-outcome-contracts.js +0 -165
  181. package/agent-spine-plugin/src/lib/learning-outcomes.js +0 -343
  182. package/agent-spine-plugin/src/lib/learning-reconciliation.js +0 -290
  183. package/agent-spine-plugin/src/lib/learning-retry-contracts.js +0 -188
  184. package/agent-spine-plugin/src/lib/learning-schema.js +0 -229
  185. package/agent-spine-plugin/src/lib/learning-scope-targets.js +0 -424
  186. package/agent-spine-plugin/src/lib/learning-state-upgrade.js +0 -477
  187. package/agent-spine-plugin/src/lib/learning-status-configuration.js +0 -476
  188. package/agent-spine-plugin/src/lib/learning-storage.js +0 -203
  189. package/agent-spine-plugin/src/lib/learning-trial-recovery.js +0 -218
  190. package/agent-spine-plugin/src/lib/learning-validation-contracts.js +0 -375
  191. package/agent-spine-plugin/src/lib/learning-validation-renewal.js +0 -298
  192. package/agent-spine-plugin/src/lib/learning-validation-runtime.js +0 -234
  193. package/agent-spine-plugin/src/lib/learning.js +0 -36
  194. package/agent-spine-plugin/src/lib/lesson-recall-session.js +0 -172
  195. package/agent-spine-plugin/src/lib/mcp-autonomy-tools.js +0 -37
  196. package/agent-spine-plugin/src/lib/mcp-delivery-completion.js +0 -124
  197. package/agent-spine-plugin/src/lib/mcp-delivery-tools.js +0 -45
  198. package/agent-spine-plugin/src/lib/mcp-premortem.js +0 -68
  199. package/agent-spine-plugin/src/lib/mcp-runtime.js +0 -355
  200. package/agent-spine-plugin/src/lib/mcp-source-context.js +0 -61
  201. package/agent-spine-plugin/src/lib/mcp-timeline-tools.js +0 -240
  202. package/agent-spine-plugin/src/lib/mcp-world-tools.js +0 -52
  203. package/agent-spine-plugin/src/lib/object-transport.js +0 -206
  204. package/agent-spine-plugin/src/lib/owned-file-lock.js +0 -182
  205. package/agent-spine-plugin/src/lib/paths.js +0 -109
  206. package/agent-spine-plugin/src/lib/peer-transport.js +0 -283
  207. package/agent-spine-plugin/src/lib/persona-runtime.js +0 -581
  208. package/agent-spine-plugin/src/lib/pre-answer-timeline-recall.js +0 -104
  209. package/agent-spine-plugin/src/lib/preflight-delivery-id.js +0 -27
  210. package/agent-spine-plugin/src/lib/preflight.js +0 -688
  211. package/agent-spine-plugin/src/lib/project-portfolio.js +0 -176
  212. package/agent-spine-plugin/src/lib/runtime.js +0 -13
  213. package/agent-spine-plugin/src/lib/selfstarter-core.js +0 -382
  214. package/agent-spine-plugin/src/lib/selfstarter-jobs.js +0 -149
  215. package/agent-spine-plugin/src/lib/selfstarter-lease.js +0 -204
  216. package/agent-spine-plugin/src/lib/selfstarter-policy.js +0 -90
  217. package/agent-spine-plugin/src/lib/selfstarter-workspace.js +0 -111
  218. package/agent-spine-plugin/src/lib/selfstarter.js +0 -11
  219. package/agent-spine-plugin/src/lib/session-timeline-auth.js +0 -316
  220. package/agent-spine-plugin/src/lib/session-timeline-codex.js +0 -69
  221. package/agent-spine-plugin/src/lib/session-timeline-contract.js +0 -56
  222. package/agent-spine-plugin/src/lib/session-timeline-enrollment-source.js +0 -38
  223. package/agent-spine-plugin/src/lib/session-timeline-enrollment-storage.js +0 -128
  224. package/agent-spine-plugin/src/lib/session-timeline-enrollment-transport.js +0 -15
  225. package/agent-spine-plugin/src/lib/session-timeline-enrollment.js +0 -478
  226. package/agent-spine-plugin/src/lib/session-timeline-event-extract.js +0 -186
  227. package/agent-spine-plugin/src/lib/session-timeline-host-origin.js +0 -73
  228. package/agent-spine-plugin/src/lib/session-timeline-host-receipt.js +0 -117
  229. package/agent-spine-plugin/src/lib/session-timeline-invocation.js +0 -201
  230. package/agent-spine-plugin/src/lib/session-timeline-king.js +0 -93
  231. package/agent-spine-plugin/src/lib/session-timeline-prior.js +0 -57
  232. package/agent-spine-plugin/src/lib/session-timeline-provider.js +0 -36
  233. package/agent-spine-plugin/src/lib/session-timeline-query.js +0 -56
  234. package/agent-spine-plugin/src/lib/session-timeline-results.js +0 -56
  235. package/agent-spine-plugin/src/lib/session-timeline-root.js +0 -11
  236. package/agent-spine-plugin/src/lib/session-timeline-search.js +0 -82
  237. package/agent-spine-plugin/src/lib/session-timeline-sid-acl.js +0 -213
  238. package/agent-spine-plugin/src/lib/session-timeline-source-open.js +0 -30
  239. package/agent-spine-plugin/src/lib/session-timeline-source.js +0 -80
  240. package/agent-spine-plugin/src/lib/session-timeline-state.js +0 -45
  241. package/agent-spine-plugin/src/lib/session-timeline-transport.js +0 -42
  242. package/agent-spine-plugin/src/lib/session-timeline-windows-acl.js +0 -145
  243. package/agent-spine-plugin/src/lib/session-timeline.js +0 -462
  244. package/agent-spine-plugin/src/lib/sharing.js +0 -969
  245. package/agent-spine-plugin/src/lib/source-roots.js +0 -475
  246. package/agent-spine-plugin/src/lib/source-tree-scan.js +0 -178
  247. package/agent-spine-plugin/src/lib/sqlite-transport.js +0 -501
  248. package/agent-spine-plugin/src/lib/task-knowledge-context.js +0 -99
  249. package/agent-spine-plugin/src/lib/telegram-adapter.js +0 -119
  250. package/agent-spine-plugin/src/lib/timeline-continuation-update.js +0 -100
  251. package/agent-spine-plugin/src/lib/timeline-tool-guard.js +0 -225
  252. package/agent-spine-plugin/src/lib/timeline-user-feedback.js +0 -216
  253. package/agent-spine-plugin/src/lib/timeline-world-capture.js +0 -233
  254. package/agent-spine-plugin/src/lib/voice-runtime.js +0 -39
  255. package/agent-spine-plugin/src/lib/world-knowledge.js +0 -306
  256. package/agent-spine-plugin/src/lib/world-model.js +0 -333
  257. package/agent-spine-plugin/src/mcp.js +0 -456
  258. package/agent-spine-plugin/src/version.js +0 -1
  259. package/agent-spine-plugin/src/worker.js +0 -257
  260. package/bin/agentspine-king-goal-inbox.mjs +0 -127
  261. package/bin/agentspine-king-goal-intake.mjs +0 -106
  262. package/bin/agentspine-king-host-runner.mjs +0 -109
  263. package/bin/agentspine-king-snapshot-policy.cjs +0 -80
  264. package/bin/agentspine-king-status-policy.mjs +0 -226
  265. package/bin/agentspine-king-worker-host.mjs +0 -160
  266. package/bin/managed-plugin-selection.cjs +0 -141
  267. package/bin/verify-agent-behavior.cjs +0 -122
  268. package/bin/verify-agent-components.cjs +0 -104
@@ -29,7 +29,7 @@ function canonical(value) { return path.resolve(value).toLowerCase(); }
29
29
  function stagingState(staging, impl, expected) {
30
30
  const parent = path.dirname(path.resolve(staging));
31
31
  if (path.basename(parent) !== 'managed'
32
- || !/^\.(?:agent-spine-selected|telegram)-[0-9]+-[a-f0-9-]+\.tmp$/.test(path.basename(staging))
32
+ || !/^\.telegram-[0-9]+-[a-f0-9-]+\.tmp$/.test(path.basename(staging))
33
33
  || canonical(impl.realpathSync(parent)) !== canonical(parent)) throw new Error('Invalid private staging scope');
34
34
  let stat;
35
35
  try { stat = impl.lstatSync(staging); } catch (error) { if (error.code === 'ENOENT') return null; throw error; }
@@ -42,7 +42,7 @@ function renamePrivateStaging(source, target, options = {}) {
42
42
  const impl = options.fsImpl || fs;
43
43
  if ((options.platform || process.platform) !== 'win32') return impl.renameSync(source, target);
44
44
  if (canonical(path.dirname(target)) !== canonical(path.dirname(source))
45
- || !/^(?:telegram(?:-[a-f0-9]{64}(?:-[a-f0-9-]{36})?)?|agent-spine-[a-f0-9]{64})$/.test(path.basename(target))) throw new Error('Invalid private staging target');
45
+ || !/^telegram(?:-[a-f0-9]{64}(?:-[a-f0-9-]{36})?)?$/.test(path.basename(target))) throw new Error('Invalid private staging target');
46
46
  const identity = stagingState(source, impl);
47
47
  if (!identity) throw new Error('Private staging is missing');
48
48
  return withWindowsFsRetry(() => impl.renameSync(source, target), {
@@ -0,0 +1,84 @@
1
+ 'use strict';
2
+
3
+ const { createHash, randomUUID } = require('node:crypto');
4
+ const fs = require('node:fs');
5
+ const path = require('node:path');
6
+
7
+ const MAX_REGISTRY_BYTES = 1024 * 1024;
8
+ const digest = (bytes) => createHash('sha256').update(bytes).digest('hex');
9
+ const samePath = (left, right) => process.platform === 'win32'
10
+ ? left.toLowerCase() === right.toLowerCase() : left === right;
11
+
12
+ function readRegistry(filename) {
13
+ const parent = path.dirname(filename);
14
+ if (!samePath(fs.realpathSync(parent), path.resolve(parent))) {
15
+ throw new Error('PLUGIN_REGISTRY_PARENT_LINK');
16
+ }
17
+ const before = fs.lstatSync(filename);
18
+ if (!before.isFile() || before.isSymbolicLink() || before.nlink !== 1
19
+ || before.size > MAX_REGISTRY_BYTES) throw new Error('INVALID_PLUGIN_REGISTRY_FILE');
20
+ const descriptor = fs.openSync(filename, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0));
21
+ let bytes;
22
+ let after;
23
+ try {
24
+ const opened = fs.fstatSync(descriptor);
25
+ if (opened.dev !== before.dev || opened.ino !== before.ino || opened.nlink !== 1) {
26
+ throw new Error('PLUGIN_REGISTRY_CHANGED');
27
+ }
28
+ const buffer = Buffer.alloc(MAX_REGISTRY_BYTES + 1);
29
+ let length = 0;
30
+ while (length < buffer.length) {
31
+ const count = fs.readSync(descriptor, buffer, length, buffer.length - length, null);
32
+ if (count === 0) break;
33
+ length += count;
34
+ }
35
+ if (length > MAX_REGISTRY_BYTES) throw new Error('INVALID_PLUGIN_REGISTRY_FILE');
36
+ bytes = buffer.subarray(0, length);
37
+ after = fs.fstatSync(descriptor);
38
+ } finally {
39
+ fs.closeSync(descriptor);
40
+ }
41
+ const currentPath = fs.lstatSync(filename);
42
+ if (before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size
43
+ || before.mtimeMs !== after.mtimeMs || after.nlink !== 1
44
+ || currentPath.dev !== before.dev || currentPath.ino !== before.ino || currentPath.isSymbolicLink()) {
45
+ throw new Error('PLUGIN_REGISTRY_CHANGED');
46
+ }
47
+ const document = JSON.parse(bytes.toString('utf8'));
48
+ if (document?.version !== 1 || !Array.isArray(document.plugins)
49
+ || document.plugins.some((entry) => !entry || typeof entry !== 'object' || Array.isArray(entry))) {
50
+ throw new Error('INVALID_PLUGIN_REGISTRY_DOCUMENT');
51
+ }
52
+ return { bytes, document, hash: digest(bytes), identity: after };
53
+ }
54
+
55
+ async function retireBundledPlugins({ blunDir, io }) {
56
+ const filename = path.resolve(blunDir, 'plugins', 'installed.json');
57
+ let original;
58
+ try {
59
+ original = readRegistry(filename);
60
+ } catch (error) {
61
+ if (error.code === 'ENOENT') return { removed: 0, changed: false };
62
+ throw error;
63
+ }
64
+ const plugins = original.document.plugins.filter((entry) => entry.id !== 'agent-spine');
65
+ const removed = original.document.plugins.length - plugins.length;
66
+ if (removed === 0) return { removed, changed: false };
67
+ const updated = { ...original.document, plugins };
68
+ let serialized = `${JSON.stringify(updated, null, 2)}\n`;
69
+ if (Buffer.byteLength(serialized) > MAX_REGISTRY_BYTES) serialized = `${JSON.stringify(updated)}\n`;
70
+ if (Buffer.byteLength(serialized) > MAX_REGISTRY_BYTES) throw new Error('INVALID_PLUGIN_REGISTRY_FILE');
71
+ const temporary = path.join(path.dirname(filename), `.retired-plugins-${randomUUID()}.tmp`);
72
+ try {
73
+ await io.writePrivateFile(temporary, serialized);
74
+ const current = readRegistry(filename);
75
+ if (current.hash !== original.hash || current.identity.dev !== original.identity.dev
76
+ || current.identity.ino !== original.identity.ino) throw new Error('PLUGIN_REGISTRY_CHANGED');
77
+ fs.renameSync(temporary, filename);
78
+ } finally {
79
+ if (fs.existsSync(temporary)) fs.unlinkSync(temporary);
80
+ }
81
+ return { removed, changed: true };
82
+ }
83
+
84
+ module.exports = { retireBundledPlugins };
@@ -0,0 +1,105 @@
1
+ 'use strict';
2
+
3
+ const SCRIPT = String.raw`
4
+ [Console]::InputEncoding=[Text.UTF8Encoding]::new($false)
5
+ [Console]::OutputEncoding=[Text.UTF8Encoding]::new($false)
6
+
7
+ $ErrorActionPreference='Stop'
8
+ $ProgressPreference='SilentlyContinue'
9
+ $phase='TEMP_PATH'
10
+ try {
11
+ Set-StrictMode -Version 3
12
+ $target=$env:BLUN_PRIVATE_TEMP_TARGET
13
+ $sid=[Security.Principal.WindowsIdentity]::GetCurrent().User
14
+ $system=[Security.Principal.SecurityIdentifier]::new('S-1-5-18')
15
+ if ([IO.Path]::GetFullPath($target) -cne $target -or $target -notmatch '^[A-Za-z]:\\') { throw 'path' }
16
+ if ([IO.Directory]::Exists($target) -or [IO.File]::Exists($target)) { throw 'exists' }
17
+ $parent=[IO.Path]::GetDirectoryName($target)
18
+ if (-not [IO.Directory]::Exists($parent)) { throw 'parent' }
19
+ for ($ancestor=$parent; -not [string]::IsNullOrEmpty($ancestor); $ancestor=[IO.Path]::GetDirectoryName($ancestor)) {
20
+ if (([IO.File]::GetAttributes($ancestor) -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw 'reparse' }
21
+ }
22
+ $acl=[Security.AccessControl.DirectorySecurity]::new()
23
+ $acl.SetOwner($sid)
24
+ $acl.SetAccessRuleProtection($true,$false)
25
+ $flags=[Security.AccessControl.InheritanceFlags]'ContainerInherit,ObjectInherit'
26
+ $expected=@{}
27
+ $expected[$sid.Value]=$sid
28
+ $expected[$system.Value]=$system
29
+ foreach ($trustee in $expected.Values) {
30
+ $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($trustee,[Security.AccessControl.FileSystemRights]::FullControl,$flags,[Security.AccessControl.PropagationFlags]::None,[Security.AccessControl.AccessControlType]::Allow))
31
+ }
32
+ $phase='TEMP_CREATE'
33
+ $directory=[IO.Directory]::CreateDirectory($target,$acl)
34
+ if (($directory.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw 'reparse' }
35
+ $phase='TEMP_ACL_VERIFICATION'
36
+ $actual=$directory.GetAccessControl([Security.AccessControl.AccessControlSections]'Owner,Access')
37
+ if (-not $actual.AreAccessRulesProtected -or $actual.GetOwner([Security.Principal.SecurityIdentifier]).Value -ne $sid.Value) { throw 'owner' }
38
+ $rules=$actual.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])
39
+ if ($rules.Count -ne $expected.Count) { throw 'acl' }
40
+ $seen=@{}
41
+ foreach ($rule in $rules) {
42
+ $key=$rule.IdentityReference.Value
43
+ if ((-not $expected.ContainsKey($key)) -or $seen.ContainsKey($key) -or $rule.IsInherited -or $rule.AccessControlType -ne 'Allow' -or $rule.FileSystemRights -ne 'FullControl' -or $rule.InheritanceFlags -ne $flags -or $rule.PropagationFlags -ne 'None') { throw 'acl' }
44
+ $seen[$key]=$true
45
+ }
46
+ for ($ancestor=$target; -not [string]::IsNullOrEmpty($ancestor); $ancestor=[IO.Path]::GetDirectoryName($ancestor)) {
47
+ if (([IO.File]::GetAttributes($ancestor) -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw 'reparse' }
48
+ }
49
+ $phase='TEMP_WRITE_PROBE'
50
+ $probe=[IO.Path]::Combine($target,[Guid]::NewGuid().ToString('N')+'.probe')
51
+ $handle=[IO.File]::Open($probe,[IO.FileMode]::CreateNew,[IO.FileAccess]::ReadWrite,[IO.FileShare]::None)
52
+ try { $handle.WriteByte(0); $handle.Flush($true) } finally { $handle.Dispose() }
53
+ [IO.File]::Delete($probe)
54
+ $env:TEMP=$target
55
+ $env:TMP=$target
56
+ [Console]::Out.WriteLine('{"ready":true}')
57
+ if ([Console]::ReadLine() -cne 'BLUN_STARTUP_TEMP_ACK_V1') { throw 'ack' }
58
+ } catch {
59
+ [Console]::Error.Write(('BLUN_PRIVATE_TEMP_ERROR_V2:{0}' -f $phase))
60
+ exit 1
61
+ }
62
+ $ErrorActionPreference='Stop'
63
+ $ProgressPreference='SilentlyContinue'
64
+ try {
65
+ $bytes=[Convert]::FromBase64String($env:BLUN_STARTUP_NATIVE)
66
+ $mem=[IO.MemoryStream]::new($bytes)
67
+ $zip=[IO.Compression.GZipStream]::new($mem,[IO.Compression.CompressionMode]::Decompress)
68
+ $reader=[IO.StreamReader]::new($zip,[Text.Encoding]::UTF8)
69
+ try { $null=Add-Type -TypeDefinition $reader.ReadToEnd() -Language CSharp } finally { $reader.Dispose();$zip.Dispose();$mem.Dispose();[Array]::Clear($bytes,0,$bytes.Length) }
70
+ $sid=[Security.Principal.WindowsIdentity]::GetCurrent().User.Value
71
+ while ($null -ne ($line=[Console]::ReadLine())) {
72
+ $request=$line | ConvertFrom-Json
73
+ $frame=$null
74
+ try {
75
+ [BlunPrivateAclNative]::Warnings.Clear()
76
+ [BlunPrivateAclNative]::Repaired.Clear()
77
+ [BlunPrivateAclNative]::OutsideProfile.Clear()
78
+ [BlunPrivateAclNative]::StartupOwnerSid=$null
79
+ switch ($request.kind) {
80
+ 'directory' { [BlunPrivateAclNative]::InspectStartupDirectory($request.target,$sid) }
81
+ 'temp-verify' { [BlunPrivateAclNative]::InspectStartupDirectory($request.target,$sid,$false);if ([BlunPrivateAclNative]::Warnings.Count -ne 0) { throw 'temp-acl' } }
82
+ 'file' { [BlunPrivateAclNative]::HardenExisting($request.target,$sid,$false) }
83
+ 'file-write' {
84
+ $frame=[Convert]::FromBase64String($request.frame)
85
+ [BlunPrivateAclNative]::WritePrivateFile($request.target,$sid,$frame)
86
+ }
87
+ default { throw 'Invalid startup operation' }
88
+ }
89
+ $result=@{ id=$request.id;ok=$true;directoryDaclWrites=[BlunPrivateAclNative]::DirectoryDaclWrites;warnings=@([BlunPrivateAclNative]::Warnings);repaired=@([BlunPrivateAclNative]::Repaired);outsideProfile=@([BlunPrivateAclNative]::OutsideProfile) }
90
+ } catch {
91
+ $nativeCode=0;$reason='unknown';$failure=$_.Exception
92
+ for($depth=0;$depth -lt 8 -and $null -ne $failure;$depth++) {
93
+ if($failure -is [ComponentModel.Win32Exception]){$nativeCode=$failure.NativeErrorCode;$reason='native-error';break}
94
+ if($failure -is [UnauthorizedAccessException]){$reason='access-denied';break}
95
+ if($failure -is [IO.IOException]){$reason='io-error';break}
96
+ if($failure -is [ArgumentException]){$reason='argument-error';break}
97
+ $failure=$failure.InnerException
98
+ }
99
+ $result=@{ id=$request.id;ok=$false;phase=[BlunPrivateAclNative]::CurrentPhase;target=[BlunPrivateAclNative]::CurrentTarget;nativeErrorCode=$nativeCode;reason=$reason;sid=$sid;ownerSid=[BlunPrivateAclNative]::StartupOwnerSid }
100
+ } finally { if ($null -ne $frame) { [Array]::Clear($frame,0,$frame.Length) } }
101
+ [Console]::Out.WriteLine(($result | ConvertTo-Json -Compress -Depth 5))
102
+ }
103
+ } catch { [Console]::Error.Write('BLUN_STARTUP_HOST_FAILED');exit 1 }
104
+ `;
105
+ module.exports = SCRIPT;
@@ -8,108 +8,7 @@ const { createInterface } = require('node:readline');
8
8
 
9
9
  // One asynchronous host and one native compilation for the complete preparation.
10
10
  // No startup tree propagation, no persistent "verified" cache, no unverified timeout pass.
11
- const SCRIPT = String.raw`
12
- [Console]::InputEncoding=[Text.UTF8Encoding]::new($false)
13
- [Console]::OutputEncoding=[Text.UTF8Encoding]::new($false)
14
-
15
- $ErrorActionPreference='Stop'
16
- $ProgressPreference='SilentlyContinue'
17
- $phase='TEMP_PATH'
18
- try {
19
- Set-StrictMode -Version 3
20
- $target=$env:BLUN_PRIVATE_TEMP_TARGET
21
- $sid=[Security.Principal.WindowsIdentity]::GetCurrent().User
22
- $system=[Security.Principal.SecurityIdentifier]::new('S-1-5-18')
23
- if ([IO.Path]::GetFullPath($target) -cne $target -or $target -notmatch '^[A-Za-z]:\\') { throw 'path' }
24
- if ([IO.Directory]::Exists($target) -or [IO.File]::Exists($target)) { throw 'exists' }
25
- $parent=[IO.Path]::GetDirectoryName($target)
26
- if (-not [IO.Directory]::Exists($parent)) { throw 'parent' }
27
- for ($ancestor=$parent; -not [string]::IsNullOrEmpty($ancestor); $ancestor=[IO.Path]::GetDirectoryName($ancestor)) {
28
- if (([IO.File]::GetAttributes($ancestor) -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw 'reparse' }
29
- }
30
- $acl=[Security.AccessControl.DirectorySecurity]::new()
31
- $acl.SetOwner($sid)
32
- $acl.SetAccessRuleProtection($true,$false)
33
- $flags=[Security.AccessControl.InheritanceFlags]'ContainerInherit,ObjectInherit'
34
- $expected=@{}
35
- $expected[$sid.Value]=$sid
36
- $expected[$system.Value]=$system
37
- foreach ($trustee in $expected.Values) {
38
- $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($trustee,[Security.AccessControl.FileSystemRights]::FullControl,$flags,[Security.AccessControl.PropagationFlags]::None,[Security.AccessControl.AccessControlType]::Allow))
39
- }
40
- $phase='TEMP_CREATE'
41
- $directory=[IO.Directory]::CreateDirectory($target,$acl)
42
- if (($directory.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw 'reparse' }
43
- $phase='TEMP_ACL_VERIFICATION'
44
- $actual=$directory.GetAccessControl([Security.AccessControl.AccessControlSections]'Owner,Access')
45
- if (-not $actual.AreAccessRulesProtected -or $actual.GetOwner([Security.Principal.SecurityIdentifier]).Value -ne $sid.Value) { throw 'owner' }
46
- $rules=$actual.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])
47
- if ($rules.Count -ne $expected.Count) { throw 'acl' }
48
- $seen=@{}
49
- foreach ($rule in $rules) {
50
- $key=$rule.IdentityReference.Value
51
- if ((-not $expected.ContainsKey($key)) -or $seen.ContainsKey($key) -or $rule.IsInherited -or $rule.AccessControlType -ne 'Allow' -or $rule.FileSystemRights -ne 'FullControl' -or $rule.InheritanceFlags -ne $flags -or $rule.PropagationFlags -ne 'None') { throw 'acl' }
52
- $seen[$key]=$true
53
- }
54
- for ($ancestor=$target; -not [string]::IsNullOrEmpty($ancestor); $ancestor=[IO.Path]::GetDirectoryName($ancestor)) {
55
- if (([IO.File]::GetAttributes($ancestor) -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw 'reparse' }
56
- }
57
- $phase='TEMP_WRITE_PROBE'
58
- $probe=[IO.Path]::Combine($target,[Guid]::NewGuid().ToString('N')+'.probe')
59
- $handle=[IO.File]::Open($probe,[IO.FileMode]::CreateNew,[IO.FileAccess]::ReadWrite,[IO.FileShare]::None)
60
- try { $handle.WriteByte(0); $handle.Flush($true) } finally { $handle.Dispose() }
61
- [IO.File]::Delete($probe)
62
- $env:TEMP=$target
63
- $env:TMP=$target
64
- [Console]::Out.WriteLine('{"ready":true}')
65
- if ([Console]::ReadLine() -cne 'BLUN_STARTUP_TEMP_ACK_V1') { throw 'ack' }
66
- } catch {
67
- [Console]::Error.Write(('BLUN_PRIVATE_TEMP_ERROR_V2:{0}' -f $phase))
68
- exit 1
69
- }
70
- $ErrorActionPreference='Stop'
71
- $ProgressPreference='SilentlyContinue'
72
- try {
73
- $bytes=[Convert]::FromBase64String($env:BLUN_STARTUP_NATIVE)
74
- $mem=[IO.MemoryStream]::new($bytes)
75
- $zip=[IO.Compression.GZipStream]::new($mem,[IO.Compression.CompressionMode]::Decompress)
76
- $reader=[IO.StreamReader]::new($zip,[Text.Encoding]::UTF8)
77
- try { $null=Add-Type -TypeDefinition $reader.ReadToEnd() -Language CSharp } finally { $reader.Dispose();$zip.Dispose();$mem.Dispose();[Array]::Clear($bytes,0,$bytes.Length) }
78
- $sid=[Security.Principal.WindowsIdentity]::GetCurrent().User.Value
79
- while ($null -ne ($line=[Console]::ReadLine())) {
80
- $request=$line | ConvertFrom-Json
81
- $frame=$null
82
- try {
83
- [BlunPrivateAclNative]::Warnings.Clear()
84
- [BlunPrivateAclNative]::Repaired.Clear()
85
- [BlunPrivateAclNative]::OutsideProfile.Clear()
86
- [BlunPrivateAclNative]::StartupOwnerSid=$null
87
- switch ($request.kind) {
88
- 'directory' { [BlunPrivateAclNative]::InspectStartupDirectory($request.target,$sid) }
89
- 'temp-verify' { [BlunPrivateAclNative]::InspectStartupDirectory($request.target,$sid,$false);if ([BlunPrivateAclNative]::Warnings.Count -ne 0) { throw 'temp-acl' } }
90
- 'file' { [BlunPrivateAclNative]::HardenExisting($request.target,$sid,$false) }
91
- 'file-write' {
92
- $frame=[Convert]::FromBase64String($request.frame)
93
- [BlunPrivateAclNative]::WritePrivateFile($request.target,$sid,$frame)
94
- }
95
- default { throw 'Invalid startup operation' }
96
- }
97
- $result=@{ id=$request.id;ok=$true;directoryDaclWrites=[BlunPrivateAclNative]::DirectoryDaclWrites;warnings=@([BlunPrivateAclNative]::Warnings);repaired=@([BlunPrivateAclNative]::Repaired);outsideProfile=@([BlunPrivateAclNative]::OutsideProfile) }
98
- } catch {
99
- $nativeCode=0;$reason='unknown';$failure=$_.Exception
100
- for($depth=0;$depth -lt 8 -and $null -ne $failure;$depth++) {
101
- if($failure -is [ComponentModel.Win32Exception]){$nativeCode=$failure.NativeErrorCode;$reason='native-error';break}
102
- if($failure -is [UnauthorizedAccessException]){$reason='access-denied';break}
103
- if($failure -is [IO.IOException]){$reason='io-error';break}
104
- if($failure -is [ArgumentException]){$reason='argument-error';break}
105
- $failure=$failure.InnerException
106
- }
107
- $result=@{ id=$request.id;ok=$false;phase=[BlunPrivateAclNative]::CurrentPhase;target=[BlunPrivateAclNative]::CurrentTarget;nativeErrorCode=$nativeCode;reason=$reason;sid=$sid;ownerSid=[BlunPrivateAclNative]::StartupOwnerSid }
108
- } finally { if ($null -ne $frame) { [Array]::Clear($frame,0,$frame.Length) } }
109
- [Console]::Out.WriteLine(($result | ConvertTo-Json -Compress -Depth 5))
110
- }
111
- } catch { [Console]::Error.Write('BLUN_STARTUP_HOST_FAILED');exit 1 }
112
- `;
11
+ const SCRIPT = require('./startup-security-host.cjs');
113
12
  function createStartupSecurity(options) {
114
13
  const windows = (options.platform || process.platform) === 'win32';
115
14
  const counters = { powershell: 0, requests: 0, rootDaclWrites: 0 };
@@ -118,7 +17,10 @@ function createStartupSecurity(options) {
118
17
  let remainingMs=options.budgetMs ?? 10000;
119
18
  const warned = new Set();
120
19
  let budgetWarned=false;
121
- const warning=(code,target)=>(options.onWarning || (w=>process.emitWarning(w.message,{code:w.code})))(error(code,target));
20
+ const warnings = require('./startup-warning-policy.cjs').createStartupWarningReporter({
21
+ onWarning: options.onWarning, emitWarning: w => process.emitWarning(w.message, {code:w.code}),
22
+ });
23
+ const warning=(code,target)=>warnings.report(error(code,target));
122
24
  function fail(error) {
123
25
  fatal ||= error;
124
26
  rejectReady?.(fatal);
@@ -181,7 +83,7 @@ function createStartupSecurity(options) {
181
83
  warned.add(key);
182
84
  const w=error('BLUN_STARTUP_ROOT_ACL_NOT_REPAIRED_OUTSIDE_PROFILE',outside);
183
85
  w.message+=`; Außerhalb von %USERPROFILE%\\.blun wird die Ordner-DACL nicht repariert. Der Start wird bei Benutzerbesitz fortgesetzt.`;
184
- (options.onWarning || (w=>process.emitWarning(w.message,{code:w.code})))(w);
86
+ warnings.report(w);
185
87
  }
186
88
  }
187
89
  for (const repaired of value.repaired) {
@@ -192,7 +94,7 @@ function createStartupSecurity(options) {
192
94
  for (const warning of value.warnings) {
193
95
  if (typeof warning!=='string' || path.resolve(warning).toLowerCase()!==path.resolve(p.target).toLowerCase() || p.kind!=='directory') {p.reject(error('BLUN_STARTUP_SECURITY_PROTOCOL'));return fail(error('BLUN_STARTUP_SECURITY_PROTOCOL'));}
194
96
  const key=path.resolve(warning).toLowerCase();
195
- if (!warned.has(key)) {warned.add(key);(options.onWarning || (w=>process.emitWarning(w.message,{code:w.code})))(error('BLUN_STARTUP_ROOT_ACL_WARNING',warning));}
97
+ if (!warned.has(key)) {warned.add(key);warnings.report(error('BLUN_STARTUP_ROOT_ACL_WARNING',warning));}
196
98
  }
197
99
  p.resolve();
198
100
  });
@@ -244,6 +146,8 @@ function createStartupSecurity(options) {
244
146
  }
245
147
  const api={
246
148
  counters,
149
+ get diagnostics() { return warnings.snapshot(); },
150
+ get droppedDiagnostics() { return warnings.dropped(); },
247
151
  ensurePrivateDirectory:target=>request(target,'directory'),
248
152
  securePrivateFile:target=>request(target,'file'),
249
153
  writePrivateFile:(target,content)=>request(target,'file-write',content),
@@ -0,0 +1,22 @@
1
+ 'use strict';
2
+
3
+ function createStartupWarningReporter({ onWarning, emitWarning }) {
4
+ const records = [];
5
+ let dropped = 0;
6
+ return {
7
+ report(warning) {
8
+ const record = Object.freeze({ code: warning.code, privatePath: warning.privatePath });
9
+ if (records.length < 256) records.push(record);
10
+ else dropped += 1;
11
+ if (onWarning) return onWarning(warning);
12
+ // The native verifier has already accepted these additional read permissions
13
+ // or trusted owner/SYSTEM/Administrators grants. Keep diagnostic evidence
14
+ // without printing a Node warning and trace hint for a successful startup.
15
+ if (warning.code !== 'BLUN_STARTUP_ROOT_ACL_WARNING') emitWarning(warning);
16
+ },
17
+ snapshot: () => records.slice(),
18
+ dropped: () => dropped,
19
+ };
20
+ }
21
+
22
+ module.exports = { createStartupWarningReporter };
@@ -0,0 +1,125 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+
6
+ const LEASE_ADOPT_MESSAGE = 'blun-update-lease-adopted';
7
+ const LEASE_CANCEL_MESSAGE = 'blun-update-lease-cancel';
8
+ const LEASE_COMMIT_MESSAGE = 'blun-update-lease-commit';
9
+ const LEASE_HANDOFF_MESSAGE = 'blun-update-lease-handoff';
10
+ const LEASE_BUSY_MESSAGE = 'blun-update-lease-busy';
11
+ const LEASE_UNAVAILABLE_MESSAGE = 'blun-update-lease-unavailable';
12
+
13
+ function isInstallerMessage(message) {
14
+ if (!message || message.type !== LEASE_HANDOFF_MESSAGE) return false;
15
+ const installer = message.installer;
16
+ return installer
17
+ && typeof installer === 'object'
18
+ && typeof message.packageRoot === 'string'
19
+ && path.isAbsolute(message.packageRoot)
20
+ && typeof installer.npmCliPath === 'string'
21
+ && path.isAbsolute(installer.npmCliPath)
22
+ && Array.isArray(installer.npmArgs)
23
+ && installer.npmArgs.every((entry) => typeof entry === 'string')
24
+ && typeof installer.installCwd === 'string'
25
+ && path.isAbsolute(installer.installCwd);
26
+ }
27
+
28
+ function runInstallerWorker(tryAcquireUpdateLease) {
29
+ let state = 'BOOT';
30
+ let started = false;
31
+ let installLease;
32
+ let installCwd;
33
+ const isControlMessage = (message, type) => message
34
+ && typeof message === 'object'
35
+ && Object.getPrototypeOf(message) === Object.prototype
36
+ && Reflect.ownKeys(message).length === 1
37
+ && message.type === type;
38
+ const exitWithoutInstall = async (code = 0) => {
39
+ if (state === 'DONE') return;
40
+ state = 'DONE';
41
+ try {
42
+ await installLease?.release();
43
+ } catch {}
44
+ process.exit(code);
45
+ };
46
+ const startInstaller = (installer) => {
47
+ if (started || state !== 'COMMITTED') return;
48
+ started = true;
49
+ try {
50
+ installLease.assertOwned();
51
+ process.chdir(installer.installCwd);
52
+ process.argv = [process.execPath, installer.npmCliPath, ...installer.npmArgs];
53
+ require(installer.npmCliPath);
54
+ } catch {
55
+ process.exit(1);
56
+ }
57
+ };
58
+
59
+ process.once('message', async (message) => {
60
+ if (state !== 'BOOT' || !isInstallerMessage(message)) {
61
+ process.exit(1);
62
+ return;
63
+ }
64
+ state = 'PREPARED';
65
+ installCwd = message.installer.installCwd;
66
+ process.once('exit', () => {
67
+ if (!installCwd) return;
68
+ try {
69
+ process.chdir(path.dirname(installCwd));
70
+ fs.rmSync(installCwd, { recursive: true, force: true });
71
+ } catch {}
72
+ });
73
+ const leaseResult = await tryAcquireUpdateLease({
74
+ packageRoot: message.packageRoot,
75
+ role: 'install',
76
+ });
77
+ if (!leaseResult.acquired) {
78
+ const type = leaseResult.reason === 'busy'
79
+ ? LEASE_BUSY_MESSAGE
80
+ : LEASE_UNAVAILABLE_MESSAGE;
81
+ if (process.connected) {
82
+ try {
83
+ process.send({ type }, () => process.exit(75));
84
+ return;
85
+ } catch {}
86
+ }
87
+ process.exit(75);
88
+ return;
89
+ }
90
+ installLease = leaseResult.lease;
91
+ state = 'LEASED';
92
+ if (!process.connected) {
93
+ await exitWithoutInstall();
94
+ return;
95
+ }
96
+ const onControl = (control) => {
97
+ if (state !== 'LEASED') {
98
+ void exitWithoutInstall(1);
99
+ return;
100
+ }
101
+ if (isControlMessage(control, LEASE_CANCEL_MESSAGE)) {
102
+ void exitWithoutInstall();
103
+ return;
104
+ }
105
+ if (!isControlMessage(control, LEASE_COMMIT_MESSAGE)) {
106
+ void exitWithoutInstall(1);
107
+ return;
108
+ }
109
+ state = 'COMMITTED';
110
+ setImmediate(() => startInstaller(message.installer));
111
+ };
112
+ process.once('message', onControl);
113
+ try {
114
+ process.send({ type: LEASE_ADOPT_MESSAGE });
115
+ } catch {
116
+ process.removeListener('message', onControl);
117
+ await exitWithoutInstall();
118
+ }
119
+ });
120
+ process.once('disconnect', () => {
121
+ if (state !== 'COMMITTED' && state !== 'DONE') void exitWithoutInstall();
122
+ });
123
+ }
124
+
125
+ module.exports = { runInstallerWorker };