跳转至内容

工具与技能

工具是通过 @tool 装饰器注册的普通 Python 函数;注册表向模型提供其 Schema,并在执行时强制权限级别。Skill 是 Agent 可按需加载的 Markdown 操作手册;App 与 Expert 将技能与配置打包在一起。

演练参见工具、技能与专家。

注册表

tool

tool(
    name: str,
    description: str,
    permission: PermissionLevel = PermissionLevel.AUTO,
)
Source code in src/dashscope_agenticx/tools/registry.py
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
def tool(
    name: str,
    description: str,
    permission: PermissionLevel = PermissionLevel.AUTO,
):
    def decorator(func: Callable) -> Callable:
        params_schema = _build_parameters_schema(func)
        tool_def = ToolDefinition(
            name=name,
            description=description,
            permission=permission,
            func=func,
            parameters=params_schema,
        )
        registry.register(tool_def)
        func._tool_definition = tool_def
        return func

    return decorator

ToolRegistry

ToolRegistry()
Source code in src/dashscope_agenticx/tools/registry.py
348
349
350
351
352
def __init__(self):
    self._tools: dict[str, ToolDefinition] = {}
    # Monotonic mutation counter. Agent loops use it to detect tools that
    # were connected/enabled mid-turn and rebuild the provider schema.
    self._version = 0

version property

version: int

Registry mutation version for cheap schema invalidation.

register

register(tool_def: ToolDefinition)

Register a tool. When used as a decorator with a ToolDefinition, returns a decorator.

Source code in src/dashscope_agenticx/tools/registry.py
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
def register(self, tool_def: ToolDefinition):
    """Register a tool. When used as a decorator with a ToolDefinition,
    returns a decorator."""
    if isinstance(tool_def, ToolDefinition):
        self._tools[tool_def.name] = tool_def
        self._version += 1

        def decorator(func: Callable) -> Callable:
            self._tools[tool_def.name].func = func
            self._version += 1
            func._tool_definition = tool_def
            return func

        return decorator
    # Called with a callable directly (legacy)
    self._tools[tool_def.name] = tool_def
    self._version += 1
    return None

register_mcp_tool

register_mcp_tool(
    name: str,
    description: str,
    parameters: dict,
    call_fn: Callable,
)
Source code in src/dashscope_agenticx/tools/registry.py
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
def register_mcp_tool(
    self,
    name: str,
    description: str,
    parameters: dict,
    call_fn: Callable,
):
    tool_def = ToolDefinition(
        name=name,
        description=description,
        permission=PermissionLevel.AUTO,
        func=call_fn,
        parameters=parameters,
    )
    self._tools[name] = tool_def
    self._version += 1

unregister

unregister(name: str)
Source code in src/dashscope_agenticx/tools/registry.py
395
396
397
398
def unregister(self, name: str):
    if name in self._tools:
        self._tools.pop(name)
        self._version += 1

get

get(name: str) -> ToolDefinition | None
Source code in src/dashscope_agenticx/tools/registry.py
400
401
def get(self, name: str) -> ToolDefinition | None:
    return self._tools.get(name)

list_tools

list_tools() -> list[ToolDefinition]
Source code in src/dashscope_agenticx/tools/registry.py
403
404
def list_tools(self) -> list[ToolDefinition]:
    return list(self._tools.values())

clone

clone() -> 'ToolRegistry'

Return an isolated registry with the same tool definitions.

Tool callables are intentionally shared: built-in functions are immutable registration targets. Definitions and parameter schemas are copied so runtime-local registration, renaming, or unregistration does not mutate another runtime.

Source code in src/dashscope_agenticx/tools/registry.py
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
def clone(self) -> "ToolRegistry":
    """Return an isolated registry with the same tool definitions.

    Tool callables are intentionally shared: built-in functions are
    immutable registration targets. Definitions and parameter schemas are
    copied so runtime-local registration, renaming, or unregistration does
    not mutate another runtime.
    """
    cloned = ToolRegistry()
    for tool_def in self._tools.values():
        cloned._tools[tool_def.name] = ToolDefinition(
            name=tool_def.name,
            description=tool_def.description,
            permission=tool_def.permission,
            func=tool_def.func,
            parameters=copy.deepcopy(tool_def.parameters),
        )
    cloned._version = self._version
    return cloned

to_schema_list

to_schema_list(user_input: str = '') -> list[dict]

Convert registered tools to JSON schema format.

If user_input is provided, prioritize tools relevant to the input. Core tools (filesystem, shell) are always included. Specialized tools (platform, MCP) are included if keywords match.

Source code in src/dashscope_agenticx/tools/registry.py
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
def to_schema_list(self, user_input: str = "") -> list[dict]:
    """Convert registered tools to JSON schema format.

    If user_input is provided, prioritize tools relevant to the input.
    Core tools (filesystem, shell) are always included.
    Specialized tools (platform, MCP) are included if keywords match."""
    result = []

    # Determine which tools to include
    include_tools = set(_CORE_TOOLS)

    include_tools.update(_SESSION_ALWAYS_ON)

    # evolve_skill stays env-gated until caps and utility pruning land —
    # auto-generated skills without pruning are library noise.
    if os.environ.get("AGENTICX_EVOLVE_SKILL", "0") == "1":
        include_tools.add("evolve_skill")

    # Add capability-gated agent tools (delegate/subagent_invoke) whenever
    # they are registered — registration itself is the capability gate.
    include_tools.update(_CAPABILITY_AGENT_TOOLS & set(self._tools))

    # Same gate applies to every tool registered under an enabled
    # capability: extension HTTP/vision tools ({cap}_{tool} names).
    # Without this they'd be registered but never offered to the model,
    # making /capability enable a no-op in practice.
    # Exception: bailian_* CLI wrappers are numerous (~25 full schemas);
    # they ride only when a keyword matches (see keyword_tools above),
    # with the platform name as the catch-all.
    # Lazy import: dashscope_agenticx.tools.platform imports this module.
    from dashscope_agenticx.tools.platform import capability_tool_names

    include_tools.update(
        n
        for n in capability_tool_names() & set(self._tools)
        if not n.startswith("bailian_")
    )

    # Add keyword-matched tools if user input provided
    if user_input:
        if isinstance(user_input, list):
            input_lower = " ".join(
                b.get("text", "")
                for b in user_input
                if isinstance(b, dict)
            ).lower()
        else:
            input_lower = user_input.lower()
        for keyword, tools in _KEYWORD_TOOLS.items():
            if keyword.lower() in input_lower:
                include_tools.update(tools)

    # Add all MCP tools (they're dynamically added and usually relevant)
    for name in self._tools:
        if name.startswith("mcp_"):
            include_tools.add(name)

    # Build schema list
    for name, t in self._tools.items():
        # Include if in the filtered set, or if it's an MCP tool
        if name in include_tools or name.startswith("mcp_"):
            result.append(
                {
                    "name": t.name,
                    "description": t.description,
                    "parameters": t.parameters,
                },
            )

    return result

ToolDefinition dataclass

ToolDefinition(
    name: str,
    description: str,
    permission: PermissionLevel = PermissionLevel.AUTO,
    func: Callable = None,
    parameters: dict = dict(),
)

name instance-attribute

name: str

description instance-attribute

description: str

permission class-attribute instance-attribute

permission: PermissionLevel = PermissionLevel.AUTO

func class-attribute instance-attribute

func: Callable = field(default=None)

parameters class-attribute instance-attribute

parameters: dict = field(default_factory=dict)

PermissionLevel

Bases: Enum

AUTO class-attribute instance-attribute

AUTO = 'auto'

CONFIRM class-attribute instance-attribute

CONFIRM = 'confirm'

DANGEROUS class-attribute instance-attribute

DANGEROUS = 'dangerous'

RuntimeToolRegistry

RuntimeToolRegistry()

Bases: ToolRegistry

Backward-compatible registry facade with runtime-local binding.

Static @tool imports populate the default registry. A Runtime clones that baseline and binds the clone through a ContextVar while wiring and executing an Agent. Existing modules that import the global registry therefore resolve to the correct runtime without a process-wide parent pointer, while legacy callers continue to see a ToolRegistry instance.

Source code in src/dashscope_agenticx/tools/registry.py
508
509
510
511
512
def __init__(self):
    self._default = ToolRegistry()
    self._bound: contextvars.ContextVar[
        ToolRegistry | None
    ] = contextvars.ContextVar("agenticx_tool_registry", default=None)

version property

version: int

current

current() -> ToolRegistry
Source code in src/dashscope_agenticx/tools/registry.py
514
515
def current(self) -> ToolRegistry:
    return self._bound.get() or self._default

bind

bind(target: ToolRegistry)
Source code in src/dashscope_agenticx/tools/registry.py
517
518
519
520
521
522
523
@contextlib.contextmanager
def bind(self, target: ToolRegistry):
    token = self._bound.set(target)
    try:
        yield target
    finally:
        self._bound.reset(token)

register

register(tool_def: ToolDefinition)
Source code in src/dashscope_agenticx/tools/registry.py
537
538
def register(self, tool_def: ToolDefinition):
    return self.current().register(tool_def)

register_mcp_tool

register_mcp_tool(
    name: str,
    description: str,
    parameters: dict,
    call_fn: Callable,
)
Source code in src/dashscope_agenticx/tools/registry.py
540
541
542
543
544
545
546
547
548
549
550
551
552
def register_mcp_tool(
    self,
    name: str,
    description: str,
    parameters: dict,
    call_fn: Callable,
):
    return self.current().register_mcp_tool(
        name,
        description,
        parameters,
        call_fn,
    )

unregister

unregister(name: str)
Source code in src/dashscope_agenticx/tools/registry.py
554
555
def unregister(self, name: str):
    return self.current().unregister(name)

get

get(name: str) -> ToolDefinition | None
Source code in src/dashscope_agenticx/tools/registry.py
557
558
def get(self, name: str) -> ToolDefinition | None:
    return self.current().get(name)

list_tools

list_tools() -> list[ToolDefinition]
Source code in src/dashscope_agenticx/tools/registry.py
560
561
def list_tools(self) -> list[ToolDefinition]:
    return self.current().list_tools()

clone

clone() -> ToolRegistry
Source code in src/dashscope_agenticx/tools/registry.py
563
564
def clone(self) -> ToolRegistry:
    return self.current().clone()

to_schema_list

to_schema_list(user_input: str = '') -> list[dict]
Source code in src/dashscope_agenticx/tools/registry.py
566
567
def to_schema_list(self, user_input: str = "") -> list[dict]:
    return self.current().to_schema_list(user_input)

bind_tool_registry

bind_tool_registry(target: ToolRegistry)

Bind the compatibility facade to target for the current context.

Source code in src/dashscope_agenticx/tools/registry.py
574
575
576
def bind_tool_registry(target: ToolRegistry):
    """Bind the compatibility facade to ``target`` for the current context."""
    return registry.bind(target)

内置工具

核心工具随基础安装一起提供:

filesystem

read_file

read_file(
    path: str,
    offset: int | None = None,
    limit: int | None = None,
) -> str
Source code in src/dashscope_agenticx/tools/filesystem.py
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
@tool(
    name="read_file",
    description=(
        "Read file contents, prefixed with 1-based line numbers. offset is "
        "the line number to start at; limit is how many lines to return. "
        "Reads are windowed: when lines remain, the result ends with the "
        "omitted count and the offset that continues from there."
    ),
    permission=PermissionLevel.AUTO,
)
def read_file(
    path: str,
    offset: int | None = None,
    limit: int | None = None,
) -> str:
    try:
        path = validate_path(path)
    except ValueError as e:
        return f"Error: {e}"
    if not os.path.isfile(path):
        return f"Error: file not found - {path}"

    if os.path.splitext(path)[1].lower() in _IMAGE_BINARY_EXTS:
        from dashscope_agenticx.tools import vision

        perceived = vision.auto_perceive(path)
        if perceived is not None:
            return perceived
        return (
            f"[{path} is an image; reading it as text returns binary "
            "noise, not its content. To perceive what the image shows — "
            "text, digits, a chart, geometry — call view_image on this "
            "path, or run tesseract OCR when exact text matters. For "
            "metadata only (format, dimensions), run_command with "
            "file/identify instead.]"
        )

    return _read_text_window(path, offset, limit)

write_file

write_file(path: str, content: str) -> str
Source code in src/dashscope_agenticx/tools/filesystem.py
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
@tool(
    name="write_file",
    description=(
        "Write content to a file; overwrites if it exists. "
        "The result includes a unified diff. `path` must be inside the "
        "working directory or the system temp dir."
    ),
    permission=PermissionLevel.CONFIRM,
)
def write_file(path: str, content: str) -> str:
    import difflib

    try:
        path = validate_write_path(path)
    except ValueError as e:
        return f"Error: {e}"

    if len(content) > _MAX_WRITE_SIZE:
        return (
            f"Error: content too large ({len(content)} bytes); "
            f"limit is {_MAX_WRITE_SIZE // (1024*1024)} MB"
        )

    parent = os.path.dirname(path)
    if parent and not os.path.exists(parent):
        os.makedirs(parent, exist_ok=True)

    # Capture before-state for diff (best-effort — binary or read errors
    # fall through to "new file" treatment).
    old_content = ""
    existed = os.path.isfile(path)
    if existed:
        try:
            with open(path, "r", encoding="utf-8") as f:
                old_content = f.read()
        except (OSError, UnicodeDecodeError):
            existed = False  # treat as new for diff purposes

    # Checkpoint the current state so /undo can reverse this write.
    # Lazy import to avoid tool-module import cycles.
    from dashscope_agenticx.tools import checkpoint

    checkpoint.snapshot(path, "overwrite" if existed else "create")

    with open(path, "w", encoding="utf-8") as f:
        f.write(content)

    if not existed:
        return f"Created file: {path} ({len(content)} chars)"

    if old_content == content:
        return f"Content unchanged: {path}"

    # Cap displayed diff so a 5000-line full rewrite doesn't drown the UI;
    # full content is in messages so LLM still sees everything it wrote.
    # Don't pass lineterm="" — default "\n" gives proper newlines on the
    # ---, +++, @@ control lines so the diff is readable when joined.
    diff_lines = list(
        difflib.unified_diff(
            old_content.splitlines(keepends=True),
            content.splitlines(keepends=True),
            fromfile=f"a/{path}",
            tofile=f"b/{path}",
            n=3,
        ),
    )
    MAX_DIFF_LINES = 80
    truncated = ""
    if len(diff_lines) > MAX_DIFF_LINES:
        total_added = sum(
            1
            for dline in diff_lines
            if dline.startswith("+") and not dline.startswith("+++")
        )
        diff_lines = diff_lines[:MAX_DIFF_LINES]
        truncated = (
            f"\n... (diff truncated: {total_added} lines added, "
            f"showing first {MAX_DIFF_LINES})"
        )
    diff_text = "".join(diff_lines)

    return (
        f"Wrote file: {path} ({len(content)} chars)\n"
        f"--- diff ---\n"
        f"{diff_text}{truncated}"
    )

