@cortex-agent/server 2026.5.19-1

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 (503) hide show
  1. package/defaults/.claude/settings.json +13 -0
  2. package/defaults/CORTEX.md +15 -0
  3. package/defaults/config/budget.json +4 -0
  4. package/defaults/config/session-hooks.json +7 -0
  5. package/defaults/config/thread-templates.json +528 -0
  6. package/defaults/context/CORTEX.md +40 -0
  7. package/defaults/context/decisions/DR-0012.md +54 -0
  8. package/defaults/context/ideas/CORTEX.md +10 -0
  9. package/defaults/context/projects/CORTEX.md +25 -0
  10. package/defaults/context/scans/CORTEX.md +13 -0
  11. package/defaults/context/user/CORTEX.md +21 -0
  12. package/defaults/data/schedules.json +52 -0
  13. package/defaults/gitignore +44 -0
  14. package/defaults/hooks/ask-user-question-hook.mjs +66 -0
  15. package/defaults/hooks/cortex-md-injector.mjs +237 -0
  16. package/defaults/hooks/exit-plan-mode-hook.mjs +84 -0
  17. package/defaults/hooks/memory-ref-tracker.mjs +154 -0
  18. package/defaults/hooks/new-session-hook.mjs +83 -0
  19. package/defaults/hooks/post-task-hook.mjs +63 -0
  20. package/defaults/hooks/rules-loader.mjs +212 -0
  21. package/defaults/hooks/sensitive-file-edit.mjs +84 -0
  22. package/defaults/hooks/session-activity-tracker.mjs +254 -0
  23. package/defaults/hooks/task-status-check.mjs +218 -0
  24. package/defaults/hooks/tasks-yaml-guard.mjs +230 -0
  25. package/defaults/plugins/cortex-coder/.claude-plugin/plugin.json +5 -0
  26. package/defaults/plugins/cortex-coder/skills/cli-standards/SKILL.md +208 -0
  27. package/defaults/plugins/cortex-coder/skills/code-standards/SKILL.md +146 -0
  28. package/defaults/plugins/cortex-coder/skills/develop/SKILL.md +164 -0
  29. package/defaults/plugins/cortex-common/.claude-plugin/plugin.json +5 -0
  30. package/defaults/plugins/cortex-common/skills/compound/SKILL.md +349 -0
  31. package/defaults/plugins/cortex-common/skills/compound-simple/SKILL.md +104 -0
  32. package/defaults/plugins/cortex-common/skills/critique/SKILL.md +88 -0
  33. package/defaults/plugins/cortex-common/skills/debug-campaign/SKILL.md +508 -0
  34. package/defaults/plugins/cortex-common/skills/diagnose/SKILL.md +169 -0
  35. package/defaults/plugins/cortex-common/skills/postmortem/SKILL.md +135 -0
  36. package/defaults/plugins/cortex-common/skills/solution-design/SKILL.md +183 -0
  37. package/defaults/plugins/cortex-common/skills/synthesize/SKILL.md +120 -0
  38. package/defaults/plugins/cortex-stage-gate/.claude-plugin/plugin.json +5 -0
  39. package/defaults/plugins/cortex-stage-gate/skills/need-approval/SKILL.md +89 -0
  40. package/defaults/plugins/cortex-stage-gate/skills/reorient/SKILL.md +163 -0
  41. package/defaults/plugins/cortex-stage-gate/skills/task/SKILL.md +425 -0
  42. package/defaults/plugins/cortex-system/.claude-plugin/plugin.json +5 -0
  43. package/defaults/plugins/cortex-system/skills/approval/SKILL.md +84 -0
  44. package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +199 -0
  45. package/defaults/plugins/cortex-system/skills/deep-retrospective/CORTEX.md +8 -0
  46. package/defaults/plugins/cortex-system/skills/deep-retrospective/SKILL.md +201 -0
  47. package/defaults/plugins/cortex-system/skills/deep-retrospective/scripts/CORTEX.md +8 -0
  48. package/defaults/plugins/cortex-system/skills/deep-retrospective/scripts/extract_session.py +165 -0
  49. package/defaults/plugins/cortex-system/skills/deep-retrospective/scripts/scan_logs.py +402 -0
  50. package/defaults/plugins/cortex-system/skills/evolve/SKILL.md +115 -0
  51. package/defaults/plugins/cortex-system/skills/feedback/SKILL.md +262 -0
  52. package/defaults/plugins/cortex-system/skills/gravity/SKILL.md +125 -0
  53. package/defaults/plugins/cortex-system/skills/orient/SKILL.md +310 -0
  54. package/defaults/plugins/cortex-system/skills/orient-project/SKILL.md +85 -0
  55. package/defaults/plugins/cortex-system/skills/project-init/SKILL.md +167 -0
  56. package/defaults/plugins/cortex-system/skills/refresh-skills/SKILL.md +153 -0
  57. package/defaults/plugins/cortex-system/skills/schedule/SKILL.md +209 -0
  58. package/defaults/plugins/cortex-system/skills/thread/SKILL.md +478 -0
  59. package/defaults/plugins/cortex-system/skills/user-learn/SKILL.md +95 -0
  60. package/defaults/prompts/directives/coder-reviewer.md +106 -0
  61. package/defaults/prompts/directives/coder.md +90 -0
  62. package/defaults/prompts/directives/director.md +97 -0
  63. package/defaults/prompts/directives/doc-reviewer.md +93 -0
  64. package/defaults/prompts/directives/doc-writer.md +85 -0
  65. package/defaults/prompts/directives/executor-reviewer.md +96 -0
  66. package/defaults/prompts/directives/executor.md +85 -0
  67. package/defaults/prompts/directives/milestone-executor.md +119 -0
  68. package/defaults/prompts/directives/milestone-reviewer.md +108 -0
  69. package/defaults/prompts/directives/plan-executor.md +121 -0
  70. package/defaults/prompts/directives/plan-reviewer.md +99 -0
  71. package/defaults/prompts/systemPrompts/coder.md +64 -0
  72. package/defaults/prompts/systemPrompts/direct.md +92 -0
  73. package/defaults/prompts/systemPrompts/web-opus-4-6.md +68 -0
  74. package/defaults/prompts/systemPrompts/web-sonnet-4-6.md +76 -0
  75. package/defaults/prompts/systemPrompts/web.md +50 -0
  76. package/defaults/prompts/systemPrompts/worker.md +67 -0
  77. package/defaults/rules/correction-propagation.md +31 -0
  78. package/defaults/rules/decision-records.md +49 -0
  79. package/defaults/rules/experiment-format.md +165 -0
  80. package/defaults/rules/issues-md.md +37 -0
  81. package/defaults/rules/meta-conventions.md +45 -0
  82. package/defaults/rules/mission-md.md +47 -0
  83. package/defaults/rules/overview-md.md +41 -0
  84. package/defaults/rules/roadmap-md.md +55 -0
  85. package/defaults/rules/status-md.md +49 -0
  86. package/defaults/rules/task-system.md +53 -0
  87. package/dist/agent-adapter/capabilities.d.ts +12 -0
  88. package/dist/agent-adapter/capabilities.js +52 -0
  89. package/dist/agent-adapter/claude/adapter-tui.d.ts +140 -0
  90. package/dist/agent-adapter/claude/adapter-tui.js +422 -0
  91. package/dist/agent-adapter/claude/adapter.d.ts +85 -0
  92. package/dist/agent-adapter/claude/adapter.js +771 -0
  93. package/dist/agent-adapter/claude/cost-from-usage.d.ts +62 -0
  94. package/dist/agent-adapter/claude/cost-from-usage.js +97 -0
  95. package/dist/agent-adapter/claude/defaults.d.ts +30 -0
  96. package/dist/agent-adapter/claude/defaults.js +49 -0
  97. package/dist/agent-adapter/claude/event-parser.d.ts +28 -0
  98. package/dist/agent-adapter/claude/event-parser.js +173 -0
  99. package/dist/agent-adapter/claude/hooks-builder.d.ts +36 -0
  100. package/dist/agent-adapter/claude/hooks-builder.js +57 -0
  101. package/dist/agent-adapter/claude/jsonl-tail.d.ts +68 -0
  102. package/dist/agent-adapter/claude/jsonl-tail.js +344 -0
  103. package/dist/agent-adapter/claude/spawn-args.d.ts +38 -0
  104. package/dist/agent-adapter/claude/spawn-args.js +83 -0
  105. package/dist/agent-adapter/claude/tmux-control.d.ts +69 -0
  106. package/dist/agent-adapter/claude/tmux-control.js +127 -0
  107. package/dist/agent-adapter/claude/tool-summarizers.d.ts +2 -0
  108. package/dist/agent-adapter/claude/tool-summarizers.js +24 -0
  109. package/dist/agent-adapter/codex/adapter.d.ts +42 -0
  110. package/dist/agent-adapter/codex/adapter.js +916 -0
  111. package/dist/agent-adapter/codex/event-parser.d.ts +17 -0
  112. package/dist/agent-adapter/codex/event-parser.js +41 -0
  113. package/dist/agent-adapter/codex/spawn-args.d.ts +6 -0
  114. package/dist/agent-adapter/codex/spawn-args.js +30 -0
  115. package/dist/agent-adapter/index.d.ts +8 -0
  116. package/dist/agent-adapter/index.js +33 -0
  117. package/dist/agent-adapter/normalize/event-stream.d.ts +6 -0
  118. package/dist/agent-adapter/normalize/event-stream.js +47 -0
  119. package/dist/agent-adapter/normalize/event-types.d.ts +58 -0
  120. package/dist/agent-adapter/normalize/event-types.js +5 -0
  121. package/dist/agent-adapter/normalize/hooks.d.ts +26 -0
  122. package/dist/agent-adapter/normalize/hooks.js +5 -0
  123. package/dist/agent-adapter/normalize/prompt-builder.d.ts +6 -0
  124. package/dist/agent-adapter/normalize/prompt-builder.js +23 -0
  125. package/dist/agent-adapter/normalize/tool-names.d.ts +6 -0
  126. package/dist/agent-adapter/normalize/tool-names.js +73 -0
  127. package/dist/agent-adapter/pi/adapter.d.ts +60 -0
  128. package/dist/agent-adapter/pi/adapter.js +626 -0
  129. package/dist/agent-adapter/pi/agent-dir.d.ts +11 -0
  130. package/dist/agent-adapter/pi/agent-dir.js +34 -0
  131. package/dist/agent-adapter/pi/event-parser.d.ts +26 -0
  132. package/dist/agent-adapter/pi/event-parser.js +313 -0
  133. package/dist/agent-adapter/pi/framing.d.ts +6 -0
  134. package/dist/agent-adapter/pi/framing.js +35 -0
  135. package/dist/agent-adapter/pi/hook-bridge.d.ts +59 -0
  136. package/dist/agent-adapter/pi/hook-bridge.js +233 -0
  137. package/dist/agent-adapter/pi/mcp-bridge.d.ts +26 -0
  138. package/dist/agent-adapter/pi/mcp-bridge.js +140 -0
  139. package/dist/agent-adapter/pi/pi-ext-types.d.ts +90 -0
  140. package/dist/agent-adapter/pi/pi-ext-types.js +5 -0
  141. package/dist/agent-adapter/pi/spawn-args.d.ts +20 -0
  142. package/dist/agent-adapter/pi/spawn-args.js +54 -0
  143. package/dist/agent-adapter/pi/tool-shims.d.ts +2 -0
  144. package/dist/agent-adapter/pi/tool-shims.js +181 -0
  145. package/dist/agent-adapter/types.d.ts +94 -0
  146. package/dist/agent-adapter/types.js +5 -0
  147. package/dist/core/async-mutex.d.ts +6 -0
  148. package/dist/core/async-mutex.js +36 -0
  149. package/dist/core/cli-utils.d.ts +37 -0
  150. package/dist/core/cli-utils.js +69 -0
  151. package/dist/core/config-generator.d.ts +9 -0
  152. package/dist/core/config-generator.js +58 -0
  153. package/dist/core/gateway-generator.d.ts +46 -0
  154. package/dist/core/gateway-generator.js +336 -0
  155. package/dist/core/log.d.ts +7 -0
  156. package/dist/core/log.js +103 -0
  157. package/dist/core/paths.d.ts +32 -0
  158. package/dist/core/paths.js +49 -0
  159. package/dist/core/profile-generator.d.ts +65 -0
  160. package/dist/core/profile-generator.js +310 -0
  161. package/dist/core/running-executions.d.ts +88 -0
  162. package/dist/core/running-executions.js +186 -0
  163. package/dist/core/status-format.d.ts +18 -0
  164. package/dist/core/status-format.js +31 -0
  165. package/dist/core/task-parser.d.ts +69 -0
  166. package/dist/core/task-parser.js +423 -0
  167. package/dist/core/types/agent-types.d.ts +31 -0
  168. package/dist/core/types/agent-types.js +5 -0
  169. package/dist/core/types/thread-types.d.ts +261 -0
  170. package/dist/core/types/thread-types.js +5 -0
  171. package/dist/core/utils.d.ts +29 -0
  172. package/dist/core/utils.js +98 -0
  173. package/dist/core/version.d.ts +3 -0
  174. package/dist/core/version.js +12 -0
  175. package/dist/domain/agents/config.d.ts +58 -0
  176. package/dist/domain/agents/config.js +313 -0
  177. package/dist/domain/agents/facade.d.ts +52 -0
  178. package/dist/domain/agents/facade.js +264 -0
  179. package/dist/domain/agents/index.d.ts +2 -0
  180. package/dist/domain/agents/index.js +4 -0
  181. package/dist/domain/agents/profile-manager.d.ts +54 -0
  182. package/dist/domain/agents/profile-manager.js +161 -0
  183. package/dist/domain/costs/codex-event-format.d.ts +4 -0
  184. package/dist/domain/costs/codex-event-format.js +66 -0
  185. package/dist/domain/costs/codex-usage-monitor.d.ts +7 -0
  186. package/dist/domain/costs/codex-usage-monitor.js +72 -0
  187. package/dist/domain/costs/cost-tracker.d.ts +115 -0
  188. package/dist/domain/costs/cost-tracker.js +327 -0
  189. package/dist/domain/costs/gateway-manager.d.ts +6 -0
  190. package/dist/domain/costs/gateway-manager.js +228 -0
  191. package/dist/domain/costs/rate-limit-parser.d.ts +11 -0
  192. package/dist/domain/costs/rate-limit-parser.js +87 -0
  193. package/dist/domain/costs/rate-limit-throttle.d.ts +32 -0
  194. package/dist/domain/costs/rate-limit-throttle.js +129 -0
  195. package/dist/domain/executions/registry.d.ts +20 -0
  196. package/dist/domain/executions/registry.js +124 -0
  197. package/dist/domain/mcp/core-server.d.ts +2 -0
  198. package/dist/domain/mcp/core-server.js +34 -0
  199. package/dist/domain/mcp/server.d.ts +3 -0
  200. package/dist/domain/mcp/server.js +78 -0
  201. package/dist/domain/mcp/tools/context.d.ts +23 -0
  202. package/dist/domain/mcp/tools/context.js +51 -0
  203. package/dist/domain/mcp/tools/cortex-md.d.ts +17 -0
  204. package/dist/domain/mcp/tools/cortex-md.js +36 -0
  205. package/dist/domain/mcp/tools/cost.d.ts +2 -0
  206. package/dist/domain/mcp/tools/cost.js +54 -0
  207. package/dist/domain/mcp/tools/executions.d.ts +2 -0
  208. package/dist/domain/mcp/tools/executions.js +94 -0
  209. package/dist/domain/mcp/tools/schedule.d.ts +23 -0
  210. package/dist/domain/mcp/tools/schedule.js +245 -0
  211. package/dist/domain/mcp/tools/slack.d.ts +21 -0
  212. package/dist/domain/mcp/tools/slack.js +124 -0
  213. package/dist/domain/mcp/tools/task-ops.d.ts +2 -0
  214. package/dist/domain/mcp/tools/task-ops.js +509 -0
  215. package/dist/domain/mcp/tools/tui-ask.d.ts +31 -0
  216. package/dist/domain/mcp/tools/tui-ask.js +108 -0
  217. package/dist/domain/mcp/tools/tui-plan.d.ts +28 -0
  218. package/dist/domain/mcp/tools/tui-plan.js +118 -0
  219. package/dist/domain/mcp/tui-server.d.ts +2 -0
  220. package/dist/domain/mcp/tui-server.js +69 -0
  221. package/dist/domain/memory/consolidate.d.ts +55 -0
  222. package/dist/domain/memory/consolidate.js +471 -0
  223. package/dist/domain/memory/cortex-md-injector.d.ts +30 -0
  224. package/dist/domain/memory/cortex-md-injector.js +123 -0
  225. package/dist/domain/memory/cortex-md-scanner.d.ts +9 -0
  226. package/dist/domain/memory/cortex-md-scanner.js +67 -0
  227. package/dist/domain/memory/index-regen.d.ts +19 -0
  228. package/dist/domain/memory/index-regen.js +398 -0
  229. package/dist/domain/memory/rules-loader.d.ts +27 -0
  230. package/dist/domain/memory/rules-loader.js +97 -0
  231. package/dist/domain/memory/skill-scanner.d.ts +5 -0
  232. package/dist/domain/memory/skill-scanner.js +132 -0
  233. package/dist/domain/memory/user-context.d.ts +5 -0
  234. package/dist/domain/memory/user-context.js +34 -0
  235. package/dist/domain/memory/watcher.d.ts +2 -0
  236. package/dist/domain/memory/watcher.js +81 -0
  237. package/dist/domain/monitor/disk-monitor.d.ts +20 -0
  238. package/dist/domain/monitor/disk-monitor.js +97 -0
  239. package/dist/domain/monitor/gpu-monitor.d.ts +26 -0
  240. package/dist/domain/monitor/gpu-monitor.js +135 -0
  241. package/dist/domain/remote/client-bootstrap.d.ts +1 -0
  242. package/dist/domain/remote/client-bootstrap.js +139 -0
  243. package/dist/domain/remote/client-hot-reload.d.ts +18 -0
  244. package/dist/domain/remote/client-hot-reload.js +142 -0
  245. package/dist/domain/remote/client-manager.d.ts +50 -0
  246. package/dist/domain/remote/client-manager.js +452 -0
  247. package/dist/domain/remote/cortex-client.d.ts +1 -0
  248. package/dist/domain/remote/cortex-client.js +704 -0
  249. package/dist/domain/scheduling/job-registry.d.ts +31 -0
  250. package/dist/domain/scheduling/job-registry.js +34 -0
  251. package/dist/domain/scheduling/jobs/_shared.d.ts +14 -0
  252. package/dist/domain/scheduling/jobs/_shared.js +45 -0
  253. package/dist/domain/scheduling/jobs/memory-index-regen.d.ts +1 -0
  254. package/dist/domain/scheduling/jobs/memory-index-regen.js +16 -0
  255. package/dist/domain/scheduling/jobs/scheduled-task.d.ts +11 -0
  256. package/dist/domain/scheduling/jobs/scheduled-task.js +186 -0
  257. package/dist/domain/scheduling/jobs/target-dispatch.d.ts +41 -0
  258. package/dist/domain/scheduling/jobs/target-dispatch.js +48 -0
  259. package/dist/domain/scheduling/jobs/task-archive.d.ts +1 -0
  260. package/dist/domain/scheduling/jobs/task-archive.js +19 -0
  261. package/dist/domain/scheduling/jobs/task-dispatch.d.ts +12 -0
  262. package/dist/domain/scheduling/jobs/task-dispatch.js +214 -0
  263. package/dist/domain/scheduling/runner.d.ts +13 -0
  264. package/dist/domain/scheduling/runner.js +24 -0
  265. package/dist/domain/scheduling/schedule-cli.d.ts +16 -0
  266. package/dist/domain/scheduling/schedule-cli.js +268 -0
  267. package/dist/domain/scheduling/schedule-command.d.ts +4 -0
  268. package/dist/domain/scheduling/schedule-command.js +274 -0
  269. package/dist/domain/scheduling/scheduler.d.ts +86 -0
  270. package/dist/domain/scheduling/scheduler.js +544 -0
  271. package/dist/domain/sessions/session-backup.d.ts +49 -0
  272. package/dist/domain/sessions/session-backup.js +217 -0
  273. package/dist/domain/sessions/session-hooks.d.ts +103 -0
  274. package/dist/domain/sessions/session-hooks.js +311 -0
  275. package/dist/domain/sessions/session-registry.d.ts +21 -0
  276. package/dist/domain/sessions/session-registry.js +31 -0
  277. package/dist/domain/sessions/session.d.ts +3 -0
  278. package/dist/domain/sessions/session.js +14 -0
  279. package/dist/domain/tasks/archiver.d.ts +9 -0
  280. package/dist/domain/tasks/archiver.js +123 -0
  281. package/dist/domain/tasks/dispatch-utils.d.ts +37 -0
  282. package/dist/domain/tasks/dispatch-utils.js +143 -0
  283. package/dist/domain/tasks/dispatcher.d.ts +48 -0
  284. package/dist/domain/tasks/dispatcher.js +285 -0
  285. package/dist/domain/tasks/lint.d.ts +12 -0
  286. package/dist/domain/tasks/lint.js +102 -0
  287. package/dist/domain/tasks/mutator.d.ts +21 -0
  288. package/dist/domain/tasks/mutator.js +208 -0
  289. package/dist/domain/tasks/parser.d.ts +1 -0
  290. package/dist/domain/tasks/parser.js +6 -0
  291. package/dist/domain/tasks/pending-tracker.d.ts +67 -0
  292. package/dist/domain/tasks/pending-tracker.js +163 -0
  293. package/dist/domain/tasks/recommendation/extractor.d.ts +12 -0
  294. package/dist/domain/tasks/recommendation/extractor.js +563 -0
  295. package/dist/domain/tasks/recommendation/patterns.d.ts +11 -0
  296. package/dist/domain/tasks/recommendation/patterns.js +99 -0
  297. package/dist/domain/tasks/recommendation/types.d.ts +67 -0
  298. package/dist/domain/tasks/recommendation/types.js +5 -0
  299. package/dist/domain/tasks/store.d.ts +1 -0
  300. package/dist/domain/tasks/store.js +3 -0
  301. package/dist/domain/tasks/system/cortex-run.d.ts +24 -0
  302. package/dist/domain/tasks/system/cortex-run.js +342 -0
  303. package/dist/domain/tasks/system/task-cli.d.ts +49 -0
  304. package/dist/domain/tasks/system/task-cli.js +664 -0
  305. package/dist/domain/tasks/system/task-completion.d.ts +22 -0
  306. package/dist/domain/tasks/system/task-completion.js +89 -0
  307. package/dist/domain/tasks/system/task-id-utils.d.ts +24 -0
  308. package/dist/domain/tasks/system/task-id-utils.js +84 -0
  309. package/dist/domain/tasks/system/task-lifecycle-edit.d.ts +34 -0
  310. package/dist/domain/tasks/system/task-lifecycle-edit.js +208 -0
  311. package/dist/domain/tasks/system/task-lock.d.ts +25 -0
  312. package/dist/domain/tasks/system/task-lock.js +139 -0
  313. package/dist/domain/tasks/system/task-mutations.d.ts +31 -0
  314. package/dist/domain/tasks/system/task-mutations.js +110 -0
  315. package/dist/domain/tasks/system/task-process.d.ts +37 -0
  316. package/dist/domain/tasks/system/task-process.js +119 -0
  317. package/dist/domain/tasks/system/task-state.d.ts +70 -0
  318. package/dist/domain/tasks/system/task-state.js +176 -0
  319. package/dist/domain/threads/artifact-io.d.ts +18 -0
  320. package/dist/domain/threads/artifact-io.js +182 -0
  321. package/dist/domain/threads/auto-thread.d.ts +3 -0
  322. package/dist/domain/threads/auto-thread.js +19 -0
  323. package/dist/domain/threads/hook-runner.d.ts +4 -0
  324. package/dist/domain/threads/hook-runner.js +250 -0
  325. package/dist/domain/threads/index.d.ts +5 -0
  326. package/dist/domain/threads/index.js +7 -0
  327. package/dist/domain/threads/prompt-builder.d.ts +25 -0
  328. package/dist/domain/threads/prompt-builder.js +176 -0
  329. package/dist/domain/threads/runner.d.ts +83 -0
  330. package/dist/domain/threads/runner.js +434 -0
  331. package/dist/domain/threads/state-machine.d.ts +61 -0
  332. package/dist/domain/threads/state-machine.js +440 -0
  333. package/dist/domain/threads/template-loader.d.ts +20 -0
  334. package/dist/domain/threads/template-loader.js +189 -0
  335. package/dist/domain/threads/template-resolver.d.ts +1 -0
  336. package/dist/domain/threads/template-resolver.js +95 -0
  337. package/dist/domain/threads/utils.d.ts +19 -0
  338. package/dist/domain/threads/utils.js +49 -0
  339. package/dist/entry/app.d.ts +1 -0
  340. package/dist/entry/app.js +234 -0
  341. package/dist/entry/cli.d.ts +12 -0
  342. package/dist/entry/cli.js +254 -0
  343. package/dist/entry/daemon.d.ts +11 -0
  344. package/dist/entry/daemon.js +521 -0
  345. package/dist/entry/init.d.ts +93 -0
  346. package/dist/entry/init.js +1299 -0
  347. package/dist/entry/startup-helpers.d.ts +2 -0
  348. package/dist/entry/startup-helpers.js +56 -0
  349. package/dist/entry/startup-notify.d.ts +10 -0
  350. package/dist/entry/startup-notify.js +20 -0
  351. package/dist/events/event-bus.d.ts +42 -0
  352. package/dist/events/event-bus.js +84 -0
  353. package/dist/events/event-logger.d.ts +12 -0
  354. package/dist/events/event-logger.js +135 -0
  355. package/dist/events/event-replay.d.ts +1 -0
  356. package/dist/events/event-replay.js +51 -0
  357. package/dist/events/event-types.d.ts +145 -0
  358. package/dist/events/event-types.js +5 -0
  359. package/dist/events/index.d.ts +5 -0
  360. package/dist/events/index.js +6 -0
  361. package/dist/hooks/ask-user-question-hook.mjs +66 -0
  362. package/dist/hooks/cortex-md-injector.mjs +237 -0
  363. package/dist/hooks/exit-plan-mode-hook.mjs +84 -0
  364. package/dist/hooks/memory-ref-tracker.mjs +154 -0
  365. package/dist/hooks/new-session-hook.mjs +83 -0
  366. package/dist/hooks/post-task-hook.mjs +63 -0
  367. package/dist/hooks/rules-loader.mjs +212 -0
  368. package/dist/hooks/sensitive-file-edit.mjs +84 -0
  369. package/dist/hooks/session-activity-tracker.mjs +254 -0
  370. package/dist/hooks/task-status-check.mjs +218 -0
  371. package/dist/hooks/tasks-yaml-guard.mjs +230 -0
  372. package/dist/orchestration/agent-runner.d.ts +72 -0
  373. package/dist/orchestration/agent-runner.js +289 -0
  374. package/dist/orchestration/busy-tracker.d.ts +12 -0
  375. package/dist/orchestration/busy-tracker.js +35 -0
  376. package/dist/orchestration/channel-queue.d.ts +18 -0
  377. package/dist/orchestration/channel-queue.js +32 -0
  378. package/dist/orchestration/dispatch-reconciler.d.ts +1 -0
  379. package/dist/orchestration/dispatch-reconciler.js +16 -0
  380. package/dist/orchestration/durable-helpers.d.ts +4 -0
  381. package/dist/orchestration/durable-helpers.js +42 -0
  382. package/dist/orchestration/interactions/ask-user-question.d.ts +32 -0
  383. package/dist/orchestration/interactions/ask-user-question.js +182 -0
  384. package/dist/orchestration/interactions/command-action-router.d.ts +47 -0
  385. package/dist/orchestration/interactions/command-action-router.js +91 -0
  386. package/dist/orchestration/interactions/interaction-handlers.d.ts +5 -0
  387. package/dist/orchestration/interactions/interaction-handlers.js +279 -0
  388. package/dist/orchestration/interactions/plan-approvals.d.ts +47 -0
  389. package/dist/orchestration/interactions/plan-approvals.js +77 -0
  390. package/dist/orchestration/interactions/plan-handler.d.ts +6 -0
  391. package/dist/orchestration/interactions/plan-handler.js +12 -0
  392. package/dist/orchestration/lifecycle.d.ts +50 -0
  393. package/dist/orchestration/lifecycle.js +308 -0
  394. package/dist/orchestration/orchestrator.d.ts +29 -0
  395. package/dist/orchestration/orchestrator.js +25 -0
  396. package/dist/orchestration/routing/commands/cancel.d.ts +10 -0
  397. package/dist/orchestration/routing/commands/cancel.js +136 -0
  398. package/dist/orchestration/routing/commands/channel.d.ts +11 -0
  399. package/dist/orchestration/routing/commands/channel.js +219 -0
  400. package/dist/orchestration/routing/commands/command-context.d.ts +29 -0
  401. package/dist/orchestration/routing/commands/command-context.js +4 -0
  402. package/dist/orchestration/routing/commands/cost.d.ts +3 -0
  403. package/dist/orchestration/routing/commands/cost.js +22 -0
  404. package/dist/orchestration/routing/commands/device.d.ts +6 -0
  405. package/dist/orchestration/routing/commands/device.js +83 -0
  406. package/dist/orchestration/routing/commands/dispatch.d.ts +2 -0
  407. package/dist/orchestration/routing/commands/dispatch.js +49 -0
  408. package/dist/orchestration/routing/commands/index.d.ts +15 -0
  409. package/dist/orchestration/routing/commands/index.js +130 -0
  410. package/dist/orchestration/routing/commands/mode.d.ts +13 -0
  411. package/dist/orchestration/routing/commands/mode.js +290 -0
  412. package/dist/orchestration/routing/commands/nvtop.d.ts +3 -0
  413. package/dist/orchestration/routing/commands/nvtop.js +103 -0
  414. package/dist/orchestration/routing/commands/orient.d.ts +2 -0
  415. package/dist/orchestration/routing/commands/orient.js +3 -0
  416. package/dist/orchestration/routing/commands/schedule.d.ts +4 -0
  417. package/dist/orchestration/routing/commands/schedule.js +132 -0
  418. package/dist/orchestration/routing/commands/sendfile.d.ts +2 -0
  419. package/dist/orchestration/routing/commands/sendfile.js +92 -0
  420. package/dist/orchestration/routing/commands/session.d.ts +9 -0
  421. package/dist/orchestration/routing/commands/session.js +153 -0
  422. package/dist/orchestration/routing/commands/status.d.ts +7 -0
  423. package/dist/orchestration/routing/commands/status.js +180 -0
  424. package/dist/orchestration/routing/commands/tail.d.ts +2 -0
  425. package/dist/orchestration/routing/commands/tail.js +73 -0
  426. package/dist/orchestration/routing/commands/task.d.ts +6 -0
  427. package/dist/orchestration/routing/commands/task.js +142 -0
  428. package/dist/orchestration/routing/commands/thread-handlers.d.ts +2 -0
  429. package/dist/orchestration/routing/commands/thread-handlers.js +138 -0
  430. package/dist/orchestration/routing/commands/thread.d.ts +2 -0
  431. package/dist/orchestration/routing/commands/thread.js +2 -0
  432. package/dist/orchestration/routing/edit-handler.d.ts +24 -0
  433. package/dist/orchestration/routing/edit-handler.js +161 -0
  434. package/dist/orchestration/routing/file-handler.d.ts +6 -0
  435. package/dist/orchestration/routing/file-handler.js +23 -0
  436. package/dist/orchestration/routing/hook-bridge-subscribers.d.ts +4 -0
  437. package/dist/orchestration/routing/hook-bridge-subscribers.js +79 -0
  438. package/dist/orchestration/routing/hook-bridge.d.ts +30 -0
  439. package/dist/orchestration/routing/hook-bridge.js +112 -0
  440. package/dist/orchestration/routing/message-router.d.ts +6 -0
  441. package/dist/orchestration/routing/message-router.js +70 -0
  442. package/dist/orchestration/routing/webhook.d.ts +10 -0
  443. package/dist/orchestration/routing/webhook.js +239 -0
  444. package/dist/orchestration/status-helpers.d.ts +66 -0
  445. package/dist/orchestration/status-helpers.js +222 -0
  446. package/dist/orchestration/superseded-edits.d.ts +22 -0
  447. package/dist/orchestration/superseded-edits.js +31 -0
  448. package/dist/orchestration/thread-executor.d.ts +31 -0
  449. package/dist/orchestration/thread-executor.js +234 -0
  450. package/dist/platform/adapter.d.ts +28 -0
  451. package/dist/platform/adapter.js +5 -0
  452. package/dist/platform/adapters/feishu.d.ts +66 -0
  453. package/dist/platform/adapters/feishu.js +558 -0
  454. package/dist/platform/adapters/index.d.ts +16 -0
  455. package/dist/platform/adapters/index.js +65 -0
  456. package/dist/platform/adapters/slack.d.ts +90 -0
  457. package/dist/platform/adapters/slack.js +630 -0
  458. package/dist/platform/index.d.ts +12 -0
  459. package/dist/platform/index.js +10 -0
  460. package/dist/platform/interactive-builder.d.ts +27 -0
  461. package/dist/platform/interactive-builder.js +120 -0
  462. package/dist/platform/testing.d.ts +100 -0
  463. package/dist/platform/testing.js +190 -0
  464. package/dist/platform/tool-trace.d.ts +33 -0
  465. package/dist/platform/tool-trace.js +165 -0
  466. package/dist/platform/types.d.ts +176 -0
  467. package/dist/platform/types.js +5 -0
  468. package/dist/platform/utils/rate-limiter.d.ts +92 -0
  469. package/dist/platform/utils/rate-limiter.js +213 -0
  470. package/dist/platform/virtual-message.d.ts +68 -0
  471. package/dist/platform/virtual-message.js +464 -0
  472. package/dist/store/atomic-write.d.ts +6 -0
  473. package/dist/store/atomic-write.js +18 -0
  474. package/dist/store/channel-repo.d.ts +21 -0
  475. package/dist/store/channel-repo.js +55 -0
  476. package/dist/store/conversation-ledger-repo.d.ts +86 -0
  477. package/dist/store/conversation-ledger-repo.js +220 -0
  478. package/dist/store/cost-repo.d.ts +57 -0
  479. package/dist/store/cost-repo.js +135 -0
  480. package/dist/store/execution-repo.d.ts +172 -0
  481. package/dist/store/execution-repo.js +343 -0
  482. package/dist/store/in-memory-repository.d.ts +14 -0
  483. package/dist/store/in-memory-repository.js +31 -0
  484. package/dist/store/json-repository.d.ts +51 -0
  485. package/dist/store/json-repository.js +118 -0
  486. package/dist/store/outbound-queue.d.ts +65 -0
  487. package/dist/store/outbound-queue.js +269 -0
  488. package/dist/store/profile-repo.d.ts +36 -0
  489. package/dist/store/profile-repo.js +144 -0
  490. package/dist/store/project-dir-repo.d.ts +22 -0
  491. package/dist/store/project-dir-repo.js +60 -0
  492. package/dist/store/schedule-repo.d.ts +92 -0
  493. package/dist/store/schedule-repo.js +88 -0
  494. package/dist/store/session-registry-repo.d.ts +38 -0
  495. package/dist/store/session-registry-repo.js +96 -0
  496. package/dist/store/session-repo.d.ts +14 -0
  497. package/dist/store/session-repo.js +56 -0
  498. package/dist/store/task-repo.d.ts +41 -0
  499. package/dist/store/task-repo.js +137 -0
  500. package/dist/store/thread-repo.d.ts +50 -0
  501. package/dist/store/thread-repo.js +190 -0
  502. package/package.json +58 -0
  503. package/scripts/postinstall-restart-trigger.mjs +39 -0
