blun-king-cli 9.1.643 → 9.1.645

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (268) hide show
  1. package/CHANGELOG.md +19 -123
  2. package/LIESMICH.txt +17 -45
  3. package/README.md +15 -76
  4. package/RELEASE-9.1.645.md +29 -0
  5. package/bin/blun.js +3 -3
  6. package/bin/king.js +3 -3
  7. package/bin/launcher-mode.js +125 -126
  8. package/bin/launcher-runtime.js +603 -616
  9. package/bin/plugin-bootstrap.js +339 -405
  10. package/bin/rename-private-staging.cjs +2 -2
  11. package/bin/retired-bundled-plugins.cjs +84 -0
  12. package/bin/startup-security-host.cjs +105 -0
  13. package/bin/startup-security.cjs +9 -105
  14. package/bin/startup-warning-policy.cjs +22 -0
  15. package/bin/update-lease-installer.cjs +125 -0
  16. package/bin/update-lease-sockets.cjs +228 -0
  17. package/bin/update-lease.js +22 -327
  18. package/bin/verify-bundled-agent-sources.cjs +2 -4
  19. package/blun.mjs +77 -180
  20. package/bundled-agent-sources.json +1 -552
  21. package/package.json +3 -6
  22. package/tool-liveness642/receipt.json +1 -1
  23. package/worker-host.mjs +62 -120
  24. package/agent-spine-plugin/.claude-plugin/marketplace.json +0 -20
  25. package/agent-spine-plugin/.claude-plugin/plugin.json +0 -14
  26. package/agent-spine-plugin/.codex-plugin/plugin.json +0 -47
  27. package/agent-spine-plugin/.mcp.json +0 -8
  28. package/agent-spine-plugin/CHANGELOG.md +0 -1614
  29. package/agent-spine-plugin/LICENSE +0 -186
  30. package/agent-spine-plugin/README.md +0 -432
  31. package/agent-spine-plugin/assets/agentspine-banner.svg +0 -32
  32. package/agent-spine-plugin/bin/agentspine-mcp.js +0 -4
  33. package/agent-spine-plugin/bin/agentspine.js +0 -7
  34. package/agent-spine-plugin/blun.plugin.json +0 -68
  35. package/agent-spine-plugin/docs/acceptance.md +0 -61
  36. package/agent-spine-plugin/docs/artifact-evaluation.md +0 -93
  37. package/agent-spine-plugin/docs/host-integration.md +0 -193
  38. package/agent-spine-plugin/docs/preflight-recall.md +0 -71
  39. package/agent-spine-plugin/docs/preservation-contract.md +0 -53
  40. package/agent-spine-plugin/docs/quality-gates.md +0 -50
  41. package/agent-spine-plugin/docs/session-timeline.md +0 -112
  42. package/agent-spine-plugin/docs/source-roots.md +0 -113
  43. package/agent-spine-plugin/docs/world-model.md +0 -119
  44. package/agent-spine-plugin/hooks/codex.json +0 -47
  45. package/agent-spine-plugin/hooks/hooks.json +0 -106
  46. package/agent-spine-plugin/hooks/version.json +0 -5
  47. package/agent-spine-plugin/package.json +0 -77
  48. package/agent-spine-plugin/scripts/check-codex-install.js +0 -226
  49. package/agent-spine-plugin/scripts/check-hosts.js +0 -208
  50. package/agent-spine-plugin/scripts/check-install-hook.js +0 -227
  51. package/agent-spine-plugin/scripts/check-install-selfstarter.js +0 -154
  52. package/agent-spine-plugin/scripts/check-install.js +0 -478
  53. package/agent-spine-plugin/scripts/check-line-budget.js +0 -58
  54. package/agent-spine-plugin/scripts/check-syntax.js +0 -29
  55. package/agent-spine-plugin/scripts/github-actions.js +0 -11
  56. package/agent-spine-plugin/scripts/hermetic-process.js +0 -191
  57. package/agent-spine-plugin/scripts/release-check.js +0 -150
  58. package/agent-spine-plugin/scripts/run-acceptance.js +0 -19
  59. package/agent-spine-plugin/scripts/run-checks.js +0 -50
  60. package/agent-spine-plugin/scripts/run-tests-hermetic.js +0 -112
  61. package/agent-spine-plugin/skills/agent-spine/SKILL.md +0 -99
  62. package/agent-spine-plugin/spine-example/1-identity.md +0 -12
  63. package/agent-spine-plugin/spine-example/2-voice.md +0 -6
  64. package/agent-spine-plugin/spine-example/3-conduct.md +0 -8
  65. package/agent-spine-plugin/spine-example/4-history.md +0 -4
  66. package/agent-spine-plugin/src/cli-agent.js +0 -315
  67. package/agent-spine-plugin/src/cli-attention.js +0 -95
  68. package/agent-spine-plugin/src/cli-autonomy.js +0 -36
  69. package/agent-spine-plugin/src/cli-common.js +0 -71
  70. package/agent-spine-plugin/src/cli-continuity.js +0 -116
  71. package/agent-spine-plugin/src/cli-core.js +0 -128
  72. package/agent-spine-plugin/src/cli-diagnostics.js +0 -291
  73. package/agent-spine-plugin/src/cli-host.js +0 -21
  74. package/agent-spine-plugin/src/cli-learning.js +0 -320
  75. package/agent-spine-plugin/src/cli-premortem.js +0 -16
  76. package/agent-spine-plugin/src/cli-sharing.js +0 -230
  77. package/agent-spine-plugin/src/cli.js +0 -181
  78. package/agent-spine-plugin/src/codex-reader-launcher.js +0 -182
  79. package/agent-spine-plugin/src/hook.js +0 -500
  80. package/agent-spine-plugin/src/index.js +0 -108
  81. package/agent-spine-plugin/src/lib/acceptance.js +0 -435
  82. package/agent-spine-plugin/src/lib/action-lesson-recall.js +0 -118
  83. package/agent-spine-plugin/src/lib/attention-context.js +0 -167
  84. package/agent-spine-plugin/src/lib/attention-events.js +0 -113
  85. package/agent-spine-plugin/src/lib/attention-privacy.js +0 -72
  86. package/agent-spine-plugin/src/lib/attention-schema.js +0 -164
  87. package/agent-spine-plugin/src/lib/attention-storage.js +0 -93
  88. package/agent-spine-plugin/src/lib/attention.js +0 -164
  89. package/agent-spine-plugin/src/lib/audit-premortem.js +0 -223
  90. package/agent-spine-plugin/src/lib/audit.js +0 -401
  91. package/agent-spine-plugin/src/lib/authentication.js +0 -515
  92. package/agent-spine-plugin/src/lib/autonomy-policy.js +0 -110
  93. package/agent-spine-plugin/src/lib/autonomy-store.js +0 -202
  94. package/agent-spine-plugin/src/lib/autonomy.js +0 -8
  95. package/agent-spine-plugin/src/lib/briefing.js +0 -493
  96. package/agent-spine-plugin/src/lib/catalog-document-read.js +0 -51
  97. package/agent-spine-plugin/src/lib/catalog.js +0 -167
  98. package/agent-spine-plugin/src/lib/channel-continuity.js +0 -19
  99. package/agent-spine-plugin/src/lib/channel-runtime.js +0 -665
  100. package/agent-spine-plugin/src/lib/codex-installation.js +0 -231
  101. package/agent-spine-plugin/src/lib/codex-skill-installation.js +0 -211
  102. package/agent-spine-plugin/src/lib/context.js +0 -156
  103. package/agent-spine-plugin/src/lib/continuity.js +0 -338
  104. package/agent-spine-plugin/src/lib/coordination.js +0 -577
  105. package/agent-spine-plugin/src/lib/delivery-agent-usage.js +0 -231
  106. package/agent-spine-plugin/src/lib/delivery-assignment.js +0 -220
  107. package/agent-spine-plugin/src/lib/delivery-command-actions.js +0 -462
  108. package/agent-spine-plugin/src/lib/delivery-knowledge.js +0 -78
  109. package/agent-spine-plugin/src/lib/delivery-premortem-binding.js +0 -107
  110. package/agent-spine-plugin/src/lib/delivery-premortem-closure.js +0 -171
  111. package/agent-spine-plugin/src/lib/delivery-premortem-codec.js +0 -45
  112. package/agent-spine-plugin/src/lib/delivery-premortem-correction.js +0 -101
  113. package/agent-spine-plugin/src/lib/delivery-premortem-file.js +0 -21
  114. package/agent-spine-plugin/src/lib/delivery-premortem-index.js +0 -493
  115. package/agent-spine-plugin/src/lib/delivery-premortem-inspection.js +0 -37
  116. package/agent-spine-plugin/src/lib/delivery-premortem-recovery.js +0 -120
  117. package/agent-spine-plugin/src/lib/delivery-premortem-rejection.js +0 -65
  118. package/agent-spine-plugin/src/lib/delivery-premortem-results.js +0 -28
  119. package/agent-spine-plugin/src/lib/delivery-premortem-session-guard.js +0 -46
  120. package/agent-spine-plugin/src/lib/delivery-premortem-write-ledger.js +0 -285
  121. package/agent-spine-plugin/src/lib/delivery-premortem.js +0 -499
  122. package/agent-spine-plugin/src/lib/delivery-shell-heredoc.js +0 -115
  123. package/agent-spine-plugin/src/lib/delivery-shell-substitutions.js +0 -111
  124. package/agent-spine-plugin/src/lib/delivery-shell-wrapper.js +0 -64
  125. package/agent-spine-plugin/src/lib/delivery-target.js +0 -73
  126. package/agent-spine-plugin/src/lib/delivery-verification.js +0 -445
  127. package/agent-spine-plugin/src/lib/documents.js +0 -239
  128. package/agent-spine-plugin/src/lib/feed-transport.js +0 -499
  129. package/agent-spine-plugin/src/lib/filesystem-retry.js +0 -34
  130. package/agent-spine-plugin/src/lib/gateway-common.js +0 -68
  131. package/agent-spine-plugin/src/lib/gateway-control.js +0 -370
  132. package/agent-spine-plugin/src/lib/gateway-delivery.js +0 -103
  133. package/agent-spine-plugin/src/lib/gateway-execution.js +0 -350
  134. package/agent-spine-plugin/src/lib/gateway-group-response.js +0 -128
  135. package/agent-spine-plugin/src/lib/gateway-host-fencing.js +0 -92
  136. package/agent-spine-plugin/src/lib/gateway-host-lifecycle.js +0 -193
  137. package/agent-spine-plugin/src/lib/gateway-inspection.js +0 -85
  138. package/agent-spine-plugin/src/lib/gateway-knowledge.js +0 -129
  139. package/agent-spine-plugin/src/lib/gateway-policy-provenance.js +0 -197
  140. package/agent-spine-plugin/src/lib/gateway-premortem-disposition.js +0 -82
  141. package/agent-spine-plugin/src/lib/gateway-premortem.js +0 -363
  142. package/agent-spine-plugin/src/lib/gateway-prepared-host.js +0 -28
  143. package/agent-spine-plugin/src/lib/gateway-runs.js +0 -345
  144. package/agent-spine-plugin/src/lib/gateway-runtime-identity.js +0 -31
  145. package/agent-spine-plugin/src/lib/gateway-runtime-records.js +0 -21
  146. package/agent-spine-plugin/src/lib/gateway-runtime.js +0 -18
  147. package/agent-spine-plugin/src/lib/gateway-state-transaction.js +0 -356
  148. package/agent-spine-plugin/src/lib/gateway-state.js +0 -344
  149. package/agent-spine-plugin/src/lib/graph.js +0 -337
  150. package/agent-spine-plugin/src/lib/hook-artifact-guards.js +0 -356
  151. package/agent-spine-plugin/src/lib/hook-audit.js +0 -43
  152. package/agent-spine-plugin/src/lib/hook-briefing-use.js +0 -78
  153. package/agent-spine-plugin/src/lib/hook-context.js +0 -441
  154. package/agent-spine-plugin/src/lib/hook-final-message.js +0 -26
  155. package/agent-spine-plugin/src/lib/hook-input.js +0 -27
  156. package/agent-spine-plugin/src/lib/hook-output.js +0 -284
  157. package/agent-spine-plugin/src/lib/hook-premortem.js +0 -257
  158. package/agent-spine-plugin/src/lib/hook-process-advisory.js +0 -36
  159. package/agent-spine-plugin/src/lib/hook-protection.js +0 -95
  160. package/agent-spine-plugin/src/lib/hook-stop-verification.js +0 -84
  161. package/agent-spine-plugin/src/lib/hook-timeline.js +0 -102
  162. package/agent-spine-plugin/src/lib/host-instruction-budget.js +0 -11
  163. package/agent-spine-plugin/src/lib/https-transport.js +0 -392
  164. package/agent-spine-plugin/src/lib/identifier-analysis.js +0 -446
  165. package/agent-spine-plugin/src/lib/indexed-memory-offline.js +0 -40
  166. package/agent-spine-plugin/src/lib/indexed-memory.js +0 -298
  167. package/agent-spine-plugin/src/lib/knowledge-evidence.js +0 -431
  168. package/agent-spine-plugin/src/lib/learning-applications.js +0 -441
  169. package/agent-spine-plugin/src/lib/learning-artifact-evaluator.js +0 -114
  170. package/agent-spine-plugin/src/lib/learning-candidates.js +0 -274
  171. package/agent-spine-plugin/src/lib/learning-context.js +0 -137
  172. package/agent-spine-plugin/src/lib/learning-delivery-contracts.js +0 -310
  173. package/agent-spine-plugin/src/lib/learning-evaluation-contracts.js +0 -350
  174. package/agent-spine-plugin/src/lib/learning-evaluation-registration.js +0 -372
  175. package/agent-spine-plugin/src/lib/learning-evaluation-revocation.js +0 -292
  176. package/agent-spine-plugin/src/lib/learning-evidence-contracts.js +0 -321
  177. package/agent-spine-plugin/src/lib/learning-findings.js +0 -458
  178. package/agent-spine-plugin/src/lib/learning-measurement-contracts.js +0 -285
  179. package/agent-spine-plugin/src/lib/learning-measurements.js +0 -265
  180. package/agent-spine-plugin/src/lib/learning-outcome-contracts.js +0 -165
  181. package/agent-spine-plugin/src/lib/learning-outcomes.js +0 -343
  182. package/agent-spine-plugin/src/lib/learning-reconciliation.js +0 -290
  183. package/agent-spine-plugin/src/lib/learning-retry-contracts.js +0 -188
  184. package/agent-spine-plugin/src/lib/learning-schema.js +0 -229
  185. package/agent-spine-plugin/src/lib/learning-scope-targets.js +0 -424
  186. package/agent-spine-plugin/src/lib/learning-state-upgrade.js +0 -477
  187. package/agent-spine-plugin/src/lib/learning-status-configuration.js +0 -476
  188. package/agent-spine-plugin/src/lib/learning-storage.js +0 -203
  189. package/agent-spine-plugin/src/lib/learning-trial-recovery.js +0 -218
  190. package/agent-spine-plugin/src/lib/learning-validation-contracts.js +0 -375
  191. package/agent-spine-plugin/src/lib/learning-validation-renewal.js +0 -298
  192. package/agent-spine-plugin/src/lib/learning-validation-runtime.js +0 -234
  193. package/agent-spine-plugin/src/lib/learning.js +0 -36
  194. package/agent-spine-plugin/src/lib/lesson-recall-session.js +0 -172
  195. package/agent-spine-plugin/src/lib/mcp-autonomy-tools.js +0 -37
  196. package/agent-spine-plugin/src/lib/mcp-delivery-completion.js +0 -124
  197. package/agent-spine-plugin/src/lib/mcp-delivery-tools.js +0 -45
  198. package/agent-spine-plugin/src/lib/mcp-premortem.js +0 -68
  199. package/agent-spine-plugin/src/lib/mcp-runtime.js +0 -355
  200. package/agent-spine-plugin/src/lib/mcp-source-context.js +0 -61
  201. package/agent-spine-plugin/src/lib/mcp-timeline-tools.js +0 -240
  202. package/agent-spine-plugin/src/lib/mcp-world-tools.js +0 -52
  203. package/agent-spine-plugin/src/lib/object-transport.js +0 -206
  204. package/agent-spine-plugin/src/lib/owned-file-lock.js +0 -182
  205. package/agent-spine-plugin/src/lib/paths.js +0 -109
  206. package/agent-spine-plugin/src/lib/peer-transport.js +0 -283
  207. package/agent-spine-plugin/src/lib/persona-runtime.js +0 -581
  208. package/agent-spine-plugin/src/lib/pre-answer-timeline-recall.js +0 -104
  209. package/agent-spine-plugin/src/lib/preflight-delivery-id.js +0 -27
  210. package/agent-spine-plugin/src/lib/preflight.js +0 -688
  211. package/agent-spine-plugin/src/lib/project-portfolio.js +0 -176
  212. package/agent-spine-plugin/src/lib/runtime.js +0 -13
  213. package/agent-spine-plugin/src/lib/selfstarter-core.js +0 -382
  214. package/agent-spine-plugin/src/lib/selfstarter-jobs.js +0 -149
  215. package/agent-spine-plugin/src/lib/selfstarter-lease.js +0 -204
  216. package/agent-spine-plugin/src/lib/selfstarter-policy.js +0 -90
  217. package/agent-spine-plugin/src/lib/selfstarter-workspace.js +0 -111
  218. package/agent-spine-plugin/src/lib/selfstarter.js +0 -11
  219. package/agent-spine-plugin/src/lib/session-timeline-auth.js +0 -316
  220. package/agent-spine-plugin/src/lib/session-timeline-codex.js +0 -69
  221. package/agent-spine-plugin/src/lib/session-timeline-contract.js +0 -56
  222. package/agent-spine-plugin/src/lib/session-timeline-enrollment-source.js +0 -38
  223. package/agent-spine-plugin/src/lib/session-timeline-enrollment-storage.js +0 -128
  224. package/agent-spine-plugin/src/lib/session-timeline-enrollment-transport.js +0 -15
  225. package/agent-spine-plugin/src/lib/session-timeline-enrollment.js +0 -478
  226. package/agent-spine-plugin/src/lib/session-timeline-event-extract.js +0 -186
  227. package/agent-spine-plugin/src/lib/session-timeline-host-origin.js +0 -73
  228. package/agent-spine-plugin/src/lib/session-timeline-host-receipt.js +0 -117
  229. package/agent-spine-plugin/src/lib/session-timeline-invocation.js +0 -201
  230. package/agent-spine-plugin/src/lib/session-timeline-king.js +0 -93
  231. package/agent-spine-plugin/src/lib/session-timeline-prior.js +0 -57
  232. package/agent-spine-plugin/src/lib/session-timeline-provider.js +0 -36
  233. package/agent-spine-plugin/src/lib/session-timeline-query.js +0 -56
  234. package/agent-spine-plugin/src/lib/session-timeline-results.js +0 -56
  235. package/agent-spine-plugin/src/lib/session-timeline-root.js +0 -11
  236. package/agent-spine-plugin/src/lib/session-timeline-search.js +0 -82
  237. package/agent-spine-plugin/src/lib/session-timeline-sid-acl.js +0 -213
  238. package/agent-spine-plugin/src/lib/session-timeline-source-open.js +0 -30
  239. package/agent-spine-plugin/src/lib/session-timeline-source.js +0 -80
  240. package/agent-spine-plugin/src/lib/session-timeline-state.js +0 -45
  241. package/agent-spine-plugin/src/lib/session-timeline-transport.js +0 -42
  242. package/agent-spine-plugin/src/lib/session-timeline-windows-acl.js +0 -145
  243. package/agent-spine-plugin/src/lib/session-timeline.js +0 -462
  244. package/agent-spine-plugin/src/lib/sharing.js +0 -969
  245. package/agent-spine-plugin/src/lib/source-roots.js +0 -475
  246. package/agent-spine-plugin/src/lib/source-tree-scan.js +0 -178
  247. package/agent-spine-plugin/src/lib/sqlite-transport.js +0 -501
  248. package/agent-spine-plugin/src/lib/task-knowledge-context.js +0 -99
  249. package/agent-spine-plugin/src/lib/telegram-adapter.js +0 -119
  250. package/agent-spine-plugin/src/lib/timeline-continuation-update.js +0 -100
  251. package/agent-spine-plugin/src/lib/timeline-tool-guard.js +0 -225
  252. package/agent-spine-plugin/src/lib/timeline-user-feedback.js +0 -216
  253. package/agent-spine-plugin/src/lib/timeline-world-capture.js +0 -233
  254. package/agent-spine-plugin/src/lib/voice-runtime.js +0 -39
  255. package/agent-spine-plugin/src/lib/world-knowledge.js +0 -306
  256. package/agent-spine-plugin/src/lib/world-model.js +0 -333
  257. package/agent-spine-plugin/src/mcp.js +0 -456
  258. package/agent-spine-plugin/src/version.js +0 -1
  259. package/agent-spine-plugin/src/worker.js +0 -257
  260. package/bin/agentspine-king-goal-inbox.mjs +0 -127
  261. package/bin/agentspine-king-goal-intake.mjs +0 -106
  262. package/bin/agentspine-king-host-runner.mjs +0 -109
  263. package/bin/agentspine-king-snapshot-policy.cjs +0 -80
  264. package/bin/agentspine-king-status-policy.mjs +0 -226
  265. package/bin/agentspine-king-worker-host.mjs +0 -160
  266. package/bin/managed-plugin-selection.cjs +0 -141
  267. package/bin/verify-agent-behavior.cjs +0 -122
  268. package/bin/verify-agent-components.cjs +0 -104
