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,257 +0,0 @@
1
- #!/usr/bin/env node
2
- import { spawn } from "node:child_process";
3
- import { watch } from "node:fs";
4
- import { lstat, realpath } from "node:fs/promises";
5
- import { isAbsolute, join, resolve } from "node:path";
6
- import {
7
- claimGatewayWork, completeGatewayRun, deliverPrepared, executionAttemptForStep,
8
- failGatewayRun, loadGatewayRuntime, markGatewayHostStarted, reconcileGateway, updateGatewayHealth
9
- } from "./lib/gateway-runtime.js";
10
- import { createTelegramAdapter } from "./lib/telegram-adapter.js";
11
- import { acknowledgeChannelDelivery, loadChannelRuntime } from "./lib/channel-runtime.js";
12
- import { channelTimelineContinuity } from "./lib/channel-continuity.js";
13
- import { groupResponseContract, settleSuppressedGroupEvents } from "./lib/gateway-group-response.js";
14
- import { loadPersonaRuntime, syncPersonaRosterFromEnvironment } from "./lib/persona-runtime.js";
15
- import { selfHelpPolicyForWorkItem } from "./lib/knowledge-evidence.js";
16
- import { isMainModule } from "./lib/runtime.js";
17
- import { executePreparedHost } from "./lib/gateway-prepared-host.js";
18
- import { gatewayWorkMatcher } from "./lib/gateway-runs.js";
19
-
20
- const MAX_FRAME = 64 * 1024;
21
- const WAKE_FILES = new Set(["attention.json", "channel-runtime.json", "gateway-policy.json", "persona-policy.json", "persona-runtime.json"]);
22
-
23
- async function wakeSnapshot(directory) {
24
- return Promise.all([...WAKE_FILES].sort().map(async (name) => {
25
- try {
26
- const metadata = await lstat(join(directory, name), { bigint: true });
27
- return `${name}:${metadata.dev}:${metadata.ino}:${metadata.size}:${metadata.mtimeNs}`;
28
- } catch (error) {
29
- if (error.code === "ENOENT") return `${name}:missing`;
30
- throw error;
31
- }
32
- })).then((entries) => entries.join("\n"));
33
- }
34
-
35
- export async function waitForGatewayWake(root, delayMs, { watchFactory = watch, realpathFactory = realpath, onReady = null } = {}) {
36
- const delay = Math.max(250, Math.min(60000, Number(delayMs) || 60000));
37
- const { directory } = await loadGatewayRuntime(root);
38
- let watchPath;
39
- try { watchPath = await realpathFactory(directory); } catch { return "watch-unavailable"; }
40
- let before;
41
- try { before = await wakeSnapshot(watchPath); } catch { return "watch-unavailable"; }
42
- return new Promise((resolvePromise) => {
43
- let settled = false; let watcher;
44
- const finish = (reason) => {
45
- if (settled) return;
46
- settled = true; clearTimeout(timer);
47
- watcher?.close();
48
- resolvePromise(reason);
49
- };
50
- const timer = setTimeout(() => finish("timer"), delay);
51
- try {
52
- watcher = watchFactory(watchPath, { persistent: true }, (_eventType, filename) => {
53
- const name = filename === null ? null : String(filename);
54
- if (name === null || WAKE_FILES.has(name)) finish("event");
55
- });
56
- watcher.on?.("error", () => finish("watch-error"));
57
- Promise.resolve().then(() => onReady?.(watchPath)).then(() => wakeSnapshot(watchPath)).then((after) => {
58
- if (after !== before) finish("event");
59
- }).catch(() => finish("watch-error"));
60
- } catch { finish("watch-unavailable"); }
61
- });
62
- }
63
-
64
- function exactRunner(env) {
65
- const runner = env.AGENTSPINE_HOST_RUNNER;
66
- if (!runner || !isAbsolute(runner)) throw new Error("AGENTSPINE_HOST_RUNNER must be an absolute locally approved executable path");
67
- return resolve(runner);
68
- }
69
-
70
- async function invokeHostRunner(item, { env = process.env, timeoutMs = 300000, spawnProcess = spawn } = {}) {
71
- const executable = exactRunner(env);
72
- return new Promise((resolvePromise, reject) => {
73
- const child = spawnProcess(executable, [], {
74
- shell: false, windowsHide: true, stdio: ["pipe", "pipe", "pipe"],
75
- env: Object.fromEntries(["PATH", "Path", "HOME", "USERPROFILE", "SystemRoot", "SYSTEMROOT", "WINDIR",
76
- "AGENTSPINE_STATE_DIR", "CLAUDE_CONFIG_DIR", "CODEX_HOME"].filter((key) => env[key] !== undefined).map((key) => [key, env[key]]))
77
- });
78
- let stdout = Buffer.alloc(0); let stderr = Buffer.alloc(0); let settled = false;
79
- const finish = (error, value) => { if (settled) return; settled = true; clearTimeout(timer); error ? reject(error) : resolvePromise(value); };
80
- child.stdout.on("data", (chunk) => { stdout = Buffer.concat([stdout, chunk]); if (stdout.length > MAX_FRAME) child.kill(); });
81
- child.stderr.on("data", (chunk) => { stderr = Buffer.concat([stderr, chunk]).subarray(0, 2048); });
82
- child.on("error", (error) => finish(error));
83
- child.on("close", (code) => {
84
- if (stdout.length > MAX_FRAME) return finish(new Error("host runner response exceeds 64 KiB"));
85
- if (code !== 0) return finish(new Error("host runner failed: " + stderr.toString("utf8").slice(0, 2048)));
86
- try { finish(null, JSON.parse(stdout.toString("utf8"))); } catch { finish(new Error("host runner returned invalid JSON")); }
87
- });
88
- const timer = setTimeout(() => { child.kill(); finish(new Error("host runner exceeded its bounded timeout")); }, timeoutMs);
89
- child.stdin.end(JSON.stringify({ schema: "agentspine.run-request/v1", item, authority: "execution-state-only" }) + "\n");
90
- });
91
- }
92
-
93
- async function hostWorkItem(root, item) {
94
- const [{ policy }, personas, channel] = await Promise.all([
95
- loadGatewayRuntime(root), loadPersonaRuntime(root), loadChannelRuntime(root)
96
- ]);
97
- const persona = personas.runtime.personas.find((entry) => entry.personaId === item.agentId && entry.status === "active");
98
- const identity = personas.policy.bindings.find((entry) => entry.id === persona?.bindingId && entry.active);
99
- if (!persona || !identity) throw new Error("claimed work lost its authenticated agent identity");
100
- const goal = item.goalId === null ? null : policy.goals.find((entry) => entry.goalId === item.goalId) || null;
101
- const goalStep = item.goalStepId === null || item.goalStepId === undefined ? null
102
- : goal?.plan?.steps.find((entry) => entry.stepId === item.goalStepId) || null;
103
- if (item.goalStepId && !goalStep) throw new Error("claimed work lost its exact goal-plan step");
104
- const executionAttempt = executionAttemptForStep(goalStep);
105
- const event = item.channelEventId === null ? null
106
- : channel.runtime.events.find((entry) => entry.eventId === item.channelEventId) || null;
107
- if (item.channelEventId && !event) throw new Error("claimed channel work lost its exact event");
108
- const continuity = channelTimelineContinuity(event);
109
- return {
110
- ...structuredClone(item), host: identity.host, profileId: identity.profileId, projectRoot: root,
111
- goal: goal ? structuredClone(goal) : null,
112
- goalStep: goalStep ? { ...structuredClone(goalStep),
113
- ...(executionAttempt === null ? {} : { executionAttempt }) } : null,
114
- selfHelpPolicy: goalStep ? selfHelpPolicyForWorkItem(goalStep) : null,
115
- groupResponseContract: groupResponseContract(event),
116
- hostEnvironment: {
117
- AGENTSPINE_GATEWAY_CONTEXT: "agentspine.gateway-start/v1",
118
- AGENTSPINE_ENTITY_ID: item.agentId,
119
- AGENTSPINE_PROJECT_ID: item.projectId,
120
- AGENTSPINE_HOST: identity.host,
121
- AGENTSPINE_GATEWAY_QUEUE_ID: item.queueId,
122
- AGENTSPINE_GATEWAY_ATTEMPT: String(item.attempts),
123
- ...(item.groupId === null ? {} : { AGENTSPINE_GROUP_ID: item.groupId }),
124
- ...(goalStep ? {
125
- AGENTSPINE_GOAL_ID: goal.goalId,
126
- AGENTSPINE_GOAL_STEP_ID: goalStep.stepId,
127
- AGENTSPINE_PLAN_DEFINITIONS_DIGEST: goal.plan.definitionsDigest
128
- } : {}),
129
- ...(event ? {
130
- AGENTSPINE_CHANNEL_EVENT_ID: event.eventId,
131
- AGENTSPINE_CHANNEL_PROVIDER: event.provider,
132
- AGENTSPINE_PORTAL_REF: continuity.portalRef,
133
- AGENTSPINE_THREAD_REF: continuity.threadRef
134
- } : {})
135
- },
136
- channelStart: event ? {
137
- agent_spine_scope: { entity_id: event.agentId, project_id: event.projectId, group_id: event.groupId },
138
- agent_spine_channel_event: { event_id: event.eventId, provider: event.provider },
139
- session_key: event.sessionKey,
140
- authority: "explicit-local-channel-policy"
141
- } : null
142
- };
143
- }
144
-
145
- export async function runWorkerTick({ root = process.cwd(), workerId = "gateway-worker:local", now = null,
146
- hostRunner = invokeHostRunner, hostFactory = null, agentId = null, projectId = null, groupId, goalOnly = false,
147
- clock = null, adapter = null, env = process.env } = {}) {
148
- // Explicit `now` remains a deterministic test clock; production reads the clock at each boundary.
149
- const fixedTime = now;
150
- const currentTime = clock ?? (fixedTime === null ? () => new Date() : () => fixedTime);
151
- const matchesWork = gatewayWorkMatcher({ agentId, projectId, groupId, goalOnly });
152
- now = currentTime();
153
- const deliveryAdapter = adapter || createTelegramAdapter({ root, env });
154
- await syncPersonaRosterFromEnvironment({ root, env, now });
155
- const initial = await loadGatewayRuntime(root);
156
- if (!initial.policy.enabled || initial.policy.killSwitch) return { status: "stopped", processed: false };
157
- await settleSuppressedGroupEvents({ root, now });
158
- if (typeof deliveryAdapter.poll === "function") {
159
- try { await deliveryAdapter.poll(); }
160
- catch (error) {
161
- await updateGatewayHealth({ root, worker: "degraded", adapter: "failed", now });
162
- throw error;
163
- }
164
- }
165
- await reconcileGateway({ root, now });
166
- await updateGatewayHealth({ root, worker: "healthy", adapter: "healthy", now });
167
- const afterReconcile = await loadGatewayRuntime(root);
168
- const queueById = new Map(afterReconcile.runtime.queue.map((item) => [item.queueId, item]));
169
- const dueOutbox = afterReconcile.runtime.outbox.filter((item) => ["prepared", "failed"].includes(item.status)
170
- && matchesWork(queueById.get(item.queueId))
171
- && new Date(item.nextAttemptAt) <= new Date(now)).sort((a, b) => a.nextAttemptAt.localeCompare(b.nextAttemptAt)
172
- || a.createdAt.localeCompare(b.createdAt) || a.outboxId.localeCompare(b.outboxId))[0] || null;
173
- if (dueOutbox) {
174
- const delivery = await deliverPrepared({ root, outboxId: dueOutbox.outboxId, adapter: deliveryAdapter, now });
175
- if (delivery.outbox.status === "delivered") await acknowledgeChannelDelivery({ root,
176
- eventId: delivery.outbox.eventId, bindingId: delivery.outbox.bindingId,
177
- deliveryReceiptId: delivery.receipt.id, now });
178
- return { status: delivery.outbox.status, processed: true, outboxId: delivery.outbox.outboxId,
179
- recoveredDelivery: true };
180
- }
181
- const claim = await claimGatewayWork({ root, workerId, agentId, projectId, groupId, goalOnly, executionMode: "host-effect", now });
182
- if (!claim.item) return { status: claim.reason, processed: false };
183
- let result; let quiescence;
184
- try {
185
- const item = await hostWorkItem(root, claim.item);
186
- if (hostFactory) ({ result, quiescence } = await executePreparedHost({
187
- root, item, hostFactory, env, clock: currentTime
188
- }));
189
- else {
190
- await markGatewayHostStarted({ root, queueId: item.queueId, workerId,
191
- claimedAt: item.lease.claimedAt, attempt: item.attempts, now });
192
- result = await hostRunner(item, { env });
193
- }
194
- }
195
- catch (error) {
196
- const failed = await failGatewayRun({ root, queueId: claim.item.queueId, workerId,
197
- claimedAt: claim.item.lease.claimedAt, attempt: claim.item.attempts,
198
- error: "Host runtime unavailable: " + String(error.message).slice(0, 400), now: currentTime() });
199
- return { status: failed.item.status, processed: true, queueId: failed.item.queueId, retryAt: failed.item.availableAt };
200
- }
201
- const completed = await completeGatewayRun({ root, queueId: claim.item.queueId, workerId,
202
- claimedAt: claim.item.lease.claimedAt, attempt: claim.item.attempts, result, quiescence, now: currentTime() });
203
- if (completed.communication?.suppressed) {
204
- await settleSuppressedGroupEvents({ root, now });
205
- return { status: "silent", processed: true, queueId: completed.item.queueId,
206
- communication: completed.communication, deliveryConfirmed: false, completionVerified: false };
207
- }
208
- if (!completed.outbox) return {
209
- status: completed.clarification ? "needs-clarification"
210
- : completed.exploration ? "exploring" : completed.selfHelp ? "self-help-resolved"
211
- : completed.selfHelpRequired ? "self-help-required" : completed.item.status,
212
- processed: true, queueId: completed.item.queueId, hostSettlement: completed.hostSettlement,
213
- ...(completed.clarification ? { clarification: completed.clarification } : {}),
214
- ...(completed.exploration ? { exploration: completed.exploration } : {}),
215
- ...(completed.selfHelp ? { selfHelp: completed.selfHelp } : {}),
216
- ...(completed.selfHelpRequired ? { selfHelpRequired: completed.selfHelpRequired } : {})
217
- };
218
- const delivery = await deliverPrepared({ root, outboxId: completed.outbox.outboxId,
219
- adapter: deliveryAdapter, now: currentTime() });
220
- if (delivery.outbox.status === "delivered") await acknowledgeChannelDelivery({ root,
221
- eventId: delivery.outbox.eventId, bindingId: delivery.outbox.bindingId,
222
- deliveryReceiptId: delivery.receipt.id, now: currentTime() });
223
- return { status: delivery.outbox.status, processed: true, queueId: completed.item.queueId, outboxId: delivery.outbox.outboxId };
224
- }
225
-
226
- export async function runWorker({ root = process.cwd(), once = false, env = process.env,
227
- waitForWake = waitForGatewayWake } = {}) {
228
- const workerId = "gateway-worker:" + process.pid;
229
- do {
230
- const result = await runWorkerTick({ root, workerId, env });
231
- if (once) return result;
232
- const { policy, runtime } = await loadGatewayRuntime(root);
233
- if (!policy.enabled || policy.killSwitch) return { status: "stopped", processed: false };
234
- const pending = [
235
- ...runtime.queue.filter((item) => item.status === "pending").map((item) => new Date(item.availableAt).getTime()),
236
- ...runtime.outbox.filter((item) => ["prepared", "failed"].includes(item.status))
237
- .map((item) => new Date(item.nextAttemptAt).getTime())
238
- ];
239
- const delay = pending.length ? Math.max(250, Math.min(60000, Math.min(...pending) - Date.now())) : 60000;
240
- await waitForWake(root, delay);
241
- } while (true);
242
- }
243
-
244
- if (isMainModule(import.meta.url)) {
245
- const args = process.argv.slice(2); const once = args.includes("--once");
246
- const rootIndex = args.indexOf("--root");
247
- if (rootIndex >= 0 && (!args[rootIndex + 1] || args[rootIndex + 1].startsWith("--"))) throw new Error("--root requires a path");
248
- const root = rootIndex >= 0 ? args[rootIndex + 1] : process.cwd();
249
- const rosterIndex = args.indexOf("--persona-roster");
250
- if (rosterIndex >= 0 && (!args[rosterIndex + 1] || args[rosterIndex + 1].startsWith("--"))) {
251
- throw new Error("--persona-roster requires a path");
252
- }
253
- const env = { ...process.env };
254
- if (rosterIndex >= 0) env.AGENTSPINE_PERSONA_ROSTER_FILE = args[rosterIndex + 1];
255
- runWorker({ root, once, env }).then((result) => process.stdout.write(JSON.stringify(result) + "\n"))
256
- .catch((error) => { process.stderr.write("AgentSpine worker: " + String(error.message).slice(0, 2048) + "\n"); process.exitCode = 1; });
257
- }
@@ -1,127 +0,0 @@
1
- import { open, lstat, mkdir, readFile, rename, writeFile } from 'node:fs/promises';
2
- import path from 'node:path';
3
- import { createHash } from 'node:crypto';
4
-
5
- import { ingestGoalInstruction, parseGoalInstruction } from './agentspine-king-goal-intake.mjs';
6
-
7
- const CHECKPOINT_SCHEMA = 'blun.king-goal-queue-checkpoint/v1';
8
- const MAX_READ_BYTES = 4 * 1024 * 1024;
9
-
10
- function queueIdentity(metadata) {
11
- return `${metadata.dev}:${metadata.ino}:${metadata.birthtimeMs}`;
12
- }
13
-
14
- async function readCheckpoint(filePath) {
15
- try {
16
- const value = JSON.parse(await readFile(filePath, 'utf8'));
17
- if (value?.schema === CHECKPOINT_SCHEMA && typeof value.fileId === 'string'
18
- && Number.isSafeInteger(value.offset) && value.offset >= 0 && Array.isArray(value.accepted)
19
- && value.accepted.length <= 512 && value.accepted.every(item => item && /^[a-f0-9]{64}$/.test(item.sha256)
20
- && typeof item.goalId === 'string' && item.goalId.length > 0)) return value;
21
- throw new Error('GOAL_QUEUE_CHECKPOINT_INVALID');
22
- } catch (error) {
23
- if (error?.code !== 'ENOENT') throw error;
24
- }
25
- return { schema: CHECKPOINT_SCHEMA, fileId: '', offset: 0, lastMessageId: null, accepted: [] };
26
- }
27
-
28
- async function writeCheckpoint(filePath, value) {
29
- await mkdir(path.dirname(filePath), { recursive: true });
30
- const temporary = `${filePath}.${process.pid}.${Date.now()}.tmp`;
31
- await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, {
32
- encoding: 'utf8', flag: 'wx', mode: 0o600,
33
- });
34
- await rename(temporary, filePath);
35
- }
36
-
37
- function parseQueueLine(line) {
38
- let envelope;
39
- try { envelope = JSON.parse(line); } catch { return null; }
40
- if (!envelope || typeof envelope.text !== 'string' || !envelope.meta || Array.isArray(envelope.meta)
41
- || typeof envelope.meta !== 'object') return null;
42
- return envelope;
43
- }
44
-
45
- function isAuthorizedInstruction(envelope, input) {
46
- const addressed = envelope.meta.addressed === true || envelope.meta.addressed === 'true';
47
- const threads = ['thread_id', 'telegram_thread_id', 'message_thread_id']
48
- .map(key => envelope.meta[key]).filter(value => value !== null && value !== undefined && value !== '').map(String);
49
- const thread = input.instructionThreadId === null || input.instructionThreadId === undefined ? null : String(input.instructionThreadId);
50
- return addressed && String(envelope.meta.user_id) === String(input.instructionSenderId)
51
- && String(envelope.meta.chat_id) === String(input.instructionChatId)
52
- && (threads.length > 0 ? threads.every(value => value === thread) : thread === null);
53
- }
54
-
55
- async function queueChunk(filePath, checkpoint) {
56
- const metadata = await lstat(filePath);
57
- if (!metadata.isFile() || metadata.isSymbolicLink()) throw new Error('GOAL_QUEUE_NOT_REGULAR');
58
- const fileId = queueIdentity(metadata);
59
- const offset = checkpoint.fileId === fileId && metadata.size >= checkpoint.offset ? checkpoint.offset : 0;
60
- const bytes = Math.min(MAX_READ_BYTES, metadata.size - offset);
61
- if (bytes <= 0) return { fileId, offset, lines: [] };
62
- const handle = await open(filePath, 'r');
63
- try {
64
- const buffer = Buffer.alloc(bytes);
65
- const { bytesRead } = await handle.read(buffer, 0, bytes, offset);
66
- const content = buffer.subarray(0, bytesRead);
67
- const lastNewline = content.lastIndexOf(10);
68
- if (lastNewline < 0) {
69
- if (bytesRead >= MAX_READ_BYTES) throw new Error('GOAL_QUEUE_LINE_TOO_LARGE');
70
- return { fileId, offset, lines: [] };
71
- }
72
- const complete = content.subarray(0, lastNewline + 1);
73
- return { fileId, offset, lines: complete.toString('utf8').split('\n').slice(0, -1) };
74
- } finally { await handle.close(); }
75
- }
76
-
77
- async function ingestGoalInbox(input) {
78
- const checkpoint = await readCheckpoint(input.checkpointFile);
79
- let cursor = checkpoint.offset;
80
- const results = [];
81
- const chunk = await queueChunk(input.queueFile, checkpoint);
82
- if (chunk.offset !== checkpoint.offset || chunk.fileId !== checkpoint.fileId) cursor = chunk.offset;
83
- for (const line of chunk.lines) {
84
- cursor += Buffer.byteLength(line, 'utf8') + 1;
85
- const envelope = parseQueueLine(line);
86
- if (!envelope || !isAuthorizedInstruction(envelope, input)
87
- || !/\bZIEL-[A-Za-z0-9._-]+\.json\b/u.test(envelope.text)) continue;
88
- try {
89
- const instruction = parseGoalInstruction(envelope.text);
90
- const accepted = checkpoint.accepted.find((item) => item.sha256 === instruction.sha256);
91
- if (accepted) {
92
- results.push({ status: 'duplicate', messageId: String(envelope.meta.message_id),
93
- sha256: instruction.sha256, goal: { goalId: accepted.goalId } });
94
- continue;
95
- }
96
- const ingested = await ingestGoalInstruction({ ...input, instructionText: envelope.text });
97
- results.push({ status: ingested.duplicate ? 'duplicate' : 'ingested',
98
- messageId: String(envelope.meta.message_id), ...ingested });
99
- checkpoint.accepted.push({ sha256: ingested.sha256, goalId: ingested.goal.goalId });
100
- checkpoint.accepted = checkpoint.accepted.slice(-512);
101
- } catch (error) {
102
- results.push({ status: 'rejected', messageId: String(envelope.meta.message_id),
103
- error: String(error?.message || error).slice(0, 200) });
104
- }
105
- const result = results.at(-1);
106
- result.eventId = createHash('sha256').update(line).digest('hex');
107
- // Keep status persistence outside the ingestion catch and before advancing the durable cursor.
108
- await input.recordResult?.(result);
109
- }
110
- await writeCheckpoint(input.checkpointFile, {
111
- schema: CHECKPOINT_SCHEMA,
112
- fileId: chunk.fileId,
113
- offset: cursor,
114
- lastMessageId: results.at(-1)?.messageId || checkpoint.lastMessageId || null,
115
- accepted: checkpoint.accepted,
116
- updatedAt: new Date().toISOString(),
117
- });
118
- return results;
119
- }
120
-
121
- export {
122
- CHECKPOINT_SCHEMA,
123
- ingestGoalInbox,
124
- isAuthorizedInstruction,
125
- parseQueueLine,
126
- queueIdentity,
127
- };
@@ -1,106 +0,0 @@
1
- import { createHash } from 'node:crypto';
2
- import { lstat, readFile, realpath } from 'node:fs/promises';
3
- import path from 'node:path';
4
-
5
- const ASSIGNMENT_SCHEMA = 'blun.king-goal-assignment/v1';
6
- const INSTRUCTION_RE = /(ZIEL-[A-Za-z0-9._-]+\.json)\b[^\r\n]{0,200}?\bsha256\b\s*[=:]?\s*([a-f0-9]{64})(?:\s|[),.;]|$)/iu;
7
-
8
- function digest(value) {
9
- return createHash('sha256').update(value).digest('hex');
10
- }
11
-
12
- function parseGoalInstruction(text) {
13
- const match = String(text || '').match(INSTRUCTION_RE);
14
- if (!match) throw new Error('GOAL_INSTRUCTION_REQUIRES_FILE_AND_SHA256');
15
- return Object.freeze({ fileName: match[1], sha256: match[2].toLowerCase() });
16
- }
17
-
18
- function assignmentInput(value) {
19
- if (!value || value.schema !== ASSIGNMENT_SCHEMA || typeof value.goalId !== 'string'
20
- || typeof value.logicalPersonaId !== 'string' || typeof value.successCriterion !== 'string'
21
- || !Array.isArray(value.steps) || value.steps.length === 0) {
22
- throw new Error('GOAL_ASSIGNMENT_INVALID');
23
- }
24
- assertTerminalGoalGate(value.steps);
25
- return value;
26
- }
27
-
28
- function assertTerminalGoalGate(steps) {
29
- const ids = new Set(steps.map((step) => step?.stepId));
30
- if (ids.size !== steps.length || ids.has(undefined)) throw new Error('GOAL_PLAN_STEP_IDS_INVALID');
31
- const dependedOn = new Set(steps.flatMap((step) => Array.isArray(step.dependsOn) ? step.dependsOn : []));
32
- const terminalSteps = steps.filter((step) => !dependedOn.has(step.stepId));
33
- if (terminalSteps.length !== 1 || !terminalSteps[0].execution?.verification) {
34
- throw new Error('GOAL_PLAN_TERMINAL_GATE_REQUIRED');
35
- }
36
- const terminalId = terminalSteps[0].stepId;
37
- const byId = new Map(steps.map((step) => [step.stepId, step]));
38
- const reachesGate = (stepId, seen = new Set()) => {
39
- if (stepId === terminalId) return true;
40
- if (seen.has(stepId)) return false;
41
- seen.add(stepId);
42
- return steps.some((candidate) => Array.isArray(candidate.dependsOn)
43
- && candidate.dependsOn.includes(stepId) && reachesGate(candidate.stepId, new Set(seen)));
44
- };
45
- if ([...byId.keys()].some((stepId) => !reachesGate(stepId))) {
46
- throw new Error('GOAL_PLAN_TERMINAL_GATE_MUST_DEPEND_ON_ALL_STEPS');
47
- }
48
- }
49
-
50
- function inside(directory, candidate) {
51
- const relative = path.relative(directory, candidate);
52
- return relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
53
- }
54
-
55
- async function readVerifiedGoalFile(exchangeDirectory, instruction) {
56
- const exchange = await realpath(path.resolve(exchangeDirectory));
57
- const candidate = path.resolve(exchange, instruction.fileName);
58
- if (!inside(exchange, candidate)) throw new Error('GOAL_FILE_OUTSIDE_EXCHANGE');
59
- const metadata = await lstat(candidate);
60
- if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.size > 1024 * 1024) {
61
- throw new Error('GOAL_FILE_NOT_REGULAR');
62
- }
63
- const canonical = await realpath(candidate);
64
- if (!inside(exchange, canonical)) throw new Error('GOAL_FILE_OUTSIDE_EXCHANGE');
65
- const payload = await readFile(canonical);
66
- if (digest(payload) !== instruction.sha256) throw new Error('GOAL_FILE_SHA256_MISMATCH');
67
- let value;
68
- try { value = JSON.parse(payload.toString('utf8')); }
69
- catch { throw new Error('GOAL_FILE_INVALID_JSON'); }
70
- return { assignment: assignmentInput(value), filePath: canonical, sha256: instruction.sha256 };
71
- }
72
-
73
- async function ingestGoalInstruction(input) {
74
- const instruction = parseGoalInstruction(input.instructionText);
75
- const verified = await readVerifiedGoalFile(input.exchangeDirectory, instruction);
76
- const value = verified.assignment;
77
- if (value.logicalPersonaId !== input.logicalPersonaId) throw new Error('GOAL_PERSONA_MISMATCH');
78
- if (value.projectId !== input.projectId) throw new Error('GOAL_PROJECT_MISMATCH');
79
- if (value.groupId !== input.groupId || value.ownerSubjectId !== input.ownerSubjectId) {
80
- throw new Error('GOAL_AUTHORITY_MISMATCH');
81
- }
82
- if (value.snapshotSha256 !== input.snapshot.snapshotSha256) throw new Error('GOAL_SNAPSHOT_MISMATCH');
83
- const result = await input.assignGoal({
84
- root: input.snapshot.root,
85
- goalId: value.goalId,
86
- agentId: input.runtimePersonaId,
87
- ownerSubjectId: value.ownerSubjectId,
88
- projectId: value.projectId,
89
- groupId: value.groupId,
90
- priority: value.priority ?? 70,
91
- successCriterion: value.successCriterion,
92
- nextSafeStep: value.nextSafeStep ?? null,
93
- steps: value.steps,
94
- deadline: value.deadline ?? null,
95
- confirmation: 'local-owner-confirmed',
96
- });
97
- return Object.freeze({ ...verified, duplicate: result.duplicate === true, goal: result.goal });
98
- }
99
-
100
- export {
101
- ASSIGNMENT_SCHEMA,
102
- assertTerminalGoalGate,
103
- ingestGoalInstruction,
104
- parseGoalInstruction,
105
- readVerifiedGoalFile,
106
- };
@@ -1,109 +0,0 @@
1
- import { randomUUID } from 'node:crypto';
2
-
3
- export const MAX_RAW_BYTES = 64 * 1024;
4
- export const MAX_CHECKPOINT_BYTES = 16 * 1024;
5
- export const MAX_TICK_MS = 1_800_000;
6
- export const RESULT_SCHEMA = 'agentspine.blun-step-result/v1';
7
- const HOST_ENVIRONMENT_KEYS = [
8
- 'AGENTSPINE_GATEWAY_CONTEXT', 'AGENTSPINE_ENTITY_ID', 'AGENTSPINE_PROJECT_ID',
9
- 'AGENTSPINE_HOST', 'AGENTSPINE_GATEWAY_QUEUE_ID', 'AGENTSPINE_GATEWAY_ATTEMPT',
10
- 'AGENTSPINE_GROUP_ID', 'AGENTSPINE_GOAL_ID', 'AGENTSPINE_GOAL_STEP_ID',
11
- 'AGENTSPINE_PLAN_DEFINITIONS_DIGEST', 'AGENTSPINE_CHANNEL_EVENT_ID',
12
- 'AGENTSPINE_CHANNEL_PROVIDER', 'AGENTSPINE_PORTAL_REF', 'AGENTSPINE_THREAD_REF',
13
- ];
14
-
15
- function goalSessionKaos(kaos, environment) {
16
- if (environment === undefined) return kaos;
17
- if (!environment || typeof environment !== 'object' || Array.isArray(environment)
18
- || Object.entries(environment).some(([key, value]) => !HOST_ENVIRONMENT_KEYS.includes(key)
19
- || typeof value !== 'string' || value.includes('\0'))) throw new Error('GOAL_WORKER_ENVIRONMENT_INVALID');
20
- if (typeof kaos?.withEnv !== 'function') throw new Error('GOAL_WORKER_ENVIRONMENT_REQUIRED');
21
- // Replace the complete per-tick scope without changing process.env or the base Kaos.
22
- return kaos.withEnv(Object.fromEntries(HOST_ENVIRONMENT_KEYS.map(key => [key, environment[key] ?? ''])));
23
- }
24
-
25
- export function buildGoalPrompt(item) {
26
- return 'Execute exactly one bounded goal-plan tick. Return exactly one visible final JSON object.\n'
27
- + JSON.stringify({ schema: 'agentspine.blun-step-request/v1', goal: item.goal, goalStep: item.goalStep,
28
- selfHelpPolicy: item.selfHelpPolicy, requiredResult: { schema: RESULT_SCHEMA,
29
- fields: ['text', 'checkpoint', 'completed', 'blocked', 'blocker', 'knowledgeGap', 'selfHelp', 'execution'],
30
- rule: 'Every tick requires a non-null checkpoint; only report completed work backed by verification.' } });
31
- }
32
-
33
- export function parseGoalResult(text) {
34
- if (Buffer.byteLength(text, 'utf8') > MAX_RAW_BYTES) throw new Error('GOAL_STEP_RESULT_EXCEEDS_64_KIB');
35
- let value;
36
- try { value = JSON.parse(text.trim()); } catch { throw new Error('GOAL_STEP_RESULT_INVALID_JSON'); }
37
- if (!value || value.schema !== RESULT_SCHEMA || typeof value.text !== 'string'
38
- || !value.text.trim() || value.text.length > 16000
39
- || (value.completed !== undefined && typeof value.completed !== 'boolean')
40
- || (value.blocked !== undefined && typeof value.blocked !== 'boolean')
41
- || (value.completed === true && value.blocked === true)) throw new Error('GOAL_STEP_RESULT_INVALID');
42
- if (value.checkpoint === undefined || value.checkpoint === null) throw new Error('GOAL_STEP_CHECKPOINT_REQUIRED');
43
- if (Buffer.byteLength(JSON.stringify(value.checkpoint), 'utf8') > MAX_CHECKPOINT_BYTES) {
44
- throw new Error('GOAL_STEP_CHECKPOINT_TOO_LARGE');
45
- }
46
- return value;
47
- }
48
-
49
- export function runSessionStep(session, item, timeoutMs, signal) {
50
- return new Promise((resolve, reject) => {
51
- let ended = false;
52
- let text = '';
53
- let turnId;
54
- let unsubscribe = () => {};
55
- const finish = (error) => {
56
- if (ended) return;
57
- ended = true; clearTimeout(timer); unsubscribe(); signal?.removeEventListener('abort', aborted);
58
- if (error) { reject(error); return; }
59
- try { resolve(parseGoalResult(text)); } catch (error) { reject(error); }
60
- };
61
- const aborted = () => finish(new Error('GOAL_WORKER_STOP_REQUESTED'));
62
- const timer = setTimeout(() => finish(new Error('GOAL_STEP_DEADLINE')), timeoutMs);
63
- unsubscribe = session.onEvent((event) => {
64
- if (event.sessionId !== session.id || event.agentId !== 'main') return;
65
- if (event.type === 'turn.started' && turnId === undefined) { turnId = event.turnId; return; }
66
- if (event.type === 'error') { finish(new Error('GOAL_STEP_SESSION_ERROR')); return; }
67
- if (turnId === undefined || event.turnId !== turnId) return;
68
- if (event.type === 'turn.step.started' || event.type === 'turn.step.retrying') text = '';
69
- if (event.type === 'assistant.delta') {
70
- text += event.delta;
71
- if (Buffer.byteLength(text, 'utf8') > MAX_RAW_BYTES) finish(new Error('GOAL_STEP_RESULT_EXCEEDS_64_KIB'));
72
- }
73
- if (event.type === 'turn.ended') finish(event.reason === 'completed' ? null : new Error('GOAL_STEP_TURN_NOT_COMPLETED'));
74
- });
75
- signal?.addEventListener('abort', aborted, { once: true });
76
- if (signal?.aborted) aborted();
77
- if (!ended) Promise.resolve().then(() => { if (!ended) return session.prompt(buildGoalPrompt(item)); }).catch(finish);
78
- });
79
- }
80
-
81
- export function createGoalHostFactory({ harness, workDir, model, permission, tickTimeoutMs = MAX_TICK_MS,
82
- cleanupTimeoutMs = 10000, sessionOptions, onSession, signal }) {
83
- if (!Number.isInteger(tickTimeoutMs) || tickTimeoutMs < 1000 || tickTimeoutMs > MAX_TICK_MS
84
- || !Number.isInteger(cleanupTimeoutMs) || cleanupTimeoutMs < 1 || cleanupTimeoutMs > 60000) {
85
- throw new Error('GOAL_WORKER_TIMEOUT_OUT_OF_RANGE');
86
- }
87
- if (!['manual', 'auto', 'yolo'].includes(permission)) throw new Error('GOAL_WORKER_PERMISSION_REQUIRED');
88
- return async (item) => {
89
- if (item.projectRoot !== workDir || !item.goal) throw new Error('GOAL_WORKER_SCOPE_MISMATCH');
90
- const session = await harness.createSession({ ...sessionOptions, id: 'worker-' + randomUUID(),
91
- workDir, model, permission, kaos: goalSessionKaos(sessionOptions?.kaos, item.hostEnvironment),
92
- metadata: { gatewayQueueId: item.queueId, gatewayAttempt: item.attempts } });
93
- onSession?.(session);
94
- let started = false;
95
- return { sessionId: session.id,
96
- async run() {
97
- if (started) throw new Error('GOAL_WORKER_SESSION_ALREADY_RUN');
98
- started = true;
99
- return runSessionStep(session, item, tickTimeoutMs, signal);
100
- },
101
- async quiesce() {
102
- const proof = await session.quiesce({ deadlineAt: Date.now() + cleanupTimeoutMs });
103
- if (proof.status === 'quiescent' && proof.sessionId === session.id && proof.remaining.length === 0) {
104
- await session.close();
105
- }
106
- return proof;
107
- } };
108
- };
109
- }