Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /CIRISAI_CIRISAgent /ciris_adapters /oracle /service.py
| """ | |
| Oracle Tool Service for CIRIS. | |
| Converted from Clawdbot skill: oracle | |
| Best practices for using the oracle CLI (prompt + file bundling, engines, sessions, and file attachment patterns). | |
| This service provides skill-based guidance for using external tools/CLIs. | |
| The detailed instructions from the original SKILL.md are embedded in the | |
| ToolInfo.documentation field for DMA-aware tool selection. | |
| """ | |
| import logging | |
| import os | |
| import shutil | |
| from typing import Any, Dict, List, Optional | |
| from uuid import uuid4 | |
| from ciris_engine.schemas.adapters.tools import ( | |
| BinaryRequirement, | |
| ConfigRequirement, | |
| EnvVarRequirement, | |
| InstallStep, | |
| ToolDMAGuidance, | |
| ToolDocumentation, | |
| ToolExecutionResult, | |
| ToolExecutionStatus, | |
| ToolGotcha, | |
| ToolInfo, | |
| ToolParameterSchema, | |
| ToolRequirements, | |
| UsageExample, | |
| ) | |
| logger = logging.getLogger(__name__) | |
| class OracleToolService: | |
| """ | |
| Oracle tool service providing skill-based guidance. | |
| Original skill: oracle | |
| Description: Best practices for using the oracle CLI (prompt + file bundling, engines, sessions, and file attachment patterns). | |
| """ | |
| def __init__(self, config: Optional[Dict[str, Any]] = None) -> None: | |
| """Initialize the tool service.""" | |
| self.config = config or {} | |
| self._call_count = 0 | |
| logger.info("OracleToolService initialized") | |
| async def start(self) -> None: | |
| """Start the service.""" | |
| logger.info("OracleToolService started") | |
| async def stop(self) -> None: | |
| """Stop the service.""" | |
| logger.info("OracleToolService stopped") | |
| def _build_tool_info(self) -> ToolInfo: | |
| """Build the ToolInfo with all skill documentation.""" | |
| return ToolInfo( | |
| name="oracle", | |
| description="""Best practices for using the oracle CLI (prompt + file bundling, engines, sessions, and file attachment patterns).""", | |
| parameters=ToolParameterSchema( | |
| type="object", | |
| properties={ | |
| "command": { | |
| "type": "string", | |
| "description": "The command to execute (will be validated against skill guidance)", | |
| }, | |
| "working_dir": { | |
| "type": "string", | |
| "description": "Working directory for command execution (optional)", | |
| }, | |
| }, | |
| required=["command"], | |
| ), | |
| category="skill", | |
| when_to_use="""When you need to best practices for using the oracle cli (prompt + file bundling, engines, sessions, and file attachm...""", | |
| requirements=ToolRequirements( | |
| binaries=[ | |
| BinaryRequirement(name="oracle"), | |
| ], | |
| ), | |
| install_steps=[ | |
| InstallStep( | |
| id="node", | |
| kind="node", | |
| label="Install oracle (node)", | |
| package="@steipete/oracle", | |
| provides_binaries=["oracle"], | |
| ), | |
| ], | |
| documentation=ToolDocumentation( | |
| quick_start="Oracle bundles your prompt + selected files into one “one-shot” request so another model can answer with real repo context (API or browser automation). Treat output as advisory: verify against code + ", | |
| detailed_instructions="""# oracle — best use\n\nOracle bundles your prompt + selected files into one “one-shot” request so another model can answer with real repo context (API or browser automation). Treat output as advisory: verify against code + tests.\n\n## Main use case (browser, GPT‑5.2 Pro)\n\nDefault workflow here: `--engine browser` with GPT‑5.2 Pro in ChatGPT. This is the common “long think” path: ~10 minutes to ~1 hour is normal; expect a stored session you can reattach to.\n\nRecommended defaults:\n- Engine: browser (`--engine browser`)\n- Model: GPT‑5.2 Pro (`--model gpt-5.2-pro` or `--model \"5.2 Pro\"`)\n\n## Golden path\n\n1. Pick a tight file set (fewest files that still contain the truth).\n2. Preview payload + token spend (`--dry-run` + `--files-report`).\n3. Use browser mode for the usual GPT‑5.2 Pro workflow; use API only when you explicitly want it.\n4. If the run detaches/timeouts: reattach to the stored session (don’t re-run).\n\n## Commands (preferred)\n\n- Help:\n - `oracle --help`\n - If the binary isn’t installed: `npx -y @steipete/oracle --help` (avoid `pnpx` here; sqlite bindings).\n\n- Preview (no tokens):\n - `oracle --dry-run summary -p \"<task>\" --file \"src/**\" --file \"!**/*.test.*\"`\n - `oracle --dry-run full -p \"<task>\" --file \"src/**\"`\n\n- Token sanity:\n - `oracle --dry-run summary --files-report -p \"<task>\" --file \"src/**\"`\n\n- Browser run (main path; long-running is normal):\n - `oracle --engine browser --model gpt-5.2-pro -p \"<task>\" --file \"src/**\"`\n\n- Manual paste fallback:\n - `oracle --render --copy -p \"<task>\" --file \"src/**\"`\n - Note: `--copy` is a hidden alias for `--copy-markdown`.\n\n## Attaching files (`--file`)\n\n`--file` accepts files, directories, and globs. You can pass it multiple times; entries can be comma-separated.\n\n- Include:\n - `--file \"src/**\"`\n - `--file src/index.ts`\n - `--file docs --file README.md`\n\n- Exclude:\n - `--file \"src/**\" --file \"!src/**/*.test.ts\" --file \"!**/*.snap\"`\n\n- Defaults (implementation behavior):\n - Default-ignored dirs: `node_modules`, `dist`, `coverage`, `.git`, `.turbo`, `.next`, `build`, `tmp` (skipped unless explicitly passed as literal dirs/files).\n - Honors `.gitignore` when expanding globs.\n - Does not follow symlinks.\n - Dotfiles filtered unless opted in via pattern (e.g. `--file \".github/**\"`).\n - Files > 1 MB rejected.\n\n## Engines (API vs browser)\n\n- Auto-pick: `api` when `OPENAI_API_KEY` is set; otherwise `browser`.\n- Browser supports GPT + Gemini only; use `--engine api` for Claude/Grok/Codex or multi-model runs.\n- Browser attachments:\n - `--browser-attachments auto|never|always` (auto pastes inline up to ~60k chars then uploads).\n- Remote browser host:\n - Host: `oracle serve --host 0.0.0.0 --port 9473 --token <secret>`\n - Client: `oracle --engine browser --remote-host <host:port> --remote-token <secret> -p \"<task>\" --file \"src/**\"`\n\n## Sessions + slugs\n\n- Stored under `~/.oracle/sessions` (override with `ORACLE_HOME_DIR`).\n- Runs may detach or take a long time (browser + GPT‑5.2 Pro often does). If the CLI times out: don’t re-run; reattach.\n - List: `oracle status --hours 72`\n - Attach: `oracle session <id> --render`\n- Use `--slug \"<3-5 words>\"` to keep session IDs readable.\n- Duplicate prompt guard exists; use `--force` only when you truly want a fresh run.\n\n## Prompt template (high signal)\n\nOracle starts with **zero** project knowledge. Assume the model cannot infer your stack, build tooling, conventions, or “obvious” paths. Include:\n- Project briefing (stack + build/test commands + platform constraints).\n- “Where things live” (key directories, entrypoints, config files, boundaries).\n- Exact question + what you tried + the error text (verbatim).\n- Constraints (“don’t change X”, “must keep public API”, etc).\n- Desired output (“return patch plan + tests”, “give 3 options with tradeoffs”).\n\n## Safety\n\n- Don’t attach secrets by default (`.env`, key files, auth tokens). Redact aggressively; share only what’s required.\n\n## “Exhaustive prompt” restoration pattern\n\nFor long investigations, write a standalone prompt + file set so you can rerun days later:\n- 6–30 sentence project briefing + the goal.\n- Repro steps + exact errors + what you tried.\n- Attach all context files needed (entrypoints, configs, key modules, docs).\n\nOracle runs are one-shot; the model doesn’t remember prior runs. “Restoring context” means re-running with the same prompt + `--file …` set (or reattaching a still-running stored session).""", | |
| examples=[], | |
| gotchas=[], | |
| homepage="https://askoracle.dev", | |
| ), | |
| dma_guidance=ToolDMAGuidance( | |
| requires_approval=False, | |
| ), | |
| tags=["skill", "ciris", "oracle", "cli"], | |
| version="1.0.0", | |
| ) | |
| # ========================================================================= | |
| # ToolServiceProtocol Implementation | |
| # ========================================================================= | |
| async def get_available_tools(self) -> List[str]: | |
| """Get available tool names.""" | |
| return ["oracle"] | |
| async def list_tools(self) -> List[str]: | |
| """Legacy alias for get_available_tools().""" | |
| return await self.get_available_tools() | |
| async def get_tool_info(self, tool_name: str) -> Optional[ToolInfo]: | |
| """Get detailed info for a specific tool.""" | |
| if tool_name == "oracle": | |
| return self._build_tool_info() | |
| return None | |
| async def get_all_tool_info(self) -> List[ToolInfo]: | |
| """Get info for all tools.""" | |
| return [self._build_tool_info()] | |
| async def get_tool_schema(self, tool_name: str) -> Optional[ToolParameterSchema]: | |
| """Get parameter schema for a tool.""" | |
| tool_info = await self.get_tool_info(tool_name) | |
| return tool_info.parameters if tool_info else None | |
| async def validate_parameters(self, tool_name: str, parameters: Dict[str, Any]) -> bool: | |
| """Validate parameters for a tool.""" | |
| if tool_name != "oracle": | |
| return False | |
| return "command" in parameters | |
| async def get_tool_result(self, correlation_id: str, timeout: float = 30.0) -> Optional[ToolExecutionResult]: | |
| """Get result of previously executed tool.""" | |
| return None | |
| def get_tools(self) -> List[Dict[str, Any]]: | |
| """Return list of available tools (legacy format).""" | |
| tool_info = self._build_tool_info() | |
| return [ | |
| { | |
| "name": tool_info.name, | |
| "description": tool_info.description, | |
| "parameters": tool_info.parameters.model_dump() if tool_info.parameters else {}, | |
| } | |
| ] | |
| async def execute_tool( | |
| self, | |
| tool_name: str, | |
| parameters: Dict[str, Any], | |
| context: Optional[Dict[str, Any]] = None, | |
| ) -> ToolExecutionResult: | |
| """Execute the skill-based tool. | |
| Note: This is a guidance tool - it provides instructions for using | |
| external CLIs rather than executing them directly. The agent should | |
| use the bash tool to execute the actual commands. | |
| """ | |
| self._call_count += 1 | |
| correlation_id = str(uuid4()) | |
| if tool_name != "oracle": | |
| return ToolExecutionResult( | |
| tool_name=tool_name, | |
| status=ToolExecutionStatus.NOT_FOUND, | |
| success=False, | |
| data=None, | |
| error=f"Unknown tool: {tool_name}", | |
| correlation_id=correlation_id, | |
| ) | |
| try: | |
| command = parameters.get("command", "") | |
| # Check requirements using ToolInfo | |
| tool_info = self._build_tool_info() | |
| requirements_met, missing = self._check_requirements(tool_info) | |
| if not requirements_met: | |
| return ToolExecutionResult( | |
| tool_name=tool_name, | |
| status=ToolExecutionStatus.FAILED, | |
| success=False, | |
| data={"missing_requirements": missing}, | |
| error=f"Missing requirements: {', '.join(missing)}", | |
| correlation_id=correlation_id, | |
| ) | |
| # Return guidance for executing the command | |
| return ToolExecutionResult( | |
| tool_name=tool_name, | |
| status=ToolExecutionStatus.COMPLETED, | |
| success=True, | |
| data={ | |
| "command": command, | |
| "guidance": "Use bash tool to execute this command", | |
| "skill_instructions": tool_info.documentation.quick_start if tool_info.documentation else None, | |
| "requirements_met": requirements_met, | |
| }, | |
| error=None, | |
| correlation_id=correlation_id, | |
| ) | |
| except Exception as e: | |
| logger.error(f"Error executing tool {tool_name}: {e}") | |
| return ToolExecutionResult( | |
| tool_name=tool_name, | |
| status=ToolExecutionStatus.FAILED, | |
| success=False, | |
| data=None, | |
| error=str(e), | |
| correlation_id=correlation_id, | |
| ) | |
| def get_service_metadata(self) -> Dict[str, Any]: | |
| """Return service metadata for DSAR and data source discovery.""" | |
| return { | |
| "data_source": True, | |
| "data_source_type": "secrets", | |
| "contains_pii": True, | |
| "gdpr_applicable": True, | |
| "connector_id": "oracle", | |
| } | |
| def _check_requirements(self, tool_info: ToolInfo) -> tuple[bool, List[str]]: | |
| """Check if all requirements are met using ToolInfo.requirements.""" | |
| missing = [] | |
| if not tool_info.requirements: | |
| return True, [] | |
| req = tool_info.requirements | |
| # Check binaries | |
| for bin_req in req.binaries: | |
| if not shutil.which(bin_req.name): | |
| missing.append(f"binary:{bin_req.name}") | |
| # Check any_binaries (at least one) | |
| if req.any_binaries: | |
| found = any(shutil.which(b.name) for b in req.any_binaries) | |
| if not found: | |
| names = [b.name for b in req.any_binaries] | |
| missing.append(f"any_binary:{','.join(names)}") | |
| # Check env vars | |
| for env_req in req.env_vars: | |
| if not os.environ.get(env_req.name): | |
| missing.append(f"env:{env_req.name}") | |
| # Check config keys (skip for now - would need config service) | |
| # for config_req in req.config_keys: | |
| # ... | |
| return len(missing) == 0, missing | |
Xet Storage Details
- Size:
- 14.3 kB
- Xet hash:
- 941c2b79b46c6a1bce0e2bf581700a36ad718655ff6410bd91cd271999fa514d
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.