list_directory

list_directory(path: str) -> str
Source code in src/dashscope_agenticx/tools/filesystem.py
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
@tool(
    name="list_directory",
    description="List directory contents with file type and size.",
    permission=PermissionLevel.AUTO,
)
def list_directory(path: str) -> str:
    try:
        path = validate_path(path)
    except ValueError as e:
        return f"Error: {e}"
    if not os.path.isdir(path):
        return f"Error: directory not found - {path}"

    entries = []
    for name in sorted(os.listdir(path)):
        full = os.path.join(path, name)
        if os.path.isdir(full):
            entries.append(f"  [dir]  {name}/")
        else:
            size = os.path.getsize(full)
            entries.append(f"  [file] {name}  ({_format_size(size)})")

    header = f"Directory: {path} ({len(entries)} entries)"
    return header + "\n" + "\n".join(entries)

create_directory

create_directory(path: str) -> str
Source code in src/dashscope_agenticx/tools/filesystem.py
282
283
284
285
286
287
288
289
290
291
292
293
@tool(
    name="create_directory",
    description="Create a directory, including nested levels.",
    permission=PermissionLevel.CONFIRM,
)
def create_directory(path: str) -> str:
    try:
        path = validate_write_path(path)
    except ValueError as e:
        return f"Error: {e}"
    os.makedirs(path, exist_ok=True)
    return f"Created directory: {path}"

delete_file

delete_file(path: str) -> str
Source code in src/dashscope_agenticx/tools/filesystem.py
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
@tool(
    name="delete_file",
    description="Delete the specified file. This cannot be undone.",
    permission=PermissionLevel.DANGEROUS,
)
def delete_file(path: str) -> str:
    try:
        path = validate_path(path)
    except ValueError as e:
        return f"Error: {e}"
    if not os.path.isfile(path):
        return f"Error: file not found - {path}"
    # Checkpoint so /undo can restore the deleted file.
    from dashscope_agenticx.tools import checkpoint

    checkpoint.snapshot(path, "delete")
    os.remove(path)
    return f"Deleted file: {path}"

delete_directory

delete_directory(path: str) -> str
Source code in src/dashscope_agenticx/tools/filesystem.py
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
@tool(
    name="delete_directory",
    description=(
        "Delete a directory and all its contents. The tree is checkpointed "
        "first, so /undo can restore it within the checkpoint size budget."
    ),
    permission=PermissionLevel.DANGEROUS,
)
def delete_directory(path: str) -> str:
    try:
        path = validate_path(path)
    except ValueError as e:
        return f"Error: {e}"
    if not os.path.isdir(path):
        return f"Error: directory not found - {path}"
    # Prevent deleting cwd itself
    abs_path = os.path.abspath(path)
    cwd = os.path.abspath(".")
    if abs_path == cwd:
        return "Error: cannot delete the current working directory"
    # Checkpoint so /undo can restore the tree; oversized trees are recorded
    # without a backup and undo will say so.
    from dashscope_agenticx.tools import checkpoint

    checkpoint.snapshot(path, "delete_dir")
    shutil.rmtree(path)
    return f"Deleted directory: {path}"

search_files

search_files(pattern: str, path: str | None = None) -> str
Source code in src/dashscope_agenticx/tools/filesystem.py
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
@tool(
    name="search_files",
    description=(
        "Search files by name or path pattern, relative to `path` "
        "(default: the working directory). Supports wildcards like *.py, "
        "test_*, src/*.ts and .github/workflows/*.yml. `*` crosses directory "
        "separators, so *.md finds every Markdown file at any depth."
    ),
    permission=PermissionLevel.AUTO,
)
def search_files(pattern: str, path: str | None = None) -> str:
    search_root = os.path.expanduser(path) if path else os.getcwd()
    try:
        search_root = validate_path(search_root)
    except ValueError as e:
        return f"Error: {e}"
    if not os.path.isdir(search_root):
        return f"Error: search path not found - {search_root}"

    needle = pattern.replace(os.sep, "/")
    want_hidden = _pattern_names_hidden_dir(pattern)
    matches = []
    root_depth = search_root.rstrip(os.sep).count(os.sep)
    for root, dirs, files in os.walk(search_root):
        # Enforce depth limit
        current_depth = root.rstrip(os.sep).count(os.sep) - root_depth
        if current_depth >= _MAX_SEARCH_DEPTH:
            dirs[:] = []
        # Sensitive directories are always skipped. Other dot-directories are
        # skipped unless the pattern asks for one, so
        # `.agenticx/skills/*.md` is
        # searchable without walking every `.git` in the tree.
        dirs[:] = [
            d
            for d in dirs
            if d not in SENSITIVE_NAMES
            and (want_hidden or not d.startswith("."))
        ]
        for name in files:
            if name in SENSITIVE_NAMES:
                continue
            rel = os.path.relpath(os.path.join(root, name), search_root)
            if fnmatch.fnmatch(rel.replace(os.sep, "/"), needle) or (
                fnmatch.fnmatch(name, needle)
            ):
                matches.append(os.path.join(root, name))
                if len(matches) >= 100:
                    break
        if len(matches) >= 100:
            break

    if not matches:
        return (
            f"No files match '{pattern}' under {search_root}. The pattern is "
            "matched against paths relative to that root, and dot-directories "
            "are skipped unless the pattern names one."
        )
    result = f"Found {len(matches)} matching files:\n"
    result += "\n".join(f"  {m}" for m in matches)
    return result

move_file

move_file(src: str, dst: str) -> str
Source code in src/dashscope_agenticx/tools/filesystem.py
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
@tool(
    name="move_file",
    description="Move or rename a file/directory.",
    permission=PermissionLevel.CONFIRM,
)
def move_file(src: str, dst: str) -> str:
    try:
        src = validate_path(src)
        dst = validate_write_path(dst)
    except ValueError as e:
        return f"Error: {e}"
    if not os.path.exists(src):
        return f"Error: source path not found - {src}"
    shutil.move(src, dst)
    return f"Moved: {src} → {dst}"

shell

MAX_OUTPUT_LENGTH module-attribute

MAX_OUTPUT_LENGTH = 10000

MAX_OUTPUT_BYTES module-attribute

MAX_OUTPUT_BYTES = 5 * 1024 * 1024

DEFAULT_TIMEOUT module-attribute

DEFAULT_TIMEOUT = 600

TIMEOUT_ENV module-attribute

TIMEOUT_ENV = 'AGENTICX_COMMAND_TIMEOUT'

IS_WINDOWS module-attribute

IS_WINDOWS = os.name == 'nt'

OUTPUT_ENCODINGS module-attribute

OUTPUT_ENCODINGS = _resolve_output_encodings()

OUTPUT_ENCODING module-attribute

OUTPUT_ENCODING = OUTPUT_ENCODINGS[0]

WIN_SHELL module-attribute

WIN_SHELL = _resolve_win_shell()

BLOCKED_PATTERNS module-attribute

BLOCKED_PATTERNS = [
    "mkfs",
    "dd if=",
    "> /dev/sd",
    "chmod -R 777 /",
    "shred",
    "wipefs",
    "--no-preserve-root",
    "rd /s /q",
    "del /f /q /s",
    "> \\\\.\\PhysicalDrive",
]

default_timeout

default_timeout() -> int

Seconds a run_command call gets before it is killed.

Resolved per call rather than at import, so exporting AGENTICX_COMMAND_TIMEOUT takes effect without a restart.

Source code in src/dashscope_agenticx/tools/shell.py
183
184
185
186
187
188
189
190
191
192
193
def default_timeout() -> int:
    """Seconds a run_command call gets before it is killed.

    Resolved per call rather than at import, so exporting
    ``AGENTICX_COMMAND_TIMEOUT`` takes effect without a restart.
    """
    try:
        value = int(os.environ.get(TIMEOUT_ENV, "") or DEFAULT_TIMEOUT)
    except ValueError:
        return DEFAULT_TIMEOUT
    return value if value > 0 else DEFAULT_TIMEOUT

shell_label

shell_label() -> str

How run_command executes a command, for the system prompt.

Lives next to _spawn so the prompt cannot drift from what the tool really runs. Nothing used to say which shell this is: a model that assumes POSIX spends a turn on ls -la ... 2>/dev/null || find / before a PowerShell ParserError tells it otherwise.

Source code in src/dashscope_agenticx/tools/shell.py
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
def shell_label() -> str:
    """How ``run_command`` executes a command, for the system prompt.

    Lives next to ``_spawn`` so the prompt cannot drift from what the tool
    really runs. Nothing used to say which shell this is: a model that assumes
    POSIX spends a turn on ``ls -la ... 2>/dev/null || find /`` before a
    PowerShell ParserError tells it otherwise.
    """
    if not IS_WINDOWS:
        return (
            "POSIX sh via `/bin/sh -c` — not the user's interactive shell, "
            "so no aliases, rc files or zsh/bash-only syntax"
        )
    exe = os.path.basename(WIN_SHELL[0])
    if exe.lower().startswith("pwsh"):
        chaining = "`&&`/`||` work (PowerShell 7+)"
    else:
        chaining = (
            "`&&`/`||` are not statement separators (Windows PowerShell "
            "5.1) — use `;` or separate calls"
        )
    return (
        f"PowerShell on Windows ({exe}). Write PowerShell, not POSIX: no "
        f"`2>/dev/null`, no `ls -la`/`find`/`grep`; {chaining}. Use "
        "`$env:USERPROFILE`, `Get-ChildItem`, `Select-String`."
    )

is_safe_readonly

is_safe_readonly(cmd: str) -> bool

True if cmd is a pure inspection command that's safe to run without asking. Conservative: any unrecognized binary, any chained write op, or any unsafe token returns False so the confirm prompt stays in place.

Source code in src/dashscope_agenticx/tools/shell.py
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
def is_safe_readonly(cmd: str) -> bool:
    """True if ``cmd`` is a pure inspection command that's safe to run
    without asking. Conservative: any unrecognized binary, any chained
    write op, or any unsafe token returns False so the confirm prompt
    stays in place."""
    s = cmd.strip()
    if not s:
        return False
    if "$(" in s or "`" in s:
        return False  # command substitution could hide anything
    # Each pipeline / chain segment must be individually safe. Split on
    # newlines too: `ls\npython3 -c ...` is two commands. Lone `&` is not
    # split on — it would chop `2>&1` apart, and the _UNSAFE_TOKENS /
    # _UNSAFE_FLAGS checks still catch `sleep & rm bar` as a single chunk.
    chunks = re.split(r"\s*(?:\|\||&&|;|\||\n)\s*", s)
    return all(_is_safe_single(c) for c in chunks if c.strip())

run_command async

