@ebowwa/coder 0.7.63 → 0.7.64

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 (341) hide show
  1. package/dist/core/__tests__/permissions.test.d.ts +12 -0
  2. package/dist/core/__tests__/permissions.test.d.ts.map +1 -0
  3. package/dist/core/__tests__/permissions.test.js +851 -0
  4. package/dist/core/agent-loop/__tests__/compaction.test.d.ts +5 -0
  5. package/dist/core/agent-loop/__tests__/compaction.test.d.ts.map +1 -0
  6. package/dist/core/agent-loop/__tests__/compaction.test.js +209 -0
  7. package/dist/core/agent-loop/__tests__/formatters.test.d.ts +5 -0
  8. package/dist/core/agent-loop/__tests__/formatters.test.d.ts.map +1 -0
  9. package/dist/core/agent-loop/__tests__/formatters.test.js +195 -0
  10. package/dist/core/agent-loop/__tests__/index.test.d.ts +5 -0
  11. package/dist/core/agent-loop/__tests__/index.test.d.ts.map +1 -0
  12. package/dist/core/agent-loop/__tests__/index.test.js +121 -0
  13. package/dist/core/agent-loop/__tests__/loop-state.test.d.ts +5 -0
  14. package/dist/core/agent-loop/__tests__/loop-state.test.d.ts.map +1 -0
  15. package/dist/core/agent-loop/__tests__/loop-state.test.js +340 -0
  16. package/dist/core/agent-loop/__tests__/message-builder.test.d.ts +5 -0
  17. package/dist/core/agent-loop/__tests__/message-builder.test.d.ts.map +1 -0
  18. package/dist/core/agent-loop/__tests__/message-builder.test.js +178 -0
  19. package/dist/core/agent-loop/__tests__/tool-executor.test.d.ts +5 -0
  20. package/dist/core/agent-loop/__tests__/tool-executor.test.d.ts.map +1 -0
  21. package/dist/core/agent-loop/__tests__/tool-executor.test.js +331 -0
  22. package/dist/core/agent-loop/compaction.d.ts +39 -0
  23. package/dist/core/agent-loop/compaction.d.ts.map +1 -0
  24. package/dist/core/agent-loop/compaction.js +51 -0
  25. package/dist/core/agent-loop/formatters.d.ts +21 -0
  26. package/dist/core/agent-loop/formatters.d.ts.map +1 -0
  27. package/dist/core/agent-loop/formatters.js +42 -0
  28. package/dist/core/agent-loop/index.d.ts +25 -0
  29. package/dist/core/agent-loop/index.d.ts.map +1 -0
  30. package/dist/core/agent-loop/index.js +83 -0
  31. package/dist/core/agent-loop/loop-state.d.ts +74 -0
  32. package/dist/core/agent-loop/loop-state.d.ts.map +1 -0
  33. package/dist/core/agent-loop/loop-state.js +147 -0
  34. package/dist/core/agent-loop/message-builder.d.ts +13 -0
  35. package/dist/core/agent-loop/message-builder.d.ts.map +1 -0
  36. package/dist/core/agent-loop/message-builder.js +49 -0
  37. package/dist/core/agent-loop/tool-executor.d.ts +23 -0
  38. package/dist/core/agent-loop/tool-executor.d.ts.map +1 -0
  39. package/dist/core/agent-loop/tool-executor.js +152 -0
  40. package/dist/core/agent-loop/turn-executor.d.ts +57 -0
  41. package/dist/core/agent-loop/turn-executor.d.ts.map +1 -0
  42. package/dist/core/agent-loop/turn-executor.js +124 -0
  43. package/dist/core/agent-loop/types.d.ts +141 -0
  44. package/dist/core/agent-loop/types.d.ts.map +1 -0
  45. package/dist/core/agent-loop/types.js +4 -0
  46. package/dist/core/agent-loop.d.ts +17 -0
  47. package/dist/core/agent-loop.d.ts.map +1 -0
  48. package/dist/core/agent-loop.js +16 -0
  49. package/dist/core/api-client-impl.d.ts +62 -0
  50. package/dist/core/api-client-impl.d.ts.map +1 -0
  51. package/dist/core/api-client-impl.js +479 -0
  52. package/dist/core/api-client.d.ts +6 -0
  53. package/dist/core/api-client.d.ts.map +1 -0
  54. package/dist/core/api-client.js +5 -0
  55. package/dist/core/checkpoints.d.ts +128 -0
  56. package/dist/core/checkpoints.d.ts.map +1 -0
  57. package/dist/core/checkpoints.js +438 -0
  58. package/dist/core/claude-md.d.ts +71 -0
  59. package/dist/core/claude-md.d.ts.map +1 -0
  60. package/dist/core/claude-md.js +198 -0
  61. package/dist/core/cognitive-security/hooks.d.ts +138 -0
  62. package/dist/core/cognitive-security/hooks.d.ts.map +1 -0
  63. package/dist/core/cognitive-security/hooks.js +389 -0
  64. package/dist/core/cognitive-security/index.d.ts +751 -0
  65. package/dist/core/cognitive-security/index.d.ts.map +1 -0
  66. package/dist/core/cognitive-security/index.js +1123 -0
  67. package/dist/core/cognitive-security/middleware.d.ts +136 -0
  68. package/dist/core/cognitive-security/middleware.d.ts.map +1 -0
  69. package/dist/core/cognitive-security/middleware.js +376 -0
  70. package/dist/core/config-loader.d.ts +127 -0
  71. package/dist/core/config-loader.d.ts.map +1 -0
  72. package/dist/core/config-loader.js +219 -0
  73. package/dist/core/context-compaction.d.ts +87 -0
  74. package/dist/core/context-compaction.d.ts.map +1 -0
  75. package/dist/core/context-compaction.js +428 -0
  76. package/dist/core/git-status.d.ts +25 -0
  77. package/dist/core/git-status.d.ts.map +1 -0
  78. package/dist/core/git-status.js +204 -0
  79. package/dist/core/image.d.ts +69 -0
  80. package/dist/core/image.d.ts.map +1 -0
  81. package/dist/core/image.js +290 -0
  82. package/dist/core/image.test.d.ts +2 -0
  83. package/dist/core/image.test.d.ts.map +1 -0
  84. package/dist/core/image.test.js +149 -0
  85. package/dist/core/models.d.ts +123 -0
  86. package/dist/core/models.d.ts.map +1 -0
  87. package/dist/core/models.js +325 -0
  88. package/dist/core/permissions.d.ts +81 -0
  89. package/dist/core/permissions.d.ts.map +1 -0
  90. package/dist/core/permissions.js +327 -0
  91. package/dist/core/retry.d.ts +25 -0
  92. package/dist/core/retry.d.ts.map +1 -0
  93. package/dist/core/retry.js +121 -0
  94. package/dist/core/session-store.d.ts +9 -0
  95. package/dist/core/session-store.d.ts.map +1 -0
  96. package/dist/core/session-store.js +10 -0
  97. package/dist/core/sessions/export.d.ts +47 -0
  98. package/dist/core/sessions/export.d.ts.map +1 -0
  99. package/dist/core/sessions/export.js +256 -0
  100. package/dist/core/sessions/index.d.ts +132 -0
  101. package/dist/core/sessions/index.d.ts.map +1 -0
  102. package/dist/core/sessions/index.js +442 -0
  103. package/dist/core/sessions/metadata.d.ts +77 -0
  104. package/dist/core/sessions/metadata.d.ts.map +1 -0
  105. package/dist/core/sessions/metadata.js +233 -0
  106. package/dist/core/sessions/persistence.d.ts +72 -0
  107. package/dist/core/sessions/persistence.d.ts.map +1 -0
  108. package/dist/core/sessions/persistence.js +201 -0
  109. package/dist/core/sessions/types.d.ts +110 -0
  110. package/dist/core/sessions/types.d.ts.map +1 -0
  111. package/dist/core/sessions/types.js +4 -0
  112. package/dist/core/stream-highlighter.d.ts +18 -0
  113. package/dist/core/stream-highlighter.d.ts.map +1 -0
  114. package/dist/core/stream-highlighter.js +916 -0
  115. package/dist/core/system-reminders.d.ts +89 -0
  116. package/dist/core/system-reminders.d.ts.map +1 -0
  117. package/dist/core/system-reminders.js +285 -0
  118. package/dist/ecosystem/hooks/__tests__/index.test.d.ts +5 -0
  119. package/dist/ecosystem/hooks/__tests__/index.test.d.ts.map +1 -0
  120. package/dist/ecosystem/hooks/__tests__/index.test.js +458 -0
  121. package/dist/ecosystem/hooks/index.d.ts +59 -0
  122. package/dist/ecosystem/hooks/index.d.ts.map +1 -0
  123. package/dist/ecosystem/hooks/index.js +294 -0
  124. package/dist/ecosystem/hooks/prompt-evaluator.d.ts +32 -0
  125. package/dist/ecosystem/hooks/prompt-evaluator.d.ts.map +1 -0
  126. package/dist/ecosystem/hooks/prompt-evaluator.js +229 -0
  127. package/dist/ecosystem/skills/index.d.ts +55 -0
  128. package/dist/ecosystem/skills/index.d.ts.map +1 -0
  129. package/dist/ecosystem/skills/index.js +258 -0
  130. package/dist/ecosystem/tools/__tests__/index.test.d.ts +7 -0
  131. package/dist/ecosystem/tools/__tests__/index.test.d.ts.map +1 -0
  132. package/dist/ecosystem/tools/__tests__/index.test.js +856 -0
  133. package/dist/ecosystem/tools/index.d.ts +24 -0
  134. package/dist/ecosystem/tools/index.d.ts.map +1 -0
  135. package/dist/ecosystem/tools/index.js +1709 -0
  136. package/dist/index.d.ts +24 -0
  137. package/dist/index.d.ts.map +1 -0
  138. package/dist/index.js +32 -52192
  139. package/dist/interfaces/mcp/client.d.ts +40 -0
  140. package/dist/interfaces/mcp/client.d.ts.map +1 -0
  141. package/dist/interfaces/mcp/client.js +309 -0
  142. package/dist/interfaces/ui/index.d.ts +36 -0
  143. package/dist/interfaces/ui/index.d.ts.map +1 -0
  144. package/dist/interfaces/ui/index.js +61 -0
  145. package/dist/interfaces/ui/spinner.d.ts +140 -0
  146. package/dist/interfaces/ui/spinner.d.ts.map +1 -0
  147. package/dist/interfaces/ui/spinner.js +342 -0
  148. package/dist/interfaces/ui/terminal/cli/index.d.ts +12 -0
  149. package/dist/interfaces/ui/terminal/cli/index.d.ts.map +1 -0
  150. package/dist/interfaces/ui/terminal/cli/index.js +159 -52768
  151. package/dist/interfaces/ui/terminal/shared/args.d.ts +39 -0
  152. package/dist/interfaces/ui/terminal/shared/args.d.ts.map +1 -0
  153. package/dist/interfaces/ui/terminal/shared/args.js +176 -0
  154. package/dist/interfaces/ui/terminal/shared/index.d.ts +11 -0
  155. package/dist/interfaces/ui/terminal/shared/index.d.ts.map +1 -0
  156. package/dist/interfaces/ui/terminal/shared/index.js +16 -0
  157. package/dist/interfaces/ui/terminal/shared/loading-state.d.ts +124 -0
  158. package/dist/interfaces/ui/terminal/shared/loading-state.d.ts.map +1 -0
  159. package/dist/interfaces/ui/terminal/shared/loading-state.js +246 -0
  160. package/dist/interfaces/ui/terminal/shared/query.d.ts +22 -0
  161. package/dist/interfaces/ui/terminal/shared/query.d.ts.map +1 -0
  162. package/dist/interfaces/ui/terminal/shared/query.js +100 -0
  163. package/dist/interfaces/ui/terminal/shared/setup.d.ts +33 -0
  164. package/dist/interfaces/ui/terminal/shared/setup.d.ts.map +1 -0
  165. package/dist/interfaces/ui/terminal/shared/setup.js +226 -0
  166. package/dist/interfaces/ui/terminal/shared/status-line.d.ts +117 -0
  167. package/dist/interfaces/ui/terminal/shared/status-line.d.ts.map +1 -0
  168. package/dist/interfaces/ui/terminal/shared/status-line.js +267 -0
  169. package/dist/interfaces/ui/terminal/shared/system-prompt.d.ts +38 -0
  170. package/dist/interfaces/ui/terminal/shared/system-prompt.d.ts.map +1 -0
  171. package/dist/interfaces/ui/terminal/shared/system-prompt.js +102 -0
  172. package/dist/interfaces/ui/terminal/tui/HelpPanel.d.ts +39 -0
  173. package/dist/interfaces/ui/terminal/tui/HelpPanel.d.ts.map +1 -0
  174. package/dist/interfaces/ui/terminal/tui/HelpPanel.js +215 -0
  175. package/dist/interfaces/ui/terminal/tui/InputContext.d.ts +91 -0
  176. package/dist/interfaces/ui/terminal/tui/InputContext.d.ts.map +1 -0
  177. package/dist/interfaces/ui/terminal/tui/InputContext.js +154 -0
  178. package/dist/interfaces/ui/terminal/tui/InputField.d.ts +18 -0
  179. package/dist/interfaces/ui/terminal/tui/InputField.d.ts.map +1 -0
  180. package/dist/interfaces/ui/terminal/tui/InputField.js +41 -0
  181. package/dist/interfaces/ui/terminal/tui/InteractiveTUI.d.ts +16 -0
  182. package/dist/interfaces/ui/terminal/tui/InteractiveTUI.d.ts.map +1 -0
  183. package/dist/interfaces/ui/terminal/tui/InteractiveTUI.js +451 -0
  184. package/dist/interfaces/ui/terminal/tui/MessageArea.d.ts +10 -0
  185. package/dist/interfaces/ui/terminal/tui/MessageArea.d.ts.map +1 -0
  186. package/dist/interfaces/ui/terminal/tui/MessageArea.js +91 -0
  187. package/dist/interfaces/ui/terminal/tui/MessageStore.d.ts +48 -0
  188. package/dist/interfaces/ui/terminal/tui/MessageStore.d.ts.map +1 -0
  189. package/dist/interfaces/ui/terminal/tui/MessageStore.js +151 -0
  190. package/dist/interfaces/ui/terminal/tui/StatusBar.d.ts +9 -0
  191. package/dist/interfaces/ui/terminal/tui/StatusBar.d.ts.map +1 -0
  192. package/dist/interfaces/ui/terminal/tui/StatusBar.js +36 -0
  193. package/dist/interfaces/ui/terminal/tui/commands.d.ts +21 -0
  194. package/dist/interfaces/ui/terminal/tui/commands.d.ts.map +1 -0
  195. package/dist/interfaces/ui/terminal/tui/commands.js +359 -0
  196. package/dist/interfaces/ui/terminal/tui/components/InteractiveElements.d.ts +115 -0
  197. package/dist/interfaces/ui/terminal/tui/components/InteractiveElements.d.ts.map +1 -0
  198. package/dist/interfaces/ui/terminal/tui/components/InteractiveElements.js +306 -0
  199. package/dist/interfaces/ui/terminal/tui/components/MultilineInput.d.ts +92 -0
  200. package/dist/interfaces/ui/terminal/tui/components/MultilineInput.d.ts.map +1 -0
  201. package/dist/interfaces/ui/terminal/tui/components/MultilineInput.js +399 -0
  202. package/dist/interfaces/ui/terminal/tui/components/PaneManager.d.ts +59 -0
  203. package/dist/interfaces/ui/terminal/tui/components/PaneManager.d.ts.map +1 -0
  204. package/dist/interfaces/ui/terminal/tui/components/PaneManager.js +139 -0
  205. package/dist/interfaces/ui/terminal/tui/components/Sidebar.d.ts +68 -0
  206. package/dist/interfaces/ui/terminal/tui/components/Sidebar.d.ts.map +1 -0
  207. package/dist/interfaces/ui/terminal/tui/components/Sidebar.js +340 -0
  208. package/dist/interfaces/ui/terminal/tui/components/index.d.ts +23 -0
  209. package/dist/interfaces/ui/terminal/tui/components/index.d.ts.map +1 -0
  210. package/dist/interfaces/ui/terminal/tui/components/index.js +51 -0
  211. package/dist/interfaces/ui/terminal/tui/console.d.ts +20 -0
  212. package/dist/interfaces/ui/terminal/tui/console.d.ts.map +1 -0
  213. package/dist/interfaces/ui/terminal/tui/console.js +46 -0
  214. package/dist/interfaces/ui/terminal/tui/index.d.ts +20 -0
  215. package/dist/interfaces/ui/terminal/tui/index.d.ts.map +1 -0
  216. package/dist/interfaces/ui/terminal/tui/index.js +28 -0
  217. package/dist/interfaces/ui/terminal/tui/run.d.ts +13 -0
  218. package/dist/interfaces/ui/terminal/tui/run.d.ts.map +1 -0
  219. package/dist/interfaces/ui/terminal/tui/run.js +31 -0
  220. package/dist/interfaces/ui/terminal/tui/spinner.d.ts +44 -0
  221. package/dist/interfaces/ui/terminal/tui/spinner.d.ts.map +1 -0
  222. package/dist/interfaces/ui/terminal/tui/spinner.js +59 -0
  223. package/dist/interfaces/ui/terminal/tui/tui-app.d.ts +39 -0
  224. package/dist/interfaces/ui/terminal/tui/tui-app.d.ts.map +1 -0
  225. package/dist/interfaces/ui/terminal/tui/tui-app.js +198 -0
  226. package/dist/interfaces/ui/terminal/tui/tui-footer.d.ts +167 -0
  227. package/dist/interfaces/ui/terminal/tui/tui-footer.d.ts.map +1 -0
  228. package/dist/interfaces/ui/terminal/tui/tui-footer.js +330 -0
  229. package/dist/interfaces/ui/terminal/tui/types.d.ts +165 -0
  230. package/dist/interfaces/ui/terminal/tui/types.d.ts.map +1 -0
  231. package/dist/interfaces/ui/terminal/tui/types.js +5 -0
  232. package/dist/interfaces/ui/terminal/tui/useInputHandler.d.ts +23 -0
  233. package/dist/interfaces/ui/terminal/tui/useInputHandler.d.ts.map +1 -0
  234. package/dist/interfaces/ui/terminal/tui/useInputHandler.js +72 -0
  235. package/dist/interfaces/ui/terminal/tui/useNativeInput.d.ts +90 -0
  236. package/dist/interfaces/ui/terminal/tui/useNativeInput.d.ts.map +1 -0
  237. package/dist/interfaces/ui/terminal/tui/useNativeInput.js +188 -0
  238. package/dist/native/index.d.ts +480 -0
  239. package/dist/native/index.d.ts.map +1 -0
  240. package/dist/native/index.js +1625 -0
  241. package/dist/teammates/index.d.ts +161 -0
  242. package/dist/teammates/index.d.ts.map +1 -0
  243. package/dist/teammates/index.js +827 -0
  244. package/dist/types/index.d.ts +482 -0
  245. package/dist/types/index.d.ts.map +1 -0
  246. package/dist/types/index.js +52 -0
  247. package/package.json +4 -2
  248. package/packages/src/core/__tests__/permissions.test.ts +1091 -0
  249. package/packages/src/core/agent-loop/__tests__/compaction.test.ts +280 -0
  250. package/packages/src/core/agent-loop/__tests__/formatters.test.ts +234 -0
  251. package/packages/src/core/agent-loop/__tests__/index.test.ts +162 -0
  252. package/packages/src/core/agent-loop/__tests__/loop-state.test.ts +413 -0
  253. package/packages/src/core/agent-loop/__tests__/message-builder.test.ts +229 -0
  254. package/packages/src/core/agent-loop/__tests__/tool-executor.test.ts +457 -0
  255. package/packages/src/core/agent-loop/compaction.ts +88 -0
  256. package/packages/src/core/agent-loop/formatters.ts +50 -0
  257. package/packages/src/core/agent-loop/index.ts +135 -0
  258. package/packages/src/core/agent-loop/loop-state.ts +187 -0
  259. package/packages/src/core/agent-loop/message-builder.ts +62 -0
  260. package/packages/src/core/agent-loop/tool-executor.ts +211 -0
  261. package/packages/src/core/agent-loop/turn-executor.ts +222 -0
  262. package/packages/src/core/agent-loop/types.ts +148 -0
  263. package/packages/src/core/agent-loop.ts +18 -0
  264. package/packages/src/core/api-client-impl.ts +619 -0
  265. package/packages/src/core/api-client.ts +6 -0
  266. package/packages/src/core/checkpoints.ts +606 -0
  267. package/packages/src/core/claude-md.ts +272 -0
  268. package/packages/src/core/cognitive-security/hooks.ts +590 -0
  269. package/packages/src/core/cognitive-security/index.ts +2041 -0
  270. package/packages/src/core/cognitive-security/middleware.ts +536 -0
  271. package/packages/src/core/config-loader.ts +324 -0
  272. package/packages/src/core/context-compaction.ts +578 -0
  273. package/packages/src/core/git-status.ts +262 -0
  274. package/packages/src/core/image.test.ts +180 -0
  275. package/packages/src/core/image.ts +350 -0
  276. package/packages/src/core/lmdb.db +0 -0
  277. package/packages/src/core/lmdb.db-lock +0 -0
  278. package/packages/src/core/models.ts +430 -0
  279. package/packages/src/core/normalizers/todo +4 -0
  280. package/packages/src/core/permissions.ts +431 -0
  281. package/packages/src/core/retry.ts +170 -0
  282. package/packages/src/core/session-store.ts +36 -0
  283. package/packages/src/core/sessions/export.ts +329 -0
  284. package/packages/src/core/sessions/index.ts +587 -0
  285. package/packages/src/core/sessions/metadata.ts +309 -0
  286. package/packages/src/core/sessions/persistence.ts +244 -0
  287. package/packages/src/core/sessions/types.ts +169 -0
  288. package/packages/src/core/stream-highlighter.ts +1123 -0
  289. package/packages/src/core/system-reminders.ts +402 -0
  290. package/packages/src/core/todo +8 -0
  291. package/packages/src/ecosystem/hooks/__tests__/index.test.ts +561 -0
  292. package/packages/src/ecosystem/hooks/index.ts +341 -0
  293. package/packages/src/ecosystem/hooks/prompt-evaluator.ts +300 -0
  294. package/packages/src/ecosystem/skills/index.ts +295 -0
  295. package/packages/src/ecosystem/tools/__tests__/index.test.ts +1335 -0
  296. package/packages/src/ecosystem/tools/index.ts +1877 -0
  297. package/packages/src/index.ts +120 -0
  298. package/packages/src/interfaces/mcp/client.ts +389 -0
  299. package/packages/src/interfaces/ui/Screenshot 2026-03-02 at 9.23.10/342/200/257PM.png +0 -0
  300. package/packages/src/interfaces/ui/Screenshot 2026-03-03 at 10.55.11/342/200/257AM.png +0 -0
  301. package/packages/src/interfaces/ui/index.ts +161 -0
  302. package/packages/src/interfaces/ui/lmdb.db +0 -0
  303. package/packages/src/interfaces/ui/lmdb.db-lock +0 -0
  304. package/packages/src/interfaces/ui/spinner.ts +451 -0
  305. package/packages/src/interfaces/ui/terminal/cli/index.ts +228 -0
  306. package/packages/src/interfaces/ui/terminal/lmdb.db +0 -0
  307. package/packages/src/interfaces/ui/terminal/lmdb.db-lock +0 -0
  308. package/packages/src/interfaces/ui/terminal/shared/args.ts +222 -0
  309. package/packages/src/interfaces/ui/terminal/shared/index.ts +71 -0
  310. package/packages/src/interfaces/ui/terminal/shared/loading-state.ts +322 -0
  311. package/packages/src/interfaces/ui/terminal/shared/query.ts +146 -0
  312. package/packages/src/interfaces/ui/terminal/shared/setup.ts +295 -0
  313. package/packages/src/interfaces/ui/terminal/shared/status-line.ts +358 -0
  314. package/packages/src/interfaces/ui/terminal/shared/system-prompt.ts +146 -0
  315. package/packages/src/interfaces/ui/terminal/tui/HelpPanel.tsx +262 -0
  316. package/packages/src/interfaces/ui/terminal/tui/InputContext.tsx +232 -0
  317. package/packages/src/interfaces/ui/terminal/tui/InputField.tsx +62 -0
  318. package/packages/src/interfaces/ui/terminal/tui/InteractiveTUI.tsx +537 -0
  319. package/packages/src/interfaces/ui/terminal/tui/MessageArea.tsx +107 -0
  320. package/packages/src/interfaces/ui/terminal/tui/MessageStore.tsx +240 -0
  321. package/packages/src/interfaces/ui/terminal/tui/StatusBar.tsx +54 -0
  322. package/packages/src/interfaces/ui/terminal/tui/commands.ts +438 -0
  323. package/packages/src/interfaces/ui/terminal/tui/components/InteractiveElements.tsx +584 -0
  324. package/packages/src/interfaces/ui/terminal/tui/components/MultilineInput.tsx +614 -0
  325. package/packages/src/interfaces/ui/terminal/tui/components/PaneManager.tsx +333 -0
  326. package/packages/src/interfaces/ui/terminal/tui/components/Sidebar.tsx +604 -0
  327. package/packages/src/interfaces/ui/terminal/tui/components/index.ts +118 -0
  328. package/packages/src/interfaces/ui/terminal/tui/console.ts +49 -0
  329. package/packages/src/interfaces/ui/terminal/tui/index.ts +90 -0
  330. package/packages/src/interfaces/ui/terminal/tui/run.tsx +42 -0
  331. package/packages/src/interfaces/ui/terminal/tui/spinner.ts +69 -0
  332. package/packages/src/interfaces/ui/terminal/tui/tui-app.tsx +390 -0
  333. package/packages/src/interfaces/ui/terminal/tui/tui-footer.ts +422 -0
  334. package/packages/src/interfaces/ui/terminal/tui/types.ts +186 -0
  335. package/packages/src/interfaces/ui/terminal/tui/useInputHandler.ts +104 -0
  336. package/packages/src/interfaces/ui/terminal/tui/useNativeInput.ts +239 -0
  337. package/packages/src/lmdb.db +0 -0
  338. package/packages/src/lmdb.db-lock +0 -0
  339. package/packages/src/native/index.ts +2345 -0
  340. package/packages/src/teammates/index.ts +982 -0
  341. package/packages/src/types/index.ts +722 -0
