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,370 +0,0 @@
1
- import { attentionFindings, loadAttention } from "./attention.js";
2
- import { channelRuntimeFindings, loadChannelPolicy, loadChannelRuntime } from "./channel-runtime.js";
3
- import { loadGraph } from "./graph.js";
4
- import { expireGatewayLane } from "./gateway-host-lifecycle.js";
5
- import { heldExecution } from "./gateway-host-fencing.js";
6
- import * as goalPremortem from "./gateway-premortem.js";
7
- import { resolveKnowledgeGapCandidate, sameKnowledgeGapResolution } from "./knowledge-evidence.js";
8
- import { loadPersonaRuntime, personaRuntimeFindings } from "./persona-runtime.js";
9
- import { assertActivePersona } from "./gateway-runtime-identity.js";
10
- import { appendReceipt, preserve } from "./gateway-runtime-records.js";
11
- import { writeGatewayStatePair } from "./gateway-state-transaction.js";
12
- import {
13
- CONFIRMATION, PRIORITY, WAKE_KINDS, emptyPolicy, emptyRuntime, exactId,
14
- safeText, sha256, timestamp
15
- } from "./gateway-common.js";
16
- import { currentExecutionAttempt } from "./gateway-execution.js";
17
- import {
18
- createGoalPlan, currentPlanStep, newGoalQueue, normalizePolicy, normalizeRuntime,
19
- pathsFor, planQueueKey, planStepAgentId, readJson, validGoal, withLock, writeJson
20
- } from "./gateway-state.js";
21
-
22
- export async function setGatewayControl({ root = process.cwd(), enabled, killSwitch, confirmation, now = new Date() }) {
23
- if (confirmation !== CONFIRMATION) throw new Error("gateway control changes require explicit local owner confirmation");
24
- const paths = await pathsFor(root);
25
- return withLock(paths, async () => {
26
- const policy = await readJson(paths.gatewayPolicyPath, paths.catalog.root, normalizePolicy, emptyPolicy);
27
- const previous = { enabled: policy.enabled, killSwitch: policy.killSwitch };
28
- if (enabled !== undefined) policy.enabled = Boolean(enabled);
29
- if (killSwitch !== undefined) policy.killSwitch = Boolean(killSwitch);
30
- policy.revision += 1;
31
- policy.history.push({ kind: "control", at: timestamp(now), value: previous, authority: "authenticated-goal-policy" });
32
- await writeJson(paths.gatewayPolicyPath, policy);
33
- return { enabled: policy.enabled, killSwitch: policy.killSwitch, revision: policy.revision };
34
- });
35
- }
36
-
37
- export async function reviewLegacyGatewayHold({ root = process.cwd(), queueId, goalId, ownerSubjectId,
38
- projectId, groupId = null, workerId, claimedAt, attempt, hostStopped, effectsReviewed, reviewNote,
39
- confirmation, now = new Date() }) {
40
- if (confirmation !== CONFIRMATION || hostStopped !== true || effectsReviewed !== true) {
41
- throw new Error("legacy hold review requires explicit local owner confirmation of host stop and reviewed effects");
42
- }
43
- queueId = exactId(queueId, "queueId"); goalId = exactId(goalId, "goalId");
44
- ownerSubjectId = exactId(ownerSubjectId, "ownerSubjectId"); workerId = exactId(workerId, "workerId");
45
- projectId = exactId(projectId, "projectId"); groupId = exactId(groupId, "groupId", true);
46
- if (typeof claimedAt !== "string" || timestamp(claimedAt) !== claimedAt
47
- || !Number.isInteger(attempt) || attempt < 1 || attempt > 20) {
48
- throw new Error("legacy hold review requires the exact claim timestamp and integer attempt");
49
- }
50
- if (typeof reviewNote !== "string" || reviewNote.length > 500) throw new Error("legacy review note must contain 1-500 characters");
51
- reviewNote = safeText(reviewNote, "reviewNote", 500);
52
- const current = timestamp(now);
53
- const paths = await pathsFor(root);
54
- return withLock(paths, async () => {
55
- const policy = await readJson(paths.gatewayPolicyPath, paths.catalog.root, normalizePolicy, emptyPolicy);
56
- const runtime = await readJson(paths.gatewayRuntimePath, paths.catalog.root, normalizeRuntime, emptyRuntime);
57
- const item = runtime.queue.find((entry) => entry.queueId === queueId);
58
- const goal = policy.goals.find((entry) => entry.goalId === goalId);
59
- const step = goal?.plan?.steps.find((entry) => entry.stepId === item?.goalStepId);
60
- if (!item || !goal || item.goalId !== goalId || goal.ownerSubjectId !== ownerSubjectId
61
- || item.projectId !== projectId || goal.projectId !== projectId
62
- || item.groupId !== groupId || goal.groupId !== groupId
63
- || (item.goalStepId && !step) || item.agentId !== planStepAgentId(goal, step)) {
64
- throw new Error("legacy hold review requires the exact goal owner and queue scope");
65
- }
66
- const hold = item.executionHold;
67
- if (!hold || hold.workerId !== workerId || hold.claimedAt !== claimedAt || hold.attempt !== attempt) {
68
- throw new Error("legacy hold review requires the exact held generation");
69
- }
70
- if (hold.hostSessionId !== null || runtime.history.some((entry) => entry.kind === "queue"
71
- && entry.objectId === queueId && entry.value.attempts === attempt
72
- && entry.value.executionHold?.hostSessionId)) {
73
- throw new Error("a known host session requires exact-session quiescence, not legacy owner review");
74
- }
75
- if (item.lease !== null || !["blocked", "cancelled"].includes(item.status)) {
76
- throw new Error("legacy owner review requires an unleased blocked or cancelled queue item");
77
- }
78
- const details = { goalId, ownerSubjectId, projectId, groupId, workerId, claimedAt, attempt,
79
- hostStopped: true, effectsReviewed: true, reviewNote, reviewBasis: "local-owner-attestation" };
80
- if (hold.status === "settled") {
81
- const receipt = runtime.receipts.find((entry) => entry.kind === "legacy-host-owner-reviewed"
82
- && entry.objectId === queueId && entry.details.workerId === workerId
83
- && entry.details.claimedAt === claimedAt && entry.details.attempt === attempt);
84
- if (!receipt || JSON.stringify(receipt.details) !== JSON.stringify(details)) {
85
- throw new Error("legacy hold already has a different settlement or owner review");
86
- }
87
- return { item: structuredClone(item), receipt: structuredClone(receipt), duplicate: true };
88
- }
89
- if (current < item.updatedAt || current < claimedAt || (hold.hostStartedAt && current < hold.hostStartedAt)) {
90
- throw new Error("legacy review timestamp precedes the held generation");
91
- }
92
- // This attestation is not native quiescence, goal completion, or authority to resume work.
93
- preserve(runtime, "queue", item, "legacy-host-owner-reviewed", current);
94
- hold.status = "settled"; hold.settledAt = current;
95
- item.updatedAt = current; runtime.revision += 1;
96
- const receipt = appendReceipt(runtime, "legacy-host-owner-reviewed", queueId, current, details);
97
- await writeJson(paths.gatewayRuntimePath, runtime);
98
- return { item: structuredClone(item), receipt: structuredClone(receipt), duplicate: false };
99
- });
100
- }
101
-
102
- export async function assignGoal({ root = process.cwd(), goalId, agentId, ownerSubjectId, projectId, groupId = null,
103
- priority = 70, successCriterion, nextSafeStep = null, steps = null, deadline = null, confirmation, now = new Date() }) {
104
- if (confirmation !== CONFIRMATION) throw new Error("goal assignment requires explicit local owner confirmation");
105
- const paths = await pathsFor(root);
106
- return withLock(paths, async () => {
107
- const [policy, runtime, personas] = await Promise.all([
108
- readJson(paths.gatewayPolicyPath, paths.catalog.root, normalizePolicy, emptyPolicy),
109
- readJson(paths.gatewayRuntimePath, paths.catalog.root, normalizeRuntime, emptyRuntime),
110
- loadPersonaRuntime(paths.catalog.root, paths.catalog)
111
- ]);
112
- goalId = exactId(goalId, "goalId"); agentId = exactId(agentId, "agentId");
113
- projectId = exactId(projectId, "projectId"); groupId = exactId(groupId, "groupId", true);
114
- const leadIdentity = assertActivePersona(personas.policy, personas.runtime, agentId, projectId, groupId);
115
- const createdAt = timestamp(now);
116
- const active = policy.goals.find((item) => item.agentId === agentId && item.status === "active" && item.goalId !== goalId);
117
- if (active) throw new Error("an agent may have only one active focused goal");
118
- const previous = policy.goals.find((item) => item.goalId === goalId);
119
- const premortemContractVersion = previous?.plan ? goalPremortem.goalPremortemContractVersion(policy, goalId) : 1;
120
- const plan = steps === null ? null : createGoalPlan(steps, createdAt, agentId, {
121
- goals: policy.goals, scope: { goalId, projectId, groupId, before: createdAt },
122
- premortemContractVersion
123
- });
124
- if (plan) {
125
- for (const stepAgentId of new Set(plan.steps.map((step) => step.agentId))) {
126
- const stepIdentity = assertActivePersona(personas.policy, personas.runtime, stepAgentId, projectId, groupId);
127
- if (stepIdentity.binding.tenantId !== leadIdentity.binding.tenantId) {
128
- throw new Error("goal-plan team members must share the authenticated tenant and exact project group");
129
- }
130
- }
131
- }
132
- const firstStep = plan ? plan.steps.find((step) => step.stepId === plan.currentStepId) : null;
133
- const goal = { goalId, agentId, ownerSubjectId: exactId(ownerSubjectId, "ownerSubjectId"),
134
- projectId, groupId, priority: Number(priority), successCriterion: safeText(successCriterion, "successCriterion"),
135
- nextSafeStep: safeText(firstStep?.title || nextSafeStep, "nextSafeStep"), deadline: deadline === null ? null : timestamp(deadline),
136
- status: "active", checkpoint: null, heartbeatAt: null, blocker: null,
137
- createdAt: previous?.createdAt || createdAt, updatedAt: createdAt,
138
- plan, authority: "authenticated-goal-policy" };
139
- if (!validGoal(goal, paths.catalog.root, plan ? premortemContractVersion : undefined)) throw new Error("goal assignment is invalid");
140
- if (previous && [previous.agentId, previous.ownerSubjectId, previous.projectId, previous.groupId].join("\0")
141
- !== [goal.agentId, goal.ownerSubjectId, goal.projectId, goal.groupId].join("\0")) throw new Error("goal scope is immutable");
142
- if (previous?.plan && previous.plan.definitionsDigest !== goal.plan?.definitionsDigest) {
143
- throw new Error("goal plan definitions are immutable; assign a new goal ID");
144
- }
145
- if (previous && runtime.queue.some((item) => item.goalId === goalId && heldExecution(item))) {
146
- return { goal: structuredClone(previous), gatewayPolicyPath: paths.gatewayPolicyPath, duplicate: true, held: true };
147
- }
148
- if (previous?.plan && previous.status === "blocked") {
149
- const blockedStep = currentPlanStep(previous);
150
- if (!blockedStep || blockedStep.status !== "blocked") throw new Error("blocked goal plan has no bound blocked step");
151
- if ((blockedStep.knowledgeGaps || []).some((gap) => gap.status === "open")) {
152
- throw new Error("blocked goal plan has an open knowledge gap; resolve it with goal-clarify");
153
- }
154
- if (blockedStep.execution?.explorationMaxAttempts !== undefined
155
- && currentExecutionAttempt(blockedStep.execution, blockedStep.executionOutcomes || []) === null) {
156
- throw new Error("bounded exploration is exhausted or stopped by a blocking defect; assign a new goal ID");
157
- }
158
- policy.history.push({ kind: "goal", at: createdAt, value: structuredClone(previous), authority: "authenticated-goal-policy" });
159
- blockedStep.status = "active"; blockedStep.blocker = null; blockedStep.updatedAt = createdAt;
160
- previous.status = "active"; previous.blocker = null; previous.updatedAt = createdAt; previous.plan.revision += 1;
161
- policy.revision += 1;
162
- const key = planQueueKey(previous.goalId, blockedStep.stepId, "owner-resume", String(previous.plan.revision));
163
- const queued = newGoalQueue(previous, blockedStep, "follow-up", key, createdAt);
164
- runtime.queue.push(queued); runtime.revision += 1;
165
- appendReceipt(runtime, "goal-step-resumed", queued.queueId, createdAt, { goalStepId: blockedStep.stepId });
166
- await writeGatewayStatePair(policy, runtime);
167
- return { goal: structuredClone(previous), gatewayPolicyPath: paths.gatewayPolicyPath, resumed: true };
168
- }
169
- if (previous?.plan) return { goal: structuredClone(previous), gatewayPolicyPath: paths.gatewayPolicyPath, duplicate: true };
170
- if (previous) {
171
- policy.history.push({ kind: "goal", at: createdAt, value: structuredClone(previous), authority: "authenticated-goal-policy" });
172
- goal.createdAt = previous.createdAt;
173
- }
174
- policy.goals = policy.goals.filter((item) => item.goalId !== goal.goalId);
175
- policy.goals.push(goal);
176
- if (plan) goalPremortem.registerGoalPremortemContract(policy, goal, premortemContractVersion, createdAt);
177
- policy.revision += 1;
178
- const key = firstStep ? planQueueKey(goal.goalId, firstStep.stepId, "assignment") : "goal:" + goal.goalId + ":assignment";
179
- if (!runtime.queue.some((item) => item.dedupeKey === key)) {
180
- runtime.queue.push(newGoalQueue(goal, firstStep, "assignment", key, createdAt));
181
- runtime.revision += 1;
182
- appendReceipt(runtime, "queued", "gateway-queue:" + sha256(key).slice(0, 32), createdAt, { kind: "assignment", dedupeKey: key });
183
- }
184
- await writeGatewayStatePair(policy, runtime);
185
- return { goal, gatewayPolicyPath: paths.gatewayPolicyPath };
186
- });
187
- }
188
-
189
- export async function resolveGoalKnowledgeGap({ root = process.cwd(), goalId, gapId, answer,
190
- answerSource = "owner-input", sourceDigest = null, confirmation, now = new Date() }) {
191
- if (confirmation !== CONFIRMATION) throw new Error("knowledge gap resolution requires explicit local owner confirmation");
192
- const paths = await pathsFor(root);
193
- return withLock(paths, async () => {
194
- const [policy, runtime, personas] = await Promise.all([
195
- readJson(paths.gatewayPolicyPath, paths.catalog.root, normalizePolicy, emptyPolicy),
196
- readJson(paths.gatewayRuntimePath, paths.catalog.root, normalizeRuntime, emptyRuntime),
197
- loadPersonaRuntime(paths.catalog.root, paths.catalog)
198
- ]);
199
- goalId = exactId(goalId, "goalId"); gapId = exactId(gapId, "gapId");
200
- const goal = policy.goals.find((item) => item.goalId === goalId);
201
- const step = goal && currentPlanStep(goal);
202
- if (!goal?.plan || !step) throw new Error("knowledge gap resolution requires the exact current goal-plan step");
203
- assertActivePersona(personas.policy, personas.runtime, goal.agentId, goal.projectId, goal.groupId);
204
- const gap = (step.knowledgeGaps || []).find((item) => item.gapId === gapId);
205
- if (!gap) throw new Error("knowledge gap is not bound to the current goal-plan step");
206
- if (gap.status === "resolved") {
207
- if (!sameKnowledgeGapResolution(gap, { answer, answerSource, sourceDigest })) {
208
- throw new Error("knowledge gap already has a different bound resolution");
209
- }
210
- return { goal: structuredClone(goal), gap: structuredClone(gap), duplicate: true };
211
- }
212
- if (goal.status !== "blocked" || step.status !== "blocked") {
213
- throw new Error("open knowledge gap resolution requires the exact blocked goal-plan step");
214
- }
215
- const resolvedAt = timestamp(now);
216
- const candidate = resolveKnowledgeGapCandidate(gap, { answer, answerSource, sourceDigest,
217
- resolvedAt, resolvedBySubjectId: goal.ownerSubjectId });
218
- policy.history.push({ kind: "goal", at: resolvedAt, value: structuredClone(goal), authority: "authenticated-goal-policy" });
219
- Object.assign(gap, candidate);
220
- step.status = "active"; step.blocker = null; step.updatedAt = resolvedAt;
221
- goal.status = "active"; goal.blocker = null; goal.updatedAt = resolvedAt; goal.nextSafeStep = step.title;
222
- goal.plan.revision += 1; policy.revision += 1;
223
- const key = planQueueKey(goal.goalId, step.stepId, "clarified", gap.resolutionDigest.slice(0, 20));
224
- let queued = runtime.queue.find((item) => item.dedupeKey === key);
225
- if (!queued) {
226
- queued = newGoalQueue(goal, step, "follow-up", key, resolvedAt);
227
- runtime.queue.push(queued); runtime.revision += 1;
228
- appendReceipt(runtime, "knowledge-gap-resolved", queued.queueId, resolvedAt, {
229
- goalStepId: step.stepId, gapId: gap.gapId, answerSource
230
- });
231
- }
232
- await writeGatewayStatePair(policy, runtime);
233
- return { goal: structuredClone(goal), gap: structuredClone(gap), queueId: queued.queueId, duplicate: false };
234
- });
235
- }
236
-
237
- export async function enqueueGatewayWake({ root = process.cwd(), kind, agentId, projectId, groupId = null, goalId = null,
238
- channelEventId = null, dedupeKey, availableAt = null, now = new Date() }) {
239
- if (!WAKE_KINDS.has(kind)) throw new Error("unsupported gateway wake kind");
240
- const paths = await pathsFor(root);
241
- return withLock(paths, async () => {
242
- const [policy, runtime, personas] = await Promise.all([
243
- readJson(paths.gatewayPolicyPath, paths.catalog.root, normalizePolicy, emptyPolicy),
244
- readJson(paths.gatewayRuntimePath, paths.catalog.root, normalizeRuntime, emptyRuntime),
245
- loadPersonaRuntime(paths.catalog.root, paths.catalog)
246
- ]);
247
- if (!policy.enabled || policy.killSwitch) throw new Error("gateway is disabled by local policy");
248
- agentId = exactId(agentId, "agentId"); projectId = exactId(projectId, "projectId"); groupId = exactId(groupId, "groupId", true);
249
- assertActivePersona(personas.policy, personas.runtime, agentId, projectId, groupId);
250
- goalId = exactId(goalId, "goalId", true); channelEventId = exactId(channelEventId, "channelEventId", true);
251
- const key = exactId(dedupeKey, "dedupeKey");
252
- const existing = runtime.queue.find((item) => item.dedupeKey === key);
253
- if (existing) return { item: existing, duplicate: true };
254
- const createdAt = timestamp(now);
255
- const item = { queueId: "gateway-queue:" + sha256(key).slice(0, 32), dedupeKey: key, kind, agentId, projectId, groupId,
256
- goalId, goalStepId: null, channelEventId, priority: PRIORITY[kind], status: "pending", attempts: 0, lease: null,
257
- availableAt: availableAt === null ? createdAt : timestamp(availableAt), createdAt, updatedAt: createdAt,
258
- completedAt: null, lastError: null, authority: "execution-state-only" };
259
- runtime.queue.push(item); runtime.revision += 1;
260
- appendReceipt(runtime, "queued", item.queueId, createdAt, { kind, dedupeKey: key });
261
- await writeJson(paths.gatewayRuntimePath, runtime);
262
- return { item, duplicate: false };
263
- });
264
- }
265
-
266
- export async function reconcileGateway({ root = process.cwd(), now = new Date() }) {
267
- const paths = await pathsFor(root);
268
- return withLock(paths, async () => {
269
- const [policy, runtime, channelPolicy, channel, attention, personas, { graph }] = await Promise.all([
270
- readJson(paths.gatewayPolicyPath, paths.catalog.root, normalizePolicy, emptyPolicy),
271
- readJson(paths.gatewayRuntimePath, paths.catalog.root, normalizeRuntime, emptyRuntime),
272
- loadChannelPolicy(paths.catalog.root, paths.catalog), loadChannelRuntime(paths.catalog.root, paths.catalog),
273
- loadAttention(paths.catalog.root, paths.catalog), loadPersonaRuntime(paths.catalog.root, paths.catalog),
274
- loadGraph(paths.catalog.root, paths.catalog)
275
- ]);
276
- const current = timestamp(now);
277
- const findings = personaRuntimeFindings(personas.policy, personas.runtime, graph);
278
- if (findings.length) throw new Error("persona runtime is unhealthy: " + findings.join(", "));
279
- const channelFindings = channelRuntimeFindings(channel.runtime, channelPolicy.policy, graph);
280
- if (channelFindings.length) throw new Error("channel runtime is unhealthy: " + channelFindings.join(", "));
281
- const attentionIssues = attentionFindings(attention.attention);
282
- if (attentionIssues.length) throw new Error("attention runtime is unhealthy: " + attentionIssues.join(", "));
283
- let policyChanged = false;
284
- for (const lane of runtime.lanes.filter((item) => item.status === "leased" && new Date(item.expiresAt) <= new Date(current))) {
285
- policyChanged = expireGatewayLane(policy, runtime, lane, current,
286
- { preserve, appendReceipt }) || policyChanged;
287
- }
288
- for (const outbox of runtime.outbox.filter((item) => item.status === "sending")) {
289
- preserve(runtime, "outbox", outbox, "ambiguous-send-recovery", current);
290
- outbox.status = "delivery-unknown"; outbox.updatedAt = current;
291
- appendReceipt(runtime, "delivery-unknown", outbox.outboxId, current, { reason: "crash-during-send" });
292
- }
293
- if (policy.enabled && !policy.killSwitch) {
294
- for (const goal of policy.goals.filter((item) => item.status === "active" && item.plan)) {
295
- const step = currentPlanStep(goal);
296
- if (!step) throw new Error("active goal plan has no current step");
297
- try {
298
- assertActivePersona(personas.policy, personas.runtime, planStepAgentId(goal, step), goal.projectId, goal.groupId);
299
- } catch {
300
- policy.history.push({ kind: "goal", at: current, value: structuredClone(goal), authority: "authenticated-goal-policy" });
301
- const blocker = "Assigned team member is unavailable in this exact project group.";
302
- step.status = "blocked"; step.blocker = blocker; step.updatedAt = current;
303
- goal.status = "blocked"; goal.blocker = blocker; goal.updatedAt = current; goal.plan.revision += 1;
304
- for (const queued of runtime.queue.filter((item) => item.goalId === goal.goalId
305
- && item.goalStepId === step.stepId && ["pending", "leased"].includes(item.status))) {
306
- preserve(runtime, "queue", queued, "step-agent-unavailable", current);
307
- queued.status = "cancelled"; queued.lease = null; queued.completedAt = current; queued.updatedAt = current;
308
- for (const lane of runtime.lanes.filter((item) => item.queueId === queued.queueId && item.status === "leased")) {
309
- lane.status = "expired"; lane.updatedAt = current;
310
- }
311
- appendReceipt(runtime, "step-agent-unavailable", queued.queueId, current, { goalStepId: step.stepId });
312
- }
313
- policy.revision += 1; policyChanged = true;
314
- continue;
315
- }
316
- const runnable = runtime.queue.some((item) => item.goalId === goal.goalId && item.goalStepId === step.stepId
317
- && item.agentId === planStepAgentId(goal, step)
318
- && ["pending", "leased", "awaiting-delivery"].includes(item.status));
319
- if (!runnable) {
320
- const key = planQueueKey(goal.goalId, step.stepId, "recovery", String(goal.plan.revision));
321
- if (!runtime.queue.some((item) => item.dedupeKey === key)) {
322
- const queued = newGoalQueue(goal, step, "follow-up", key, current);
323
- runtime.queue.push(queued);
324
- appendReceipt(runtime, "queued", queued.queueId, current, { kind: "follow-up", goalStepId: step.stepId });
325
- }
326
- }
327
- }
328
- for (const goal of policy.goals.filter((item) => item.status === "active" && item.deadline
329
- && new Date(item.deadline) <= new Date(current))) {
330
- const step = currentPlanStep(goal);
331
- const deadlineAgentId = planStepAgentId(goal, step);
332
- try { assertActivePersona(personas.policy, personas.runtime, deadlineAgentId, goal.projectId, goal.groupId); }
333
- catch { continue; }
334
- const key = "goal:" + goal.goalId + ":deadline:" + goal.deadline;
335
- if (!runtime.queue.some((item) => item.dedupeKey === key)) runtime.queue.push({
336
- queueId: "gateway-queue:" + sha256(key).slice(0, 32), dedupeKey: key, kind: "deadline",
337
- agentId: deadlineAgentId, projectId: goal.projectId, groupId: goal.groupId, goalId: goal.goalId,
338
- goalStepId: step?.stepId || null, channelEventId: null, priority: PRIORITY.deadline, status: "pending", attempts: 0, lease: null,
339
- availableAt: current, createdAt: current, updatedAt: current, completedAt: null, lastError: null,
340
- authority: "execution-state-only"
341
- });
342
- }
343
- for (const event of channel.runtime.events.filter((item) => item.status === "pending")) {
344
- if (!personas.runtime.personas.some((persona) => persona.personaId === event.agentId && persona.status === "active")) continue;
345
- const key = "channel:" + event.eventId;
346
- if (!runtime.queue.some((item) => item.dedupeKey === key)) runtime.queue.push({ queueId: "gateway-queue:" + sha256(key).slice(0, 32),
347
- dedupeKey: key, kind: "direct-message", agentId: event.agentId, projectId: event.projectId, groupId: event.groupId,
348
- goalId: null, goalStepId: null, channelEventId: event.eventId, priority: PRIORITY["direct-message"], status: "pending", attempts: 0,
349
- lease: null, availableAt: current, createdAt: current, updatedAt: current, completedAt: null, lastError: null, authority: "execution-state-only" });
350
- }
351
- for (const event of attention.attention.events.filter((item) => item.entityId
352
- && ((item.kind === "promise" && item.status === "open") || (item.kind === "blocker" && item.status === "resolved")))) {
353
- try { assertActivePersona(personas.policy, personas.runtime, event.entityId, event.projectId, event.groupId); }
354
- catch { continue; }
355
- const kind = event.kind === "promise" ? "promise" : "resolved-blocker";
356
- const key = "attention:" + event.id + ":" + event.status;
357
- if (!runtime.queue.some((entry) => entry.dedupeKey === key)) runtime.queue.push({ queueId: "gateway-queue:" + sha256(key).slice(0, 32),
358
- dedupeKey: key, kind, agentId: event.entityId, projectId: event.projectId, groupId: event.groupId,
359
- goalId: null, goalStepId: null, channelEventId: null, priority: PRIORITY[kind], status: "pending", attempts: 0, lease: null,
360
- availableAt: event.dueAt || current, createdAt: current, updatedAt: current, completedAt: null, lastError: null, authority: "execution-state-only" });
361
- }
362
- }
363
- runtime.health.gateway = policy.enabled && !policy.killSwitch ? "running" : "stopped";
364
- runtime.health.scheduler = "healthy"; runtime.health.queue = "healthy"; runtime.health.lastReconciledAt = current;
365
- runtime.revision += 1;
366
- if (policyChanged) await writeGatewayStatePair(policy, runtime);
367
- else await writeJson(paths.gatewayRuntimePath, runtime);
368
- return { policy, runtime, recovered: true };
369
- });
370
- }
@@ -1,103 +0,0 @@
1
- import { loadChannelPolicy, loadChannelRuntime } from "./channel-runtime.js";
2
- import { loadPersonaRuntime } from "./persona-runtime.js";
3
- import { assertActivePersona, exactReplyBinding } from "./gateway-runtime-identity.js";
4
- import { appendReceipt, preserve } from "./gateway-runtime-records.js";
5
- import { HEALTH_VALUES, emptyPolicy, emptyRuntime, exactId, safeText, timestamp } from "./gateway-common.js";
6
- import { normalizePolicy, normalizeRuntime, pathsFor, readJson, withLock, writeJson } from "./gateway-state.js";
7
-
8
- export async function deliverPrepared({ root = process.cwd(), outboxId, adapter, now = new Date() }) {
9
- if (!adapter || typeof adapter.send !== "function") throw new Error("delivery adapter is unavailable");
10
- const paths = await pathsFor(root);
11
- let prepared;
12
- await withLock(paths, async () => {
13
- const [policy, runtime, channelPolicy, channelRuntime, personas] = await Promise.all([
14
- readJson(paths.gatewayPolicyPath, paths.catalog.root, normalizePolicy, emptyPolicy),
15
- readJson(paths.gatewayRuntimePath, paths.catalog.root, normalizeRuntime, emptyRuntime),
16
- loadChannelPolicy(paths.catalog.root, paths.catalog), loadChannelRuntime(paths.catalog.root, paths.catalog),
17
- loadPersonaRuntime(paths.catalog.root, paths.catalog)
18
- ]);
19
- if (!policy.enabled || policy.killSwitch) throw new Error("gateway was disabled before delivery");
20
- const outbox = runtime.outbox.find((item) => item.outboxId === exactId(outboxId, "outboxId"));
21
- if (!outbox) throw new Error("unknown outbox item");
22
- if (["delivered", "acknowledged"].includes(outbox.status)) { prepared = { duplicate: true, outbox: structuredClone(outbox) }; return; }
23
- if (outbox.status !== "prepared" && outbox.status !== "failed") throw new Error("outbox item is not safely retryable");
24
- if (new Date(outbox.nextAttemptAt) > new Date(timestamp(now))) throw new Error("outbox retry is not due");
25
- const event = channelRuntime.runtime.events.find((item) => item.eventId === outbox.eventId);
26
- if (!event) throw new Error("outbox channel event is missing");
27
- try {
28
- assertActivePersona(personas.policy, personas.runtime, event.agentId, event.projectId, event.groupId);
29
- exactReplyBinding(channelPolicy.policy, event);
30
- }
31
- catch (error) {
32
- const current = timestamp(now);
33
- preserve(runtime, "outbox", outbox, "capability-revoked", current);
34
- outbox.status = "dead-letter"; outbox.lastError = safeText(error.message, "adapterError", 500);
35
- outbox.updatedAt = current;
36
- const queue = runtime.queue.find((item) => item.queueId === outbox.queueId);
37
- if (queue) { queue.status = "dead-letter"; queue.completedAt = current; queue.updatedAt = current; }
38
- runtime.health.adapter = "failed"; runtime.revision += 1;
39
- const receipt = appendReceipt(runtime, "dead-letter", outbox.outboxId, current, { reason: "identity-or-capability-revoked" });
40
- await writeJson(paths.gatewayRuntimePath, runtime);
41
- prepared = { duplicate: false, terminal: true, outbox: structuredClone(outbox), receipt };
42
- return;
43
- }
44
- preserve(runtime, "outbox", outbox, "sending", timestamp(now));
45
- outbox.status = "sending"; outbox.attempts += 1; outbox.updatedAt = timestamp(now); runtime.revision += 1;
46
- appendReceipt(runtime, "sending", outbox.outboxId, outbox.updatedAt, { attempt: outbox.attempts });
47
- await writeJson(paths.gatewayRuntimePath, runtime);
48
- prepared = { duplicate: false, outbox: structuredClone(outbox) };
49
- });
50
- if (prepared.duplicate || prepared.terminal) return prepared;
51
- let outcome;
52
- try { outcome = await adapter.send(structuredClone(prepared.outbox)); }
53
- catch (error) { outcome = { ok: false, effect: "unknown", error: error.message }; }
54
- return withLock(paths, async () => {
55
- const runtime = await readJson(paths.gatewayRuntimePath, paths.catalog.root, normalizeRuntime, emptyRuntime);
56
- const outbox = runtime.outbox.find((item) => item.outboxId === prepared.outbox.outboxId);
57
- if (!outbox || outbox.status !== "sending") throw new Error("outbox sending state changed unexpectedly");
58
- const current = timestamp(now);
59
- preserve(runtime, "outbox", outbox, outcome?.ok ? "delivered" : "send-failed", current);
60
- if (outcome?.ok) {
61
- outbox.status = "delivered"; outbox.deliveredAt = current; outbox.adapterReceipt = safeText(String(outcome.receipt || "delivered"), "adapterReceipt", 500);
62
- runtime.health.adapter = "healthy";
63
- const queue = runtime.queue.find((item) => item.queueId === outbox.queueId);
64
- if (queue) { queue.status = "completed"; queue.completedAt = current; queue.updatedAt = current; }
65
- } else if (outcome?.effect === "none") {
66
- outbox.status = outbox.attempts < 3 ? "failed" : "dead-letter";
67
- outbox.lastError = safeText(String(outcome.error || "adapter failure"), "adapterError", 500);
68
- runtime.health.adapter = outbox.status === "failed" ? "degraded" : "failed";
69
- if (outbox.status === "failed") {
70
- const delay = Math.min(300000, Number(outcome.retryAfterMs) || 1000 * (2 ** outbox.attempts));
71
- outbox.nextAttemptAt = new Date(new Date(current).getTime() + delay).toISOString();
72
- } else {
73
- const queue = runtime.queue.find((item) => item.queueId === outbox.queueId);
74
- if (queue) { queue.status = "dead-letter"; queue.completedAt = current; queue.updatedAt = current; }
75
- }
76
- } else {
77
- outbox.status = "delivery-unknown"; outbox.lastError = safeText(String(outcome?.error || "delivery outcome is ambiguous"), "adapterError", 500);
78
- runtime.health.adapter = "failed";
79
- }
80
- outbox.updatedAt = current; runtime.revision += 1;
81
- const receipt = appendReceipt(runtime, outbox.status, outbox.outboxId, current, { adapterReceipt: outbox.adapterReceipt });
82
- await writeJson(paths.gatewayRuntimePath, runtime);
83
- return { outbox, receipt, duplicate: false };
84
- });
85
- }
86
-
87
- export async function updateGatewayHealth({ root = process.cwd(), worker = null, adapter = null, host = null,
88
- now = new Date() } = {}) {
89
- const paths = await pathsFor(root);
90
- return withLock(paths, async () => {
91
- const runtime = await readJson(paths.gatewayRuntimePath, paths.catalog.root, normalizeRuntime, emptyRuntime);
92
- for (const [key, value] of Object.entries({ worker, adapter, host })) {
93
- if (value !== null) {
94
- if (!HEALTH_VALUES.has(value)) throw new Error("unsupported gateway health value");
95
- runtime.health[key] = value;
96
- }
97
- }
98
- runtime.health.lastTickAt = timestamp(now); runtime.revision += 1;
99
- await writeJson(paths.gatewayRuntimePath, runtime);
100
- return structuredClone(runtime.health);
101
- });
102
- }
103
-