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,80 +0,0 @@
1
- 'use strict';
2
-
3
- const { createHash } = require('node:crypto');
4
- const fs = require('node:fs');
5
- const path = require('node:path');
6
-
7
- const STAND_SCHEMA = 'blun.snapshot-stand/v1';
8
- const SHA256_RE = /^[a-f0-9]{64}$/iu;
9
-
10
- function sha256(value) {
11
- return createHash('sha256').update(value).digest('hex');
12
- }
13
-
14
- function exactSha(value, label) {
15
- const digest = String(value || '').trim().toLowerCase();
16
- if (!SHA256_RE.test(digest)) throw new Error(`${label} must be a SHA256 digest`);
17
- return digest;
18
- }
19
-
20
- function isInside(root, candidate) {
21
- const relative = path.relative(root, candidate);
22
- return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));
23
- }
24
-
25
- function standMetadata(fsImpl, root, standPath) {
26
- if (!isInside(root, standPath)) throw new Error('SNAPSHOT_STAND_OUTSIDE_WORKSPACE');
27
- const parts = path.relative(root, standPath).split(path.sep);
28
- let cursor = root;
29
- let metadata;
30
- for (let index = 0; index < parts.length; index++) {
31
- cursor = path.join(cursor, parts[index]);
32
- metadata = fsImpl.lstatSync(cursor, { bigint: true });
33
- if (metadata.isSymbolicLink() || (index < parts.length - 1 ? !metadata.isDirectory() : !metadata.isFile())) {
34
- throw new Error('SNAPSHOT_STAND_NOT_REGULAR');
35
- }
36
- }
37
- if (!isInside(root, fsImpl.realpathSync(standPath))) throw new Error('SNAPSHOT_STAND_OUTSIDE_WORKSPACE');
38
- return metadata;
39
- }
40
-
41
- function sameFile(left, right) {
42
- return left.isFile() && right.isFile() && ['dev', 'ino', 'size', 'mtimeNs', 'ctimeNs']
43
- .every(key => left[key] === right[key]);
44
- }
45
-
46
- function verifyWorkspaceSnapshot(input, options = {}) {
47
- const fsImpl = options.fsImpl || fs;
48
- const root = fsImpl.realpathSync(path.resolve(input.root));
49
- const standPath = path.resolve(root, input.standFile || '.blun-snapshot-stand.json');
50
- const metadata = standMetadata(fsImpl, root, standPath);
51
- const descriptor = fsImpl.openSync(standPath, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
52
- let payload;
53
- try {
54
- const before = fsImpl.fstatSync(descriptor, { bigint: true });
55
- if (!sameFile(metadata, before)) throw new Error('SNAPSHOT_STAND_CHANGED');
56
- payload = fsImpl.readFileSync(descriptor);
57
- const after = fsImpl.fstatSync(descriptor, { bigint: true });
58
- if (!sameFile(before, after) || !sameFile(after, standMetadata(fsImpl, root, standPath))) {
59
- throw new Error('SNAPSHOT_STAND_CHANGED');
60
- }
61
- } finally { fsImpl.closeSync(descriptor); }
62
- const standSha256 = sha256(payload);
63
- if (standSha256 !== exactSha(input.expectedStandSha256, 'expectedStandSha256')) {
64
- throw new Error('SNAPSHOT_STAND_SHA256_MISMATCH');
65
- }
66
- let stand;
67
- try { stand = JSON.parse(payload.toString('utf8')); }
68
- catch { throw new Error('SNAPSHOT_STAND_INVALID_JSON'); }
69
- if (stand?.schema !== STAND_SCHEMA || typeof stand.projectId !== 'string') {
70
- throw new Error('SNAPSHOT_STAND_INVALID');
71
- }
72
- const snapshotSha256 = exactSha(stand.snapshotSha256, 'snapshotSha256');
73
- if (snapshotSha256 !== exactSha(input.expectedSnapshotSha256, 'expectedSnapshotSha256')) {
74
- throw new Error('SNAPSHOT_SHA256_MISMATCH');
75
- }
76
- if (stand.projectId !== input.projectId) throw new Error('SNAPSHOT_PROJECT_MISMATCH');
77
- return Object.freeze({ root, standPath, standSha256, snapshotSha256, projectId: stand.projectId });
78
- }
79
-
80
- module.exports = { STAND_SCHEMA, verifyWorkspaceSnapshot };
@@ -1,226 +0,0 @@
1
- import { createHash, randomUUID } from 'node:crypto';
2
- import { lstat, mkdir, open, readFile, realpath, rename, unlink } from 'node:fs/promises';
3
- import path from 'node:path';
4
-
5
- const SCHEMA = 'blun.king-goal-status/v2';
6
- const MAX_BYTES = 4 * 1024 * 1024;
7
- const STATES = new Set(['pending', 'dispatching', 'uncertain', 'delivered']);
8
- const RESULT_REJECTIONS = new Set(['GOAL_STEP_RESULT_EXCEEDS_64_KIB', 'GOAL_STEP_RESULT_INVALID_JSON',
9
- 'GOAL_STEP_RESULT_INVALID', 'GOAL_STEP_CHECKPOINT_REQUIRED', 'GOAL_STEP_CHECKPOINT_TOO_LARGE']);
10
- const digest = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
11
- const identifier = value => typeof value === 'string' && /^[A-Za-z0-9:._@/-]{1,200}$/.test(value);
12
- const routeKeys = ['id', 'provider', 'tenantId', 'accountId', 'chatId', 'threadId', 'agentId',
13
- 'projectId', 'groupId', 'createdAt'];
14
-
15
- export function goalResultRejectionCode(error) {
16
- const code = String(error?.message ?? error).replace(/^Host runtime unavailable: /, '');
17
- return RESULT_REJECTIONS.has(code) ? code : null;
18
- }
19
-
20
- function normalizeScope(input) {
21
- const keys = ['logicalPersonaId', 'runtimePersonaId', 'projectId', 'groupId', 'ownerSubjectId',
22
- 'chatId', 'senderId'];
23
- if (!input || keys.some(key => !identifier(input[key]))
24
- || (input.threadId !== null && input.threadId !== undefined && !identifier(input.threadId))) throw new Error('GOAL_STATUS_SCOPE_INVALID');
25
- return { ...Object.fromEntries(keys.map(key => [key, input[key]])), threadId: input.threadId ?? null };
26
- }
27
-
28
- function errorCode(error) {
29
- return /^(GOAL_[A-Z0-9_]{1,100})(?::|\s|$)/.exec(String(error ?? ''))?.[1] ?? 'GOAL_STATUS_OPERATION_REJECTED';
30
- }
31
-
32
- function normalizeEvent(input) {
33
- if (!input || !identifier(input.eventId)) throw new Error('GOAL_STATUS_EVENT_INVALID');
34
- if (input.kind === 'intake-rejected' && identifier(input.messageId)) {
35
- return { kind: input.kind, eventId: input.eventId, messageId: input.messageId, error: errorCode(input.error) };
36
- }
37
- if (!identifier(input.goalId) || (input.goalStepId !== null && input.goalStepId !== undefined && !identifier(input.goalStepId))) {
38
- throw new Error('GOAL_STATUS_EVENT_INVALID');
39
- }
40
- const event = { kind: input.kind, eventId: input.eventId, goalId: input.goalId, goalStepId: input.goalStepId ?? null };
41
- if (input.kind === 'result-rejected' && Number.isSafeInteger(input.attempt) && input.attempt > 0) {
42
- return { ...event, attempt: input.attempt, error: errorCode(input.error) };
43
- }
44
- if (input.kind !== 'goal-status' || !identifier(input.status)
45
- || !['offen', 'blockiert', 'bestanden'].includes(input.gate)) throw new Error('GOAL_STATUS_EVENT_INVALID');
46
- return { ...event, status: input.status, gate: input.gate };
47
- }
48
-
49
- function message(scope, event) {
50
- if (event.kind === 'intake-rejected') {
51
- return `${scope.logicalPersonaId} | Zielannahme Nachricht ${event.messageId} | abgelehnt | ${event.error}`;
52
- }
53
- if (event.kind === 'result-rejected') {
54
- return `${scope.logicalPersonaId} | Zielantwort ${event.goalId} / ${event.goalStepId ?? '-'} | abgelehnt ${event.attempt} | ${event.error}`;
55
- }
56
- return `${scope.logicalPersonaId} | Ziel ${event.goalId} | Schritt ${event.goalStepId ?? '-'} | ${event.status} | Gate ${event.gate}`;
57
- }
58
-
59
- function matches(binding, scope) {
60
- return binding?.status === 'active' && binding.provider === 'telegram'
61
- && binding.authority === 'explicit-local-channel-policy'
62
- && binding.agentId === scope.runtimePersonaId && binding.projectId === scope.projectId
63
- && binding.groupId === scope.groupId && binding.chatId === scope.chatId
64
- && (binding.threadId ?? null) === scope.threadId
65
- && binding.senderIds?.includes(scope.senderId) && binding.capabilities?.includes('reply');
66
- }
67
-
68
- function selectRoute(loaded, scope) {
69
- const candidates = loaded?.policy?.bindings?.filter(binding => matches(binding, scope)) ?? [];
70
- if (candidates.length !== 1) return null;
71
- const binding = candidates[0];
72
- if (routeKeys.some(key => key !== 'threadId' && (typeof binding[key] !== 'string' || !binding[key]))) return null;
73
- return Object.fromEntries(routeKeys.map(key => [key, binding[key] ?? null]));
74
- }
75
-
76
- function sameRoute(left, right) {
77
- return left && right && routeKeys.every(key => left[key] === right[key]);
78
- }
79
-
80
- async function assertRegular(file) {
81
- try {
82
- const meta = await lstat(file);
83
- if (!meta.isFile() || meta.isSymbolicLink()) throw new Error('GOAL_STATUS_NOT_REGULAR');
84
- } catch (error) { if (error.code !== 'ENOENT') throw error; }
85
- }
86
-
87
- async function loadState(file) {
88
- await assertRegular(file);
89
- let bytes;
90
- try { bytes = await readFile(file); } catch (error) {
91
- if (error.code === 'ENOENT') return { schema: SCHEMA, receipts: [] };
92
- throw error;
93
- }
94
- try {
95
- if (bytes.length > MAX_BYTES) throw new Error('oversized');
96
- const state = JSON.parse(bytes);
97
- if (state?.schema !== SCHEMA || !Array.isArray(state.receipts)) throw new Error('schema');
98
- const keys = new Set();
99
- for (const record of state.receipts) {
100
- const scope = normalizeScope(record.scope);
101
- const event = normalizeEvent(record.event);
102
- if (JSON.stringify(scope) !== JSON.stringify(record.scope) || JSON.stringify(event) !== JSON.stringify(record.event)
103
- || record.key !== digest({ scope, event }) || keys.has(record.key) || !STATES.has(record.status)
104
- || !Number.isSafeInteger(record.nextAttemptAt) || record.nextAttemptAt < 0
105
- || !Number.isSafeInteger(record.attempts) || record.attempts < 0
106
- || (record.route !== null && (!record.route || routeKeys.some(key => !(key in record.route))))
107
- || (record.status === 'delivered' && !/^telegram-message:\d+$/.test(record.receipt))) throw new Error('receipt');
108
- keys.add(record.key);
109
- }
110
- return state;
111
- } catch { throw new Error('GOAL_STATUS_STATE_INVALID'); }
112
- }
113
-
114
- async function saveState(file, state, assertOwned) {
115
- const bytes = JSON.stringify(state) + '\n';
116
- if (Buffer.byteLength(bytes) > MAX_BYTES) throw new Error('GOAL_STATUS_CAPACITY');
117
- const temporary = `${file}.${randomUUID()}.tmp`;
118
- const handle = await open(temporary, 'wx', 0o600);
119
- try {
120
- await handle.writeFile(bytes);
121
- await handle.sync();
122
- } finally { await handle.close(); }
123
- try {
124
- await assertOwned();
125
- await assertRegular(file);
126
- await rename(temporary, file);
127
- } finally { await unlink(temporary).catch(error => { if (error.code !== 'ENOENT') throw error; }); }
128
- }
129
-
130
- export function createGoalStatusReporter({ stateFile, scope: inputScope, withOwnedFileLock,
131
- loadPolicy, adapter, now = Date.now, maxRecords = 512 }) {
132
- const scope = normalizeScope(inputScope);
133
- if (!path.isAbsolute(stateFile) || typeof withOwnedFileLock !== 'function'
134
- || typeof loadPolicy !== 'function' || typeof adapter?.send !== 'function'
135
- || !Number.isSafeInteger(maxRecords) || maxRecords < 1) throw new Error('GOAL_STATUS_CONFIG_INVALID');
136
- const scopeKey = digest(scope);
137
- const transact = async task => {
138
- const directory = path.dirname(stateFile);
139
- await mkdir(directory, { recursive: true });
140
- if (path.relative(directory, await realpath(directory)) !== '') throw new Error('GOAL_STATUS_DIRECTORY_REDIRECTED');
141
- const assertPath = async () => {
142
- if (path.relative(directory, await realpath(directory)) !== '') throw new Error('GOAL_STATUS_DIRECTORY_REDIRECTED');
143
- await assertRegular(`${stateFile}.lock`);
144
- };
145
- return withOwnedFileLock(`${stateFile}.lock`, async ({ assertOwned }) => {
146
- const state = await loadState(stateFile);
147
- return task(state, () => saveState(stateFile, state, assertOwned), assertOwned);
148
- }, { assertPath });
149
- };
150
-
151
- const record = async input => {
152
- const event = normalizeEvent(input);
153
- return transact(async (state, save) => {
154
- const key = digest({ scope, event });
155
- const existing = state.receipts.find(row => row.key === key);
156
- if (existing) return { key, status: existing.status };
157
- // Retain the deduplication history and every unresolved delivery; never silently evict one.
158
- if (state.receipts.length >= maxRecords) throw new Error('GOAL_STATUS_CAPACITY');
159
- state.receipts.push({ key, scope, event, route: selectRoute(await loadPolicy(), scope),
160
- status: 'pending', attempts: 0, nextAttemptAt: 0, receipt: null });
161
- await save();
162
- return { key, status: 'pending' };
163
- });
164
- };
165
-
166
- const flush = () => transact(async (state, save, assertOwned) => {
167
- const results = [];
168
- for (const row of state.receipts) {
169
- if (digest(row.scope) !== scopeKey || row.status === 'delivered') continue;
170
- const result = status => { results.push({ key: row.key, status }); };
171
- // A process may have died after Telegram accepted the request but before the receipt was saved.
172
- if (row.status === 'dispatching') { row.status = 'uncertain'; await save(); }
173
- if (row.status === 'uncertain') { result('uncertain'); continue; }
174
- const current = selectRoute(await loadPolicy(), scope);
175
- if (!current) { result(row.route ? 'route-changed' : 'unrouted'); continue; }
176
- if (row.route && !sameRoute(row.route, current)) { result('route-changed'); continue; }
177
- if (row.nextAttemptAt > now()) { result('waiting'); continue; }
178
- row.route ??= current;
179
- row.status = 'dispatching'; row.attempts++;
180
- await save();
181
- if (!sameRoute(row.route, selectRoute(await loadPolicy(), scope))) {
182
- row.status = 'pending'; await save(); result('route-changed'); continue;
183
- }
184
- await assertOwned();
185
- let outcome;
186
- try {
187
- outcome = await adapter.send({ provider: row.route.provider, bindingId: row.route.id,
188
- tenantId: row.route.tenantId, accountId: row.route.accountId, chatId: row.route.chatId,
189
- threadId: row.route.threadId, replyTo: null,
190
- idempotencyKey: row.key, text: message(scope, row.event) });
191
- } catch { outcome = { ok: false, effect: 'unknown' }; }
192
- if (outcome?.ok === true && /^telegram-message:\d+$/.test(outcome.receipt)) {
193
- row.status = 'delivered'; row.receipt = outcome.receipt;
194
- } else if (outcome?.ok === false && outcome.effect === 'none') {
195
- row.status = 'pending';
196
- const wait = Number.isSafeInteger(outcome.retryAfterMs) && outcome.retryAfterMs > 0 ? outcome.retryAfterMs : 15000;
197
- row.nextAttemptAt = Math.min(Number.MAX_SAFE_INTEGER, now() + wait);
198
- } else { row.status = 'uncertain'; }
199
- await save();
200
- result(row.status);
201
- }
202
- return results;
203
- });
204
-
205
- const reconcile = async context => {
206
- for (const goal of context.goals) {
207
- if (goal.agentId !== scope.runtimePersonaId || goal.projectId !== scope.projectId
208
- || goal.groupId !== scope.groupId || goal.ownerSubjectId !== scope.ownerSubjectId) continue;
209
- const rows = context.queue.filter(row => row.goalId === goal.goalId && row.agentId === scope.runtimePersonaId
210
- && row.projectId === scope.projectId && row.groupId === scope.groupId && row.attempts > 0);
211
- const row = rows.toSorted((a, b) => a.updatedAt.localeCompare(b.updatedAt)).at(-1);
212
- if (!row) continue;
213
- const step = goal.plan?.steps.find(item => item.stepId === row.goalStepId);
214
- if (row.goalStepId && !step) continue;
215
- const identity = { eventId: `${row.queueId}:${row.attempts}`, goalId: goal.goalId, goalStepId: row.goalStepId ?? null };
216
- const rejection = goalResultRejectionCode(row.lastError);
217
- if (rejection) {
218
- await record({ ...identity, kind: 'result-rejected', attempt: row.attempts, error: rejection });
219
- }
220
- const status = row.status === 'blocked' ? 'blocked' : step?.status ?? goal.status;
221
- await record({ ...identity, kind: 'goal-status', status,
222
- gate: goal.status === 'completed' ? 'bestanden' : status === 'blocked' ? 'blockiert' : 'offen' });
223
- }
224
- };
225
- return Object.freeze({ record, flush, reconcile });
226
- }
@@ -1,160 +0,0 @@
1
- #!/usr/bin/env node
2
- import { appendFile, mkdir, readFile, realpath } from 'node:fs/promises';
3
- import path from 'node:path';
4
- import { fileURLToPath, pathToFileURL } from 'node:url';
5
- import { setTimeout as delay } from 'node:timers/promises';
6
- import { createGoalHostFactory } from './agentspine-king-host-runner.mjs';
7
- import { ingestGoalInbox } from './agentspine-king-goal-inbox.mjs';
8
- import { createGoalStatusReporter, goalResultRejectionCode } from './agentspine-king-status-policy.mjs';
9
- import snapshotPolicy from './agentspine-king-snapshot-policy.cjs';
10
-
11
- const packageRoot = path.resolve(import.meta.dirname, '..');
12
- const required = ['blunHome', 'profile', 'projectRoot', 'projectId', 'standFile', 'expectedStandSha256',
13
- 'expectedSnapshotSha256', 'exchangeDirectory', 'telegramQueueFile', 'instructionSenderId', 'instructionChatId',
14
- 'logicalPersonaId', 'runtimePersonaId', 'groupId', 'ownerSubjectId', 'permission', 'gatewayStateDirectory'];
15
-
16
- export async function loadWorkerConfig(file) {
17
- const config = JSON.parse(await readFile(path.resolve(file), 'utf8'));
18
- if (config?.schema !== 'blun.king-goal-worker-config/v1'
19
- || required.some(key => typeof config[key] !== 'string' || !config[key])
20
- || (config.instructionThreadId !== null && config.instructionThreadId !== undefined && (typeof config.instructionThreadId !== 'string'
21
- || !/^[1-9][0-9]*$/.test(config.instructionThreadId) || !Number.isSafeInteger(Number(config.instructionThreadId))))
22
- || !['manual', 'auto', 'yolo'].includes(config.permission)) throw new Error('KING_WORKER_CONFIG_INVALID');
23
- for (const key of ['blunHome', 'projectRoot', 'exchangeDirectory', 'telegramQueueFile', 'gatewayStateDirectory']) {
24
- if (!path.isAbsolute(config[key])) throw new Error('KING_WORKER_ABSOLUTE_PATH_REQUIRED');
25
- }
26
- const blunHome = await realpath(config.blunHome);
27
- const relative = path.relative(blunHome, path.resolve(config.gatewayStateDirectory));
28
- if (path.isAbsolute(relative) || relative === '..' || relative.startsWith('..' + path.sep)) throw new Error('KING_WORKER_STATE_OUTSIDE_APP_HOME');
29
- const state = await realpath(config.gatewayStateDirectory);
30
- const canonicalRelative = path.relative(blunHome, state);
31
- if (path.isAbsolute(canonicalRelative) || canonicalRelative === '..' || canonicalRelative.startsWith('..' + path.sep)) {
32
- throw new Error('KING_WORKER_STATE_OUTSIDE_APP_HOME');
33
- }
34
- return Object.freeze({ ...config, blunHome, gatewayStateDirectory: state, projectRoot: await realpath(config.projectRoot) });
35
- }
36
-
37
- export async function runGuardedWorkerTick(context) {
38
- const { config, gateway, hostFactory, env, adapter } = context;
39
- const snapshot = snapshotPolicy.verifyWorkspaceSnapshot({ root: config.projectRoot, projectId: config.projectId,
40
- standFile: config.standFile, expectedStandSha256: config.expectedStandSha256,
41
- expectedSnapshotSha256: config.expectedSnapshotSha256 });
42
- const personas = await gateway.loadPersonaRuntime(snapshot.root);
43
- const persona = personas.runtime.personas.find(item => item.personaId === config.runtimePersonaId && item.status === 'active');
44
- const binding = personas.policy.bindings.find(item => item.id === persona?.bindingId && item.active);
45
- if (!binding || binding.profileId !== config.profile || binding.groupId !== config.groupId) {
46
- throw new Error('KING_WORKER_IDENTITY_MISMATCH');
47
- }
48
- const { withOwnedFileLock } = await import(pathToFileURL(path.join(packageRoot,
49
- 'agent-spine-plugin/src/lib/owned-file-lock.js')).href);
50
- const statusReporter = createGoalStatusReporter({
51
- stateFile: path.join(config.blunHome, 'worker', 'goal-status-v2.json'),
52
- scope: { logicalPersonaId: config.logicalPersonaId, runtimePersonaId: config.runtimePersonaId,
53
- projectId: config.projectId, groupId: config.groupId, ownerSubjectId: config.ownerSubjectId,
54
- chatId: config.instructionChatId, senderId: config.instructionSenderId,
55
- threadId: config.instructionThreadId ?? null },
56
- withOwnedFileLock, loadPolicy: () => gateway.loadChannelPolicy(snapshot.root), adapter,
57
- });
58
- const statusReports = [];
59
- const reportCommittedStatus = async () => {
60
- const context = await gateway.gatewayContext({ root: snapshot.root, agentId: config.runtimePersonaId });
61
- if (!context.enabled || context.killSwitch) return;
62
- await statusReporter.reconcile(context);
63
- statusReports.push(...await statusReporter.flush());
64
- };
65
- // Reconcile the saved goal state first: a prior process may have stopped after committing its tick.
66
- await reportCommittedStatus();
67
- const intake = await ingestGoalInbox({ exchangeDirectory: config.exchangeDirectory,
68
- queueFile: config.telegramQueueFile, checkpointFile: path.join(config.blunHome, 'worker', 'goal-queue-checkpoint.json'),
69
- instructionSenderId: config.instructionSenderId, instructionChatId: config.instructionChatId,
70
- instructionThreadId: config.instructionThreadId,
71
- logicalPersonaId: config.logicalPersonaId, runtimePersonaId: config.runtimePersonaId,
72
- projectId: config.projectId, groupId: config.groupId, ownerSubjectId: config.ownerSubjectId,
73
- snapshot, assignGoal: gateway.assignGoal,
74
- recordResult: result => result.status === 'rejected'
75
- ? statusReporter.record({ kind: 'intake-rejected', eventId: result.eventId,
76
- messageId: result.messageId, error: result.error }) : undefined });
77
- const result = await gateway.runWorkerTick({ root: snapshot.root, workerId: 'gateway-worker:blun:' + process.pid,
78
- agentId: config.runtimePersonaId, projectId: config.projectId, groupId: config.groupId,
79
- goalOnly: true, env,
80
- hostFactory: async item => {
81
- const host = await hostFactory(item);
82
- return { ...host, async run() {
83
- try { return await host.run(); }
84
- catch (error) {
85
- const rejection = goalResultRejectionCode(error);
86
- if (rejection) {
87
- // Record the concrete parser failure before the gateway replaces it with an execution hold.
88
- await statusReporter.record({ kind: 'result-rejected', eventId: `${item.queueId}:${item.attempts}`,
89
- goalId: item.goal.goalId, goalStepId: item.goalStep?.stepId ?? null,
90
- attempt: item.attempts, error: rejection });
91
- }
92
- throw error;
93
- }
94
- } };
95
- },
96
- adapter: { send: item => adapter.send(item) } });
97
- await reportCommittedStatus();
98
- return { ...result, intake, statusReports };
99
- }
100
-
101
- export async function runWorkerHost(config, { once = false, signal, onResult = () => {} } = {}) {
102
- const gateway = await import(pathToFileURL(path.join(packageRoot, 'agent-spine-plugin/src/index.js')).href);
103
- const { createKingWorkerHarness, LocalKaos } = await import(pathToFileURL(path.join(packageRoot, 'worker-host.mjs')).href);
104
- const env = { ...process.env, BLUN_HOME: config.blunHome, BLUN_PROFILE: config.profile };
105
- const harness = createKingWorkerHarness({ homeDir: config.blunHome, configPath: config.settingsPath });
106
- const hostFactory = createGoalHostFactory({ harness, workDir: config.projectRoot, model: config.model,
107
- permission: config.permission, tickTimeoutMs: config.tickTimeoutMs, cleanupTimeoutMs: config.cleanupTimeoutMs,
108
- sessionOptions: { kaos: (await LocalKaos.create()).withCwd(config.projectRoot).withEnv({
109
- BLUN_HOME: config.blunHome, BLUN_PROFILE: config.profile, AGENTSPINE_STATE_DIR: config.gatewayStateDirectory,
110
- }) },
111
- signal });
112
- const adapter = gateway.createTelegramAdapter({ root: config.projectRoot, env });
113
- try {
114
- do {
115
- if (signal?.aborted) return { status: 'stopped', processed: false };
116
- const result = await runGuardedWorkerTick({ config, gateway, hostFactory, env, adapter });
117
- await mkdir(path.join(config.blunHome, 'worker'), { recursive: true });
118
- await appendFile(path.join(config.blunHome, 'worker', 'worker.log'), JSON.stringify({
119
- schema: 'blun.king-goal-worker-log/v1', at: new Date().toISOString(), status: result.status,
120
- queueId: result.queueId ?? null, hostSettlement: result.hostSettlement ?? null,
121
- statusReports: result.statusReports,
122
- intake: result.intake.map(item => ({ status: item.status, messageId: item.messageId, error: item.error }))
123
- }) + '\n', { mode: 0o600 });
124
- await onResult(result);
125
- if (once || result.status === 'stopped' || result.status === 'blocked') return result;
126
- await delay(result.processed ? 1000 : 15000, undefined, { signal }).catch(error => {
127
- if (error.name !== 'AbortError') throw error;
128
- });
129
- } while (!signal?.aborted);
130
- return { status: 'stopped', processed: false };
131
- } finally {
132
- let quiet = true;
133
- for (const session of harness.sessions.values()) {
134
- const proof = await session.quiesce({ deadlineAt: Date.now() + (config.cleanupTimeoutMs ?? 10000) }).catch(() => null);
135
- if (!proof || proof.status !== 'quiescent' || proof.remaining.length) quiet = false;
136
- }
137
- // Never turn a cleanup deadline into a successful host termination acknowledgement.
138
- if (quiet) await harness.close();
139
- }
140
- }
141
-
142
- async function main() {
143
- const args = process.argv.slice(2);
144
- const index = args.indexOf('--config');
145
- if (index < 0 || !args[index + 1] || args[index + 1].startsWith('--')) throw new Error('--config requires a path');
146
- const config = await loadWorkerConfig(args[index + 1]);
147
- process.env.BLUN_HOME = config.blunHome;
148
- process.env.BLUN_PROFILE = config.profile;
149
- process.env.AGENTSPINE_STATE_DIR = config.gatewayStateDirectory;
150
- const controller = new AbortController();
151
- const stop = () => controller.abort();
152
- process.once('SIGINT', stop); process.once('SIGTERM', stop);
153
- try { await runWorkerHost(config, { once: args.includes('--once'), signal: controller.signal,
154
- onResult: result => process.stdout.write(JSON.stringify(result) + '\n') }); }
155
- finally { process.removeListener('SIGINT', stop); process.removeListener('SIGTERM', stop); }
156
- }
157
-
158
- if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
159
- main().catch(error => { process.stderr.write(String(error.message).slice(0, 500) + '\n'); process.exitCode = 1; });
160
- }
@@ -1,141 +0,0 @@
1
- 'use strict';
2
- const { createHash, randomUUID } = require('node:crypto');
3
- const fs = require('node:fs');
4
- const path = require('node:path');
5
- const { renamePrivateStaging } = require('./rename-private-staging.cjs');
6
- const { ensurePrivateDirectory, securePrivateTree } = require('./private-paths');
7
- const SCHEMA = 'blun.managed-plugin-selection/v1';
8
-
9
- function snapshotPluginTree(root) {
10
- const entries = [];
11
- const rootStat = fs.lstatSync(root);
12
- if (rootStat.isSymbolicLink() || !rootStat.isDirectory()) return null;
13
- const visit = (directory, relativeDirectory = '') => {
14
- for (const entry of fs.readdirSync(directory, { withFileTypes: true })
15
- .sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0)) {
16
- const relativePath = path.join(relativeDirectory, entry.name);
17
- const absolutePath = path.join(directory, entry.name);
18
- const stat = fs.lstatSync(absolutePath);
19
- if (stat.isSymbolicLink()) return false;
20
- if (stat.isDirectory()) {
21
- entries.push({ kind: 'directory', path: relativePath });
22
- if (!visit(absolutePath, relativePath)) return false;
23
- } else if (stat.isFile()) {
24
- entries.push({ kind: 'file', path: relativePath, content: fs.readFileSync(absolutePath) });
25
- } else return false;
26
- }
27
- return true;
28
- };
29
- return visit(root) ? entries : null;
30
- }
31
-
32
- function digestPluginEntries(entries) {
33
- if (entries === null) throw new Error('Invalid managed plugin tree');
34
- const hash = createHash('sha256');
35
- for (const entry of entries) {
36
- hash.update(Buffer.from(`${entry.kind}\0${entry.path}\0`, 'utf8'));
37
- if (entry.kind === 'file') {
38
- const length = Buffer.allocUnsafe(8);
39
- length.writeBigUInt64BE(BigInt(entry.content.length));
40
- hash.update(length);
41
- hash.update(entry.content);
42
- }
43
- }
44
- return hash.digest('hex');
45
- }
46
-
47
- function samePath(left, right) {
48
- const normalize = value => process.platform === 'win32' ? path.resolve(value).toLowerCase() : path.resolve(value);
49
- return normalize(left) === normalize(right);
50
- }
51
-
52
- function scopedPluginRoot(blunDir, pluginRoot) {
53
- const managed = path.resolve(blunDir, 'plugins', 'managed');
54
- const root = path.resolve(pluginRoot);
55
- if (!samePath(path.dirname(root), managed)) throw new Error('Selected AgentSpine root is outside this profile');
56
- for (const directory of [blunDir, path.dirname(managed), managed, root]) {
57
- const stat = fs.lstatSync(directory);
58
- if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Error('Selected AgentSpine root contains a linked directory');
59
- }
60
- if (!samePath(path.dirname(fs.realpathSync(root)), fs.realpathSync(managed))) {
61
- throw new Error('Selected AgentSpine root resolves outside this profile');
62
- }
63
- return root;
64
- }
65
-
66
- function describeAgentSpineSelection({ blunDir, pluginRoot }) {
67
- const root = scopedPluginRoot(blunDir, pluginRoot);
68
- const digest = digestPluginEntries(snapshotPluginTree(root));
69
- if (path.basename(root) !== `agent-spine-${digest}`) throw new Error('Selected AgentSpine digest mismatch');
70
- return { schema: SCHEMA, digest };
71
- }
72
-
73
- function selectedAgentSpineRoot({ installed, blunDir }) {
74
- const records = installed.plugins.filter(record => record.id === 'agent-spine');
75
- if (!records.some(record => Object.hasOwn(record, 'managedSelection'))) return null;
76
- if (records.length !== 1) throw new Error('Ambiguous AgentSpine selection');
77
- const [record] = records;
78
- const selection = record.managedSelection;
79
- if (!selection || selection.schema !== SCHEMA || !/^[a-f0-9]{64}$/.test(selection.digest || '')
80
- || Object.keys(selection).sort().join(',') !== 'digest,schema' || typeof record.root !== 'string') {
81
- throw new Error('Invalid AgentSpine selection');
82
- }
83
- const actual = describeAgentSpineSelection({ blunDir, pluginRoot: record.root });
84
- if (actual.digest !== selection.digest) throw new Error('Selected AgentSpine digest mismatch');
85
- return record.root;
86
- }
87
-
88
- function copySelectedAgentSpinePlugin({ blunDir, sourceRoot }) {
89
- const plugins = path.resolve(blunDir, 'plugins');
90
- const managed = path.join(plugins, 'managed');
91
- ensurePrivateDirectory(plugins);
92
- ensurePrivateDirectory(managed);
93
- const digest = digestPluginEntries(snapshotPluginTree(sourceRoot));
94
- const pluginRoot = path.join(managed, `agent-spine-${digest}`);
95
- if (fs.existsSync(pluginRoot)) {
96
- describeAgentSpineSelection({ blunDir, pluginRoot });
97
- return pluginRoot;
98
- }
99
- const staging = path.join(managed, `.agent-spine-selected-${process.pid}-${randomUUID()}.tmp`);
100
- try {
101
- fs.cpSync(sourceRoot, staging, { recursive: true, errorOnExist: true, force: false });
102
- securePrivateTree(staging);
103
- if (digestPluginEntries(snapshotPluginTree(staging)) !== digest) throw new Error('AgentSpine source changed during installation');
104
- renamePrivateStaging(staging, pluginRoot);
105
- describeAgentSpineSelection({ blunDir, pluginRoot });
106
- return pluginRoot;
107
- } finally {
108
- if (!samePath(path.dirname(staging), managed) || !path.basename(staging).startsWith('.agent-spine-selected-')) {
109
- throw new Error('Invalid AgentSpine staging cleanup path');
110
- }
111
- fs.rmSync(staging, { recursive: true, force: true });
112
- }
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
- }
139
-
140
- module.exports = { copySelectedAgentSpinePluginAsync, snapshotPluginTree, digestPluginEntries, describeAgentSpineSelection,
141
- selectedAgentSpineRoot, copySelectedAgentSpinePlugin };