@solidxai/core 0.1.21-beta.1 → 0.1.22-beta.0

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 (72) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/dist/decorators/settings-provider.decorator.d.ts +2 -1
  3. package/dist/decorators/settings-provider.decorator.d.ts.map +1 -1
  4. package/dist/decorators/settings-provider.decorator.js +3 -2
  5. package/dist/decorators/settings-provider.decorator.js.map +1 -1
  6. package/dist/dtos/create-agent-user-memory.dto.d.ts +1 -1
  7. package/dist/dtos/create-agent-user-memory.dto.d.ts.map +1 -1
  8. package/dist/dtos/create-agent-user-memory.dto.js +2 -2
  9. package/dist/dtos/create-agent-user-memory.dto.js.map +1 -1
  10. package/dist/dtos/update-agent-user-memory.dto.d.ts +1 -1
  11. package/dist/dtos/update-agent-user-memory.dto.d.ts.map +1 -1
  12. package/dist/dtos/update-agent-user-memory.dto.js +2 -2
  13. package/dist/dtos/update-agent-user-memory.dto.js.map +1 -1
  14. package/dist/entities/agent-user-memory.entity.d.ts +1 -1
  15. package/dist/entities/agent-user-memory.entity.d.ts.map +1 -1
  16. package/dist/entities/agent-user-memory.entity.js +2 -2
  17. package/dist/entities/agent-user-memory.entity.js.map +1 -1
  18. package/dist/helpers/setting-key.helper.d.ts +6 -0
  19. package/dist/helpers/setting-key.helper.d.ts.map +1 -0
  20. package/dist/helpers/setting-key.helper.js +28 -0
  21. package/dist/helpers/setting-key.helper.js.map +1 -0
  22. package/dist/helpers/setting-key.helper.spec.d.ts +2 -0
  23. package/dist/helpers/setting-key.helper.spec.d.ts.map +1 -0
  24. package/dist/helpers/setting-key.helper.spec.js +37 -0
  25. package/dist/helpers/setting-key.helper.spec.js.map +1 -0
  26. package/dist/resources/agent-embed/solid-agent-embed.js +42 -19
  27. package/dist/seeders/module-metadata-seeder.service.d.ts.map +1 -1
  28. package/dist/seeders/module-metadata-seeder.service.js +13 -1
  29. package/dist/seeders/module-metadata-seeder.service.js.map +1 -1
  30. package/dist/seeders/seed-data/solid-core-metadata.json +2 -180
  31. package/dist/services/agent-tool-registry.service.js +5 -5
  32. package/dist/services/agent-tool-registry.service.js.map +1 -1
  33. package/dist/services/mail/smtp-email.service.d.ts.map +1 -1
  34. package/dist/services/mail/smtp-email.service.js +2 -6
  35. package/dist/services/mail/smtp-email.service.js.map +1 -1
  36. package/dist/services/model-metadata.service.d.ts.map +1 -1
  37. package/dist/services/model-metadata.service.js +4 -2
  38. package/dist/services/model-metadata.service.js.map +1 -1
  39. package/dist/services/setting.service.d.ts +1 -1
  40. package/dist/services/setting.service.d.ts.map +1 -1
  41. package/dist/services/setting.service.js +25 -8
  42. package/dist/services/setting.service.js.map +1 -1
  43. package/dist/services/setting.service.spec.d.ts +2 -0
  44. package/dist/services/setting.service.spec.d.ts.map +1 -0
  45. package/dist/services/setting.service.spec.js +110 -0
  46. package/dist/services/setting.service.spec.js.map +1 -0
  47. package/dist/services/settings/default-settings-provider.service.d.ts +146 -6
  48. package/dist/services/settings/default-settings-provider.service.d.ts.map +1 -1
  49. package/dist/services/settings/default-settings-provider.service.js +81 -4
  50. package/dist/services/settings/default-settings-provider.service.js.map +1 -1
  51. package/dist/subscribers/agent-tool-registry.subscriber.d.ts.map +1 -1
  52. package/dist/subscribers/agent-tool-registry.subscriber.js +16 -11
  53. package/dist/subscribers/agent-tool-registry.subscriber.js.map +1 -1
  54. package/package.json +1 -1
  55. package/plan.md +480 -0
  56. package/resources/agent-embed/solid-agent-embed.js +42 -19
  57. package/src/decorators/settings-provider.decorator.ts +6 -3
  58. package/src/dtos/create-agent-user-memory.dto.ts +1 -1
  59. package/src/dtos/update-agent-user-memory.dto.ts +1 -1
  60. package/src/entities/agent-user-memory.entity.ts +2 -2
  61. package/src/helpers/setting-key.helper.spec.ts +32 -0
  62. package/src/helpers/setting-key.helper.ts +30 -0
  63. package/src/seeders/module-metadata-seeder.service.ts +12 -1
  64. package/src/seeders/seed-data/solid-core-metadata.json +2 -180
  65. package/src/services/agent-tool-registry.service.ts +5 -5
  66. package/src/services/mail/smtp-email.service.ts +3 -6
  67. package/src/services/model-metadata.service.ts +5 -2
  68. package/src/services/setting.service.spec.ts +117 -0
  69. package/src/services/setting.service.ts +29 -9
  70. package/src/services/settings/default-settings-provider.service.ts +81 -4
  71. package/src/subscribers/agent-tool-registry.subscriber.ts +16 -9
  72. package/src/services/1.js +0 -6
@@ -11609,8 +11609,8 @@
11609
11609
  "relationCoModelSingularName": "agentSession",
11610
11610
  "relationCoModelColumnName": null,
11611
11611
  "relationModelModuleName": "solid-core",
11612
- "relationCascade": "cascade",
11613
- "required": true,
11612
+ "relationCascade": "set null",
11613
+ "required": false,
11614
11614
  "unique": false,
11615
11615
  "index": false,
11616
11616
  "private": false,
@@ -29685,183 +29685,5 @@
29685
29685
  ],
29686
29686
  "agenthubTags": [],
29687
29687
  "agenthubAgents": [],