@@ -0,0 +1,1123 @@
1
+ /**
2
+ * Cognitive Security - Intent Module
3
+ *
4
+ * TypeScript bindings for the Rust cognitive security module.
5
+ * Provides intent preservation, alignment scoring, and corruption detection.
6
+ */
7
+ // ===== Native Bindings =====
8
+ import { native } from "../../native/index.js";
9
+ let nativeModule = null;
10
+ async function getNative() {
11
+ if (!nativeModule) {
12
+ // Use the already-loaded native module from src/native/index.ts
13
+ // which properly maps all functions including cognitive security
14
+ nativeModule = native;
15
+ }
16
+ return nativeModule;
17
+ }
18
+ // ===== Key Management =====
19
+ /**
20
+ * Generate a new Ed25519 keypair for signing intents
21
+ */
22
+ export async function generateKeypair() {
23
+ const native = await getNative();
24
+ return native.cs_generate_keypair();
25
+ }
26
+ // ===== Signing & Verification =====
27
+ /**
28
+ * Sign an agent intent with a private key
29
+ */
30
+ export async function signIntent(intent, privateKey) {
31
+ const native = await getNative();
32
+ return native.cs_sign_intent(intent, privateKey);
33
+ }
34
+ /**
35
+ * Verify an intent's signature
36
+ */
37
+ export async function verifyIntent(intent) {
38
+ const native = await getNative();
39
+ return native.cs_verify_intent(intent);
40
+ }
41
+ /**
42
+ * Hash an intent for comparison
43
+ */
44
+ export async function hashIntent(intent) {
45
+ const native = await getNative();
46
+ return native.cs_hash_intent(intent);
47
+ }
48
+ /**
49
+ * Check if two intents are equivalent (ignoring signatures)
50
+ */
51
+ export async function intentsEquivalent(intent1, intent2) {
52
+ const native = await getNative();
53
+ return native.cs_intents_equivalent(intent1, intent2);
54
+ }
55
+ // ===== Alignment Scoring =====
56
+ /**
57
+ * Score how well an action aligns with an intent
58
+ */
59
+ export async function scoreAlignment(action, intent) {
60
+ const native = await getNative();
61
+ return native.cs_score_alignment(action, intent);
62
+ }
63
+ /**
64
+ * Batch score multiple actions against an intent
65
+ */
66
+ export async function batchScoreAlignment(actions, intent) {
67
+ const native = await getNative();
68
+ return native.cs_batch_score_alignment(actions, intent);
69
+ }
70
+ /**
71
+ * Check if any action in a sequence would violate intent
72
+ */
73
+ export async function checkSequenceViolations(actions, intent) {
74
+ const native = await getNative();
75
+ return native.cs_check_sequence_violations(actions, intent);
76
+ }
77
+ // ===== Intent Management =====
78
+ /**
79
+ * Load intent from a JSON file
80
+ */
81
+ export async function loadIntent(path) {
82
+ const native = await getNative();
83
+ return native.cs_load_intent(path);
84
+ }
85
+ /**
86
+ * Save intent to a JSON file
87
+ */
88
+ export async function saveIntent(intent, path) {
89
+ const native = await getNative();
90
+ return native.cs_save_intent(intent, path);
91
+ }
92
+ /**
93
+ * Parse intent from JSON string
94
+ */
95
+ export async function parseIntent(json) {
96
+ const native = await getNative();
97
+ return native.cs_parse_intent(json);
98
+ }
99
+ /**
100
+ * Serialize intent to JSON string
101
+ */
102
+ export async function serializeIntent(intent) {
103
+ const native = await getNative();
104
+ return native.cs_serialize_intent(intent);
105
+ }
106
+ /**
107
+ * Validate intent structure
108
+ */
109
+ export async function validateIntent(intent) {
110
+ const native = await getNative();
111
+ return native.cs_validate_intent(intent);
112
+ }
113
+ /**
114
+ * Create a default data collector intent
115
+ */
116
+ export async function createDataCollectorIntent(name, description) {
117
+ const native = await getNative();
118
+ return native.cs_create_data_collector_intent(name, description);
119
+ }
120
+ /**
121
+ * Merge two intents (child overrides parent)
122
+ */
123
+ export async function mergeIntents(base, override) {
124
+ const native = await getNative();
125
+ return native.cs_merge_intents(base, override);
126
+ }
127
+ // ===== Corruption Detection =====
128
+ /**
129
+ * Analyze behavior for signs of intent corruption
130
+ */
131
+ export async function analyzeCorruption(snapshot, intent) {
132
+ const native = await getNative();
133
+ return native.cs_analyze_corruption(snapshot, intent);
134
+ }
135
+ /**
136
+ * Detect behavioral drift between two snapshots
137
+ */
138
+ export async function detectDrift(baseline, current) {
139
+ const native = await getNative();
140
+ return native.cs_detect_drift(baseline, current);
141
+ }
142
+ /**
143
+ * Create an empty behavior snapshot
144
+ */
145
+ export async function createEmptySnapshot() {
146
+ const native = await getNative();
147
+ return native.cs_create_empty_snapshot();
148
+ }
149
+ /**
150
+ * Update a snapshot with a new action result
151
+ */
152
+ export async function updateSnapshot(snapshot, action, alignment) {
153
+ const native = await getNative();
154
+ return native.cs_update_snapshot(snapshot, action, alignment);
155
+ }
156
+ // ===== Action Classification =====
157
+ /**
158
+ * Classify an operation into an action type
159
+ */
160
+ export async function classifyOperation(operation, domain, target, reasoning) {
161
+ const native = await getNative();
162
+ return native.classify_operation(operation, domain, target, reasoning);
163
+ }
164
+ /**
165
+ * Get all supported action types
166
+ */
167
+ export async function getActionTypes() {
168
+ const native = await getNative();
169
+ return native.get_action_types();
170
+ }
171
+ /**
172
+ * Get risk levels for all action types
173
+ */
174
+ export async function getActionRiskLevels() {
175
+ const native = await getNative();
176
+ return native.get_action_risk_levels();
177
+ }
178
+ // ===== Action Validation =====
179
+ /**
180
+ * Create a deny-all policy
181
+ */
182
+ export async function createDenyAllPolicy() {
183
+ const native = await getNative();
184
+ return native.create_deny_all_policy();
185
+ }
186
+ /**
187
+ * Create an observe-only policy
188
+ */
189
+ export async function createObserveOnlyPolicy() {
190
+ const native = await getNative();
191
+ return native.create_observe_only_policy();
192
+ }
193
+ /**
194
+ * Create a transfer approval policy
195
+ */
196
+ export async function createTransferApprovalPolicy() {
197
+ const native = await getNative();
198
+ return native.create_transfer_approval_policy();
199
+ }
200
+ // ===== Domain Configs =====
201
+ /**
202
+ * Create file domain configuration
203
+ */
204
+ export async function createFileDomainConfig() {
205
+ const native = await getNative();
206
+ return native.create_file_domain_config();
207
+ }
208
+ /**
209
+ * Create network domain configuration
210
+ */
211
+ export async function createNetworkDomainConfig() {
212
+ const native = await getNative();
213
+ return native.create_network_domain_config();
214
+ }
215
+ /**
216
+ * Create shell domain configuration
217
+ */
218
+ export async function createShellDomainConfig() {
219
+ const native = await getNative();
220
+ return native.create_shell_domain_config();
221
+ }
222
+ // ===== Flow Classification =====
223
+ /**
224
+ * Classify data based on content and source
225
+ */
226
+ export async function classifyData(content, source, tags) {
227
+ const native = await getNative();
228
+ return native.classify_data(content, source, tags);
229
+ }
230
+ /**
231
+ * Check if content contains sensitive data
232
+ */
233
+ export async function containsSensitiveData(content) {
234
+ const native = await getNative();
235
+ return native.contains_sensitive_data(content);
236
+ }
237
+ /**
238
+ * Redact sensitive content
239
+ */
240
+ export async function redactSensitive(content, replacement) {
241
+ const native = await getNative();
242
+ return native.redact_sensitive(content, replacement ?? null);
243
+ }
244
+ /**
245
+ * Get sensitivity levels
246
+ */
247
+ export async function getSensitivityLevels() {
248
+ const native = await getNative();
249
+ return native.get_sensitivity_levels();
250
+ }
251
+ /**
252
+ * Get data categories
253
+ */
254
+ export async function getDataCategories() {
255
+ const native = await getNative();
256
+ return native.get_data_categories();
257
+ }
258
+ // ===== Flow Policy Engine =====
259
+ /**
260
+ * Create a flow policy engine
261
+ */
262
+ export async function createFlowPolicyEngine() {
263
+ const native = await getNative();
264
+ if (typeof native.create_flow_policy_engine === 'function') {
265
+ return native.create_flow_policy_engine();
266
+ }
267
+ // Return JS fallback handle
268
+ return createFallbackFlowPolicyEngine();
269
+ }
270
+ function createFallbackFlowPolicyEngine() {
271
+ const policies = new Map();
272
+ let defaultAction = "allow";
273
+ let blpMode = "disabled";
274
+ return {
275
+ addPolicy(policy) {
276
+ policies.set(policy.id, policy);
277
+ },
278
+ removePolicy(policyId) {
279
+ return policies.delete(policyId);
280
+ },
281
+ evaluate(data, sourceDomain, targetDomain) {
282
+ // Simple fallback: allow if sensitivity allows
283
+ const sensitivityOrder = {
284
+ public: 1, internal: 2, confidential: 3, secret: 4, top_secret: 5,
285
+ };
286
+ const sourceLevel = sensitivityOrder[data.sensitivity] || 2;
287
+ const targetLevel = sensitivityOrder[targetDomain] || 1;
288
+ // Bell-LaPadula: can't write up (no read up, no write down)
289
+ if (blpMode === "enabled") {
290
+ if (sourceLevel > targetLevel) {
291
+ return {
292
+ allowed: false,
293
+ reason: `BLP violation: cannot flow from ${data.sensitivity} to ${targetDomain}`,
294
+ applied_policy: "blp_default",
295
+ can_log: true,
296
+ can_transmit: false,
297
+ can_store: true,
298
+ transformations: [],
299
+ confidence: 1.0,
300
+ warnings: [],
301
+ };
302
+ }
303
+ }
304
+ return {
305
+ allowed: defaultAction === "allow",
306
+ reason: `Allowed by default (${defaultAction})`,
307
+ applied_policy: null,
308
+ can_log: true,
309
+ can_transmit: true,
310
+ can_store: true,
311
+ transformations: [],
312
+ confidence: 0.5,
313
+ warnings: [],
314
+ };
315
+ },
316
+ listPolicies() {
317
+ return Array.from(policies.values());
318
+ },
319
+ setDefaultAction(action) {
320
+ defaultAction = action;
321
+ },
322
+ setBlpMode(mode) {
323
+ blpMode = mode;
324
+ },
325
+ };
326
+ }
327
+ /**
328
+ * Create an allow-all flow policy
329
+ */
330
+ export async function createAllowAllFlowPolicy() {
331
+ const native = await getNative();
332
+ if (typeof native.create_allow_all_flow_policy === 'function') {
333
+ return native.create_allow_all_flow_policy();
334
+ }
335
+ return {
336
+ id: "allow_all",
337
+ description: "Allow all flows",
338
+ source_pattern: "*",
339
+ target_pattern: "*",
340
+ min_source_sensitivity: null,
341
+ max_target_sensitivity: null,
342
+ categories: [],
343
+ effect: "allow",
344
+ priority: 0,
345
+ required_transforms: [],
346
+ log_flow: false,
347
+ require_approval: false,
348
+ conditions: null,
349
+ enabled: true,
350
+ };
351
+ }
352
+ /**
353
+ * Create a deny-all flow policy
354
+ */
355
+ export async function createDenyAllFlowPolicy() {
356
+ const native = await getNative();
357
+ if (typeof native.create_deny_all_flow_policy === 'function') {
358
+ return native.create_deny_all_flow_policy();
359
+ }
360
+ return {
361
+ id: "deny_all",
362
+ description: "Deny all flows",
363
+ source_pattern: "*",
364
+ target_pattern: "*",
365
+ min_source_sensitivity: null,
366
+ max_target_sensitivity: null,
367
+ categories: [],
368
+ effect: "deny",
369
+ priority: 1000,
370
+ required_transforms: [],
371
+ log_flow: false,
372
+ require_approval: false,
373
+ conditions: null,
374
+ enabled: true,
375
+ };
376
+ }
377
+ /**
378
+ * Create a strict flow policy
379
+ */
380
+ export async function createStrictFlowPolicy() {
381
+ const native = await getNative();
382
+ if (typeof native.create_strict_flow_policy === 'function') {
383
+ return native.create_strict_flow_policy();
384
+ }
385
+ return {
386
+ id: "strict",
387
+ description: "Strict flow policy",
388
+ source_pattern: "*",
389
+ target_pattern: "*",
390
+ min_source_sensitivity: "internal",
391
+ max_target_sensitivity: null,
392
+ categories: [],
393
+ effect: "transform",
394
+ priority: 500,
395
+ required_transforms: ["redact_sensitive"],
396
+ log_flow: true,
397
+ require_approval: true,
398
+ conditions: null,
399
+ enabled: true,
400
+ };
401
+ }
402
+ // ===== Flow Tracker =====
403
+ /**
404
+ * Create a flow tracker
405
+ */
406
+ export async function createFlowTracker() {
407
+ const native = await getNative();
408
+ if (typeof native.create_flow_tracker === 'function') {
409
+ return native.create_flow_tracker();
410
+ }
411
+ // Return JS fallback handle
412
+ return createFallbackFlowTracker();
413
+ }
414
+ function createFallbackFlowTracker() {
415
+ const flows = [];
416
+ let maxFlows = 10000;
417
+ return {
418
+ record(data, sourceDomain, targetDomain, direction, validation, sessionId, actionId) {
419
+ const record = {
420
+ id: `flow_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`,
421
+ data_id: data.id,
422
+ source_domain: sourceDomain,
423
+ target_domain: targetDomain,
424
+ direction,
425
+ allowed: validation.allowed,
426
+ reason: validation.reason,
427
+ policy_id: validation.applied_policy,
428
+ session_id: sessionId,
429
+ action_id: actionId,
430
+ timestamp: Date.now(),
431
+ data_hash: "",
432
+ };
433
+ if (flows.length >= maxFlows) {
434
+ flows.shift();
435
+ }
436
+ flows.push(record);
437
+ return record;
438
+ },
439
+ getFlow(flowId) {
440
+ return flows.find(f => f.id === flowId) || null;
441
+ },
442
+ getLineage(dataId) {
443
+ return flows.filter(f => f.data_id === dataId);
444
+ },
445
+ bySource(domain) {
446
+ return flows.filter(f => f.source_domain === domain);
447
+ },
448
+ byTarget(domain) {
449
+ return flows.filter(f => f.target_domain === domain);
450
+ },
451
+ bySession(sessionId) {
452
+ return flows.filter(f => f.session_id === sessionId);
453
+ },
454
+ blocked() {
455
+ return flows.filter(f => !f.allowed);
456
+ },
457
+ allowed() {
458
+ return flows.filter(f => f.allowed);
459
+ },
460
+ recent(limit) {
461
+ return flows.slice(-limit);
462
+ },
463
+ stats() {
464
+ return {
465
+ total_flows: flows.length,
466
+ allowed_count: flows.filter(f => f.allowed).length,
467
+ blocked_count: flows.filter(f => !f.allowed).length,
468
+ by_direction: [],
469
+ by_source_domain: [],
470
+ by_target_domain: [],
471
+ first_timestamp: flows[0]?.timestamp || Date.now(),
472
+ last_timestamp: flows[flows.length - 1]?.timestamp || Date.now(),
473
+ };
474
+ },
475
+ domainStats(domain) {
476
+ const domainFlows = flows.filter(f => f.source_domain === domain || f.target_domain === domain);
477
+ if (domainFlows.length === 0)
478
+ return null;
479
+ return {
480
+ domain,
481
+ inbound_count: domainFlows.filter(f => f.target_domain === domain).length,
482
+ outbound_count: domainFlows.filter(f => f.source_domain === domain).length,
483
+ blocked_count: domainFlows.filter(f => !f.allowed).length,
484
+ by_sensitivity: {},
485
+ };
486
+ },
487
+ count() {
488
+ return flows.length;
489
+ },
490
+ clear() {
491
+ flows.length = 0;
492
+ },
493
+ setMaxFlows(max) {
494
+ maxFlows = max;
495
+ },
496
+ exportJsonl() {
497
+ return flows.map(f => JSON.stringify(f)).join("\n");
498
+ },
499
+ };
500
+ }
501
+ // ===== Leak Prevention =====
502
+ /**
503
+ * Create a leak prevention engine
504
+ */
505
+ export async function createLeakPrevention() {
506
+ const native = await getNative();
507
+ if (typeof native.create_leak_prevention === 'function') {
508
+ return native.create_leak_prevention();
509
+ }
510
+ // Return JS fallback handle
511
+ return createFallbackLeakPrevention();
512
+ }
513
+ function createFallbackLeakPrevention() {
514
+ const sensitivePatterns = [];
515
+ const channels = new Set(["stdout", "stderr", "network", "file"]);
516
+ let mode = "alert";
517
+ let checkCount = 0;
518
+ let blockedCount = 0;
519
+ let alertCount = 0;
520
+ const leakPatterns = [
521
+ { pattern: /password[=:]\s*\S+/gi, type: "credential_exposure" },
522
+ { pattern: /api[_-]?key[=:]\s*\S+/gi, type: "credential_exposure" },
523
+ { pattern: /token[=:]\s*\S+/gi, type: "credential_exposure" },
524
+ { pattern: /secret[=:]\s*\S+/gi, type: "credential_exposure" },
525
+ { pattern: /\b[A-Za-z0-9._%+-]{20,}@\b/g, type: "pii_exposure" },
526
+ { pattern: /\b\d{4}[- ]?\d{4}[- ]?\d{4}\b/g, type: "pii_exposure" },
527
+ { pattern: /-----BEGIN.*KEY-----/g, type: "secret_key_exposure" },
528
+ { pattern: /-----BEGIN.*PRIVATE KEY-----/g, type: "secret_key_exposure" },
529
+ { pattern: /mongodb:\/\/.+/gi, type: "internal_url_exposure" },
530
+ { pattern: /redis:\/\/.+/gi, type: "internal_url_exposure" },
531
+ ];
532
+ return {
533
+ check(content, channel) {
534
+ checkCount++;
535
+ const detections = [];
536
+ for (const { pattern, type } of leakPatterns) {
537
+ if (pattern.test(content)) {
538
+ detections.push({
539
+ pattern_name: pattern.source,
540
+ leak_type: type,
541
+ severity: type === "credential_exposure" ? 5 : type === "secret_key_exposure" ? 5 : 3,
542
+ match_found: true,
543
+ });
544
+ }
545
+ }
546
+ for (const sensitive of sensitivePatterns) {
547
+ if (content.includes(sensitive)) {
548
+ detections.push({
549
+ pattern_name: "registered_sensitive",
550
+ leak_type: "credential_exposure",
551
+ severity: 4,
552
+ match_found: true,
553
+ });
554
+ }
555
+ }
556
+ const channelAllowed = channels.has(channel);
557
+ const shouldBlock = detections.length > 0 && mode === "block";
558
+ const action = shouldBlock ? "block" : detections.length > 0 ? "alert" : "allow";
559
+ if (action === "block")
560
+ blockedCount++;
561
+ else if (action === "alert")
562
+ alertCount++;
563
+ return {
564
+ action,
565
+ detections,
566
+ channel_allowed: channelAllowed,
567
+ checked_at: Date.now(),
568
+ };
569
+ },
570
+ sanitize(content) {
571
+ let sanitized = content;
572
+ for (const { pattern } of leakPatterns) {
573
+ sanitized = sanitized.replace(pattern, "[REDACTED]");
574
+ }
575
+ for (const sensitive of sensitivePatterns) {
576
+ sanitized = sanitized.replace(sensitive, "[REDACTED]");
577
+ }
578
+ return sanitized;
579
+ },
580
+ registerSensitive(data) {
581
+ sensitivePatterns.push(data);
582
+ },
583
+ addChannel(channel) {
584
+ channels.add(channel);
585
+ },
586
+ removeChannel(channel) {
587
+ channels.delete(channel);
588
+ },
589
+ setMode(newMode) {
590
+ if (newMode === "alert" || newMode === "block") {
591
+ mode = newMode;
592
+ }
593
+ },
594
+ stats() {
595
+ return {
596
+ total_checks: checkCount,
597
+ blocked_count: blockedCount,
598
+ alert_count: alertCount,
599
+ by_leak_type: {},
600
+ };
601
+ },
602
+ clearSensitive() {
603
+ sensitivePatterns.length = 0;
604
+ },
605
+ };
606
+ }
607
+ /**
608
+ * Quick check content for leaks
609
+ */
610
+ export async function checkForLeaks(content, channel) {
611
+ const native = await getNative();
612
+ if (typeof native.check_for_leaks === 'function') {
613
+ return native.check_for_leaks(content, channel);
614
+ }
615
+ // Use fallback implementation
616
+ const engine = createFallbackLeakPrevention();
617
+ return engine.check(content, channel);
618
+ }
619
+ /**
620
+ * Quick sanitize content
621
+ */
622
+ export async function sanitizeContent(content) {
623
+ const native = await getNative();
624
+ if (typeof native.sanitizeContent === 'function') {
625
+ return native.sanitizeContent(content);
626
+ }
627
+ // Use fallback implementation
628
+ const engine = createFallbackLeakPrevention();
629
+ return engine.sanitize(content);
630
+ }
631
+ // ===== Taint Tracking =====
632
+ /**
633
+ * Create a taint tracker
634
+ */
635
+ export async function createTaintTracker() {
636
+ const native = await getNative();
637
+ if (typeof native.createTaintTracker === 'function') {
638
+ return native.createTaintTracker();
639
+ }
640
+ // Return JS fallback handle
641
+ return createFallbackTaintTracker();
642
+ }
643
+ function createFallbackTaintTracker() {
644
+ const sources = new Map();
645
+ const taintedData = new Map();
646
+ const propagations = [];
647
+ return {
648
+ registerSource(sourceType, sensitivity, tags) {
649
+ const id = `source_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`;
650
+ sources.set(id, {
651
+ id,
652
+ source_type: sourceType,
653
+ sensitivity,
654
+ registered_at: Date.now(),
655
+ tags,
656
+ });
657
+ return id;
658
+ },
659
+ taint(sourceId, data, locationType, identifier) {
660
+ const source = sources.get(sourceId);
661
+ if (!source)
662
+ return null;
663
+ const taintId = `taint_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`;
664
+ const tainted = {
665
+ id: taintId,
666
+ source_id: sourceId,
667
+ data_hash: data.substring(0, 32),
668
+ sensitivity: source.sensitivity,
669
+ location: {
670
+ location_type: locationType,
671
+ identifier,
672
+ context: null,
673
+ },
674
+ propagated_from: [],
675
+ tainted_at: Date.now(),
676
+ can_sanitize: true,
677
+ last_accessed: Date.now(),
678
+ access_count: 0,
679
+ };
680
+ taintedData.set(taintId, tainted);
681
+ return taintId;
682
+ },
683
+ propagate(sourceTaintId, newData, locationType, identifier, propagationType, operation) {
684
+ const sourceTaint = taintedData.get(sourceTaintId);
685
+ if (!sourceTaint)
686
+ return null;
687
+ const newTaintId = `taint_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`;
688
+ const newTaint = {
689
+ id: newTaintId,
690
+ source_id: sourceTaint.source_id,
691
+ data_hash: newData.substring(0, 32),
692
+ sensitivity: sourceTaint.sensitivity,
693
+ location: {
694
+ location_type: locationType,
695
+ identifier,
696
+ context: null,
697
+ },
698
+ propagated_from: [sourceTaintId],
699
+ tainted_at: Date.now(),
700
+ can_sanitize: true,
701
+ last_accessed: Date.now(),
702
+ access_count: 0,
703
+ };
704
+ taintedData.set(newTaintId, newTaint);
705
+ propagations.push({
706
+ id: `prop_${Date.now()}`,
707
+ source_id: sourceTaintId,
708
+ target_id: newTaintId,
709
+ propagation_type: propagationType,
710
+ operation,
711
+ timestamp: Date.now(),
712
+ });
713
+ return newTaintId;
714
+ },
715
+ canFlow(taintId, sink) {
716
+ const taint = taintedData.get(taintId);
717
+ if (!taint) {
718
+ return { allowed: true, reason: "No taint found", requires_sanitization: false };
719
+ }
720
+ // Check sensitivity-based flow
721
+ const sensitivityOrder = ["public", "internal", "confidential", "secret", "top_secret"];
722
+ const taintLevel = sensitivityOrder.indexOf(taint.sensitivity);
723
+ if (taintLevel >= 3) {
724
+ // High sensitivity data
725
+ if (sink === "external" || sink === "network") {
726
+ return {
727
+ allowed: false,
728
+ reason: `Cannot flow ${taint.sensitivity} data to ${sink}`,
729
+ requires_sanitization: true,
730
+ };
731
+ }
732
+ }
733
+ return { allowed: true, reason: "Flow allowed", requires_sanitization: false };
734
+ },
735
+ isTainted(data) {
736
+ for (const taint of taintedData.values()) {
737
+ if (data.includes(taint.data_hash)) {
738
+ return true;
739
+ }
740
+ }
741
+ return false;
742
+ },
743
+ getTaint(taintId) {
744
+ return taintedData.get(taintId) || null;
745
+ },
746
+ stats() {
747
+ return {
748
+ total_sources: sources.size,
749
+ total_tainted: taintedData.size,
750
+ total_propagations: propagations.length,
751
+ by_source_type: {},
752
+ by_sensitivity: {},
753
+ };
754
+ },
755
+ clear(taintId) {
756
+ return taintedData.delete(taintId);
757
+ },
758
+ clearAll() {
759
+ sources.clear();
760
+ taintedData.clear();
761
+ propagations.length = 0;
762
+ },
763
+ };
764
+ }
765
+ let directiveStoreHandle = null;
766
+ let actionSignerHandle = null;
767
+ let driftDetectorHandle = null;
768
+ /**
769
+ * Create a directive store for immutable directives
770
+ */
771
+ export async function createDirectiveStore() {
772
+ const native = await getNative();
773
+ if (native.create_directive_store) {
774
+ return native.create_directive_store();
775
+ }
776
+ // Fallback to JS implementation
777
+ return new DirectiveStoreHandle();
778
+ }
779
+ /**
780
+ * Create an action signer for cryptographic action signing
781
+ */
782
+ export async function createActionSigner(privateKeyHex, sessionId) {
783
+ const native = await getNative();
784
+ if (native.create_action_signer) {
785
+ return native.create_action_signer(privateKeyHex, sessionId);
786
+ }
787
+ // Fallback to JS implementation
788
+ return new ActionSignerHandle(privateKeyHex, sessionId);
789
+ }
790
+ /**
791
+ * Create a drift detector for behavioral analytics
792
+ */
793
+ export async function createDriftDetector(agentId, intentId) {
794
+ const native = await getNative();
795
+ if (native.create_drift_detector) {
796
+ return native.create_drift_detector(agentId, intentId);
797
+ }
798
+ // Fallback to JS implementation
799
+ return new DriftDetectorHandle(agentId, intentId);
800
+ }
801
+ /**
802
+ * Create default financial protection directives
803
+ */
804
+ export async function createDefaultFinancialDirectives(store) {
805
+ const native = await getNative();
806
+ if (native.create_default_financial_directives) {
807
+ return native.create_default_financial_directives(store);
808
+ }
809
+ // JS fallback - create basic directives
810
+ return [
811
+ await store.createDirective("forbidden_action", JSON.stringify({
812
+ actions: ["*"],
813
+ paramPatterns: ["send.*eth", "send.*btc", "transfer.*crypto", "wallet.*address"]
814
+ }), "financial", 1, false, "system"),
815
+ await store.createDirective("forbidden_action", JSON.stringify({
816
+ actions: ["mcp__telegram__telegram_send_message"],
817
+ paramPatterns: ["password", "secret", "api_key", "private_key"]
818
+ }), "credentials", 1, false, "system"),
819
+ ];
820
+ }
821
+ // ===== JS Fallback Implementations =====
822
+ class DirectiveStoreHandle {
823
+ directives = new Map();
824
+ async setSigningKey(privateKeyHex) {
825
+ // JS fallback - no actual signing
826
+ }
827
+ async createDirective(directiveType, rule, domain, priority = 5, overridable = false, createdBy = "user") {
828
+ const id = `directive-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
829
+ const directive = {
830
+ id,
831
+ directiveType,
832
+ rule,
833
+ domain,
834
+ priority,
835
+ overridable,
836
+ createdAt: Date.now(),
837
+ createdBy,
838
+ ruleHash: await this.hashRule(rule),
839
+ };
840
+ this.directives.set(id, directive);
841
+ return directive;
842
+ }
843
+ async addDirective(directive) {
844
+ this.directives.set(directive.id, directive);
845
+ }
846
+ async evaluate(actionType, domain, target, params) {
847
+ const violations = [];
848
+ const approvalDirectives = [];
849
+ for (const directive of this.directives.values()) {
850
+ if (directive.domain !== "*" && directive.domain !== domain)
851
+ continue;
852
+ const matches = this.evaluateRule(directive.rule, actionType, domain, target, params);
853
+ if (matches) {
854
+ if (directive.directiveType === "forbidden_action") {
855
+ violations.push({
856
+ directiveId: directive.id,
857
+ directiveType: directive.directiveType,
858
+ reason: `Matched forbidden pattern in ${directive.domain}`,
859
+ severity: directive.priority === 1 ? "critical" : "high",
860
+ });
861
+ }
862
+ else if (directive.directiveType === "required_approval") {
863
+ approvalDirectives.push(directive.id);
864
+ }
865
+ }
866
+ }
867
+ const hasCritical = violations.some(v => v.severity === "critical");
868
+ return {
869
+ allowed: !hasCritical,
870
+ requiresApproval: approvalDirectives.length > 0,
871
+ violations,
872
+ approvalDirectives,
873
+ denialReason: hasCritical ? "Critical directive violation" : undefined,
874
+ };
875
+ }
876
+ evaluateRule(rule, actionType, domain, target, params) {
877
+ try {
878
+ const ruleJson = JSON.parse(rule);
879
+ // Check action patterns
880
+ if (ruleJson.actions) {
881
+ for (const action of ruleJson.actions) {
882
+ if (action === "*" || action === actionType)
883
+ return true;
884
+ }
885
+ }
886
+ // Check param patterns
887
+ if (ruleJson.paramPatterns || ruleJson.param_patterns) {
888
+ const patterns = ruleJson.paramPatterns || ruleJson.param_patterns;
889
+ for (const pattern of patterns) {
890
+ if (params.toLowerCase().includes(pattern.toLowerCase()))
891
+ return true;
892
+ }
893
+ }
894
+ return false;
895
+ }
896
+ catch {
897
+ // Simple string match
898
+ return rule.includes(actionType) || rule.includes(domain);
899
+ }
900
+ }
901
+ async hashRule(rule) {
902
+ const encoder = new TextEncoder();
903
+ const data = encoder.encode(rule);
904
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
905
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
906
+ return hashArray.map(b => b.toString(16).padStart(2, "0")).join("");
907
+ }
908
+ }
909
+ class ActionSignerHandle {
910
+ privateKey;
911
+ _sessionId;
912
+ _sequence = 0;
913
+ _lastHash = null;
914
+ _intentId = null;
915
+ constructor(privateKey, sessionId) {
916
+ this.privateKey = privateKey;
917
+ this._sessionId = sessionId;
918
+ }
919
+ setIntent(intentId) {
920
+ this._intentId = intentId;
921
+ }
922
+ async sign(tool, domain, actionType, target, params) {
923
+ this._sequence++;
924
+ const timestamp = Date.now();
925
+ const id = `action-${this._sessionId}-${this._sequence}`;
926
+ // Hash params
927
+ const encoder = new TextEncoder();
928
+ const paramsData = encoder.encode(params);
929
+ const paramsHashBuffer = await crypto.subtle.digest("SHA-256", paramsData);
930
+ const paramsHash = Array.from(new Uint8Array(paramsHashBuffer))
931
+ .map(b => b.toString(16).padStart(2, "0"))
932
+ .join("");
933
+ // Create action (without signature for hash computation)
934
+ const action = {
935
+ id,
936
+ sequence: this._sequence,
937
+ sessionId: this._sessionId,
938
+ tool,
939
+ domain,
940
+ actionType,
941
+ target: target || undefined,
942
+ paramsHash,
943
+ timestamp,
944
+ intentId: this._intentId ?? undefined,
945
+ signature: "",
946
+ signedBy: this.privateKey.substring(0, 16), // Placeholder
947
+ prevHash: this._lastHash ?? undefined,
948
+ hash: "",
949
+ };
950
+ // Compute hash
951
+ const hashInput = `${action.id}:${action.sequence}:${action.tool}:${action.domain}:${action.paramsHash}:${action.timestamp}`;
952
+ const hashData = encoder.encode(hashInput);
953
+ const hashBuffer = await crypto.subtle.digest("SHA-256", hashData);
954
+ action.hash = Array.from(new Uint8Array(hashBuffer))
955
+ .map(b => b.toString(16).padStart(2, "0"))
956
+ .join("");
957
+ // Sign (simplified - in production use Ed25519)
958
+ action.signature = `sig-${action.hash.substring(0, 32)}`;
959
+ this._lastHash = action.hash;
960
+ return action;
961
+ }
962
+ async verify(action) {
963
+ // Simplified verification
964
+ const valid = action.signature === `sig-${action.hash.substring(0, 32)}`;
965
+ return {
966
+ signatureValid: valid,
967
+ chainIntact: action.prevHash === this._lastHash || action.sequence === 1,
968
+ hashValid: true,
969
+ intentVerified: !this._intentId || action.intentId === this._intentId,
970
+ valid,
971
+ error: valid ? undefined : "Signature verification failed",
972
+ };
973
+ }
974
+ getSequence() {
975
+ return this._sequence;
976
+ }
977
+ getSessionId() {
978
+ return this._sessionId;
979
+ }
980
+ get publicKey() {
981
+ return this.privateKey.substring(0, 16) + "...";
982
+ }
983
+ }
984
+ /**
985
+ * Verify a signed action without needing a signer handle
986
+ */
987
+ export async function verifySignedAction(action, publicKeyHex) {
988
+ const native = await getNative();
989
+ if (native.verify_signed_action) {
990
+ return native.verify_signed_action(action, publicKeyHex);
991
+ }
992
+ // JS fallback - simplified verification
993
+ const expectedSig = `sig-${action.hash.substring(0, 32)}`;
994
+ const valid = action.signature === expectedSig;
995
+ return {
996
+ signatureValid: valid,
997
+ chainIntact: action.prevHash !== null || action.sequence === 1,
998
+ hashValid: true,
999
+ intentVerified: true, // Can't verify intent without context
1000
+ valid,
1001
+ error: valid ? undefined : "Signature verification failed",
1002
+ };
1003
+ }
1004
+ class DriftDetectorHandle {
1005
+ agentId;
1006
+ intentId;
1007
+ profile;
1008
+ recentActions = [];
1009
+ actionTimes = [];
1010
+ threshold = 0.3;
1011
+ constructor(agentId, intentId) {
1012
+ this.agentId = agentId;
1013
+ this.intentId = intentId || null;
1014
+ this.profile = {
1015
+ agentId,
1016
+ intentId: intentId || undefined,
1017
+ createdAt: Date.now(),
1018
+ updatedAt: Date.now(),
1019
+ totalActions: 0,
1020
+ actionTypes: {},
1021
+ domains: {},
1022
+ tools: {},
1023
+ actionsPerMinute: 0,
1024
+ rateWindow: 60,
1025
+ commonSequences: [],
1026
+ forbiddenAttempts: 0,
1027
+ approvalRequests: 0,
1028
+ };
1029
+ }
1030
+ record(action) {
1031
+ this.profile.totalActions++;
1032
+ this.profile.updatedAt = Date.now();
1033
+ // Update distributions
1034
+ this.profile.actionTypes[action.actionType] = (this.profile.actionTypes[action.actionType] || 0) + 1;
1035
+ this.profile.domains[action.domain] = (this.profile.domains[action.domain] || 0) + 1;
1036
+ this.profile.tools[action.tool] = (this.profile.tools[action.tool] || 0) + 1;
1037
+ // Track recent actions
1038
+ this.recentActions.push(action);
1039
+ if (this.recentActions.length > 100) {
1040
+ this.recentActions.shift();
1041
+ }
1042
+ // Track times for rate calculation
1043
+ this.actionTimes.push(action.timestamp);
1044
+ const cutoff = Date.now() - this.profile.rateWindow * 1000;
1045
+ this.actionTimes = this.actionTimes.filter(t => t > cutoff);
1046
+ // Calculate rate
1047
+ if (this.actionTimes.length > 1) {
1048
+ const lastTime = this.actionTimes[this.actionTimes.length - 1];
1049
+ const firstTime = this.actionTimes[0];
1050
+ if (lastTime !== undefined && firstTime !== undefined) {
1051
+ const timeSpan = (lastTime - firstTime) / 1000;
1052
+ if (timeSpan > 0) {
1053
+ this.profile.actionsPerMinute = (this.actionTimes.length / timeSpan) * 60;
1054
+ }
1055
+ }
1056
+ }
1057
+ }
1058
+ recordForbidden() {
1059
+ this.profile.forbiddenAttempts++;
1060
+ }
1061
+ recordApproval() {
1062
+ this.profile.approvalRequests++;
1063
+ }
1064
+ detect() {
1065
+ const indicators = [];
1066
+ // Check for too many forbidden attempts
1067
+ if (this.profile.forbiddenAttempts > 0) {
1068
+ const forbiddenRatio = this.profile.forbiddenAttempts / this.profile.totalActions;
1069
+ if (forbiddenRatio > 0.1) {
1070
+ indicators.push({
1071
+ indicatorType: "forbidden-pattern",
1072
+ severity: Math.min(forbiddenRatio, 1),
1073
+ description: `${this.profile.forbiddenAttempts} forbidden attempts (${(forbiddenRatio * 100).toFixed(1)}%)`,
1074
+ factor: "security_violations",
1075
+ evidence: [`${this.profile.forbiddenAttempts} forbidden attempts`],
1076
+ });
1077
+ }
1078
+ }
1079
+ // Check rate anomaly
1080
+ if (this.profile.actionsPerMinute > 30) {
1081
+ indicators.push({
1082
+ indicatorType: "rate-anomaly",
1083
+ severity: Math.min(this.profile.actionsPerMinute / 60, 1),
1084
+ description: `High action rate: ${this.profile.actionsPerMinute.toFixed(1)}/min`,
1085
+ factor: "action_rate",
1086
+ evidence: [`${this.profile.actionsPerMinute.toFixed(1)} actions/min`],
1087
+ });
1088
+ }
1089
+ // Calculate drift score
1090
+ const overallDrift = indicators.length > 0
1091
+ ? indicators.reduce((sum, i) => sum + i.severity, 0) / indicators.length
1092
+ : 0;
1093
+ const concernLevel = overallDrift > 0.7
1094
+ ? "critical"
1095
+ : overallDrift > 0.5
1096
+ ? "high"
1097
+ : overallDrift > this.threshold
1098
+ ? "medium"
1099
+ : overallDrift > 0.1
1100
+ ? "low"
1101
+ : "none";
1102
+ return {
1103
+ overallDrift,
1104
+ driftFactors: indicators.map(i => ({
1105
+ factorType: i.factor,
1106
+ drift: i.severity,
1107
+ description: i.description,
1108
+ })),
1109
+ concernLevel,
1110
+ };
1111
+ }
1112
+ getProfile() {
1113
+ return { ...this.profile };
1114
+ }
1115
+ setThreshold(threshold) {
1116
+ this.threshold = threshold;
1117
+ }
1118
+ getRecentActions() {
1119
+ return [...this.recentActions];
1120
+ }
1121
+ }
1122
+ // ===== Automatic Security Hooks =====
1123
+ export * from "./hooks.js";