from cmdbox.app import common, client, feature
from cmdbox.app.commons import cache, convert, redis_client, resdata, validator
from cmdbox.app.options import Options
from pathlib import Path
from typing import Dict, Any, Tuple, List, Union
import argparse
import json
import logging
import pydantic
[docs]
class SkillList(feature.OneshotResultEdgeFeature, validator.Validator):
[docs]
def get_mode(self) -> Union[str, List[str]]:
return 'skill'
[docs]
def get_cmd(self) -> str:
return 'list'
[docs]
def get_option(self) -> Dict[str, Any]:
return dict(
use_redis=self.USE_REDIS_TRUE, nouse_webmode=False, use_agent=False,
description_ja="インストール済みAgent Skillsを一覧表示します。",
description_en="List installed Agent Skills.",
choice=[
dict(opt="host", type=Options.T_STR, default=self.default_host, required=True, multi=False, hide=True, choice=None, web="mask",
description_ja="Redisサーバーのサービスホストを指定します。",
description_en="Specify the service host of the Redis server."),
dict(opt="port", type=Options.T_INT, default=self.default_port, required=True, multi=False, hide=True, choice=None, web="mask",
description_ja="Redisサーバーのサービスポートを指定します。",
description_en="Specify the service port of the Redis server."),
dict(opt="password", type=Options.T_PASSWD, default=self.default_pass, required=True, multi=False, hide=True, choice=None, web="mask",
description_ja=f"Redisサーバーのアクセスパスワード(任意)を指定します。省略時は `{self.default_pass}` を使用します。",
description_en=f"Specify the access password of the Redis server (optional). If omitted, `{self.default_pass}` is used."),
dict(opt="svname", type=Options.T_STR, default=self.default_svname, required=True, multi=False, hide=True, choice=None, web="readonly",
description_ja="サーバーのサービス名を指定します。省略時は `server` を使用します。",
description_en="Specify the service name of the inference server. If omitted, `server` is used."),
dict(opt="retry_count", type=Options.T_INT, default=3, required=False, multi=False, hide=True, choice=None,
description_ja="Redisサーバーへの再接続回数を指定します。0以下を指定すると永遠に再接続を行います。",
description_en="Specifies the number of reconnections to the Redis server.If less than 0 is specified, reconnection is forever."),
dict(opt="retry_interval", type=Options.T_INT, default=5, required=False, multi=False, hide=True, choice=None,
description_ja="Redisサーバーに再接続までの秒数を指定します。",
description_en="Specifies the number of seconds before reconnecting to the Redis server."),
dict(opt="timeout", type=Options.T_INT, default=120, required=False, multi=False, hide=True, choice=None,
description_ja="サーバーの応答が返ってくるまでの最大待ち時間を指定。",
description_en="Specify the maximum waiting time until the server responds."),
dict(opt="kwd", type=Options.T_STR, default=None, required=False, multi=False, hide=False, choice=None,
description_ja="検索したいスキル名を指定します。grepで検索します。",
description_en="Specify the name of the skill you want to search for. The search will be performed using grep."),
]
)
@cache.async_apprun_cache(exclude_fn=lambda args: hasattr(args,'kwd') and args.kwd)
@validator.async_apprun_check
async def apprun(self, logger: logging.Logger, args: argparse.Namespace, tm: float,
pf: List[Dict[str, float]] = []) -> Tuple[int, Dict[str, Any], Any]:
payload = dict(kwd=args.kwd if hasattr(args, 'kwd') and args.kwd else '*')
payload_b64 = convert.str2b64str(common.to_str(payload))
cl = client.Client(logger, redis_host=args.host, redis_port=args.port, redis_password=args.password, svname=args.svname)
ret = await cl.redis_cli.asend_cmd(self.get_svcmd(), [payload_b64],
retry_count=args.retry_count, retry_interval=args.retry_interval, timeout=args.timeout, nowait=False)
common.print_format(ret, args.format, tm, pf=pf)
if 'success' not in ret:
return self.RESP_WARN, ret, cl
return self.RESP_SUCCESS, ret, cl
[docs]
def is_cluster_redirect(self):
return False
[docs]
def svrun(self, data_dir: Path, logger: logging.Logger, redis_cli: redis_client.RedisClient, msg: List[str],
sessions: Dict[str, Dict[str, Any]]) -> int:
reskey = msg[1]
try:
payload = json.loads(convert.b64str2str(msg[2]))
kwd = payload.get('kwd', '*')
skills_dir = data_dir / '.skills'
rows = []
if skills_dir.exists() and skills_dir.is_dir():
for p in sorted(skills_dir.glob(kwd)):
if not p.is_dir():
continue
rows.append(dict(
name=p.name,
path=str(p),
has_skill_md=(p / 'SKILL.md').exists(),
))
redis_cli.rpush(reskey, dict(success=dict(data=rows)))
return self.RESP_SUCCESS
except Exception as e:
msg = dict(warn=f"{self.get_mode()}_{self.get_cmd()}: {e}")
logger.warning(f"{self.get_mode()}_{self.get_cmd()}: {e}", exc_info=True)
redis_cli.rpush(reskey, msg)
return self.RESP_WARN
[docs]
def output_schema(self) -> type:
class SkillRecord(resdata.Base):
name: Union[str, None] = pydantic.Field(default=None, description="スキル名")
path: Union[str, None] = pydantic.Field(default=None, description="スキルパス")
has_skill_md: Union[bool, None] = pydantic.Field(default=None, description="SKILL.md有無")
class Data(resdata.Data):
data: Union[List[SkillRecord], None] = pydantic.Field(default=None, description="処理結果のデータ")
class Result(resdata.Result):
success: Union[Data, None] = pydantic.Field(default=None, description="成功した場合の結果")
return Result