run_command(
    command: str, timeout: int | None = None
) -> str
Source code in src/dashscope_agenticx/tools/shell.py
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
@tool(
    name="run_command",
    description=(
        "Execute a shell command and return its output. "
        "Dangerous commands are blocked. Pass timeout (seconds) to override "
        f"the {DEFAULT_TIMEOUT}s default for long builds or test runs."
    ),
    permission=PermissionLevel.CONFIRM,
)
async def run_command(command: str, timeout: int | None = None) -> str:
    if not command or not command.strip():
        return (
            "Error: empty command argument; re-invoke with the "
            "command to run"
        )
    for pattern in BLOCKED_PATTERNS:
        if pattern in command:
            return (
                f"Error: command blocked "
                f"(contains dangerous pattern: {pattern})"
            )
    if _RM_ROOT_RE.search(command):
        return "Error: command blocked (contains dangerous pattern: rm -rf /)"
    if _FORMAT_CMD_RE.search(command):
        return "Error: command blocked (contains dangerous pattern: format)"
    for name, regex in _BLOCKED_REGEXES:
        if regex.search(command):
            return (
                f"Error: command blocked "
                f"(contains dangerous pattern: {name})"
            )

    # Belt-and-suspenders on top of utils.validation.coerce_types: if the model
    # still managed to slip something un-castable through (e.g. "auto"),
    # fall back to the default instead of letting asyncio.wait_for raise
    # TypeError on `<= 0`.
    try:
        timeout = int(timeout) if timeout not in (None, "", 0) else 0
    except (TypeError, ValueError):
        timeout = 0
    if timeout <= 0:
        timeout = default_timeout()

    proc = None
    try:
        proc = await _spawn(command)
        stdout, stderr = await asyncio.wait_for(
            proc.communicate(),
            timeout=timeout,
        )
    except asyncio.TimeoutError:
        await _kill_tree(proc)
        return (
            f"Error: command timed out after {timeout}s and was killed. "
            "Pass a larger timeout argument (seconds) if it needs longer; "
            f"the default is {default_timeout()}s."
        )
    except asyncio.CancelledError:
        # Ctrl-C: kill synchronously, because awaiting inside a cancellation
        # handler can be interrupted before the kill lands.
        _signal_tree(proc)
        raise
    except Exception as e:
        await _kill_tree(proc)
        return f"Error: execution failed - {e}"

    # Enforce hard size limits to prevent OOM on huge outputs
    stdout_bytes = len(stdout) if stdout else 0
    stderr_bytes = len(stderr) if stderr else 0
    total_bytes = stdout_bytes + stderr_bytes

    if total_bytes > MAX_OUTPUT_BYTES:
        # Truncate raw bytes before decoding
        if stdout_bytes > MAX_OUTPUT_BYTES // 2:
            stdout = stdout[: MAX_OUTPUT_BYTES // 2]
        if stderr_bytes > MAX_OUTPUT_BYTES // 2:
            stderr = stderr[: MAX_OUTPUT_BYTES // 2]

    output = ""
    if stdout:
        output += _decode_output(stdout)
    if stderr:
        output += "\n[stderr]\n" + _decode_output(stderr)

    if len(output) > MAX_OUTPUT_LENGTH:
        output = (
            output[:MAX_OUTPUT_LENGTH]
            + f"\n\n... (output truncated, {total_bytes} bytes total)"
        )

    exit_info = f"\n[exit code: {proc.returncode}]"
    return (
        output.strip()
        + exit_info
        + (_vision_inject(command) or _vision_tip(command, output))
    )

session

Session/config tools — let the agent switch models, manage capabilities, and connect MCP services on behalf of the user.

register_session_tools

register_session_tools(
    config: Config,
    *,
    get_agent: Callable,
    get_provider_fn: Callable,
    connect_mcp_fn: Callable,
    disconnect_mcp_fn: Callable,
    list_mcp_services_fn: Callable,
    get_mcp_clients_fn: Callable
)

Register tools that let the LLM manage session state.

Called once after agent construction. Uses closures over runtime objects.

Source code in src/dashscope_agenticx/tools/session.py
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
def register_session_tools(
    config: Config,
    *,
    get_agent: Callable,
    get_provider_fn: Callable,
    connect_mcp_fn: Callable,
    disconnect_mcp_fn: Callable,
    list_mcp_services_fn: Callable,
    get_mcp_clients_fn: Callable,
):
    """Register tools that let the LLM manage session state.

    Called once after agent construction. Uses closures over runtime objects.
    """

    # ===== Model / Provider =====

    async def switch_model(model_name: str) -> str:
        agent = get_agent()
        config.model = normalize_model_name(model_name)
        agent.provider = get_provider_fn(
            config.provider,
            config.model,
            config.api_key,
            base_url=config.base_url or None,
        )
        agent.model_name = config.model
        config.save_workspace()
        return f"Switched model: {config.provider}/{config.model}"

    async def switch_provider(provider_name: str) -> str:
        if provider_name not in PROVIDER_MODELS:
            return (
                f"Unknown provider: {provider_name}; "
                f"options: {', '.join(PROVIDER_MODELS)}"
            )
        agent = get_agent()
        config.provider = provider_name
        config.model = PROVIDER_MODELS[provider_name][0]
        agent.provider = get_provider_fn(
            config.provider,
            config.model,
            config.api_key,
            base_url=config.base_url or None,
        )
        agent.provider_name = config.provider
        agent.model_name = config.model
        config.save_global()
        config.save_workspace()
        return f"Switched: {provider_name}/{config.model}"

    async def list_models() -> str:
        lines = []
        for provider, models in PROVIDER_MODELS.items():
            marker = " ← current" if provider == config.provider else ""
            lines.append(f"{provider}{marker}: {', '.join(models)}")
        return "\n".join(lines)

    registry.register(
        ToolDefinition(
            name="switch_model",
            description=(
                "Switch the current AI model "
                "(e.g. qwen-plus, claude-sonnet-4-20250514)"
            ),
            permission=PermissionLevel.AUTO,
            func=switch_model,
            parameters={
                "type": "object",
                "properties": {
                    "model_name": {
                        "type": "string",
                        "description": "Model name",
                    },
                },
                "required": ["model_name"],
            },
        ),
    )
    registry.register(
        ToolDefinition(
            name="switch_provider",
            description=f"Switch AI provider ({'/'.join(PROVIDER_MODELS)})",
            permission=PermissionLevel.AUTO,
            func=switch_provider,
            parameters={
                "type": "object",
                "properties": {
                    "provider_name": {
                        "type": "string",
                        "description": "Provider name",
                    },
                },
                "required": ["provider_name"],
            },
        ),
    )
    registry.register_mcp_tool(
        name="list_models",
        description="List all available AI models and providers",
        parameters={"type": "object", "properties": {}},
        call_fn=list_models,
    )

    # ===== Capability =====

    async def capability_list() -> str:
        from dashscope_agenticx.tools.platform import all_capability_keys

        all_keys = all_capability_keys()
        enabled = (
            set(config.enabled_capabilities)
            if config.enabled_capabilities is not None
            else set(all_keys)
        )
        lines = []
        for k in all_keys:
            status = "✓ enabled" if k in enabled else "✗ disabled"
            lines.append(f"  {k} — {status}")
        return "Capabilities:\n" + "\n".join(lines)

    async def capability_enable(key: str) -> str:
        from dashscope_agenticx.tools.platform import (
            _is_cloud_capability,
            all_capability_keys,
            register_one_capability,
        )

        all_keys = all_capability_keys()
        if key not in all_keys:
            return (
                f"Unknown capability: {key}; "
                f"options: {', '.join(all_keys)}"
            )
        if config.privacy_mode and _is_cloud_capability(key):
            return (
                f"Privacy mode is on; cannot enable cloud capability "
                f"{key}. Run /privacy off first to use it."
            )
        enabled = (
            set(config.enabled_capabilities)
            if config.enabled_capabilities is not None
            else set(all_keys)
        )
        if key in enabled:
            return f"{key} is already enabled"
        enabled.add(key)
        config.enabled_capabilities = sorted(enabled)
        config.save_workspace()
        count = register_one_capability(config, key, connect_mcp_fn)
        if count == 0:
            return (
                f"Enabled {key} but registered 0 tools — credentials "
                f"or runtime requirements are likely missing (e.g. bl "
                f"not in PATH). The agent cannot add credentials "
                f"interactively; tell the user to run "
                f"/capability enable {key} to finish setup."
            )
        return f"Enabled {key} (registered {count} tools)"

    async def capability_disable(key: str) -> str:
        from dashscope_agenticx.tools.platform import (
            all_capability_keys,
            unregister_capability_tools,
        )

        all_keys = all_capability_keys()
        if key not in all_keys:
            return (
                f"Unknown capability: {key}; "
                f"options: {', '.join(all_keys)}"
            )
        enabled = (
            set(config.enabled_capabilities)
            if config.enabled_capabilities is not None
            else set(all_keys)
        )
        if key not in enabled:
            return f"{key} is already disabled"
        enabled.discard(key)
        config.enabled_capabilities = sorted(enabled)
        config.save_workspace()
        unregister_capability_tools(key)
        return f"Disabled {key}"

    registry.register_mcp_tool(
        name="capability_list",
        description="List all capabilities and their enabled status",
        parameters={"type": "object", "properties": {}},
        call_fn=capability_list,
    )
    registry.register(
        ToolDefinition(
            name="capability_enable",
            description=(
                "Enable a cloud capability "
                "(e.g. knowledge base, web search, MCP)"
            ),
            permission=PermissionLevel.CONFIRM,
            func=capability_enable,
            parameters={
                "type": "object",
                "properties": {
                    "key": {
                        "type": "string",
                        "description": (
                            "Capability key, e.g. bailian.mcp, bailian.cli"
                        ),
                    },
                },
                "required": ["key"],
            },
        ),
    )
    registry.register(
        ToolDefinition(
            name="capability_disable",
            description="Disable a cloud capability",
            permission=PermissionLevel.CONFIRM,
            func=capability_disable,
            parameters={
                "type": "object",
                "properties": {
                    "key": {
                        "type": "string",
                        "description": "Capability key",
                    },
                },
                "required": ["key"],
            },
        ),
    )

    # ===== MCP =====

    async def mcp_list_services() -> str:
        return list_mcp_services_fn()

    async def mcp_connect(service: str) -> str:
        clients = get_mcp_clients_fn()
        if service in clients:
            return (
                f"{service} already connected "
                f"({len(clients[service].tools)} tools)"
            )
        error = await connect_mcp_fn(service, config)
        if error:
            return f"Failed to connect {service}: {error}"
        clients = get_mcp_clients_fn()
        client = clients.get(service)
        tool_count = len(client.tools) if client else 0
        from dashscope_agenticx.config import MCPServerConfig

        if not any(m.service == service for m in config.mcp_servers):
            config.mcp_servers.append(MCPServerConfig(service=service))
            config.save_workspace()
        return f"Connected {service}; found {tool_count} tools"

    async def mcp_disconnect(service: str) -> str:
        clients = get_mcp_clients_fn()
        if service not in clients:
            return f"{service} is not connected"
        await disconnect_mcp_fn(service)
        config.mcp_servers = [
            m for m in config.mcp_servers if m.service != service
        ]
        config.save_workspace()
        return f"Disconnected {service}"

    if not config.privacy_mode:
        registry.register_mcp_tool(
            name="mcp_list_services",
            description=(
                "List available MCP cloud services "
                "(time, code execution, doc parsing, etc.)"
            ),
            parameters={"type": "object", "properties": {}},
            call_fn=mcp_list_services,
        )
        registry.register(
            ToolDefinition(
                name="mcp_connect",
                description=(
                    "Connect an MCP cloud service "
                    "(its tools become available once connected)"
                ),
                permission=PermissionLevel.CONFIRM,
                func=mcp_connect,
                parameters={
                    "type": "object",
                    "properties": {
                        "service": {
                            "type": "string",
                            "description": (
                                "Service name, e.g. time, "
                                "code-interpreter, doc-analysis"
                            ),
                        },
                    },
                    "required": ["service"],
                },
            ),
        )
        registry.register(
            ToolDefinition(
                name="mcp_disconnect",
                description="Disconnect an MCP cloud service",
                permission=PermissionLevel.CONFIRM,
                func=mcp_disconnect,
                parameters={
                    "type": "object",
                    "properties": {
                        "service": {
                            "type": "string",
                            "description": "Service name",
                        },
                    },
                    "required": ["service"],
                },
            ),
        )

    register_plan_tools(get_agent=get_agent)

register_plan_tools

register_plan_tools(*, get_agent: Callable)

Bind plan operations to the executing Agent's session tier.

Source code in src/dashscope_agenticx/tools/session.py
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
def register_plan_tools(*, get_agent: Callable):
    """Bind plan operations to the executing Agent's session tier."""

    async def create_plan(goal: str, steps: list[str]) -> str:
        """Create a multi-step execution plan for complex tasks."""
        return get_agent().memory_manager.session.plan.create_plan(goal, steps)

    async def complete_step(step_index: int) -> str:
        """Mark a plan step as completed."""
        tracker = get_agent().memory_manager.session.plan
        tracker.mark_step_complete(step_index)
        if tracker.is_complete():
            tracker.clear_plan()
            return "All steps completed"
        return f"Step {step_index + 1} completed"

    async def get_plan_status() -> str:
        """Get current plan progress."""
        section = get_agent().memory_manager.session.plan.get_plan_section()
        return section if section else "No plan in progress"

    registry.register(
        ToolDefinition(
            name="create_plan",
            description=(
                "Create a multi-step execution plan for complex "
                "tasks (e.g. refactors, designs, new features)."
            ),
            permission=PermissionLevel.AUTO,
            func=create_plan,
            parameters={
                "type": "object",
                "properties": {
                    "goal": {
                        "type": "string",
                        "description": "Overall goal of the plan",
                    },
                    "steps": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": "List of step descriptions",
                    },
                },
                "required": ["goal", "steps"],
            },
        ),
    )
    registry.register(
        ToolDefinition(
            name="complete_step",
            description="Mark a plan step as completed",
            permission=PermissionLevel.AUTO,
            func=complete_step,
            parameters={
                "type": "object",
                "properties": {
                    "step_index": {
                        "type": "integer",
                        "description": "Step index (0-based)",
                    },
                },
                "required": ["step_index"],
            },
        ),
    )
    registry.register(
        ToolDefinition(
            name="get_plan_status",
            description="Get progress of the current plan",
            permission=PermissionLevel.AUTO,
            func=get_plan_status,
            parameters={"type": "object", "properties": {}},
        ),
    )

checkpoint

File checkpoint/undo support for mutating file tools.

Backups live under <workspace>/.agenticx/checkpoints/ next to a JSONL index. snapshot() records the pre-mutation state of a file and undo() reverses the most recent recorded mutation.

console module-attribute

console = Console()

snapshot

snapshot(path: str, action: str) -> None

Record a pre-mutation checkpoint for path.

action is one of "overwrite", "create" or "delete". Never raises: a checkpoint failure must not break the write tool.

Source code in src/dashscope_agenticx/tools/checkpoint.py
102
103
104
105
106
107
108
109
110
111
112
def snapshot(path: str, action: str) -> None:
    """Record a pre-mutation checkpoint for *path*.

    *action* is one of ``"overwrite"``, ``"create"`` or ``"delete"``.
    Never raises: a checkpoint failure must not break the write tool.
    """
    try:
        _snapshot(path, action)
    except Exception:
        # Checkpointing is best-effort; skip silently on any error.
        pass

undo

undo() -> str

Undo the most recent checkpointed file mutation.

Returns a human-readable result string; never raises.

Source code in src/dashscope_agenticx/tools/checkpoint.py
153
154
155
156
157
158
159
160
161
def undo() -> str:
    """Undo the most recent checkpointed file mutation.

    Returns a human-readable result string; never raises.
    """
    try:
        return _undo()
    except Exception as e:
        return f"Error: undo failed - {e}"

handle_undo_command

handle_undo_command() -> None

CLI-facing wrapper: undo the last change and print the result.

Source code in src/dashscope_agenticx/tools/checkpoint.py
218
219
220
def handle_undo_command() -> None:
    """CLI-facing wrapper: undo the last change and print the result."""
    console.print(undo())

skills

Model-invocable skill tool: expand a .md skill template into instructions.

register_skill_tools

register_skill_tools(get_agent: Callable) -> None

Register use_skill for .agenticx/skills/*.md templates.

Called once after agent construction, alongside register_evolution_tools.

Source code in src/dashscope_agenticx/tools/skills.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
def register_skill_tools(get_agent: Callable) -> None:
    """Register use_skill for .agenticx/skills/*.md templates.

    Called once after agent construction, alongside register_evolution_tools.
    """

    @registry.register(
        Tool(
            name="use_skill",
            description=(
                "Invoke a skill prompt template (configured in "
                ".agenticx/skills/*.md, catalog in the system prompt's "
                "skill "
                "list); returns expanded instructions to follow strictly."
            ),
            parameters={
                "type": "object",
                "properties": {
                    "name": {
                        "type": "string",
                        "description": (
                            "Skill name (e.g. explain-code, translate)"
                        ),
                    },
                    "args": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": (
                            "Positional args in template arguments order"
                        ),
                    },
                },
                "required": ["name"],
            },
        ),
    )
    async def use_skill(name: str, args: list[str] | None = None) -> str:
        from dashscope_agenticx.skills.base import (
            BUILTIN_SKILLS,
            load_skill_files,
            render_skill,
        )

        load_skill_files()
        skill = BUILTIN_SKILLS.get(name)
        if not skill:
            return (
                f"Error: unknown skill '{name}'. "
                "See the skill list in the system prompt."
            )
        if skill.mcp_service:
            from dashscope_agenticx.cli.mcp import _mcp_clients

            if skill.mcp_service not in _mcp_clients:
                return (
                    f"Error: skill '{name}' requires MCP service "
                    f"{skill.mcp_service}; ask the user to connect first."
                )
        rendered = render_skill(skill, [str(a) for a in (args or [])])
        # `is None`, not falsy: render_skill only returns None when arguments
        # are missing, so the hint below always lists at least one name. An
        # empty body is a valid (if useless) skill, not a missing argument.
        if rendered is None:
            hint = " ".join(f"<{a}>" for a in skill.arguments)
            return f"Error: missing args. '{name}' requires: {hint}"
        agent = get_agent()
        if agent is not None:
            agent.turn_skills += 1
            agent.executor.record_skills([name])
        return rendered

platform

current_capability_tools

current_capability_tools() -> dict[str, set[str]]

Return capability registrations for the current Runtime context.

Source code in src/dashscope_agenticx/tools/platform.py
29
30
31
32
def current_capability_tools() -> dict[str, set[str]]:
    """Return capability registrations for the current Runtime context."""
    bound = _capability_tools_ctx.get()
    return _default_capability_tools if bound is None else bound

bind_capability_tools

bind_capability_tools(tracker: dict[str, set[str]])

Bind capability registration bookkeeping to one Runtime.

Source code in src/dashscope_agenticx/tools/platform.py
35
36
37
38
39
40
41
42
@contextlib.contextmanager
def bind_capability_tools(tracker: dict[str, set[str]]):
    """Bind capability registration bookkeeping to one Runtime."""
    token = _capability_tools_ctx.set(tracker)
    try:
        yield tracker
    finally:
        _capability_tools_ctx.reset(token)

disabled_capabilities_hint

disabled_capabilities_hint(config: Config) -> str

Build the system-prompt section that lists explicitly-disabled capabilities. None or empty = no disabled hints.

Source code in src/dashscope_agenticx/tools/platform.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
def disabled_capabilities_hint(config: Config) -> str:
    """Build the system-prompt section that lists explicitly-disabled
    capabilities. None or empty = no disabled hints.
    """
    caps = config.enabled_capabilities
    if not caps:
        return ""
    disabled = [
        k
        for k in _CAPABILITY_KEYS
        if k not in caps and k in _DISABLED_CAPABILITY_HINTS
    ]
    if not disabled:
        return ""
    lines = [
        "\n\n## Disabled capabilities (user turned these off; "
        "strictly respect this — do not work around them)",
    ]
    for k in disabled:
        lines.append(f"- **{k}**: {_DISABLED_CAPABILITY_HINTS[k]}")
    return "\n".join(lines)

all_capability_keys

all_capability_keys() -> list[str]

Built-in capability keys plus anything declared in custom-extensions.toml. Used by register_platform_tools and surfaced to /capability.

Source code in src/dashscope_agenticx/tools/platform.py
118
119
120
121
122
123
124
def all_capability_keys() -> list[str]:
    """Built-in capability keys plus anything declared in
    custom-extensions.toml. Used by register_platform_tools and surfaced
    to /capability."""
    from dashscope_agenticx.extensions import current as _ext_current

    return _CAPABILITY_KEYS + [c.key for c in _ext_current().capabilities]

register_platform_tools

register_platform_tools(
    config: Config, connect_mcp_fn: Callable | None = None
)
Source code in src/dashscope_agenticx/tools/platform.py
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
def register_platform_tools(
    config: Config,
    connect_mcp_fn: Callable | None = None,
):
    if config.privacy_mode:
        # Registration is process-global. A previous non-private Agent may have
        # left cloud/MCP tools in the registry, so merely skipping new
        # registration is insufficient for SDKs that create multiple Agents.
        unregister_cloud_capability_tools()
        for name in [t.name for t in registry.list_tools()]:
            if name.startswith(("mcp_", "bailian_")):
                registry.unregister(name)

    caps = config.enabled_capabilities
    all_enabled = caps is None
    for cap_key in all_capability_keys():
        if config.privacy_mode and _is_cloud_capability(cap_key):
            # privacy mode: cloud capabilities never reach the tool surface
            continue
        if all_enabled or cap_key in (caps or []):
            register_one_capability(config, cap_key, connect_mcp_fn)

register_one_capability

register_one_capability(
    config: Config,
    cap_key: str,
    connect_mcp_fn: Callable | None = None,
) -> int

Register a single capability's tools, tracking new names for later unregister. Returns the count of tools added (0 when creds are missing or the capability key is unknown — silent so the caller can treat it as best-effort).

Source code in src/dashscope_agenticx/tools/platform.py
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
def register_one_capability(
    config: Config,
    cap_key: str,
    connect_mcp_fn: Callable | None = None,
) -> int:
    """Register a single capability's tools, tracking new names for later
    unregister. Returns the count of tools added (0 when creds are missing
    or the capability key is unknown — silent so the caller can treat it
    as best-effort)."""
    before = {t.name for t in registry.list_tools()}

    if cap_key == "bailian.mcp":
        if config.api_key and connect_mcp_fn:
            _register_mcp_tools(config, connect_mcp_fn)
    elif cap_key == "bailian.cli":
        if cli_client := get_cli_provider(config):
            _register_bailian_cli_tools(cli_client)
    elif cap_key == "local.subagent":
        from dashscope_agenticx.agents.subagent import (
            _has_parent,
            register_subagent_tool,
        )

        if _has_parent():
            register_subagent_tool()
        # else: parent agent not constructed yet; register_platform_tools
        # was called too early — cli.py wires _set_parent_agent + a final
        # re-register pass after Agent construction.
    elif cap_key == "local.delegate":
        from dashscope_agenticx.agents.delegate import (
            _has_parent,
            register_delegate_tools,
        )

        if _has_parent():
            register_delegate_tools()
    elif cap_key == "local.memory":
        _register_local_memory_tools(config)
    else:
        # Fall through to extension capabilities (custom-extensions.toml).
        # The cap_key is checked against load_extensions() output; if
        # found, its tools are wired via the HTTP-tool factory.
        if not _register_extension_capability(cap_key, config):
            return 0

    after = {t.name for t in registry.list_tools()}
    new_names = after - before
    current_capability_tools().setdefault(cap_key, set()).update(new_names)
    return len(new_names)

unregister_capability_tools

unregister_capability_tools(cap_key: str) -> int

Drop all tools previously registered under cap_key. Returns the count of tools removed.

Note: for bailian.mcp this removes the mcp_connect dispatcher and any mcp__* tools that were registered through it. Active MCPClient instances are left running — they're held by cli._mcp_clients, which only the slash-command handler touches; here we just clear the visible tool surface. Re-enable + /mcp services would re-register cleanly.

Source code in src/dashscope_agenticx/tools/platform.py
356
357
358
359
360
361
362
363
364
365
366
367
368
def unregister_capability_tools(cap_key: str) -> int:
    """Drop all tools previously registered under cap_key. Returns the
    count of tools removed.

    Note: for bailian.mcp this removes the mcp_connect dispatcher and any
    mcp_<service>_* tools that were registered through it. Active MCPClient
    instances are left running — they're held by cli._mcp_clients, which
    only the slash-command handler touches; here we just clear the visible
    tool surface. Re-enable + /mcp services would re-register cleanly."""
    names = current_capability_tools().pop(cap_key, set())
    for name in names:
        registry.unregister(name)
    return len(names)

capability_tool_names

capability_tool_names() -> set[str]

All tool names currently registered under any capability. Consumed by ToolRegistry.to_schema_list: registration is the capability gate, so any tool present here must be exposed to the model (extension HTTP/vision tools and bailian_* wrappers would otherwise be invisible).

Source code in src/dashscope_agenticx/tools/platform.py
371
372
373
374
375
376
377
378
379
def capability_tool_names() -> set[str]:
    """All tool names currently registered under any capability. Consumed by
    ToolRegistry.to_schema_list: registration is the capability gate, so any
    tool present here must be exposed to the model (extension HTTP/vision
    tools and bailian_* wrappers would otherwise be invisible)."""
    names: set[str] = set()
    for tool_names in current_capability_tools().values():
        names |= tool_names
    return names

unregister_cloud_capability_tools

unregister_cloud_capability_tools() -> int

Privacy mode on: drop every registered cloud capability tool (bailian.*, extension HTTP/vision tools). Returns total tools removed.

Source code in src/dashscope_agenticx/tools/platform.py
388
389
390
391
392
393
394
395
396
def unregister_cloud_capability_tools() -> int:
    """Privacy mode on: drop every registered cloud capability tool (bailian.*,
    extension HTTP/vision tools). Returns total tools removed."""
    removed = 0
    for cap_key in [
        k for k in list(current_capability_tools()) if _is_cloud_capability(k)
    ]:
        removed += unregister_capability_tools(cap_key)
    return removed

refresh_extension_capability_tools

refresh_extension_capability_tools(config: Config) -> int

Re-register all enabled extension capabilities so their tool closures rebind to the latest custom-extensions.toml definitions (endpoint, auth, token). Called by /capability reload and /dev hot reload — without it, edited configs keep running through stale closures until restart. Returns total tools re-registered.

Source code in src/dashscope_agenticx/tools/platform.py
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
def refresh_extension_capability_tools(config: Config) -> int:
    """Re-register all enabled extension capabilities so their tool closures
    rebind to the latest custom-extensions.toml definitions (endpoint, auth,
    token). Called by /capability reload and /dev hot reload — without it,
    edited configs keep running through stale closures until restart.
    Returns total tools re-registered."""
    from dashscope_agenticx.extensions import current as _ext_current

    ext_keys = {c.key for c in _ext_current().capabilities}
    if config.enabled_capabilities is None:
        targets = sorted(ext_keys)
    else:
        targets = sorted(ext_keys & set(config.enabled_capabilities))
    if config.privacy_mode:
        targets = [k for k in targets if not _is_cloud_capability(k)]
    total = 0
    for key in targets:
        unregister_capability_tools(key)
        total += register_one_capability(config, key)
    return total

可选工具需要安装扩展;其模块采用惰性导入,因此在核心安装下浏览下方 参考也是安全的:

模块 扩展
tools.web_search dashscope-agenticx[web]
tools.browser dashscope-agenticx[browser]
tools.camera, tools.vision dashscope-agenticx[media]

Web search tool — DuckDuckGo-based web search.

Uses the duckduckgo-search package (DDGS) as a free, keyless search backend. Complements the browser tools (scrape_web, scrape_web_html) which handle page content extraction. Together they form a complete web acquisition pipeline: web_search → find relevant URLs scrape_web → extract content from those URLs

Security: - Query length limits to prevent abuse - Result count limits to avoid overwhelming context windows - Lazy import of duckduckgo_search to keep startup fast

web_search(
    query: str, max_results: int = 10, region: str = "wt-wt"
) -> str

Search the web using DuckDuckGo and return structured results.

Parameters:

Name Type Description Default
query str

search keywords, e.g. 'Python asyncio tutorial' or 'Rust ownership explained'

required
max_results int

number of results to return, default 10, max 30

10
region str

region code, e.g. 'cn-zh' (Chinese), 'us-en' (English), 'wt-wt' (global, default)

'wt-wt'
Source code in src/dashscope_agenticx/tools/web_search.py
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
@tool(
    name="web_search",
    description=(
        "Search the web with DuckDuckGo. Returns a JSON list of titles, "
        "URLs, and snippets. Good for finding up-to-date info, docs, and "
        "tutorials. Use scrape_web afterwards to fetch full page content."
    ),
    permission=PermissionLevel.AUTO,
)
async def web_search(
    query: str,
    max_results: int = 10,
    region: str = "wt-wt",
) -> str:
    """Search the web using DuckDuckGo and return structured results.

    Args:
        query: search keywords, e.g. 'Python asyncio tutorial'
            or 'Rust ownership explained'
        max_results: number of results to return, default 10, max 30
        region: region code, e.g. 'cn-zh' (Chinese), 'us-en' (English),
            'wt-wt' (global, default)
    """
    query = _validate_query(query)
    max_results = _validate_max_results(max_results)
    region = _validate_region(region)

    DDGS = _get_ddgs_class()

    try:
        with DDGS() as ddgs:
            results = list(
                ddgs.text(
                    query,
                    region=region,
                    max_results=max_results,
                ),
            )
    except ImportError as e:
        return str(e)
    except Exception as e:
        return json.dumps(
            {
                "query": query,
                "error": f"Search failed: {type(e).__name__}: {e}",
                "results": [],
            },
            ensure_ascii=False,
        )

    return _format_results(results, query)

browser

Browser tools — Playwright-based web scraping for JS-rendered pages.

Security hardening: - URL scheme validation (http/https only) - SSRF protection against private/internal IPs (DNS-level + route-level anti-rebinding interception) - Screenshot path traversal prevention - CSS selector sanitisation - Output bounded by text truncation in each tool

Performance hardening: - Browser instance reuse within a session (thread-safe) - atexit cleanup to avoid zombie chromium processes

scrape_web async

scrape_web(
    url: str, wait_selector: str = "", timeout: int = 30000
) -> str

Scrape a web page using Playwright headless browser.

Parameters:

Name Type Description Default
url str

The URL to scrape (http/https only).

required
wait_selector str

Optional CSS selector to wait for before extracting content.

''
timeout int

Max wait time in milliseconds (default 30s, max 120s).

30000
Source code in src/dashscope_agenticx/tools/browser.py
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
@tool(
    name="scrape_web",
    description=(
        "Scrape web page content with a Playwright headless browser "
        "(supports JS-rendered SPA pages). Returns the page's plain "
        "text. Optional wait selector, timeout, etc."
    ),
    permission=PermissionLevel.AUTO,
)
async def scrape_web(
    url: str,
    wait_selector: str = "",
    timeout: int = 30000,
) -> str:
    """Scrape a web page using Playwright headless browser.

    Args:
        url: The URL to scrape (http/https only).
        wait_selector: Optional CSS selector to wait for before extracting
            content.
        timeout: Max wait time in milliseconds (default 30s, max 120s).
    """
    try:
        _validate_url(url)
        wait_selector = _validate_selector(wait_selector)
    except ValueError as e:
        return f"Error: {e}"

    try:
        async with _launch_page(timeout=timeout) as page:
            await _navigate_and_wait(page, url, wait_selector, timeout)
            content = await page.inner_text("body")
            title = await page.title() or ""
    except ImportError as e:
        return str(e)
    except Exception as e:
        return f"Error: web scraping failed — {e}"

    # Clean up excessive whitespace
    lines = [line.strip() for line in content.splitlines() if line.strip()]
    text = "\n".join(lines)

    max_len = 50_000
    if len(text) > max_len:
        text = text[:max_len] + "\n...(content truncated)"

    result = ""
    if title:
        result += f"# {title}\n\n"
    result += f"URL: {url}\n\n{text}"
    return result

scrape_web_html async

scrape_web_html(
    url: str, wait_selector: str = "", timeout: int = 30000
) -> str

Scrape a web page and return the rendered HTML source.

Parameters:

Name Type Description Default
url str

The URL to scrape (http/https only).

required
wait_selector str

Optional CSS selector to wait for before extracting HTML.

''
timeout int

Max wait time in milliseconds (default 30s, max 120s).

30000
Source code in src/dashscope_agenticx/tools/browser.py
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
@tool(
    name="scrape_web_html",
    description=(
        "Scrape a web page's HTML source with a Playwright headless "
        "browser (supports JS-rendered pages). Returns the fully "
        "rendered HTML."
    ),
    permission=PermissionLevel.AUTO,
)
async def scrape_web_html(
    url: str,
    wait_selector: str = "",
    timeout: int = 30000,
) -> str:
    """Scrape a web page and return the rendered HTML source.

    Args:
        url: The URL to scrape (http/https only).
        wait_selector: Optional CSS selector to wait for before extracting
            HTML.
        timeout: Max wait time in milliseconds (default 30s, max 120s).
    """
    try:
        _validate_url(url)
        wait_selector = _validate_selector(wait_selector)
    except ValueError as e:
        return f"Error: {e}"

    try:
        async with _launch_page(timeout=timeout) as page:
            await _navigate_and_wait(page, url, wait_selector, timeout)
            html = await page.content()
    except ImportError as e:
        return str(e)
    except Exception as e:
        return f"Error: web scraping failed — {e}"

    max_len = 80_000
    if len(html) > max_len:
        html = html[:max_len] + "\n...(HTML truncated)"
    return html

scrape_web_screenshot async

scrape_web_screenshot(
    url: str,
    output_path: str = "screenshot.png",
    full_page: bool = True,
    wait_selector: str = "",
    timeout: int = 30000,
) -> str

Take a screenshot of a web page using Playwright headless browser.

Parameters:

Name Type Description Default
url str

The URL to screenshot (http/https only).

required
output_path str

Where to save the screenshot image (must be within current directory).

'screenshot.png'
full_page bool

If True, capture the full scrollable page.

True
wait_selector str

Optional CSS selector to wait for before capturing.

''
timeout int

Max wait time in milliseconds (default 30s, max 120s).

30000
Source code in src/dashscope_agenticx/tools/browser.py
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
@tool(
    name="scrape_web_screenshot",
    description=(
        "Take a screenshot of a web page with a Playwright headless "
        "browser and save it as an image file. Useful for inspecting "
        "visual layout."
    ),
    permission=PermissionLevel.AUTO,
)
async def scrape_web_screenshot(
    url: str,
    output_path: str = "screenshot.png",
    full_page: bool = True,
    wait_selector: str = "",
    timeout: int = 30000,
) -> str:
    """Take a screenshot of a web page using Playwright headless browser.

    Args:
        url: The URL to screenshot (http/https only).
        output_path: Where to save the screenshot image (must be within
            current directory).
        full_page: If True, capture the full scrollable page.
        wait_selector: Optional CSS selector to wait for before capturing.
        timeout: Max wait time in milliseconds (default 30s, max 120s).
    """
    try:
        _validate_url(url)
        wait_selector = _validate_selector(wait_selector)
        output_path = _validate_screenshot_path(output_path)
    except ValueError as e:
        return f"Error: {e}"

    try:
        async with _launch_page(
            timeout=timeout,
            viewport={"width": 1280, "height": 720},
        ) as page:
            await _navigate_and_wait(page, url, wait_selector, timeout)
            await page.screenshot(path=output_path, full_page=full_page)
    except ImportError as e:
        return str(e)
    except Exception as e:
        return f"Error: screenshot failed — {e}"

    return (
        f"Screenshot saved to {output_path}. Call the view_image tool "
        f"with this path to analyze it (the user can also attach it "
        f"via @path)."
    )

camera

Camera tools — allows the LLM to capture photos and record video from the webcam.

camera_capture

camera_capture(path: str = 'camera_capture.jpg') -> str
Source code in src/dashscope_agenticx/tools/camera.py
10
11
12
13
14
15
16
17
18
19
20
21
22
@tool(
    name="camera_capture",
    description=(
        "Take a photo with the webcam and save it to the given path. "
        "The photo can then be analyzed with the view_image tool (the "
        "user can also attach it via @path)."
    ),
    permission=PermissionLevel.CONFIRM,
)
def camera_capture(path: str = "camera_capture.jpg") -> str:
    from dashscope_agenticx.ui.camera import capture

    return capture(path)

camera_record

camera_record(
    path: str = "camera_record.mp4", duration: float = 5.0
) -> str
Source code in src/dashscope_agenticx/tools/camera.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
@tool(
    name="camera_record",
    description=(
        "Record a video clip with the webcam and save it to the given "
        "path. The recording duration (seconds) can be specified."
    ),
    permission=PermissionLevel.CONFIRM,
)
def camera_record(
    path: str = "camera_record.mp4",
    duration: float = 5.0,
) -> str:
    from dashscope_agenticx.ui.camera import record

    return record(path, duration)

vision

Built-in vision tool — let the agent analyze local images itself.

Previously the only multimodal entry point was user-input @path expansion, so after scrape_web_screenshot / camera_capture the model could not see the saved image and sometimes echoed the user-facing @path hint verbatim, ending the turn prematurely. view_image closes that gap by routing the image to a vision-capable model on the active provider.

Very tall/wide images (e.g. a long announcement table) get downscaled or truncated by vision-model backends until text is illegible, so view_image auto-slices them with Pillow (when installed) and runs one vision call per slice. Without Pillow it falls back to sending the whole image as-is.

auto_perceive is the read_file hook: nine bench runs (071c–071i) showed the model reads an image as text exactly once, receives the "call view_image / tesseract" redirect, and goes back to pixel scripting within seconds — advice is ignorable, delivered perception is not. When read_file hits a binary image it calls auto_perceive, which runs the same vision pipeline inline and injects the result, falling back to the text redirect whenever perception is unavailable.

view_image_call_count

view_image_call_count() -> int
Source code in src/dashscope_agenticx/tools/vision.py
109
110
def view_image_call_count() -> int:
    return _view_image_calls

auto_perceive_count

auto_perceive_count() -> int
Source code in src/dashscope_agenticx/tools/vision.py
131
132
def auto_perceive_count() -> int:
    return _auto_perceive_attempts

pick_vision_model

pick_vision_model(config: Config) -> str

Choose a vision-capable model on the active provider.

Preference: the active model when it accepts images, then the first vision model declared on the provider's extension block, then a per-provider built-in fallback.

Source code in src/dashscope_agenticx/tools/vision.py
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
def pick_vision_model(config: Config) -> str:
    """Choose a vision-capable model on the active provider.

    Preference: the active model when it accepts images, then the first
    vision model declared on the provider's extension block, then a
    per-provider built-in fallback.
    """
    if is_vision_model(config.model):
        return config.model

    from dashscope_agenticx.extensions import find_provider

    ext = find_provider(config.provider)
    if ext and ext.vision_models:
        return ext.vision_models[0]
    return _FALLBACK_VISION_MODELS.get(config.provider, "qwen3-vl-plus")

plan_slices

plan_slices(width: int, height: int)

Return crop boxes for an oversized image, or None if it fits.

Slices run along the long axis with a small overlap so rows cut at a box boundary still appear complete in one of the two neighbors.

Source code in src/dashscope_agenticx/tools/vision.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
def plan_slices(width: int, height: int):
    """Return crop boxes for an oversized image, or None if it fits.

    Slices run along the long axis with a small overlap so rows cut at
    a box boundary still appear complete in one of the two neighbors.
    """
    long_side = max(width, height)
    short_side = max(min(width, height), 1)
    if (
        long_side <= _SLICE_MAX_LONG_SIDE
        and long_side / short_side <= _SLICE_MAX_RATIO
    ):
        return None

    step = _SLICE_STEP
    overlap = _SLICE_OVERLAP
    count = math.ceil((long_side - overlap) / (step - overlap))
    if count > _SLICE_MAX_COUNT:
        # Re-derive a coarser step; drop the overlap so the cap holds.
        step = math.ceil(long_side / _SLICE_MAX_COUNT)
        overlap = 0

    boxes = []
    if height >= width:
        y = 0
        while y < height:
            y2 = min(y + step, height)
            boxes.append((0, y, width, y2))
            if y2 == height:
                break
            y = y2 - overlap
    else:
        x = 0
        while x < width:
            x2 = min(x + step, width)
            boxes.append((x, 0, x2, height))
            if x2 == width:
                break
            x = x2 - overlap
    return boxes

parse_region

parse_region(region: str, width: int, height: int) -> tuple

Parse x0,y0,x1,y1 fractions into a pixel crop box.

Fractions keep the parameter resolution-independent: the model can ask for "the top-left ninth" as 0,0,0.333,0.333 without knowing the image size. Pixels would invite off-by-one hallucinations.

Source code in src/dashscope_agenticx/tools/vision.py
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
def parse_region(region: str, width: int, height: int) -> tuple:
    """Parse ``x0,y0,x1,y1`` fractions into a pixel crop box.

    Fractions keep the parameter resolution-independent: the model can
    ask for "the top-left ninth" as 0,0,0.333,0.333 without knowing the
    image size. Pixels would invite off-by-one hallucinations.
    """
    parts = [p.strip() for p in region.split(",")]
    if len(parts) != 4:
        raise ValueError(
            f'expected "x0,y0,x1,y1" (4 comma-separated fractions), '
            f"got {region!r}",
        )
    try:
        x0, y0, x1, y1 = (float(p) for p in parts)
    except ValueError:
        raise ValueError(
            f"region values must be numbers, got {region!r}",
        ) from None
    if not (0 <= x0 < x1 <= 1 and 0 <= y0 < y1 <= 1):
        raise ValueError(
            f"region must satisfy 0<=x0<x1<=1 and 0<=y0<y1<=1, got {region!r}",
        )
    return (
        int(x0 * width),
        int(y0 * height),
        max(int(x1 * width), int(x0 * width) + 1),
        max(int(y1 * height), int(y0 * height) + 1),
    )

perception_available

perception_available() -> bool

Whether an agent has registered a perception context.

Source code in src/dashscope_agenticx/tools/vision.py
480
481
482
def perception_available() -> bool:
    """Whether an agent has registered a perception context."""
    return _PERCEPTION_CTX is not None

auto_perceive

auto_perceive(
    safe_path: str, *, via: str = "read_file"
) -> str | None

Perceive an image inline and return the read, or None.

Called by read_file (an image opened as text) and by run_command (a command referencing an image). safe_path must already exist. Returns None — caller then falls back to its text hint — when the hook is disabled (AGENTICX_AUTO_VISION=0), unconfigured (no agent registered a perception context), this same image was already perceived once (the content is in context; repeats just burn latency), out of budget (AGENTICX_AUTO_VISION_MAX successful+failed attempts per process), or the pipeline itself raises.

The agent loop runs sync tools inline on the event-loop thread, so the async pipeline runs on a helper thread with its own loop — the same blocking shape run_command already has.

Source code in src/dashscope_agenticx/tools/vision.py
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
def auto_perceive(safe_path: str, *, via: str = "read_file") -> str | None:
    """Perceive an image inline and return the read, or None.

    Called by read_file (an image opened as text) and by run_command (a
    command referencing an image). ``safe_path`` must already exist.
    Returns None — caller then falls back to its text hint — when the
    hook is disabled (AGENTICX_AUTO_VISION=0), unconfigured (no agent
    registered a perception context), this same image was already
    perceived once (the content is in context; repeats just burn
    latency), out of budget (AGENTICX_AUTO_VISION_MAX successful+failed
    attempts per process), or the pipeline itself raises.

    The agent loop runs sync tools inline on the event-loop thread, so
    the async pipeline runs on a helper thread with its own loop — the
    same blocking shape run_command already has.
    """
    global _auto_perceive_attempts
    if os.environ.get("AGENTICX_AUTO_VISION", "1") == "0":
        return None
    if _PERCEPTION_CTX is None:
        return None
    real = os.path.realpath(safe_path)
    if real in _auto_perceived_paths:
        return None
    if _auto_perceive_attempts >= _auto_perceive_budget():
        return None
    _auto_perceive_attempts += 1
    config, get_provider_fn = _PERCEPTION_CTX
    question = (
        "Describe this image in detail. If it contains text, digits or "
        "tables, transcribe them verbatim."
    )

    box: list = []

    def _runner():
        try:
            box.append(
                asyncio.run(
                    _perceive_image(
                        config,
                        get_provider_fn,
                        real,
                        question,
                        "auto",
                    ),
                ),
            )
        except BaseException:  # pylint: disable=broad-except
            box.append(None)

    worker = threading.Thread(target=_runner, daemon=True)
    worker.start()
    worker.join(timeout=_AUTO_PERCEIVE_TIMEOUT)
    if not box or box[0] is None:
        return None
    _auto_perceived_paths.add(real)
    if via == "command":
        prefix = (
            "[this command references an image; its content was "
            "perceived with a vision model (auto-perception):]"
        )
    else:
        prefix = (
            "[read_file cannot decode images as text; this image was "
            "perceived with a vision model (auto-perception):]"
        )
    return (
        f"{prefix}\n"
        f"{box[0]}\n"
        "[for exact digit-level text cross-check with tesseract OCR on "
        "the file, or call view_image with a focused question or a "
        "cropped region.]"
    )

register_vision_tools

register_vision_tools(
    config: Config, *, get_provider_fn: Callable
)

Register view_image; called once after agent construction.

Source code in src/dashscope_agenticx/tools/vision.py
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
def register_vision_tools(config: Config, *, get_provider_fn: Callable):
    """Register ``view_image``; called once after agent construction."""
    global _PERCEPTION_CTX
    _PERCEPTION_CTX = (config, get_provider_fn)

    async def view_image(
        image_path: str,
        question: str = (
            "Describe this image in detail. If it contains text or "
            "tables, transcribe them verbatim."
        ),
        slice_mode: str = "auto",
        region: str = "",
    ) -> str:
        global _view_image_calls
        _view_image_calls += 1

        from dashscope_agenticx.utils.paths import validate_path

        try:
            safe_path = validate_path(image_path)
        except (ValueError, OSError) as e:
            return f"Error: failed to read image: {e}"

        return await _perceive_image(
            config,
            get_provider_fn,
            safe_path,
            question,
            slice_mode,
            region,
        )

    registry.register(
        ToolDefinition(
            name="view_image",
            description=(
                "Analyze a local image file (screenshot, photo, chart, "
                "scan, render) with a vision model: OCR/transcribe text "
                "or digits, describe layout or content. Very tall/wide "
                "images are split automatically. Use whenever a task "
                "requires reading an image's content — including images "
                "you rendered yourself from data (plots, geometry, "
                "toolpaths) — instead of approximating the perception "
                "with terminal output or pixel scripting. For grid-like "
                "content (tables, digit grids), read the whole image "
                "first, then re-read it block by block with the region "
                "parameter: region is a real pixel crop (upscaled "
                "automatically), far more accurate than asking about a "
                "region of the full image. When every character matters "
                "(codes, serial numbers, mixed-case text), never trust "
                "one whole-image read of small or stylized text: "
                "verify it with region reads of a few characters each "
                "before committing to an answer, and overlap adjacent "
                "crops so no character sits on a crop boundary. When "
                "re-reads of one glyph keep disagreeing, more identical "
                "re-reads will not converge — the glyph is at the "
                "recognizer's noise floor: adjudicate with a feature "
                "question (a dot, serif, or enclosed counter present or "
                "absent) on a crop of only that glyph, and prefer the "
                "candidate that makes the assembled string read as "
                "coherent text over the one that does not. Overlapping "
                "crops also cross-check each other: characters shared by "
                "two crops must read the same in both, and if they do "
                "not, re-read the contested span before committing. And "
                "when you rendered the image yourself, ambiguous reads "
                "are a rendering problem, not a perception limit: "
                "re-render larger or higher-contrast and read the new "
                "render instead of re-reading the same pixels. Glyphs "
                "from confusable sets (0/O/o, 1/l/i/I, 5/S, 8/B, and "
                "same-shape letter case like cC, kK, pP) need "
                "feature-level confirmation — dot, serif, counter, "
                "relative height — not just repeated transcription: "
                "stylized fonts make wrong glyphs look unambiguous. "
                "Context is what corrupts stylized reads: word-shaped "
                "crops get pattern-completed into expected words, while "
                "a crop of one isolated glyph can only be read as "
                "pixels — settle contested characters glyph by glyph, "
                "and never let an expected word override what isolated "
                "glyphs clearly show."
            ),
            permission=PermissionLevel.AUTO,
            func=view_image,
            parameters={
                "type": "object",
                "properties": {
                    "image_path": {
                        "type": "string",
                        "description": (
                            "Path to the image file (relative to the "
                            "workspace or absolute)"
                        ),
                    },
                    "question": {
                        "type": "string",
                        "description": (
                            "What to extract from the image; defaults "
                            "to a full description + verbatim OCR"
                        ),
                    },
                    "slice_mode": {
                        "type": "string",
                        "enum": ["auto", "never"],
                        "description": (
                            "auto (default): split oversized images "
                            "into slices; never: always send the whole "
                            "image in one call"
                        ),
                    },
                    "region": {
                        "type": "string",
                        "description": (
                            'Crop before reading: "x0,y0,x1,y1" as '
                            "fractions of width/height (0-1, origin "
                            "top-left), e.g. the middle horizontal "
                            'third is "0,0.333,1,0.667". Overrides '
                            "slicing. For dense grids/tables transcribe "
                            "a few cells per call; for exact-character "
                            "work (codes, labels, stylized or small "
                            "text) crop to a few characters per call. "
                            "When tiling a long string with several "
                            "crops, overlap adjacent crops: a character "
                            "at a crop boundary is exactly the one most "
                            "likely to be dropped or duplicated, so "
                            "every character must appear fully inside "
                            "at least one crop. Each region read samples "
                            "the vision model several times and shows "
                            "every answer when they disagree."
                        ),
                    },
                },
                "required": ["image_path"],
            },
        ),
    )

技能

Skill dataclass

Skill(
    name: str,
    description: str,
    mcp_service: str,
    prompt_template: str,
    arguments: list[str],
)

name instance-attribute

name: str

description instance-attribute

description: str

mcp_service instance-attribute

mcp_service: str

prompt_template instance-attribute

prompt_template: str

arguments instance-attribute

arguments: list[str]

register

register(skill: Skill)
Source code in src/dashscope_agenticx/skills/base.py
34
35
36
def register(skill: Skill):
    with _skills_lock:
        BUILTIN_SKILLS[skill.name] = skill

load_skill_files

load_skill_files()

Load skills from .md files in global and workspace skill folders.

Global files load first; workspace files override by name. File-sourced entries from the previous scan are dropped first, so deleting a skill file propagates without a restart.

Source code in src/dashscope_agenticx/skills/base.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
def load_skill_files():
    """Load skills from .md files in global and workspace skill folders.

    Global files load first; workspace files override by name. File-sourced
    entries from the previous scan are dropped first, so deleting a skill
    file propagates without a restart.
    """
    from dashscope_agenticx.config import CONFIG_DIR, WORKSPACE_DIR

    global_dir = CONFIG_DIR / "skills"
    workspace_dir = WORKSPACE_DIR / "skills"

    with _skills_lock:
        for name in _FILE_SKILL_NAMES:
            BUILTIN_SKILLS.pop(name, None)
        _FILE_SKILL_NAMES.clear()

        for skills_dir in (global_dir, workspace_dir):
            if not skills_dir.is_dir():
                continue
            for path in sorted(skills_dir.glob("*.md")):
                try:
                    skill = _parse_skill_md(path)
                except Exception as e:
                    import logging

                    logging.getLogger(__name__).warning(
                        "Skipping unparseable skill file %s: %s",
                        path,
                        e,
                    )
                    continue
                if skill:
                    register(skill)
                    _FILE_SKILL_NAMES.add(skill.name)

register_skill_file

register_skill_file(path: Path | str) -> bool

Register one skill .md at runtime, without waiting for a restart.

Copies path into the workspace skills dir when it lives elsewhere, then rescans so the catalog, /skill completion, and the prompt summary all see the change immediately. Returns True when the file parsed and its skill is registered after the rescan.

Source code in src/dashscope_agenticx/skills/base.py
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
def register_skill_file(path: Path | str) -> bool:
    """Register one skill .md at runtime, without waiting for a restart.

    Copies *path* into the workspace skills dir when it lives elsewhere,
    then rescans so the catalog, /skill completion, and the prompt summary
    all see the change immediately. Returns True when the file parsed and
    its skill is registered after the rescan.
    """
    from dashscope_agenticx.config import WORKSPACE_DIR

    src = Path(path)
    try:
        skill = _parse_skill_md(src)
    except Exception:
        return False
    if skill is None:
        return False

    skills_dir = WORKSPACE_DIR / "skills"
    target = skills_dir / src.name
    try:
        if src.resolve() != target.resolve():
            skills_dir.mkdir(parents=True, exist_ok=True)
            shutil.copyfile(src, target)
    except OSError:
        return False

    load_skill_files()
    with _skills_lock:
        return BUILTIN_SKILLS.get(skill.name) is not None

list_skills

list_skills(
    connected_services: set[str] | None = None,
) -> str

Format skills list for display.

Source code in src/dashscope_agenticx/skills/base.py
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
def list_skills(connected_services: set[str] | None = None) -> str:
    """Format skills list for display."""
    lines = ["Available skills:"]
    lines.append("=" * 40)

    available = []
    needs_mcp = []

    for skill in BUILTIN_SKILLS.values():
        if not skill.mcp_service:
            available.append(skill)
        elif connected_services and skill.mcp_service in connected_services:
            available.append(skill)
        else:
            needs_mcp.append(skill)

    if available:
        lines.append("")
        lines.append("[Ready to use]")
        for s in available:
            args = " ".join(f"<{a}>" for a in s.arguments)
            lines.append(f"  \u25b8 {s.name} {args}")
            lines.append(f"     {s.description}")

    if needs_mcp:
        lines.append("")
        lines.append("[Requires MCP connection]")
        for s in needs_mcp:
            args = " ".join(f"<{a}>" for a in s.arguments)
            lines.append(f"  \u25ab {s.name} {args}  (needs: {s.mcp_service})")
            lines.append(f"     {s.description}")

    lines.append("")
    lines.append("Usage: /skill <name> <arg1> <arg2> ...")
    lines.append("Example: /skill my-skill arg1 arg2")
    return "\n".join(lines)

render_skill

render_skill(skill: Skill, args: list[str]) -> str | None

Render a skill prompt with given arguments. Returns None if args don't match.

Source code in src/dashscope_agenticx/skills/base.py
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
def render_skill(skill: Skill, args: list[str]) -> str | None:
    """Render a skill prompt with given arguments. Returns None if args
    don't match."""
    if len(args) < len(skill.arguments):
        return None
    template = skill.prompt_template
    # A skill body is Markdown, not a format string: it is full of literal
    # braces from the JSON and Python it documents. Running str.format() over
    # the whole body raised KeyError on `{"role": ...}`, which the old
    # `except KeyError` turned into a bogus "missing args" report for every
    # no-argument skill that showed a payload, and let the IndexError from
    # `{}` escape entirely. Substitute only the declared arguments and leave
    # every other brace exactly as the author wrote it.
    for i, arg_name in enumerate(skill.arguments):
        if i == len(skill.arguments) - 1:
            value = " ".join(args[i:])
        else:
            value = args[i]
        template = template.replace("{" + arg_name + "}", value)
    return template

SkillManager dataclass

SkillManager(
    packages: list[SkillPackage] = list(),
    _force_enabled: set[str] = set(),
    _force_disabled: set[str] = set(),
    _hook_bus: HookBus | None = None,
    _global: bool = False,
    _registry_url: str = "",
    tool_registry: ToolRegistry = (lambda: registry)(),
)

Manages loaded skill packages and their activation state.

packages class-attribute instance-attribute

packages: list[SkillPackage] = field(default_factory=list)

tool_registry class-attribute instance-attribute

tool_registry: ToolRegistry = field(
    default_factory=lambda: registry
)

load

load(hook_bus: HookBus | None = None) -> None

Discover and register packages from workspace and global dirs.

Source code in src/dashscope_agenticx/skills/manager.py
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
def load(self, hook_bus: HookBus | None = None) -> None:
    """Discover and register packages from workspace and global dirs."""
    if hook_bus is not None:
        self._hook_bus = hook_bus
    bus = self._hook_bus
    # Clear previously registered tools and hooks
    for pkg in self.packages:
        unregister_skill_package(pkg, bus)
    self.packages = discover_skill_packages(
        extra_dirs=[store.get_skills_dir(self._global)],
    )
    for pkg in self.packages:
        if bus is not None:
            register_skill_package(pkg, self.tool_registry, bus)
        else:
            register_skill_package(
                pkg,
                self.tool_registry,
                HookBus(),
            )

reload

reload() -> None

Reload packages from disk.

Source code in src/dashscope_agenticx/skills/manager.py
55
56
57
58
59
def reload(self) -> None:
    """Reload packages from disk."""
    self._force_enabled.clear()
    self._force_disabled.clear()
    self.load(self._hook_bus)

list

list() -> list[dict[str, Any]]

Return package info for display.

Source code in src/dashscope_agenticx/skills/manager.py
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
def list(self) -> list[dict[str, Any]]:
    """Return package info for display."""
    return [
        {
            "name": pkg.name,
            "version": pkg.version,
            "description": pkg.description,
            "always_active": pkg.always_active,
            "triggers": pkg.triggers,
            "tools": list(pkg.tools_registered),
            "publisher": (
                pkg.app_manifest.publisher if pkg.app_manifest else ""
            ),
            "checksum": (
                pkg.app_manifest.checksum if pkg.app_manifest else ""
            ),
            "trust": (
                pkg.app_manifest.trust.value
                if pkg.app_manifest
                else "untrusted"
            ),
            "permissions": (
                list(pkg.app_manifest.permissions.names())
                if pkg.app_manifest
                else []
            ),
        }
        for pkg in self.packages
    ]

install

install(source: str) -> str

Install a skill package and reload.

Source code in src/dashscope_agenticx/skills/manager.py
91
92
93
94
95
96
97
98
99
def install(self, source: str) -> str:
    """Install a skill package and reload."""
    name = store.install(
        source,
        global_=self._global,
        registry_url=self._registry_url,
    )
    self.reload()
    return name
link(source_dir: str) -> str

Symlink a local skill package and reload.

Source code in src/dashscope_agenticx/skills/manager.py
101
102
103
104
105
def link(self, source_dir: str) -> str:
    """Symlink a local skill package and reload."""
    name = store.link(source_dir, global_=self._global)
    self.reload()
    return name

uninstall

uninstall(name: str) -> bool

Remove an installed skill package and reload.

Source code in src/dashscope_agenticx/skills/manager.py
107
108
109
110
111
112
113
114
def uninstall(self, name: str) -> bool:
    """Remove an installed skill package and reload."""
    result = store.uninstall(name, global_=self._global)
    if result:
        self._force_enabled.discard(name)
        self._force_disabled.discard(name)
        self.reload()
    return result

update

update(name: str) -> str

Update a single installed skill package and reload.

Source code in src/dashscope_agenticx/skills/manager.py
116
117
118
119
120
121
122
123
124
def update(self, name: str) -> str:
    """Update a single installed skill package and reload."""
    store.update(
        name,
        global_=self._global,
        registry_url=self._registry_url,
    )
    self.reload()
    return name

update_all

update_all() -> builtins.list[tuple[str, str | None]]

Update all installed skill packages and reload.

Source code in src/dashscope_agenticx/skills/manager.py
126
127
128
129
130
131
132
133
def update_all(self) -> builtins.list[tuple[str, str | None]]:
    """Update all installed skill packages and reload."""
    results = store.update_all(
        global_=self._global,
        registry_url=self._registry_url,
    )
    self.reload()
    return results

search

search(query: str) -> builtins.list[dict[str, Any]]

Search installed packages and the registry.

Source code in src/dashscope_agenticx/skills/manager.py
135
136
137
138
139
140
141
def search(self, query: str) -> builtins.list[dict[str, Any]]:
    """Search installed packages and the registry."""
    return store.search(
        query,
        global_=self._global,
        registry_url=self._registry_url,
    )

publish

publish(source_dir: str) -> Path

Validate and package a skill directory.

Source code in src/dashscope_agenticx/skills/manager.py
143
144
145
def publish(self, source_dir: str) -> Path:
    """Validate and package a skill directory."""
    return store.publish(source_dir)

active_packages

active_packages(
    user_input: str,
) -> builtins.list[SkillPackage]

Return packages that should be active for the given user input.

Source code in src/dashscope_agenticx/skills/manager.py
147
148
149
150
151
152
153
154
155
def active_packages(self, user_input: str) -> builtins.list[SkillPackage]:
    """Return packages that should be active for the given user input."""
    active: list[SkillPackage] = []
    for pkg in self.packages:
        if pkg.name in self._force_disabled:
            continue
        if pkg.name in self._force_enabled or pkg.is_active(user_input):
            active.append(pkg)
    return active

active_prompts

active_prompts(user_input: str) -> str

Concatenate prompts from active packages.

Source code in src/dashscope_agenticx/skills/manager.py
157
158
159
160
161
162
163
164
165
166
def active_prompts(self, user_input: str) -> str:
    """Concatenate prompts from active packages."""
    prompts = [
        pkg.prompt
        for pkg in self.active_packages(user_input)
        if pkg.prompt
    ]
    if not prompts:
        return ""
    return "\n\n".join(prompts)

enable

enable(name: str) -> bool
Source code in src/dashscope_agenticx/skills/manager.py
168
169
170
171
172
173
174
def enable(self, name: str) -> bool:
    pkg = self._find(name)
    if pkg is None:
        return False
    self._force_enabled.add(name)
    self._force_disabled.discard(name)
    return True

disable

disable(name: str) -> bool
Source code in src/dashscope_agenticx/skills/manager.py
176
177
178
179
180
181
182
def disable(self, name: str) -> bool:
    pkg = self._find(name)
    if pkg is None:
        return False
    self._force_disabled.add(name)
    self._force_enabled.discard(name)
    return True

get_skill_manager

get_skill_manager() -> SkillManager
Source code in src/dashscope_agenticx/skills/manager.py
195
196
def get_skill_manager() -> SkillManager:
    return _skill_manager

应用与专家

AppManifest dataclass

AppManifest(
    name: str,
    version: str,
    description: str = "",
    publisher: str = "",
    schema_version: str = "1",
    permissions: AppPermissions = AppPermissions(),
    declared_checksum: str = "",
    checksum: str = "",
    trust: AppTrust = AppTrust.UNTRUSTED,
    runtime_requires: str = ">=1.0.0,<2",
    profile: str = ".agenticx",
    eval_path: str = "",
    acceptance_path: str = "",
)

Declarative App identity and requested host capabilities.

name instance-attribute

name: str

version instance-attribute

version: str

description class-attribute instance-attribute

description: str = ''

publisher class-attribute instance-attribute

publisher: str = ''

schema_version class-attribute instance-attribute

schema_version: str = '1'

permissions class-attribute instance-attribute

permissions: AppPermissions = field(
    default_factory=AppPermissions
)

declared_checksum class-attribute instance-attribute

declared_checksum: str = ''

checksum class-attribute instance-attribute

checksum: str = ''

trust class-attribute instance-attribute

trust: AppTrust = AppTrust.UNTRUSTED

runtime_requires class-attribute instance-attribute

runtime_requires: str = '>=1.0.0,<2'

profile class-attribute instance-attribute

profile: str = '.agenticx'

eval_path class-attribute instance-attribute

eval_path: str = ''

acceptance_path class-attribute instance-attribute

acceptance_path: str = ''

can_execute_python property

can_execute_python: bool

can_execute_shell_hooks property

can_execute_shell_hooks: bool

AppTrust

Bases: str, Enum

Runtime trust assigned externally, never self-declared by an App.

UNTRUSTED class-attribute instance-attribute

UNTRUSTED = 'untrusted'

COMMUNITY class-attribute instance-attribute

COMMUNITY = 'community'

VERIFIED class-attribute instance-attribute

VERIFIED = 'verified'

OFFICIAL class-attribute instance-attribute

OFFICIAL = 'official'

allows_code_execution property

allows_code_execution: bool

parse classmethod

parse(value: object) -> 'AppTrust'
Source code in src/dashscope_agenticx/apps/manifest.py
27
28
29
30
31
32
33
34
@classmethod
def parse(cls, value: object) -> "AppTrust":
    if isinstance(value, cls):
        return value
    try:
        return cls(str(value))
    except ValueError:
        return cls.UNTRUSTED

AppPermissions dataclass

AppPermissions(
    python_tools: bool = False,
    shell_hooks: bool = False,
    shell: bool = False,
    network: tuple[str, ...] = (),
    filesystem: tuple[str, ...] = (),
)

Capabilities an App asks the host to grant.

python_tools class-attribute instance-attribute

python_tools: bool = False

shell_hooks class-attribute instance-attribute

shell_hooks: bool = False

shell class-attribute instance-attribute

shell: bool = False

network class-attribute instance-attribute

network: tuple[str, ...] = ()

filesystem class-attribute instance-attribute

filesystem: tuple[str, ...] = ()

from_mapping classmethod

from_mapping(value: object) -> 'AppPermissions'
Source code in src/dashscope_agenticx/apps/manifest.py
47
48
49
50
51
52
53
54
55
56
57
58
59
@classmethod
def from_mapping(cls, value: object) -> "AppPermissions":
    data = value if isinstance(value, dict) else {}
    for name in ("python_tools", "shell_hooks", "shell"):
        if name in data and not isinstance(data[name], bool):
            raise ValueError(f"App permission {name} must be a boolean")
    return cls(
        python_tools=bool(data.get("python_tools", False)),
        shell_hooks=bool(data.get("shell_hooks", False)),
        shell=bool(data.get("shell", False)),
        network=_string_tuple(data.get("network", ())),
        filesystem=_string_tuple(data.get("filesystem", ())),
    )

names

names() -> tuple[str, ...]
Source code in src/dashscope_agenticx/apps/manifest.py
61
62
63
64
65
66
67
68
69
70
71
def names(self) -> tuple[str, ...]:
    values: list[str] = []
    if self.python_tools:
        values.append("python_tools")
    if self.shell_hooks:
        values.append("shell_hooks")
    if self.shell:
        values.append("shell")
    values.extend(f"network:{item}" for item in self.network)
    values.extend(f"filesystem:{item}" for item in self.filesystem)
    return tuple(values)

as_dict

as_dict() -> dict[str, object]
Source code in src/dashscope_agenticx/apps/manifest.py
73
74
75
76
77
78
79
80
def as_dict(self) -> dict[str, object]:
    return {
        "python_tools": self.python_tools,
        "shell_hooks": self.shell_hooks,
        "shell": self.shell,
        "network": list(self.network),
        "filesystem": list(self.filesystem),
    }

load_app_manifest

load_app_manifest(
    path: Path,
    *,
    trust: AppTrust | str = AppTrust.UNTRUSTED,
    expected_checksum: str = ""
) -> AppManifest | None

Load and verify an App manifest from a package directory.

Source code in src/dashscope_agenticx/apps/manifest.py
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
def load_app_manifest(
    path: Path,
    *,
    trust: AppTrust | str = AppTrust.UNTRUSTED,
    expected_checksum: str = "",
) -> AppManifest | None:
    """Load and verify an App manifest from a package directory."""
    data = _manifest_data(path)
    if not data:
        return None
    app = data.get("app") if isinstance(data.get("app"), dict) else data
    schema_version = str(app.get("schema_version", "1"))
    if schema_version != "1":
        raise ValueError(f"Unsupported App schema version: {schema_version}")
    permissions = AppPermissions.from_mapping(data.get("permissions"))
    checksum = compute_app_checksum(path)
    declared = str(app.get("checksum", data.get("checksum", ""))).strip()
    expected = expected_checksum.strip()
    for label, value in (("declared", declared), ("expected", expected)):
        if value and value != checksum:
            raise ValueError(
                f"App {label} checksum mismatch: expected {value}, "
                f"computed {checksum}",
            )
    name = str(app.get("name", path.name)).strip()
    if not name:
        raise ValueError("App manifest name must not be empty")
    return AppManifest(
        name=name,
        version=str(app.get("version", "0.0.1")),
        description=str(app.get("description", "")),
        publisher=str(app.get("publisher", "")),
        schema_version=schema_version,
        permissions=permissions,
        declared_checksum=declared,
        checksum=checksum,
        trust=AppTrust.parse(trust),
        runtime_requires=str(
            (data.get("runtime") or {}).get("requires", ">=1.0.0,<2")
            if isinstance(data.get("runtime"), dict)
            else ">=1.0.0,<2",
        ),
        profile=str(app.get("profile", ".agenticx")),
        eval_path=str(app.get("eval", "")),
        acceptance_path=str(app.get("acceptance", "")),
    )

compute_app_checksum

compute_app_checksum(path: Path) -> str

Return a deterministic SHA-256 over regular App files.

Symlinks are rejected because checksumming the link text while later importing its target would verify different bytes from those executed. Generated caches and install metadata are excluded from the identity.

Source code in src/dashscope_agenticx/apps/manifest.py
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
def compute_app_checksum(path: Path) -> str:
    """Return a deterministic SHA-256 over regular App files.

    Symlinks are rejected because checksumming the link text while later
    importing its target would verify different bytes from those executed.
    Generated caches and install metadata are excluded from the identity.
    """
    root = path.resolve()
    if not root.is_dir():
        raise ValueError(f"App path is not a directory: {path}")
    digest = hashlib.sha256()
    excluded = {
        ".agenticx-skills.json",
        ".agenticcli-skills.json",
        "__pycache__",
        ".git",
    }
    for item in sorted(path.rglob("*"), key=lambda value: value.as_posix()):
        relative = item.relative_to(path)
        if any(part in excluded for part in relative.parts):
            continue
        if item.is_symlink():
            raise ValueError(f"App contains a symlink: {relative.as_posix()}")
        if not item.is_file():
            continue
        relative_text = relative.as_posix().encode("utf-8")
        payload = item.read_bytes()
        if relative.as_posix() in {"app.toml", "skill.toml"}:
            parsed = load_toml(item)
            if isinstance(parsed, dict):
                parsed.pop("checksum", None)
                app = parsed.get("app")
                if isinstance(app, dict):
                    app.pop("checksum", None)
                payload = json.dumps(
                    parsed,
                    ensure_ascii=False,
                    sort_keys=True,
                    separators=(",", ":"),
                ).encode("utf-8")
        digest.update(len(relative_text).to_bytes(8, "big"))
        digest.update(relative_text)
        digest.update(len(payload).to_bytes(8, "big"))
        digest.update(payload)
    return f"sha256:{digest.hexdigest()}"

permission_diff

permission_diff(
    before: AppPermissions | None, after: AppPermissions
) -> dict[str, list[str]]

Return stable added/removed permission names for install prompts.

Source code in src/dashscope_agenticx/apps/manifest.py
227
228
229
230
231
232
233
234
235
236
237
def permission_diff(
    before: AppPermissions | None,
    after: AppPermissions,
) -> dict[str, list[str]]:
    """Return stable added/removed permission names for install prompts."""
    old = set(before.names() if before else ())
    new = set(after.names())
    return {
        "added": sorted(new - old),
        "removed": sorted(old - new),
    }

install

install(
    source: str,
    *,
    root: Path | None = None,
    trust: AppTrust | str = AppTrust.COMMUNITY,
    expected_checksum: str = "",
    confirm_permissions: (
        Callable[[AppManifest, dict], bool] | None
    ) = None
) -> AppInstallResult
Source code in src/dashscope_agenticx/apps/store.py
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
def install(
    source: str,
    *,
    root: Path | None = None,
    trust: AppTrust | str = AppTrust.COMMUNITY,
    expected_checksum: str = "",
    confirm_permissions: Callable[[AppManifest, dict], bool] | None = None,
) -> AppInstallResult:
    if source.startswith("bundled:"):
        name = _safe_name(source.split(":", 1)[1])
        bundled_root = bundled_apps_dir().resolve()
        source_path = (bundled_root / name).resolve()
        if source_path.parent != bundled_root:
            raise RuntimeError(
                "Bundled App must be inside the shipped catalog",
            )
        trust = AppTrust.OFFICIAL
    else:
        source_path = Path(source).expanduser().resolve()
    manifest = load_app_manifest(
        source_path,
        trust=trust,
        expected_checksum=expected_checksum,
    )
    if manifest is None or not (source_path / "app.toml").is_file():
        raise RuntimeError(f"App bundle is missing app.toml: {source_path}")
    _validate_bundle(source_path, manifest)
    if not runtime_compatible(manifest):
        raise RuntimeError(
            f"App {manifest.name} requires AgenticX "
            f"{manifest.runtime_requires}; current version is {__version__}",
        )
    root = root or apps_dir()
    name = _safe_name(manifest.name)
    registry = load_registry(root)
    previous = registry.get(name, {})
    before = AppPermissions.from_mapping(
        previous.get("permissions") if isinstance(previous, dict) else None,
    )
    changes = permission_diff(
        before if previous else None,
        manifest.permissions,
    )
    if confirm_permissions is not None and not confirm_permissions(
        manifest,
        changes,
    ):
        raise RuntimeError("App installation cancelled before writing files")
    destination = root / name
    root.mkdir(parents=True, exist_ok=True)
    _copy_bundle(source_path, destination)
    installed = load_app_manifest(
        destination,
        trust=trust,
        expected_checksum=manifest.checksum,
    )
    assert installed is not None
    _validate_bundle(destination, installed)
    registry[name] = {
        "name": name,
        "version": installed.version,
        "source": str(source_path),
        "publisher": installed.publisher,
        "checksum": installed.checksum,
        "trust": installed.trust.value,
        "permissions": installed.permissions.as_dict(),
        "runtime_requires": installed.runtime_requires,
        "permission_diff": changes,
        "installed_at": (
            previous.get("installed_at", _now())
            if isinstance(previous, dict)
            else _now()
        ),
        "updated_at": _now(),
    }
    save_registry(root, registry)
    return AppInstallResult(installed, changes, destination)

AppInstallResult dataclass

AppInstallResult(
    manifest: AppManifest,
    permission_changes: dict[str, list[str]],
    path: Path,
)

manifest instance-attribute

manifest: AppManifest

permission_changes instance-attribute

permission_changes: dict[str, list[str]]

path instance-attribute

path: Path

load_registry

load_registry(root: Path | None = None) -> dict[str, Any]
Source code in src/dashscope_agenticx/apps/store.py
54
55
56
57
58
59
60
61
62
63
64
65
66
def load_registry(root: Path | None = None) -> dict[str, Any]:
    root = root or apps_dir()
    path = _registry_path(root)
    if not path.is_file():
        legacy_path = root / LEGACY_REGISTRY_FILE
        if not legacy_path.is_file():
            return {}
        path = legacy_path
    try:
        value = json.loads(path.read_text(encoding="utf-8"))
        return value if isinstance(value, dict) else {}
    except (OSError, json.JSONDecodeError):
        return {}

runtime_compatible

runtime_compatible(
    manifest: AppManifest, version: str = __version__
) -> bool
Source code in src/dashscope_agenticx/apps/store.py
77
78
79
80
81
82
83
84
def runtime_compatible(
    manifest: AppManifest,
    version: str = __version__,
) -> bool:
    try:
        return Version(version) in SpecifierSet(manifest.runtime_requires)
    except (InvalidSpecifier, InvalidVersion):
        return False

运行时扩展

来自 .agenticx/custom-extensions.toml 的声明式 Provider、工具、 能力与技能:

CustomExtensions dataclass

CustomExtensions(
    providers: list[CustomProvider] = list(),
    capabilities: list[CustomCapability] = list(),
    skills: list[CustomSkill] = list(),
    shell_tools: list[CustomShellTool] = list(),
    errors: list[str] = list(),
)

providers class-attribute instance-attribute

providers: list[CustomProvider] = field(
    default_factory=list
)

capabilities class-attribute instance-attribute

capabilities: list[CustomCapability] = field(
    default_factory=list
)

skills class-attribute instance-attribute

skills: list[CustomSkill] = field(default_factory=list)

shell_tools class-attribute instance-attribute

shell_tools: list[CustomShellTool] = field(
    default_factory=list
)

errors class-attribute instance-attribute

errors: list[str] = field(default_factory=list)

CustomProvider dataclass

CustomProvider(
    name: str,
    base_url: str,
    api_key_env: str = "",
    api_key_enc: str = "",
    default_model: str = "",
    models: list[str] = list(),
    vision_models: list[str] = list(),
    audio_models: list[str] = list(),
    protocol: str = "openai",
    reasoning_field: str = "",
    auth: bool = True,
    source: str = "",
)

name instance-attribute

name: str

base_url instance-attribute

base_url: str

api_key_env class-attribute instance-attribute

api_key_env: str = ''

api_key_enc class-attribute instance-attribute

api_key_enc: str = ''

default_model class-attribute instance-attribute

default_model: str = ''

models class-attribute instance-attribute

models: list[str] = field(default_factory=list)

vision_models class-attribute instance-attribute

vision_models: list[str] = field(default_factory=list)

audio_models class-attribute instance-attribute

audio_models: list[str] = field(default_factory=list)

protocol class-attribute instance-attribute

protocol: str = 'openai'

reasoning_field class-attribute instance-attribute

reasoning_field: str = ''

auth class-attribute instance-attribute

auth: bool = True

source class-attribute instance-attribute

source: str = ''

resolved_models

resolved_models() -> list[str]
Source code in src/dashscope_agenticx/extensions.py
91
92
93
94
95
96
def resolved_models(self) -> list[str]:
    out = [self.default_model] if self.default_model else []
    for m in self.models:
        if m and m != self.default_model:
            out.append(m)
    return out or [normalize_model_name(self.name)]

resolved_protocol

resolved_protocol() -> str

Normalize protocol aliases. 'openai_compatible' → 'openai'; 'dashscope' / 'anthropic' / 'openai' pass through unchanged.

Source code in src/dashscope_agenticx/extensions.py
 98
 99
100
101
102
103
104
def resolved_protocol(self) -> str:
    """Normalize protocol aliases. 'openai_compatible' → 'openai';
    'dashscope' / 'anthropic' / 'openai' pass through unchanged."""
    p = (self.protocol or "openai").lower()
    if p == "openai_compatible":
        return "openai"
    return p

resolve_api_key

resolve_api_key(config=None) -> str
Source code in src/dashscope_agenticx/extensions.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
def resolve_api_key(self, config=None) -> str:
    if not self.auth:
        return "ollama"  # placeholder; OpenAI SDK requires non-empty
    # User-set global config slot wins (set via /provider or startup).
    if config is not None:
        cfg_val = getattr(config, f"{self.name}_api_key", "")
        if cfg_val:
            return cfg_val
    if self.api_key_env:
        val = os.environ.get(self.api_key_env, "")
        if val:
            return val
    if self.api_key_enc:
        return resolve_secret(self.api_key_enc)
    return ""

CustomTool dataclass

CustomTool(
    name: str,
    description: str,
    endpoint: str,
    http_method: str = "POST",
    auth: str = "",
    params: list[dict] = list(),
    body_template: str = "",
    headers: dict[str, str] = dict(),
    result_jsonpath: str = "",
    permission: str = "auto",
    type: str = "http",
    provider: str = "",
    model: str = "",
)

name instance-attribute

name: str

description instance-attribute

description: str

endpoint instance-attribute

endpoint: str

http_method class-attribute instance-attribute

http_method: str = 'POST'

auth class-attribute instance-attribute

auth: str = ''

params class-attribute instance-attribute

params: list[dict] = field(default_factory=list)

body_template class-attribute instance-attribute

body_template: str = ''

headers class-attribute instance-attribute

headers: dict[str, str] = field(default_factory=dict)

result_jsonpath class-attribute instance-attribute

result_jsonpath: str = ''

permission class-attribute instance-attribute

permission: str = 'auto'

type class-attribute instance-attribute

type: str = 'http'

provider class-attribute instance-attribute

provider: str = ''

model class-attribute instance-attribute

model: str = ''

CustomCapability dataclass

CustomCapability(
    key: str,
    display: str = "",
    auth: str = "",
    api_key_env: str = "",
    api_key_enc: str = "",
    tools: list[CustomTool] = list(),
    source: str = "",
    runtime_key: str = "",
)

key instance-attribute

key: str

display class-attribute instance-attribute

display: str = ''

auth class-attribute instance-attribute

auth: str = ''

api_key_env class-attribute instance-attribute

api_key_env: str = ''

api_key_enc class-attribute instance-attribute

api_key_enc: str = ''

tools class-attribute instance-attribute

tools: list[CustomTool] = field(default_factory=list)

source class-attribute instance-attribute

source: str = ''

runtime_key class-attribute instance-attribute

runtime_key: str = ''

resolve_auth_key

resolve_auth_key() -> str

Auth token resolution: env var (named by api_key_env if set OR derived from auth's "bearer:$X" form) wins, then a reused built-in provider key, falling back to keyring/legacy storage. Empty string when nothing's available.

Source code in src/dashscope_agenticx/extensions.py
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
def resolve_auth_key(self) -> str:
    """Auth token resolution: env var (named by api_key_env if set OR
    derived from auth's "bearer:$X" form) wins, then a reused built-in
    provider key, falling back to keyring/legacy storage. Empty string
    when nothing's available."""
    env_name = self.api_key_env or auth_env_name(self.auth)
    if env_name:
        val = os.environ.get(env_name, "")
        if val:
            return val
    if self.runtime_key:
        return self.runtime_key
    if self.api_key_enc:
        return resolve_secret(self.api_key_enc)
    return ""

CustomSkill dataclass

CustomSkill(
    name: str,
    description: str,
    prompt_template: str,
    arguments: list[str] = list(),
    mcp_service: str = "",
    source: str = "",
)

name instance-attribute

name: str

description instance-attribute

description: str

prompt_template instance-attribute

prompt_template: str

arguments class-attribute instance-attribute

arguments: list[str] = field(default_factory=list)

mcp_service class-attribute instance-attribute

mcp_service: str = ''

source class-attribute instance-attribute

source: str = ''

CustomShellTool dataclass

CustomShellTool(
    name: str,
    description: str,
    command_template: str,
    params: list[dict] = list(),
    permission: str = "confirm",
    source: str = "",
)

name instance-attribute

name: str

description instance-attribute

description: str

command_template instance-attribute

command_template: str

params class-attribute instance-attribute

params: list[dict] = field(default_factory=list)

permission class-attribute instance-attribute

permission: str = 'confirm'

source class-attribute instance-attribute

source: str = ''

load_extensions

load_extensions() -> CustomExtensions

Read global + workspace extension files; workspace entries with the same name as a global entry override (later wins). Errors are collected rather than raised — partial successes still register; bad entries get surfaced to the user via the cli banner.

Source code in src/dashscope_agenticx/extensions.py
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
def load_extensions() -> CustomExtensions:
    """Read global + workspace extension files; workspace entries with the
    same name as a global entry override (later wins). Errors are collected
    rather than raised — partial successes still register; bad entries get
    surfaced to the user via the cli banner."""
    ext = CustomExtensions()
    by_provider: dict[str, CustomProvider] = {}
    by_capability: dict[str, CustomCapability] = {}
    by_skill: dict[str, CustomSkill] = {}
    by_shell_tool: dict[str, CustomShellTool] = {}

    # Load order (later wins on same name): global → workspace.
    # Bundled defaults were removed; users declare providers in
    # ~/.agenticx/custom-extensions.toml or
    # ./.agenticx/custom-extensions.toml.
    # See the basic-chat Expert (`agenticx expert download basic-chat`).
    paths: list[Path] = [GLOBAL_EXTENSIONS_FILE, WORKSPACE_EXTENSIONS_FILE]

    for path in paths:
        if not path.exists():
            continue
        try:
            data = tomllib.loads(path.read_text(encoding="utf-8"))
        except tomllib.TOMLDecodeError as e:
            ext.errors.append(f"{path}: TOML parse error: {e}")
            continue
        except OSError as e:
            ext.errors.append(f"{path}: read failed: {e}")
            continue
        for raw in data.get("providers", []):
            err = _validate_provider(raw)
            if err:
                ext.errors.append(
                    f"{path}: provider {raw.get('name', '?')}: {err}",
                )
                continue
            p = CustomProvider(
                name=raw["name"],
                base_url=raw["base_url"],
                api_key_env=raw.get("api_key_env", "") or "",
                api_key_enc=(
                    raw.get("api_key", "")
                    if str(raw.get("api_key", "")).startswith(
                        ("KEYRING:", "ENC:"),
                    )
                    else ""
                ),
                default_model=raw.get("default_model", "") or "",
                models=list(raw.get("models", []) or []),
                vision_models=list(raw.get("vision_models", []) or []),
                audio_models=list(raw.get("audio_models", []) or []),
                protocol=raw.get("protocol", "openai"),
                reasoning_field=raw.get("reasoning_field", "") or "",
                auth=bool(raw.get("auth", True)),
                source=str(path),
            )
            by_provider[p.name] = p

        for raw in data.get("capabilities", []):
            err = _validate_capability(raw)
            if err:
                ext.errors.append(
                    f"{path}: capability {raw.get('key', '?')}: {err}",
                )
                continue
            cap = CustomCapability(
                key=raw["key"],
                display=raw.get("display", raw["key"]),
                auth=raw.get("auth", ""),
                api_key_env=raw.get("api_key_env", "") or "",
                api_key_enc=(
                    raw.get("api_key", "")
                    if str(raw.get("api_key", "")).startswith(
                        ("KEYRING:", "ENC:"),
                    )
                    else ""
                ),
                source=str(path),
            )
            for traw in raw.get("tools", []) or []:
                terr = _validate_tool(traw)
                if terr:
                    ext.errors.append(
                        f"{path}: capability {cap.key} tool "
                        f"{traw.get('name', '?')}: {terr}",
                    )
                    continue
                cap.tools.append(
                    CustomTool(
                        name=traw["name"],
                        description=traw.get("description", ""),
                        endpoint=traw.get("endpoint", ""),
                        http_method=traw.get("http_method", "POST").upper(),
                        auth=traw.get("auth", ""),
                        params=list(traw.get("params", []) or []),
                        body_template=traw.get("body_template", ""),
                        headers=dict(traw.get("headers", {}) or {}),
                        result_jsonpath=traw.get("result_jsonpath", ""),
                        permission=traw.get("permission", "auto").lower(),
                        type=(traw.get("type", "http") or "http").lower(),
                        provider=traw.get("provider", "") or "",
                        model=traw.get("model", "") or "",
                    ),
                )
            by_capability[cap.key] = cap

        for raw in data.get("skills", []):
            if not raw.get("name") or not raw.get("prompt_template"):
                ext.errors.append(
                    f"{path}: skill {raw.get('name', '?')}: "
                    f"missing name or prompt_template",
                )
                continue
            by_skill[raw["name"]] = CustomSkill(
                name=raw["name"],
                description=raw.get("description", ""),
                prompt_template=raw["prompt_template"],
                arguments=list(raw.get("arguments", []) or []),
                mcp_service=raw.get("mcp_service", "") or "",
                source=str(path),
            )

        for raw in data.get("shell_tools", []):
            if not raw.get("name") or not raw.get("command_template"):
                ext.errors.append(
                    f"{path}: shell_tool {raw.get('name', '?')}: "
                    f"missing name or command_template",
                )
                continue
            by_shell_tool[raw["name"]] = CustomShellTool(
                name=raw["name"],
                description=raw.get("description", ""),
                command_template=raw["command_template"],
                params=list(raw.get("params", []) or []),
                permission=raw.get("permission", "confirm").lower(),
                source=str(path),
            )

    ext.providers = list(by_provider.values())
    ext.capabilities = list(by_capability.values())
    ext.skills = list(by_skill.values())
    ext.shell_tools = list(by_shell_tool.values())
    return ext