@@ -0,0 +1,704 @@
1
+ // input: CORTEX_SERVER_HOST/PORT/DEVICE_NAME env vars
2
+ // output: standalone cortex-client daemon (bash/read/write/...)
3
+ // pos: client daemon entry point on remote devices
4
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
+ import WebSocket from 'ws';
6
+ import * as fs from 'fs';
7
+ import * as path from 'path';
8
+ import * as os from 'os';
9
+ import { execFileSync, spawn } from 'child_process';
10
+ import { scanCortexMDChain } from '../memory/cortex-md-scanner.js';
11
+ import { createLogger } from '../../core/log.js';
12
+ const log = createLogger('cortex-client');
13
+ // --- Config ---
14
+ const SERVER_HOST = process.env.CORTEX_SERVER_HOST;
15
+ const SERVER_PORT = process.env.CORTEX_SERVER_PORT || '3002';
16
+ const DEVICE_NAME = process.env.CORTEX_DEVICE_NAME || os.hostname();
17
+ const PLATFORM = process.platform;
18
+ const HEARTBEAT_INTERVAL_MS = 5000;
19
+ const GIT_BASH_PATHS = [
20
+ 'C:\\Program Files\\Git\\bin\\bash.exe',
21
+ 'C:\\Program Files (x86)\\Git\\bin\\bash.exe',
22
+ ];
23
+ if (!SERVER_HOST) {
24
+ log.error('CORTEX_SERVER_HOST is required');
25
+ process.exit(1);
26
+ }
27
+ // --- Output accumulator (prevents WS message size explosion) ---
28
+ class OutputAccumulator {
29
+ head = '';
30
+ headFull = false;
31
+ tail = '';
32
+ totalChars = 0;
33
+ headSize;
34
+ tailSize;
35
+ constructor(maxBytes) {
36
+ this.headSize = Math.floor(maxBytes * 0.6);
37
+ this.tailSize = Math.floor(maxBytes * 0.4);
38
+ }
39
+ append(data) {
40
+ this.totalChars += data.length;
41
+ if (!this.headFull) {
42
+ this.head += data;
43
+ if (this.head.length > this.headSize) {
44
+ const overflow = this.head.slice(this.headSize);
45
+ this.head = this.head.slice(0, this.headSize);
46
+ this.headFull = true;
47
+ this.tail = overflow;
48
+ }
49
+ }
50
+ else {
51
+ this.tail += data;
52
+ if (this.tail.length > this.tailSize * 2) {
53
+ this.tail = this.tail.slice(-this.tailSize);
54
+ }
55
+ }
56
+ }
57
+ toString() {
58
+ if (!this.headFull)
59
+ return this.head;
60
+ const finalTail = this.tail.slice(-this.tailSize);
61
+ const omitted = this.totalChars - this.head.length - finalTail.length;
62
+ return `${this.head}\n\n[... ${omitted} chars truncated ...]\n\n${finalTail}`;
63
+ }
64
+ }
65
+ // --- Utility functions ---
66
+ function detectEncoding(buffer) {
67
+ if (buffer.length >= 2 && buffer[0] === 0xFF && buffer[1] === 0xFE)
68
+ return 'utf16le';
69
+ return 'utf8';
70
+ }
71
+ function detectLineEnding(content) {
72
+ const crlfCount = (content.match(/\r\n/g) || []).length;
73
+ const lfOnly = content.replace(/\r\n/g, '').match(/\n/g);
74
+ const lfCount = lfOnly ? lfOnly.length : 0;
75
+ return crlfCount > lfCount ? '\r\n' : '\n';
76
+ }
77
+ function countWords(text) {
78
+ let count = 0;
79
+ const english = text.match(/[a-zA-Z]+/g);
80
+ if (english)
81
+ count += english.length;
82
+ const cjk = text.match(/[\u4e00-\u9fff\u3400-\u4dbf\uf900-\ufaff]/g);
83
+ if (cjk)
84
+ count += cjk.length;
85
+ return count;
86
+ }
87
+ // --- Image detection ---
88
+ const IMAGE_SIGNATURES = [
89
+ { bytes: [0xFF, 0xD8, 0xFF], mimeType: 'image/jpeg' },
90
+ { bytes: [0x89, 0x50, 0x4E, 0x47], mimeType: 'image/png' },
91
+ { bytes: [0x47, 0x49, 0x46, 0x38], mimeType: 'image/gif' },
92
+ { bytes: [0x52, 0x49, 0x46, 0x46], mimeType: 'image/webp' },
93
+ { bytes: [0x42, 0x4D], mimeType: 'image/bmp' },
94
+ ];
95
+ function detectImageType(buffer) {
96
+ for (const sig of IMAGE_SIGNATURES) {
97
+ if (buffer.length < sig.bytes.length)
98
+ continue;
99
+ if (!sig.bytes.every((b, i) => buffer[i] === b))
100
+ continue;
101
+ // WebP: RIFF header needs additional check at offset 8-11
102
+ if (sig.mimeType === 'image/webp') {
103
+ if (buffer.length >= 12 && buffer.slice(8, 12).toString('ascii') === 'WEBP') {
104
+ return 'image/webp';
105
+ }
106
+ continue;
107
+ }
108
+ return sig.mimeType;
109
+ }
110
+ return null;
111
+ }
112
+ function extractImageDimensions(buf, mime) {
113
+ try {
114
+ if (mime === 'image/png' && buf.length >= 24) {
115
+ return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
116
+ }
117
+ if (mime === 'image/gif' && buf.length >= 10) {
118
+ return { width: buf.readUInt16LE(6), height: buf.readUInt16LE(8) };
119
+ }
120
+ if (mime === 'image/bmp' && buf.length >= 26) {
121
+ return { width: buf.readInt32LE(18), height: Math.abs(buf.readInt32LE(22)) };
122
+ }
123
+ if (mime === 'image/webp' && buf.length >= 30) {
124
+ if (buf.slice(12, 16).toString('ascii') === 'VP8 ' && buf.length >= 30) {
125
+ return { width: buf.readUInt16LE(26) & 0x3FFF, height: buf.readUInt16LE(28) & 0x3FFF };
126
+ }
127
+ if (buf.slice(12, 17).toString('ascii') === 'VP8L' && buf.length >= 25) {
128
+ const bits = buf.readUInt32LE(21);
129
+ return { width: (bits & 0x3FFF) + 1, height: ((bits >> 14) & 0x3FFF) + 1 };
130
+ }
131
+ }
132
+ if (mime === 'image/jpeg') {
133
+ let offset = 2;
134
+ while (offset < buf.length - 9) {
135
+ if (buf[offset] !== 0xFF)
136
+ break;
137
+ const marker = buf[offset + 1];
138
+ if (marker === 0xC0 || marker === 0xC2) {
139
+ return { width: buf.readUInt16BE(offset + 7), height: buf.readUInt16BE(offset + 5) };
140
+ }
141
+ const segLen = buf.readUInt16BE(offset + 2);
142
+ offset += 2 + segLen;
143
+ }
144
+ }
145
+ }
146
+ catch { }
147
+ return null;
148
+ }
149
+ // --- Capabilities detection ---
150
+ function detectCapabilities() {
151
+ const caps = [];
152
+ try {
153
+ execFileSync('rg', ['--version'], { timeout: 5000, stdio: 'pipe' });
154
+ caps.push('rg');
155
+ }
156
+ catch { }
157
+ return caps;
158
+ }
159
+ // --- Shell execution ---
160
+ function findGitBash() {
161
+ for (const p of GIT_BASH_PATHS) {
162
+ if (fs.existsSync(p))
163
+ return p;
164
+ }
165
+ return null;
166
+ }
167
+ function spawnCommand(cmd, args, timeout, maxOutputBytes = 500_000) {
168
+ return new Promise((resolve) => {
169
+ const proc = spawn(cmd, args, {
170
+ stdio: ['pipe', 'pipe', 'pipe'],
171
+ env: { ...process.env },
172
+ });
173
+ const stdoutAcc = new OutputAccumulator(maxOutputBytes);
174
+ const stderrAcc = new OutputAccumulator(50_000);
175
+ proc.stdout.on('data', (d) => stdoutAcc.append(d.toString()));
176
+ proc.stderr.on('data', (d) => stderrAcc.append(d.toString()));
177
+ // SIGKILL fallback — ensures process is killed even if it ignores SIGTERM
178
+ const timer = setTimeout(() => {
179
+ try {
180
+ proc.kill('SIGKILL');
181
+ }
182
+ catch { }
183
+ }, timeout);
184
+ proc.on('close', (code) => {
185
+ clearTimeout(timer);
186
+ resolve({ stdout: stdoutAcc.toString(), stderr: stderrAcc.toString(), exitCode: code ?? 1 });
187
+ });
188
+ proc.on('error', (err) => {
189
+ clearTimeout(timer);
190
+ resolve({ stdout: stdoutAcc.toString(), stderr: stderrAcc.toString() + '\n' + err.message, exitCode: 127 });
191
+ });
192
+ });
193
+ }
194
+ function execBash(command, timeout) {
195
+ const shell = PLATFORM === 'win32' ? findGitBash() : '/bin/bash';
196
+ if (!shell) {
197
+ return Promise.resolve({ stdout: '', stderr: 'bash not found (git-bash not installed on Windows?)', exitCode: 127 });
198
+ }
199
+ return spawnCommand(shell, ['-l', '-c', command], timeout, 200_000);
200
+ }
201
+ function execBashBackground(command) {
202
+ const shell = PLATFORM === 'win32' ? findGitBash() : '/bin/bash';
203
+ if (!shell)
204
+ return { pid: undefined };
205
+ const proc = spawn(shell, ['-l', '-c', command], {
206
+ stdio: 'ignore',
207
+ detached: true,
208
+ env: { ...process.env },
209
+ });
210
+ proc.unref();
211
+ return { pid: proc.pid };
212
+ }
213
+ // --- Tool: Read ---
214
+ const MAX_READ_WORDS = 25_000;
215
+ const DEFAULT_READ_LINES = 2000;
216
+ const MAX_READ_FILE_SIZE = 10 * 1024 * 1024; // 10MB
217
+ /** Normalize file path for the current platform.
218
+ * On Windows, converts git-bash paths (/c/Users/...) to native (C:\Users\...). */
219
+ function normalizePath(p) {
220
+ if (PLATFORM !== 'win32')
221
+ return p;
222
+ const m = p.match(/^\/([A-Za-z])\/(.*)/);
223
+ if (m)
224
+ return `${m[1].toUpperCase()}:\\${m[2].replace(/\//g, '\\')}`;
225
+ return p;
226
+ }
227
+ function safeScanCortexMDs(filePath) {
228
+ try {
229
+ return scanCortexMDChain(filePath);
230
+ }
231
+ catch {
232
+ return [];
233
+ }
234
+ }
235
+ function handleRead(params) {
236
+ try {
237
+ const filePath = normalizePath(params.file_path);
238
+ if (!path.isAbsolute(filePath)) {
239
+ return { error: 'file_path must be absolute' };
240
+ }
241
+ if (!fs.existsSync(filePath)) {
242
+ return { error: `File not found: ${filePath}` };
243
+ }
244
+ const stat = fs.statSync(filePath);
245
+ if (!stat.isFile()) {
246
+ return { error: `Not a file: ${filePath}` };
247
+ }
248
+ if (stat.size > MAX_READ_FILE_SIZE) {
249
+ return { error: `File too large (${(stat.size / 1024 / 1024).toFixed(1)}MB, max 10MB). Use offset and limit for range reading.` };
250
+ }
251
+ const rawBuf = fs.readFileSync(filePath);
252
+ const cortexMDs = safeScanCortexMDs(filePath);
253
+ // Image detection — before text decode
254
+ const imageType = detectImageType(rawBuf);
255
+ if (imageType) {
256
+ const dims = extractImageDimensions(rawBuf, imageType);
257
+ return {
258
+ image: {
259
+ data: rawBuf.toString('base64'),
260
+ mimeType: imageType,
261
+ ...(dims ? { width: dims.width, height: dims.height } : {}),
262
+ originalSize: rawBuf.length,
263
+ },
264
+ cortexMDs,
265
+ };
266
+ }
267
+ // PDF detection — return as blob resource
268
+ if (rawBuf.length >= 4 && rawBuf[0] === 0x25 && rawBuf[1] === 0x50 && rawBuf[2] === 0x44 && rawBuf[3] === 0x46) {
269
+ return { pdf: { data: rawBuf.toString('base64'), originalSize: rawBuf.length }, cortexMDs };
270
+ }
271
+ // Text path (unchanged)
272
+ const encoding = detectEncoding(rawBuf);
273
+ const content = rawBuf.toString(encoding);
274
+ const lines = content.split('\n');
275
+ const offset = params.offset || 0;
276
+ const limit = params.limit || DEFAULT_READ_LINES;
277
+ const sliced = lines.slice(offset, offset + limit);
278
+ const numbered = sliced.map((line, i) => `${offset + i + 1}\t${line}`).join('\n');
279
+ // Word-count self-bounds — read never persists to file, returns error instead
280
+ const wordCount = countWords(numbered);
281
+ if (wordCount > MAX_READ_WORDS) {
282
+ const suggestedLimit = Math.max(1, Math.floor(limit * (MAX_READ_WORDS / wordCount) * 0.9));
283
+ return {
284
+ error: `File content too large (~${wordCount} words, limit is ${MAX_READ_WORDS}). ` +
285
+ `Use offset and limit for range reading. Total lines: ${lines.length}. ` +
286
+ `Suggested: limit=${suggestedLimit} to stay within bounds.`,
287
+ };
288
+ }
289
+ return { content: numbered, cortexMDs };
290
+ }
291
+ catch (err) {
292
+ return { error: err.message };
293
+ }
294
+ }
295
+ // --- Tool: Write ---
296
+ // Diff snapshot helpers: capture pre-write/edit content for net-diff reconstruction in mcp-server.
297
+ // 1 MiB cap + NUL-byte guard keeps RPC payloads bounded; oversize/binary => null + truncated flag.
298
+ const DIFF_SNAPSHOT_MAX_BYTES = 1024 * 1024;
299
+ function captureOriginalFile(filePath) {
300
+ try {
301
+ if (!fs.existsSync(filePath))
302
+ return { originalFile: null, originalFileTruncated: false };
303
+ const stat = fs.statSync(filePath);
304
+ if (!stat.isFile())
305
+ return { originalFile: null, originalFileTruncated: false };
306
+ if (stat.size > DIFF_SNAPSHOT_MAX_BYTES)
307
+ return { originalFile: null, originalFileTruncated: true };
308
+ const buf = fs.readFileSync(filePath);
309
+ if (buf.includes(0))
310
+ return { originalFile: null, originalFileTruncated: true };
311
+ return { originalFile: buf.toString('utf8'), originalFileTruncated: false };
312
+ }
313
+ catch {
314
+ return { originalFile: null, originalFileTruncated: false };
315
+ }
316
+ }
317
+ function handleWrite(params) {
318
+ try {
319
+ const filePath = normalizePath(params.file_path);
320
+ if (!path.isAbsolute(filePath)) {
321
+ return { error: 'file_path must be absolute' };
322
+ }
323
+ const dir = path.dirname(filePath);
324
+ fs.mkdirSync(dir, { recursive: true });
325
+ let content = params.content;
326
+ // Snapshot pre-write content (if any) for net-diff reconstruction upstream.
327
+ const snapshot = captureOriginalFile(filePath);
328
+ // Preserve existing file's line ending style
329
+ if (fs.existsSync(filePath)) {
330
+ try {
331
+ const existing = fs.readFileSync(filePath, 'utf8');
332
+ const lineEnding = detectLineEnding(existing);
333
+ if (lineEnding === '\r\n') {
334
+ content = content.replace(/\r\n/g, '\n').replace(/\n/g, '\r\n');
335
+ }
336
+ }
337
+ catch { }
338
+ }
339
+ fs.writeFileSync(filePath, content, 'utf8');
340
+ const newContentTruncated = Buffer.byteLength(content, 'utf8') > DIFF_SNAPSHOT_MAX_BYTES;
341
+ return {
342
+ success: true,
343
+ cortexMDs: safeScanCortexMDs(filePath),
344
+ originalFile: snapshot.originalFile,
345
+ originalFileTruncated: snapshot.originalFileTruncated,
346
+ newContent: newContentTruncated ? undefined : content,
347
+ newContentTruncated,
348
+ };
349
+ }
350
+ catch (err) {
351
+ return { error: err.message };
352
+ }
353
+ }
354
+ // --- Tool: Edit ---
355
+ function handleEdit(params) {
356
+ try {
357
+ const filePath = normalizePath(params.file_path);
358
+ if (!path.isAbsolute(filePath)) {
359
+ return { error: 'file_path must be absolute' };
360
+ }
361
+ const rawBuf = fs.readFileSync(filePath);
362
+ const encoding = detectEncoding(rawBuf);
363
+ const rawContent = rawBuf.toString(encoding);
364
+ const originalLineEnding = detectLineEnding(rawContent);
365
+ // Normalize to \n for matching
366
+ const content = rawContent.replace(/\r\n/g, '\n');
367
+ const oldStr = (params.old_string || '').replace(/\r\n/g, '\n');
368
+ const newStr = (params.new_string || '').replace(/\r\n/g, '\n');
369
+ if (!oldStr) {
370
+ return { error: 'old_string is required' };
371
+ }
372
+ // Snapshot the pre-edit content (normalized to \n) for net-diff reconstruction upstream.
373
+ // 1 MiB cap + NUL-byte guard mirrors captureOriginalFile to keep RPC payloads bounded.
374
+ const oversize = rawBuf.length > DIFF_SNAPSHOT_MAX_BYTES;
375
+ const isBinary = rawBuf.includes(0);
376
+ const originalFile = (oversize || isBinary) ? null : content;
377
+ const originalFileTruncated = oversize || isBinary;
378
+ const buildResult = (newContentNorm) => {
379
+ const newContentTruncated = originalFileTruncated || Buffer.byteLength(newContentNorm, 'utf8') > DIFF_SNAPSHOT_MAX_BYTES;
380
+ return {
381
+ success: true,
382
+ cortexMDs: safeScanCortexMDs(filePath),
383
+ originalFile,
384
+ originalFileTruncated,
385
+ newContent: newContentTruncated ? undefined : newContentNorm,
386
+ newContentTruncated,
387
+ };
388
+ };
389
+ if (params.replace_all) {
390
+ if (!content.includes(oldStr)) {
391
+ return { error: 'old_string not found in file' };
392
+ }
393
+ const result = content.split(oldStr).join(newStr);
394
+ const final = originalLineEnding === '\r\n' ? result.replace(/\n/g, '\r\n') : result;
395
+ fs.writeFileSync(filePath, final, encoding);
396
+ return buildResult(result);
397
+ }
398
+ // Uniqueness check
399
+ const firstIdx = content.indexOf(oldStr);
400
+ if (firstIdx === -1) {
401
+ return { error: 'old_string not found in file' };
402
+ }
403
+ const secondIdx = content.indexOf(oldStr, firstIdx + 1);
404
+ if (secondIdx !== -1) {
405
+ return { error: 'old_string is not unique in file (found at least 2 occurrences). Provide more context to make it unique, or use replace_all.' };
406
+ }
407
+ // Functional replace avoids $& / $' / $` interpretation
408
+ const result = content.replace(oldStr, () => newStr);
409
+ const final = originalLineEnding === '\r\n' ? result.replace(/\n/g, '\r\n') : result;
410
+ fs.writeFileSync(filePath, final, encoding);
411
+ return buildResult(result);
412
+ }
413
+ catch (err) {
414
+ return { error: err.message };
415
+ }
416
+ }
417
+ // --- Tool: Glob ---
418
+ const GLOB_MAX_RESULTS = 500;
419
+ const VCS_DIRS = new Set(['.git', '.svn', '.hg', 'node_modules', '__pycache__', '.tox', '.mypy_cache']);
420
+ async function handleGlob(params) {
421
+ try {
422
+ const pattern = params.pattern;
423
+ const cwd = normalizePath(params.path || (PLATFORM === 'win32' ? 'C:\\' : process.cwd()));
424
+ if (!fs.existsSync(cwd)) {
425
+ return { error: `Directory not found: ${cwd}` };
426
+ }
427
+ // Safe glob via bash positional args — no shell injection.
428
+ // $2 undergoes: parameter expansion -> word splitting -> pathname expansion.
429
+ // Command substitution does NOT happen on expanded parameter values.
430
+ const limit = GLOB_MAX_RESULTS + 1;
431
+ const result = await spawnCommand('bash', [
432
+ '-c',
433
+ `shopt -s globstar nullglob 2>/dev/null; cd -- "$1" 2>/dev/null || exit 1; i=0; for f in $2; do echo "$f"; i=$((i+1)); [ $i -ge ${limit} ] && break; done`,
434
+ '--',
435
+ cwd,
436
+ pattern,
437
+ ], 30000);
438
+ if (result.exitCode !== 0 && !result.stdout.trim()) {
439
+ return { files: [], truncated: false };
440
+ }
441
+ let files = result.stdout.trim().split('\n').filter(Boolean);
442
+ const truncated = files.length > GLOB_MAX_RESULTS;
443
+ if (truncated)
444
+ files = files.slice(0, GLOB_MAX_RESULTS);
445
+ // Convert to absolute paths
446
+ files = files.map(f => path.isAbsolute(f) ? f : path.resolve(cwd, f));
447
+ // Filter out VCS/noise directories
448
+ files = files.filter(f => {
449
+ const parts = path.relative(cwd, f).split(path.sep);
450
+ return !parts.some(p => VCS_DIRS.has(p));
451
+ });
452
+ return { files, truncated };
453
+ }
454
+ catch (err) {
455
+ return { error: err.message };
456
+ }
457
+ }
458
+ // --- Tool: Grep ---
459
+ const GREP_VCS_EXCLUDES = ['.git', '.svn', '.hg', 'node_modules', '__pycache__'];
460
+ function buildRgArgs(params) {
461
+ const args = [];
462
+ const mode = params.output_mode || 'files_with_matches';
463
+ if (mode === 'files_with_matches') {
464
+ args.push('-l');
465
+ }
466
+ else if (mode === 'count') {
467
+ args.push('-c');
468
+ }
469
+ else {
470
+ // content mode
471
+ if (params['-n'] !== false)
472
+ args.push('-n');
473
+ if (params['-A'] != null)
474
+ args.push('-A', String(params['-A']));
475
+ if (params['-B'] != null)
476
+ args.push('-B', String(params['-B']));
477
+ const ctx = params['-C'] ?? params.context;
478
+ if (ctx != null)
479
+ args.push('-C', String(ctx));
480
+ }
481
+ if (params['-i'])
482
+ args.push('-i');
483
+ if (params.multiline)
484
+ args.push('-U', '--multiline-dotall');
485
+ if (params.glob)
486
+ args.push('--glob', params.glob);
487
+ if (params.type)
488
+ args.push('--type', params.type);
489
+ // VCS directory exclusion
490
+ for (const dir of GREP_VCS_EXCLUDES) {
491
+ args.push('--glob', `!${dir}`);
492
+ }
493
+ // Protect against minified/base64 long lines
494
+ args.push('--max-columns', '500');
495
+ // -- prevents pattern from being interpreted as an rg flag
496
+ args.push('--', params.pattern);
497
+ if (params.path)
498
+ args.push(normalizePath(params.path));
499
+ return args;
500
+ }
501
+ async function handleGrepFallback(params) {
502
+ const args = ['-rn'];
503
+ const mode = params.output_mode || 'files_with_matches';
504
+ if (mode === 'files_with_matches')
505
+ args.push('-l');
506
+ else if (mode === 'count')
507
+ args.push('-c');
508
+ if (params['-i'])
509
+ args.push('-i');
510
+ args.push('--', params.pattern);
511
+ args.push(normalizePath(params.path || '.'));
512
+ const result = await spawnCommand('grep', args, 30000);
513
+ return { output: result.stdout };
514
+ }
515
+ async function handleGrep(params) {
516
+ try {
517
+ const rgArgs = buildRgArgs(params);
518
+ const result = await spawnCommand('rg', rgArgs, 30000);
519
+ // rg exit codes: 0=matches, 1=no matches, 2=error
520
+ // exitCode 127 = rg binary not found (from our error handler)
521
+ if (result.exitCode === 127 || result.stderr.includes('not found')) {
522
+ return handleGrepFallback(params);
523
+ }
524
+ if (result.exitCode === 2) {
525
+ return { error: result.stderr.trim() || 'grep search error' };
526
+ }
527
+ let output = result.stdout;
528
+ // Apply offset and head_limit pagination
529
+ const headLimit = params.head_limit === 0 ? Infinity : (params.head_limit ?? 250);
530
+ const offset = params.offset ?? 0;
531
+ if (output && (offset > 0 || headLimit < Infinity)) {
532
+ const lines = output.split('\n');
533
+ const sliced = lines.slice(offset, offset + headLimit);
534
+ const remaining = lines.length - offset - sliced.length;
535
+ output = sliced.join('\n');
536
+ if (remaining > 0) {
537
+ output += `\n[... ${remaining} more entries, use offset to paginate]`;
538
+ }
539
+ }
540
+ return { output: output || '' };
541
+ }
542
+ catch (err) {
543
+ return { error: err.message };
544
+ }
545
+ }
546
+ // --- Command dispatcher ---
547
+ async function handleCommand(action, params) {
548
+ switch (action) {
549
+ case 'bash': {
550
+ const timeout = Math.min(params.timeout || 120000, 600000);
551
+ if (params.run_in_background) {
552
+ const { pid } = execBashBackground(params.command);
553
+ return {
554
+ success: true,
555
+ data: { stdout: `Background process started with PID ${pid}`, stderr: '', exitCode: 0 },
556
+ };
557
+ }
558
+ const result = await execBash(params.command, timeout);
559
+ return { success: true, data: result };
560
+ }
561
+ case 'read': {
562
+ const result = handleRead(params);
563
+ if (result.error)
564
+ return { success: false, error: result.error };
565
+ return { success: true, data: result };
566
+ }
567
+ case 'write': {
568
+ const result = handleWrite(params);
569
+ if (result.error)
570
+ return { success: false, error: result.error };
571
+ return { success: true, data: result };
572
+ }
573
+ case 'edit': {
574
+ const result = handleEdit(params);
575
+ if (result.error)
576
+ return { success: false, error: result.error };
577
+ return { success: true, data: result };
578
+ }
579
+ case 'glob': {
580
+ const result = await handleGlob(params);
581
+ if (result.error)
582
+ return { success: false, error: result.error };
583
+ return { success: true, data: result };
584
+ }
585
+ case 'grep': {
586
+ const result = await handleGrep(params);
587
+ if (result.error)
588
+ return { success: false, error: result.error };
589
+ return { success: true, data: result };
590
+ }
591
+ default:
592
+ return { success: false, error: `Unknown action: ${action}` };
593
+ }
594
+ }
595
+ // --- WebSocket connection ---
596
+ let ws = null;
597
+ let heartbeatTimer = null;
598
+ let reconnectDelay = 1000;
599
+ const MAX_RECONNECT_DELAY = 30000;
600
+ function connect() {
601
+ const url = `ws://${SERVER_HOST}:${SERVER_PORT}`;
602
+ log.info(`Connecting to ${url} as "${DEVICE_NAME}" (${PLATFORM})...`);
603
+ ws = new WebSocket(url);
604
+ ws.on('open', () => {
605
+ log.info(`Connected to server`);
606
+ reconnectDelay = 1000;
607
+ const capabilities = detectCapabilities();
608
+ ws.send(JSON.stringify({
609
+ type: 'hello',
610
+ device: DEVICE_NAME,
611
+ platform: PLATFORM,
612
+ capabilities,
613
+ }));
614
+ if (heartbeatTimer)
615
+ clearInterval(heartbeatTimer);
616
+ heartbeatTimer = setInterval(() => {
617
+ if (ws && ws.readyState === WebSocket.OPEN) {
618
+ ws.send(JSON.stringify({
619
+ type: 'heartbeat',
620
+ device: DEVICE_NAME,
621
+ timestamp: Date.now(),
622
+ }));
623
+ }
624
+ }, HEARTBEAT_INTERVAL_MS);
625
+ });
626
+ ws.on('message', async (raw) => {
627
+ let msg;
628
+ try {
629
+ msg = JSON.parse(raw.toString());
630
+ }
631
+ catch {
632
+ return;
633
+ }
634
+ if (msg.type === 'command' && msg.commandId) {
635
+ // Capture ws reference before async gap to prevent null dereference
636
+ const currentWs = ws;
637
+ log.info(`Executing ${msg.action}: ${JSON.stringify(msg.params).substring(0, 100)}`);
638
+ try {
639
+ const result = await handleCommand(msg.action, msg.params || {});
640
+ if (currentWs && currentWs.readyState === WebSocket.OPEN) {
641
+ currentWs.send(JSON.stringify({
642
+ type: 'result',
643
+ commandId: msg.commandId,
644
+ ...result,
645
+ }));
646
+ }
647
+ }
648
+ catch (err) {
649
+ if (currentWs && currentWs.readyState === WebSocket.OPEN) {
650
+ currentWs.send(JSON.stringify({
651
+ type: 'result',
652
+ commandId: msg.commandId,
653
+ success: false,
654
+ error: err.message,
655
+ }));
656
+ }
657
+ }
658
+ }
659
+ });
660
+ ws.on('close', (code, reason) => {
661
+ log.info(`Disconnected (code=${code}, reason=${reason?.toString() || 'none'})`);
662
+ cleanup();
663
+ if (code === 4002) {
664
+ log.info('Server rejected connection (device already connected). Exiting.');
665
+ process.exit(1);
666
+ }
667
+ scheduleReconnect();
668
+ });
669
+ ws.on('error', (err) => {
670
+ log.error(`WebSocket error: ${err.message}`);
671
+ });
672
+ }
673
+ function cleanup() {
674
+ if (heartbeatTimer) {
675
+ clearInterval(heartbeatTimer);
676
+ heartbeatTimer = null;
677
+ }
678
+ ws = null;
679
+ }
680
+ function scheduleReconnect() {
681
+ log.info(`Reconnecting in ${reconnectDelay / 1000}s...`);
682
+ setTimeout(() => {
683
+ reconnectDelay = Math.min(reconnectDelay * 2, MAX_RECONNECT_DELAY);
684
+ connect();
685
+ }, reconnectDelay);
686
+ }
687
+ // --- Graceful shutdown ---
688
+ function shutdown() {
689
+ log.info('Shutting down...');
690
+ if (heartbeatTimer)
691
+ clearInterval(heartbeatTimer);
692
+ if (ws) {
693
+ try {
694
+ ws.close(1000, 'Client shutting down');
695
+ }
696
+ catch { }
697
+ }
698
+ process.exit(0);
699
+ }
700
+ process.on('SIGINT', shutdown);
701
+ process.on('SIGTERM', shutdown);
702
+ // --- Start ---
703
+ log.info(`Starting: device="${DEVICE_NAME}", platform="${PLATFORM}", server=${SERVER_HOST}:${SERVER_PORT}`);
704
+ connect();