use super::exa::OUTPUT_MAX_BYTES;
use super::find::{FIND_DEADLINE_SECS, FIND_MAX_VISITED_ENTRIES};
use super::{
args::{
AST_GREP_DEFAULT_LIMIT, AST_GREP_MAX_LIMIT, AST_GREP_STDOUT_MAX_BYTES,
AST_GREP_TIMEOUT_SECS, BASH_DEFAULT_TIMEOUT_SECS, BASH_MAX_TIMEOUT_SECS,
BASH_STDERR_MAX_BYTES, BASH_STDOUT_MAX_BYTES, FILE_EDIT_TARGET_MAX_BYTES,
FILE_EDIT_TEXT_MAX_BYTES, FILE_READ_DEFAULT_LINES, FILE_READ_MAX_BYTES,
FILE_READ_MAX_FILES, FILE_WRITE_MAX_BYTES, FIND_DEFAULT_LIMIT, FIND_MAX_LIMIT,
GREP_DEADLINE_SECS, GREP_DEFAULT_LIMIT, GREP_MAX_CONTEXT, GREP_MAX_FILE_BYTES,
GREP_MAX_FILES, GREP_MAX_LIMIT, GREP_MAX_OFFSET, GREP_MAX_PATTERN_BYTES,
GREP_MAX_PATTERN_CHARS, GREP_MAX_PATTERN_TOTAL_BYTES, GREP_MAX_PATTERNS,
GREP_MAX_SCAN_BYTES, GREP_OUTPUT_MAX_BYTES, GREP_RANKED_PER_FILE,
VIEW_IMAGE_RESPONSE_MAX_BYTES,
},
contract::{
BASH_DISPATCH_ALIASES, FIND_DISPATCH_ALIASES, GREP_DISPATCH_ALIASES, arg_key, tool_name,
},
};
use crate::config::{DEFAULT_VIEW_IMAGE_MAX_IMAGE_BYTES, MAX_VIEW_IMAGE_MAX_IMAGE_BYTES};
use crate::subagents::{
DEFAULT_SUBAGENT_CONCURRENCY, MAX_SUBAGENT_CONCURRENCY, MAX_SUBAGENT_TASK_CONTEXT_BYTES,
MAX_SUBAGENT_TASK_INTENT_BYTES, MAX_SUBAGENT_TASKS,
};
use serde_json::{Value, json};
use std::{collections::HashSet, sync::OnceLock};
pub(crate) const MAGI_CONTROL_CONTEXT_MAX_CHARS: usize = 12_000;
const HASH_EDIT_INPUT_DESCRIPTION: &str = "Hashline patch text. Before editing, read each target without :raw. Use the latest [PATH#TAG] from that read and only line anchors displayed under that tag. Before another anchored edit, re-read the affected file. REM has no reusable tag. After an error or unexpected result, inspect touched files, re-read them, and rebuild the patch instead of replaying it.\n\nEach file section starts [PATH#TAG].\n\nBody operations:\nSWAP N.=M: replaces inclusive lines N..M.\nSWAP.BLK N: replaces the syntax block starting at N.\nINS.PRE N: and INS.POST N: insert around line N.\nINS.BLK.POST N: inserts after the block starting at N.\nINS.HEAD: and INS.TAIL: insert at file boundaries.\n\nBodyless operations:\nDEL N or DEL N.=M deletes lines.\nDEL.BLK N deletes a syntax block.\nMV DEST moves the file after line edits.\nREM deletes the file and must be the section's only operation.\n\nAll line numbers refer to the original tagged snapshot; never shift later hunk numbers. .BLK supports Rust, Python, JavaScript/JSX, TypeScript/TSX, and Go.\n\nEvery body row is +TEXT. The first + is removed. + means a blank line; use ++text or +-text for content beginning with + or -. Bodies contain final content, never diff context, -old rows, hashline prefixes, or unchanged surrounding lines.\n\nExample:\n[src/app.rs#A1B2]\nSWAP 10.=12:\n+fn main() {\n+ println!(\"ok\");\n+}\nDEL 25:";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ToolCapability {
Read,
ViewImage,
Bash,
HashEdit,
Write,
Grep,
Find,
ListFiles,
Subagents,
Web,
AstGrep,
MagiControl,
}
pub(crate) const ALL_TOOL_CAPABILITIES: [ToolCapability; 12] = MVP_TOOL_CAPABILITIES;
pub(crate) const MVP_TOOL_CAPABILITIES: [ToolCapability; 12] = [
ToolCapability::Read,
ToolCapability::ViewImage,
ToolCapability::Bash,
ToolCapability::HashEdit,
ToolCapability::Write,
ToolCapability::Grep,
ToolCapability::Find,
ToolCapability::ListFiles,
ToolCapability::Subagents,
ToolCapability::Web,
ToolCapability::AstGrep,
ToolCapability::MagiControl,
];
impl ToolCapability {
pub(crate) fn output_schema(self) -> Value {
let content = match self {
Self::Read => json!({"type":"object", "properties":{"files":{"type":"array","items":{
"type":"object", "properties":{"path":{"type":"string"},"text":{"type":"string"},"complete":{"type":"boolean"},"error":{"type":"string"}},
"required":["path","text","complete"]
}},"complete":{"type":"boolean"}},"required":["files"]}),
Self::Find => json!({"type":"object","properties":{
"files":{"type":"array","items":{"type":"string"}},"complete":{"type":"boolean"},
"scan_complete":{"type":"boolean"},"next_offset":{"type":["integer","null"]},"has_more":{"type":["boolean","null"]}
},"required":["files","complete","scan_complete","next_offset"]}),
_ => {
json!({"type":"object","properties":{"text":{"type":"string"}},"required":["text"]})
}
};
json!({"type":"object","properties":{
"success":{"type":"boolean"},"content":content,
"error":{"type":"object","properties":{"code":{"type":"string"},"message":{"type":"string"}},"required":["code","message"]}
},"required":["success"]})
}
pub fn canonical_name(self) -> &'static str {
match self {
Self::Read => tool_name::READ,
Self::ViewImage => tool_name::VIEW_IMAGE,
Self::Bash => tool_name::BASH,
Self::HashEdit => tool_name::HASH_EDIT,
Self::Write => tool_name::WRITE,
Self::Grep => tool_name::GREP,
Self::Find => tool_name::FIND,
Self::ListFiles => tool_name::LIST_FILES,
Self::Subagents => tool_name::SUBAGENTS,
Self::Web => tool_name::WEB,
Self::AstGrep => tool_name::AST_GREP,
Self::MagiControl => tool_name::MAGI_CONTROL,
}
}
pub fn aliases(self) -> &'static [&'static str] {
match self {
Self::Bash => BASH_DISPATCH_ALIASES,
Self::Grep => GREP_DISPATCH_ALIASES,
Self::Find => FIND_DISPATCH_ALIASES,
_ => &[],
}
}
pub fn from_dispatch_name(name: &str) -> Option<Self> {
ALL_TOOL_CAPABILITIES
.iter()
.copied()
.find(|tool| tool.canonical_name() == name || tool.aliases().contains(&name))
}
pub(crate) fn description(self) -> &'static str {
match self {
Self::Read => {
"**Tool Name**: `read`\nRead ordered local files and skills. Prefer focused local-file reads with line selectors instead of reading an entire file. Skills and skill references always load in full and reject line selectors. Local files without a selector return up to 400 lines. Use web open for HTTP(S) URLs. Local files return current-session `[PATH#TAG]` and 1-based `LINE:TEXT` anchors by default; `TAG` covers the whole file. For `hash_edit`, use only anchors returned by the latest non-raw read. Follow truncation and omission notices."
}
Self::ViewImage => {
"**Tool Name**: `view_image`\nInspect one local image with the configured vision model; provide an absolute path and specific visual details to report."
}
Self::Bash => {
"**Tool Name**: `bash`\nRun non-interactive commands from cwd. For HTTP, use this only for explicit/custom methods, headers, bodies, redirect control, binary/downloads, private/local services, or when the user explicitly requests `bash` or `curl`; prefer dedicated tools when available. Never block or rewrite `curl`. Use `hash_edit` for anchored changes to existing files and `write` for new files or complete replacements instead of shell-based editing. Excessive output can terminate the command."
}
Self::HashEdit => {
"**Tool Name**: `hash_edit`\nEdit existing files using current-session hashline tags and displayed anchors. Read targets without `:raw` first; use `write` for new files."
}
Self::Write => {
"**Tool Name**: `write`\nCreate or fully replace a file, creating parent directories as needed. Use `hash_edit` for anchored changes to existing files."
}
Self::Grep => {
"**Tool Name**: `grep`\nSearch file contents with native bounded search. `patterns` is an OR list (1–8); each item is independently treated as a case-sensitive regex with literal fallback. Results are ranked heuristically by default; use `mode: \"raw\"` for deterministic path/line order. `limit` and `offset` paginate unique primary matching lines; context is optional, does not consume the primary limit, and may be omitted at the output cap. Per-file, scan, traversal, deadline, and output budgets are reported in metadata when results are partial. Use `read` for full source and `ast_grep` for structural searches."
}
Self::Find => {
"**Tool Name**: `find`\nRecursively fuzzy-search file and directory paths, not contents. Ignored and hidden paths are omitted. Traversal is cancellable and bounded by an entry budget and deadline; partial scans are identified in result metadata. Use `list_files` for direct children and `grep` or `ast_grep` for content."
}
Self::ListFiles => {
"**Tool Name**: `list_files`\nList up to 1000 sorted names of a directory's direct children. Includes hidden and ignored entries; returns non-symlink regular files by default and also directories when requested. Non-recursive; use `find` for recursive fuzzy path search."
}
Self::Subagents => {
"**Tool Name**: `subagents`\nDelegate independent or parallel work to child agents with self-contained context. Use a listed `identity` for specialized work; the call returns after every task finishes."
}
Self::Web => {
"**Tool Name**: `web`\nResearch public web information and programming documentation. Use search with query, or open with either url or a prior cached reference. Omit unused fields or set them to null. URL open returns bounded readable text from public HTTP(S) pages; no credentials, redirects, private networks, JavaScript, or browser interaction. Cached references are temporary, available only in this runtime, and never refresh content. With active openai-codex, search returns synthesized answers with URL citations, not page extracts or cached references; omit domainFilter and recencyFilter. Output supplies no publication/crawl/fetch timestamps, so do not infer freshness."
}
Self::AstGrep => {
"**Tool Name**: `ast_grep`\nSearch source code by AST structure (operation search, the default), or inspect symbols before reading source (operation outline). Search, read-only rewrite previews, and outline are embedded; no CLI installation is needed. Search requires a nonempty pattern; omit outline-only fields or set them to null. For outline, omit pattern/rewrite or set both to null, never empty strings or placeholder patterns. Unused optional fields may be omitted or null. Outline defaults to items structure and view digest (including internal symbols), and returns bounded complete top-level entries with direct members and 1-based ranges. Narrow outline with name regex, symbol_type, items, view, and pub_members. Check partial/truncated metadata; files over byte/tree budgets are skipped. Deadlines are cooperative between bounded library calls. Project configs and custom extractors are disabled. Use grep for literal text, including comments and string contents."
}
Self::MagiControl => {
"**Tool Name**: `magi_control`\nManage the current agent session through enabled internal actions. Use `context_usage` to inspect current context-window use; pass only `action` for this action. The agent operates within a finite context window, so manage tokens proactively to preserve capacity for remaining work. Use `compact` when an operation reaches a good stopping point, a clear path remains, and a summary can preserve enough context to continue reliably. For `compact` only, optionally provide `context` containing facts that must survive compaction. `magi_control` must be the only tool call in its provider response. After compaction, execution automatically continues."
}
}
}
fn parameters_json(self) -> Value {
match self {
Self::Read => json!({
"type": "object",
"properties": {
(arg_key::PATHS): {
"type": "array",
"minItems": 1,
"maxItems": FILE_READ_MAX_FILES,
"items": {"type": "string", "minLength": 1},
"description": "Ordered targets: local files or skill://<name>[/relative-reference]. Local-file selectors: :N, :N-M, :-M, :N+, :N+K, and :raw; combine :raw with one line selector. Skills and skill references always load in full and reject line selectors. Raw disables hashline formatting only. Use web open for HTTP(S) URLs."
}
},
"required": [arg_key::PATHS],
"additionalProperties": false,
"x-defaultLines": FILE_READ_DEFAULT_LINES,
"x-maxBytes": FILE_READ_MAX_BYTES,
"x-maxFiles": FILE_READ_MAX_FILES
}),
Self::ViewImage => json!({
"type": "object",
"properties": {
(arg_key::PATH): {"type": "string", "minLength": 1, "description": "Absolute path to one existing regular local PNG, JPEG, GIF, or WebP image; extensions are case-insensitive and the file signature must match the extension. The path is canonicalized; outside-cwd access follows tools.view_image.absolute_paths."},
(arg_key::PROMPT): {"type": "string", "minLength": 1, "description": "Required nonblank instructions identifying the visual details to inspect and report. Runtime trimming remains authoritative."}
},
"required": [arg_key::PATH, arg_key::PROMPT],
"additionalProperties": false,
"x-defaultMaxImageBytes": DEFAULT_VIEW_IMAGE_MAX_IMAGE_BYTES,
"x-maxConfigurableImageBytes": MAX_VIEW_IMAGE_MAX_IMAGE_BYTES,
"x-outputMaxBytes": VIEW_IMAGE_RESPONSE_MAX_BYTES
}),
Self::Bash => json!({
"type": "object",
"properties": {
(arg_key::INTENT): {
"type": "string",
"minLength": 1,
"description": "Required nonblank, concise explanation of why this command is being run. Shown to the user on the bash transcript card."
},
(arg_key::COMMAND): {
"type": "string",
"minLength": 1,
"description": "Shell command to run."
},
(arg_key::TIMEOUT): {"type": "integer", "minimum": 1, "maximum": BASH_MAX_TIMEOUT_SECS, "description": format!("Timeout in seconds; defaults to {BASH_DEFAULT_TIMEOUT_SECS}. Use a shorter timeout only when needed.")}
},
"required": [arg_key::COMMAND, arg_key::INTENT],
"additionalProperties": false,
"x-stdoutMaxBytes": BASH_STDOUT_MAX_BYTES,
"x-stderrMaxBytes": BASH_STDERR_MAX_BYTES,
"x-notSandboxed": true
}),
Self::HashEdit => json!({
"type": "object",
"properties": {
(arg_key::INPUT): {"type": "string", "minLength": 1, "description": HASH_EDIT_INPUT_DESCRIPTION},
},
"required": [arg_key::INPUT],
"additionalProperties": false,
"x-targetMaxBytes": FILE_EDIT_TARGET_MAX_BYTES,
"x-editTextMaxBytes": FILE_EDIT_TEXT_MAX_BYTES,
"x-writeMaxBytes": FILE_WRITE_MAX_BYTES
}),
Self::Write => json!({
"type": "object",
"properties": {
(arg_key::PATH): {"type": "string", "minLength": 1, "description": "Target file path, relative resolves from cwd, outside-cwd absolute behavior follows tools.write.absolute_paths, parent directories created. Final symlink targets are rejected."},
(arg_key::CONTENT): {"type": "string", "description": format!("Complete UTF-8 file content, empty allowed, replaces rather than appends, runtime maximum {FILE_WRITE_MAX_BYTES} UTF-8 bytes.")}
},
"required": [arg_key::PATH, arg_key::CONTENT],
"additionalProperties": false,
"x-maxContentBytes": FILE_WRITE_MAX_BYTES
}),
Self::Grep => json!({
"type": "object",
"properties": {
(arg_key::PATTERNS): {
"type": "array",
"minItems": 1,
"maxItems": GREP_MAX_PATTERNS,
"items": {"type": "string", "minLength": 1, "maxLength": GREP_MAX_PATTERN_CHARS},
"description": format!("OR semantics; each pattern is an independent case-sensitive regex with literal fallback. Each pattern is limited to {GREP_MAX_PATTERN_CHARS} characters and {GREP_MAX_PATTERN_BYTES} UTF-8 bytes; all patterns together are limited to {GREP_MAX_PATTERN_TOTAL_BYTES} UTF-8 bytes.")
},
(arg_key::PATH): {"type": "string", "description": "Optional recursive search path; defaults to cwd. Relative paths resolve from cwd; outside-cwd absolute paths follow tools.grep.absolute_paths. Hidden and ignored files, .git, target, binary and special files are skipped."},
(arg_key::MODE): {"type": "string", "enum": ["ranked", "raw"], "description": format!("Optional output mode; defaults to ranked. Ranked results are grouped by file, heuristically ordered, and limited to {GREP_RANKED_PER_FILE} primary matches per file. Raw results are deterministic path/line records and exhaustive only within read, traversal, scan-time, and output budgets; raw pagination uses one extra match as lookahead.")},
(arg_key::LIMIT): {"type": "integer", "minimum": 1, "maximum": GREP_MAX_LIMIT, "description": format!("primary matching lines per page; defaults to {GREP_DEFAULT_LIMIT}. Context rows do not consume this limit.")},
(arg_key::OFFSET): {"type": "integer", "minimum": 0, "maximum": GREP_MAX_OFFSET, "description": format!("Number of primary matching lines to skip for pagination; defaults to 0 and is capped at {GREP_MAX_OFFSET}. has_more and next_offset count primary rows only.")},
(arg_key::CONTEXT): {"type": "integer", "minimum": 0, "maximum": GREP_MAX_CONTEXT, "description": format!("Optional context lines before and after each primary match; defaults to 0 and is capped at {GREP_MAX_CONTEXT} per side. Context does not consume the primary limit and may be omitted at the output cap.")}
},
"required": [arg_key::PATTERNS],
"additionalProperties": false,
"x-defaultLimit": GREP_DEFAULT_LIMIT,
"x-defaultOffset": 0,
"x-defaultContext": 0,
"x-maxPatternBytes": GREP_MAX_PATTERN_BYTES,
"x-maxPatternTotalBytes": GREP_MAX_PATTERN_TOTAL_BYTES,
"x-maxFileBytes": GREP_MAX_FILE_BYTES,
"x-maxScanBytes": GREP_MAX_SCAN_BYTES,
"x-maxFiles": GREP_MAX_FILES,
"x-deadlineSeconds": GREP_DEADLINE_SECS,
"x-rankedPerFile": GREP_RANKED_PER_FILE,
"x-outputMaxBytes": GREP_OUTPUT_MAX_BYTES
}),
Self::Find => json!({
"type": "object",
"properties": {
(arg_key::QUERY): {"type": "string", "minLength": 1, "maxLength": 512, "description": "Case-insensitive fuzzy terms matched against full paths; every whitespace-separated term must match. Glob syntax is unsupported."},
(arg_key::PATH): {"type": "string", "description": "Existing directory to search; defaults to cwd. Relative paths resolve from cwd; outside-cwd absolute paths follow tools.find.absolute_paths."},
(arg_key::KIND): {"type": "string", "enum": ["files", "directories", "mixed"], "description": "Path kinds to return; defaults to files."},
(arg_key::LIMIT): {"type": "integer", "minimum": 1, "maximum": FIND_MAX_LIMIT, "description": "Maximum ranked matches returned; defaults to 50."},
(arg_key::OFFSET): {"type": "integer", "minimum": 0, "description": "Ranked matches to skip for pagination; defaults to 0."}
},
"required": [arg_key::QUERY],
"additionalProperties": false,
"x-defaultLimit": FIND_DEFAULT_LIMIT,
"x-maxVisitedEntries": FIND_MAX_VISITED_ENTRIES,
"x-deadlineSeconds": FIND_DEADLINE_SECS
}),
Self::ListFiles => json!({
"type": "object",
"properties": {
(arg_key::PATH): {"type": "string", "minLength": 1, "description": "Existing directory to list. Relative paths resolve from cwd; outside-cwd absolute paths follow tools.list_files.absolute_paths."},
(arg_key::INCLUDE_DIRECTORIES): {"type": "boolean", "description": "Also return direct child directories; defaults to false."}
},
"required": [arg_key::PATH],
"additionalProperties": false
}),
Self::Subagents => json!({
"type": "object",
"properties": {
(arg_key::TASKS): {
"type": "array",
"minItems": 1,
"maxItems": MAX_SUBAGENT_TASKS,
"description": "Independent tasks; may run concurrently. Results are returned in input order.",
"items": {
"type": "object",
"properties": {
"intent": {
"type": "string",
"minLength": 1,
"description": format!("Required nonblank objective; runtime maximum is {MAX_SUBAGENT_TASK_INTENT_BYTES} UTF-8 bytes.")
},
"mode": {"type": "string", "enum": ["inspect", "standard"], "description": "Select inspect for read-only discovery: only local/skill read, find, list_files, grep and ast_grep; no shell, tests, edits, network, MCP or delegation. Fixed for the task; implementation requires a separate authorized standard task. Omission means standard, still subject to inherited/profile restrictions."},
"agent": {"type": "string", "description": "Optional label/persona included with the task; it does not select an identity profile."},
(arg_key::IDENTITY): {"type": "string", "description": "Optional profile ID from available identities listed in the system prompt. IDs use ASCII letters, digits, `_`, or `-`; availability is dynamic."},
"context": {
"type": "string",
"description": format!("Optional self-contained exact instructions and relevant context; runtime maximum is {MAX_SUBAGENT_TASK_CONTEXT_BYTES} UTF-8 bytes.")
},
"cwd": {"type": "string", "description": "Optional existing child directory; defaults to the parent cwd. Relative paths resolve from the parent cwd; absolute behavior follows tools.subagents.absolute_paths."}
},
"required": ["intent"],
"additionalProperties": false
}
},
(arg_key::CONCURRENCY): {
"type": "integer",
"minimum": 1,
"maximum": MAX_SUBAGENT_CONCURRENCY,
"description": format!("Optional worker count from 1 to {MAX_SUBAGENT_CONCURRENCY}; defaults to {DEFAULT_SUBAGENT_CONCURRENCY}. Effective workers are capped by task count.")
}
},
"required": [arg_key::TASKS],
"additionalProperties": false,
"x-defaultConcurrency": DEFAULT_SUBAGENT_CONCURRENCY,
"x-maxTasks": MAX_SUBAGENT_TASKS,
"x-maxConcurrency": MAX_SUBAGENT_CONCURRENCY,
"x-taskIntentMaxBytes": MAX_SUBAGENT_TASK_INTENT_BYTES,
"x-taskContextMaxBytes": MAX_SUBAGENT_TASK_CONTEXT_BYTES
}),
Self::Web => json!({
"type": "object",
"properties": {
"operation": {"type":"string", "enum":["search","open"]},
"query": {"type":["string","null"], "minLength":1,"maxLength":512,"description":"Required for search. Omit for open."},
"domainFilter": {"type":["array","null"], "maxItems":super::exa::MAX_DOMAINS, "items":{"type":"string","minLength":1,"maxLength":super::exa::MAX_DOMAIN_CHARS + 1}, "description":"Exa search only; rejected for active openai-codex. Bare ASCII domains; prefix '-' to exclude. Domain portion at most 253 characters, labels at most 63. No schemes, paths, ports or whitespace."},
"recencyFilter": {"type":["string","null"], "enum":["day","week","month","year",null], "description":"Exa search only; rejected for active openai-codex. Publication-date window: past 1, 7, 30 or 365 days, measured from the current UTC date; not crawl freshness."},
"url": {"type":["string","null"], "minLength":1,"maxLength":2048,"description":"Public HTTP(S) URL for open; no credentials or private networks."},
"reference": {"type":["string","null"], "minLength":1,"maxLength":80,"description":"Stable web reference from a prior result; alternative to URL for cache-only open."},
"limit": {"type":["integer","null"], "minimum":1,"maximum":10,"description":"Search results; default 5. Codex search treats this as a source-count target, not a guaranteed count. Omit for open."}
},
"required": ["operation"],
"additionalProperties": false,
"x-outputMaxBytes": OUTPUT_MAX_BYTES
}),
Self::AstGrep => json!({
"type": "object",
"properties": {
(arg_key::OPERATION): {"type": "string", "enum": ["search", "outline"], "description": "Defaults to search. Outline returns complete top-level symbols with direct members and 1-based ranges."},
(arg_key::PATTERN): {"type": ["string", "null"], "minLength": 1, "description": "Search requires a nonempty pattern; for outline, omit or use null (not an empty string or placeholder). $X matches one named node; $$$X matches zero or more nodes."},
(arg_key::LANGUAGE): {"type": ["string", "null"], "description": "Language hint; inferred from file extensions when omitted or null."},
(arg_key::PATH): {"type": ["string", "null"], "description": "File or directory to search; relative paths resolve from cwd. Omit or use null to search cwd."},
(arg_key::REWRITE): {"type": ["string", "null"], "description": "Search only: replacement pattern; may reuse pattern metavariables. Previews a diff without modifying files. For outline or no preview, omit or use null (not an empty string)."},
"items": {"type": ["string", "null"], "enum": ["structure", "exports", "imports", "all", null], "description": "Outline only; omit or use null for search. Defaults to structure when omitted or null, including internal symbols."},
"view": {"type": ["string", "null"], "enum": ["names", "signatures", "digest", "expanded", null], "description": "Outline only; omit or use null for search. Defaults to digest when omitted or null; controls included signatures and direct members."},
"name": {"type": ["string", "null"], "minLength": 1, "maxLength": 512, "description": "Outline only: case-sensitive Rust regex over top-level name, signature and first source line. Runtime maximum 512 bytes. Omit or use null for no filter or for search."},
"symbol_type": {"type": ["string", "null"], "minLength": 1, "maxLength": 512, "description": "Outline only: comma-separated lower camel case symbol types, e.g. class,function. Runtime maximum 512 bytes. Omit or use null for no filter or for search."},
"pub_members": {"type": ["boolean", "null"], "description": "Outline only: restrict direct members to public ones; defaults to false when omitted or null. For search, omit or use null (not false)."},
(arg_key::LIMIT): {"type": ["integer", "null"], "minimum": 1, "maximum": AST_GREP_MAX_LIMIT, "description": "Maximum search lines or complete top-level outline entries; defaults to 100 when omitted or null. Output byte and work budgets also apply."}
},
"required": [],
"additionalProperties": false,
"x-defaultLimit": AST_GREP_DEFAULT_LIMIT,
"x-timeoutSeconds": AST_GREP_TIMEOUT_SECS,
"x-stdoutMaxBytes": AST_GREP_STDOUT_MAX_BYTES
}),
Self::MagiControl => json!({
"type": "object",
"properties": {
(arg_key::ACTION): {"type": "string", "enum": ["compact", "context_usage"], "description": "Internal action to run immediately."},
(arg_key::CONTEXT): {
"type": "string",
"minLength": 1,
"maxLength": MAGI_CONTROL_CONTEXT_MAX_CHARS,
"description": "Only used with action compact: optional facts to preserve in the compaction summary. Do not send for context_usage; it will be ignored."
}
},
"required": [arg_key::ACTION],
"additionalProperties": false
}),
}
}
pub(crate) fn provider_definition_json(self) -> Value {
json!({
"type": "function",
"name": self.canonical_name(),
"description": self.description(),
"parameters": self.parameters_json()
})
}
}
static MVP_TOOL_DEFINITIONS_JSON: OnceLock<Value> = OnceLock::new();
static MVP_TOOL_DEFINITIONS_WITHOUT_SUBAGENTS_JSON: OnceLock<Value> = OnceLock::new();
fn build_tool_definitions_json(include_subagents: bool, disabled_tools: &HashSet<String>) -> Value {
Value::Array(
MVP_TOOL_CAPABILITIES
.iter()
.filter(|tool| {
(include_subagents || **tool != ToolCapability::Subagents)
&& !disabled_tools.contains(tool.canonical_name())
})
.map(|tool| tool.provider_definition_json())
.collect(),
)
}
fn build_mvp_tool_definitions_json() -> Value {
build_tool_definitions_json(true, &HashSet::new())
}
fn build_mvp_tool_definitions_without_subagents_json() -> Value {
build_tool_definitions_json(false, &HashSet::new())
}
pub(crate) fn mvp_tool_definitions_json() -> Value {
MVP_TOOL_DEFINITIONS_JSON
.get_or_init(build_mvp_tool_definitions_json)
.clone()
}
pub(crate) fn mvp_tool_definitions_json_with_subagents(include_subagents: bool) -> Value {
if include_subagents {
mvp_tool_definitions_json()
} else {
MVP_TOOL_DEFINITIONS_WITHOUT_SUBAGENTS_JSON
.get_or_init(build_mvp_tool_definitions_without_subagents_json)
.clone()
}
}
pub(crate) fn tool_definitions_json_with_dynamic(
include_subagents: bool,
dynamic_definitions: &[Value],
disabled_tools: &HashSet<String>,
) -> Value {
if dynamic_definitions.is_empty() && disabled_tools.is_empty() {
return mvp_tool_definitions_json_with_subagents(include_subagents);
}
let mut definitions = build_tool_definitions_json(include_subagents, disabled_tools)
.as_array()
.cloned()
.unwrap_or_default();
definitions.extend(dynamic_definitions.iter().filter_map(|definition| {
let name = definition.get("name")?.as_str()?;
(!disabled_tools.contains(name)).then(|| definition.clone())
}));
Value::Array(definitions)
}