29688
- "agenthubTools": [
29689
- {
29690
- "name": "bash",
29691
- "iconName": "terminal",
29692
- "description": "Run an allowlisted command (npm, npx, node, tsc, eslint, git, find, curl) in the consuming SolidX project.",
29693
- "type": "solidx",
29694
- "status": "active",
29695
- "sourceCode": "import shlex\nimport shutil\nimport subprocess\n\nfrom pydantic import BaseModel, Field\nfrom agenthub.sdk import (project_root, tool, ToolContext, ToolError, ToolResponse,\n ToolConfigResponse, ToolInitResponse, tool_config, tool_init)\n\nALLOWED = {\"npm\", \"npx\", \"node\", \"tsc\", \"eslint\", \"git\", \"find\", \"curl\"}\n\n\nclass Args(BaseModel):\n command: str = Field(description=\"Command to run, e.g. `npx tsc --noEmit`. Shell operators are not allowed.\")\n cwd: str = Field(\".\", description=\"Directory relative to the project root, e.g. solid-ui or solid-api.\")\n\n\n@tool_config\ndef config() -> ToolConfigResponse:\n return ToolConfigResponse(required_secrets=[])\n\n\n@tool_init\ndef init() -> ToolInitResponse:\n root = project_root()\n if not root.is_dir():\n return ToolInitResponse(success=False, message=f\"Project root {root} does not exist.\")\n missing = sorted(command for command in ALLOWED if shutil.which(command) is None)\n if \"npx\" in missing:\n return ToolInitResponse(success=False, message=\"npx is not on PATH; install Node.js.\")\n return ToolInitResponse(success=True, message=f\"Project root {root} is ready.\" +\n (f\" Not on PATH: {', '.join(missing)}.\" if missing else \"\"))\n\n\n@tool(name=\"bash\", description=\"Run an allowlisted command (npm, npx, node, tsc, eslint, git, find, curl) in the \"\n \"consuming SolidX project.\")\ndef bash(args: Args, ctx: ToolContext) -> ToolResponse:\n if any(operator in args.command for operator in (\";\", \"&&\", \"||\", \"|\", \">\", \"<\", \"`\", \"$(\", \"\\n\")):\n raise ToolError(\"invalid_command\", \"Shell operators and substitution are forbidden\",\n guidance=\"Run one command per call; use `cwd` instead of `cd`.\")\n parts = shlex.split(args.command)\n if not parts or parts[0] not in ALLOWED:\n raise ToolError(\"invalid_command\", f\"Only {', '.join(sorted(ALLOWED))} are available\")\n if parts[0] == \"find\" and any(part in {\"-exec\", \"-execdir\", \"-ok\", \"-okdir\", \"-delete\"}\n or part.startswith(\"-fprint\") for part in parts[1:]):\n raise ToolError(\"invalid_command\", \"Unsafe find option\")\n if parts[0] == \"git\" and any(part in {\"-c\", \"--config-env\", \"--exec-path\", \"config\"} or\n part.startswith((\"-c=\", \"--config-env=\", \"--exec-path=\"))\n for part in parts[1:]):\n raise ToolError(\"invalid_command\", \"Unsafe git option\")\n root = project_root()\n cwd = (root / args.cwd).resolve()\n if not cwd.is_relative_to(root):\n raise ToolError(\"path_outside_workspace\", f\"cwd '{args.cwd}' is outside the project root\")\n if not cwd.is_dir():\n raise ToolError(\"path_not_found\", f\"cwd '{args.cwd}' does not exist\")\n try:\n completed = subprocess.run(parts, cwd=cwd, capture_output=True, text=True, errors=\"replace\", timeout=600,\n check=False)\n except subprocess.TimeoutExpired as exc:\n raise ToolError(\"command_timeout\", \"Command exceeded 600 seconds\", guidance=\"Run a narrower command.\") from exc\n # Build and test failures are reported at the end of the output, so keep the tail.\n return ToolResponse({\"status\": completed.returncode, \"cwd\": str(cwd.relative_to(root)) or \".\",\n \"stdout\": completed.stdout[-50000:], \"stderr\": completed.stderr[-10000:],\n \"truncated\": len(completed.stdout) > 50000 or len(completed.stderr) > 10000})\n",
29696
- "tags": [],
29697
- "moduleUserKey": "solid-core"
29698
- },
29699
- {
29700
- "name": "filesystem",
29701
- "iconName": "folder_open",
29702
- "description": "Search, read, edit, or write files in the consuming SolidX project.",
29703
- "type": "solidx",
29704
- "status": "active",
29705
- "sourceCode": "\"\"\"Consuming-project search/read/edit/write, ported from the SolidX agent's ``filesystem_tool``.\n\nPaths resolve against the consuming project root (``CONTAINER_SOLIDX_CONSUMING_PROJECT_ROOT``, then\n``SOLIDX_PROJECT_ROOT``, then the working directory) or the Agent Hub tool staging area. Edits use MCP-style\n{oldText, newText} pairs: exact substring first, then a whitespace-tolerant line match; otherwise the call\nfails so the model re-reads instead of anchoring to the wrong place. Search uses ripgrep, falling back to grep.\n\"\"\"\n\nimport json\nimport os\nimport re\nimport shutil\nimport subprocess\nfrom pathlib import Path\nfrom secrets import token_hex\nfrom typing import Literal\n\nfrom pydantic import BaseModel, Field, field_validator\nfrom agenthub.sdk import (project_root, tool, ToolContext, ToolError, ToolResponse,\n ToolConfigResponse, ToolInitResponse, tool_config, tool_init)\n\nDEFAULT_FRONTEND_ROOT = \"solid-ui\"\n\n\nclass Edit(BaseModel):\n oldText: str\n newText: str\n\n\nclass Args(BaseModel):\n action: Literal[\"search\", \"read\", \"edit\", \"write\"] = Field(description=\"One of search, read, edit, write.\")\n query: str | None = Field(None, description=\"Required for action=search. Regex/text query for search.\")\n path: str | None = Field(None, description=\"For search/read/edit/write. For search defaults to solid-ui when \"\n \"omitted.\")\n glob: str | None = Field(None, description='Optional glob filter for action=search (for example \"*.tsx\").')\n case_sensitive: bool = Field(False, description=\"For action=search. Whether match is case-sensitive.\")\n max_matches: int = Field(200, description=\"For action=search. Maximum total matches returned.\")\n context_lines: int = Field(2, description=\"For action=search. Number of context lines around each match.\")\n start_line: int | None = Field(None, description=\"For action=read. Optional 1-based start line.\")\n end_line: int | None = Field(None, description=\"For action=read. Optional 1-based end line (inclusive).\")\n max_chars: int = Field(20000, description=\"For action=read. Maximum returned character count.\")\n edits: list[Edit] | None = Field(None, description=(\n \"Required for action=edit. Non-empty list of {oldText, newText} pairs. Each oldText must appear in the file \"\n \"(exact substring or whitespace-tolerant line match). On no match the call fails with edit_no_match; re-read \"\n \"the file and resubmit instead of retrying the same edit. New file creation belongs to action=write.\"))\n content: str | None = Field(None, description=\"Required for action=write. Full UTF-8 text content for the \"\n \"target file.\")\n overwrite: bool = Field(False, description=\"For action=write. When false (default) writing fails with \"\n \"file_exists if the target already exists.\")\n dry_run: bool = Field(False, description=\"For action=edit. Validate edits without persisting changes.\")\n\n @field_validator(\"edits\", mode=\"before\")\n @classmethod\n def parse_edits(cls, value):\n # Models sometimes send complex arguments as a JSON-encoded string.\n if isinstance(value, str):\n try:\n return json.loads(value) if value.strip() else value\n except json.JSONDecodeError as exc:\n raise ValueError(\"edits must be an array of {oldText, newText} objects, not a quoted string\") from exc\n return value\n\n\ndef _resolve(path: str) -> Path:\n root = project_root()\n raw = Path(path.strip())\n resolved = raw.resolve() if raw.is_absolute() else (root / raw).resolve()\n staging = (Path.home() / \".solidx\" / \"agent-hub\" / \"tools\").resolve()\n if not any(resolved.is_relative_to(allowed) for allowed in (root, staging)):\n raise ToolError(\"path_outside_workspace\", f\"Path '{path}' is outside workspace root '{root}' and the \"\n f\"Agent Hub tool staging area '{staging}'\", retryable=True,\n guidance=\"Provide a path under the workspace root or Agent Hub tool staging area.\")\n return resolved\n\n\ndef _relative(path: Path) -> str:\n root = project_root()\n return str(path.relative_to(root)) if path.is_relative_to(root) else str(path)\n\n\ndef _read_text(target: Path, relative: str) -> str:\n try:\n return target.read_text(encoding=\"utf-8\")\n except UnicodeDecodeError as exc:\n raise ToolError(\"binary_or_non_utf8\", f\"File '{relative}' is not UTF-8 text\",\n guidance=\"Use this tool only for UTF-8 text files.\") from exc\n\n\ndef _atomic_write(target: Path, content: str) -> None:\n temporary = target.parent / f\"{target.name}.{token_hex(16)}.tmp\"\n try:\n temporary.write_text(content, encoding=\"utf-8\")\n os.replace(temporary, target)\n finally:\n temporary.unlink(missing_ok=True)\n\n\ndef _indent(line: str) -> str:\n return line[:len(line) - len(line.lstrip(\" \\t\"))]\n\n\ndef _apply_edit(content: str, old_text: str, new_text: str) -> str | None:\n old_text, new_text = old_text.replace(\"\\r\\n\", \"\\n\"), new_text.replace(\"\\r\\n\", \"\\n\")\n if old_text in content:\n return content.replace(old_text, new_text, 1)\n old_lines, lines = old_text.split(\"\\n\"), content.split(\"\\n\")\n for i in range(len(lines) - len(old_lines) + 1):\n if not all(old.strip() == line.strip() for old, line in zip(old_lines, lines[i:i + len(old_lines)])):\n continue\n base = _indent(lines[i])\n rebuilt = []\n for j, line in enumerate(new_text.split(\"\\n\")):\n old_indent, new_indent = (_indent(old_lines[j]) if j < len(old_lines) else \"\"), _indent(line)\n if j == 0:\n rebuilt.append(base + line.lstrip())\n elif old_indent and new_indent:\n rebuilt.append(base + \" \" * max(0, len(new_indent) - len(old_indent)) + line.lstrip())\n else:\n rebuilt.append(line)\n lines[i:i + len(old_lines)] = rebuilt\n return \"\\n\".join(lines)\n return None\n\n\ndef _search_command(backend: str, query: str, root: Path, args: Args) -> list[str]:\n if backend == \"rg\":\n command = [\"rg\", \"--json\", \"--line-number\", \"--column\", \"--context\", str(args.context_lines)]\n command += [] if args.case_sensitive else [\"-i\"]\n command += [\"-g\", args.glob] if args.glob else []\n else:\n command = [\"grep\", \"-n\", \"-E\", \"--binary-files=without-match\", \"--color=never\", \"-C\", str(args.context_lines)]\n command += [\"-R\"] if root.is_dir() else []\n command += [] if args.case_sensitive else [\"-i\"]\n command += [f\"--include={args.glob}\"] if args.glob else []\n return command + [query, str(root)]\n\n\ndef _repair_regex(query: str) -> str:\n \"\"\"Escape a regex the model meant literally; keep top-level alternation.\"\"\"\n parts = [part for part in query.split(\"|\") if part]\n return \"|\".join(re.escape(part) for part in parts) if len(parts) > 1 else re.escape(query)\n\n\ndef _match(path: str, line: int, column: int, text: str, context: dict, context_lines: int) -> dict:\n def around(numbers):\n return [{\"line\": number, \"text\": context[(path, number)]} for number in numbers if (path, number) in context]\n return {\"path\": _relative(Path(path).resolve()), \"line\": line, \"column\": column, \"preview\": text,\n \"before\": around(range(max(1, line - context_lines), line)),\n \"after\": around(range(line + 1, line + context_lines + 1))}\n\n\ndef _parse_rg(stdout: str, args: Args) -> list[dict]:\n events = []\n for line in stdout.splitlines():\n try:\n events.append(json.loads(line))\n except json.JSONDecodeError:\n continue\n context = {(event[\"data\"][\"path\"][\"text\"], event[\"data\"][\"line_number\"]):\n event[\"data\"][\"lines\"].get(\"text\", \"\").rstrip(\"\\n\") for event in events if event.get(\"type\") == \"context\"}\n matches = []\n for event in events:\n if event.get(\"type\") != \"match\":\n continue\n data = event[\"data\"]\n submatches = data.get(\"submatches\") or [{\"start\": 0}]\n matches.append(_match(data[\"path\"][\"text\"], data[\"line_number\"], submatches[0][\"start\"] + 1,\n data[\"lines\"].get(\"text\", \"\").rstrip(\"\\n\"), context, args.context_lines))\n if len(matches) >= args.max_matches:\n break\n return matches\n\n\ndef _parse_grep(stdout: str, args: Args) -> list[dict]:\n pattern = re.compile(r\"^(.*?)([:\\-])(\\d+)([:\\-])(.*)$\")\n rows = [match.groups() for raw in stdout.splitlines() if raw.strip() not in {\"\", \"--\"}\n and (match := pattern.match(raw))]\n context = {(path, int(line)): text for path, first, line, second, text in rows if (first, second) != (\":\", \":\")}\n matches = []\n for path, first, line, second, text in rows:\n if (first, second) == (\":\", \":\"):\n matches.append(_match(path, int(line), 1, text, context, args.context_lines))\n if len(matches) >= args.max_matches:\n break\n return matches\n\n\ndef _search(args: Args) -> ToolResponse:\n if not (args.query or \"\").strip():\n raise ToolError(\"missing_query\", \"query is required for action='search'\")\n if args.max_matches <= 0:\n raise ToolError(\"invalid_max_matches\", \"max_matches must be greater than 0\")\n if args.context_lines < 0:\n raise ToolError(\"invalid_context_lines\", \"context_lines cannot be negative\")\n root = _resolve(args.path or DEFAULT_FRONTEND_ROOT)\n if not root.exists():\n raise ToolError(\"path_not_found\", f\"Search path does not exist: '{_relative(root)}'. Drop the `path` (or pass \"\n \"a parent that exists) and use a `glob` filter to scope the search instead.\", retryable=True,\n guidance=\"Search from a directory that exists and narrow with `glob`, e.g. \"\n \"glob='**/CurrencyExchange/*.tsx'.\")\n backend = \"rg\" if shutil.which(\"rg\") else \"grep\" if shutil.which(\"grep\") else None\n if backend is None:\n raise ToolError(\"search_backend_not_found\", \"Neither ripgrep (rg) nor grep is available in PATH\",\n guidance=\"Install ripgrep (recommended) or grep and retry.\")\n query = args.query\n\n def run(text):\n return subprocess.run(_search_command(backend, text, root, args), capture_output=True, text=True,\n encoding=\"utf-8\", errors=\"replace\", timeout=120, check=False)\n\n completed = run(query)\n if completed.returncode not in (0, 1) and \"regex parse error\" in completed.stderr.lower() \\\n and _repair_regex(query) != query:\n query = _repair_regex(query)\n completed = run(query)\n if completed.returncode not in (0, 1):\n stderr = completed.stderr.strip() or \"search command failed.\"\n if \"No such file or directory\" in stderr or \"os error 2\" in stderr:\n raise ToolError(\"path_not_found\", stderr[:2000], retryable=True,\n guidance=\"Search from a directory that exists and narrow with `glob`.\")\n raise ToolError(\"search_failed\", stderr[:2000])\n matches = (_parse_rg if backend == \"rg\" else _parse_grep)(completed.stdout, args)\n return ToolResponse({\"query\": query, \"path\": _relative(root), \"backend\": backend, \"glob\": args.glob,\n \"case_sensitive\": args.case_sensitive, \"context_lines\": args.context_lines,\n \"count\": len(matches), \"truncated\": len(matches) >= args.max_matches, \"matches\": matches})\n\n\ndef _read(args: Args, target: Path, relative: str) -> ToolResponse:\n if args.max_chars <= 0:\n raise ToolError(\"invalid_max_chars\", \"max_chars must be greater than 0\")\n if args.start_line is not None and args.start_line <= 0:\n raise ToolError(\"invalid_start_line\", \"start_line must be greater than 0 when provided\")\n if args.end_line is not None and args.end_line <= 0:\n raise ToolError(\"invalid_end_line\", \"end_line must be greater than 0 when provided\")\n if args.start_line and args.end_line and args.start_line > args.end_line:\n raise ToolError(\"invalid_line_range\", \"start_line cannot be greater than end_line\")\n lines = _read_text(target, relative).splitlines(keepends=True)\n selected = \"\".join(lines[(args.start_line or 1) - 1:args.end_line or len(lines)])\n return ToolResponse({\"path\": relative, \"start_line\": args.start_line, \"end_line\": args.end_line,\n \"total_lines\": len(lines), \"size_bytes\": target.stat().st_size,\n \"truncated\": len(selected) > args.max_chars, \"content\": selected[:args.max_chars]})\n\n\ndef _edit(args: Args, target: Path, relative: str) -> ToolResponse:\n if not args.edits:\n raise ToolError(\"invalid_edits\", \"edits must be a non-empty list of {oldText, newText} pairs\")\n for index, item in enumerate(args.edits):\n if item.oldText == item.newText:\n raise ToolError(\"noop_edit\", f\"edits[{index}] has identical oldText and newText (no-op)\")\n original = _read_text(target, relative).replace(\"\\r\\n\", \"\\n\")\n modified = original\n for index, item in enumerate(args.edits):\n result = _apply_edit(modified, item.oldText, item.newText)\n if result is None:\n raise ToolError(\"edit_no_match\", f\"edits[{index}].oldText not found in '{relative}'. Re-read the file to \"\n \"capture the current content, then resubmit.\", retryable=True,\n guidance=\"Call action='read' on this path to get the current content, then build a new \"\n \"oldText that matches verbatim (or differs only in whitespace per line).\")\n modified = result\n changed = not args.dry_run and modified != original\n if changed:\n _atomic_write(target, modified)\n return ToolResponse({\"dry_run\": args.dry_run, \"workspace_root\": str(project_root()),\n \"allowed_scope\": \"workspace/**\", \"path\": relative, \"edit_count\": len(args.edits),\n \"files_changed\": [relative] if changed else [],\n \"files_validated\": [relative] if args.dry_run else []})\n\n\ndef _write(args: Args, target: Path, relative: str) -> ToolResponse:\n if args.content is None:\n raise ToolError(\"missing_content\", \"content is required for action='write'\")\n if target.is_dir():\n raise ToolError(\"not_a_file\", f\"Path is not a file: '{relative}'\")\n existed = target.exists()\n if existed and not args.overwrite:\n raise ToolError(\"file_exists\", f\"File already exists: '{relative}'. Pass overwrite=true to replace it.\",\n retryable=True, guidance=\"Use action='edit' for targeted changes, or pass overwrite=true.\")\n target.parent.mkdir(parents=True, exist_ok=True)\n _atomic_write(target, args.content)\n return ToolResponse({\"path\": relative, \"created\": not existed, \"overwritten\": existed,\n \"size_bytes\": target.stat().st_size})\n\n\n@tool_config\ndef config() -> ToolConfigResponse:\n return ToolConfigResponse(required_secrets=[])\n\n\n@tool_init\ndef init() -> ToolInitResponse:\n root = project_root()\n if not root.is_dir():\n return ToolInitResponse(success=False, message=f\"Project root {root} does not exist.\")\n backend = \"ripgrep\" if shutil.which(\"rg\") else \"grep\" if shutil.which(\"grep\") else None\n if backend is None:\n return ToolInitResponse(success=False, message=\"Neither ripgrep (rg) nor grep is on PATH.\")\n return ToolInitResponse(success=True, message=f\"Project root {root} is ready; search uses {backend}.\")\n\n\n@tool(name=\"filesystem\", description=\"Search, read, edit, or write files in the consuming SolidX project.\")\ndef filesystem(args: Args, ctx: ToolContext) -> ToolResponse:\n if args.action == \"search\":\n return _search(args)\n if not (args.path or \"\").strip():\n raise ToolError(\"missing_path\", f\"path is required for action='{args.action}'\")\n target = _resolve(args.path)\n relative = _relative(target)\n if args.action == \"write\":\n return _write(args, target, relative)\n if not target.exists():\n raise ToolError(\"file_not_found\", f\"File not found: '{relative}'.\" +\n (\" Use action='write' to create it.\" if args.action == \"edit\" else \"\"), retryable=True)\n if not target.is_file():\n raise ToolError(\"not_a_file\", f\"Path is not a file: '{relative}'\")\n return _read(args, target, relative) if args.action == \"read\" else _edit(args, target, relative)\n",
29706
- "tags": [],
29707
- "moduleUserKey": "solid-core"
29708
- },
29709
- {
29710
- "name": "list_widgets",
29711
- "iconName": "widgets",
29712
- "description": "List this session's UI-discovered chat widgets and their prop schemas.",
29713
- "type": "solidx",
29714
- "status": "active",
29715
- "sourceCode": "from pydantic import BaseModel\nfrom agenthub.sdk import (tool, ToolContext, ToolResponse, ToolConfigResponse, ToolInitResponse,\n tool_config, tool_init)\n\n\nclass Args(BaseModel):\n pass\n\n\n@tool_config\ndef config() -> ToolConfigResponse:\n return ToolConfigResponse(required_secrets=[])\n\n\n@tool_init\ndef init() -> ToolInitResponse:\n return ToolInitResponse(success=True, message=\"No external dependencies.\")\n\n\n@tool(name=\"list_widgets\", description=\"List this session's UI-discovered chat widgets and their prop schemas.\")\ndef list_widgets(args: Args, ctx: ToolContext) -> ToolResponse:\n return ToolResponse({\"widgets\": list(ctx.widget_catalog)})\n",
29716
- "tags": [],
29717
- "moduleUserKey": "solid-core"
29718
- },
29719
- {
29720
- "name": "load_skill",
29721
- "iconName": "menu_book",
29722
- "description": "Load the body of a skill linked to this agent.",
29723
- "type": "solidx",
29724
- "status": "active",
29725
- "sourceCode": "from pydantic import BaseModel\nfrom agenthub.sdk import (tool, ToolContext, ToolResponse, ToolConfigResponse, ToolInitResponse,\n tool_config, tool_init)\n\n\nclass Args(BaseModel):\n name: str\n\n\n@tool_config\ndef config() -> ToolConfigResponse:\n return ToolConfigResponse(required_secrets=[])\n\n\n@tool_init\ndef init() -> ToolInitResponse:\n return ToolInitResponse(success=True, message=\"Handled by the runtime; no external dependencies.\")\n\n\n@tool(name=\"load_skill\", description=\"Load the body of a skill linked to this agent.\")\ndef load_skill(args: Args, ctx: ToolContext) -> ToolResponse:\n \"\"\"Handled by the per-session executor.\"\"\"\n raise RuntimeError(\"load_skill must be dispatched by ToolExecutor\")\n",
29726
- "tags": [],
29727
- "moduleUserKey": "solid-core"
29728
- },
29729
- {
29730
- "name": "memory_delete",
29731
- "iconName": "bookmark_remove",
29732
- "description": "Permanently delete a memory the user asked to forget or that is no longer true.",
29733
- "type": "solidx",
29734
- "status": "active",
29735
- "sourceCode": "from pydantic import BaseModel, Field\nfrom agenthub.memory import not_found, owner, repository\nfrom agenthub.sdk import (tool, ToolContext, ToolResponse, ToolConfigResponse, ToolInitResponse,\n tool_config, tool_init)\n\n\nclass Args(BaseModel):\n id: int = Field(description=\"Id of the memory to delete, from memory_view.\")\n\n\n@tool_config\ndef config() -> ToolConfigResponse:\n return ToolConfigResponse(required_secrets=[])\n\n\n@tool_init\ndef init() -> ToolInitResponse:\n return ToolInitResponse(success=True, message=\"Uses the AgentHub database; no external dependencies.\")\n\n\n@tool(name=\"memory_delete\", description=(\n \"Permanently delete a memory when the user asks you to forget it or it is no longer true.\"))\ndef memory_delete(args: Args, ctx: ToolContext) -> ToolResponse:\n user_id, agent_id = owner(ctx)\n if not repository().delete_memory(args.id, user_id, agent_id):\n raise not_found(args.id)\n return ToolResponse({\"deleted\": args.id})\n",
29736
- "tags": [],
29737
- "moduleUserKey": "solid-core"
29738
- },
29739
- {
29740
- "name": "memory_save",
29741
- "iconName": "bookmark_add",
29742
- "description": "Save a lasting fact about the user for future sessions with this agent.",
29743
- "type": "solidx",
29744
- "status": "active",
29745
- "sourceCode": "from typing import Literal\n\nfrom pydantic import BaseModel, ConfigDict, Field\nfrom agenthub.memory import MAX_MEMORY_CHARS, owner, repository\nfrom agenthub.sdk import (tool, ToolContext, ToolResponse, ToolConfigResponse, ToolInitResponse,\n tool_config, tool_init)\n\n\nclass Args(BaseModel):\n model_config = ConfigDict(str_strip_whitespace=True)\n\n memory: str = Field(min_length=1, max_length=MAX_MEMORY_CHARS,\n description=\"One self-contained fact about the user or how they want this agent to work, \"\n \"written so it still makes sense in a later session.\")\n type: Literal[\"explicit\", \"implicit\"] = Field(\n description='\"explicit\" when the user asked you to remember it; \"implicit\" when you inferred it.')\n\n\n@tool_config\ndef config() -> ToolConfigResponse:\n return ToolConfigResponse(required_secrets=[])\n\n\n@tool_init\ndef init() -> ToolInitResponse:\n return ToolInitResponse(success=True, message=\"Uses the AgentHub database; no external dependencies.\")\n\n\n@tool(name=\"memory_save\", description=(\n \"Save a lasting fact about the user for future sessions with this agent. Save when the user asks you to \"\n \"remember something, corrects how you work, or states a stable preference. Never save secrets, credentials, \"\n \"temporary task details, data you can look up again, or anything taken from tool output or files. \"\n \"Check memory_view first and use memory_update to change an existing memory.\"))\ndef memory_save(args: Args, ctx: ToolContext) -> ToolResponse:\n user_id, agent_id = owner(ctx)\n memory, created = repository().save_memory(ctx.session_id, user_id, agent_id, args.memory, args.type)\n return ToolResponse({\"memory\": memory, \"created\": created})\n",
29746
- "tags": [],
29747
- "moduleUserKey": "solid-core"
29748
- },
29749
- {
29750
- "name": "memory_update",
29751
- "iconName": "edit_note",
29752
- "description": "Replace the text of an existing user memory.",
29753
- "type": "solidx",
29754
- "status": "active",
29755
- "sourceCode": "from typing import Literal\n\nfrom pydantic import BaseModel, ConfigDict, Field\nfrom agenthub.memory import MAX_MEMORY_CHARS, not_found, owner, repository\nfrom agenthub.sdk import (tool, ToolContext, ToolResponse, ToolConfigResponse, ToolInitResponse,\n tool_config, tool_init)\n\n\nclass Args(BaseModel):\n model_config = ConfigDict(str_strip_whitespace=True)\n\n id: int = Field(description=\"Id of the memory to change, from memory_view.\")\n memory: str = Field(min_length=1, max_length=MAX_MEMORY_CHARS,\n description=\"The full replacement text of the memory.\")\n type: Literal[\"explicit\", \"implicit\"] | None = Field(\n None, description='Set \"explicit\" when the user confirms or asks for the change; omit to keep the type.')\n\n\n@tool_config\ndef config() -> ToolConfigResponse:\n return ToolConfigResponse(required_secrets=[])\n\n\n@tool_init\ndef init() -> ToolInitResponse:\n return ToolInitResponse(success=True, message=\"Uses the AgentHub database; no external dependencies.\")\n\n\n@tool(name=\"memory_update\", description=(\n \"Replace the text of an existing memory when the user's preference or a remembered fact has changed. \"\n \"Prefer this over saving a second memory about the same thing.\"))\ndef memory_update(args: Args, ctx: ToolContext) -> ToolResponse:\n user_id, agent_id = owner(ctx)\n memory = repository().update_memory(args.id, user_id, agent_id, args.memory, args.type)\n if memory is None:\n raise not_found(args.id)\n return ToolResponse({\"memory\": memory})\n",
29756
- "tags": [],
29757
- "moduleUserKey": "solid-core"
29758
- },
29759
- {
29760
- "name": "memory_view",
29761
- "iconName": "bookmarks",
29762
- "description": "Read this agent’s memories about the user, optionally filtered by type, creation date, or session.",
29763
- "type": "solidx",
29764
- "status": "active",
29765
- "sourceCode": "from datetime import date\nfrom typing import Literal\n\nfrom pydantic import BaseModel, Field\nfrom agenthub.memory import not_found, owner, repository\nfrom agenthub.sdk import (tool, ToolContext, ToolResponse, ToolConfigResponse, ToolInitResponse,\n tool_config, tool_init)\n\n\nclass Args(BaseModel):\n id: int | None = Field(None, description=\"Id of one memory to read; omit to list all memories, newest first.\")\n type: Literal[\"explicit\", \"implicit\"] | None = Field(None, description=\"Filter by memory type.\")\n date: date | None = Field(None, description=\"Filter by the memory's creation date (YYYY-MM-DD, UTC).\")\n sessionid: str | None = Field(None, description=\"Filter by the session's public UUID.\")\n\n\n@tool_config\ndef config() -> ToolConfigResponse:\n return ToolConfigResponse(required_secrets=[])\n\n\n@tool_init\ndef init() -> ToolInitResponse:\n return ToolInitResponse(success=True, message=\"Uses the AgentHub database; no external dependencies.\")\n\n\n@tool(name=\"memory_view\", description=(\n \"Read what you remember about this user for this agent. Optionally filter by type, creation date, \"\n \"or session UUID. Use it before saving or changing a memory, and when the user asks what you remember.\"))\ndef memory_view(args: Args, ctx: ToolContext) -> ToolResponse:\n user_id, agent_id = owner(ctx)\n if args.id is None:\n return ToolResponse({\"memories\": repository().list_memories(\n user_id, agent_id, memory_type=args.type, created_on=args.date, session_uid=args.sessionid)})\n memory = repository().get_memory(args.id, user_id, agent_id, memory_type=args.type,\n created_on=args.date, session_uid=args.sessionid)\n if memory is None:\n raise not_found(args.id)\n return ToolResponse({\"memory\": memory})\n",
29766
- "tags": [],
29767
- "moduleUserKey": "solid-core"
29768
- },
29769
- {
29770
- "name": "request_human_input",
29771
- "iconName": "contact_support",
29772
- "description": "Pause to ask the session user a question.",
29773
- "type": "solidx",
29774
- "status": "active",
29775
- "sourceCode": "from pydantic import BaseModel\nfrom agenthub.sdk import (tool, ToolContext, ToolResponse, ToolConfigResponse, ToolInitResponse,\n tool_config, tool_init)\n\n\nclass Args(BaseModel):\n question: str\n options: list[str] | None = None\n context: dict | None = None\n\n\n@tool_config\ndef config() -> ToolConfigResponse:\n return ToolConfigResponse(required_secrets=[])\n\n\n@tool_init\ndef init() -> ToolInitResponse:\n return ToolInitResponse(success=True, message=\"Handled by the runtime; no external dependencies.\")\n\n\n@tool(name=\"request_human_input\", description=\"Pause to ask the session user a question.\")\ndef request_human_input(args: Args, ctx: ToolContext) -> ToolResponse:\n \"\"\"Handled by the per-session executor.\"\"\"\n raise RuntimeError(\"request_human_input must be dispatched by ToolExecutor\")\n",
29776
- "tags": [],
29777
- "moduleUserKey": "solid-core"
29778
- },
29779
- {
29780
- "name": "run_read_only_mssql",
29781
- "iconName": "table_view",
29782
- "description": "Execute a single read-only T-SQL SELECT/WITH statement against the SQL Server project database and return rows.",
29783
- "type": "solidx",
29784
- "status": "active",
29785
- "sourceCode": "\"\"\"Read-only SQL against a consuming project database on Microsoft SQL Server (pymssql driver).\n\nSQL Server has no read-only transaction mode and T-SQL allows several statements without ``;``, so safety\ncomes from three layers: the statement check below (applied after string literals and quoted identifiers are\nremoved), a transaction that is always rolled back, and, for a hard guarantee, a read-only login supplied in\n``AGENTHUB_READONLY_DATABASE_URL`` (for example a ``db_datareader`` user).\n\"\"\"\n\nimport os\nimport re\nfrom functools import lru_cache\n\nfrom pydantic import BaseModel, Field\nfrom sqlalchemy import create_engine, text\nfrom sqlalchemy.engine import make_url\nfrom agenthub.sdk import (tool, ToolContext, ToolError, ToolResponse, ToolConfigResponse,\n ToolInitResponse, tool_config, tool_init)\n\nBACKEND = \"mssql\"\n_FORBIDDEN_SQL_RE = re.compile(\n r\"\\b(insert|update|delete|merge|drop|truncate|alter|create|grant|revoke|deny|exec|execute|into|\"\n r\"openrowset|opendatasource|openquery|openxml|bulk|backup|restore|dbcc|shutdown|kill|waitfor|use|set|\"\n r\"declare|begin|commit|rollback|save|reconfigure|checkpoint|go)\\b|\\b(?:sp|xp)_\\w+\",\n re.IGNORECASE,\n)\n_ALLOWED_START_RE = re.compile(r\"^\\s*(select|with)\\b\", re.IGNORECASE)\n_SQL_COMMENT_RE = re.compile(r\"(--[^\\n]*|/\\*.*?\\*/)\", re.DOTALL)\n# String literals ('it''s', N'...') and quoted identifiers ([order], \"update\") cannot hide statements.\n_QUOTED_RE = re.compile(r\"N?'(?:[^']|'')*'|\\[(?:[^\\]]|\\]\\])*\\]|\\\"(?:[^\\\"]|\\\"\\\")*\\\"\", re.IGNORECASE)\n\n\nclass Args(BaseModel):\n query: str = Field(description=\"T-SQL SELECT or WITH statement to execute. Use TOP, not LIMIT.\")\n datasource: str = Field(\"default\", description='Datasource name (currently informational; default \"default\").')\n limit: int = Field(100, description=\"Maximum rows to return (default 100, max 1000).\")\n\n\ndef _database_url():\n raw = os.environ.get(\"AGENTHUB_READONLY_DATABASE_URL\") or os.environ.get(\"DATABASE_URL\")\n if not raw:\n raise ToolError(\"db_query_error\", \"No project database is configured.\")\n url = make_url(raw)\n if url.get_backend_name() != BACKEND:\n raise ToolError(\"unsupported_database\", f\"The project database is {url.get_backend_name()}, not SQL Server.\",\n guidance=\"Use run_read_only_postgres for PostgreSQL.\")\n return url.set(drivername=\"mssql+pymssql\")\n\n\n@lru_cache(maxsize=2)\ndef _engine(url):\n # timeout: per-query seconds; login_timeout: connect seconds.\n return create_engine(url, pool_pre_ping=True, pool_size=2, max_overflow=0,\n connect_args={\"timeout\": 30, \"login_timeout\": 10})\n\n\ndef _validate(sql: str) -> str:\n cleaned = _SQL_COMMENT_RE.sub(\"\", sql or \"\").strip()\n if cleaned.endswith(\";\"):\n cleaned = cleaned[:-1].rstrip()\n if not cleaned:\n raise ToolError(\"invalid_query\", \"Query is empty.\")\n code = _QUOTED_RE.sub(\"''\", cleaned)\n if \";\" in code:\n raise ToolError(\"multiple_statements_not_allowed\", \"Only one read-only SQL statement is allowed.\")\n if not _ALLOWED_START_RE.match(code):\n raise ToolError(\"query_must_be_read_only\", \"Only read-only queries are allowed (SELECT/WITH).\",\n retryable=True, guidance=\"Provide a read-only query. For DELETE/UPDATE/INSERT requests, \"\n \"ask for SQL generation only.\")\n if match := _FORBIDDEN_SQL_RE.search(code):\n raise ToolError(\"forbidden_sql_operation\", f\"'{match.group(0)}' is not allowed in this tool.\",\n retryable=True, guidance=\"Use a single SELECT/WITH query. SELECT ... INTO, EXEC, and \"\n \"procedures are not allowed.\")\n return cleaned\n\n\ndef _plain(value):\n return value if value is None or isinstance(value, (str, int, float, bool)) else str(value)\n\n\n@tool_config\ndef config() -> ToolConfigResponse:\n # DATABASE_URL is the runtime's project database, not a Core secret.\n return ToolConfigResponse(required_secrets=[])\n\n\n@tool_init\ndef init() -> ToolInitResponse:\n try:\n url = _database_url()\n except ToolError as exc:\n return ToolInitResponse(success=False, message=str(exc))\n engine = create_engine(url, connect_args={\"timeout\": 5, \"login_timeout\": 5})\n try:\n with engine.connect() as connection:\n connection.execute(text(\"SELECT 1\"))\n except Exception as exc:\n return ToolInitResponse(success=False, message=f\"Could not query the project database ({type(exc).__name__}).\")\n finally:\n engine.dispose()\n return ToolInitResponse(success=True, message=\"SQL Server project database connection confirmed.\")\n\n\n@tool(name=\"run_read_only_mssql\",\n description=\"Execute a single read-only T-SQL SELECT/WITH statement against the SQL Server project database \"\n \"and return rows.\")\ndef run_read_only_mssql(args: Args, ctx: ToolContext) -> ToolResponse:\n if args.limit <= 0:\n raise ToolError(\"invalid_limit\", \"limit must be greater than 0.\")\n limit = min(args.limit, 1000)\n query = _validate(args.query)\n engine = _engine(_database_url())\n with engine.connect() as connection:\n transaction = connection.begin()\n try:\n result = connection.execute(text(query))\n columns = list(result.keys())\n rows = [{key: _plain(value) for key, value in zip(columns, row)} for row in result.fetchmany(limit)]\n except Exception as exc:\n raise ToolError(\"db_query_error\", f\"Read-only SQL execution failed: {exc}\"[:2000], retryable=True,\n guidance=\"Verify table/column names and DB connectivity, then retry.\") from exc\n finally:\n transaction.rollback()\n return ToolResponse({\"datasource\": args.datasource, \"query\": query, \"limit\": limit, \"rowCount\": len(rows),\n \"columns\": columns, \"rows\": rows})\n",
29786
- "tags": [],
29787
- "moduleUserKey": "solid-core"
29788
- },
29789
- {
29790
- "name": "run_read_only_postgres",
29791
- "iconName": "table_view",
29792
- "description": "Execute a single read-only SQL statement against the PostgreSQL project database and return rows.",
29793
- "type": "solidx",
29794
- "status": "active",
29795
- "sourceCode": "\"\"\"Read-only SQL against a consuming project database on PostgreSQL, ported from the SolidX agent's\n``run_read_only_sql``. Statements are checked first, then run in a read-only transaction with a statement\ntimeout that is always rolled back.\"\"\"\n\nimport os\nimport re\nfrom functools import lru_cache\n\nfrom pydantic import BaseModel, Field\nfrom sqlalchemy import create_engine, text\nfrom sqlalchemy.engine import make_url\nfrom agenthub.sdk import (tool, ToolContext, ToolError, ToolResponse, ToolConfigResponse,\n ToolInitResponse, tool_config, tool_init)\n\nBACKEND = \"postgresql\"\n_FORBIDDEN_SQL_RE = re.compile(\n r\"\\b(insert|update|delete|upsert|merge|drop|truncate|alter|create|replace|grant|revoke|vacuum|analyze|refresh)\\b\",\n re.IGNORECASE,\n)\n_ALLOWED_START_RE = re.compile(r\"^\\s*(select|with|explain|show)\\b\", re.IGNORECASE)\n_SQL_COMMENT_RE = re.compile(r\"(--[^\\n]*|/\\*.*?\\*/)\", re.DOTALL)\n\n\nclass Args(BaseModel):\n query: str = Field(description=\"PostgreSQL statement to execute. Only read-only statements are allowed.\")\n datasource: str = Field(\"default\", description='Datasource name (currently informational; default \"default\").')\n limit: int = Field(100, description=\"Maximum rows to return (default 100, max 1000).\")\n\n\ndef _database_url():\n # AGENTHUB_READONLY_DATABASE_URL may point at a read-only role; DATABASE_URL is the project database.\n raw = os.environ.get(\"AGENTHUB_READONLY_DATABASE_URL\") or os.environ.get(\"DATABASE_URL\")\n if not raw:\n raise ToolError(\"db_query_error\", \"No project database is configured.\")\n url = make_url(raw)\n if url.get_backend_name() != BACKEND:\n raise ToolError(\"unsupported_database\", f\"The project database is {url.get_backend_name()}, not PostgreSQL.\",\n guidance=\"Use run_read_only_mssql for SQL Server.\")\n return url\n\n\n@lru_cache(maxsize=2)\ndef _engine(url):\n return create_engine(url, pool_pre_ping=True, pool_size=2, max_overflow=0)\n\n\ndef _validate(sql: str) -> str:\n cleaned = _SQL_COMMENT_RE.sub(\"\", sql or \"\").strip()\n if not cleaned:\n raise ToolError(\"invalid_query\", \"Query is empty.\")\n if \";\" in cleaned:\n raise ToolError(\"multiple_statements_not_allowed\", \"Only one read-only SQL statement is allowed.\")\n if not _ALLOWED_START_RE.match(cleaned):\n raise ToolError(\"query_must_be_read_only\", \"Only read-only queries are allowed (SELECT/WITH/EXPLAIN/SHOW).\",\n retryable=True, guidance=\"Provide a read-only query. For DELETE/UPDATE/INSERT requests, \"\n \"ask for SQL generation only.\")\n if _FORBIDDEN_SQL_RE.search(cleaned):\n raise ToolError(\"forbidden_sql_operation\", \"Mutating SQL operations are not allowed in this tool.\",\n retryable=True, guidance=\"Use only read-only SQL. If you need a DELETE query, request query \"\n \"text and run it manually after validation.\")\n return cleaned\n\n\ndef _plain(value):\n return value if value is None or isinstance(value, (str, int, float, bool)) else str(value)\n\n\n@tool_config\ndef config() -> ToolConfigResponse:\n # DATABASE_URL is the runtime's project database, not a Core secret.\n return ToolConfigResponse(required_secrets=[])\n\n\n@tool_init\ndef init() -> ToolInitResponse:\n try:\n url = _database_url()\n except ToolError as exc:\n return ToolInitResponse(success=False, message=str(exc))\n engine = create_engine(url, connect_args={\"connect_timeout\": 5} if url.get_backend_name() == \"postgresql\" else {})\n try:\n with engine.connect() as connection:\n connection.execute(text(\"SELECT 1\"))\n except Exception as exc:\n return ToolInitResponse(success=False, message=f\"Could not query the project database ({type(exc).__name__}).\")\n finally:\n engine.dispose()\n return ToolInitResponse(success=True, message=\"PostgreSQL project database connection confirmed.\")\n\n\n@tool(name=\"run_read_only_postgres\",\n description=\"Execute a single read-only SQL statement against the PostgreSQL project database and return rows.\")\ndef run_read_only_postgres(args: Args, ctx: ToolContext) -> ToolResponse:\n if args.limit <= 0:\n raise ToolError(\"invalid_limit\", \"limit must be greater than 0.\")\n limit = min(args.limit, 1000)\n query = _validate(args.query)\n engine = _engine(_database_url())\n with engine.connect() as connection:\n transaction = connection.begin()\n try:\n if engine.dialect.name == \"postgresql\":\n # Defence in depth on top of the statement checks above.\n connection.execute(text(\"SET TRANSACTION READ ONLY\"))\n connection.execute(text(\"SET LOCAL statement_timeout = 30000\"))\n result = connection.execute(text(query))\n columns = list(result.keys())\n rows = [{key: _plain(value) for key, value in zip(columns, row)} for row in result.fetchmany(limit)]\n except Exception as exc:\n raise ToolError(\"db_query_error\", f\"Read-only SQL execution failed: {exc}\"[:2000], retryable=True,\n guidance=\"Verify table/column names and DB connectivity, then retry.\") from exc\n finally:\n transaction.rollback()\n return ToolResponse({\"datasource\": args.datasource, \"query\": query, \"limit\": limit, \"rowCount\": len(rows),\n \"columns\": columns, \"rows\": rows})\n",
29796
- "tags": [],
29797
- "moduleUserKey": "solid-core"
29798
- },
29799
- {
29800
- "name": "web_search",
29801
- "iconName": "travel_explore",
29802
- "description": "Search the web and optionally fetch readable text from the top results.",
29803
- "type": "solidx",
29804
- "status": "active",
29805
- "sourceCode": "import re\nfrom concurrent.futures import ThreadPoolExecutor\nfrom html.parser import HTMLParser\nfrom urllib.parse import parse_qs, urlparse\n\nimport requests\nfrom pydantic import BaseModel\nfrom agenthub.sdk import (tool, ToolContext, ToolError, ToolResponse, ToolConfigResponse,\n ToolInitResponse, tool_config, tool_init)\n\nSEARCH_URL = \"https://html.duckduckgo.com/html/\"\nHEADERS = {\"User-Agent\": \"Mozilla/5.0 (compatible; AgentHub/1.0; +https://solidxai.com)\",\n \"Accept-Language\": \"en-US,en;q=0.8\"}\nSKIPPED_TAGS = {\"script\", \"style\", \"noscript\", \"svg\", \"nav\", \"footer\", \"header\", \"form\", \"iframe\", \"template\"}\n\n\nclass Args(BaseModel):\n query: str\n max_results: int = 5\n fetch_pages: int = 0\n max_page_chars: int = 8000\n region: str = \"wt-wt\"\n\n\nclass _ResultParser(HTMLParser):\n \"\"\"Collects title, url, and snippet from DuckDuckGo's HTML results page.\"\"\"\n\n def __init__(self):\n super().__init__()\n self.results: list[dict] = []\n self.field: str | None = None\n\n def handle_starttag(self, tag, attrs):\n attributes = dict(attrs)\n classes = (attributes.get(\"class\") or \"\").split()\n if tag == \"a\" and \"result__a\" in classes:\n self.results.append({\"title\": \"\", \"url\": _target(attributes.get(\"href\") or \"\"), \"snippet\": \"\"})\n self.field = \"title\"\n elif \"result__snippet\" in classes and self.results:\n self.field = \"snippet\"\n\n def handle_endtag(self, tag):\n if tag in {\"a\", \"td\", \"div\"}:\n self.field = None\n\n def handle_data(self, data):\n if self.field:\n self.results[-1][self.field] += data\n\n\nclass _TextParser(HTMLParser):\n def __init__(self):\n super().__init__()\n self.title, self.parts, self.skipping, self.in_title = \"\", [], 0, False\n\n def handle_starttag(self, tag, attrs):\n self.skipping += tag in SKIPPED_TAGS\n self.in_title = self.in_title or tag == \"title\"\n\n def handle_endtag(self, tag):\n self.skipping -= tag in SKIPPED_TAGS and self.skipping > 0\n self.in_title = self.in_title and tag != \"title\"\n\n def handle_data(self, data):\n if self.in_title:\n self.title += data\n elif not self.skipping:\n self.parts.append(data)\n\n\ndef _target(href: str) -> str:\n \"\"\"Unwrap DuckDuckGo's /l/?uddg= redirect.\"\"\"\n parsed = urlparse(href if \"://\" in href else \"https:\" + href if href.startswith(\"//\") else href)\n if parsed.netloc.endswith(\"duckduckgo.com\") and parsed.path == \"/l/\":\n return parse_qs(parsed.query).get(\"uddg\", [\"\"])[0]\n return parsed.geturl()\n\n\ndef _clean(value: str) -> str:\n return re.sub(r\"\\s+\", \" \", value).strip()\n\n\ndef _fetch(url: str, max_chars: int) -> dict:\n try:\n with requests.get(url, headers=HEADERS, timeout=15, stream=True) as response:\n response.raise_for_status()\n content_type = response.headers.get(\"content-type\", \"\")\n if not content_type.startswith((\"text/html\", \"text/plain\", \"application/xhtml\")):\n return {\"error\": f\"Unsupported content type {content_type or 'unknown'}\"}\n raw = response.raw.read(2_000_000, decode_content=True)\n html = raw.decode(response.encoding or \"utf-8\", errors=\"replace\")\n except requests.RequestException as exc:\n return {\"error\": type(exc).__name__}\n if content_type.startswith(\"text/plain\"):\n return {\"content\": _clean(html)[:max_chars]}\n parser = _TextParser()\n parser.feed(html)\n text = _clean(\" \".join(parser.parts))\n return {\"page_title\": _clean(parser.title), \"content\": text[:max_chars], \"truncated\": len(text) > max_chars}\n\n\n@tool_config\ndef config() -> ToolConfigResponse:\n return ToolConfigResponse(required_secrets=[])\n\n\n@tool_init\ndef init() -> ToolInitResponse:\n try:\n response = requests.get(SEARCH_URL, headers=HEADERS, timeout=5)\n except requests.RequestException as exc:\n return ToolInitResponse(success=False, message=f\"Could not reach the search provider ({type(exc).__name__}).\")\n if response.status_code >= 500:\n return ToolInitResponse(success=False, message=f\"Search provider returned HTTP {response.status_code}.\")\n return ToolInitResponse(success=True, message=\"Search provider is reachable.\")\n\n\n@tool(name=\"web_search\", description=\"Search the web and optionally fetch readable text from the top results.\")\ndef web_search(args: Args, ctx: ToolContext) -> ToolResponse:\n if not args.query.strip():\n raise ToolError(\"invalid_query\", \"Query must not be empty\")\n try:\n response = requests.post(SEARCH_URL, data={\"q\": args.query, \"kl\": args.region}, headers=HEADERS, timeout=20)\n except requests.RequestException as exc:\n raise ToolError(\"search_unavailable\", type(exc).__name__, retryable=True) from exc\n if response.status_code != 200 or \"anomaly-modal\" in response.text:\n raise ToolError(\"search_unavailable\", f\"Search provider returned {response.status_code}\", retryable=True,\n guidance=\"Retry later or rephrase the query\")\n parser = _ResultParser()\n parser.feed(response.text)\n results, seen = [], set()\n for item in parser.results:\n url = item[\"url\"]\n if not url.startswith((\"http://\", \"https://\")) or urlparse(url).netloc.endswith(\"duckduckgo.com\") or url in seen:\n continue\n seen.add(url)\n results.append({\"title\": _clean(item[\"title\"]), \"url\": url, \"snippet\": _clean(item[\"snippet\"])})\n if len(results) >= max(1, min(args.max_results, 10)):\n break\n fetch = results[:max(0, min(args.fetch_pages, 5))]\n if fetch:\n max_chars = max(500, min(args.max_page_chars, 20000))\n with ThreadPoolExecutor(max_workers=len(fetch)) as pool:\n for result, page in zip(fetch, pool.map(lambda item: _fetch(item[\"url\"], max_chars), fetch)):\n result.update(page)\n return ToolResponse({\"query\": args.query, \"results\": results})\n",
29806
- "tags": [],
29807
- "moduleUserKey": "solid-core"
29808
- }
29809
- ],
29810
- "agenthubSkills": [
29811
- {
29812
- "name": "filesystem",
29813
- "iconName": "folder_open",
29814
- "description": "Use for file discovery and edits in the consuming SolidX project (solid-ui and solid-api) with the filesystem tool.",
29815
- "type": "solidx",
29816
- "body": "# Filesystem\n\nUse this skill for deterministic file discovery and edits in the consuming SolidX project: frontend code in `solid-ui/**` and backend code in `solid-api/**`.\n\n## Tool Boundary\n\n- Use `filesystem` as the primary mechanism for file discovery, inspection, editing, and creation.\n- Do not fall back to shell commands for file lookup or reads when `filesystem(action: \"search\"|\"read\")` can provide the context.\n- Do not use shell commands to create or edit files.\n- Use `bash` only for verification work that `filesystem` cannot do, such as builds, typechecks, or test runs.\n\n## Path and Root Rules\n\n- Paths are relative to the consuming project root (`CONTAINER_SOLIDX_CONSUMING_PROJECT_ROOT`, or `SOLIDX_PROJECT_ROOT`). Absolute paths must stay under that root.\n- Frontend code lives under `solid-ui/**`, backend code under `solid-api/**`.\n- `path_outside_workspace` means the target resolved outside the root; use a project-relative path.\n\n## Reading SolidX Metadata\n\nSolidX modules, models, fields, views, menus, roles, and the rest are defined in metadata JSON files inside `solid-api`. Read them with `filesystem`; never guess module, model, or field names.\n\n### Where metadata lives\n\n| Source | Path |\n| --- | --- |\n| A project module | `solid-api/src/<module>/metadata/<module>-metadata.json` |\n| SolidX core (read-only) | `solid-api/node_modules/@solidxai/core/src/seeders/seed-data/solid-core-metadata.json` (or `.../dist/seeders/seed-data/...` when `src` is absent) |\n| Email / SMS template bodies | `solid-api/src/<module>/metadata/email-templates/*.handlebars.html`, `.../sms-templates/*.handlebars.txt` |\n\nNever edit the core metadata file; it is a package dependency.\n\n### File shape\n\nTop-level keys of a metadata file:\n\n- `moduleMetadata`: the module (`name`, `displayName`, ...) and `moduleMetadata.models[]`. Each model has `singularName`, `pluralName`, `displayName`, `tableName`, `dataSource`, `userKeyFieldUserKey`, and `fields[]`.\n- Each field has `name`, `displayName`, `type` (`shortText`, `longText`, `int`, `boolean`, `date`, `selectionStatic`, `relation`, `computed`, ...), `ormType`, `required`, `unique`, `defaultValue`, and type-specific keys such as `selectionStaticValues` (`\"value:Label\"` strings) or `relationType` / `relationCoModelSingularName`.\n- `views[]` (`name`, `type` list/form/kanban/card/tree, `modelUserKey`, `layout`), `actions[]`, `menus[]`, `roles[]`, `permissions[]`, `securityRules[]`, `listOfValues[]`, `scheduledJobs[]`, `emailTemplates[]`, `smsTemplates[]`, `modelSequences[]`, `savedFilters[]`, `dashboards[]`, `mediaStorageProviders[]`.\n\nColumns in the database use snake_case of the field `name` (for example `lastLoadError` is `last_load_error`) unless the field sets `columnName`.\n\n### How to read it\n\nMetadata files are large; locate first, then read narrow line windows.\n\n1. List the modules:\n ```json\n { \"action\": \"search\", \"query\": \"\\\"moduleMetadata\\\"\", \"path\": \"solid-api/src\", \"glob\": \"*-metadata.json\", \"context_lines\": 0 }\n ```\n Each match is one module's metadata file; its folder under `solid-api/src` is the module name.\n2. Find a model by name:\n ```json\n { \"action\": \"search\", \"query\": \"\\\"singularName\\\": \\\"order\\\"\", \"path\": \"solid-api/src\", \"glob\": \"*-metadata.json\", \"context_lines\": 0 }\n ```\n The match gives the file and line number where the model definition starts.\n3. Read the model and its fields from that line, in windows:\n ```json\n { \"action\": \"read\", \"path\": \"solid-api/src/sales/metadata/sales-metadata.json\", \"start_line\": 120, \"end_line\": 420 }\n ```\n Keep reading the next window until the model's `fields` array closes.\n4. Find views, menus, or roles for a model with a targeted search, for example `\"modelUserKey\": \"order\"` or `\"name\": \"order-list-view\"`, then read around the match.\n5. For core models (users, roles, settings, agent registries), search and read the core metadata file by passing its full path as `path`; it is outside `solid-api/src`, so searches of that folder never reach it.\n\nUse the metadata you read to build correct API calls, SQL (`run_read_only_postgres` or `run_read_only_mssql`), and code edits. When a field is a relation, read the co-model's definition as well.\n\n## Tool Contract\n\n`filesystem` exposes four actions.\n\n### `filesystem(action: \"search\")`\n\nUse to locate symbols and usages before edits.\n\n- `query`: string, required. A regex/text pattern, not plain literal text. If you copy source code into it, escape regex metacharacters first (`{ } ( ) [ ] . * + ? | ^ $ \\`). For multiple literal snippets, escape each and join them with `|`.\n- `path`: string, optional. Defaults to `solid-ui`; use `solid-api` for backend.\n- `glob`: string, optional (for example `\"*.tsx\"` or `\"*.ts\"`).\n- `case_sensitive`: boolean, default `false`.\n- `max_matches`: integer, default `200`.\n- `context_lines`: integer, default `2`.\n\n```json\n{\n \"action\": \"search\",\n \"query\": \"class .*Service|@Controller|@Injectable\",\n \"path\": \"solid-api\",\n \"glob\": \"*.ts\"\n}\n```\n\nUses ripgrep (respects `.gitignore`, skips hidden and binary files); falls back to grep when ripgrep is unavailable.\n\n### `filesystem(action: \"read\")`\n\nUse for precise inspection before editing.\n\n- `path`: string, required.\n- `start_line`, `end_line`: optional 1-based integers (inclusive). To read the whole file, omit them; do not send empty strings or placeholders.\n- `max_chars`: integer, default `20000`. `truncated: true` means read a narrower window.\n\n```json\n{ \"action\": \"read\", \"path\": \"solid-ui/src/pages/orders/order-list.tsx\", \"start_line\": 1, \"end_line\": 220 }\n```\n\n### `filesystem(action: \"edit\")`\n\nUse for surgical changes to **existing** files. Each entry replaces `oldText` with `newText`; there are no line numbers or diffs. The applier tries an exact substring match first (first occurrence only), then a whitespace-tolerant line-by-line match.\n\nRequired pre-edit discipline:\n\n- Read the target with `filesystem(action: \"read\")` immediately before every edit. Read enough surrounding context to make each `oldText` unique.\n- Build `oldText` from the returned source verbatim. Never reconstruct it from memory, an earlier version, or a partial prompt snippet.\n- If the file changed after the read, read it again and rebuild the edit. Do not retry a stale payload.\n\n- `path`: string, required; the file must exist.\n- `edits`: non-empty array of `{ \"oldText\": string, \"newText\": string }`.\n- `dry_run`: boolean, optional; validate without persisting.\n\n```json\n{\n \"action\": \"edit\",\n \"path\": \"solid-api/src/orders/orders.service.ts\",\n \"edits\": [{ \"oldText\": \"const enabled = false;\", \"newText\": \"const enabled = true;\" }]\n}\n```\n\nMultiple edits apply sequentially; each sees the previous edit's result. Include 1–3 surrounding lines when needed to make `oldText` unique. Edits are atomic: if any edit fails to match, the file is unchanged.\n\n### `filesystem(action: \"write\")`\n\nUse to create new files or intentionally replace a whole file. Writes are atomic (temp file + rename) and parent directories are created automatically.\n\n- `path`: string, required.\n- `content`: string, required; full UTF-8 content.\n- `overwrite`: boolean, default `false`. Without it, writing an existing file fails with `file_exists`.\n\n```json\n{\n \"action\": \"write\",\n \"path\": \"solid-ui/src/pages/landing/Landing.tsx\",\n \"content\": \"import React from 'react';\\n\\nexport function Landing() {\\n return <div>Welcome</div>;\\n}\\n\"\n}\n```\n\nPrefer `action: \"edit\"` for partial changes; reserve `overwrite: true` for genuine full rewrites.\n\n## Recommended Flow\n\n1. `search` to locate files and references.\n2. `read` targeted line windows around the matches.\n3. `edit` for surgical changes, or `write` for new files.\n4. `read` the file again to confirm the change persisted before chaining dependent edits.\n5. If verification is required, run build, typecheck, or test commands with `bash` after all edits.\n\n## Conventions\n\n- For UI under `solid-ui/**`, prefer Radix UI + shadcn/ui patterns for behaviour and Tailwind CSS utilities for layout and spacing; reuse existing primitives before adding custom CSS.\n- For backend code, keep controller, service, and repository signatures aligned (method names, arguments, return types).\n- Prefer small focused edits over full-file rewrites.\n\n## Error Repair Playbook\n\n- `search_backend_not_found`: neither ripgrep nor grep is installed; report it.\n- `path_not_found` (search): the `path` does not exist. Drop it (or pass an existing parent) and narrow with `glob`, e.g. `glob: \"**/CurrencyExchange/*.tsx\"`. Do not retry the same call.\n- `path_outside_workspace`: use a path relative to the project root.\n- `edit_no_match`: `oldText` was not found. Re-read the file and build a new `oldText` from the current content. Do not retry the same payload.\n- `noop_edit`: `oldText` equals `newText`; drop that entry.\n- `file_not_found` (edit): the file does not exist; create it with `action: \"write\"`.\n- `file_exists` (write): the file exists and `overwrite` was not set. Use `action: \"edit\"`, or `overwrite: true` for an intentional full rewrite.\n- `binary_or_non_utf8`: the file is not UTF-8 text; this tool cannot read or edit it.\n- Validation errors: the payload was rejected before any I/O; fix the argument types and resubmit.\n",
29817
- "tags": [],
29818
- "moduleUserKey": "solid-core"
29819
- },
29820
- {
29821
- "name": "web_research",
29822
- "iconName": "travel_explore",
29823
- "description": "Research a question on the web with web_search and cite sources.",
29824
- "type": "solidx",
29825
- "body": "# Web research\n\nUse this when the answer depends on current or external information.\n\n1. Call `web_search` with a focused query. Start with `max_results` 5 and `fetch_pages` 0 to scan titles and snippets.\n2. Pick the most authoritative results (official docs, vendor sites, standards bodies) and call `web_search` again with `fetch_pages` 2-3 to read the page text.\n3. If results are thin, rephrase: add a product name, a version, or a site name; remove filler words.\n4. Cross-check facts that matter against at least two independent sources.\n5. Answer with the facts you verified and list the source URLs you relied on. Say clearly when sources disagree or nothing reliable was found.\n\nDo not invent URLs or quote text you did not fetch. If `web_search` returns `search_unavailable`, wait and retry once, then tell the user.\n",
29826
- "tags": [],
29827
- "moduleUserKey": "solid-core"
29828
- },
29829
- {
29830
- "name": "postgres_query_assistant",
29831
- "iconName": "table_view",
29832
- "description": "Use to fetch records, explore schema, read sample data, or write SQL for user-run changes on a PostgreSQL project database with run_read_only_postgres.",
29833
- "type": "solidx",
29834
- "body": "# PostgreSQL Query Assistant\n\nUse this skill to query a PostgreSQL project database with `run_read_only_postgres`:\n- fetch records with read-only SQL\n- generate SQL for mutations the user runs themselves\n- **discover schema structure** — tables, columns, types, constraints, indexes, views\n- **read sample data** to understand domain objects and their attribute semantics\n\nBefore writing SQL, confirm the project database is PostgreSQL: use `filesystem(action: \"search\", query: \"@SolidDatabaseModule\", path: \"solid-api/src\")` to find the datasource module, `filesystem(action: \"read\", ...)` it, and check its `type()`. Reuse the answer for the rest of the conversation; never ask the user. If the type is `mssql`, use the `mssql_query_assistant` skill and `run_read_only_mssql` instead. A tool error `unsupported_database` means the same thing.\n\n---\n\n## Workflow\n\n1. For record retrieval, build one read-only query and run it with `run_read_only_postgres`.\n2. Return the rows clearly, including the filters used.\n3. For mutating requests (`DELETE`, `UPDATE`, `INSERT`, `ALTER`, ...), optionally run supporting read-only queries with `run_read_only_postgres` to validate tables, columns, and matching rows, then write the SQL for the user without executing it.\n4. Ask the user to review and run mutating SQL manually, preferably after a backup.\n5. For schema or domain questions, run the discovery queries and sample reads below before drawing conclusions.\n\n---\n\n## PostgreSQL Rules for the Tool\n\n- One `SELECT`, `WITH`, `EXPLAIN`, or `SHOW` statement per call; no `;`-separated statements.\n- Pass values as literals in the query; quote identifiers that are reserved words or mixed case with double quotes (`\"order\"`).\n- Limit rows with `LIMIT n` (and `OFFSET n` for paging).\n- Queries run in a read-only transaction with a 30 second statement timeout.\n\n---\n\n## Schema Discovery\n\nApplication tables live in the `public` schema unless the project says otherwise.\n\nTables:\n```sql\nSELECT table_name FROM information_schema.tables\nWHERE table_schema = 'public' AND table_type = 'BASE TABLE' ORDER BY table_name\n```\n\nColumns of a table:\n```sql\nSELECT column_name, data_type, is_nullable, column_default FROM information_schema.columns\nWHERE table_schema = 'public' AND table_name = 'orders' ORDER BY ordinal_position\n```\n\nForeign keys (outbound from a table; swap the filter to `ccu.table_name` for inbound):\n```sql\nSELECT tc.table_name, kcu.column_name, ccu.table_name AS references_table, ccu.column_name AS references_column\nFROM information_schema.table_constraints tc\nJOIN information_schema.key_column_usage kcu ON tc.constraint_name = kcu.constraint_name AND tc.table_schema = kcu.table_schema\nJOIN information_schema.constraint_column_usage ccu ON tc.constraint_name = ccu.constraint_name AND tc.table_schema = ccu.table_schema\nWHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_name = 'orders'\n```\n\nPrimary and unique keys: the same join filtered on `tc.constraint_type IN ('PRIMARY KEY', 'UNIQUE')`.\n\nIndexes:\n```sql\nSELECT indexname, indexdef FROM pg_indexes WHERE schemaname = 'public' AND tablename = 'orders'\n```\n\nViews:\n```sql\nSELECT table_name, view_definition FROM information_schema.views WHERE table_schema = 'public'\n```\n\n---\n\n## Sample Data Reading\n\nUse small, representative samples to understand domain semantics — what the data actually means, how fields are used, and what values are common. `run_read_only_postgres` always caps returned rows at `limit`, so a row-limiting clause isn't required for correctness, but a `LIMIT` is still good practice on large tables because it stops the database producing rows that would be discarded.\n\n- **Representative sample:** fetch 10–20 rows from a table to see its shape and real values.\n- **Value distribution:** `COUNT(*)` grouped by a status/type/stage column to see which business states exist and how populated each is.\n- **Sparsity:** compare `COUNT(*)` with `COUNT(<column>)` to see how consistently a column is filled.\n- **Relation sample:** join a parent and child table on the FK column and read a few rows to see how the relationship is used.\n\n---\n\n## Semantic Discovery Strategy\n\nWhen the goal is to understand the domain (not just fetch specific records):\n\n1. List all tables to get the full surface area.\n2. Inspect columns and types for the tables of interest.\n3. Map the relationship graph with the foreign key query.\n4. Read a small sample from each key table.\n5. Check value distributions for status/type/enum columns.\n6. Join related tables to see how parent-child and many-to-many relationships are populated.\n\nOnly draw conclusions about domain semantics after reading actual data — column names alone are often insufficient.\n\n---\n\n## Rules\n\n- `run_read_only_postgres` is strictly read-only and rejects mutating statements.\n- Never attempt to execute `DELETE`, `UPDATE`, `INSERT`, `DROP`, `TRUNCATE`, `ALTER`, or other write/DDL operations.\n- When the user asks to run destructive SQL, provide the exact PostgreSQL SQL and a short safety note for manual execution.\n- Prefer scoped filters and a `LIMIT` for retrieval queries unless the user explicitly asks for full output.\n- If table or column names are ambiguous, run the schema discovery queries first rather than guessing.\n- SolidX system tables use the `ss_` prefix; leave them out of domain analysis unless the user asks about SolidX itself.\n",
29835
- "tags": [],
29836
- "moduleUserKey": "solid-core"
29837
- },
29838
- {
29839
- "name": "mssql_query_assistant",
29840
- "iconName": "table_view",
29841
- "description": "Use to fetch records, explore schema, read sample data, or write T-SQL for user-run changes on a SQL Server project database with run_read_only_mssql.",
29842
- "type": "solidx",
29843
- "body": "# SQL Server Query Assistant\n\nUse this skill to query a Microsoft SQL Server project database with `run_read_only_mssql`:\n- fetch records with read-only T-SQL\n- generate T-SQL for mutations the user runs themselves\n- **discover schema structure** — tables, columns, types, constraints, indexes, views\n- **read sample data** to understand domain objects and their attribute semantics\n\nBefore writing SQL, confirm the project database is SQL Server (`mssql`): use `filesystem(action: \"search\", query: \"@SolidDatabaseModule\", path: \"solid-api/src\")` to find the datasource module, `filesystem(action: \"read\", ...)` it, and check its `type()`. Reuse the answer for the rest of the conversation; never ask the user. If the type is `postgres`, use the `postgres_query_assistant` skill and `run_read_only_postgres` instead. A tool error `unsupported_database` means the same thing.\n\n---\n\n## Workflow\n\n1. For record retrieval, build one read-only query and run it with `run_read_only_mssql`.\n2. Return the rows clearly, including the filters used.\n3. For mutating requests (`DELETE`, `UPDATE`, `INSERT`, `ALTER`, ...), optionally run supporting read-only queries with `run_read_only_mssql` to validate tables, columns, and matching rows, then write the SQL for the user without executing it.\n4. Ask the user to review and run mutating SQL manually, preferably after a backup.\n5. For schema or domain questions, run the discovery queries and sample reads below before drawing conclusions.\n\n---\n\n## T-SQL Rules for the Tool\n\n- One `SELECT` or `WITH` statement per call. T-SQL runs consecutive statements even without `;`, so the tool rejects any extra statement keyword.\n- Rejected: `SELECT ... INTO`, `EXEC` / `EXECUTE`, stored procedures (`sp_*`, `xp_*`), `OPENROWSET` / `OPENQUERY`, `DECLARE`, `SET`, `USE`, `WAITFOR`, and all DML/DDL.\n- Limit rows with `SELECT TOP (n) ...`. There is no `LIMIT`; paging uses `ORDER BY ... OFFSET n ROWS FETCH NEXT m ROWS ONLY` and requires `ORDER BY`.\n- Quote reserved or unusual identifiers with brackets (`[order]`); Unicode string literals use `N'...'`.\n- Tables usually live in the `dbo` schema; qualify names as `dbo.orders` when in doubt.\n- Each query has a 30 second timeout and runs in a transaction that is always rolled back.\n\n---\n\n## Schema Discovery\n\nTables:\n```sql\nSELECT TABLE_SCHEMA, TABLE_NAME FROM INFORMATION_SCHEMA.TABLES\nWHERE TABLE_TYPE = 'BASE TABLE' ORDER BY TABLE_SCHEMA, TABLE_NAME\n```\n\nColumns of a table:\n```sql\nSELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, IS_NULLABLE, COLUMN_DEFAULT\nFROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'orders' ORDER BY ORDINAL_POSITION\n```\n\nForeign keys (outbound from a table; filter on `fkc.referenced_object_id` for inbound):\n```sql\nSELECT OBJECT_NAME(fkc.parent_object_id) AS table_name, pc.name AS column_name,\n OBJECT_NAME(fkc.referenced_object_id) AS references_table, rc.name AS references_column\nFROM sys.foreign_key_columns fkc\nJOIN sys.columns pc ON pc.object_id = fkc.parent_object_id AND pc.column_id = fkc.parent_column_id\nJOIN sys.columns rc ON rc.object_id = fkc.referenced_object_id AND rc.column_id = fkc.referenced_column_id\nWHERE fkc.parent_object_id = OBJECT_ID('dbo.orders')\n```\n\nPrimary and unique keys:\n```sql\nSELECT tc.CONSTRAINT_TYPE, kcu.COLUMN_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc\nJOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME\nWHERE tc.TABLE_NAME = 'orders' AND tc.CONSTRAINT_TYPE IN ('PRIMARY KEY', 'UNIQUE')\n```\n\nIndexes:\n```sql\nSELECT i.name AS index_name, i.type_desc, i.is_unique, c.name AS column_name\nFROM sys.indexes i\nJOIN sys.index_columns ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id\nJOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id\nWHERE i.object_id = OBJECT_ID('dbo.orders') ORDER BY i.name, ic.key_ordinal\n```\n\nViews:\n```sql\nSELECT TABLE_SCHEMA, TABLE_NAME, VIEW_DEFINITION FROM INFORMATION_SCHEMA.VIEWS\n```\n\n---\n\n## Sample Data Reading\n\nUse small, representative samples to understand domain semantics — what the data actually means, how fields are used, and what values are common. `run_read_only_mssql` always caps returned rows at `limit`, so a row-limiting clause isn't required for correctness, but `TOP (n)` is still good practice on large tables because it stops the database producing rows that would be discarded.\n\n- **Representative sample:** fetch 10–20 rows from a table to see its shape and real values.\n- **Value distribution:** `COUNT(*)` grouped by a status/type/stage column to see which business states exist and how populated each is.\n- **Sparsity:** compare `COUNT(*)` with `COUNT(<column>)` to see how consistently a column is filled.\n- **Relation sample:** join a parent and child table on the FK column and read a few rows to see how the relationship is used.\n\n---\n\n## Semantic Discovery Strategy\n\nWhen the goal is to understand the domain (not just fetch specific records):\n\n1. List all tables to get the full surface area.\n2. Inspect columns and types for the tables of interest.\n3. Map the relationship graph with the foreign key query.\n4. Read a small sample from each key table.\n5. Check value distributions for status/type/enum columns.\n6. Join related tables to see how parent-child and many-to-many relationships are populated.\n\nOnly draw conclusions about domain semantics after reading actual data — column names alone are often insufficient.\n\n---\n\n## Rules\n\n- `run_read_only_mssql` is strictly read-only and rejects mutating statements.\n- Never attempt to execute `DELETE`, `UPDATE`, `INSERT`, `DROP`, `TRUNCATE`, `ALTER`, or other write/DDL operations.\n- When the user asks to run destructive SQL, provide the exact T-SQL SQL and a short safety note for manual execution.\n- Prefer scoped filters and `TOP (n)` for retrieval queries unless the user explicitly asks for full output.\n- If table or column names are ambiguous, run the schema discovery queries first rather than guessing.\n- SolidX system tables use the `ss_` prefix; leave them out of domain analysis unless the user asks about SolidX itself.\n",
29844
- "tags": [],
29845
- "moduleUserKey": "solid-core"
29846
- },
29847
- {
29848
- "name": "quality_checks",
29849
- "iconName": "verified",
29850
- "description": "Use when code changes need validation with builds, type checks, and tests.",
29851
- "type": "solidx",
29852
- "body": "# Quality Checks\n\nUse this skill when code changes need validation.\n\n## Common Commands\n\nRun each with `bash`, one command per call. Commands run in the consuming project root; set `cwd` for a sub-project instead of using `cd`.\n\n| Check | `command` | `cwd` |\n| --- | --- | --- |\n| Backend typecheck | `npx tsc --noEmit` | `solid-api` |\n| Backend tests | `npm test` | `solid-api` |\n| Backend lint | `npx eslint src/ --ext .ts,.tsx` | `solid-api` |\n| Frontend typecheck | `npx tsc --noEmit` | `solid-ui` |\n| Frontend tests | `npm test` | `solid-ui` |\n\nShell operators (`&&`, `|`, `;`, redirects) are rejected.\n\n## Rules\n\n- Run validation after backend or frontend code edits.\n- Prefer a fast typecheck or targeted test first, then broader validation if needed.\n- Fix validation failures before moving on.\n- A non-zero `status` means the check failed; read the end of `stdout`/`stderr` for the errors.\n",
29853
- "tags": [],
29854
- "moduleUserKey": "solid-core"
29855
- },
29856
- {
29857
- "name": "solidctl",
29858
- "iconName": "terminal",
29859
- "description": "Use to run SolidX CLI operations (build, seed, generate, info, test, upgrade) with bash and read their results.",
29860
- "type": "solidx",
29861
- "body": "# Solidctl Operations\n\nUse this skill when the user asks for SolidX CLI actions (build, seed, generate, info, test, upgrade) or a workflow needs a solidctl step after code or metadata changes.\n\n## How to run\n\nRun solidctl with `bash`, one command per call, from the project root (`cwd` `.`, the default):\n\n```json\n{ \"command\": \"npx --yes @solidxai/solidctl@latest build\", \"cwd\": \".\" }\n```\n\n- Always use `npx --yes @solidxai/solidctl@latest <command>` so no install prompt blocks the run.\n- Shell operators (`&&`, `|`, `;`, redirects) are rejected; run dependent steps as separate calls and check each result before the next.\n- Builds and seeds can take minutes. If the call times out, tell the user rather than re-running blindly.\n\n## Supported Commands\n\n- `build` - Build project artifacts (supports `--ui-only`)\n- `seed` - Seed metadata/platform data (supports `--modules-to-seed <A,B>` and `--prune`)\n- `info` - Inspect project information (supports `--detailed`)\n- `generate` - Metadata-driven code generation (`module`, `model -n <modelName>`)\n- `test` - Testing workflows (`test data --setup|--load|--teardown`, `test run ...`)\n- `upgrade` - Upgrade SolidX dependencies (`--stable`, `--tag <tag>`, `--dry-run`)\n- `create-app` - Scaffold a new SolidX project; not for use inside an existing project\n- `release`, `legacy-migrate`, `local-upgrade`, `mcp`, `agent` - advanced/internal; do not run unless the user asks explicitly\n\n## Practical Workflow\n\n1. Metadata change: edit metadata (see the `filesystem` skill) -> `generate module` -> `build` -> `seed`\n2. Testing: `test data --setup` -> `test data --load` -> `test run ...`\n3. Upgrade: `upgrade` -> `build` -> `seed` (if metadata/platform changes are involved)\n\n## High-Value Examples\n\n```text\nnpx --yes @solidxai/solidctl@latest info --detailed\nnpx --yes @solidxai/solidctl@latest build\nnpx --yes @solidxai/solidctl@latest build --ui-only\nnpx --yes @solidxai/solidctl@latest generate module\nnpx --yes @solidxai/solidctl@latest generate model -n feeReceipt\nnpx --yes @solidxai/solidctl@latest seed --modules-to-seed Fees,Onboarding --prune\nnpx --yes @solidxai/solidctl@latest test data --setup\nnpx --yes @solidxai/solidctl@latest test run --module Fees --include-tags smoke\nnpx --yes @solidxai/solidctl@latest upgrade --stable\n```\n\n## Reading the result\n\n`bash` returns `status`, `stdout` (tail), and `stderr` (tail).\n\n- `status` non-zero: the command failed. Read the end of `stdout`/`stderr`, fix the cause, and retry with a corrected command.\n- `status` 0 is not always success. solidctl can swallow a subprocess failure and still print a \"completed\" message. Treat the run as failed when `stderr` contains any of:\n - a line starting with `Error:`\n - `spawn <binary> ENOENT` (a binary solidctl calls, such as `schematics`, is not installed)\n - `UnhandledPromiseRejection`\n - `command not found` or `is not recognized as`\n- Stale build: `stderr` shows `Cannot find module '...'`, `Cannot find module '....module'`, or `Path \"src/...\" does not exist` right after creating or changing a module. The compiled `solid-api/dist` is older than the TypeScript sources. Run `build` first, then retry the original command. Do not rewrite code for this.\n- Logged-and-caught messages such as `console.error(\"Failed to load X:\", err)` during seeding are not fatal on their own.\n\n## Rules\n\n- Run solidctl only for explicit CLI intent or a workflow-required step.\n- Prefer a single precise command over chained speculative commands.\n- If the user says `rebuild`, run `build`.\n- After metadata or model changes, prefer `generate module` unless the user asks for model-only scope.\n- After dependency upgrades, run `build` before further validation.\n- `seed --prune`, `test data --teardown`, and `upgrade` change project data or dependencies; run them only when the user's intent is clear.\n",
29862
- "tags": [],
29863
- "moduleUserKey": "solid-core"
29864
- }
29865
- ],
29866
29688
  "secrets": []
