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,119 +0,0 @@
1
- import { createHmac } from "node:crypto";
2
- import {
3
- channelEventSigningPayload, ingestChannelEvent, loadChannelPolicy
4
- } from "./channel-runtime.js";
5
-
6
- const TOKEN_RE = /^\d{6,12}:[A-Za-z0-9_-]{30,80}$/;
7
-
8
- function numeric(value, field, nullable = false) {
9
- if ((value === null || value === undefined || value === "") && nullable) return null;
10
- const raw = String(value).split(":").at(-1);
11
- if (!/^-?\d{1,20}$/.test(raw)) throw new Error(field + " must resolve to an exact Telegram numeric ID");
12
- const number = Number(raw);
13
- if (!Number.isSafeInteger(number)) throw new Error(field + " exceeds the safe integer range");
14
- return number;
15
- }
16
-
17
- export function createTelegramAdapter({ root = process.cwd(), env = process.env, fetchImpl = fetch, timeoutMs = 15000 } = {}) {
18
- if (!Number.isInteger(timeoutMs) || timeoutMs < 1000 || timeoutMs > 30000) throw new Error("Telegram timeout must be 1000-30000 ms");
19
- const offsets = new Map();
20
- return {
21
- async poll() {
22
- const { policy } = await loadChannelPolicy(root);
23
- const bindings = policy.bindings.filter((item) => item.status === "active" && item.provider === "telegram"
24
- && item.capabilities.includes("receive") && item.capabilities.includes("reply") && item.outboundSecretEnv);
25
- const accounts = [...new Map(bindings.map((item) => [
26
- [item.tenantId, item.accountId, item.outboundSecretEnv].join("\0"),
27
- { tenantId: item.tenantId, accountId: item.accountId, tokenEnv: item.outboundSecretEnv }
28
- ])).values()];
29
- let ingested = 0; let ignored = 0; let rejected = 0;
30
- for (const account of accounts) {
31
- const token = env[account.tokenEnv];
32
- if (typeof token !== "string" || !TOKEN_RE.test(token)) throw new Error("Telegram credential is unavailable or malformed");
33
- const accountKey = [account.tenantId, account.accountId, account.tokenEnv].join("\0");
34
- const controller = new AbortController();
35
- const timer = setTimeout(() => controller.abort(), timeoutMs);
36
- let response;
37
- try {
38
- response = await fetchImpl("https://api.telegram.org/bot" + token + "/getUpdates", {
39
- method: "POST", headers: { "content-type": "application/json" },
40
- body: JSON.stringify({ offset: offsets.get(accountKey) || 0, timeout: 0, allowed_updates: ["message"] }),
41
- signal: controller.signal, redirect: "error"
42
- });
43
- } catch (error) {
44
- throw new Error(error.name === "AbortError" ? "Telegram poll timeout" : "Telegram poll transport failed");
45
- } finally { clearTimeout(timer); }
46
- let payload;
47
- try { payload = await response.json(); } catch { payload = null; }
48
- if (!response.ok || payload?.ok !== true || !Array.isArray(payload.result) || payload.result.length > 100) {
49
- throw new Error("Telegram poll response is invalid");
50
- }
51
- for (const update of payload.result) {
52
- if (!Number.isSafeInteger(update?.update_id)) { rejected += 1; continue; }
53
- offsets.set(accountKey, Math.max(offsets.get(accountKey) || 0, update.update_id + 1));
54
- const message = update.message;
55
- const chatId = message?.chat?.id === undefined ? null : String(message.chat.id);
56
- const threadId = message?.message_thread_id === undefined ? null : String(message.message_thread_id);
57
- const senderId = message?.from?.id === undefined ? null : String(message.from.id);
58
- const binding = bindings.find((item) => item.tenantId === account.tenantId && item.accountId === account.accountId
59
- && item.chatId === chatId && item.threadId === threadId && item.senderIds.includes(senderId));
60
- if (!binding || typeof message?.text !== "string" || !Number.isSafeInteger(message.message_id)) { ignored += 1; continue; }
61
- const observedAt = Number.isSafeInteger(message.date)
62
- ? new Date(message.date * 1000).toISOString() : new Date().toISOString();
63
- const event = {
64
- schema: "agentspine.channel-event/v1", eventId: "telegram:update:" + update.update_id,
65
- provider: "telegram", tenantId: binding.tenantId, accountId: binding.accountId,
66
- chatId: binding.chatId, threadId: binding.threadId, senderId,
67
- replyTo: String(message.message_id), observedAt,
68
- privacy: binding.groupId === null ? "private" : "group", text: message.text
69
- };
70
- const secret = env[binding.secretEnv];
71
- if (typeof secret !== "string" || Buffer.byteLength(secret) < 32) {
72
- throw new Error("Telegram ingress signing secret is unavailable or too short");
73
- }
74
- const signature = "sha256=" + createHmac("sha256", secret).update(channelEventSigningPayload(event)).digest("hex");
75
- try {
76
- const result = await ingestChannelEvent({ root, event, signature, env, now: observedAt });
77
- if (!result.duplicate) ingested += 1;
78
- } catch { rejected += 1; }
79
- }
80
- }
81
- return { accounts: accounts.length, ingested, ignored, rejected };
82
- },
83
- async send(outbox) {
84
- if (outbox.provider !== "telegram") return { ok: false, effect: "none", error: "unsupported adapter provider" };
85
- const { policy } = await loadChannelPolicy(root);
86
- const binding = policy.bindings.find((item) => item.id === outbox.bindingId && item.status === "active"
87
- && item.provider === "telegram" && item.tenantId === outbox.tenantId && item.accountId === outbox.accountId
88
- && item.chatId === outbox.chatId && item.threadId === outbox.threadId && item.capabilities.includes("reply"));
89
- if (!binding) return { ok: false, effect: "none", error: "current Telegram reply binding is unavailable" };
90
- const token = env[binding.outboundSecretEnv];
91
- if (typeof token !== "string" || !TOKEN_RE.test(token)) return { ok: false, effect: "none", error: "Telegram credential is unavailable or malformed" };
92
- const body = { chat_id: numeric(outbox.chatId, "chatId"), text: outbox.text };
93
- if (outbox.threadId !== null) body.message_thread_id = numeric(outbox.threadId, "threadId");
94
- if (outbox.replyTo !== null) body.reply_parameters = { message_id: numeric(outbox.replyTo, "replyTo") };
95
- const controller = new AbortController();
96
- const timer = setTimeout(() => controller.abort(), timeoutMs);
97
- let response;
98
- try {
99
- response = await fetchImpl("https://api.telegram.org/bot" + token + "/sendMessage", {
100
- method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body),
101
- signal: controller.signal, redirect: "error"
102
- });
103
- } catch (error) {
104
- return { ok: false, effect: "unknown", error: error.name === "AbortError" ? "Telegram send timeout" : "Telegram transport failed" };
105
- } finally { clearTimeout(timer); }
106
- let payload;
107
- try { payload = await response.json(); } catch { payload = null; }
108
- if (response.ok && payload?.ok === true && Number.isSafeInteger(payload.result?.message_id)) {
109
- return { ok: true, receipt: "telegram-message:" + payload.result.message_id };
110
- }
111
- const retryAfter = Number(payload?.parameters?.retry_after);
112
- if (response.status === 429 && Number.isFinite(retryAfter)) {
113
- return { ok: false, effect: "none", error: "Telegram rate limited", retryAfterMs: Math.min(300000, retryAfter * 1000) };
114
- }
115
- if (response.status >= 500) return { ok: false, effect: "none", error: "Telegram server rejected the send" };
116
- return { ok: false, effect: "none", error: "Telegram send was rejected" };
117
- }
118
- };
119
- }
@@ -1,100 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import { recordWorldAssertion, worldContext } from "./world-model.js";
3
- import { TIMELINE_OUTCOME_CONTRACT_SCHEMA } from "./world-knowledge.js";
4
-
5
- const CONTINUATION_SCHEMA = "agentspine.task-continuation/v1";
6
-
7
- function digest(value) {
8
- return createHash("sha256").update(value).digest("hex");
9
- }
10
-
11
- function sameStep(left, right) {
12
- return Boolean(left && right && left.id === right.id && left.summary === right.summary);
13
- }
14
-
15
- function measuredResult(event, contract) {
16
- if (event.testLabel !== contract.measurement.testLabel) return null;
17
- const expectedTotal = contract.measurement.total;
18
- if ((expectedTotal === null) !== (event.count === null)
19
- || (event.count && event.count.total !== expectedTotal)) return null;
20
- const succeeded = event.outcome === "pass"
21
- && (event.count === null || event.count.value === contract.measurement.successCount);
22
- const result = succeeded ? "passed"
23
- : event.outcome === "blocked" || event.outcome === "skipped" ? "blocked" : "failed";
24
- return { succeeded, result };
25
- }
26
-
27
- function response(status, reason = null, assertion = null) {
28
- return { schema: "agentspine.timeline-continuation-update/v1", status, reason, assertion,
29
- completionVerified: assertion?.value?.status === "completed", automaticRetry: false,
30
- authority: "context-only" };
31
- }
32
-
33
- export async function updateTimelineContinuationFromObjective({ root, scope, event, now }) {
34
- try {
35
- const context = await worldContext({ root, subjectId: scope.currentTaskId,
36
- projectId: scope.projectId, groupId: null, includePrivate: true, includeKnowledgeHistory: true,
37
- continuationTaskId: scope.currentTaskId, portalRef: scope.portalRef, threadRef: scope.threadRef,
38
- maxItems: 100, now });
39
- const continuations = context.knowledge.current.filter((item) => item.subjectId === scope.currentTaskId
40
- && item.predicate === "task.continuation" && item.value?.schema === CONTINUATION_SCHEMA);
41
- const replay = continuations.find((item) => item.status === "confirmed"
42
- && item.source.id === event.id && item.value.lastVerifiedStep?.evidenceId === event.id);
43
- if (replay) return response("duplicate", null, replay);
44
- if (continuations.length !== 1 || continuations[0].status !== "confirmed") {
45
- return response("unavailable", continuations.length ? "timeline-continuation-conflicted"
46
- : "timeline-continuation-missing");
47
- }
48
- const current = continuations[0];
49
- const contracts = context.knowledge.current.filter((item) => item.subjectId === scope.currentTaskId
50
- && item.predicate === "task.timeline-outcome-contract"
51
- && item.value?.schema === TIMELINE_OUTCOME_CONTRACT_SCHEMA);
52
- if (contracts.length !== 1 || contracts[0].status !== "confirmed") {
53
- return response("unavailable", contracts.length ? "timeline-outcome-contract-conflicted"
54
- : "timeline-outcome-contract-missing");
55
- }
56
- const contract = contracts[0];
57
- if (!sameStep(current.value.nextStep, contract.value.step)) {
58
- return response("unavailable", "timeline-outcome-contract-superseded");
59
- }
60
- const eventTime = new Date(event.at).getTime();
61
- if (eventTime < new Date(contract.recordedAt).getTime()) {
62
- return response("unavailable", "timeline-outcome-contract-postdated");
63
- }
64
- if (eventTime < new Date(current.observedAt).getTime()
65
- || eventTime < new Date(contract.observedAt).getTime()) {
66
- return response("unavailable", "timeline-outcome-event-stale");
67
- }
68
- const measured = measuredResult(event, contract.value);
69
- if (!measured) return response("unavailable", "timeline-outcome-contract-mismatch");
70
- const value = structuredClone(current.value);
71
- value.lastVerifiedStep = {
72
- id: contract.value.step.id, summary: contract.value.step.summary, result: measured.result,
73
- evidenceId: event.id, evidenceDigest: event.messageDigest,
74
- observedAt: new Date(event.at).toISOString(), sessionRef: event.sessionRef,
75
- messageRef: event.messageRef
76
- };
77
- if (measured.succeeded) {
78
- value.status = contract.value.onSuccess.status;
79
- value.nextStep = structuredClone(contract.value.onSuccess.nextStep);
80
- if (value.status === "completed" && value.openQuestions.length) {
81
- return response("unavailable", "timeline-outcome-completion-questions-open");
82
- }
83
- }
84
- const material = [scope.currentTaskId, scope.projectId, scope.portalRef, scope.threadRef,
85
- contract.id, current.id, event.id, event.messageDigest].join("\0");
86
- const recorded = await recordWorldAssertion({ root,
87
- id: `assertion:timeline-continuation-${digest(material).slice(0, 32)}`,
88
- subjectId: scope.currentTaskId, predicate: "task.continuation", value,
89
- evidenceKind: "objective-measurement", evidenceId: event.id,
90
- evidenceDigest: event.messageDigest, observedAt: new Date(event.at).toISOString(),
91
- projectId: scope.projectId, groupId: null, privacy: "private", knowledgeKind: "task-state",
92
- sessionRef: event.sessionRef, messageRef: event.messageRef,
93
- supersedes: [current.id], requireActiveSupersedes: true,
94
- reason: `The source-verified timeline result matched pre-existing contract ${contract.id}.`,
95
- portalRef: scope.portalRef, threadRef: scope.threadRef, now });
96
- return response(recorded.status === "duplicate" ? "duplicate" : "updated", null, recorded.assertion);
97
- } catch {
98
- return response("unavailable", "timeline-continuation-update-unavailable");
99
- }
100
- }
@@ -1,225 +0,0 @@
1
- import { canonicalPath } from "./paths.js";
2
- import { resolveHostSourceCatalog } from "./source-roots.js";
3
- import { authorizeSessionTimelineInvocation } from "./session-timeline.js";
4
- import {
5
- timelineInterpretationRequest, timelineInvocationRequest, timelineToolKind
6
- } from "./mcp-timeline-tools.js";
7
- import { gatewayEnvironmentContext, hookDeliveryId, hostFromInput, sessionId } from "./hook-context.js";
8
- import { blockedHookOutput } from "./hook-output.js";
9
- import { sessionTimelineBinding } from "./session-timeline-contract.js";
10
- import { resolvePrivateSessionTimelineEnrollment } from "./session-timeline-enrollment.js";
11
- import { timelineTransportDigest } from "./session-timeline-transport.js";
12
- import {
13
- crossProviderTimelineEnabled, runtimeHostForTimeline, timelineHostForRuntime, timelineHostHome
14
- } from "./session-timeline-provider.js";
15
-
16
- function plainObject(value) {
17
- return value && typeof value === "object" && !Array.isArray(value)
18
- && Object.getPrototypeOf(value) === Object.prototype;
19
- }
20
-
21
- function absent(value) { return value === undefined || value === null || value === ""; }
22
-
23
- function rawGroupClaim(input, gateway) {
24
- const nested = plainObject(input?.agent_spine_scope) ? input.agent_spine_scope : null;
25
- return !absent(process.env.AGENTSPINE_GROUP_ID) || !absent(gateway?.groupId)
26
- || !absent(input?.group_id ?? input?.groupId)
27
- || !absent(nested?.group_id ?? nested?.groupId);
28
- }
29
-
30
- function gatewayMatchesEnrollment(gateway, binding) {
31
- if (!gateway) return true;
32
- if (!absent(gateway.groupId)) return false;
33
- const fields = [
34
- ["host", "host"], ["entityId", "entityId"], ["projectId", "projectId"],
35
- ["taskId", "taskId"], ["goalId", "goalId"], ["goalStepId", "goalStepId"]
36
- ];
37
- return gateway.host === runtimeHostForTimeline(binding.host)
38
- && fields.slice(1).every(([gatewayField, bindingField]) => gateway[gatewayField] === binding[bindingField])
39
- && (gateway.portalRef ?? null) === (binding.portalRef ?? null)
40
- && (gateway.threadRef ?? null) === (binding.threadRef ?? null)
41
- && process.env.AGENTSPINE_USER_ID === binding.userId && process.env.AGENTSPINE_TENANT_ID === binding.tenantId;
42
- }
43
-
44
- function bindingScope(binding, enrollment) {
45
- return { entityId: binding.entityId, userId: binding.userId, tenantId: binding.tenantId,
46
- projectId: binding.projectId, groupId: null, currentTaskId: binding.taskId,
47
- goalId: binding.goalId, goalStepId: binding.goalStepId,
48
- portalRef: binding.portalRef ?? null, threadRef: binding.threadRef ?? null,
49
- timelineVisibility: enrollment.timelineVisibility };
50
- }
51
-
52
- function nestedScope(args) {
53
- return plainObject(args?.agent_spine_scope) ? args.agent_spine_scope : null;
54
- }
55
-
56
- function validNestedScope(args) {
57
- return args?.agent_spine_scope === undefined || args.agent_spine_scope === null || plainObject(args.agent_spine_scope);
58
- }
59
-
60
- function scopeValues(args, keys) {
61
- const nested = nestedScope(args);
62
- return keys.flatMap((key) => [args?.[key], nested?.[key]]);
63
- }
64
-
65
- function scopeClaimsMatch(args, keys, expected) {
66
- return scopeValues(args, keys).every((value) => absent(value) || value === expected);
67
- }
68
-
69
- function noScopeClaims(args, keys) {
70
- return scopeValues(args, keys).every(absent);
71
- }
72
-
73
- function matchesScopeBinding(args, binding) {
74
- return validNestedScope(args)
75
- && scopeClaimsMatch(args, ["sessionId", "session_id"], binding.sessionId)
76
- && scopeClaimsMatch(args, ["entityId", "entity_id"], binding.entityId)
77
- && scopeClaimsMatch(args, ["userId", "user_id"], binding.userId)
78
- && scopeClaimsMatch(args, ["tenantId", "tenant_id"], binding.tenantId)
79
- && scopeClaimsMatch(args, ["projectId", "project_id"], binding.projectId)
80
- && scopeClaimsMatch(args, ["taskId", "task_id", "currentTaskId", "current_task_id"], binding.taskId)
81
- && scopeClaimsMatch(args, ["goalId", "goal_id"], binding.goalId)
82
- && scopeClaimsMatch(args, ["goalStepId", "goal_step_id"], binding.goalStepId)
83
- && scopeClaimsMatch(args, ["portalRef", "portal_ref"], binding.portalRef ?? null)
84
- && scopeClaimsMatch(args, ["threadRef", "thread_ref"], binding.threadRef ?? null)
85
- && noScopeClaims(args, ["groupId", "group_id"]);
86
- }
87
-
88
- function matchesBinding(args, binding) {
89
- return matchesScopeBinding(args, binding)
90
- && noScopeClaims(args, ["accessProof", "access_proof", "invocationPermit", "invocation_permit",
91
- "transportDigest", "transport_digest", "timelineVisibility", "timeline_visibility",
92
- "enrollmentDigest", "enrollment_digest"]);
93
- }
94
-
95
- function matchesHostBinding(input, binding) {
96
- return matchesScopeBinding(input, binding)
97
- && scopeClaimsMatch(input, ["host", "provider"], binding.host)
98
- && noScopeClaims(input, ["accessProof", "access_proof", "invocationPermit", "invocation_permit",
99
- "transportDigest", "transport_digest", "enrollmentDigest", "enrollment_digest"]);
100
- }
101
-
102
- function claimedScope(input, gateway) {
103
- const claim = (keys) => {
104
- const values = scopeValues(input, keys).filter((value) => !absent(value));
105
- return values.length && values.every((value) => value === values[0]) ? values[0] : null;
106
- };
107
- return {
108
- entityId: claim(["entityId", "entity_id"]), userId: claim(["userId", "user_id"]),
109
- tenantId: claim(["tenantId", "tenant_id"]), projectId: claim(["projectId", "project_id"]),
110
- groupId: claim(["groupId", "group_id"]), currentTaskId: claim(["taskId", "task_id", "currentTaskId", "current_task_id"]),
111
- goalId: claim(["goalId", "goal_id"]), goalStepId: claim(["goalStepId", "goal_step_id"]),
112
- portalRef: gateway?.portalRef ?? null, threadRef: gateway?.threadRef ?? null
113
- };
114
- }
115
-
116
- async function matchesRoot(value, root) {
117
- if (absent(value)) return true;
118
- if (typeof value !== "string") return false;
119
- try { return await canonicalPath(value) === root; }
120
- catch { return false; }
121
- }
122
-
123
- function requestInput(tool, args) {
124
- if (tool === "index") return args.maxBytes === undefined ? {} : { maxBytes: args.maxBytes };
125
- if (args.at === undefined && args.query === undefined) return null;
126
- if (tool === "capture" && !/^timeline-event:[a-f0-9]{32}$/.test(args.eventId || "")) return null;
127
- if (args.includePriorSessions !== undefined && typeof args.includePriorSessions !== "boolean") return null;
128
- if (args.includePriorProviders !== undefined && typeof args.includePriorProviders !== "boolean") return null;
129
- if (args.includePriorProviders === true && args.includePriorSessions !== true) return null;
130
- const interpretation = tool === "capture" && args.interpretation !== undefined
131
- ? timelineInterpretationRequest(args.interpretation) : null;
132
- if (tool === "capture" && args.interpretation !== undefined && !interpretation) return null;
133
- return { ...(tool === "capture" ? { eventId: args.eventId,
134
- ...(interpretation ? { interpretation } : {}) } : {}),
135
- ...(args.at === undefined ? {} : { at: args.at }), ...(args.query === undefined ? {} : { query: args.query }),
136
- ...(args.windowSeconds === undefined ? {} : { windowSeconds: args.windowSeconds }),
137
- ...(args.includePriorSessions === undefined ? {} : { includePriorSessions: args.includePriorSessions }),
138
- ...(args.includePriorProviders === undefined ? {} : { includePriorProviders: args.includePriorProviders }) };
139
- }
140
-
141
- function denied(reason) {
142
- return { blocked: true, reason, hostOutput: blockedHookOutput("PreToolUse", reason) };
143
- }
144
-
145
- function allowed(updatedInput) {
146
- const permission = ["codex", "king"].includes(updatedInput.host) ? {} : {
147
- permissionDecision: "ask",
148
- permissionDecisionReason: "AgentSpine binds this one context-only timeline lookup to the current host session and local transport."
149
- };
150
- return {
151
- blocked: false,
152
- updatedInput,
153
- hostOutput: {
154
- hookSpecificOutput: {
155
- hookEventName: "PreToolUse",
156
- ...permission,
157
- updatedInput
158
- }
159
- }
160
- };
161
- }
162
-
163
- export async function runTimelineToolGuard(input) {
164
- try {
165
- const tool = timelineToolKind(input?.tool_name);
166
- const runtimeHost = hostFromInput(input || {});
167
- const host = timelineHostForRuntime(runtimeHost, process.env);
168
- if (input?.hook_event_name !== "PreToolUse" || !tool || !host || !plainObject(input.tool_input)) {
169
- return denied("AgentSpine session timeline requires a verified supported-host PreToolUse payload.");
170
- }
171
- const resolved = await resolveHostSourceCatalog({ host: runtimeHost, cwd: input.cwd || process.cwd(), input });
172
- const root = resolved.projectRoot;
173
- const historyHome = timelineHostHome(host) ?? resolved.hostHome;
174
- const hostSession = sessionId(input);
175
- const gateway = gatewayEnvironmentContext();
176
- if (rawGroupClaim(input, gateway)) return denied("AgentSpine session timeline is unavailable for group-scoped activity.");
177
- const provisionalBinding = sessionTimelineBinding({ host, sessionId: hostSession, scope: claimedScope(input, gateway) });
178
- const transportDigest = timelineTransportDigest({ root, binding: provisionalBinding });
179
- if (!transportDigest) {
180
- return denied("AgentSpine session timeline requires a locally configured per-session transport capability.");
181
- }
182
- const enrollment = await resolvePrivateSessionTimelineEnrollment({ root, host, sessionId: hostSession,
183
- transcriptPath: input.transcript_path ?? input.transcriptPath, hostHome: historyHome,
184
- expectedTransportDigest: transportDigest });
185
- if (enrollment.status !== "enrolled") {
186
- return denied("AgentSpine session timeline has no active private local enrollment for this host session.");
187
- }
188
- const hostClaimsMatch = host === "king"
189
- ? scopeClaimsMatch(input, ["host", "provider"], runtimeHost)
190
- : matchesHostBinding(input, enrollment.binding);
191
- if (!gatewayMatchesEnrollment(gateway, enrollment.binding) || !hostClaimsMatch
192
- || !matchesScopeBinding(input, enrollment.binding)) {
193
- return denied("AgentSpine session timeline binding does not match the authenticated gateway scope.");
194
- }
195
- if (!await matchesRoot(input.tool_input.root, root) || !matchesBinding(input.tool_input, enrollment.binding)) {
196
- return denied("AgentSpine session timeline binding does not match this host session and scope.");
197
- }
198
- const scope = bindingScope(enrollment.binding, enrollment);
199
- const requestFields = requestInput(tool, input.tool_input);
200
- if (!requestFields) return denied("AgentSpine session timeline search needs an exact time or a concrete query.");
201
- if (requestFields.includePriorProviders && !crossProviderTimelineEnabled(process.env)) {
202
- return denied("AgentSpine cross-provider timeline recall is not enabled by this local host.");
203
- }
204
- if (input.tool_input.host && input.tool_input.host !== host) return denied("Timeline provider binding mismatch.");
205
- const updatedInput = { ...requestFields, ...(["codex", "king"].includes(host) ? { host } : {}), root, sessionId: enrollment.binding.sessionId,
206
- entityId: enrollment.binding.entityId, userId: enrollment.binding.userId, tenantId: enrollment.binding.tenantId,
207
- projectId: enrollment.binding.projectId, taskId: enrollment.binding.taskId, groupId: null,
208
- goalId: enrollment.binding.goalId, goalStepId: enrollment.binding.goalStepId,
209
- portalRef: enrollment.binding.portalRef ?? null, threadRef: enrollment.binding.threadRef ?? null,
210
- timelineVisibility: enrollment.timelineVisibility, enrollmentDigest: enrollment.enrollmentDigest };
211
- const request = timelineInvocationRequest(tool, updatedInput, root);
212
- const authorization = await authorizeSessionTimelineInvocation({
213
- root, host, sessionId: hostSession, scope, hostHome: historyHome,
214
- tool, request, toolUseId: hookDeliveryId(input), transportDigest, enrollmentDigest: enrollment.enrollmentDigest
215
- });
216
- if (!authorization) return denied("AgentSpine session timeline invocation is unavailable for this bound source.");
217
- return allowed(updatedInput);
218
- } catch {
219
- return denied("AgentSpine session timeline invocation is unavailable for this bound source.");
220
- }
221
- }
222
-
223
- export function emitTimelineToolGuard(result) {
224
- process.stdout.write(`${JSON.stringify(result.hostOutput)}\n`);
225
- }