@@ -1,441 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import { recordAttentionEvent } from "./attention.js";
3
- import { catalogForStateRoot } from "./catalog.js";
4
- import { claimChannelEvent } from "./channel-runtime.js";
5
- import { loadContinuity } from "./continuity.js";
6
- import { resolveSessionJob, startOrResumeJob } from "./selfstarter.js";
7
-
8
- const STANDARD_HOST_CONTEXT_BYTES = 9500;
9
- const MAX_CLAUDE_OVERFLOW_CONTEXT_BYTES = 32 * 1024;
10
- const ID_RE = /^[A-Za-z0-9][A-Za-z0-9:_.@/-]{0,127}$/;
11
- export const ATTENTION_WRITE_EVENTS = new Set(["UserPromptSubmit", "PostToolUse", "Stop", "SubagentStop"]);
12
- const SELFSTART_EVENTS = new Set(["SessionStart", "PostCompact"]);
13
-
14
- export function boundedId(value, field) {
15
- if (value === null || value === undefined || value === "") return null;
16
- if (typeof value !== "string" || !ID_RE.test(value)) throw new Error(`${field} is invalid`);
17
- return value;
18
- }
19
-
20
- function positiveInteger(value, field) {
21
- if (value === null || value === undefined || value === "") return null;
22
- const parsed = typeof value === "number"
23
- ? value
24
- : (typeof value === "string" && /^[1-9][0-9]*$/.test(value) ? Number(value) : Number.NaN);
25
- if (!Number.isSafeInteger(parsed) || parsed < 1) throw new Error(`${field} is invalid`);
26
- return parsed;
27
- }
28
-
29
- export function promptFromInput(input) {
30
- for (const key of ["prompt", "user_prompt", "message", "input"]) {
31
- const value = input[key];
32
- if (typeof value === "string") return value;
33
- if (Array.isArray(value)) {
34
- const text = value
35
- .filter((part) => part && typeof part === "object" && part.type === "text" && typeof part.text === "string")
36
- .map((part) => part.text)
37
- .join("\n")
38
- .trim();
39
- if (text) return text;
40
- }
41
- }
42
- return null;
43
- }
44
-
45
- export function hostContextLimit(preflight) {
46
- if (preflight?.receipt?.instructionHost === "codex") return 32768 + Buffer.byteLength(JSON.stringify(preflight.briefing || {}));
47
- const mode = preflight?.receipt?.instructionBudget?.mode;
48
- if (mode === "claude-required-overflow") return MAX_CLAUDE_OVERFLOW_CONTEXT_BYTES;
49
- return STANDARD_HOST_CONTEXT_BYTES;
50
- }
51
-
52
- export function hostFromInput(input) {
53
- const explicit = input.host || input.provider || process.env.AGENTSPINE_HOST;
54
- if (["claude", "codex", "generic"].includes(explicit)) return explicit;
55
- if ((typeof input.model === "string" && input.model.trim()) || process.env.PLUGIN_ROOT || process.env.CODEX_HOME
56
- || process.env.BLUN_PLUGIN_ROOT || process.env.BLUN_HOME) return "codex";
57
- return "claude";
58
- }
59
-
60
- export function gatewayEnvironmentContext(env = process.env) {
61
- if (env.AGENTSPINE_GATEWAY_CONTEXT !== "agentspine.gateway-start/v1") return null;
62
- const portalRef = boundedId(env.AGENTSPINE_PORTAL_REF, "AGENTSPINE_PORTAL_REF");
63
- const threadRef = boundedId(env.AGENTSPINE_THREAD_REF, "AGENTSPINE_THREAD_REF");
64
- if (Boolean(portalRef) !== Boolean(threadRef)) throw new Error("gateway portal and thread references must be paired");
65
- return {
66
- host: boundedId(env.AGENTSPINE_HOST, "AGENTSPINE_HOST"),
67
- entityId: boundedId(env.AGENTSPINE_ENTITY_ID, "AGENTSPINE_ENTITY_ID"),
68
- groupId: boundedId(env.AGENTSPINE_GROUP_ID, "AGENTSPINE_GROUP_ID"),
69
- projectId: boundedId(env.AGENTSPINE_PROJECT_ID, "AGENTSPINE_PROJECT_ID"),
70
- taskId: boundedId(env.AGENTSPINE_TASK_ID, "AGENTSPINE_TASK_ID"),
71
- queueId: boundedId(env.AGENTSPINE_GATEWAY_QUEUE_ID, "AGENTSPINE_GATEWAY_QUEUE_ID"),
72
- goalId: boundedId(env.AGENTSPINE_GOAL_ID, "AGENTSPINE_GOAL_ID"),
73
- goalStepId: boundedId(env.AGENTSPINE_GOAL_STEP_ID, "AGENTSPINE_GOAL_STEP_ID"),
74
- planDefinitionsDigest: boundedId(env.AGENTSPINE_PLAN_DEFINITIONS_DIGEST,
75
- "AGENTSPINE_PLAN_DEFINITIONS_DIGEST"),
76
- gatewayAttempt: positiveInteger(env.AGENTSPINE_GATEWAY_ATTEMPT, "AGENTSPINE_GATEWAY_ATTEMPT"),
77
- eventId: boundedId(env.AGENTSPINE_CHANNEL_EVENT_ID, "AGENTSPINE_CHANNEL_EVENT_ID"),
78
- provider: boundedId(env.AGENTSPINE_CHANNEL_PROVIDER, "AGENTSPINE_CHANNEL_PROVIDER"),
79
- portalRef, threadRef
80
- };
81
- }
82
-
83
- function gatewayBound(gateway, key, suppliedValue, field, allowAbsent = false) {
84
- if (!gateway) return suppliedValue;
85
- const gatewayValue = gateway[key];
86
- if (gatewayValue === null || gatewayValue === undefined || gatewayValue === "") {
87
- if (allowAbsent) return suppliedValue;
88
- if (suppliedValue !== undefined && suppliedValue !== null && suppliedValue !== "") {
89
- throw new Error(`${field} does not match the authenticated gateway binding`);
90
- }
91
- return null;
92
- }
93
- if (suppliedValue !== undefined && suppliedValue !== null
94
- && suppliedValue !== "" && suppliedValue !== gatewayValue) {
95
- throw new Error(`${field} does not match the authenticated gateway binding`);
96
- }
97
- return gatewayValue;
98
- }
99
-
100
- export async function runtimeScope(input, root, userStateRoot = null, catalog) {
101
- const { continuity: projectContinuity } = await loadContinuity(root, catalog);
102
- const userCatalog = userStateRoot && userStateRoot !== root
103
- ? catalogForStateRoot(catalog, userStateRoot) : catalog;
104
- const userContinuity = userStateRoot && userStateRoot !== root
105
- ? (await loadContinuity(userStateRoot, userCatalog)).continuity
106
- : projectContinuity;
107
- const continuity = {
108
- config: {
109
- ...projectContinuity.config,
110
- enabled: userContinuity.config.enabled,
111
- minConfidence: userContinuity.config.minConfidence,
112
- minDirectness: userContinuity.config.minDirectness,
113
- minEvidence: userContinuity.config.minEvidence,
114
- maxPromptBytes: userContinuity.config.maxPromptBytes,
115
- maxBriefingBytes: userContinuity.config.maxBriefingBytes,
116
- defaultEntityId: userContinuity.config.defaultEntityId
117
- }
118
- };
119
- const supplied = input.agent_spine_scope && typeof input.agent_spine_scope === "object"
120
- ? input.agent_spine_scope : input;
121
- const gateway = gatewayEnvironmentContext();
122
- const suppliedAttempt = positiveInteger(supplied.gateway_attempt ?? supplied.gatewayAttempt,
123
- "gatewayAttempt");
124
- const suppliedPortalRef = supplied.portal_ref ?? supplied.portalRef;
125
- const suppliedThreadRef = supplied.thread_ref ?? supplied.threadRef;
126
- if (!gateway && [suppliedPortalRef, suppliedThreadRef].some((value) => value !== undefined && value !== null && value !== "")) {
127
- throw new Error("portal timeline scope requires an authenticated gateway binding");
128
- }
129
- return {
130
- entityId: boundedId(gatewayBound(gateway, "entityId",
131
- supplied.entity_id ?? supplied.entityId, "entityId")
132
- ?? (gateway ? null : continuity.config.defaultEntityId), "entityId"),
133
- userId: boundedId(supplied.user_id ?? supplied.userId ?? process.env.AGENTSPINE_USER_ID, "userId"),
134
- tenantId: boundedId(supplied.tenant_id ?? supplied.tenantId ?? process.env.AGENTSPINE_TENANT_ID, "tenantId"),
135
- groupId: boundedId(gatewayBound(gateway, "groupId",
136
- supplied.group_id ?? supplied.groupId, "groupId"), "groupId"),
137
- projectId: boundedId(gatewayBound(gateway, "projectId",
138
- supplied.project_id ?? supplied.projectId, "projectId")
139
- ?? (gateway ? null : continuity.config.defaultProjectId), "projectId"),
140
- currentTaskId: boundedId(gatewayBound(gateway, "taskId",
141
- supplied.task_id ?? supplied.taskId ?? supplied.currentTaskId, "currentTaskId", true), "currentTaskId"),
142
- queueId: boundedId(gatewayBound(gateway, "queueId",
143
- supplied.queue_id ?? supplied.queueId, "queueId"), "queueId"),
144
- goalId: boundedId(gatewayBound(gateway, "goalId",
145
- supplied.goal_id ?? supplied.goalId, "goalId"), "goalId"),
146
- goalStepId: boundedId(gatewayBound(gateway, "goalStepId",
147
- supplied.goal_step_id ?? supplied.goalStepId, "goalStepId"), "goalStepId"),
148
- planDefinitionsDigest: boundedId(gatewayBound(gateway, "planDefinitionsDigest",
149
- supplied.plan_definitions_digest ?? supplied.planDefinitionsDigest,
150
- "planDefinitionsDigest"), "planDefinitionsDigest"),
151
- gatewayAttempt: gatewayBound(gateway, "gatewayAttempt", suppliedAttempt, "gatewayAttempt"),
152
- portalRef: boundedId(gatewayBound(gateway, "portalRef", suppliedPortalRef, "portalRef"), "portalRef"),
153
- threadRef: boundedId(gatewayBound(gateway, "threadRef", suppliedThreadRef, "threadRef"), "threadRef"),
154
- host: gateway
155
- ? gatewayBound(gateway, "host", input.host ?? input.provider, "host")
156
- : hostFromInput(input),
157
- config: continuity.config
158
- };
159
- }
160
-
161
- export function renderContext(event, catalog, briefing, signal = null, attentionEvent = null, selfstarter = null, channelEvent = null, sourceDiagnostics = null, preflight = null, lessonRecall = null) {
162
- const partial = sourceDiagnostics?.status === "incomplete" && catalog.summary.total > 0;
163
- const loaded = sourceDiagnostics?.status === "loaded" || partial;
164
- const packet = {
165
- schema: "agentspine.hook-context/v1",
166
- event,
167
- priority: ["current-user-request", "explicit-stops", "current-task", "host-rules", "accepted-context", "style-and-relationships"],
168
- loaded,
169
- instruction: partial
170
- ? "Apply only listed sources; others are unverified. Inspect sourceResolution; do not retry."
171
- : loaded
172
- ? "Use this already-loaded briefing now. Do not call an MCP tool to obtain it. The current user request and explicit stops override all remembered style, relationships, and older context."
173
- : "No host-native source context was loaded. Do not claim personal continuity or recall succeeded. Continue under current native host rules and inspect sourceResolution.",
174
- signal: signal ? {
175
- captured: Boolean(signal.captured),
176
- accepted: Boolean(signal.accepted),
177
- duplicate: Boolean(signal.duplicate),
178
- kind: signal.kind || null,
179
- reason: signal.reason || null
180
- } : null,
181
- attentionEvent: attentionEvent ? {
182
- captured: Boolean(attentionEvent.event),
183
- duplicate: Boolean(attentionEvent.duplicate),
184
- id: attentionEvent.event?.id || null,
185
- kind: attentionEvent.event?.kind || null,
186
- status: attentionEvent.event?.status || null,
187
- reason: attentionEvent.reason || null
188
- } : null,
189
- selfstarter: selfstarter ? {
190
- active: Boolean(selfstarter.job),
191
- blocked: Boolean(selfstarter.blocked),
192
- action: selfstarter.action || null,
193
- reason: selfstarter.reason || null,
194
- jobId: selfstarter.job?.id || null,
195
- taskId: selfstarter.job?.taskId || null,
196
- actorId: selfstarter.job?.actorId || null,
197
- targetId: selfstarter.job?.targetId || null,
198
- projectId: selfstarter.job?.projectId || null,
199
- groupId: selfstarter.job?.groupId || null,
200
- checkpointSequence: selfstarter.job?.checkpoint?.sequence ?? null,
201
- capabilities: selfstarter.job?.capabilities || [],
202
- leaseExpiresAt: selfstarter.job?.lease?.expiresAt || null,
203
- receiptId: selfstarter.receipt?.id || null,
204
- instruction: selfstarter.job
205
- ? "Resume only this exact checkpointed job. Attach its job ID to every host tool event. Each effect is separately re-authorized by PreToolUse and checkpointed by PostToolUse. Stop immediately on any denial."
206
- : null,
207
- authority: selfstarter.job ? "explicit-local-execution-policy" : "execution-state-only"
208
- } : null,
209
- channelEvent: channelEvent?.event ? {
210
- active: true,
211
- eventId: channelEvent.event.eventId,
212
- bindingId: channelEvent.event.bindingId,
213
- provider: channelEvent.event.provider,
214
- chatId: channelEvent.event.chatId,
215
- threadId: channelEvent.event.threadId,
216
- senderId: channelEvent.event.senderId,
217
- replyTo: channelEvent.event.replyTo,
218
- agentId: channelEvent.event.agentId,
219
- projectId: channelEvent.event.projectId,
220
- groupId: channelEvent.event.groupId,
221
- sessionKey: channelEvent.event.sessionKey,
222
- text: channelEvent.event.text,
223
- leaseExpiresAt: channelEvent.event.lease?.expiresAt || null,
224
- receiptId: channelEvent.receipt?.id || null,
225
- instruction: "Answer this exact authenticated channel event in its bound chat and thread. Do not infer another recipient or route. Sending remains subject to the separate current channel policy and adapter receipt.",
226
- authority: "explicit-local-channel-policy"
227
- } : null,
228
- indexedSources: catalog.summary.total,
229
- sourceResolution: sourceDiagnostics,
230
- lessonRecall: lessonRecall?.status === "recalled" ? {
231
- status: "recalled", schema: lessonRecall.schema, receiptDigest: lessonRecall.receiptDigest,
232
- items: lessonRecall.items, learning: lessonRecall.learning || [],
233
- learningDiagnostics: lessonRecall.learningDiagnostics || null, omitted: lessonRecall.omitted,
234
- instruction: lessonRecall.instruction, authority: "context-only"
235
- } : lessonRecall?.status === "group-suppressed" ? {
236
- status: "group-suppressed", items: [], authority: "context-only"
237
- } : null,
238
- preflight: preflight ? {
239
- schema: preflight.receipt.schema,
240
- receiptId: preflight.receipt.id,
241
- promptDigest: preflight.receipt.promptDigest,
242
- briefingDigest: preflight.receipt.briefingDigest,
243
- createdAt: preflight.receipt.createdAt,
244
- expiresAt: preflight.receipt.expiresAt,
245
- policy: preflight.policy,
246
- learningApplications: preflight.learningApplications || null,
247
- pendingMustRemember: preflight.pendingMustRemember ? {
248
- id: preflight.pendingMustRemember.candidate?.id || null,
249
- status: preflight.pendingMustRemember.candidate?.status || (preflight.pendingMustRemember.rejected ? "rejected" : null),
250
- reason: preflight.pendingMustRemember.reason || null
251
- } : null,
252
- premortem: preflight.premortem ? {
253
- status: preflight.premortem.status,
254
- requirementId: preflight.premortem.requirementId || null,
255
- digest: preflight.premortem.requirement?.digest || null,
256
- registration: preflight.premortem.registration || null,
257
- instruction: preflight.premortem.instruction,
258
- authority: preflight.premortem.requirement?.authority || "context-only"
259
- } : null,
260
- briefing: preflight.briefing,
261
- instruction: "This exact turn passed the mandatory pre-answer gate. Apply the complete preflight briefing before answering.",
262
- authority: "preflight-proof-only"
263
- } : null,
264
- briefing,
265
- authority: "context-only"
266
- };
267
- return JSON.stringify(packet);
268
- }
269
-
270
- export function selfstarterInput(input) {
271
- const value = input.agent_spine_job;
272
- if (value === undefined || value === null) return null;
273
- if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("agent_spine_job must be one object");
274
- return value;
275
- }
276
-
277
- function channelEventInput(input) {
278
- const gateway = gatewayEnvironmentContext();
279
- const value = input.agent_spine_channel_event ?? (input.hook_event_name === "SessionStart"
280
- && gateway?.eventId && gateway?.provider
281
- ? { event_id: gateway.eventId, provider: gateway.provider } : null);
282
- if (value === undefined || value === null) return null;
283
- if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("agent_spine_channel_event must be one object");
284
- const unknown = Object.keys(value).filter((key) => !["event_id", "eventId", "provider"].includes(key));
285
- if (unknown.length) throw new Error(`agent_spine_channel_event contains unknown field: ${unknown.sort()[0]}`);
286
- return value;
287
- }
288
-
289
- export function hookDeliveryId(input) {
290
- return boundedId(input.tool_use_id ?? input.event_id ?? input.hook_event_id, "toolUseId");
291
- }
292
-
293
- export function sessionId(input) {
294
- return boundedId(input.session_id ?? input.sessionId, "sessionId");
295
- }
296
-
297
- export function selfstarterRootSkipped(sourceDiagnostics) {
298
- return ["skipped-unmarked-home", "skipped-home-root", "skipped-profile-root"]
299
- .includes(sourceDiagnostics?.projectTreeScan);
300
- }
301
-
302
- export async function startSelfstarter(input, event, root, scope, sourceDiagnostics) {
303
- if (!SELFSTART_EVENTS.has(event)) return null;
304
- const requested = selfstarterInput(input);
305
- if (selfstarterRootSkipped(sourceDiagnostics)) {
306
- if (requested) throw new Error("self-starter cannot use a user home or host profile as its workspace root");
307
- return null;
308
- }
309
- const session = sessionId(input);
310
- if (!scope.entityId || !scope.projectId || !session) {
311
- if (requested) throw new Error("self-starter start requires an exact actor, project, and host session");
312
- return null;
313
- }
314
- return startOrResumeJob({
315
- root, actorId: scope.entityId, projectId: scope.projectId, groupId: scope.groupId,
316
- taskId: scope.currentTaskId, jobId: boundedId(requested?.job_id ?? requested?.jobId, "jobId"),
317
- host: scope.host, sessionId: session, now: input.timestamp || new Date()
318
- });
319
- }
320
-
321
- export async function startChannelEvent(input, event, root, scope, catalog) {
322
- const requested = channelEventInput(input);
323
- if (!requested) return null;
324
- if (event !== "SessionStart") throw new Error("channel event claims are accepted only at SessionStart");
325
- const session = sessionId(input);
326
- if (!scope.entityId || !scope.projectId || !session) {
327
- throw new Error("channel event start requires an exact agent, project, and host session");
328
- }
329
- const workerId = `channel-worker:${createHash("sha256").update(`${scope.host}\0${session}`).digest("hex").slice(0, 24)}`;
330
- const claim = await claimChannelEvent({
331
- root, eventId: boundedId(requested.event_id ?? requested.eventId, "channelEventId"),
332
- agentId: scope.entityId, projectId: scope.projectId, groupId: scope.groupId,
333
- provider: boundedId(requested.provider, "channelProvider"), workerId,
334
- now: input.timestamp || new Date(), catalog
335
- });
336
- if (!claim.event) throw new Error("the exact channel event is unavailable in this agent lane");
337
- return claim;
338
- }
339
-
340
- export async function selfstarterScope(input, scope, root, action) {
341
- const requested = selfstarterInput(input);
342
- const hostSession = sessionId(input);
343
- const supplied = {
344
- actorId: scope.entityId, projectId: scope.projectId, groupId: scope.groupId,
345
- taskId: scope.currentTaskId, host: scope.host, sessionId: hostSession
346
- };
347
- if (requested) return { ...supplied, jobId: boundedId(requested.job_id ?? requested.jobId, "jobId") };
348
- if (!hostSession) return null;
349
- return resolveSessionJob({ root, ...supplied, action, now: input.timestamp || new Date() });
350
- }
351
-
352
- export function toolSucceeded(input) {
353
- if (input.success === false || input.is_error === true || input.tool_error) return false;
354
- if (input.tool_result && typeof input.tool_result === "object" && input.tool_result.isError === true) return false;
355
- return true;
356
- }
357
-
358
- export function toolResult(input) {
359
- return input.tool_result ?? input.tool_response ?? input.result ?? (input.tool_error ? { failed: true } : null);
360
- }
361
-
362
- function eventReceipt(input, event, scope, discriminator = "lifecycle") {
363
- const supplied = input.event_id ?? input.hook_event_id ?? input.tool_use_id ?? input.session_id;
364
- if (typeof supplied === "string" && ID_RE.test(supplied)) {
365
- return `receipt:${createHash("sha256").update(`${event}\0${supplied}\0${discriminator}`).digest("hex").slice(0, 24)}`;
366
- }
367
- const material = [event, scope.host, scope.entityId, scope.projectId, scope.currentTaskId, discriminator].join("\0");
368
- return `receipt:${createHash("sha256").update(material).digest("hex").slice(0, 24)}`;
369
- }
370
-
371
- function heartbeatReceipt(input, scope) {
372
- const at = new Date(input.timestamp || Date.now());
373
- if (!Number.isFinite(at.getTime())) throw new Error("heartbeat timestamp is invalid");
374
- const minute = at.toISOString().slice(0, 16);
375
- const material = [scope.host, scope.entityId, scope.groupId, scope.projectId, scope.currentTaskId, minute].join("\0");
376
- return `receipt:heartbeat:${createHash("sha256").update(material).digest("hex").slice(0, 20)}`;
377
- }
378
-
379
- function minimalAttentionSignal(prompt) {
380
- if (typeof prompt !== "string" || Buffer.byteLength(prompt) > 16384) return null;
381
- const rules = [
382
- { kind: "promise", re: /^(?:i promise(?: to)?|i will|ich verspreche(?:,)?|ich werde|prometo(?: que)?|voy a|jag lovar att|jag kommer att)\s+(.+)$/i, prefix: "Promise: " },
383
- { kind: "blocker", re: /^(?:blocker|blocked(?: by)?|i am blocked(?: by)?|ich bin blockiert(?: durch)?|blockiert durch|bloquead[oa](?: por)?|estoy bloquead[oa](?: por)?|blockerad(?: av)?|jag är blockerad(?: av)?)\s*[:,-]?\s*(.+)$/i, prefix: "Blocker: " }
384
- ];
385
- for (const rule of rules) {
386
- const match = prompt.trim().match(rule.re);
387
- if (!match) continue;
388
- const value = match[1].trim().replace(/\s+/g, " ").replace(/[.!?]+$/, "").slice(0, 220);
389
- if (value) return { kind: rule.kind, summary: `${rule.prefix}${value}` };
390
- }
391
- return null;
392
- }
393
-
394
- export async function captureAttentionLifecycle(input, event, root, scope, catalog) {
395
- if (!ATTENTION_WRITE_EVENTS.has(event)) return null;
396
- const explicit = input.agent_spine_attention && typeof input.agent_spine_attention === "object"
397
- && !Array.isArray(input.agent_spine_attention) ? input.agent_spine_attention : null;
398
- let proposed = explicit;
399
- let automaticHeartbeat = false;
400
- if (!proposed && event === "UserPromptSubmit" && scope.config.enabled) {
401
- proposed = minimalAttentionSignal(promptFromInput(input));
402
- if (proposed && scope.groupId) return { event: null, duplicate: false, reason: "rejected:group conversation events are never learned automatically" };
403
- }
404
- if (!proposed && event === "PostToolUse" && scope.currentTaskId) {
405
- proposed = { kind: "heartbeat", summary: "Work heartbeat recorded.", status: "active" };
406
- automaticHeartbeat = true;
407
- }
408
- if (!proposed && ["Stop", "SubagentStop"].includes(event) && scope.currentTaskId) {
409
- proposed = { kind: "heartbeat", summary: "Work heartbeat recorded.", status: "stopped" };
410
- }
411
- if (!proposed) return null;
412
- if (event === "PostToolUse" && ![input.event_id, input.hook_event_id, input.tool_use_id].some((value) => typeof value === "string" && ID_RE.test(value))) {
413
- throw new Error("PostToolUse attention requires a stable host delivery ID");
414
- }
415
- if (!scope.entityId || !scope.projectId || !scope.currentTaskId) {
416
- if (explicit) throw new Error("lifecycle attention event is missing exact actor, project, or task scope");
417
- return { event: null, duplicate: false, reason: "missing-exact-scope" };
418
- }
419
- const privacy = proposed.privacy || "private";
420
- if (event === "UserPromptSubmit" && privacy === "group") {
421
- return { event: null, duplicate: false, reason: "rejected:group conversation events are never learned automatically" };
422
- }
423
- const discriminator = proposed.id || `${proposed.kind}:${proposed.status || ""}:${proposed.summary}`;
424
- return recordAttentionEvent({
425
- root,
426
- id: boundedId(proposed.id, "attentionEventId"),
427
- kind: proposed.kind,
428
- summary: proposed.summary,
429
- status: proposed.status || null,
430
- entityId: scope.entityId,
431
- groupId: privacy === "group" ? scope.groupId : null,
432
- projectId: scope.projectId,
433
- taskId: scope.currentTaskId,
434
- privacy,
435
- dueAt: proposed.due_at ?? proposed.dueAt ?? null,
436
- receiptId: automaticHeartbeat ? heartbeatReceipt(input, scope) : eventReceipt(input, event, scope, discriminator),
437
- host: scope.host,
438
- hookEvent: event,
439
- observedAt: input.timestamp || new Date(), catalog
440
- });
441
- }
@@ -1,26 +0,0 @@
1
- const FINAL_MESSAGE_KEYS = [
2
- "last_assistant_message", "assistant_message", "final_assistant_message", "final_message", "response"
3
- ];
4
-
5
- export function resolveFinalAssistantMessage(input) {
6
- const source = input && typeof input === "object" && !Array.isArray(input) ? input : {};
7
- const candidates = [];
8
- const malformed = [];
9
- for (const key of FINAL_MESSAGE_KEYS) {
10
- if (!Object.hasOwn(source, key)) continue;
11
- if (typeof source[key] === "string") candidates.push({ key, text: source[key] });
12
- else malformed.push(key);
13
- }
14
- if (new Set(candidates.map(({ text }) => text)).size > 1) return {
15
- status: "conflict", known: false, text: "", aliases: candidates.map(({ key }) => key),
16
- reason: `final assistant message aliases conflict: ${candidates.map(({ key }) => key).join(", ")}`
17
- };
18
- if (malformed.length) return {
19
- status: "malformed", known: false, text: "", aliases: malformed,
20
- reason: `final assistant message aliases are non-string: ${malformed.join(", ")}`
21
- };
22
- if (candidates.length) return { status: "known", known: true, text: candidates[0].text,
23
- aliases: candidates.map(({ key }) => key), reason: null };
24
- return { status: "unavailable", known: false, text: "", aliases: [],
25
- reason: "final assistant message is unavailable to this hook" };
26
- }
@@ -1,27 +0,0 @@
1
- const MAX_STDIN_BYTES = 64 * 1024;
2
-
3
- export const SILENT_OVERSIZE_POST_TOOL_USE = Symbol("silent-oversize-post-tool-use");
4
- export const SILENT_OVERSIZE_POST_TOOL_USE_ARG = "--silent-oversize-post-tool-use";
5
-
6
- export async function readHookInput({ silentOversizePostToolUse = false } = {}) {
7
- const chunks = [];
8
- let bytes = 0;
9
- let oversized = false;
10
- for await (const chunk of process.stdin) {
11
- const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
12
- const remaining = Math.max(0, MAX_STDIN_BYTES - bytes);
13
- if (remaining) chunks.push(buffer.subarray(0, remaining));
14
- bytes += buffer.length;
15
- if (bytes > MAX_STDIN_BYTES) oversized = true;
16
- }
17
- if (oversized) {
18
- if (silentOversizePostToolUse) return SILENT_OVERSIZE_POST_TOOL_USE;
19
- throw new Error("hook input exceeds the 64 KiB limit");
20
- }
21
- const value = Buffer.concat(chunks, bytes).toString("utf8");
22
- const parsed = value.trim() ? JSON.parse(value) : {};
23
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
24
- throw new Error("hook input must be one JSON object");
25
- }
26
- return parsed;
27
- }