packages feed

pms-infra-agent-socket (empty) → 0.0.1.0

raw patch · 11 files changed

+1744/−0 lines, 11 filesdep +aesondep +asyncdep +base

Dependencies added: aeson, async, base, base16-bytestring, bytestring, conduit, data-default, directory, fast-logger, filepath, hspec, hspec-discover, lens, monad-logger, mtl, network, pms-domain-model, pms-infra-agent-socket, safe-exceptions, stm, text, transformers

Files

+ CHANGELOG.md view
@@ -0,0 +1,5 @@+# Revision history for pms-infra-agent-socket++## 0.0.1.0 -- 2026-05-31++* First version.
+ LICENSE view
@@ -0,0 +1,202 @@++                                 Apache License+                           Version 2.0, January 2004+                        http://www.apache.org/licenses/++   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++   1. Definitions.++      "License" shall mean the terms and conditions for use, reproduction,+      and distribution as defined by Sections 1 through 9 of this document.++      "Licensor" shall mean the copyright owner or entity authorized by+      the copyright owner that is granting the License.++      "Legal Entity" shall mean the union of the acting entity and all+      other entities that control, are controlled by, or are under common+      control with that entity. For the purposes of this definition,+      "control" means (i) the power, direct or indirect, to cause the+      direction or management of such entity, whether by contract or+      otherwise, or (ii) ownership of fifty percent (50%) or more of the+      outstanding shares, or (iii) beneficial ownership of such entity.++      "You" (or "Your") shall mean an individual or Legal Entity+      exercising permissions granted by this License.++      "Source" form shall mean the preferred form for making modifications,+      including but not limited to software source code, documentation+      source, and configuration files.++      "Object" form shall mean any form resulting from mechanical+      transformation or translation of a Source form, including but+      not limited to compiled object code, generated documentation,+      and conversions to other media types.++      "Work" shall mean the work of authorship, whether in Source or+      Object form, made available under the License, as indicated by a+      copyright notice that is included in or attached to the work+      (an example is provided in the Appendix below).++      "Derivative Works" shall mean any work, whether in Source or Object+      form, that is based on (or derived from) the Work and for which the+      editorial revisions, annotations, elaborations, or other modifications+      represent, as a whole, an original work of authorship. For the purposes+      of this License, Derivative Works shall not include works that remain+      separable from, or merely link (or bind by name) to the interfaces of,+      the Work and Derivative Works thereof.++      "Contribution" shall mean any work of authorship, including+      the original version of the Work and any modifications or additions+      to that Work or Derivative Works thereof, that is intentionally+      submitted to Licensor for inclusion in the Work by the copyright owner+      or by an individual or Legal Entity authorized to submit on behalf of+      the copyright owner. For the purposes of this definition, "submitted"+      means any form of electronic, verbal, or written communication sent+      to the Licensor or its representatives, including but not limited to+      communication on electronic mailing lists, source code control systems,+      and issue tracking systems that are managed by, or on behalf of, the+      Licensor for the purpose of discussing and improving the Work, but+      excluding communication that is conspicuously marked or otherwise+      designated in writing by the copyright owner as "Not a Contribution."++      "Contributor" shall mean Licensor and any individual or Legal Entity+      on behalf of whom a Contribution has been received by Licensor and+      subsequently incorporated within the Work.++   2. Grant of Copyright License. Subject to the terms and conditions of+      this License, each Contributor hereby grants to You a perpetual,+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable+      copyright license to reproduce, prepare Derivative Works of,+      publicly display, publicly perform, sublicense, and distribute the+      Work and such Derivative Works in Source or Object form.++   3. Grant of Patent License. Subject to the terms and conditions of+      this License, each Contributor hereby grants to You a perpetual,+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable+      (except as stated in this section) patent license to make, have made,+      use, offer to sell, sell, import, and otherwise transfer the Work,+      where such license applies only to those patent claims licensable+      by such Contributor that are necessarily infringed by their+      Contribution(s) alone or by combination of their Contribution(s)+      with the Work to which such Contribution(s) was submitted. If You+      institute patent litigation against any entity (including a+      cross-claim or counterclaim in a lawsuit) alleging that the Work+      or a Contribution incorporated within the Work constitutes direct+      or contributory patent infringement, then any patent licenses+      granted to You under this License for that Work shall terminate+      as of the date such litigation is filed.++   4. Redistribution. You may reproduce and distribute copies of the+      Work or Derivative Works thereof in any medium, with or without+      modifications, and in Source or Object form, provided that You+      meet the following conditions:++      (a) You must give any other recipients of the Work or+          Derivative Works a copy of this License; and++      (b) You must cause any modified files to carry prominent notices+          stating that You changed the files; and++      (c) You must retain, in the Source form of any Derivative Works+          that You distribute, all copyright, patent, trademark, and+          attribution notices from the Source form of the Work,+          excluding those notices that do not pertain to any part of+          the Derivative Works; and++      (d) If the Work includes a "NOTICE" text file as part of its+          distribution, then any Derivative Works that You distribute must+          include a readable copy of the attribution notices contained+          within such NOTICE file, excluding those notices that do not+          pertain to any part of the Derivative Works, in at least one+          of the following places: within a NOTICE text file distributed+          as part of the Derivative Works; within the Source form or+          documentation, if provided along with the Derivative Works; or,+          within a display generated by the Derivative Works, if and+          wherever such third-party notices normally appear. The contents+          of the NOTICE file are for informational purposes only and+          do not modify the License. You may add Your own attribution+          notices within Derivative Works that You distribute, alongside+          or as an addendum to the NOTICE text from the Work, provided+          that such additional attribution notices cannot be construed+          as modifying the License.++      You may add Your own copyright statement to Your modifications and+      may provide additional or different license terms and conditions+      for use, reproduction, or distribution of Your modifications, or+      for any such Derivative Works as a whole, provided Your use,+      reproduction, and distribution of the Work otherwise complies with+      the conditions stated in this License.++   5. Submission of Contributions. Unless You explicitly state otherwise,+      any Contribution intentionally submitted for inclusion in the Work+      by You to the Licensor shall be under the terms and conditions of+      this License, without any additional terms or conditions.+      Notwithstanding the above, nothing herein shall supersede or modify+      the terms of any separate license agreement you may have executed+      with Licensor regarding such Contributions.++   6. Trademarks. This License does not grant permission to use the trade+      names, trademarks, service marks, or product names of the Licensor,+      except as required for reasonable and customary use in describing the+      origin of the Work and reproducing the content of the NOTICE file.++   7. Disclaimer of Warranty. Unless required by applicable law or+      agreed to in writing, Licensor provides the Work (and each+      Contributor provides its Contributions) on an "AS IS" BASIS,+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+      implied, including, without limitation, any warranties or conditions+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+      PARTICULAR PURPOSE. You are solely responsible for determining the+      appropriateness of using or redistributing the Work and assume any+      risks associated with Your exercise of permissions under this License.++   8. Limitation of Liability. In no event and under no legal theory,+      whether in tort (including negligence), contract, or otherwise,+      unless required by applicable law (such as deliberate and grossly+      negligent acts) or agreed to in writing, shall any Contributor be+      liable to You for damages, including any direct, indirect, special,+      incidental, or consequential damages of any character arising as a+      result of this License or out of the use or inability to use the+      Work (including but not limited to damages for loss of goodwill,+      work stoppage, computer failure or malfunction, or any and all+      other commercial damages or losses), even if such Contributor+      has been advised of the possibility of such damages.++   9. Accepting Warranty or Additional Liability. While redistributing+      the Work or Derivative Works thereof, You may choose to offer,+      and charge a fee for, acceptance of support, warranty, indemnity,+      or other liability obligations and/or rights consistent with this+      License. However, in accepting such obligations, You may act only+      on Your own behalf and on Your sole responsibility, not on behalf+      of any other Contributor, and only if You agree to indemnify,+      defend, and hold each Contributor harmless for any liability+      incurred by, or claims asserted against, such Contributor by reason+      of your accepting any such warranty or additional liability.++   END OF TERMS AND CONDITIONS++   APPENDIX: How to apply the Apache License to your work.++      To apply the Apache License to your work, attach the following+      boilerplate notice, with the fields enclosed by brackets "[]"+      replaced with your own identifying information. (Don't include+      the brackets!)  The text should be enclosed in the appropriate+      comment syntax for the file format. We also recommend that a+      file or class name and description of purpose be included on the+      same "printed page" as the copyright notice for easier+      identification within third-party archives.++   Copyright [yyyy] [name of copyright owner]++   Licensed under the Apache License, Version 2.0 (the "License");+   you may not use this file except in compliance with the License.+   You may obtain a copy of the License at++       http://www.apache.org/licenses/LICENSE-2.0++   Unless required by applicable law or agreed to in writing, software+   distributed under the License is distributed on an "AS IS" BASIS,+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+   See the License for the specific language governing permissions and+   limitations under the License.
+ README.md view
@@ -0,0 +1,127 @@+# pms-infra-agent-socket++----+## ⚠️ Caution++**Do not grant unrestricted control to AI.**  +Unsupervised use or misuse may lead to unintended consequences.  +All AI systems must remain strictly under human oversight and control.  +Use responsibly, with full awareness and at your own risk.  ++----+## 📘 Overview++**`pms-infra-agent-socket`** is a Haskell infrastructure library that provides AI agents with direct, low-level control over socket-based communication endpoints.++Unlike higher-level abstractions, this library exposes raw byte-stream access over both TCP/IP and Unix Domain Sockets, allowing agents to handle protocol-specific exchanges such as Telnet IAC negotiation, binary protocol framing, and real-time I/O monitoring with fine-grained control.++The library is a core component of the [`pty-mcp-server`](https://github.com/phoityne/pty-mcp-server) ecosystem and implements the `agent-socket-*` family of MCP tools.++---++## 🔧 Provided MCP Tools++### `agent-socket-open`+Opens a socket connection for subsequent read/write operations.  +Supports both **TCP** (`host` + `port`) and **Unix Domain Socket** (`file`) connections via a single tool.++- `host` — TCP host name or IP address  +- `port` — TCP service name or port number  +- `file` — Unix domain socket path (absolute path required on Windows)  ++Only one socket connection can be active at a time.++### `agent-socket-close`+Closes the active socket connection and releases all associated resources.++### `agent-socket-read`+Reads up to the specified number of bytes from the active socket connection and returns the data as a **UTF-8 string**.  +Returns an empty string if no data is available before timeout.++- `length` — Maximum number of bytes to read  ++> ⚠️ If the received data contains non-UTF-8 bytes (e.g., binary protocols, IAC bytes), use `agent-socket-read-byte` instead.++### `agent-socket-read-byte`+Reads up to the specified number of bytes from the active socket connection and returns the data as an **uppercase hex string** (e.g., `FF0A1B41`).  +Use this for binary protocols or when precise byte-level inspection is required.++- `length` — Maximum number of bytes to read  ++### `agent-socket-write`+Writes the specified **UTF-8 string** to the active socket connection.++- `data` — Text data to write  ++> ⚠️ Escape sequences such as `\r\n` in the string are sent as literal characters. To send exact byte sequences (e.g., CR+LF = `0D0A`), use `agent-socket-write-byte`.++### `agent-socket-write-byte`+Decodes the specified **hex string** and writes the resulting bytes to the active socket connection.  +Use this for binary protocols or when precise byte-level control is required.++- `data` — Uppercase hex string to decode and write (e.g., `DEADBEEF0D0A`)  ++---++## 💡 Usage Notes++### IAC / Telnet negotiation+Telnet IAC processing is the **responsibility of the agent**, not the library.  +Use `agent-socket-read-byte` and `agent-socket-write-byte` to handle IAC sequences at the byte level.++Example negotiation flow:+```+← FFFD18FFFD20FFFD23FFFD27   (Server: IAC DO TERMINAL-TYPE/SPEED/X-DISPLAY/NEW-ENVIRON)+→ FFFC18FFFC20FFFC23FFFC27   (Agent:  IAC WONT x4)+← FFFB03FFFD01FFFD1FFFFB05   (Server: IAC WILL SGA / DO ECHO / DO NAWS / WILL STATUS)+→ FFFD03FFFB01FFFC1FFFFD05   (Agent:  IAC DO SGA / WILL ECHO / WONT NAWS / DO STATUS)+← "localhost login: "         (Login prompt — read as UTF-8 string)+→ "phoityne\r\n"              (Username — send as bytes: 70686F6974796E650D0A)+← "Password: "                (Password prompt)+```++### Unix Domain Socket on Windows+Unix Domain Socket (`file` parameter) is supported on **Windows 10 build 1803 and later** at the OS level.  +However, the socket server side must be implemented in a runtime that supports `AF_UNIX` on Windows.++- **Python 3.13.7 (Windows)**: `socket.AF_UNIX` is unavailable unless **Developer Mode** is enabled.+- **PowerShell / .NET**: `System.Net.Sockets.UnixDomainSocketEndPoint` works without Developer Mode.+- **pty-mcp-server (Haskell)**: Confirmed working on Windows 11 via `Network.Socket` with `AF_UNIX`.++---++## 🏗️ Architecture++### Module Structure++```+PMS.Infra.Agent.Socket+├── DM.Type        -- Data type definitions (SocketData, AppData, tool parameter types)+├── DM.Constant    -- Constants+├── DS.Core        -- Core domain service logic+├── DS.Utility     -- Utility functions (TCP connect, Unix Domain Socket connect)+└── App.Control    -- Application control: tool dispatch and socket lifecycle management+```++### Key Design Points++- **Single active connection**: Only one socket can be open at a time per server instance. State is managed via `STM.TMVar`.+- **Dual connection mode**: `agent-socket-open` supports both TCP (`host`/`port`) and Unix Domain Socket (`file`) via a single unified interface.+- **Non-blocking reads**: Read operations return immediately with available data, allowing the agent to poll at its own pace.+- **Byte-level I/F**: In addition to UTF-8 string I/F, hex string I/F is provided for binary protocol handling. IAC processing and protocol framing are delegated to the agent.++---++## 📦 Dependencies++- [`pms-domain-model`](https://github.com/phoityne/pms-domain-model)++---++## 📜 Credits & License++- **Execution & Process Lead:** Claude Sonnet 4.6, Gemini 3 Flash, GPT-5.5+- **Direction & Policy:** phoityne+- **License:** Apache-2.0 — see [LICENSE](./LICENSE)++---
+ pms-infra-agent-socket.cabal view
@@ -0,0 +1,143 @@+cabal-version: 2.4+-- The cabal-version field refers to the version of the .cabal specification,+-- and can be different from the cabal-install (the tool) version and the+-- Cabal (the library) version you are using. As such, the Cabal (the library)+-- version used must be equal or greater than the version stated in this field.+-- Starting from the specification version 2.2, the cabal-version field must be+-- the first thing in the cabal file.++-- Initial package description 'pms-infra-agent-socket' generated by+-- 'cabal init'. For further documentation, see:+--   http://haskell.org/cabal/users-guide/+--+-- The name of the package.+name:               pms-infra-agent-socket++-- The package version.+-- See the Haskell package versioning policy (PVP) for standards+-- guiding when and how versions should be incremented.+-- https://pvp.haskell.org+-- PVP summary:     +-+------- breaking API changes+--                  | | +----- non-breaking API additions+--                  | | | +--- code changes with no API change+version:            0.0.1.0++-- A short (one-line) description of the package.+synopsis:           pms-infra-agent-socket++-- A longer description of the package.+description:        README.md++-- The license under which the package is released.+license:            Apache-2.0++-- The file containing the license text.+license-file:       LICENSE++-- The package author(s).+author:             phoityne.hs@gmail.com++-- An email address to which users can send suggestions, bug reports, and patches.+maintainer:         phoityne.hs@gmail.com++-- A copyright notice.+copyright:          2025-2026 phoityne.hs@gmail.com+category:           AI+build-type:         Simple+homepage:           https://github.com/phoityne/pms-infra-agent-socket+bug-reports:        https://github.com/phoityne/pms-infra-agent-socket/issues++-- Extra doc files to be distributed with the package, such as a CHANGELOG or a README.+extra-doc-files:    README.md,+                    CHANGELOG.md++-- Extra source files to be distributed with the package, such as examples, or a tutorial module.+-- extra-source-files:+++library+    -- Import common warning flags.+    ghc-options: -Wall -threaded++    -- Modules exported by the library.+    exposed-modules:  PMS.Infra.Agent.Socket.DM.Type,+                      PMS.Infra.Agent.Socket.DS.Utility,+                      PMS.Infra.Agent.Socket.DM.Constant,+                      PMS.Infra.Agent.Socket.App.Control,+                      PMS.Infra.Agent.Socket.DS.Core++    -- Modules included in this library but not exported.+    -- other-modules:++    -- LANGUAGE extensions used by modules in this package.+    -- other-extensions:++    -- Other library packages from which modules are imported.+    build-depends:    base >= 4.18 && < 5,+                      data-default,+                      monad-logger,+                      mtl,+                      lens,+                      text,+                      safe-exceptions,+                      fast-logger,+                      conduit,+                      bytestring,+                      transformers,+                      stm,+                      async,+                      network,+                      aeson,+                      base16-bytestring,+                      pms-domain-model++    -- Directories containing source files.+    hs-source-dirs:   src++    -- Base language which the package is written in.+    default-language: Haskell2010+    -- default-extensions:  LambdaCase++test-suite pms-infra-agent-socket-test+    -- Import common warning flags.+    ghc-options: -Wall -threaded++    -- Base language which the package is written in.+    default-language: Haskell2010++    -- Modules included in this executable, other than Main.+    other-modules:    PMS.Infra.Agent.Socket.App.ControlSpec++    -- LANGUAGE extensions used by modules in this package.+    -- other-extensions:++    -- The interface type and version of the test suite.+    type:             exitcode-stdio-1.0++    -- Directories containing source files.+    hs-source-dirs:   test++    -- The entrypoint to the test suite.+    main-is:          Spec.hs++    -- Test dependencies.+    build-depends:    base >= 4.18 && < 5,+                      hspec,+                      hspec-discover,+                      data-default,+                      stm,+                      monad-logger,+                      async,+                      lens,+                      bytestring,+                      aeson,+                      directory,+                      fast-logger,+                      filepath,+                      text,+                      network,+                      pms-domain-model,+                      pms-infra-agent-socket++    build-tool-depends:+      hspec-discover:hspec-discover
+ src/PMS/Infra/Agent/Socket/App/Control.hs view
@@ -0,0 +1,61 @@+{-# LANGUAGE LambdaCase #-}++module PMS.Infra.Agent.Socket.App.Control where++import System.IO+import qualified Control.Exception.Safe as E+import System.Log.FastLogger++import qualified PMS.Domain.Model.DM.Type as DM+import qualified PMS.Domain.Model.DS.Utility as DM++import PMS.Infra.Agent.Socket.DM.Type+import PMS.Infra.Agent.Socket.DM.Constant+import PMS.Infra.Agent.Socket.DS.Utility+import PMS.Infra.Agent.Socket.DS.Core++-- |+--+run :: DM.DomainContext ()+run domDat = do+  hPutStrLn stderr "[INFO] PMS.Infra.Agent.Socket.App.Control.run called."+  appDat <- defaultAppData+  runWithAppData appDat domDat++-- |+--+runWithAppData :: AppData -> DM.DomainContext ()+runWithAppData appDat domDat = do+  logDat <- DM.createLogger domDat _LOG_FILE_NAME+  runWithLogger logDat appDat domDat++-- |+--+runWithLogger :: (TimedFastLogger, IO ()) -> AppData -> DM.DomainContext ()+runWithLogger (logger, finalizeLogger) appDat domDat = +  flip E.catchAny exception+    $ flip E.finally finalize+    $ runApp domDat appDat logger app+    >>= \case+      Right x -> return x+      Left  e -> errorEnd e++  where+    finalize = do+      hPutStrLn stderr "-----------------------------------------------------------------------------"+      hPutStrLn stderr "[INFO] PMS.Infra.Agent.Socket.App.Control.run finalize called."+      finalizeLogger+      hPutStrLn stderr "-----------------------------------------------------------------------------"++    exception e = do+      hPutStrLn stderr "-----------------------------------------------------------------------------"+      hPutStrLn stderr "[ERROR] PMS.Infra.Agent.Socket.App.Control.run exception occurred."+      hPutStrLn stderr $ show e+      hPutStrLn stderr "-----------------------------------------------------------------------------"+      E.throwIO e++    errorEnd e = do+      hPutStrLn stderr "-----------------------------------------------------------------------------"+      hPutStrLn stderr "[ERROR] PMS.Infra.Agent.Socket.App.Control.run end with error."+      hPutStrLn stderr $ show e+      hPutStrLn stderr "-----------------------------------------------------------------------------"
+ src/PMS/Infra/Agent/Socket/DM/Constant.hs view
@@ -0,0 +1,12 @@+module PMS.Infra.Agent.Socket.DM.Constant where++--------------------------------------------------------------------------------+-- |+--+_LOG_FILE_NAME :: String+_LOG_FILE_NAME = "pms-infra-agent-socket.log"++-- |+--+_READ_BUFFER_SIZE :: Int+_READ_BUFFER_SIZE = 4096
+ src/PMS/Infra/Agent/Socket/DM/Type.hs view
@@ -0,0 +1,130 @@+{-# LANGUAGE TemplateHaskell #-}++module PMS.Infra.Agent.Socket.DM.Type where++import Control.Monad.Logger+import Control.Monad.Reader+import Control.Monad.Except+import Control.Lens+import Data.Default+import Data.Aeson.TH+import System.IO+import qualified Control.Concurrent.STM as STM++import qualified PMS.Domain.Model.DM.Type as DM+import qualified PMS.Domain.Model.DM.TH as DM++-- |+--+data AppData = AppData {+               _handleAppData :: STM.TMVar (Maybe Handle)+             , _lockAppData   :: STM.TMVar ()+             }++makeLenses ''AppData++defaultAppData :: IO AppData+defaultAppData = do+  mgrVar <- STM.newTMVarIO Nothing+  lock   <- STM.newTMVarIO ()+  return AppData {+           _handleAppData = mgrVar+         , _lockAppData   = lock+         }++-- |+--+type AppContext = ReaderT AppData (ReaderT DM.DomainData (ExceptT DM.ErrorData (LoggingT IO)))++-- |+--+type IOTask = IO++---------------------------------------------------------------------------------+-- | Arguments for agent-socket-open.+-- All fields are Maybe String so that the AI can omit irrelevant fields+-- depending on the connection type without causing a JSON parse error.+--+-- Routing rule (evaluated in socketOpenTask):+--   file = Just path              -> Unix Domain Socket connection+--   host = Just h, port = Just p  -> TCP connection+--   otherwise                     -> invalid arguments error+data SocketOpenToolParams =+  SocketOpenToolParams {+    _hostSocketOpenToolParams :: Maybe String+  , _portSocketOpenToolParams :: Maybe String+  , _fileSocketOpenToolParams :: Maybe String+  } deriving (Show, Read, Eq)++$(deriveJSON defaultOptions {fieldLabelModifier = DM.dropDataName "SocketOpenToolParams", omitNothingFields = True} ''SocketOpenToolParams)+makeLenses ''SocketOpenToolParams++instance Default SocketOpenToolParams where+  def = SocketOpenToolParams {+        _hostSocketOpenToolParams = Nothing+      , _portSocketOpenToolParams = Nothing+      , _fileSocketOpenToolParams = Nothing+      }++---------------------------------------------------------------------------------+-- | Arguments for agent-socket-read.+data SocketReadToolParams =+  SocketReadToolParams {+    _lengthSocketReadToolParams :: Int+  } deriving (Show, Read, Eq)++$(deriveJSON defaultOptions {fieldLabelModifier = DM.dropDataName "SocketReadToolParams", omitNothingFields = True} ''SocketReadToolParams)+makeLenses ''SocketReadToolParams++instance Default SocketReadToolParams where+  def = SocketReadToolParams {+        _lengthSocketReadToolParams = 0+      }++-- | Arguments for agent-socket-read-byte.+data SocketReadByteToolParams =+  SocketReadByteToolParams {+    _lengthSocketReadByteToolParams :: Int+  } deriving (Show, Read, Eq)++$(deriveJSON defaultOptions {fieldLabelModifier = DM.dropDataName "SocketReadByteToolParams", omitNothingFields = True} ''SocketReadByteToolParams)+makeLenses ''SocketReadByteToolParams++instance Default SocketReadByteToolParams where+  def = SocketReadByteToolParams {+        _lengthSocketReadByteToolParams = 0+      }+++---------------------------------------------------------------------------------+-- | Arguments for agent-socket-write.+-- appendNewline: Nothing or Just True (default) -> apply appendCRLF (auto-append newline).+--                Just False -> send string as-is without any modification.+data SocketWriteToolParams =+  SocketWriteToolParams {+    _dataSocketWriteToolParams        :: String+  , _appendNewlineSocketWriteToolParams :: Maybe Bool+  } deriving (Show, Read, Eq)++$(deriveJSON defaultOptions {fieldLabelModifier = DM.dropDataName "SocketWriteToolParams", omitNothingFields = True} ''SocketWriteToolParams)+makeLenses ''SocketWriteToolParams++instance Default SocketWriteToolParams where+  def = SocketWriteToolParams {+        _dataSocketWriteToolParams          = ""+      , _appendNewlineSocketWriteToolParams = def+      }++-- | Arguments for agent-socket-write-byte.+data SocketWriteByteToolParams =+  SocketWriteByteToolParams {+    _dataSocketWriteByteToolParams :: String+  } deriving (Show, Read, Eq)++$(deriveJSON defaultOptions {fieldLabelModifier = DM.dropDataName "SocketWriteByteToolParams", omitNothingFields = True} ''SocketWriteByteToolParams)+makeLenses ''SocketWriteByteToolParams++instance Default SocketWriteByteToolParams where+  def = SocketWriteByteToolParams {+        _dataSocketWriteByteToolParams = ""+      }
+ src/PMS/Infra/Agent/Socket/DS/Core.hs view
@@ -0,0 +1,402 @@+{-# LANGUAGE TemplateHaskell #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE LambdaCase #-}++module PMS.Infra.Agent.Socket.DS.Core where++import System.IO+import Control.Monad.Logger+import Control.Monad.IO.Class+import Control.Lens+import Control.Monad.Reader+import Control.Concurrent.Async+import qualified Control.Concurrent.STM as STM+import Data.Conduit+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import Control.Monad.Except+import qualified Control.Exception.Safe as E+import System.Exit+import Data.Aeson+import qualified Data.ByteString as BS++import qualified PMS.Domain.Model.DM.Type as DM+import qualified PMS.Domain.Model.DM.Constant as DM+import qualified PMS.Domain.Model.DS.Utility as DM++import PMS.Infra.Agent.Socket.DM.Type+import PMS.Infra.Agent.Socket.DM.Constant+import PMS.Infra.Agent.Socket.DS.Utility+++-- |+--+app :: AppContext ()+app = do+  $logDebugS DM._LOGTAG "app called."+  runConduit pipeline+  where+    pipeline :: ConduitM () Void AppContext ()+    pipeline = src .| cmd2task .| sink++---------------------------------------------------------------------------------+-- |+--+src :: ConduitT () DM.AgentSocketCommand AppContext ()+src = lift go >>= yield >> src+  where+    go :: AppContext DM.AgentSocketCommand+    go = do+      queue <- view DM.agentSocketQueueDomainData <$> lift ask+      liftIO $ STM.atomically $ STM.readTQueue queue++---------------------------------------------------------------------------------+-- |+--+cmd2task :: ConduitT DM.AgentSocketCommand (IOTask ()) AppContext ()+cmd2task = await >>= \case+  Just cmd -> flip catchError (errHdl cmd) $ do+    lift (go cmd) >>= yield >> cmd2task+  Nothing -> do+    $logWarnS DM._LOGTAG "cmd2task: await returns nothing. skip."+    cmd2task++  where+    errHdl :: DM.AgentSocketCommand -> String -> ConduitT DM.AgentSocketCommand (IOTask ()) AppContext ()+    errHdl socketCmd msg = do+      let jsonrpc = DM.getJsonRpcAgentSocketCommand socketCmd+      $logWarnS DM._LOGTAG $ T.pack $ "cmd2task: exception occurred. skip. " ++ msg+      lift $ errorToolsCallResponse jsonrpc $ "cmd2task: exception occurred. skip. " ++ msg+      cmd2task++    go :: DM.AgentSocketCommand -> AppContext (IOTask ())+    go (DM.AgentSocketEchoCommand      dat) = genEchoTask dat+    go (DM.AgentSocketOpenCommand      dat) = genSocketOpenTask dat      -- CR-04+    go (DM.AgentSocketCloseCommand     dat) = genSocketCloseTask dat     -- CR-05+    go (DM.AgentSocketReadCommand      dat) = genSocketReadTask dat      -- CR-06+    go (DM.AgentSocketReadByteCommand  dat) = genSocketReadByteTask dat  -- CR-06+    go (DM.AgentSocketWriteCommand     dat) = genSocketWriteTask dat     -- CR-07+    go (DM.AgentSocketWriteByteCommand dat) = genSocketWriteByteTask dat -- CR-07++---------------------------------------------------------------------------------+-- |+--+sink :: ConduitT (IOTask ()) Void AppContext ()+sink = await >>= \case+  Just req -> flip catchError errHdl $ do+    lift (go req) >> sink+  Nothing -> do+    $logWarnS DM._LOGTAG "sink: await returns nothing. skip."+    sink++  where+    errHdl :: String -> ConduitT (IOTask ()) Void AppContext ()+    errHdl msg = do+      $logWarnS DM._LOGTAG $ T.pack $ "sink: exception occurred. skip. " ++ msg+      sink++    go :: (IO ()) -> AppContext ()+    go task = do+      $logDebugS DM._LOGTAG "sink: start async."+      _ <- liftIOE $ async task+      $logDebugS DM._LOGTAG "sink: end async."+      return ()++---------------------------------------------------------------------------------+-- |+--+genEchoTask :: DM.AgentSocketEchoCommandData -> AppContext (IOTask ())+genEchoTask dat = do+  resQ <- view DM.responseQueueDomainData <$> lift ask+  let val = dat^.DM.valueAgentSocketEchoCommandData+  $logDebugS DM._LOGTAG $ T.pack $ "genEchoTask: echo : " ++ val+  return $ echoTask resQ dat val++-- |+--+echoTask :: STM.TQueue DM.McpResponse -> DM.AgentSocketEchoCommandData -> String -> IOTask ()+echoTask resQ cmdDat val = flip E.catchAny errHdl $ do+  hPutStrLn stderr $ "[INFO] PMS.Infra.Agent.Socket.DS.Core.echoTask run. " ++ val+  DM.toolsCallResponse resQ (cmdDat^.DM.jsonrpcAgentSocketEchoCommandData) ExitSuccess val ""+  hPutStrLn stderr "[INFO] PMS.Infra.Agent.Socket.DS.Core.echoTask end."+  where+    errHdl :: E.SomeException -> IO ()+    errHdl e = DM.toolsCallResponse resQ (cmdDat^.DM.jsonrpcAgentSocketEchoCommandData) (ExitFailure 1) "" (show e)++---------------------------------------------------------------------------------+-- | CR-04 / CR-12: agent-socket-open implementation with sandboxNetworks check.+-- The sandboxNetworks check is performed here in the gen function (AppContext),+-- consistent with how genProcRunTask performs the allowedCmds check.+-- Unix Domain Socket connections bypass the sandboxNetworks check.+genSocketOpenTask :: DM.AgentSocketOpenCommandData -> AppContext (IOTask ())+genSocketOpenTask cmdDat = do+  let argsBS = DM.unRawJsonByteString $ cmdDat^.DM.argumentsAgentSocketOpenCommandData+  resQ            <- view DM.responseQueueDomainData <$> lift ask+  handleTMVar     <- view handleAppData <$> ask+  sandboxNetworks <- view DM.sandboxNetworksDomainData <$> lift ask+  argsDat         <- liftEither $ eitherDecode argsBS+  let mFile = argsDat^.fileSocketOpenToolParams+      mHost = argsDat^.hostSocketOpenToolParams+      mPort = argsDat^.portSocketOpenToolParams+  -- CR-12: sandboxNetworks check for TCP connections only; Unix Domain Socket is exempt+  case (mFile, mHost) of+    (Nothing, Just host) -> liftIO (DM.checkSandboxNetworks sandboxNetworks host) >>= liftEither+    _                    -> return ()+  return $ socketOpenTask cmdDat resQ handleTMVar mFile mHost mPort++-- | Unix Domain Socket connection.+socketOpenTask :: DM.AgentSocketOpenCommandData+               -> STM.TQueue DM.McpResponse+               -> STM.TMVar (Maybe Handle)+               -> Maybe String+               -> Maybe String+               -> Maybe String+               -> IOTask ()+socketOpenTask cmdDat resQ handleTMVar (Just path) _ _ = flip E.catchAny errHdl $ do+  hPutStrLn stderr "[INFO] PMS.Infra.Agent.Socket.DS.Core.socketOpenTask (unix) start."+  STM.atomically (STM.takeTMVar handleTMVar) >>= \case+    Just h -> do+      STM.atomically $ STM.putTMVar handleTMVar (Just h)+      hPutStrLn stderr "[ERROR] socketOpenTask: socket is already connected."+      DM.toolsCallResponse resQ jsonRpc (ExitFailure 1) "" "socket is already connected."+    Nothing -> flip E.catchAny connErrHdl $ do+      hdl <- createUnixSocketHandle path+      STM.atomically $ STM.putTMVar handleTMVar (Just hdl)+      DM.toolsCallResponse resQ jsonRpc ExitSuccess ("socket connected to unix://" ++ path) ""+  hPutStrLn stderr "[INFO] PMS.Infra.Agent.Socket.DS.Core.socketOpenTask (unix) end."+  where+    jsonRpc = cmdDat^.DM.jsonrpcAgentSocketOpenCommandData+    errHdl :: E.SomeException -> IO ()+    errHdl e = DM.toolsCallResponse resQ jsonRpc (ExitFailure 1) "" (show e)+    connErrHdl :: E.SomeException -> IO ()+    connErrHdl e = do+      STM.atomically $ STM.putTMVar handleTMVar Nothing+      DM.toolsCallResponse resQ jsonRpc (ExitFailure 1) "" (show e)++-- | TCP connection. sandboxNetworks check is already done in genSocketOpenTask.+socketOpenTask cmdDat resQ handleTMVar Nothing (Just host) (Just port) = flip E.catchAny errHdl $ do+  hPutStrLn stderr "[INFO] PMS.Infra.Agent.Socket.DS.Core.socketOpenTask (tcp) start."+  STM.atomically (STM.takeTMVar handleTMVar) >>= \case+    Just h -> do+      STM.atomically $ STM.putTMVar handleTMVar (Just h)+      hPutStrLn stderr "[ERROR] socketOpenTask: socket is already connected."+      DM.toolsCallResponse resQ jsonRpc (ExitFailure 1) "" "socket is already connected."+    Nothing -> flip E.catchAny connErrHdl $ do+      hdl <- createSocketHandle host port+      STM.atomically $ STM.putTMVar handleTMVar (Just hdl)+      DM.toolsCallResponse resQ jsonRpc ExitSuccess ("socket connected to " ++ host ++ ":" ++ port) ""+  hPutStrLn stderr "[INFO] PMS.Infra.Agent.Socket.DS.Core.socketOpenTask (tcp) end."+  where+    jsonRpc = cmdDat^.DM.jsonrpcAgentSocketOpenCommandData+    errHdl :: E.SomeException -> IO ()+    errHdl e = DM.toolsCallResponse resQ jsonRpc (ExitFailure 1) "" (show e)+    connErrHdl :: E.SomeException -> IO ()+    connErrHdl e = do+      STM.atomically $ STM.putTMVar handleTMVar Nothing+      DM.toolsCallResponse resQ jsonRpc (ExitFailure 1) "" (show e)++-- | Invalid arguments (all other patterns).+socketOpenTask cmdDat resQ _ _ _ _ = do+  hPutStrLn stderr "[ERROR] PMS.Infra.Agent.Socket.DS.Core.socketOpenTask: invalid arguments."+  DM.toolsCallResponse resQ jsonRpc (ExitFailure 1) "" "invalid arguments: specify file, or host and port."+  where+    jsonRpc = cmdDat^.DM.jsonrpcAgentSocketOpenCommandData++---------------------------------------------------------------------------------+-- |+--+genSocketCloseTask :: DM.AgentSocketCloseCommandData -> AppContext (IOTask ())+genSocketCloseTask dat = do+  $logDebugS DM._LOGTAG $ T.pack $ "genSocketCloseTask called. "+  handleTMVar <- view handleAppData <$> ask+  resQ <- view DM.responseQueueDomainData <$> lift ask+  return $ socketCloseTask dat resQ handleTMVar++-- |+--+socketCloseTask :: DM.AgentSocketCloseCommandData+                -> STM.TQueue DM.McpResponse+                -> STM.TMVar (Maybe Handle)+                -> IOTask ()+socketCloseTask cmdDat resQ handleTMVar = flip E.catchAny errHdl $ do+  hPutStrLn stderr $ "[INFO] PMS.Infra.Agent.Socket.DS.Core.socketCloseTask run. "+  let jsonRpc = cmdDat^.DM.jsonrpcAgentSocketCloseCommandData++  STM.atomically (STM.swapTMVar handleTMVar Nothing) >>= \case+    Nothing -> do+      hPutStrLn stderr "[ERROR] PMS.Infra.Agent.Socket.DS.Core.socketCloseTask: socket is not connected."+      DM.toolsCallResponse resQ jsonRpc (ExitFailure 1) "" "socket is not connected."+    Just hdl -> do+      hClose hdl+      DM.toolsCallResponse resQ jsonRpc ExitSuccess "" "socket is closed."+      hPutStrLn stderr "[INFO] PMS.Infra.Agent.Socket.DS.Core.socketCloseTask closeSocket."++  hPutStrLn stderr "[INFO] PMS.Infra.Agent.Socket.DS.Core.socketCloseTask end."++  where+    errHdl :: E.SomeException -> IO ()+    errHdl e = DM.toolsCallResponse resQ (cmdDat^.DM.jsonrpcAgentSocketCloseCommandData) (ExitFailure 1) "" (show e)++-- |+--+genSocketReadTask :: DM.AgentSocketReadCommandData -> AppContext (IOTask ())+genSocketReadTask cmdData = do+  let argsBS = DM.unRawJsonByteString $ cmdData^.DM.argumentsAgentSocketReadCommandData+  resQ        <- view DM.responseQueueDomainData <$> lift ask+  handleTMVar <- view handleAppData <$> ask+  argsDat     <- liftEither $ eitherDecode argsBS+  let size       = argsDat^.lengthSocketReadToolParams+      actualSize = min size _READ_BUFFER_SIZE+  return $ socketReadTask cmdData resQ handleTMVar actualSize++-- |+--+socketReadTask :: DM.AgentSocketReadCommandData+               -> STM.TQueue DM.McpResponse+               -> STM.TMVar (Maybe Handle)+               -> Int+               -> IOTask ()+socketReadTask cmdDat resQ handleTMVar size = flip E.catchAny errHdl $ do+  hPutStrLn stderr $ "[INFO] PMS.Infra.Agent.Socket.DS.Core.socketReadTask run. " ++ show size++  STM.atomically (STM.readTMVar handleTMVar) >>= \case+    Nothing -> do+      hPutStrLn stderr "[ERROR] PMS.Infra.Agent.Socket.DS.Core.socketReadTask: socket is not connected."+      DM.toolsCallResponse resQ jsonRpc (ExitFailure 1) "" "socket is not connected."+    Just hdl -> do+      output <- DM.readHandle hdl _SOCKET_READ_WAIT_MSEC size+      DM.toolsCallResponse resQ jsonRpc ExitSuccess (DM.bs2strUTF8 output) ""++  hPutStrLn stderr "[INFO] PMS.Infra.Agent.Socket.DS.Core.socketReadTask end."++  where+    jsonRpc = cmdDat^.DM.jsonrpcAgentSocketReadCommandData+    errHdl e = DM.toolsCallResponse resQ jsonRpc (ExitFailure 1) "" (show e)++-- |+--+genSocketReadByteTask :: DM.AgentSocketReadByteCommandData -> AppContext (IOTask ())+genSocketReadByteTask cmdData = do+  let argsBS = DM.unRawJsonByteString $ cmdData^.DM.argumentsAgentSocketReadByteCommandData+  resQ        <- view DM.responseQueueDomainData <$> lift ask+  handleTMVar <- view handleAppData <$> ask+  argsDat     <- liftEither $ eitherDecode argsBS+  let size       = argsDat^.lengthSocketReadByteToolParams+      actualSize = min size _READ_BUFFER_SIZE+  return $ socketReadByteTask cmdData resQ handleTMVar actualSize++-- |+--+socketReadByteTask :: DM.AgentSocketReadByteCommandData+                   -> STM.TQueue DM.McpResponse+                   -> STM.TMVar (Maybe Handle)+                   -> Int+                   -> IOTask ()+socketReadByteTask cmdDat resQ handleTMVar size = flip E.catchAny errHdl $ do+  hPutStrLn stderr $ "[INFO] PMS.Infra.Agent.Socket.DS.Core.socketReadByteTask run. " ++ show size++  STM.atomically (STM.readTMVar handleTMVar) >>= \case+    Nothing -> do+      hPutStrLn stderr "[ERROR] PMS.Infra.Agent.Socket.DS.Core.socketReadByteTask: socket is not connected."+      DM.toolsCallResponse resQ jsonRpc (ExitFailure 1) "" "socket is not connected."+    Just hdl -> do+      output <- DM.readHandle hdl _SOCKET_READ_WAIT_MSEC size+      DM.toolsCallResponse resQ jsonRpc ExitSuccess (DM.bytesToHex output) ""++  hPutStrLn stderr "[INFO] PMS.Infra.Agent.Socket.DS.Core.socketReadByteTask end."++  where+    jsonRpc = cmdDat^.DM.jsonrpcAgentSocketReadByteCommandData+    errHdl e = DM.toolsCallResponse resQ jsonRpc (ExitFailure 1) "" (show e)++-- |+--+_SOCKET_READ_WAIT_MSEC :: Int+_SOCKET_READ_WAIT_MSEC = 100++---------------------------------------------------------------------------------+-- | CR-07 / CR-12: agent-socket-write implementation with invalidPatterns check.+-- The invalidPatterns check is performed here in the gen function (AppContext),+-- consistent with how genProcRunTask performs the allowedCmds check.+genSocketWriteTask :: DM.AgentSocketWriteCommandData -> AppContext (IOTask ())+genSocketWriteTask cmdData = do+  let argsBS = DM.unRawJsonByteString $ cmdData^.DM.argumentsAgentSocketWriteCommandData+  resQ            <- view DM.responseQueueDomainData <$> lift ask+  handleTMVar     <- view handleAppData <$> ask+  invalidPatterns <- view DM.invalidPatternsDomainData <$> lift ask+  argsDat         <- liftEither $ eitherDecode argsBS+  let str           = argsDat^.dataSocketWriteToolParams+      appendNewline = argsDat^.appendNewlineSocketWriteToolParams+  -- CR-12: invalidPatterns check (pure check, consistent with eitherDecode validation)+  case DM.checkInvalidPatterns invalidPatterns str of+    Just pat -> throwError $+      "agent-socket-write: rejected. input matches invalidPatterns: " ++ show pat+    Nothing  -> return ()+  return $ socketWriteTask cmdData resQ handleTMVar str appendNewline++-- |+--+socketWriteTask :: DM.AgentSocketWriteCommandData+               -> STM.TQueue DM.McpResponse+               -> STM.TMVar (Maybe Handle)+               -> String+               -> Maybe Bool+               -> IOTask ()+socketWriteTask cmdDat resQ handleTMVar str appendNewline = flip E.catchAny errHdl $ do+  hPutStrLn stderr $ "[INFO] PMS.Infra.Agent.Socket.DS.Core.socketWriteTask run."++  STM.atomically (STM.readTMVar handleTMVar) >>= \case+    Nothing ->+      DM.toolsCallResponse resQ jsonRpc (ExitFailure 1) "" "socket is not connected."+    Just hdl -> do+      -- Apply appendCRLF (auto-append newline) unless appendNewline is explicitly False.+      let payload = if appendNewline == Just False+                      then str+                      else DM.appendCRLF str+          bs = TE.encodeUtf8 (T.pack payload)+      hPutStrLn stderr $ "PMS.Infra.Agent.Socket.DS.Core.socketWriteTask " ++ show bs+      DM.writeHandle hdl bs+      DM.toolsCallResponse resQ jsonRpc ExitSuccess "" ""++  hPutStrLn stderr "[INFO] PMS.Infra.Agent.Socket.DS.Core.socketWriteTask end."++  where+    jsonRpc = cmdDat^.DM.jsonrpcAgentSocketWriteCommandData+    errHdl e = DM.toolsCallResponse resQ jsonRpc (ExitFailure 1) "" (show e)++---------------------------------------------------------------------------------+-- | CR-07: agent-socket-write-byte implementation+--+genSocketWriteByteTask :: DM.AgentSocketWriteByteCommandData -> AppContext (IOTask ())+genSocketWriteByteTask cmdData = do+  let argsBS = DM.unRawJsonByteString $ cmdData^.DM.argumentsAgentSocketWriteByteCommandData+  resQ        <- view DM.responseQueueDomainData <$> lift ask+  handleTMVar <- view handleAppData <$> ask+  argsDat     <- liftEither $ eitherDecode argsBS+  let hex = argsDat^.dataSocketWriteByteToolParams+  bs          <- liftEither $ hexToBytes hex+  return $ socketWriteByteTask cmdData resQ handleTMVar bs++-- |+--+socketWriteByteTask :: DM.AgentSocketWriteByteCommandData+                   -> STM.TQueue DM.McpResponse+                   -> STM.TMVar (Maybe Handle)+                   -> BS.ByteString+                   -> IOTask ()+socketWriteByteTask cmdDat resQ handleTMVar bs = flip E.catchAny errHdl $ do+  hPutStrLn stderr $ "[INFO] PMS.Infra.Agent.Socket.DS.Core.socketWriteByteTask run."++  STM.atomically (STM.readTMVar handleTMVar) >>= \case+    Nothing ->+      DM.toolsCallResponse resQ jsonRpc (ExitFailure 1) "" "socket is not connected."+    Just hdl -> do+      hPutStrLn stderr $ "PMS.Infra.Agent.Socket.DS.Core.socketWriteByteTask " ++ show bs+      DM.writeHandle hdl bs+      DM.toolsCallResponse resQ jsonRpc ExitSuccess "" ""++  hPutStrLn stderr "[INFO] PMS.Infra.Agent.Socket.DS.Core.socketWriteByteTask end."++  where+    jsonRpc = cmdDat^.DM.jsonrpcAgentSocketWriteByteCommandData+    errHdl e = DM.toolsCallResponse resQ jsonRpc (ExitFailure 1) "" (show e)
+ src/PMS/Infra/Agent/Socket/DS/Utility.hs view
@@ -0,0 +1,103 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE LambdaCase #-}++module PMS.Infra.Agent.Socket.DS.Utility where++import Control.Lens+import System.IO+import System.Log.FastLogger+import qualified Control.Exception.Safe as E+import Control.Monad.IO.Class+import Control.Monad.Except+import Control.Monad.Reader+import qualified Control.Concurrent.STM as STM+import Network.Socket+import qualified Data.ByteString as BS+import qualified Data.ByteString.Base16 as B16+import qualified Data.ByteString.Char8 as C8+import Data.Char (toUpper)++import qualified PMS.Domain.Model.DM.Type as DM+import qualified PMS.Domain.Model.DS.Utility as DM+import PMS.Infra.Agent.Socket.DM.Type++-- |+--+runApp :: DM.DomainData -> AppData -> TimedFastLogger -> AppContext a -> IO (Either DM.ErrorData a)+runApp domDat appDat logger ctx =+  DM.runFastLoggerT domDat logger+    $ runExceptT+    $ flip runReaderT domDat+    $ runReaderT ctx appDat++-- |+--+liftIOE :: IO a -> AppContext a+liftIOE f = liftIO (go f) >>= liftEither+  where+    go :: IO b -> IO (Either String b)+    go x = E.catchAny (Right <$> x) errHdl++    errHdl :: E.SomeException -> IO (Either String a)+    errHdl = return . Left . show++---------------------------------------------------------------------------------+-- |+--+errorToolsCallResponse :: DM.JsonRpcRequest -> String -> AppContext ()+errorToolsCallResponse jsonRpc errStr = do+  let content = [ DM.McpToolsCallResponseResultContent "text" errStr ]+      result = DM.McpToolsCallResponseResult {+                  DM._contentMcpToolsCallResponseResult = content+                , DM._isErrorMcpToolsCallResponseResult = True+                }+      resDat = DM.McpToolsCallResponseData jsonRpc result+      res = DM.McpToolsCallResponse resDat++  resQ <- view DM.responseQueueDomainData <$> lift ask+  liftIOE $ STM.atomically $ STM.writeTQueue resQ res++---------------------------------------------------------------------------------+-- | Decode an uppercase/lowercase hex string to a ByteString.+-- Input is uppercased before decoding to tolerate mixed case (e.g. "000a1BFF").+-- Returns Left with an error message if the input is not valid hex.+hexToBytes :: String -> Either String BS.ByteString+hexToBytes hex =+  case B16.decode (C8.pack (map toUpper hex)) of+    Right bs  -> Right bs+    Left  err -> Left $ "hexToBytes: invalid hex string: " ++ err++-- | Convert a TCP host/port to a Handle.+-- The socket must not be used directly after socketToHandle.+createSocketHandle :: HostName -> ServiceName -> IO Handle+createSocketHandle host port = do+  sock <- createSocket host port+  hdl  <- socketToHandle sock ReadWriteMode+  hSetBuffering hdl NoBuffering+  return hdl++-- | Connect to a Unix Domain Socket path and return a Handle.+-- The socket must not be used directly after socketToHandle.+-- Supported on Windows 10 Build 17063+ and Windows 11 via AF_UNIX (network >= 3.1.3.0).+createUnixSocketHandle :: FilePath -> IO Handle+createUnixSocketHandle path = do+  sock <- socket AF_UNIX Stream defaultProtocol+  connect sock (SockAddrUnix path)+  hdl  <- socketToHandle sock ReadWriteMode+  hSetBuffering hdl NoBuffering+  return hdl++-- |+--+createSocket :: HostName -> ServiceName -> IO Socket+createSocket host port = do+  let hint  = Just defaultHints { addrSocketType = Stream }+      justH = Just host+      justP = Just port++  getAddrInfo hint justH justP >>= \case+    [] -> E.throwString "No suitable address found for the given host and port."+    (serverAddr:_) -> do+      sock <- socket (addrFamily serverAddr) (addrSocketType serverAddr) (addrProtocol serverAddr)+      connect sock (addrAddress serverAddr)+      return sock
+ test/PMS/Infra/Agent/Socket/App/ControlSpec.hs view
@@ -0,0 +1,558 @@+{-# LANGUAGE TemplateHaskell #-}+{-# LANGUAGE OverloadedStrings #-}++module PMS.Infra.Agent.Socket.App.ControlSpec (spec) where++import Test.Hspec+import Control.Concurrent.Async+import qualified Control.Concurrent.STM as STM+import Control.Lens+import Data.Default+import qualified Data.ByteString as BS+import qualified Data.Text as T+import qualified Data.Text.Encoding as TE+import System.Directory+import System.FilePath+import System.IO+import Network.Socket+import Network.Socket.ByteString (recv)+import System.Log.FastLogger+import qualified System.Log.FastLogger as FastLogger++import qualified PMS.Domain.Model.DM.Type as DM+import qualified PMS.Infra.Agent.Socket.App.Control as SUT+import qualified PMS.Infra.Agent.Socket.DM.Type as SUT+import qualified PMS.Infra.Agent.Socket.DS.Core as Core+import qualified PMS.Infra.Agent.Socket.DS.Utility as Util++-- |+--+data SpecContext = SpecContext {+                   _domainDataSpecContext :: DM.DomainData+                 , _appDataSpecContext :: SUT.AppData+                 }++makeLenses ''SpecContext++defaultSpecContext :: IO SpecContext+defaultSpecContext = do+  domDat <- DM.defaultDomainData+  appDat <- SUT.defaultAppData+  return SpecContext {+           _domainDataSpecContext = domDat+         , _appDataSpecContext    = appDat+         }++-- |+--+spec :: Spec+spec = do+  runIO $ putStrLn "Start Spec."+  beforeAll setUpOnce $+    afterAll tearDownOnce .+      beforeWith setUp .+        after tearDown $ run++-- |+--+setUpOnce :: IO SpecContext+setUpOnce = do+  putStrLn "[INFO] EXECUTED ONLY ONCE BEFORE ALL TESTS START."+  defaultSpecContext++-- |+--+tearDownOnce :: SpecContext -> IO ()+tearDownOnce _ = do+  putStrLn "[INFO] EXECUTED ONLY ONCE AFTER ALL TESTS FINISH."++-- |+--+setUp :: SpecContext -> IO SpecContext+setUp ctx = do+  putStrLn "[INFO] EXECUTED BEFORE EACH TEST STARTS."+  domDat <- DM.defaultDomainData+  appDat <- SUT.defaultAppData+  return ctx {+               _domainDataSpecContext = domDat+             , _appDataSpecContext    = appDat+             }++-- |+--+tearDown :: SpecContext -> IO ()+tearDown _ = do+  putStrLn "[INFO] EXECUTED AFTER EACH TEST FINISHES."++-- |+--+run :: SpecWith SpecContext+run = do+  describe "runWithAppData" $ do+    context "when echo command issued." $ do+      it "should call callback" $ \ctx -> do+        putStrLn "[INFO] EXECUTING THE FIRST TEST."++        let domDat = ctx^.domainDataSpecContext+            appDat = ctx^.appDataSpecContext+            cmdQ   = domDat^.DM.agentSocketQueueDomainData+            resQ   = domDat^.DM.responseQueueDomainData+            expect = "abc"+            jsonR  = def {DM._jsonrpcJsonRpcRequest = expect}+            argDat = DM.AgentSocketEchoCommandData jsonR expect+            args   = DM.AgentSocketEchoCommand argDat++        thId <- async $ SUT.runWithAppData appDat domDat++        STM.atomically $ STM.writeTQueue cmdQ args++        (DM.McpToolsCallResponse dat) <- STM.atomically $ STM.readTQueue resQ++        let actual = dat^.DM.jsonrpcMcpToolsCallResponseData^.DM.jsonrpcJsonRpcRequest+        actual `shouldBe` expect++        cancel thId++  ---------------------------------------------------------------------------+  -- CR-06: agent-socket-read / agent-socket-read-byte+  ---------------------------------------------------------------------------++  describe "TC-06-01: read without open" $ do+    context "when handleAppData is Nothing" $ do+      it "should return isError=True" $ \ctx -> do+        let domDat = ctx^.domainDataSpecContext+            appDat = ctx^.appDataSpecContext+            cmdDat = DM.AgentSocketReadCommandData+                       { DM._jsonrpcAgentSocketReadCommandData   = mkJsonRpc "agent-socket-read"+                       , DM._argumentsAgentSocketReadCommandData = DM.RawJsonByteString ""+                       }+        Core.socketReadTask cmdDat+                            (domDat^.DM.responseQueueDomainData)+                            (appDat^.SUT.handleAppData)+                            16+        (DM.McpToolsCallResponse dat) <- STM.atomically $ STM.readTQueue (domDat^.DM.responseQueueDomainData)+        isError dat `shouldBe` True+        firstContentText dat  `shouldBe` ""+        secondContentText dat `shouldBe` "socket is not connected."++  describe "TC-06-02: read returns UTF-8 string" $ do+    context "when handle has UTF-8 bytes" $ do+      it "should decode bytes as UTF-8 string" $ \ctx -> do+        let domDat = ctx^.domainDataSpecContext+            appDat = ctx^.appDataSpecContext+            payload = TE.encodeUtf8 $ T.pack "hello-\26085\26412\35486"+            cmdDat = DM.AgentSocketReadCommandData+                       { DM._jsonrpcAgentSocketReadCommandData   = mkJsonRpc "agent-socket-read"+                       , DM._argumentsAgentSocketReadCommandData = DM.RawJsonByteString ""+                       }+        withReadHandle "pms-agent-socket-read-utf8.txt" payload $ \hdl -> do+          _ <- STM.atomically $ STM.swapTMVar (appDat^.SUT.handleAppData) (Just hdl)+          Core.socketReadTask cmdDat+                              (domDat^.DM.responseQueueDomainData)+                              (appDat^.SUT.handleAppData)+                              64+          (DM.McpToolsCallResponse dat) <- STM.atomically $ STM.readTQueue (domDat^.DM.responseQueueDomainData)+          isError dat `shouldBe` False+          firstContentText dat `shouldBe` "hello-\26085\26412\35486"++  describe "TC-06-03: read-byte returns hex string" $ do+    context "when handle has binary bytes" $ do+      it "should encode bytes as uppercase hex string" $ \ctx -> do+        let domDat = ctx^.domainDataSpecContext+            appDat = ctx^.appDataSpecContext+            payload = BS.pack [0x00, 0x0A, 0x1B, 0xFF]+            cmdDat = DM.AgentSocketReadByteCommandData+                       { DM._jsonrpcAgentSocketReadByteCommandData   = mkJsonRpc "agent-socket-read-byte"+                       , DM._argumentsAgentSocketReadByteCommandData = DM.RawJsonByteString ""+                       }+        withReadHandle "pms-agent-socket-read-byte.bin" payload $ \hdl -> do+          _ <- STM.atomically $ STM.swapTMVar (appDat^.SUT.handleAppData) (Just hdl)+          Core.socketReadByteTask cmdDat+                                  (domDat^.DM.responseQueueDomainData)+                                  (appDat^.SUT.handleAppData)+                                  4+          (DM.McpToolsCallResponse dat) <- STM.atomically $ STM.readTQueue (domDat^.DM.responseQueueDomainData)+          isError dat `shouldBe` False+          firstContentText dat `shouldBe` "000A1BFF"++  describe "TC-06-04: read timeout or no data" $ do+    context "when handle has no data" $ do+      it "should return success with empty text" $ \ctx -> do+        let domDat = ctx^.domainDataSpecContext+            appDat = ctx^.appDataSpecContext+            cmdDat = DM.AgentSocketReadCommandData+                       { DM._jsonrpcAgentSocketReadCommandData   = mkJsonRpc "agent-socket-read"+                       , DM._argumentsAgentSocketReadCommandData = DM.RawJsonByteString ""+                       }+        withEmptySocketHandle $ \hdl -> do+          _ <- STM.atomically $ STM.swapTMVar (appDat^.SUT.handleAppData) (Just hdl)+          Core.socketReadTask cmdDat+                              (domDat^.DM.responseQueueDomainData)+                              (appDat^.SUT.handleAppData)+                              16+          (DM.McpToolsCallResponse dat) <- STM.atomically $ STM.readTQueue (domDat^.DM.responseQueueDomainData)+          isError dat `shouldBe` False+          firstContentText dat `shouldBe` ""++  ---------------------------------------------------------------------------+  -- CR-07: agent-socket-write / agent-socket-write-byte+  ---------------------------------------------------------------------------++  describe "TC-07-01: write without open" $ do+    context "when handleAppData is Nothing" $ do+      it "should return isError=True with 'socket is not connected.'" $ \ctx -> do+        let domDat = ctx^.domainDataSpecContext+            appDat = ctx^.appDataSpecContext+            cmdDat = DM.AgentSocketWriteCommandData+                       { DM._jsonrpcAgentSocketWriteCommandData   = mkJsonRpc "agent-socket-write"+                       , DM._argumentsAgentSocketWriteCommandData = DM.RawJsonByteString ""+                       }+        Core.socketWriteTask cmdDat+                             (domDat^.DM.responseQueueDomainData)+                             (appDat^.SUT.handleAppData)+                             "hello"+                             Nothing+        (DM.McpToolsCallResponse dat) <- STM.atomically $ STM.readTQueue (domDat^.DM.responseQueueDomainData)+        isError dat `shouldBe` True+        secondContentText dat `shouldBe` "socket is not connected."++  describe "TC-07-02: write UTF-8 string" $ do+    context "when socket is connected and data is a UTF-8 string" $ do+      it "should write UTF-8 encoded bytes to the server side" $ \ctx -> do+        let domDat = ctx^.domainDataSpecContext+            appDat = ctx^.appDataSpecContext+            str    = "hello-\26085\26412\35486"+            expect = TE.encodeUtf8 (T.pack str)+            cmdDat = DM.AgentSocketWriteCommandData+                       { DM._jsonrpcAgentSocketWriteCommandData   = mkJsonRpc "agent-socket-write"+                       , DM._argumentsAgentSocketWriteCommandData = DM.RawJsonByteString ""+                       }+        withConnectedPair $ \clientHdl serverSock -> do+          _ <- STM.atomically $ STM.swapTMVar (appDat^.SUT.handleAppData) (Just clientHdl)+          Core.socketWriteTask cmdDat+                               (domDat^.DM.responseQueueDomainData)+                               (appDat^.SUT.handleAppData)+                               str+                               (Just False)+          (DM.McpToolsCallResponse dat) <- STM.atomically $ STM.readTQueue (domDat^.DM.responseQueueDomainData)+          isError dat `shouldBe` False+          received <- recv serverSock (BS.length expect + 16)+          received `shouldBe` expect++  describe "TC-07-03: write-byte uppercase hex string" $ do+    context "when data is uppercase hex string" $ do+      it "should write decoded bytes to the server side" $ \ctx -> do+        let domDat = ctx^.domainDataSpecContext+            appDat = ctx^.appDataSpecContext+            hex    = "000A1BFF"+            expect = BS.pack [0x00, 0x0A, 0x1B, 0xFF]+            cmdDat = DM.AgentSocketWriteByteCommandData+                       { DM._jsonrpcAgentSocketWriteByteCommandData   = mkJsonRpc "agent-socket-write-byte"+                       , DM._argumentsAgentSocketWriteByteCommandData = DM.RawJsonByteString ""+                       }+        Right bs <- return $ Util.hexToBytes hex+        withConnectedPair $ \clientHdl serverSock -> do+          _ <- STM.atomically $ STM.swapTMVar (appDat^.SUT.handleAppData) (Just clientHdl)+          Core.socketWriteByteTask cmdDat+                                   (domDat^.DM.responseQueueDomainData)+                                   (appDat^.SUT.handleAppData)+                                   bs+          (DM.McpToolsCallResponse dat) <- STM.atomically $ STM.readTQueue (domDat^.DM.responseQueueDomainData)+          isError dat `shouldBe` False+          received <- recv serverSock 16+          received `shouldBe` expect++  describe "TC-07-04: write-byte lowercase/mixed-case hex string" $ do+    context "when data is lowercase or mixed-case hex string" $ do+      it "should write correctly decoded bytes to the server side" $ \ctx -> do+        let domDat = ctx^.domainDataSpecContext+            expect = BS.pack [0x00, 0x0A, 0x1B, 0xFF]+            hexes  = ["000a1bff", "000a1BFF"]+            cmdDat = DM.AgentSocketWriteByteCommandData+                       { DM._jsonrpcAgentSocketWriteByteCommandData   = mkJsonRpc "agent-socket-write-byte"+                       , DM._argumentsAgentSocketWriteByteCommandData = DM.RawJsonByteString ""+                       }+        mapM_ (\hex -> do+          Right bs <- return $ Util.hexToBytes hex+          appDat' <- SUT.defaultAppData+          withConnectedPair $ \clientHdl serverSock -> do+            _ <- STM.atomically $ STM.swapTMVar (appDat'^.SUT.handleAppData) (Just clientHdl)+            Core.socketWriteByteTask cmdDat+                                     (domDat^.DM.responseQueueDomainData)+                                     (appDat'^.SUT.handleAppData)+                                     bs+            (DM.McpToolsCallResponse dat) <- STM.atomically $ STM.readTQueue (domDat^.DM.responseQueueDomainData)+            isError dat `shouldBe` False+            received <- recv serverSock 16+            received `shouldBe` expect+          ) hexes++  describe "TC-07-05: write-byte invalid hex string" $ do+    context "when hex string contains non-hex characters" $ do+      it "should return Left with hexToBytes error in AppContext" $ \ctx -> do+        let domDat = ctx^.domainDataSpecContext+            appDat = ctx^.appDataSpecContext+            argsJson = "{\"data\":\"ZZZZ\"}"+            cmdDat = DM.AgentSocketWriteByteCommandData+                       { DM._jsonrpcAgentSocketWriteByteCommandData   = mkJsonRpc "agent-socket-write-byte"+                       , DM._argumentsAgentSocketWriteByteCommandData = DM.RawJsonByteString argsJson+                       }+        withStderrLogger $ \logger -> do+          result <- Util.runApp domDat appDat logger (Core.genSocketWriteByteTask cmdDat)+          case result of+            Left errMsg -> errMsg `shouldContain` "hexToBytes"+            Right _     -> expectationFailure "Expected Left (hexToBytes error) but got Right"++  ---------------------------------------------------------------------------+  -- TC-A: agent-socket-write — appendNewline default (omitted) appends \n+  ---------------------------------------------------------------------------+  describe "TC-A: agent-socket-write appendNewline default appends newline" $ do+    context "when appendNewline is Nothing (default True) and input has no trailing newline" $ do+      it "should append \\n to the transmitted bytes" $ \ctx -> do+        putStrLn "[INFO] TC-A start."+        let domDat = ctx^.domainDataSpecContext+            appDat = ctx^.appDataSpecContext+            str    = "hello"+            expect = TE.encodeUtf8 (T.pack (str ++ nativeLineEnding))+            cmdDat = DM.AgentSocketWriteCommandData+                       { DM._jsonrpcAgentSocketWriteCommandData   = mkJsonRpc "agent-socket-write"+                       , DM._argumentsAgentSocketWriteCommandData = DM.RawJsonByteString ""+                       }+        withConnectedPair $ \clientHdl serverSock -> do+          _ <- STM.atomically $ STM.swapTMVar (appDat^.SUT.handleAppData) (Just clientHdl)+          Core.socketWriteTask cmdDat+                               (domDat^.DM.responseQueueDomainData)+                               (appDat^.SUT.handleAppData)+                               str+                               Nothing+          (DM.McpToolsCallResponse dat) <- STM.atomically $ STM.readTQueue (domDat^.DM.responseQueueDomainData)+          isError dat `shouldBe` False+          received <- recv serverSock (BS.length expect + 4)+          received `shouldBe` expect++  ---------------------------------------------------------------------------+  -- TC-B: agent-socket-write — appendNewline=False suppresses newline+  ---------------------------------------------------------------------------+  describe "TC-B: agent-socket-write appendNewline=False suppresses newline" $ do+    context "when appendNewline is Just False" $ do+      it "should NOT append \\n; transmitted bytes equal raw input" $ \ctx -> do+        putStrLn "[INFO] TC-B start."+        let domDat = ctx^.domainDataSpecContext+            appDat = ctx^.appDataSpecContext+            str    = "hello"+            expect = TE.encodeUtf8 (T.pack str)  -- no newline+            cmdDat = DM.AgentSocketWriteCommandData+                       { DM._jsonrpcAgentSocketWriteCommandData   = mkJsonRpc "agent-socket-write"+                       , DM._argumentsAgentSocketWriteCommandData = DM.RawJsonByteString ""+                       }+        withConnectedPair $ \clientHdl serverSock -> do+          _ <- STM.atomically $ STM.swapTMVar (appDat^.SUT.handleAppData) (Just clientHdl)+          Core.socketWriteTask cmdDat+                               (domDat^.DM.responseQueueDomainData)+                               (appDat^.SUT.handleAppData)+                               str+                               (Just False)+          (DM.McpToolsCallResponse dat) <- STM.atomically $ STM.readTQueue (domDat^.DM.responseQueueDomainData)+          isError dat `shouldBe` False+          received <- recv serverSock (BS.length expect + 4)+          received `shouldBe` expect++  ---------------------------------------------------------------------------+  -- CR-12: invalidPatterns / sandboxNetworks tests+  ---------------------------------------------------------------------------++  -- TC-08: invalidPatterns - matching input -> isError=True (via runWithAppData)+  describe "TC-08: invalidPatterns - matching input is rejected" $ do+    context "when agent-socket-write input matches an invalidPatterns entry" $ do+      it "should return isError=True" $ \_ -> do+        putStrLn "[INFO] TC-08 start."+        domDat <- DM.defaultDomainData+        let domDat' = domDat { DM._invalidPatternsDomainData = ["rm", "shutdown"] }+        appDat <- SUT.defaultAppData+        thId   <- async $ SUT.runWithAppData appDat domDat'+        let cmdQ = domDat'^.DM.agentSocketQueueDomainData+            resQ = domDat'^.DM.responseQueueDomainData+            argsJson = "{\"data\":\"rm -rf /\"}"+            cmdDat = DM.AgentSocketWriteCommandData+                       { DM._jsonrpcAgentSocketWriteCommandData   = mkJsonRpc "agent-socket-write"+                       , DM._argumentsAgentSocketWriteCommandData = DM.RawJsonByteString argsJson+                       }+        STM.atomically $ STM.writeTQueue cmdQ (DM.AgentSocketWriteCommand cmdDat)+        (DM.McpToolsCallResponse dat) <- STM.atomically $ STM.readTQueue resQ+        isError dat `shouldBe` True+        cancel thId++  -- TC-09: invalidPatterns - non-matching input is allowed (via runWithAppData)+  describe "TC-09: invalidPatterns - non-matching input is allowed" $ do+    context "when agent-socket-write input does NOT match any invalidPatterns entry" $ do+      it "should return isError=False when socket is connected" $ \_ -> do+        putStrLn "[INFO] TC-09 start."+        domDat <- DM.defaultDomainData+        let domDat' = domDat { DM._invalidPatternsDomainData = ["rm", "shutdown"] }+        appDat <- SUT.defaultAppData+        thId   <- async $ SUT.runWithAppData appDat domDat'+        withConnectedPair $ \clientHdl _serverSock -> do+          _ <- STM.atomically $ STM.swapTMVar (appDat^.SUT.handleAppData) (Just clientHdl)+          let cmdQ = domDat'^.DM.agentSocketQueueDomainData+              resQ = domDat'^.DM.responseQueueDomainData+              argsJson = "{\"data\":\"echo hello\"}"+              cmdDat = DM.AgentSocketWriteCommandData+                         { DM._jsonrpcAgentSocketWriteCommandData   = mkJsonRpc "agent-socket-write"+                         , DM._argumentsAgentSocketWriteCommandData = DM.RawJsonByteString argsJson+                         }+          STM.atomically $ STM.writeTQueue cmdQ (DM.AgentSocketWriteCommand cmdDat)+          (DM.McpToolsCallResponse dat) <- STM.atomically $ STM.readTQueue resQ+          isError dat `shouldBe` False+        cancel thId++  -- TC-10: sandboxNetworks - empty list -> TCP open is rejected+  describe "TC-10: sandboxNetworks - empty list denies all TCP connections" $ do+    context "when sandboxNetworks is empty and TCP open is attempted" $ do+      it "should return Left (connection refused)" $ \_ -> do+        putStrLn "[INFO] TC-10 start."+        domDat <- DM.defaultDomainData+        let domDat' = domDat { DM._sandboxNetworksDomainData = [] }+        appDat <- SUT.defaultAppData+        let argsJson = "{\"host\":\"127.0.0.1\",\"port\":\"9999\"}"+            cmdDat = def+                       { DM._jsonrpcAgentSocketOpenCommandData   = mkJsonRpc "agent-socket-open"+                       , DM._argumentsAgentSocketOpenCommandData = DM.RawJsonByteString argsJson+                       }+        withStderrLogger $ \logger -> do+          result <- Util.runApp domDat' appDat logger (Core.genSocketOpenTask cmdDat)+          case result of+            Left errMsg -> errMsg `shouldContain` "sandboxNetworks is empty"+            Right _     -> expectationFailure "Expected Left but got Right"++  -- TC-11: sandboxNetworks - IP within range -> gen succeeds+  describe "TC-11: sandboxNetworks - IP within range allows TCP open" $ do+    context "when sandboxNetworks contains 127.0.0.0/8 and host is 127.0.0.1" $ do+      it "should not be rejected by sandboxNetworks check" $ \_ -> do+        putStrLn "[INFO] TC-11 start."+        domDat <- DM.defaultDomainData+        let domDat' = domDat { DM._sandboxNetworksDomainData = ["127.0.0.0/8"] }+        appDat <- SUT.defaultAppData+        let argsJson = "{\"host\":\"127.0.0.1\",\"port\":\"9999\"}"+            cmdDat = def+                       { DM._jsonrpcAgentSocketOpenCommandData   = mkJsonRpc "agent-socket-open"+                       , DM._argumentsAgentSocketOpenCommandData = DM.RawJsonByteString argsJson+                       }+        withStderrLogger $ \logger -> do+          result <- Util.runApp domDat' appDat logger (Core.genSocketOpenTask cmdDat)+          case result of+            Left errMsg -> errMsg `shouldNotContain` "outside sandboxNetworks"+            Right _     -> return ()++  -- TC-12: sandboxNetworks - IP outside range -> rejected+  describe "TC-12: sandboxNetworks - IP outside range denies TCP open" $ do+    context "when sandboxNetworks contains only 10.0.0.0/8 and host is 127.0.0.1" $ do+      it "should return Left (outside sandboxNetworks)" $ \_ -> do+        putStrLn "[INFO] TC-12 start."+        domDat <- DM.defaultDomainData+        let domDat' = domDat { DM._sandboxNetworksDomainData = ["10.0.0.0/8"] }+        appDat <- SUT.defaultAppData+        let argsJson = "{\"host\":\"127.0.0.1\",\"port\":\"9999\"}"+            cmdDat = def+                       { DM._jsonrpcAgentSocketOpenCommandData   = mkJsonRpc "agent-socket-open"+                       , DM._argumentsAgentSocketOpenCommandData = DM.RawJsonByteString argsJson+                       }+        withStderrLogger $ \logger -> do+          result <- Util.runApp domDat' appDat logger (Core.genSocketOpenTask cmdDat)+          case result of+            Left errMsg -> errMsg `shouldContain` "outside sandboxNetworks"+            Right _     -> expectationFailure "Expected Left (sandboxNetworks check) but got Right"++  -- TC-13: sandboxNetworks - Unix Domain Socket is exempt+  describe "TC-13: sandboxNetworks - Unix Domain Socket bypasses sandboxNetworks check" $ do+    context "when sandboxNetworks is empty but file is specified" $ do+      it "gen should return Right (sandboxNetworks bypassed)" $ \_ -> do+        putStrLn "[INFO] TC-13 start."+        domDat <- DM.defaultDomainData+        let domDat' = domDat { DM._sandboxNetworksDomainData = [] }+        appDat <- SUT.defaultAppData+        let argsJson = "{\"file\":\"/tmp/nonexistent-pms-cr12-tc13.sock\"}"+            cmdDat = def+                       { DM._jsonrpcAgentSocketOpenCommandData   = mkJsonRpc "agent-socket-open"+                       , DM._argumentsAgentSocketOpenCommandData = DM.RawJsonByteString argsJson+                       }+        withStderrLogger $ \logger -> do+          result <- Util.runApp domDat' appDat logger (Core.genSocketOpenTask cmdDat)+          case result of+            Left errMsg -> expectationFailure $+              "Expected Right (sandboxNetworks bypassed) but got Left: " ++ errMsg+            Right _     -> return ()++---------------------------------------------------------------------------------+-- Helpers+---------------------------------------------------------------------------------++mkJsonRpc :: String -> DM.JsonRpcRequest+mkJsonRpc method = def { DM._methodJsonRpcRequest = method }++isError :: DM.McpToolsCallResponseData -> Bool+isError dat =+  dat^.DM.resultMcpToolsCallResponseData^.DM.isErrorMcpToolsCallResponseResult++firstContentText :: DM.McpToolsCallResponseData -> String+firstContentText dat =+  let contents = dat^.DM.resultMcpToolsCallResponseData^.DM.contentMcpToolsCallResponseResult+  in DM._textMcpToolsCallResponseResultContent (head contents)++secondContentText :: DM.McpToolsCallResponseData -> String+secondContentText dat =+  let contents = dat^.DM.resultMcpToolsCallResponseData^.DM.contentMcpToolsCallResponseResult+  in DM._textMcpToolsCallResponseResultContent (contents !! 1)++nativeLineEnding :: String+nativeLineEnding = case nativeNewline of+  CRLF -> "\r\n"+  LF   -> "\n"++withReadHandle :: FilePath -> BS.ByteString -> (Handle -> IO a) -> IO a+withReadHandle name content action = do+  tmpDir <- getTemporaryDirectory+  let path = tmpDir </> name+  BS.writeFile path content+  withBinaryFile path ReadMode action++withEmptySocketHandle :: (Handle -> IO a) -> IO a+withEmptySocketHandle action = do+  listener <- socket AF_INET Stream defaultProtocol+  bind listener (SockAddrInet defaultPort (tupleToHostAddress (127,0,0,1)))+  listen listener 1+  port <- socketPort listener+  client <- socket AF_INET Stream defaultProtocol+  connect client (SockAddrInet port (tupleToHostAddress (127,0,0,1)))+  (server, _) <- accept listener+  clientHdl <- socketToHandle client ReadWriteMode+  hSetBuffering clientHdl NoBuffering+  result <- action clientHdl+  hClose clientHdl+  close server+  close listener+  return result++withConnectedPair :: (Handle -> Socket -> IO a) -> IO a+withConnectedPair action = do+  listener <- socket AF_INET Stream defaultProtocol+  bind listener (SockAddrInet defaultPort (tupleToHostAddress (127,0,0,1)))+  listen listener 1+  port <- socketPort listener+  client <- socket AF_INET Stream defaultProtocol+  connect client (SockAddrInet port (tupleToHostAddress (127,0,0,1)))+  (server, _) <- accept listener+  clientHdl <- socketToHandle client ReadWriteMode+  hSetBuffering clientHdl NoBuffering+  result <- action clientHdl server+  hClose clientHdl+  close server+  close listener+  return result++withStderrLogger :: (FastLogger.TimedFastLogger -> IO a) -> IO a+withStderrLogger action = do+  tc <- newTimeCache "%Y-%m-%d %H:%M:%S"+  (logger, finalizer) <- newTimedFastLogger tc (LogStderr defaultBufSize)+  result <- action logger+  finalizer+  return result
+ test/Spec.hs view
@@ -0,0 +1,1 @@+{-# OPTIONS_GHC -F -pgmF hspec-discover #-}