29867
29689
  }
@@ -49,18 +49,18 @@ let AgentToolRegistryService = AgentToolRegistryService_1 = class AgentToolRegis
49
49
  }
50
50
  lifecycleRunner() {
51
51
  const binary = process.platform === 'win32' ? 'python.exe' : 'python';
52
- const configuredSourceRoot = process.env.SOLIDX_AGENTHUB_RUNTIME_PATH;
52
+ const configuredSourceRoot = process.env.AGENT_HUB_RUNTIME_PATH;
53
53
  const sourceRoot = configuredSourceRoot
54
54
  && (0, node_fs_1.existsSync)((0, node_path_1.join)(configuredSourceRoot, 'src', 'agenthub', 'tools', 'tool_lifecycle_check.py'))
55
55
  ? configuredSourceRoot
56
56
  : undefined;
57
57
  const solidxVenv = { root: (0, node_path_1.join)((0, node_os_1.homedir)(), '.solidx', 'agenthub-venv'), sourceRoot };
58
- const localVenv = process.env.SOLIDX_AGENTHUB_RUNTIME_PATH
59
- ? { root: (0, node_path_1.join)(process.env.SOLIDX_AGENTHUB_RUNTIME_PATH, '.venv'), sourceRoot }
58
+ const localVenv = process.env.AGENT_HUB_RUNTIME_PATH
59
+ ? { root: (0, node_path_1.join)(process.env.AGENT_HUB_RUNTIME_PATH, '.venv'), sourceRoot }
60
60
  : undefined;
61
- const preference = process.env.SOLIDX_AGENTHUB_RUNTIME_PREFERENCE?.trim().toLowerCase() || 'solidx';
61
+ const preference = process.env.AGENT_HUB_RUNTIME_PREFERENCE?.trim().toLowerCase() || 'solidx';
62
62
  if (preference !== 'solidx' && preference !== 'local') {
63
- throw new common_1.ServiceUnavailableException('SOLIDX_AGENTHUB_RUNTIME_PREFERENCE must be "solidx" or "local".');
63
+ throw new common_1.ServiceUnavailableException('AGENT_HUB_RUNTIME_PREFERENCE must be "solidx" or "local".');
64
64
  }
65
65
  const candidates = (preference === 'local' ? [localVenv, solidxVenv] : [solidxVenv, localVenv])
66
66
  .filter((candidate) => candidate !== undefined);
@@ -1 +1 @@
1
- {"version":3,"file":"agent-tool-registry.service.js","sourceRoot":"","sources":["../../src/services/agent-tool-registry.service.ts"],"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sourcesContent":["import { BadRequestException, ConflictException, Injectable, Logger, NotFoundException, ServiceUnavailableException } from '@nestjs/common';\nimport { InjectEntityManager } from '@nestjs/typeorm';\nimport { ModuleRef } from '@nestjs/core';\nimport { EntityManager } from 'typeorm';\nimport { createHash } from 'node:crypto';\nimport { spawn } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { homedir, tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { SecretService } from './secret.service';\nimport { AgentTool } from '../entities/agent-tool.entity';\nimport { AgentConfigCatalogService } from './agent-config-version.service';\nimport { AgentToolRegistry } from '../entities/agent-tool-registry.entity';\nimport { AgentToolRegistryRepository } from '../repository/agent-tool-registry.repository';\nimport { CreateAgentToolRegistryDto } from '../dtos/create-agent-tool-registry.dto';\nimport { UpdateAgentToolRegistryDto } from '../dtos/update-agent-tool-registry.dto';\n\n@Injectable()\nexport class AgentToolRegistryService extends AgentConfigCatalogService<AgentToolRegistry>{\n private readonly logger = new Logger(AgentToolRegistryService.name);\n\n constructor(\n @InjectEntityManager(\"default\")\n readonly entityManager: EntityManager,\n readonly repo: AgentToolRegistryRepository,\n readonly moduleRef: ModuleRef,\n readonly secretService: SecretService,\n ) {\n super(entityManager, repo, 'agentToolRegistry', moduleRef, AgentTool, 'agentToolRegistry');\n }\n\n private withChecksum<T extends { type?: string; sourceCode?: string; checksum?: string }>(dto: T, existing?: AgentToolRegistry): T {\n if (!['custom', 'thirdparty'].includes(dto.type ?? existing?.type)) return dto;\n\n const sourceCode = dto.sourceCode ?? existing?.sourceCode;\n if (typeof sourceCode !== 'string') return dto;\n\n return {\n ...dto,\n checksum: createHash('sha256').update(sourceCode, 'utf8').digest('hex'),\n };\n }\n\n private lifecycleRunner(): { python: string; runtimeRoot: string; sourceRoot?: string } {\n const binary = process.platform === 'win32' ? 'python.exe' : 'python';\n const configuredSourceRoot = process.env.SOLIDX_AGENTHUB_RUNTIME_PATH;\n const sourceRoot = configuredSourceRoot\n && existsSync(join(configuredSourceRoot, 'src', 'agenthub', 'tools', 'tool_lifecycle_check.py'))\n ? configuredSourceRoot\n : undefined;\n const solidxVenv = { root: join(homedir(), '.solidx', 'agenthub-venv'), sourceRoot };\n const localVenv = process.env.SOLIDX_AGENTHUB_RUNTIME_PATH\n ? { root: join(process.env.SOLIDX_AGENTHUB_RUNTIME_PATH, '.venv'), sourceRoot }\n : undefined;\n const preference = process.env.SOLIDX_AGENTHUB_RUNTIME_PREFERENCE?.trim().toLowerCase() || 'solidx';\n if (preference !== 'solidx' && preference !== 'local') {\n throw new ServiceUnavailableException('SOLIDX_AGENTHUB_RUNTIME_PREFERENCE must be \"solidx\" or \"local\".');\n }\n const candidates = (preference === 'local' ? [localVenv, solidxVenv] : [solidxVenv, localVenv])\n .filter((candidate): candidate is NonNullable<typeof candidate> => candidate !== undefined);\n for (const candidate of candidates) {\n const python = join(candidate.root, process.platform === 'win32' ? 'Scripts' : 'bin', binary);\n if (existsSync(python)) return { python, runtimeRoot: candidate.root, sourceRoot: candidate.sourceRoot };\n }\n throw new ServiceUnavailableException('AgentHub runtime virtual environment was not found.');\n }\n\n private lifecycleDatabaseUrl(): string {\n const options = this.entityManager.connection.options as any;\n if (options.type !== 'postgres') {\n throw new ServiceUnavailableException('Tool checks require Core to use PostgreSQL.');\n }\n if (options.url) return options.url;\n const host = String(options.host ?? 'localhost');\n const formattedHost = host.includes(':') && !host.startsWith('[') ? `[${host}]` : host;\n const credentials = options.username\n ? `${encodeURIComponent(String(options.username))}:${encodeURIComponent(String(options.password ?? ''))}@`\n : '';\n const ssl = options.ssl ? '?sslmode=require' : '';\n return `postgresql://${credentials}${formattedHost}:${options.port ?? 5432}/${encodeURIComponent(String(options.database))}${ssl}`;\n }\n\n private async runLifecycleScript(request: Record<string, unknown>): Promise<Record<string, any>> {\n const runner = this.lifecycleRunner();\n const requestJson = JSON.stringify(request);\n const childEnv = {\n PATH: process.env.PATH ?? '',\n VIRTUAL_ENV: runner.runtimeRoot,\n HOME: homedir(),\n DATABASE_URL: this.lifecycleDatabaseUrl(),\n ...(process.env.SYSTEMROOT ? { SYSTEMROOT: process.env.SYSTEMROOT } : {}),\n ...(runner.sourceRoot ? { PYTHONPATH: join(runner.sourceRoot, 'src') } : {}),\n };\n return new Promise((resolve, reject) => {\n const child = spawn(runner.python, ['-m', 'agenthub.tools.tool_lifecycle_check'], {\n cwd: runner.sourceRoot ?? tmpdir(),\n env: childEnv,\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n let stdout = '';\n let stderr = '';\n let settled = false;\n const finish = (callback: () => void) => {\n if (settled) return;\n settled = true;\n clearTimeout(timeout);\n callback();\n };\n const timeout = setTimeout(() => {\n child.kill('SIGKILL');\n finish(() => reject(new ServiceUnavailableException('Tool check exceeded the 20 second limit.')));\n }, 20_000);\n child.stdout.setEncoding('utf8');\n child.stderr.setEncoding('utf8');\n child.stdout.on('data', (chunk: string) => {\n stdout += chunk;\n if (stdout.length > 2_000_000) child.kill('SIGKILL');\n });\n child.stderr.on('data', (chunk: string) => {\n if (stderr.length < 2_000_000) stderr += chunk.slice(0, 2_000_000 - stderr.length);\n });\n child.on('error', (error) => finish(() => reject(new ServiceUnavailableException(`Could not start AgentHub tool checker: ${error.message}`))));\n child.on('close', (code) => finish(() => {\n if (stdout.length > 2_000_000) {\n reject(new BadRequestException('Tool check response was too large.'));\n return;\n }\n try {\n const result = JSON.parse(stdout.trim());\n if (!result || typeof result !== 'object' || Array.isArray(result)) throw new Error('Invalid response');\n resolve(result);\n } catch {\n reject(new ServiceUnavailableException(`AgentHub tool checker returned an invalid response${code === 0 ? '' : ` (exit ${code})`}. ${stderr.slice(0, 500)}`));\n }\n }));\n child.stdin.end(requestJson);\n });\n }\n\n private async readToolConfig(tool: AgentToolRegistry, checksum: string): Promise<{ success: boolean; message: string; requiredSecrets: string[] }> {\n const result = await this.runLifecycleScript({ tool_id: tool.id, checksum, phase: 'config' });\n const requiredSecrets = result.required_secrets;\n if (result.success !== true || !Array.isArray(requiredSecrets)\n || requiredSecrets.some((key) => typeof key !== 'string' || !key.trim())\n || new Set(requiredSecrets).size !== requiredSecrets.length) {\n return { success: false, message: String(result.message ?? 'The tool returned an invalid configuration.'), requiredSecrets: [] };\n }\n return { success: true, message: String(result.message ?? 'Configuration declaration checked.'), requiredSecrets };\n }\n\n async checkTool(id: number, phase: string, checksum: string) {\n if (phase !== 'config' && phase !== 'init') throw new BadRequestException('Phase must be config or init.');\n const tool = await this.repo.findOne({ where: { id } });\n if (!tool) throw new NotFoundException(`Tool ${id} was not found.`);\n if (!['custom', 'thirdparty'].includes(tool.type)) throw new BadRequestException('Only custom and third-party tools can be checked.');\n const currentChecksum = createHash('sha256').update(tool.sourceCode ?? '', 'utf8').digest('hex');\n if (!checksum || checksum !== currentChecksum) throw new ConflictException('Tool source changed. Save the tool again before running checks.');\n\n const config = await this.readToolConfig(tool, currentChecksum);\n if (!config.success) {\n return {\n toolId: id, checksum, phase,\n config: { status: 'failed', message: config.message, requiredSecrets: [], missingSecrets: [] },\n init: { status: 'skipped', message: 'Configuration must pass before initialization can run.' },\n };\n }\n\n const resolvedSecrets = phase === 'init'\n ? await this.secretService.resolveAvailable(config.requiredSecrets)\n : undefined;\n const available = phase === 'config'\n ? await this.secretService.findAvailableKeys(config.requiredSecrets)\n : Object.keys(resolvedSecrets ?? {});\n const missingSecrets = config.requiredSecrets.filter((key) => !available.includes(key));\n const configStep = {\n status: missingSecrets.length ? 'failed' : 'passed',\n message: missingSecrets.length ? 'Configure all required active secrets before initializing this tool.' : config.message,\n requiredSecrets: config.requiredSecrets,\n missingSecrets,\n };\n if (missingSecrets.length || phase === 'config') {\n return {\n toolId: id, checksum, phase, config: configStep,\n init: { status: 'skipped', message: missingSecrets.length ? 'Required secrets must be configured first.' : 'Run initialization after configuration passes.' },\n };\n }\n\n const secretValues = Object.fromEntries(Object.entries(resolvedSecrets ?? {}).map(([key, value]) => [\n key, typeof value === 'string' ? value : JSON.stringify(value),\n ]));\n const init = await this.runLifecycleScript({\n tool_id: id, checksum, phase: 'init', secret_values: secretValues,\n });\n return {\n toolId: id, checksum, phase, config: configStep,\n init: { status: init.success === true ? 'passed' : 'failed', message: String(init.message ?? (init.success ? 'Initialization check passed.' : 'Initialization check failed.')) },\n };\n }\n\n override async create(createDto: CreateAgentToolRegistryDto, files: Express.Multer.File[] = [], solidRequestContext: any = {}): Promise<AgentToolRegistry> {\n return super.create(this.withChecksum({ ...createDto, status: 'inactive', lastLoadError: null }), files, solidRequestContext);\n }\n\n override async createMany(createDtos: CreateAgentToolRegistryDto[], solidRequestContext: any = {}): Promise<AgentToolRegistry[]> {\n return super.createMany(createDtos.map((dto) => this.withChecksum({ ...dto, status: 'inactive', lastLoadError: null })), solidRequestContext);\n }\n\n override async insertMany(createDtos: CreateAgentToolRegistryDto[], filesArray: Express.Multer.File[][] = [], solidRequestContext: any = {}): Promise<AgentToolRegistry[]> {\n return super.insertMany(createDtos.map((dto) => this.withChecksum({ ...dto, status: 'inactive', lastLoadError: null })), filesArray, solidRequestContext);\n }\n\n override async update(\n id: number,\n updateDto: UpdateAgentToolRegistryDto,\n files: Express.Multer.File[] = [],\n isPartialUpdate = false,\n solidRequestContext: any = {},\n isUpdate = false,\n ): Promise<AgentToolRegistry> {\n const existing = await this.repo.findOne({ where: { id } });\n const changed = existing && ['sourceCode', 'name', 'type'].some(\n (key) => updateDto[key] !== undefined && updateDto[key] !== existing[key],\n );\n if (!changed && updateDto.status === 'active' && existing?.status !== 'active'\n && existing && ['custom', 'thirdparty'].includes(existing.type)) {\n const checkedChecksum = createHash('sha256').update(existing.sourceCode ?? '', 'utf8').digest('hex');\n if (updateDto.checksum !== checkedChecksum) {\n throw new ConflictException('Tool source changed after checks. Run configuration and initialization again.');\n }\n }\n const dto = changed ? { ...updateDto, status: 'inactive', lastLoadError: null } : updateDto;\n return super.update(id, this.withChecksum(dto, existing ?? undefined), files, isPartialUpdate, solidRequestContext, isUpdate);\n }\n\n\n}\n"]}
1
+ {"version":3,"file":"agent-tool-registry.service.js","sourceRo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ACL,8BAAa;GAR5B,wBAAwB,CAyNpC","sourcesContent":["import { BadRequestException, ConflictException, Injectable, Logger, NotFoundException, ServiceUnavailableException } from '@nestjs/common';\nimport { InjectEntityManager } from '@nestjs/typeorm';\nimport { ModuleRef } from '@nestjs/core';\nimport { EntityManager } from 'typeorm';\nimport { createHash } from 'node:crypto';\nimport { spawn } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { homedir, tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { SecretService } from './secret.service';\nimport { AgentTool } from '../entities/agent-tool.entity';\nimport { AgentConfigCatalogService } from './agent-config-version.service';\nimport { AgentToolRegistry } from '../entities/agent-tool-registry.entity';\nimport { AgentToolRegistryRepository } from '../repository/agent-tool-registry.repository';\nimport { CreateAgentToolRegistryDto } from '../dtos/create-agent-tool-registry.dto';\nimport { UpdateAgentToolRegistryDto } from '../dtos/update-agent-tool-registry.dto';\n\n@Injectable()\nexport class AgentToolRegistryService extends AgentConfigCatalogService<AgentToolRegistry>{\n private readonly logger = new Logger(AgentToolRegistryService.name);\n\n constructor(\n @InjectEntityManager(\"default\")\n readonly entityManager: EntityManager,\n readonly repo: AgentToolRegistryRepository,\n readonly moduleRef: ModuleRef,\n readonly secretService: SecretService,\n ) {\n super(entityManager, repo, 'agentToolRegistry', moduleRef, AgentTool, 'agentToolRegistry');\n }\n\n private withChecksum<T extends { type?: string; sourceCode?: string; checksum?: string }>(dto: T, existing?: AgentToolRegistry): T {\n if (!['custom', 'thirdparty'].includes(dto.type ?? existing?.type)) return dto;\n\n const sourceCode = dto.sourceCode ?? existing?.sourceCode;\n if (typeof sourceCode !== 'string') return dto;\n\n return {\n ...dto,\n checksum: createHash('sha256').update(sourceCode, 'utf8').digest('hex'),\n };\n }\n\n private lifecycleRunner(): { python: string; runtimeRoot: string; sourceRoot?: string } {\n const binary = process.platform === 'win32' ? 'python.exe' : 'python';\n const configuredSourceRoot = process.env.AGENT_HUB_RUNTIME_PATH;\n const sourceRoot = configuredSourceRoot\n && existsSync(join(configuredSourceRoot, 'src', 'agenthub', 'tools', 'tool_lifecycle_check.py'))\n ? configuredSourceRoot\n : undefined;\n const solidxVenv = { root: join(homedir(), '.solidx', 'agenthub-venv'), sourceRoot };\n const localVenv = process.env.AGENT_HUB_RUNTIME_PATH\n ? { root: join(process.env.AGENT_HUB_RUNTIME_PATH, '.venv'), sourceRoot }\n : undefined;\n const preference = process.env.AGENT_HUB_RUNTIME_PREFERENCE?.trim().toLowerCase() || 'solidx';\n if (preference !== 'solidx' && preference !== 'local') {\n throw new ServiceUnavailableException('AGENT_HUB_RUNTIME_PREFERENCE must be \"solidx\" or \"local\".');\n }\n const candidates = (preference === 'local' ? [localVenv, solidxVenv] : [solidxVenv, localVenv])\n .filter((candidate): candidate is NonNullable<typeof candidate> => candidate !== undefined);\n for (const candidate of candidates) {\n const python = join(candidate.root, process.platform === 'win32' ? 'Scripts' : 'bin', binary);\n if (existsSync(python)) return { python, runtimeRoot: candidate.root, sourceRoot: candidate.sourceRoot };\n }\n throw new ServiceUnavailableException('AgentHub runtime virtual environment was not found.');\n }\n\n private lifecycleDatabaseUrl(): string {\n const options = this.entityManager.connection.options as any;\n if (options.type !== 'postgres') {\n throw new ServiceUnavailableException('Tool checks require Core to use PostgreSQL.');\n }\n if (options.url) return options.url;\n const host = String(options.host ?? 'localhost');\n const formattedHost = host.includes(':') && !host.startsWith('[') ? `[${host}]` : host;\n const credentials = options.username\n ? `${encodeURIComponent(String(options.username))}:${encodeURIComponent(String(options.password ?? ''))}@`\n : '';\n const ssl = options.ssl ? '?sslmode=require' : '';\n return `postgresql://${credentials}${formattedHost}:${options.port ?? 5432}/${encodeURIComponent(String(options.database))}${ssl}`;\n }\n\n private async runLifecycleScript(request: Record<string, unknown>): Promise<Record<string, any>> {\n const runner = this.lifecycleRunner();\n const requestJson = JSON.stringify(request);\n const childEnv = {\n PATH: process.env.PATH ?? '',\n VIRTUAL_ENV: runner.runtimeRoot,\n HOME: homedir(),\n DATABASE_URL: this.lifecycleDatabaseUrl(),\n ...(process.env.SYSTEMROOT ? { SYSTEMROOT: process.env.SYSTEMROOT } : {}),\n ...(runner.sourceRoot ? { PYTHONPATH: join(runner.sourceRoot, 'src') } : {}),\n };\n return new Promise((resolve, reject) => {\n const child = spawn(runner.python, ['-m', 'agenthub.tools.tool_lifecycle_check'], {\n cwd: runner.sourceRoot ?? tmpdir(),\n env: childEnv,\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n let stdout = '';\n let stderr = '';\n let settled = false;\n const finish = (callback: () => void) => {\n if (settled) return;\n settled = true;\n clearTimeout(timeout);\n callback();\n };\n const timeout = setTimeout(() => {\n child.kill('SIGKILL');\n finish(() => reject(new ServiceUnavailableException('Tool check exceeded the 20 second limit.')));\n }, 20_000);\n child.stdout.setEncoding('utf8');\n child.stderr.setEncoding('utf8');\n child.stdout.on('data', (chunk: string) => {\n stdout += chunk;\n if (stdout.length > 2_000_000) child.kill('SIGKILL');\n });\n child.stderr.on('data', (chunk: string) => {\n if (stderr.length < 2_000_000) stderr += chunk.slice(0, 2_000_000 - stderr.length);\n });\n child.on('error', (error) => finish(() => reject(new ServiceUnavailableException(`Could not start AgentHub tool checker: ${error.message}`))));\n child.on('close', (code) => finish(() => {\n if (stdout.length > 2_000_000) {\n reject(new BadRequestException('Tool check response was too large.'));\n return;\n }\n try {\n const result = JSON.parse(stdout.trim());\n if (!result || typeof result !== 'object' || Array.isArray(result)) throw new Error('Invalid response');\n resolve(result);\n } catch {\n reject(new ServiceUnavailableException(`AgentHub tool checker returned an invalid response${code === 0 ? '' : ` (exit ${code})`}. ${stderr.slice(0, 500)}`));\n }\n }));\n child.stdin.end(requestJson);\n });\n }\n\n private async readToolConfig(tool: AgentToolRegistry, checksum: string): Promise<{ success: boolean; message: string; requiredSecrets: string[] }> {\n const result = await this.runLifecycleScript({ tool_id: tool.id, checksum, phase: 'config' });\n const requiredSecrets = result.required_secrets;\n if (result.success !== true || !Array.isArray(requiredSecrets)\n || requiredSecrets.some((key) => typeof key !== 'string' || !key.trim())\n || new Set(requiredSecrets).size !== requiredSecrets.length) {\n return { success: false, message: String(result.message ?? 'The tool returned an invalid configuration.'), requiredSecrets: [] };\n }\n return { success: true, message: String(result.message ?? 'Configuration declaration checked.'), requiredSecrets };\n }\n\n async checkTool(id: number, phase: string, checksum: string) {\n if (phase !== 'config' && phase !== 'init') throw new BadRequestException('Phase must be config or init.');\n const tool = await this.repo.findOne({ where: { id } });\n if (!tool) throw new NotFoundException(`Tool ${id} was not found.`);\n if (!['custom', 'thirdparty'].includes(tool.type)) throw new BadRequestException('Only custom and third-party tools can be checked.');\n const currentChecksum = createHash('sha256').update(tool.sourceCode ?? '', 'utf8').digest('hex');\n if (!checksum || checksum !== currentChecksum) throw new ConflictException('Tool source changed. Save the tool again before running checks.');\n\n const config = await this.readToolConfig(tool, currentChecksum);\n if (!config.success) {\n return {\n toolId: id, checksum, phase,\n config: { status: 'failed', message: config.message, requiredSecrets: [], missingSecrets: [] },\n init: { status: 'skipped', message: 'Configuration must pass before initialization can run.' },\n };\n }\n\n const resolvedSecrets = phase === 'init'\n ? await this.secretService.resolveAvailable(config.requiredSecrets)\n : undefined;\n const available = phase === 'config'\n ? await this.secretService.findAvailableKeys(config.requiredSecrets)\n : Object.keys(resolvedSecrets ?? {});\n const missingSecrets = config.requiredSecrets.filter((key) => !available.includes(key));\n const configStep = {\n status: missingSecrets.length ? 'failed' : 'passed',\n message: missingSecrets.length ? 'Configure all required active secrets before initializing this tool.' : config.message,\n requiredSecrets: config.requiredSecrets,\n missingSecrets,\n };\n if (missingSecrets.length || phase === 'config') {\n return {\n toolId: id, checksum, phase, config: configStep,\n init: { status: 'skipped', message: missingSecrets.length ? 'Required secrets must be configured first.' : 'Run initialization after configuration passes.' },\n };\n }\n\n const secretValues = Object.fromEntries(Object.entries(resolvedSecrets ?? {}).map(([key, value]) => [\n key, typeof value === 'string' ? value : JSON.stringify(value),\n ]));\n const init = await this.runLifecycleScript({\n tool_id: id, checksum, phase: 'init', secret_values: secretValues,\n });\n return {\n toolId: id, checksum, phase, config: configStep,\n init: { status: init.success === true ? 'passed' : 'failed', message: String(init.message ?? (init.success ? 'Initialization check passed.' : 'Initialization check failed.')) },\n };\n }\n\n override async create(createDto: CreateAgentToolRegistryDto, files: Express.Multer.File[] = [], solidRequestContext: any = {}): Promise<AgentToolRegistry> {\n return super.create(this.withChecksum({ ...createDto, status: 'inactive', lastLoadError: null }), files, solidRequestContext);\n }\n\n override async createMany(createDtos: CreateAgentToolRegistryDto[], solidRequestContext: any = {}): Promise<AgentToolRegistry[]> {\n return super.createMany(createDtos.map((dto) => this.withChecksum({ ...dto, status: 'inactive', lastLoadError: null })), solidRequestContext);\n }\n\n override async insertMany(createDtos: CreateAgentToolRegistryDto[], filesArray: Express.Multer.File[][] = [], solidRequestContext: any = {}): Promise<AgentToolRegistry[]> {\n return super.insertMany(createDtos.map((dto) => this.withChecksum({ ...dto, status: 'inactive', lastLoadError: null })), filesArray, solidRequestContext);\n }\n\n override async update(\n id: number,\n updateDto: UpdateAgentToolRegistryDto,\n files: Express.Multer.File[] = [],\n isPartialUpdate = false,\n solidRequestContext: any = {},\n isUpdate = false,\n ): Promise<AgentToolRegistry> {\n const existing = await this.repo.findOne({ where: { id } });\n const changed = existing && ['sourceCode', 'name', 'type'].some(\n (key) => updateDto[key] !== undefined && updateDto[key] !== existing[key],\n );\n if (!changed && updateDto.status === 'active' && existing?.status !== 'active'\n && existing && ['custom', 'thirdparty'].includes(existing.type)) {\n const checkedChecksum = createHash('sha256').update(existing.sourceCode ?? '', 'utf8').digest('hex');\n if (updateDto.checksum !== checkedChecksum) {\n throw new ConflictException('Tool source changed after checks. Run configuration and initialization again.');\n }\n }\n const dto = changed ? { ...updateDto, status: 'inactive', lastLoadError: null } : updateDto;\n return super.update(id, this.withChecksum(dto, existing ?? undefined), files, isPartialUpdate, solidRequestContext, isUpdate);\n }\n\n\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"smtp-email.service.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C,EAAE,MAAM,EAAE,EACb,GAAG,CAAC,EAAE,MAAM,EAAE,EACd,IAAI,CAAC,EAAE,MAAM;IAoBX,SAAS,CACX,EAAE,EAAE,MAAM,EACV,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,MAAM,EACZ,iBAAiB,UAAQ,EACzB,kBAAkB,CAAC,EAAE,qBAAqB,EAAE,EAC5C,WAAW,CAAC,EAAE,cAAc,EAAE,EAC9B,YAAY,CAAC,EAAE,GAAG,EAClB,cAAc,CAAC,EAAE,GAAG,EACpB,EAAE,CAAC,EAAE,MAAM,EAAE,EACb,GAAG,CAAC,EAAE,MAAM,EAAE,EACd,IAAI,CAAC,EAAE,MAAM;IA8BX,uBAAuB,CAAC,OAAO,KAAA;IAM/B,sBAAsB,CAAC,OAAO,EAAE,YAAY,CAAC,GAAG,CAAC;CAyC1D"}
@@ -83,12 +83,8 @@ let SMTPEMailService = SMTPEMailService_1 = class SMTPEMailService {
83
83
  return this.publisherFactory.publish(message, 'SmtpEmailQueuePublisher');
84
84
  }
85
85
  async sendEmailSynchronously(message) {
86
- let from;
87
- const { to, subject, body, attachments = [], cc, bcc } = message.payload;
88
- const envFrom = this.settingService.getConfigValue("smtpMailFrom");
89
- if (envFrom) {
90
- from = envFrom;
91
- }
86
+ const { to, subject, body, attachments = [], cc, bcc, from: payloadFrom } = message.payload;
87
+ const from = payloadFrom || this.settingService.getConfigValue("smtpMailFrom");
92
88
  if (!from || !to || !subject || !body) {
93
89
  this.logger.error(`Required fields are missing in the email message: ${JSON.stringify(message.payload)}`);
94
90
  return;
@@ -1 +1 @@
1
- {"version":3,"file":"smtp-email.service.js","sourceRoot":"","sources":["../../../src/services/mail/smtp-email.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,2CAA4D;AAE5D,4DAAoC;AACpC,sFAAsE;AAGtE,sEAAiE;AACjE,mFAAuE;AACvE,wDAAoD;AAGpD,MAAM,UAAU,GAAG,OAAO,CAAC,YAAY,CAAC,CAAC;A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AE,UAAU,CAAC,WAAW;aACtC,CAAA;YACD,IAAI,UAAU,CAAC,IAAI,EAAE,CAAC;gBAClB,eAAe,CAAC,MAAM,CAAC,GAAG,UAAU,CAAC,IAAI,CAAC;YAC9C,CAAC;YACD,IAAI,UAAU,CAAC,OAAO,EAAE,CAAC;gBACrB,eAAe,CAAC,SAAS,CAAC,GAAG,UAAU,CAAC,OAAO,CAAC;YACpD,CAAC;YACD,OAAO,eAAe,CAAC;QAC3B,CAAC,CAAC,IAAI,EAAE,CAAC;QAGT,MAAM,CAAC,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC;YACtC,IAAI,EAAE,IAAI;YACV,EAAE,EAAE,EAAE;YACN,EAAE,EAAE,EAAE;YACN,GAAG,EAAE,GAAG;YACR,OAAO,EAAE,OAAO;YAChB,IAAI,EAAE,IAAI;YACV,WAAW,EAAE,eAAe;SAC/B,CAAC,CAAC;QAIH,OAAO,CAAC,CAAC;IACb,CAAC;CACJ,CAAA;AAxJY,4CAAgB;2BAAhB,gBAAgB;IAF5B,IAAA,mBAAU,GAAE;IACZ,IAAA,sCAAY,GAAE;qCAQ4B,4CAAgB;QACZ,6CAAoB;QAC1B,gCAAc;GAT1C,gBAAgB,CAwJ5B","sourcesContent":["import { Inject, Injectable, Logger } from '@nestjs/common';\nimport { ConfigType } from '@nestjs/config';\nimport Handlebars from \"handlebars\";\nimport { MailProvider } from 'src/decorators/mail-provider.decorator';\nimport { QueueMessage } from 'src/interfaces/mq';\nimport { IMail, MailAttachment, MailAttachmentWrapper } from \"../../interfaces\";\nimport { EmailTemplateService } from '../email-template.service';\nimport { PublisherFactory } from '../queues/publisher-factory.service';\nimport { SettingService } from '../setting.service';\nimport type { SolidCoreSetting } from \"src/services/settings/default-settings-provider.service\";\n\nconst nodemailer = require(\"nodemailer\");\n\n@Injectable()\n@MailProvider()\nexport class SMTPEMailService implements IMail {\n private readonly logger = new Logger(SMTPEMailService.name);\n private readonly transporter: any;\n\n constructor(\n // private readonly emailPublisher: EmailQueuePublisher,\n // private readonly emailDbPublisher: EmailQueueDbPublisher,\n private readonly publisherFactory: PublisherFactory<any>,\n private readonly emailTemplateService: EmailTemplateService,\n private readonly settingService: SettingService\n\n ) {\n\n const host = process.env.COMMON_SMTP_EMAIL_SMTP_HOST;\n const port = +(process.env.COMMON_SMTP_EMAIL_SMTP_PORT ?? 587);\n const username = process.env.COMMON_SMTP_EMAIL_USERNAME;\n const password = process.env.COMMON_SMTP_EMAIL_PASSWORD;\n const from = process.env.COMMON_SMTP_EMAIL_FROM ?? process.env.COMMON_EMAIL_FROM;\n\n this.transporter = nodemailer.createTransport({\n host: host,\n port: port,\n secure: port === 465,\n auth: {\n user: username,\n pass: password\n }\n });\n }\n\n async sendEmailUsingTemplate(\n to: string,\n templateName: string,\n templateParams: any,\n shouldQueueEmails = false,\n wrapperAttachments?: MailAttachmentWrapper[],\n attachments?: MailAttachment[],\n parentEntity?: any,\n parentEntityId?: any,\n cc?: string[],\n bcc?: string[],\n from?: string\n ) {\n // Load template and evaluate it.\n const emailTemplate = await this.emailTemplateService.findOneByName(templateName);\n if (!emailTemplate) {\n throw new Error(`Invalid template name ${templateName}`);\n }\n\n // Evaluate the body template.\n const bodyTemplate = Handlebars.compile(emailTemplate.body);\n const body = bodyTemplate(templateParams);\n\n // Evaluate the subject template \n const subjectTemplate = Handlebars.compile(emailTemplate.subject);\n const subject = subjectTemplate(templateParams);\n\n // Finally send the email.\n return await this.sendEmail(to, subject, body, shouldQueueEmails, wrapperAttachments, attachments, parentEntity, parentEntityId, cc, bcc, from);\n }\n\n async sendEmail(\n to: string,\n subject: string,\n body: string,\n shouldQueueEmails = false,\n wrapperAttachments?: MailAttachmentWrapper[],\n attachments?: MailAttachment[],\n parentEntity?: any,\n parentEntityId?: any,\n cc?: string[],\n bcc?: string[],\n from?: string\n ) {\n const message = {\n payload: {\n from: from || this.settingService.getConfigValue<SolidCoreSetting>(\"smtpMailFrom\"),\n to: to,\n subject: subject,\n body: body,\n attachments: attachments,\n cc: cc,\n bcc: bcc,\n },\n parentEntity: parentEntity,\n parentEntityId: parentEntityId,\n };\n\n // Send using queue if the developer has explicitly invoked with true.\n if (shouldQueueEmails === true) {\n return this.sendEmailAsynchronously(message);\n }\n // If developer has not, however system config mandates that we send using queue, still we send.\n else if (shouldQueueEmails == false && this.settingService.getConfigValue<SolidCoreSetting>(\"shouldQueueEmails\") === true) {\n return this.sendEmailAsynchronously(message);\n }\n // Else we send synchronously\n else {\n return await this.sendEmailSynchronously(message);\n }\n }\n\n async sendEmailAsynchronously(message) {\n const { to, subject, body } = message.payload;\n this.logger.debug(`Queueing email to ${to} with subject ${subject} and body ${body}`);\n return this.publisherFactory.publish(message, 'SmtpEmailQueuePublisher');\n }\n\n async sendEmailSynchronously(message: QueueMessage<any>) {\n let from;\n const { to, subject, body, attachments = [], cc, bcc } = message.payload;\n\n const envFrom = this.settingService.getConfigValue<SolidCoreSetting>(\"smtpMailFrom\");\n if (envFrom) {\n from = envFrom;\n }\n\n // if any of the required fields are missing, throw an error.\n if (!from || !to || !subject || !body) {\n this.logger.error(`Required fields are missing in the email message: ${JSON.stringify(message.payload)}`);\n return;\n }\n\n const attachmentsList = attachments?.map((attachment: MailAttachment) => {\n const attachmentEntry = {\n filename: attachment.filename,\n contentType: attachment.contentType,\n }\n if (attachment.path) {\n attachmentEntry['path'] = attachment.path;\n }\n if (attachment.content) {\n attachmentEntry['content'] = attachment.content;\n }\n return attachmentEntry;\n }) || [];\n\n // throw new Error('Random error....');\n const r = await this.transporter.sendMail({\n from: from,\n to: to,\n cc: cc,\n bcc: bcc,\n subject: subject,\n html: body,\n attachments: attachmentsList,\n });\n // this.logger.debug(`Sending email to ${to} with subject ${subject} and body ${body}`);\n // this.logger.debug(`Sending email to ${to} with subject ${subject}`);\n\n return r;\n }\n}"]}
1
+ {"version":3,"file":"smtp-email.service.js","sourceRoot":"","sources":["../../../src/services/mail/smtp-email.service.ts"],"names":[],"mappings":";;;;;;;;;;;;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,EAAE,EAAE;YACpE,MAAM,eAAe,GAAG;gBACpB,QAAQ,EAAE,UAAU,CAAC,QAAQ;gBAC7B,WAAW,EAAE,UAAU,CAAC,WAAW;aACtC,CAAA;YACD,IAAI,UAAU,CAAC,IAAI,EAAE,CAAC;gBAClB,eAAe,CAAC,MAAM,CAAC,GAAG,UAAU,CAAC,IAAI,CAAC;YAC9C,CAAC;YACD,IAAI,UAAU,CAAC,OAAO,EAAE,CAAC;gBACrB,eAAe,CAAC,SAAS,CAAC,GAAG,UAAU,CAAC,OAAO,CAAC;YACpD,CAAC;YACD,OAAO,eAAe,CAAC;QAC3B,CAAC,CAAC,IAAI,EAAE,CAAC;QAGT,MAAM,CAAC,GAAG,MAAM,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC;YACtC,IAAI,EAAE,IAAI;YACV,EAAE,EAAE,EAAE;YACN,EAAE,EAAE,EAAE;YACN,GAAG,EAAE,GAAG;YACR,OAAO,EAAE,OAAO;YAChB,IAAI,EAAE,IAAI;YACV,WAAW,EAAE,eAAe;SAC/B,CAAC,CAAC;QAIH,OAAO,CAAC,CAAC;IACb,CAAC;CACJ,CAAA;AArJY,4CAAgB;2BAAhB,gBAAgB;IAF5B,IAAA,mBAAU,GAAE;IACZ,IAAA,sCAAY,GAAE;qCAQ4B,4CAAgB;QACZ,6CAAoB;QAC1B,gCAAc;GAT1C,gBAAgB,CAqJ5B","sourcesContent":["import { Inject, Injectable, Logger } from '@nestjs/common';\nimport { ConfigType } from '@nestjs/config';\nimport Handlebars from \"handlebars\";\nimport { MailProvider } from 'src/decorators/mail-provider.decorator';\nimport { QueueMessage } from 'src/interfaces/mq';\nimport { IMail, MailAttachment, MailAttachmentWrapper } from \"../../interfaces\";\nimport { EmailTemplateService } from '../email-template.service';\nimport { PublisherFactory } from '../queues/publisher-factory.service';\nimport { SettingService } from '../setting.service';\nimport type { SolidCoreSetting } from \"src/services/settings/default-settings-provider.service\";\n\nconst nodemailer = require(\"nodemailer\");\n\n@Injectable()\n@MailProvider()\nexport class SMTPEMailService implements IMail {\n private readonly logger = new Logger(SMTPEMailService.name);\n private readonly transporter: any;\n\n constructor(\n // private readonly emailPublisher: EmailQueuePublisher,\n // private readonly emailDbPublisher: EmailQueueDbPublisher,\n private readonly publisherFactory: PublisherFactory<any>,\n private readonly emailTemplateService: EmailTemplateService,\n private readonly settingService: SettingService\n\n ) {\n\n const host = process.env.COMMON_SMTP_EMAIL_SMTP_HOST;\n const port = +(process.env.COMMON_SMTP_EMAIL_SMTP_PORT ?? 587);\n const username = process.env.COMMON_SMTP_EMAIL_USERNAME;\n const password = process.env.COMMON_SMTP_EMAIL_PASSWORD;\n const from = process.env.COMMON_SMTP_EMAIL_FROM ?? process.env.COMMON_EMAIL_FROM;\n\n this.transporter = nodemailer.createTransport({\n host: host,\n port: port,\n secure: port === 465,\n auth: {\n user: username,\n pass: password\n }\n });\n }\n\n async sendEmailUsingTemplate(\n to: string,\n templateName: string,\n templateParams: any,\n shouldQueueEmails = false,\n wrapperAttachments?: MailAttachmentWrapper[],\n attachments?: MailAttachment[],\n parentEntity?: any,\n parentEntityId?: any,\n cc?: string[],\n bcc?: string[],\n from?: string\n ) {\n // Load template and evaluate it.\n const emailTemplate = await this.emailTemplateService.findOneByName(templateName);\n if (!emailTemplate) {\n throw new Error(`Invalid template name ${templateName}`);\n }\n\n // Evaluate the body template.\n const bodyTemplate = Handlebars.compile(emailTemplate.body);\n const body = bodyTemplate(templateParams);\n\n // Evaluate the subject template \n const subjectTemplate = Handlebars.compile(emailTemplate.subject);\n const subject = subjectTemplate(templateParams);\n\n // Finally send the email.\n return await this.sendEmail(to, subject, body, shouldQueueEmails, wrapperAttachments, attachments, parentEntity, parentEntityId, cc, bcc, from);\n }\n\n async sendEmail(\n to: string,\n subject: string,\n body: string,\n shouldQueueEmails = false,\n wrapperAttachments?: MailAttachmentWrapper[],\n attachments?: MailAttachment[],\n parentEntity?: any,\n parentEntityId?: any,\n cc?: string[],\n bcc?: string[],\n from?: string\n ) {\n const message = {\n payload: {\n from: from || this.settingService.getConfigValue<SolidCoreSetting>(\"smtpMailFrom\"),\n to: to,\n subject: subject,\n body: body,\n attachments: attachments,\n cc: cc,\n bcc: bcc,\n },\n parentEntity: parentEntity,\n parentEntityId: parentEntityId,\n };\n\n // Send using queue if the developer has explicitly invoked with true.\n if (shouldQueueEmails === true) {\n return this.sendEmailAsynchronously(message);\n }\n // If developer has not, however system config mandates that we send using queue, still we send.\n else if (shouldQueueEmails == false && this.settingService.getConfigValue<SolidCoreSetting>(\"shouldQueueEmails\") === true) {\n return this.sendEmailAsynchronously(message);\n }\n // Else we send synchronously\n else {\n return await this.sendEmailSynchronously(message);\n }\n }\n\n async sendEmailAsynchronously(message) {\n const { to, subject, body } = message.payload;\n this.logger.debug(`Queueing email to ${to} with subject ${subject} and body ${body}`);\n return this.publisherFactory.publish(message, 'SmtpEmailQueuePublisher');\n }\n\n async sendEmailSynchronously(message: QueueMessage<any>) {\n const { to, subject, body, attachments = [], cc, bcc, from: payloadFrom } = message.payload;\n\n // Prefer the from address passed by the caller, fall back to the configured one.\n const from = payloadFrom || this.settingService.getConfigValue<SolidCoreSetting>(\"smtpMailFrom\");\n\n // if any of the required fields are missing, throw an error.\n if (!from || !to || !subject || !body) {\n this.logger.error(`Required fields are missing in the email message: ${JSON.stringify(message.payload)}`);\n return;\n }\n\n const attachmentsList = attachments?.map((attachment: MailAttachment) => {\n const attachmentEntry = {\n filename: attachment.filename,\n contentType: attachment.contentType,\n }\n if (attachment.path) {\n attachmentEntry['path'] = attachment.path;\n }\n if (attachment.content) {\n attachmentEntry['content'] = attachment.content;\n }\n return attachmentEntry;\n }) || [];\n\n // throw new Error('Random error....');\n const r = await this.transporter.sendMail({\n from: from,\n to: to,\n cc: cc,\n bcc: bcc,\n subject: subject,\n html: body,\n attachments: attachmentsList,\n });\n // this.logger.debug(`Sending email to ${to} with subject ${subject} and body ${body}`);\n // this.logger.debug(`Sending email to ${to} with subject ${subject}`);\n\n return r;\n }\n}"]}