Skip to content

Governance & Engine

Governance covers permission policy, OS sandboxing, audit logging, event hooks, and scheduled tasks. The engine layer is the turn execution kernel: model invocation, tool coordination, prompt assembly, acceptance gates, and deliverable collection.

See Security, Platform & MCP and Subagents, Hooks & Memory for the user-facing flows (permissions.toml, hooks.toml, /cron, /rule).

Permissions

PermissionPolicy dataclass

PermissionPolicy(
    tool_rules: dict[str, str] = dict(),
    command_rules: dict[str, str] = dict(),
)

Per-tool and per-domain permission rules.

Rules are checked before the interactive prompt. For command rules the most specific (longest) matching prefix wins, so a narrow deny always overrides a broad allow. If no rule matches, the normal PermissionLevel flow applies.

tool_rules class-attribute instance-attribute

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

command_rules class-attribute instance-attribute

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

check_tool

check_tool(tool_name: str) -> str | None

Return the policy decision for a tool, or None to fall through.

Source code in src/dashscope_agenticx/permission.py
54
55
56
def check_tool(self, tool_name: str) -> str | None:
    """Return the policy decision for a tool, or None to fall through."""
    return self.tool_rules.get(tool_name)

check_command

check_command(command: str) -> str | None

Return the policy decision for a shell command, or None.

Source code in src/dashscope_agenticx/permission.py
58
59
60
61
62
63
64
65
66
67
def check_command(self, command: str) -> str | None:
    """Return the policy decision for a shell command, or None."""
    normalized = _normalize_command(command)
    best: tuple[int, str] | None = None
    for prefix, decision in self.command_rules.items():
        if normalized.startswith(prefix):
            # pylint: disable=unsubscriptable-object
            if best is None or len(prefix) > best[0]:
                best = (len(prefix), decision)
    return best[1] if best else None

add_tool_rule

add_tool_rule(tool_name: str, decision: str) -> None
Source code in src/dashscope_agenticx/permission.py
69
70
71
72
73
74
def add_tool_rule(self, tool_name: str, decision: str) -> None:
    if decision not in ("allow", "deny", "confirm"):
        raise ValueError(
            f"decision must be allow/deny/confirm, got {decision}",
        )
    self.tool_rules[tool_name] = decision

add_command_rule

add_command_rule(prefix: str, decision: str) -> None
Source code in src/dashscope_agenticx/permission.py
76
77
78
79
80
81
82
83
84
def add_command_rule(self, prefix: str, decision: str) -> None:
    if decision not in ("allow", "deny", "confirm"):
        raise ValueError(
            f"decision must be allow/deny/confirm, got {decision}",
        )
    normalized = _normalize_command(prefix)
    if not normalized:
        raise ValueError("command rule prefix must not be empty")
    self.command_rules[normalized] = decision

load_permission_policy

load_permission_policy(
    policy: PermissionPolicy | None = None,
) -> PermissionPolicy

Load configured rules without modifying the process-wide facade.

Source code in src/dashscope_agenticx/permission.py
154
155
156
157
158
159
160
161
162
163
164
165
166
167
def load_permission_policy(
    policy: PermissionPolicy | None = None,
) -> PermissionPolicy:
    """Load configured rules without modifying the process-wide facade."""
    from dashscope_agenticx.config import CONFIG_DIR, WORKSPACE_DIR

    policy = policy if policy is not None else PermissionPolicy()
    for path in (
        CONFIG_DIR / "permissions.toml",
        WORKSPACE_DIR / "permissions.toml",
    ):
        for err in load_permissions_file(policy, path):
            log.warning("%s", err)
    return policy

load_permissions_file

load_permissions_file(
    policy: PermissionPolicy, path: Path
) -> list[str]

Merge a permissions.toml into policy; returns load errors.

Source code in src/dashscope_agenticx/permission.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
def load_permissions_file(policy: PermissionPolicy, path: Path) -> list[str]:
    """Merge a permissions.toml into ``policy``; returns load errors."""
    from dashscope_agenticx.utils import load_toml

    errors: list[str] = []
    data = load_toml(path)
    if data is None:
        return errors
    for section, add in (
        ("tools", policy.add_tool_rule),
        ("commands", policy.add_command_rule),
    ):
        entries = data.get(section, {})
        if not isinstance(entries, dict):
            errors.append(f"{path}: [{section}] must be a table")
            continue
        for key, decision in entries.items():
            try:
                add(str(key), str(decision))
            except ValueError as e:
                errors.append(f"{path}: [{section}] {key!r}: {e}")
    return errors

get_permission_policy

get_permission_policy() -> PermissionPolicy
Source code in src/dashscope_agenticx/permission.py
131
132
133
def get_permission_policy() -> PermissionPolicy:
    bound = _policy_context.get()
    return _policy if bound is None else bound

set_permission_policy

set_permission_policy(policy: PermissionPolicy) -> None
Source code in src/dashscope_agenticx/permission.py
136
137
138
def set_permission_policy(policy: PermissionPolicy) -> None:
    global _policy
    _policy = policy

configure_permission_policy

configure_permission_policy() -> PermissionPolicy

Load permissions.toml (global + workspace) into the global policy.

Called once at startup alongside configure_audit_logger. Workspace rules are applied last and win on identical keys. Invalid entries are skipped with a warning — a malformed rule must never widen permissions silently, so bad decisions are dropped, not defaulted to allow.

Source code in src/dashscope_agenticx/permission.py
141
142
143
144
145
146
147
148
149
150
151
def configure_permission_policy() -> PermissionPolicy:
    """Load permissions.toml (global + workspace) into the global policy.

    Called once at startup alongside ``configure_audit_logger``. Workspace
    rules are applied last and win on identical keys. Invalid entries are
    skipped with a warning — a malformed rule must never widen permissions
    silently, so bad decisions are dropped, not defaulted to allow.
    """
    policy = load_permission_policy()
    set_permission_policy(policy)
    return policy

Sandbox

detect_backend

detect_backend() -> Optional[str]

Return the available sandbox backend name, or None.

macOS prefers sandbox-exec (Seatbelt); Linux prefers bwrap. Windows has no supported backend. Detection only checks for the tool's presence on PATH — it never starts a sandbox.

Source code in src/dashscope_agenticx/sandbox.py
44
45
46
47
48
49
50
51
52
53
54
55
def detect_backend() -> Optional[str]:
    """Return the available sandbox backend name, or ``None``.

    macOS prefers ``sandbox-exec`` (Seatbelt); Linux prefers ``bwrap``.
    Windows has no supported backend. Detection only checks for the tool's
    presence on PATH — it never starts a sandbox.
    """
    if sys.platform == "darwin":
        return SEATBELT if shutil.which("sandbox-exec") else None
    if sys.platform.startswith("linux"):
        return BWRAP if shutil.which("bwrap") else None
    return None

available

available() -> bool

True when a sandbox backend is detected on this machine.

Source code in src/dashscope_agenticx/sandbox.py
58
59
60
def available() -> bool:
    """True when a sandbox backend is detected on this machine."""
    return detect_backend() is not None

is_enabled

is_enabled() -> bool

Whether sandboxing is enabled (config-driven, overridable).

Reads sandbox from the loaded config on each call so config changes take effect; degrades to False on any error so the sandbox can never break command execution.

Source code in src/dashscope_agenticx/sandbox.py
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def is_enabled() -> bool:
    """Whether sandboxing is enabled (config-driven, overridable).

    Reads ``sandbox`` from the loaded config on each call so config
    changes take effect; degrades to ``False`` on any error so the
    sandbox can never break command execution.
    """
    if _enabled_override is not None:
        return bool(_enabled_override)
    try:
        from dashscope_agenticx.config import Config

        return bool(Config.load().sandbox)
    except Exception:
        return False

set_enabled

set_enabled(value: Optional[bool]) -> None

Override sandbox enablement; pass None to use the config value.

Source code in src/dashscope_agenticx/sandbox.py
68
69
70
71
def set_enabled(value: Optional[bool]) -> None:
    """Override sandbox enablement; pass ``None`` to use the config value."""
    global _enabled_override
    _enabled_override = value

build_argv

build_argv(
    command: str, cwd: str, backend: Optional[str] = None
) -> Optional[list[str]]

Return an argv to run command inside the sandbox, or None.

None means "no sandbox available — run the command normally". backend may be passed explicitly (mainly for tests); otherwise it is detected.

Source code in src/dashscope_agenticx/sandbox.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
def build_argv(
    command: str,
    cwd: str,
    backend: Optional[str] = None,
) -> Optional[list[str]]:
    """Return an argv to run *command* inside the sandbox, or ``None``.

    ``None`` means "no sandbox available — run the command normally".
    ``backend`` may be passed explicitly (mainly for tests); otherwise it
    is detected.
    """
    backend = backend or detect_backend()
    if backend == SEATBELT:
        return [
            "sandbox-exec",
            "-p",
            seatbelt_profile(cwd),
            "/bin/sh",
            "-c",
            command,
        ]
    if backend == BWRAP:
        return bwrap_argv(command, cwd)
    return None

seatbelt_profile

seatbelt_profile(cwd: str) -> str

Build a macOS Seatbelt profile confining writes to the workspace.

The base policy stays default-allow; only filesystem writes are denied, then re-allowed for the workspace and standard temp/cache locations. Reads, process execution, and networking are untouched so ordinary development commands keep working.

Source code in src/dashscope_agenticx/sandbox.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
def seatbelt_profile(cwd: str) -> str:
    """Build a macOS Seatbelt profile confining writes to the workspace.

    The base policy stays default-allow; only filesystem writes are
    denied, then re-allowed for the workspace and standard temp/cache
    locations. Reads, process execution, and networking are untouched so
    ordinary development commands keep working.
    """
    safe_cwd = cwd.replace('"', '\\"')
    return "\n".join(
        [
            "(version 1)",
            "(allow default)",
            "(deny file-write*)",
            f'(allow file-write* (subpath "{safe_cwd}"))',
            '(allow file-write* (subpath "/private/tmp"))',
            '(allow file-write* (subpath "/tmp"))',
            '(allow file-write* (subpath "/private/var/folders"))',
            '(allow file-write* (literal "/dev/null"))',
        ],
    )

bwrap_argv

bwrap_argv(command: str, cwd: str) -> list[str]

Build a bwrap argv that runs command with a read-only root.

The whole filesystem is bound read-only, then the workspace and a fresh /tmp are made writable. Commands that need to write elsewhere (e.g. package caches) will fail — this is the intended confinement.

Source code in src/dashscope_agenticx/sandbox.py
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
def bwrap_argv(command: str, cwd: str) -> list[str]:
    """Build a ``bwrap`` argv that runs *command* with a read-only root.

    The whole filesystem is bound read-only, then the workspace and a
    fresh ``/tmp`` are made writable. Commands that need to write elsewhere
    (e.g. package caches) will fail — this is the intended confinement.
    """
    return [
        "bwrap",
        "--ro-bind",
        "/",
        "/",
        "--bind",
        cwd,
        cwd,
        "--tmpfs",
        "/tmp",
        "--proc",
        "/proc",
        "--dev",
        "/dev",
        "--chdir",
        cwd,
        "/bin/sh",
        "-c",
        command,
    ]

is_sandboxed_path

is_sandboxed_path(path: str, cwd: str) -> bool

True when path is inside the writable workspace or temp areas.

Informational helper (e.g. for messages); not a security check.

Source code in src/dashscope_agenticx/sandbox.py
169
170
171
172
173
174
175
176
177
178
179
180
181
def is_sandboxed_path(path: str, cwd: str) -> bool:
    """True when *path* is inside the writable workspace or temp areas.

    Informational helper (e.g. for messages); not a security check.
    """
    try:
        abs_path = os.path.abspath(path)
    except (OSError, ValueError):
        return False
    for base in (cwd, "/tmp", "/private/tmp"):
        if abs_path == base or abs_path.startswith(base + os.sep):
            return True
    return False

Audit

AuditEvent dataclass

AuditEvent(
    timestamp: str,
    source: str,
    action: str,
    subject: str,
    decision: str,
    reason: str = "",
    details: dict[str, Any] = dict(),
)

One auditable action in the system.

timestamp instance-attribute

timestamp: str

source instance-attribute

source: str

action instance-attribute

action: str

subject instance-attribute

subject: str

decision instance-attribute

decision: str

reason class-attribute instance-attribute

reason: str = ''

details class-attribute instance-attribute

details: dict[str, Any] = field(default_factory=dict)

now classmethod

now(
    source: str,
    action: str,
    subject: str,
    decision: str,
    reason: str = "",
    **details
) -> "AuditEvent"
Source code in src/dashscope_agenticx/audit.py
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
@classmethod
def now(
    cls,
    source: str,
    action: str,
    subject: str,
    decision: str,
    reason: str = "",
    **details,
) -> "AuditEvent":
    return cls(
        timestamp=datetime.now(timezone.utc).isoformat(),
        source=source,
        action=action,
        subject=subject,
        decision=decision,
        reason=reason,
        details=details,
    )

AuditLogger

AuditLogger(path: Path | None = None)

Append-only JSONL audit log.

Source code in src/dashscope_agenticx/audit.py
117
118
119
def __init__(self, path: Path | None = None):
    self._path = path or _AUDIT_FILE
    self._privacy_mode = False

set_privacy_mode

set_privacy_mode(enabled: bool) -> None
Source code in src/dashscope_agenticx/audit.py
121
122
def set_privacy_mode(self, enabled: bool) -> None:
    self._privacy_mode = enabled

log

log(event: AuditEvent) -> None

Append one event. Swallows I/O errors so audit never breaks the agent.

Source code in src/dashscope_agenticx/audit.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
def log(self, event: AuditEvent) -> None:
    """Append one event. Swallows I/O errors so audit never breaks
    the agent."""
    try:
        self._path.parent.mkdir(parents=True, exist_ok=True)
        record = asdict(event)
        if self._privacy_mode:
            record["details"] = _redact_args(record.get("details", {}))
            if record.get("source") == "user":
                record["subject"] = _redact_text(record.get("subject", ""))
        with self._path.open("a", encoding="utf-8") as f:
            f.write(
                json.dumps(record, ensure_ascii=False, default=str) + "\n",
            )
    except Exception:
        pass  # audit must never break the agent loop

log_user_input

log_user_input(text: str, preview_len: int = 100) -> None
Source code in src/dashscope_agenticx/audit.py
141
142
143
def log_user_input(self, text: str, preview_len: int = 100) -> None:
    preview = text[:preview_len] + ("…" if len(text) > preview_len else "")
    self.log(AuditEvent.now("user", "input", preview, "received"))

log_tool_call

log_tool_call(
    tool_name: str,
    args: dict[str, Any],
    decision: str,
    reason: str = "",
) -> None
Source code in src/dashscope_agenticx/audit.py
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
def log_tool_call(
    self,
    tool_name: str,
    args: dict[str, Any],
    decision: str,
    reason: str = "",
) -> None:
    self.log(
        AuditEvent.now(
            "agent",
            "tool_call",
            tool_name,
            decision,
            reason,
            **args,
        ),
    )

log_cron

log_cron(
    job_id: str, decision: str, reason: str = ""
) -> None
Source code in src/dashscope_agenticx/audit.py
163
164
def log_cron(self, job_id: str, decision: str, reason: str = "") -> None:
    self.log(AuditEvent.now("scheduler", "cron", job_id, decision, reason))

query

query(
    source: str | None = None,
    action: str | None = None,
    subject: str | None = None,
    decision: str | None = None,
    limit: int = 50,
) -> list[dict[str, Any]]

Read back events matching the given filters.

Source code in src/dashscope_agenticx/audit.py
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
def query(
    self,
    source: str | None = None,
    action: str | None = None,
    subject: str | None = None,
    decision: str | None = None,
    limit: int = 50,
) -> list[dict[str, Any]]:
    """Read back events matching the given filters."""
    if not self._path.exists():
        return []
    results: list[dict[str, Any]] = []
    try:
        with self._path.open("r", encoding="utf-8") as f:
            for line in f:
                line = line.strip()
                if not line:
                    continue
                try:
                    record = json.loads(line)
                except json.JSONDecodeError:
                    continue
                if source and record.get("source") != source:
                    continue
                if action and record.get("action") != action:
                    continue
                if subject and record.get("subject") != subject:
                    continue
                if decision and record.get("decision") != decision:
                    continue
                results.append(record)
                if len(results) >= limit:
                    break
    except Exception:
        pass  # unreadable log file → empty result, query must not raise
    return results

recent

recent(limit: int = 20) -> list[dict[str, Any]]

Return the last N events (tail of the log).

Source code in src/dashscope_agenticx/audit.py
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
def recent(self, limit: int = 20) -> list[dict[str, Any]]:
    """Return the last N events (tail of the log)."""
    if not self._path.exists():
        return []
    try:
        lines = self._path.read_text(encoding="utf-8").strip().split("\n")
    except Exception:
        return []
    records: list[dict[str, Any]] = []
    for line in lines[-limit:]:
        line = line.strip()
        if not line:
            continue
        try:
            records.append(json.loads(line))
        except json.JSONDecodeError:
            continue
    return records

clear

clear() -> None
Source code in src/dashscope_agenticx/audit.py
222
223
224
225
226
def clear(self) -> None:
    try:
        self._path.unlink(missing_ok=True)
    except Exception:
        pass  # best-effort: a locked/readonly log file is not fatal

get_audit_logger

get_audit_logger() -> AuditLogger
Source code in src/dashscope_agenticx/audit.py
234
235
def get_audit_logger() -> AuditLogger:
    return _logger

configure_audit_logger

configure_audit_logger(config) -> AuditLogger

Wire config settings into the global audit logger at startup.

Re-arms privacy redaction after a restart: the logger is constructed at import time with privacy off, so without this the persisted privacy_mode = true would not redact until the user re-ran /privacy on.

Source code in src/dashscope_agenticx/audit.py
243
244
245
246
247
248
249
250
251
252
def configure_audit_logger(config) -> AuditLogger:
    """Wire config settings into the global audit logger at startup.

    Re-arms privacy redaction after a restart: the logger is constructed at
    import time with privacy off, so without this the persisted
    ``privacy_mode = true`` would not redact until the user re-ran
    ``/privacy on``.
    """
    _logger.set_privacy_mode(bool(getattr(config, "privacy_mode", False)))
    return _logger

Hooks

Hook

Hook(event: str, spec: dict[str, Any])

A single hook rule loaded from hooks.toml.

category distinguishes governance hooks (block/confirm/alert — security-critical, permission/audit/compliance) from plugin hooks (run/warn/log — functional extensions like tool before/after processing). Governance hooks are dispatched first so security decisions take precedence over functional extensions.

Source code in src/dashscope_agenticx/hooks.py
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
def __init__(self, event: str, spec: dict[str, Any]):
    self.event = event
    self.match = spec.get("match", "*")
    self.condition = spec.get("condition")
    self.content_pattern = spec.get("content_pattern")
    self.action = spec.get("action", "run")
    self.run = spec.get("run", "")
    self.message = spec.get("message", "")
    self.silent = spec.get("silent", False)
    self.on_fail = spec.get("on_fail", "warn")  # warn | alert | block
    # Governance hooks (block/confirm/alert) run before plugin hooks
    # (run/warn/log) so security decisions are never bypassed.
    self.category = (
        "governance"
        if self.action in self._GOVERNANCE_ACTIONS
        else "plugin"
    )

event instance-attribute

event = event

match instance-attribute

match = spec.get('match', '*')

condition instance-attribute

condition = spec.get('condition')

content_pattern instance-attribute

content_pattern = spec.get('content_pattern')

action instance-attribute

action = spec.get('action', 'run')

run instance-attribute

run = spec.get('run', '')

message instance-attribute

message = spec.get('message', '')

silent instance-attribute

silent = spec.get('silent', False)

on_fail instance-attribute

on_fail = spec.get('on_fail', 'warn')

category instance-attribute

category = (
    "governance"
    if self.action in self._GOVERNANCE_ACTIONS
    else "plugin"
)

applies_to

applies_to(ctx: HookContext) -> bool
Source code in src/dashscope_agenticx/hooks.py
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
def applies_to(self, ctx: HookContext) -> bool:
    if self.event != ctx.event:
        return False
    if self.match != "*" and not fnmatch.fnmatch(
        ctx.tool_name,
        self.match,
    ):
        return False
    if self.condition:
        path = _resolve_path(ctx.arguments)
        if not _match_condition(self.condition, path):
            return False
    if self.content_pattern:
        text = ""
        if ctx.event == "on_error":
            text = ctx.result or ""
        elif ctx.event == "on_response":
            # The reply body is passed via arguments["content"] (result
            # stays unset); fall back to result for direct dispatchers.
            content = ctx.arguments.get("content")
            text = ctx.result or (
                content if isinstance(content, str) else ""
            )
        elif ctx.event == "on_message":
            # The user message is passed via arguments["input"].
            content = ctx.arguments.get("input")
            text = content if isinstance(content, str) else ""
        elif ctx.event in ("before_tool_call", "after_tool_call"):
            text = json.dumps(ctx.arguments, ensure_ascii=False)
        if not fnmatch.fnmatch(text, self.content_pattern):
            return False
    return True

execute

execute(ctx: HookContext) -> HookActionResult
Source code in src/dashscope_agenticx/hooks.py
440
441
442
443
444
445
446
447
448
449
450
451
452
453
def execute(self, ctx: HookContext) -> HookActionResult:
    variables = _build_variables(ctx)
    simple = self._execute_simple(ctx, variables)
    if simple is not None:
        return simple

    if self.action == "run":
        if not self.run:
            return HookActionResult()
        code, stdout, stderr = _run_shell(self.run, variables)
        return self._run_command_result(code, stdout, stderr)

    # Unknown action — no-op
    return HookActionResult()

execute_async async

execute_async(ctx: HookContext) -> HookActionResult

Async variant of execute: run-actions await an asyncio subprocess instead of blocking the event loop for up to the hook timeout.

Source code in src/dashscope_agenticx/hooks.py
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
async def execute_async(self, ctx: HookContext) -> HookActionResult:
    """Async variant of execute: run-actions await an asyncio subprocess
    instead of blocking the event loop for up to the hook timeout."""
    variables = _build_variables(ctx)
    simple = self._execute_simple(ctx, variables)
    if simple is not None:
        return simple

    if self.action == "run":
        if not self.run:
            return HookActionResult()
        code, stdout, stderr = await _run_shell_async(self.run, variables)
        return self._run_command_result(code, stdout, stderr)

    # Unknown action — no-op
    return HookActionResult()

HookBus

HookBus(hooks_file: Path | None = None)

Central event bus for hooks.

Source code in src/dashscope_agenticx/hooks.py
476
477
478
def __init__(self, hooks_file: Path | None = None):
    self.hooks: list[Hook] = []
    self._load_hooks(hooks_file or WORKSPACE_DIR / "hooks.toml")

hooks instance-attribute

hooks: list[Hook] = []

register

register(hook: Hook) -> None
Source code in src/dashscope_agenticx/hooks.py
492
493
def register(self, hook: Hook) -> None:
    self.hooks.append(hook)

unregister

unregister(hook: Hook) -> None

Remove a previously registered hook (by identity).

Source code in src/dashscope_agenticx/hooks.py
495
496
497
def unregister(self, hook: Hook) -> None:
    """Remove a previously registered hook (by identity)."""
    self.hooks = [h for h in self.hooks if h is not hook]

dispatch

dispatch(ctx: HookContext) -> HookDispatchResult
Source code in src/dashscope_agenticx/hooks.py
499
500
501
502
503
504
505
506
507
508
509
510
511
def dispatch(self, ctx: HookContext) -> HookDispatchResult:
    result = HookDispatchResult()
    # Governance hooks (block/confirm/alert) run before plugin hooks
    # (run/warn/log) so security decisions are never bypassed by a
    # functional extension.
    applicable = [h for h in self.hooks if h.applies_to(ctx)]
    applicable.sort(key=lambda h: 0 if h.category == "governance" else 1)
    for hook in applicable:
        result.merge(hook.execute(ctx))
        # Stop at first block
        if result.blocked:
            break
    return result

dispatch_async async

dispatch_async(ctx: HookContext) -> HookDispatchResult

Async variant of dispatch — identical ordering/semantics, but command hooks run as awaited asyncio subprocesses so the event loop is not blocked.

Source code in src/dashscope_agenticx/hooks.py
513
514
515
516
517
518
519
520
521
522
523
524
525
async def dispatch_async(self, ctx: HookContext) -> HookDispatchResult:
    """Async variant of dispatch — identical ordering/semantics, but
    command hooks run as awaited asyncio subprocesses so the event loop
    is not blocked."""
    result = HookDispatchResult()
    applicable = [h for h in self.hooks if h.applies_to(ctx)]
    applicable.sort(key=lambda h: 0 if h.category == "governance" else 1)
    for hook in applicable:
        result.merge(await hook.execute_async(ctx))
        # Stop at first block
        if result.blocked:
            break
    return result

HookContext dataclass

HookContext(
    event: str,
    tool_name: str,
    arguments: dict[str, Any] = dict(),
    result: str | None = None,
    success: bool | None = None,
)

Context passed to every hook callback.

event instance-attribute

event: str

tool_name instance-attribute

tool_name: str

arguments class-attribute instance-attribute

arguments: dict[str, Any] = field(default_factory=dict)

result class-attribute instance-attribute

result: str | None = None

success class-attribute instance-attribute

success: bool | None = None

HookActionResult dataclass

HookActionResult(
    blocked: bool = False,
    confirm: bool = False,
    warning: str = "",
    alert: str = "",
    log: str = "",
    output: str = "",
    error: str = "",
)

Result of a single hook action.

blocked class-attribute instance-attribute

blocked: bool = False

confirm class-attribute instance-attribute

confirm: bool = False

warning class-attribute instance-attribute

warning: str = ''

alert class-attribute instance-attribute

alert: str = ''

log class-attribute instance-attribute

log: str = ''

output class-attribute instance-attribute

output: str = ''

error class-attribute instance-attribute

error: str = ''

HookDispatchResult dataclass

HookDispatchResult(
    blocked: bool = False,
    confirm: bool = False,
    warnings: list[str] = list(),
    alerts: list[str] = list(),
    logs: list[str] = list(),
    outputs: list[str] = list(),
)

Aggregated result of dispatching an event to all matching hooks.

blocked class-attribute instance-attribute

blocked: bool = False

confirm class-attribute instance-attribute

confirm: bool = False

warnings class-attribute instance-attribute

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

alerts class-attribute instance-attribute

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

logs class-attribute instance-attribute

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

outputs class-attribute instance-attribute

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

merge

merge(action: HookActionResult) -> None
Source code in src/dashscope_agenticx/hooks.py
70
71
72
73
74
75
76
77
78
79
80
def merge(self, action: HookActionResult) -> None:
    self.blocked = self.blocked or action.blocked
    self.confirm = self.confirm or action.confirm
    if action.warning:
        self.warnings.append(action.warning)
    if action.alert:
        self.alerts.append(action.alert)
    if action.log:
        self.logs.append(action.log)
    if action.output:
        self.outputs.append(action.output)

create_hook_bus

create_hook_bus(hooks_file: Path | None = None) -> HookBus
Source code in src/dashscope_agenticx/hooks.py
528
529
def create_hook_bus(hooks_file: Path | None = None) -> HookBus:
    return HookBus(hooks_file)

Scheduling

Scheduler

Scheduler(config, agent)
Source code in src/dashscope_agenticx/scheduler.py
292
293
294
295
296
297
def __init__(self, config, agent):
    self.config = config
    self.agent = agent
    self.jobs: dict[str, CronJob] = {}
    self._tasks: dict[str, asyncio.Task] = {}
    self._pending_prompts: list[str] = []

config instance-attribute

config = config

agent instance-attribute

agent = agent

jobs instance-attribute

jobs: dict[str, CronJob] = {}

load_and_start async

load_and_start() -> None
Source code in src/dashscope_agenticx/scheduler.py
299
300
301
302
303
304
305
306
307
308
309
310
async def load_and_start(self) -> None:
    if _PERSIST_PATH.exists():
        try:
            data = json.loads(_PERSIST_PATH.read_text(encoding="utf-8"))
            for jid, jd in data.items():
                self.jobs[jid] = CronJob.from_dict(jd)
        except (json.JSONDecodeError, KeyError):
            pass

    for jid, job in self.jobs.items():
        if job.enabled:
            self._start_job_task(jid)

shutdown async

shutdown() -> None
Source code in src/dashscope_agenticx/scheduler.py
312
313
314
315
316
317
async def shutdown(self) -> None:
    for task in self._tasks.values():
        task.cancel()
    if self._tasks:
        await asyncio.gather(*self._tasks.values(), return_exceptions=True)
    self._tasks.clear()

add_job

add_job(
    schedule: ScheduleSpec,
    skills: list[SkillInvocation],
    condition: str | None,
    subagent: bool,
) -> CronJob
Source code in src/dashscope_agenticx/scheduler.py
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
def add_job(
    self,
    schedule: ScheduleSpec,
    skills: list[SkillInvocation],
    condition: str | None,
    subagent: bool,
) -> CronJob:
    job = CronJob(
        id=secrets.token_hex(3),
        schedule=schedule,
        skills=skills,
        condition=condition,
        subagent=subagent,
        enabled=True,
        created_at=datetime.now().isoformat(),
    )
    self.jobs[job.id] = job
    self._persist()
    self._start_job_task(job.id)
    return job

remove_job

remove_job(job_id: str) -> bool
Source code in src/dashscope_agenticx/scheduler.py
340
341
342
343
344
345
346
347
348
def remove_job(self, job_id: str) -> bool:
    if job_id not in self.jobs:
        return False
    task = self._tasks.pop(job_id, None)
    if task:
        task.cancel()
    del self.jobs[job_id]
    self._persist()
    return True

pause_job

pause_job(job_id: str) -> bool
Source code in src/dashscope_agenticx/scheduler.py
350
351
352
353
354
355
356
357
358
def pause_job(self, job_id: str) -> bool:
    if job_id not in self.jobs:
        return False
    self.jobs[job_id].enabled = False
    task = self._tasks.pop(job_id, None)
    if task:
        task.cancel()
    self._persist()
    return True

resume_job

resume_job(job_id: str) -> bool
Source code in src/dashscope_agenticx/scheduler.py
360
361
362
363
364
365
366
def resume_job(self, job_id: str) -> bool:
    if job_id not in self.jobs:
        return False
    self.jobs[job_id].enabled = True
    self._start_job_task(job_id)
    self._persist()
    return True

get_pending_prompts

get_pending_prompts() -> list[str]
Source code in src/dashscope_agenticx/scheduler.py
368
369
370
371
def get_pending_prompts(self) -> list[str]:
    prompts = self._pending_prompts[:]
    self._pending_prompts.clear()
    return prompts

print_jobs

print_jobs() -> None
Source code in src/dashscope_agenticx/scheduler.py
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
def print_jobs(self) -> None:
    if not self.jobs:
        console.print("[dim]No scheduled jobs[/dim]")
        console.print(
            "[dim]Usage: /cron add every 5m skill "
            "weather Hangzhou[/dim]",
        )
        return

    console.print("[bold]📋 Scheduled jobs[/bold]")
    for job in self.jobs.values():
        status = (
            "[green]running[/green]"
            if job.enabled
            else "[yellow]paused[/yellow]"
        )
        skill_names = ", ".join(s.name for s in job.skills)
        console.print(f"  [{job.id}] {status}  {job.schedule.raw}")
        console.print(f"    skills: {skill_names}")
        if job.condition:
            console.print(f"    condition: {job.condition}")
        if job.last_run:
            console.print(f"    last run: {job.last_run}")
        if job.last_result:
            result_preview = job.last_result[:80].replace("\n", " ")
            console.print(f"    result: {result_preview}...")
        console.print(f"    runs: {job.run_count}")
        console.print()

CronJob dataclass

CronJob(
    id: str,
    schedule: ScheduleSpec,
    skills: list[SkillInvocation],
    condition: str | None = None,
    subagent: bool = True,
    enabled: bool = True,
    created_at: str = "",
    last_run: str | None = None,
    last_result: str | None = None,
    run_count: int = 0,
)

id instance-attribute

id: str

schedule instance-attribute

schedule: ScheduleSpec

skills instance-attribute

skills: list[SkillInvocation]

condition class-attribute instance-attribute

condition: str | None = None

subagent class-attribute instance-attribute

subagent: bool = True

enabled class-attribute instance-attribute

enabled: bool = True

created_at class-attribute instance-attribute

created_at: str = ''

last_run class-attribute instance-attribute

last_run: str | None = None

last_result class-attribute instance-attribute

last_result: str | None = None

run_count class-attribute instance-attribute

run_count: int = 0

to_dict

to_dict() -> dict
Source code in src/dashscope_agenticx/scheduler.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
def to_dict(self) -> dict:
    return {
        "id": self.id,
        "schedule": self.schedule.to_dict(),
        "skills": [s.to_dict() for s in self.skills],
        "condition": self.condition,
        "subagent": self.subagent,
        "enabled": self.enabled,
        "created_at": self.created_at,
        "last_run": self.last_run,
        "last_result": self.last_result,
        "run_count": self.run_count,
    }

from_dict classmethod

from_dict(d: dict) -> CronJob
Source code in src/dashscope_agenticx/scheduler.py
104
105
106
107
108
109
110
111
112
113
114
115
116
117
@classmethod
def from_dict(cls, d: dict) -> CronJob:
    return cls(
        id=d["id"],
        schedule=ScheduleSpec.from_dict(d["schedule"]),
        skills=[SkillInvocation.from_dict(s) for s in d["skills"]],
        condition=d.get("condition"),
        subagent=d.get("subagent", True),
        enabled=d.get("enabled", True),
        created_at=d.get("created_at", ""),
        last_run=d.get("last_run"),
        last_result=d.get("last_result"),
        run_count=d.get("run_count", 0),
    )

ScheduleSpec dataclass

ScheduleSpec(
    kind: str,
    raw: str,
    interval_seconds: float | None = None,
    at_datetime: str | None = None,
    cron_fields: list[str] | None = None,
)

kind instance-attribute

kind: str

raw instance-attribute

raw: str

interval_seconds class-attribute instance-attribute

interval_seconds: float | None = None

at_datetime class-attribute instance-attribute

at_datetime: str | None = None

cron_fields class-attribute instance-attribute

cron_fields: list[str] | None = None

to_dict

to_dict() -> dict
Source code in src/dashscope_agenticx/scheduler.py
57
58
59
60
61
62
63
64
def to_dict(self) -> dict:
    return {
        "kind": self.kind,
        "raw": self.raw,
        "interval_seconds": self.interval_seconds,
        "at_datetime": self.at_datetime,
        "cron_fields": self.cron_fields,
    }

from_dict classmethod

from_dict(d: dict) -> ScheduleSpec
Source code in src/dashscope_agenticx/scheduler.py
66
67
68
69
70
71
72
73
74
@classmethod
def from_dict(cls, d: dict) -> ScheduleSpec:
    return cls(
        kind=d["kind"],
        raw=d["raw"],
        interval_seconds=d.get("interval_seconds"),
        at_datetime=d.get("at_datetime"),
        cron_fields=d.get("cron_fields"),
    )

SkillInvocation dataclass

SkillInvocation(name: str, args: list[str] = list())

name instance-attribute

name: str

args class-attribute instance-attribute

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

to_dict

to_dict() -> dict
Source code in src/dashscope_agenticx/scheduler.py
41
42
def to_dict(self) -> dict:
    return {"name": self.name, "args": self.args}

from_dict classmethod

from_dict(d: dict) -> SkillInvocation
Source code in src/dashscope_agenticx/scheduler.py
44
45
46
@classmethod
def from_dict(cls, d: dict) -> SkillInvocation:
    return cls(name=d["name"], args=d.get("args", []))

parse_cron_add

parse_cron_add(
    args_str: str,
) -> tuple[
    ScheduleSpec, list[SkillInvocation], str | None, bool
]
Source code in src/dashscope_agenticx/scheduler.py
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
def parse_cron_add(
    args_str: str,
) -> tuple[ScheduleSpec, list[SkillInvocation], str | None, bool]:
    tokens = shlex.split(args_str, posix=os.name != "nt")

    schedule: ScheduleSpec | None = None
    skills: list[SkillInvocation] = []
    condition: str | None = None
    subagent: bool = True

    i = 0
    while i < len(tokens):
        tok = tokens[i]
        if tok in ("every", "at", "cron"):
            if i + 1 >= len(tokens):
                raise ValueError(f"{tok} requires an argument")
            val = tokens[i + 1]
            if tok == "every":
                secs = parse_interval(val)
                schedule = ScheduleSpec(
                    kind="interval",
                    raw=f"every {val}",
                    interval_seconds=secs,
                )
            elif tok == "at":
                dt = parse_at_time(val)
                schedule = ScheduleSpec(
                    kind="at",
                    raw=f"at {val}",
                    at_datetime=dt.isoformat(),
                )
            elif tok == "cron":
                parts = val.strip().split()
                if len(parts) != 5:
                    raise ValueError(f"cron expression needs 5 fields: {val}")
                schedule = ScheduleSpec(
                    kind="cron",
                    raw=f"cron {val}",
                    cron_fields=parts,
                )
            i += 2
        elif tok == "condition":
            if i + 1 >= len(tokens):
                raise ValueError("condition requires an argument")
            condition = tokens[i + 1]
            i += 2
        elif tok == "no-subagent":
            subagent = False
            i += 1
        elif tok == "skill":
            i += 1
            if i >= len(tokens):
                raise ValueError("skill requires a skill name")
            name = tokens[i]
            i += 1
            skill_args: list[str] = []
            while i < len(tokens) and tokens[i] not in (
                "skill",
                "every",
                "at",
                "cron",
                "condition",
                "no-subagent",
            ):
                skill_args.append(tokens[i])
                i += 1
            skills.append(SkillInvocation(name, skill_args))
        else:
            raise ValueError(f"unknown argument: {tok}")

    if not schedule:
        raise ValueError("a schedule is required: every, at, or cron")
    if not skills:
        raise ValueError("at least one skill is required")

    return schedule, skills, condition, subagent

next_cron_fire

next_cron_fire(
    fields: list[str], after: datetime
) -> datetime | None
Source code in src/dashscope_agenticx/scheduler.py
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
def next_cron_fire(fields: list[str], after: datetime) -> datetime | None:
    minutes = sorted(_parse_cron_field(fields[0], 0, 59))
    hours = sorted(_parse_cron_field(fields[1], 0, 23))
    doms = _parse_cron_field(fields[2], 1, 31)
    months = _parse_cron_field(fields[3], 1, 12)
    dows = _expand_dow(fields[4])

    earliest = after.replace(second=0, microsecond=0) + timedelta(minutes=1)
    day = earliest
    # Scan day-by-day (not minute-by-minute) so sparse crons don't block the
    # event loop. 9 years covers the longest Feb-29 gap (2096 → 2104).
    for _ in range(366 * 9):
        if day.month in months and day.day in doms and day.weekday() in dows:
            for hour in hours:
                for minute in minutes:
                    candidate = day.replace(hour=hour, minute=minute)
                    if candidate >= earliest:
                        return candidate
        day = (day + timedelta(days=1)).replace(hour=0, minute=0)
    return None

Execution kernel

ModelInvoker

Own provider streaming, retry, usage, and LLM trace bookkeeping.

invoke async

invoke(
    agent: Any,
    request_messages: list[dict],
    tools_schema: list[dict],
    *,
    hint: str = "",
    hint_chars: dict[str, int] | None = None
) -> AsyncIterator[ModelDelta | ModelInvocation]
Source code in src/dashscope_agenticx/engine.py
 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
async def invoke(
    self,
    agent: Any,
    request_messages: list[dict],
    tools_schema: list[dict],
    *,
    hint: str = "",
    hint_chars: dict[str, int] | None = None,
) -> AsyncIterator[ModelDelta | ModelInvocation]:
    full_content = ""
    full_reasoning = ""
    tool_calls: list[ToolCall] = []
    seen_tool_calls: set[tuple[str, str]] = set()
    last_chunk: LLMChunk | None = None
    finish_reason = ""
    llm_start = time.monotonic()
    turn_attempt = 0

    while True:
        emitted = False
        try:
            async for chunk in agent.provider.chat_stream(
                normalize_for_model(request_messages, agent.model_name),
                tools_schema,
                response_format=(
                    {"type": "json_object"} if agent.json_mode else None
                ),
            ):
                if chunk.delta_content:
                    emitted = True
                    full_content += chunk.delta_content
                    yield ModelDelta(chunk.delta_content)
                if chunk.delta_reasoning_content:
                    full_reasoning += chunk.delta_reasoning_content
                    agent._emit_event(
                        AgentEventType.REASONING_DELTA,
                        {"text": chunk.delta_reasoning_content},
                    )
                if chunk.tool_calls:
                    emitted = True
                    for tool_call in chunk.tool_calls:
                        tool_call = self._normalize_tool_call(
                            agent,
                            tool_call,
                        )
                        key = (
                            tool_call.name,
                            json.dumps(
                                tool_call.arguments,
                                sort_keys=True,
                                ensure_ascii=False,
                            ),
                        )
                        if key in seen_tool_calls:
                            continue
                        seen_tool_calls.add(key)
                        tool_calls.append(tool_call)
                if chunk.usage:
                    agent._emit_event(  # pylint: disable=protected-access
                        AgentEventType.USAGE_UPDATED,
                        dict(chunk.usage),
                    )
                    last_chunk = chunk
                if chunk.finish_reason:
                    finish_reason = chunk.finish_reason
            break
        except Exception as exc:
            if (
                not emitted
                and is_retryable_error(exc)
                and turn_attempt < agent.turn_retry_max
                and not _budget_burned_slowly(exc)
            ):
                turn_attempt += 1
                full_content = ""
                full_reasoning = ""
                tool_calls = []
                seen_tool_calls = set()
                last_chunk = None
                finish_reason = ""
                await asyncio.sleep(
                    min(
                        agent.turn_retry_delay * (2 ** (turn_attempt - 1)),
                        agent.turn_retry_backoff_cap,
                    ),
                )
                continue
            if emitted and is_retryable_error(exc):
                warning = (
                    f"\n[Stream interrupted ({exc}); continuing with "
                    "the partial response]\n"
                )
                yield ModelDelta(warning)
                break
            raise

    agent.executor.record_api_call(
        last_chunk.usage if last_chunk and last_chunk.usage else None,
    )
    prompt_stats = agent.executor.record_prompt_composition(
        request_messages,
        tools_schema,
    )
    prompt_stats["est_prompt_tokens"] = estimate_message_tokens(
        request_messages,
    ) + estimate_tokens(json.dumps(tools_schema, ensure_ascii=False))
    if hint_chars:
        prompt_stats["hint_chars"] = hint_chars
    prompt_stats["prefix_chars"] = (
        prompt_stats["system_chars"]
        + prompt_stats["user_chars"]
        + prompt_stats["assistant_chars"]
        + prompt_stats["tool_result_chars"]
        + prompt_stats["tool_call_args_chars"]
        + prompt_stats["tools_schema_chars"]
        - len(hint)
    )
    usage = last_chunk.usage if last_chunk and last_chunk.usage else None
    agent.trace_logger.log_llm_call(
        messages=request_messages,
        tools=tools_schema,
        response={
            "content": full_content,
            "tool_calls": [
                {"name": call.name, "arguments": call.arguments}
                for call in tool_calls
            ],
            "usage": usage,
        },
        duration_ms=int((time.monotonic() - llm_start) * 1000),
        model=agent.model_name,
        prompt_stats=prompt_stats,
    )
    yield ModelInvocation(
        content=full_content,
        reasoning_content=full_reasoning,
        tool_calls=tool_calls,
        finish_reason=finish_reason,
        usage=usage,
    )

RunGuards

RunGuards()

Build volatile loop hints and enforce non-provider run limits.

Source code in src/dashscope_agenticx/engine.py
226
227
228
def __init__(self):
    self.reflection = None
    self.stagnation = None

reflection instance-attribute

reflection = None

stagnation instance-attribute

stagnation = None

bind

bind(reflection, stagnation) -> None

Own the per-run guard trackers exposed by compatibility memory.

Source code in src/dashscope_agenticx/engine.py
230
231
232
233
def bind(self, reflection, stagnation) -> None:
    """Own the per-run guard trackers exposed by compatibility memory."""
    self.reflection = reflection
    self.stagnation = stagnation

build_hint

build_hint(
    agent: Any, loop_index: int
) -> tuple[str, dict[str, int]]
Source code in src/dashscope_agenticx/engine.py
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
def build_hint(
    self,
    agent: Any,
    loop_index: int,
) -> tuple[str, dict[str, int]]:
    parts = {
        "reflection": agent._reflection_section(),
        "stagnation": agent._stagnation_section(),
        "convergence": agent._convergence_section(loop_index),
        "time_budget": agent._time_budget_section(),
        "compression": agent._compression_section(),
        "silence": agent._silence_section(),
    }
    return (
        "".join(parts.values()).strip(),
        {name: len(value) for name, value in parts.items() if value},
    )

readonly_stop

readonly_stop(agent: Any) -> str
Source code in src/dashscope_agenticx/engine.py
253
254
255
256
257
258
259
260
261
262
263
264
265
def readonly_stop(self, agent: Any) -> str:
    if (
        agent.oneshot
        and agent.readonly_hard_cap
        and self.stagnation is not None
        and self.stagnation.readonly_streak >= agent.readonly_hard_cap
    ):
        return (
            f"\n[Stopped: {agent.readonly_hard_cap} consecutive "
            "read-only tool calls with no progress. Ending the run "
            "to avoid an infinite verification loop.]\n"
        )
    return ""

ToolCoordinator

Coordinate calls while preserving assistant/tool message pairing.

execute async

execute(
    agent: Any,
    tool_calls: list[ToolCall],
    messages_with_system: list[dict],
) -> ToolBatchResult
Source code in src/dashscope_agenticx/engine.py
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
async def execute(
    self,
    agent: Any,
    tool_calls: list[ToolCall],
    messages_with_system: list[dict],
) -> ToolBatchResult:
    result = ToolBatchResult()
    any_needs_confirm = any(
        agent._needs_confirmation(call) for call in tool_calls
    )
    if len(tool_calls) > 1 and not any_needs_confirm:
        values = await asyncio.gather(
            *[agent._execute_tool(call) for call in tool_calls],
            return_exceptions=True,
        )
        supplement_info = None
        aborted: UserAbortedTurn | None = None
        for tool_call, value in zip(tool_calls, values):
            if isinstance(value, UserAbortedTurn):
                aborted = aborted or value
                value = "Cancelled (user aborted this turn)"
            elif isinstance(value, UserSupplement):
                supplement_info = value.supplement
                value = "Cancelled (user added info to replan)"
            elif isinstance(value, Exception):
                value = f"Error: {value}"

            result.output.append(
                ToolDisplayText(
                    f"\n[{tool_call.name}] →\n"
                    f"{tool_result_for_display(tool_call.name, value)}\n",
                    tool_call.id,
                    tool_call.name,
                ),
            )
            tool_msg = agent._tool_message(tool_call, value)
            agent.messages.append(tool_msg)
            messages_with_system.append(tool_msg)

        if aborted:
            raise aborted
        if supplement_info:
            supplement_msg = {
                "role": "user",
                "content": (
                    f"[User supplement]: {supplement_info}\n"
                    "Replan with the new info and continue."
                ),
            }
            agent.messages.append(supplement_msg)
            messages_with_system.append(supplement_msg)
            result.replan = True
        return result

    answered_ids: set[str] = set()
    try:
        for tool_call in tool_calls:
            value = await agent._execute_tool(tool_call)
            rendered = tool_result_for_display(tool_call.name, value)
            result.output.append(
                ToolDisplayText(
                    f"\n[{tool_call.name}] →\n{rendered}\n",
                    tool_call.id,
                    tool_call.name,
                ),
            )
            tool_msg = agent._tool_message(tool_call, value)
            agent.messages.append(tool_msg)
            messages_with_system.append(tool_msg)
            answered_ids.add(tool_call.id)
    except UserSupplement as exc:
        agent._close_pending_tool_calls(
            tool_calls,
            answered_ids,
            messages_with_system,
        )
        supplement_text = (
            f"[User supplement]: {exc.supplement}\n"
            "Replan with the new info and continue."
        )
        result.output.append(f"\n{supplement_text}\n")
        supplement_msg = {"role": "user", "content": supplement_text}
        agent.messages.append(supplement_msg)
        messages_with_system.append(supplement_msg)
        result.replan = True
    except UserAbortedTurn:
        agent._close_pending_tool_calls(
            tool_calls,
            answered_ids,
            messages_with_system,
            reason="Cancelled (user aborted this turn)",
        )
        raise
    return result

SessionPersistence

Commit completed turn projections, memory, and learned experience.

finalize async

finalize(
    agent: Any, user_input: Any, last_content: str
) -> None
Source code in src/dashscope_agenticx/engine.py
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
421
422
423
424
425
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
async def finalize(
    self,
    agent: Any,
    user_input: Any,
    last_content: str,
) -> None:
    if agent.session_path is not None:
        try:
            turn_topic = agent.session_path.parent.name
            outcome = ""
            if agent._current_turn_tools:
                outcome = agent._classify_outcome(
                    agent._turn_tool_successes,
                    agent._turn_tool_failures,
                )
            agent.session_manager.record_turn_event(
                user_text=text_of(user_input),
                assistant_text=last_content,
                tools_used=agent._current_turn_tools,
                outcome=outcome,
                topic=turn_topic,
                identifiers=dict(agent._event_context),
            )
            agent.session_manager.record_messages_snapshot(
                agent.messages,
                topic=turn_topic,
                identifiers=dict(agent._event_context),
            )
        except Exception:
            pass

    agent.save_session()
    if last_content:
        await agent._store_memory(
            [
                {"role": "user", "content": text_of(user_input)},
                {"role": "assistant", "content": last_content},
            ],
        )
    if not agent._current_turn_tools:
        return
    task_summary = truncate(" ".join(text_of(user_input).split()), 100)
    outcome = agent._classify_outcome(
        agent._turn_tool_successes,
        agent._turn_tool_failures,
    )
    agent.memory_manager.record_experience(
        task_summary=task_summary,
        tools_used=agent._current_turn_tools,
        outcome=outcome,
        verified=outcome in {"success", "failure"},
    )
    if outcome != "success":
        return

    import os

    if os.environ.get("AGENTICX_EXPERIMENTAL_LEARNING", "") != "1":
        return

    from dashscope_agenticx.memory.directives_learning import (
        _load_patterns,
        analyze_patterns,
        propose_directive,
        record_tool_sequence,
    )

    record_tool_sequence(agent._current_turn_tools)
    try:
        seq_count = len(_load_patterns().get("sequences", []))
        if seq_count >= 5 and seq_count % 5 == 0:
            for proposal in analyze_patterns():
                propose_directive(
                    proposal["directive"],
                    proposal["pattern"],
                )
    except Exception:
        pass

Executor

Executor(
    auto_approve: bool = False, confirm_mode: str = "all"
)
Source code in src/dashscope_agenticx/executor.py
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
def __init__(
    self,
    auto_approve: bool = False,
    confirm_mode: str = "all",
):
    self.auto_approve = auto_approve
    # "all": CONFIRM and DANGEROUS both prompt; "dangerous": only
    # DANGEROUS prompts (CONFIRM-level tools auto-pass).
    self.confirm_mode = confirm_mode
    # Trust cache scoped to ONE conversation turn (a single user prompt
    # plus the agent loop that answers it). Agent.run / run_stream clear
    # these in a finally block on completion or abort. DANGEROUS tools
    # never enter _always_allow (see _check_permission below).
    self._always_allow: set[str] = set()
    self._always_deny: set[str] = set()
    # run_command grants live here keyed by the exact command, not in
    # _always_allow keyed by tool name. Approving one `ls` must not turn
    # into unprompted approval of every later shell command in the turn.
    self._always_allow_commands: set[str] = set()
    # Optional async callback for TUI mode confirmation
    self._confirm_callback = None
    # Structured runtime observer. It is deliberately synchronous: event
    # sinks enqueue metadata and must never block a permission decision.
    self._permission_observer: Callable[[str, dict], None] | None = None

    # Usage stats
    self._session_start_time: float = time.time()
    self._tool_call_counts: dict[str, int] = {}
    self._total_tool_calls: int = 0
    self._skill_calls: int = 0
    self._skill_counts: dict[str, int] = {}
    self._api_calls: int = 0
    self._usage_calls: int = 0
    self._token_usage: dict[str, int] = {
        "input_tokens": 0,
        "output_tokens": 0,
        "total_tokens": 0,
        "cached_tokens": 0,
    }
    self._prompt_composition: dict[str, int] = {
        "system": 0,
        "user": 0,
        "assistant": 0,
        "tools": 0,
    }
    self._prompt_details: dict[str, int] = {
        "tool_result_chars": 0,
        "tool_call_args_chars": 0,
        "tools_schema_chars": 0,
    }
    self._errors: int = 0

auto_approve instance-attribute

auto_approve = auto_approve

confirm_mode instance-attribute

confirm_mode = confirm_mode

fork_for_child

fork_for_child() -> 'Executor'

Keep child authorization caches separate from the parent turn.

Source code in src/dashscope_agenticx/executor.py
244
245
246
247
248
249
250
251
252
def fork_for_child(self) -> "Executor":
    """Keep child authorization caches separate from the parent turn."""
    child = Executor(self.auto_approve, self.confirm_mode)
    vars(child).update(
        _confirm_callback=self._confirm_callback,
        _always_deny=set(self._always_deny),
        _usage_parent=self,
    )
    return child

absorb_child_usage

absorb_child_usage(child: 'Executor') -> None

Account for child work exactly once without importing its grants.

Source code in src/dashscope_agenticx/executor.py
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
def absorb_child_usage(self, child: "Executor") -> None:
    """Account for child work exactly once without importing its grants."""
    if getattr(child, "_usage_parent", None) is not self:
        return
    previous = getattr(child, "_merged_usage", {})
    for name in (
        "_total_tool_calls",
        "_skill_calls",
        "_api_calls",
        "_usage_calls",
        "_errors",
    ):
        value = getattr(child, name)
        setattr(
            self,
            name,
            getattr(self, name) + value - previous.get(name, 0),
        )
        previous[name] = value
    for name in (
        "_tool_call_counts",
        "_skill_counts",
        "_token_usage",
        "_prompt_composition",
        "_prompt_details",
    ):
        target = getattr(self, name)
        earlier = previous.get(name, {})
        for key, value in getattr(child, name).items():
            target[key] = target.get(key, 0) + value - earlier.get(key, 0)
        previous[name] = dict(getattr(child, name))
    vars(child)["_merged_usage"] = previous

clear_session_trust

clear_session_trust() -> None

Called by Agent at the end of each turn to reset trust grants.

Source code in src/dashscope_agenticx/executor.py
287
288
289
290
291
def clear_session_trust(self) -> None:
    """Called by Agent at the end of each turn to reset trust grants."""
    self._always_allow.clear()
    self._always_deny.clear()
    self._always_allow_commands.clear()

set_permission_observer

set_permission_observer(
    observer: Callable[[str, dict], None] | None,
) -> None

Receive permission lifecycle metadata for typed runtime events.

Source code in src/dashscope_agenticx/executor.py
293
294
295
296
297
298
def set_permission_observer(
    self,
    observer: Callable[[str, dict], None] | None,
) -> None:
    """Receive permission lifecycle metadata for typed runtime events."""
    self._permission_observer = observer

trust_snapshot

trust_snapshot() -> tuple[set[str], set[str], set[str]]

Turn-scoped grants as (tools allowed, commands allowed, denied).

Copies, so the /trust handlers can read and report without holding a reference they could mutate behind the executor's back.

Source code in src/dashscope_agenticx/executor.py
310
311
312
313
314
315
316
317
318
319
320
def trust_snapshot(self) -> tuple[set[str], set[str], set[str]]:
    """Turn-scoped grants as (tools allowed, commands allowed, denied).

    Copies, so the ``/trust`` handlers can read and report without
    holding a reference they could mutate behind the executor's back.
    """
    return (
        set(self._always_allow),
        set(self._always_allow_commands),
        set(self._always_deny),
    )

trust_tool

trust_tool(name: str) -> None

Pre-approve a whole tool for this turn. Additive only.

Source code in src/dashscope_agenticx/executor.py
322
323
324
325
def trust_tool(self, name: str) -> None:
    """Pre-approve a whole tool for this turn. Additive only."""
    self._always_deny.discard(name)
    self._always_allow.add(name)

deny_tool

deny_tool(name: str) -> None

Pre-deny a whole tool for this turn. Additive only.

Source code in src/dashscope_agenticx/executor.py
327
328
329
330
def deny_tool(self, name: str) -> None:
    """Pre-deny a whole tool for this turn. Additive only."""
    self._always_allow.discard(name)
    self._always_deny.add(name)

record_api_call

record_api_call(usage: dict | None = None) -> None

Record an API call and its token usage.

Source code in src/dashscope_agenticx/executor.py
362
363
364
365
366
367
368
369
370
def record_api_call(self, usage: dict | None = None) -> None:
    """Record an API call and its token usage."""
    self._api_calls += 1
    if usage:
        self._usage_calls += 1
        self._token_usage["input_tokens"] += usage.get("input_tokens", 0)
        self._token_usage["output_tokens"] += usage.get("output_tokens", 0)
        self._token_usage["total_tokens"] += usage.get("total_tokens", 0)
        self._token_usage["cached_tokens"] += usage.get("cached_tokens", 0)

record_error

record_error() -> None

Record an error occurrence.

Source code in src/dashscope_agenticx/executor.py
372
373
374
def record_error(self) -> None:
    """Record an error occurrence."""
    self._errors += 1

record_skills

record_skills(names: list[str]) -> None

Record skill packages activated for a turn.

Source code in src/dashscope_agenticx/executor.py
376
377
378
379
380
def record_skills(self, names: list[str]) -> None:
    """Record skill packages activated for a turn."""
    for name in names:
        self._skill_calls += 1
        self._skill_counts[name] = self._skill_counts.get(name, 0) + 1

record_prompt_composition

record_prompt_composition(
    messages: list[dict],
    tools_schema: list[dict] | None = None,
) -> dict[str, int]

Accumulate prompt size (chars) by category for one LLM call.

Also returns the per-call breakdown so the trace can persist what this specific request was made of; the accumulator feeding /stats keeps its coarser system/user/assistant/tools buckets.

Source code in src/dashscope_agenticx/executor.py
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
421
422
423
424
425
426
427
def record_prompt_composition(
    self,
    messages: list[dict],
    tools_schema: list[dict] | None = None,
) -> dict[str, int]:
    """Accumulate prompt size (chars) by category for one LLM call.

    Also returns the per-call breakdown so the trace can persist what
    this specific request was made of; the accumulator feeding /stats
    keeps its coarser system/user/assistant/tools buckets.
    """
    per_call = {
        "system_chars": 0,
        "user_chars": 0,
        "assistant_chars": 0,
        "tool_result_chars": 0,
        "tool_call_args_chars": 0,
        "tools_schema_chars": 0,
    }
    for msg in messages:
        role = msg.get("role")
        content = msg.get("content")
        if isinstance(content, str):
            n = len(content)
        elif content:
            n = len(json.dumps(content, ensure_ascii=False))
        else:
            n = 0
        if role in ("system", "user", "assistant"):
            self._prompt_composition[role] += n
            per_call[f"{role}_chars"] += n
        elif role == "tool":
            self._prompt_composition["tools"] += n
            per_call["tool_result_chars"] += n
        if role == "assistant":
            for tc in msg.get("tool_calls") or []:
                args = (tc.get("function") or {}).get("arguments") or ""
                self._prompt_composition["tools"] += len(args)
                per_call["tool_call_args_chars"] += len(args)
    if tools_schema:
        n = len(json.dumps(tools_schema, ensure_ascii=False))
        self._prompt_composition["tools"] += n
        per_call["tools_schema_chars"] += n
    for key in self._prompt_details:
        self._prompt_details[key] += per_call[key]
    return per_call

execute async

execute(tool_def: ToolDefinition, arguments: dict) -> str

Run one tool call and return its text result.

Thin wrapper over :meth:execute_detailed for callers that only need the text, such as the MCP server bridge.

Source code in src/dashscope_agenticx/executor.py
429
430
431
432
433
434
435
436
async def execute(self, tool_def: ToolDefinition, arguments: dict) -> str:
    """Run one tool call and return its text result.

    Thin wrapper over :meth:`execute_detailed` for callers that only need
    the text, such as the MCP server bridge.
    """
    outcome = await self.execute_detailed(tool_def, arguments)
    return outcome.text

execute_detailed async

execute_detailed(
    tool_def: ToolDefinition, arguments: dict
) -> ToolOutcome

Run one tool call and return a structured outcome.

Source code in src/dashscope_agenticx/executor.py
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
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
async def execute_detailed(
    self,
    tool_def: ToolDefinition,
    arguments: dict,
) -> ToolOutcome:
    """Run one tool call and return a structured outcome."""
    # Validate required params BEFORE asking for permission — otherwise
    # the model can emit `{}` and the user is forced to confirm a call
    # that will immediately fail validation anyway.
    arguments = normalize_tool_arguments(tool_def, arguments)
    missing = missing_required_args(tool_def, arguments)
    if missing:
        hint = ""
        if not arguments:
            hint = (
                " The argument object arrived empty: if your previous "
                "response was cut off by the output limit, retry with "
                "smaller arguments instead of the same oversized call."
            )
        return ToolOutcome(
            ok=False,
            text=(
                f"Error: tool {tool_def.name} missing required arguments: "
                f"{', '.join(missing)}. Call again following the schema "
                f"(required: {tool_def.parameters.get('required', [])})."
                f" Received argument keys: {list(arguments)}."
                f"{hint}"
            ),
            signal_kind=SIGNAL_VALIDATION,
        )

    observe_permission = tool_def.permission != PermissionLevel.AUTO
    permission_payload = {
        "tool": tool_def.name,
        "permission": tool_def.permission.value,
        "arguments": arguments,
        "auto_approve": self.auto_approve,
        "confirm_mode": self.confirm_mode,
    }
    if observe_permission:
        self._notify_permission("requested", permission_payload)
    try:
        allowed = await self._async_check_permission(tool_def, arguments)
    except BaseException as exc:
        if observe_permission:
            self._notify_permission(
                "resolved",
                {
                    **permission_payload,
                    "allowed": False,
                    "outcome": "aborted",
                    "error_type": type(exc).__name__,
                },
            )
        raise
    if observe_permission:
        self._notify_permission(
            "resolved",
            {
                **permission_payload,
                "allowed": allowed,
                "outcome": "allowed" if allowed else "denied",
            },
        )
    if not allowed:
        from dashscope_agenticx.audit import get_audit_logger

        get_audit_logger().log_tool_call(
            tool_def.name,
            arguments,
            decision="denied",
            reason="user declined",
        )
        return ToolOutcome(
            ok=False,
            text="Cancelled",
            signal_kind=SIGNAL_CANCELLED,
        )

    try:
        arguments = coerce_types(tool_def.func, arguments)
        with StderrSpinner(f"Running {tool_def.name}..."):
            result = tool_def.func(**arguments)
            if inspect.isawaitable(result):
                result = await result
        self._total_tool_calls += 1
        self._tool_call_counts[tool_def.name] = (
            self._tool_call_counts.get(tool_def.name, 0) + 1
        )
        from dashscope_agenticx.audit import get_audit_logger

        get_audit_logger().log_tool_call(
            tool_def.name,
            arguments,
            decision="executed",
        )
        return classify_tool_text(str(result), arguments)
    except Exception as e:
        self.record_error()
        from dashscope_agenticx.audit import get_audit_logger

        get_audit_logger().log_tool_call(
            tool_def.name,
            arguments,
            decision="failed",
            reason=str(e),
        )
        return ToolOutcome(
            ok=False,
            text=f"{EXEC_ERROR_PREFIX}: {type(e).__name__}: {e}",
            signal_kind=SIGNAL_EXCEPTION,
        )

get_stats

get_stats() -> dict

Return session usage statistics.

Source code in src/dashscope_agenticx/executor.py
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
def get_stats(self) -> dict:
    """Return session usage statistics."""
    session_duration = time.time() - self._session_start_time
    return {
        "total_tool_calls": self._total_tool_calls,
        "tool_counts": dict(self._tool_call_counts),
        "skill_calls": self._skill_calls,
        "skill_counts": dict(self._skill_counts),
        "api_calls": self._api_calls,
        "usage_calls": self._usage_calls,
        "token_usage": dict(self._token_usage),
        "prompt_composition": dict(self._prompt_composition),
        "prompt_details": dict(self._prompt_details),
        "errors": self._errors,
        "session_duration": session_duration,
    }

ToolOutcome dataclass

ToolOutcome(
    ok: bool,
    text: str,
    signal_kind: str,
    exit_code: int | None = None,
)

Structured result of one tool call.

Reflection, experience memory, directive learning and stagnation detection all key off tool success, so this is the single source of truth for that verdict instead of each call site sniffing prefixes off the text.

ok instance-attribute

ok: bool

text instance-attribute

text: str

signal_kind instance-attribute

signal_kind: str

exit_code class-attribute instance-attribute

exit_code: int | None = None

cancelled property

cancelled: bool

User rejection is neutral, not a failure.

Callers must not feed it to the consecutive-failure counter, or declining a permission prompt would look like the tool breaking.

classify_tool_text

classify_tool_text(
    text: str, arguments: dict | None = None
) -> ToolOutcome

Derive an outcome from a tool's returned text.

Tools still signal failure by returning a string, so this remains inference — but it now happens once, here, instead of being re-guessed at every call site. The shell exit-code trailer is read as the real signal it is rather than being flattened into prose.

Source code in src/dashscope_agenticx/executor.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
def classify_tool_text(
    text: str,
    arguments: dict | None = None,
) -> ToolOutcome:
    """Derive an outcome from a tool's returned text.

    Tools still signal failure by returning a string, so this remains
    inference — but it now happens once, here, instead of being re-guessed at
    every call site. The shell exit-code trailer is read as the real signal it
    is rather than being flattened into prose.
    """
    if text.startswith(_CANCEL_PREFIXES):
        return ToolOutcome(
            ok=False,
            text=text,
            signal_kind=SIGNAL_CANCELLED,
        )

    match = _EXIT_CODE_RE.search(text)
    if match:
        code = int(match.group(1))
        binary = _last_segment_binary(
            str((arguments or {}).get("command", "")),
        )
        return ToolOutcome(
            # A non-zero exit is a failure unless the command is one whose
            # exit status is its answer.
            ok=code == 0 or binary in _BENIGN_NONZERO_EXIT,
            text=text,
            signal_kind=SIGNAL_EXIT_CODE,
            exit_code=code,
        )

    if text.startswith(_FAILURE_PREFIXES):
        return ToolOutcome(
            ok=False,
            text=text,
            signal_kind=SIGNAL_TOOL_REPORTED,
        )
    return ToolOutcome(ok=True, text=text, signal_kind=SIGNAL_OK)

PromptContext dataclass

PromptContext(
    user_input: str,
    user_name: str = "",
    provider_name: str = "",
    model_name: str = "",
    memory_manager: Any = None,
    experience_tracker: Any = None,
    disabled_caps_provider: Callable[[], str] | None = None,
    directives_provider: (
        Callable[[], list[str]] | None
    ) = None,
    scene_provider: Callable[[], str] | None = None,
    current_turn_tools: list[str] = list(),
    connected_mcp_services: (
        Callable[[], list[str]] | None
    ) = None,
)

Per-turn context handed to every section's render call.

user_input instance-attribute

user_input: str

user_name class-attribute instance-attribute

user_name: str = ''

provider_name class-attribute instance-attribute

provider_name: str = ''

model_name class-attribute instance-attribute

model_name: str = ''

memory_manager class-attribute instance-attribute

memory_manager: Any = None

experience_tracker class-attribute instance-attribute

experience_tracker: Any = None

disabled_caps_provider class-attribute instance-attribute

disabled_caps_provider: Callable[[], str] | None = None

directives_provider class-attribute instance-attribute

directives_provider: Callable[[], list[str]] | None = None

scene_provider class-attribute instance-attribute

scene_provider: Callable[[], str] | None = None

current_turn_tools class-attribute instance-attribute

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

connected_mcp_services class-attribute instance-attribute

connected_mcp_services: Callable[[], list[str]] | None = (
    None
)

default_pipeline

default_pipeline(
    base_prompt: str,
    project_instructions: str | None,
    skills_summary_fn: Callable[[list[str]], str],
    active_prompts_fn: Callable[[str], str],
) -> PromptPipeline

Build the standard pipeline matching the legacy Agent section order.

Skills/skill-packages lead the ephemeral suffix (they vary with MCP state and user input); the stable prefix is only base prompt + project instructions, byte-identical across turns for provider prompt caching.

Source code in src/dashscope_agenticx/prompt_pipeline.py
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
def default_pipeline(
    base_prompt: str,
    project_instructions: str | None,
    skills_summary_fn: Callable[[list[str]], str],
    active_prompts_fn: Callable[[str], str],
) -> PromptPipeline:
    """Build the standard pipeline matching the legacy Agent section order.

    Skills/skill-packages lead the ephemeral suffix (they vary with MCP state
    and user input); the stable prefix is only base prompt + project
    instructions, byte-identical across turns for provider prompt caching.
    """
    return (
        PromptPipeline(base_prompt, project_instructions)
        .add_ephemeral(SkillsSection(skills_summary_fn))
        .add_ephemeral(SkillPackagesSection(active_prompts_fn))
        .add_ephemeral(DisabledCapsSection())
        .add_ephemeral(DirectivesSection())
        .add_ephemeral(SceneSection())
        .add_ephemeral(PlanSection())
        .add_ephemeral(ExperienceSection())
        .add_ephemeral(ToolChainsSection())
        .add_ephemeral(DirectivesLearningSection())
        .add_ephemeral(EnvironmentSection())
    )

AcceptanceGate

AcceptanceGate(
    command: str = "",
    source: str = EXPLICIT,
    retries: int = DEFAULT_RETRIES,
    timeout: int = DEFAULT_TIMEOUT,
)

Runs the acceptance check and decides whether the answer stands.

Two runs per turn at most: a baseline captured before the first mutation, and the check at the loop's exit. The baseline is what turns "the suite is red" into "you made it red" — Agentless reproduces the issue on the unpatched repository for the same reason, and AlphaCodium's test anchors are the same obligation stated positively.

Source code in src/dashscope_agenticx/acceptance.py
156
157
158
159
160
161
162
163
164
165
166
167
168
169
def __init__(
    self,
    command: str = "",
    source: str = EXPLICIT,
    retries: int = DEFAULT_RETRIES,
    timeout: int = DEFAULT_TIMEOUT,
):
    self.command = command
    self.source = source
    self.retries = retries
    self.timeout = timeout
    self.baseline: AcceptanceRun | None = None
    self.attempts = 0
    self._baseline_task: asyncio.Task | None = None

command instance-attribute

command = command

source instance-attribute

source = source

retries instance-attribute

retries = retries

timeout instance-attribute

timeout = timeout

baseline instance-attribute

baseline: AcceptanceRun | None = None

attempts instance-attribute

attempts = 0

active property

active: bool

An empty command is the off switch.

from_env classmethod

from_env(oneshot: bool) -> AcceptanceGate

Build the gate from AGENTICX_ACCEPTANCE* environment variables.

An explicit command wins over discovery. Setting AGENTICX_ACCEPTANCE=0 turns the gate off, which is what a benchmark measuring raw model output wants.

Source code in src/dashscope_agenticx/acceptance.py
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
@classmethod
def from_env(cls, oneshot: bool) -> AcceptanceGate:
    """Build the gate from ``AGENTICX_ACCEPTANCE*`` environment
    variables.

    An explicit command wins over discovery. Setting
    ``AGENTICX_ACCEPTANCE=0``
    turns the gate off, which is what a benchmark measuring raw model
    output wants.
    """
    if not (oneshot and _env_flag("AGENTICX_ACCEPTANCE", True)):
        return cls()
    command = os.environ.get("AGENTICX_ACCEPTANCE_CMD", "").strip()
    source = EXPLICIT
    if not command:
        command = discover_acceptance_command() or ""
        source = DISCOVERED
    return cls(
        command=command,
        source=source,
        retries=_env_int("AGENTICX_ACCEPTANCE_RETRIES", DEFAULT_RETRIES),
        timeout=_env_int("AGENTICX_ACCEPTANCE_TIMEOUT", DEFAULT_TIMEOUT),
    )

reset

reset() -> None

Drop the previous turn's anchor and retry budget.

The baseline has to come from the workspace as this turn found it, and the retry budget is per-turn so one slow turn cannot spend the next one's. An in-flight capture is cancelled for the same reason: left running, it would write the previous turn's verdict into this turn's baseline.

Source code in src/dashscope_agenticx/acceptance.py
200
201
202
203
204
205
206
207
208
209
210
211
212
213
def reset(self) -> None:
    """Drop the previous turn's anchor and retry budget.

    The baseline has to come from the workspace as *this* turn found it,
    and the retry budget is per-turn so one slow turn cannot spend the
    next one's. An in-flight capture is cancelled for the same reason:
    left running, it would write the previous turn's verdict into this
    turn's ``baseline``.
    """
    if self._baseline_task is not None and not self._baseline_task.done():
        self._baseline_task.cancel()
    self._baseline_task = None
    self.baseline = None
    self.attempts = 0

ensure_baseline async

ensure_baseline() -> None

Capture the pre-change verdict, once per turn.

Called before the first mutating tool call rather than at turn start: a read-only or pure-answer turn never pays for a test suite, and the baseline still comes from a workspace the agent has not touched.

Concurrent callers share one task rather than checking a flag. The flag form lets the second mutating call in a parallel batch proceed while the baseline is still running, so the "pre-change" verdict would be captured against a workspace that had already changed.

Source code in src/dashscope_agenticx/acceptance.py
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
async def ensure_baseline(self) -> None:
    """Capture the pre-change verdict, once per turn.

    Called before the first mutating tool call rather than at turn start:
    a read-only or pure-answer turn never pays for a test suite, and the
    baseline still comes from a workspace the agent has not touched.

    Concurrent callers share one task rather than checking a flag. The
    flag form lets the second mutating call in a parallel batch proceed
    while the baseline is still running, so the "pre-change" verdict would
    be captured against a workspace that had already changed.
    """
    if not self.active:
        return
    if self._baseline_task is None:
        self._baseline_task = asyncio.ensure_future(self._capture())
    await self._baseline_task

check async

check() -> GateVerdict | None

Run the check at the loop's exit and rule on the answer.

None means "not applicable" — gate off, no command found, or nothing was mutated this turn, in which case there is no work to accept.

Source code in src/dashscope_agenticx/acceptance.py
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
async def check(self) -> GateVerdict | None:
    """Run the check at the loop's exit and rule on the answer.

    ``None`` means "not applicable" — gate off, no command found, or
    nothing was mutated this turn, in which case there is no work to
    accept.
    """
    if not self.active or self.baseline is None:
        return None
    run = await self._run()
    self.attempts += 1
    if run.ok:
        return GateVerdict(run)
    if _never_ran(run) and self._baseline_never_ran():
        return GateVerdict(run, note=self._unrunnable_note(run))
    if self._unchanged_since_baseline(run):
        return GateVerdict(run, note=self._insensitive_note(run))
    if self.attempts > self.retries:
        return GateVerdict(run, note=self._unverified_note(run))
    return GateVerdict(run, rejection=self._rejection(run))

GateVerdict dataclass

GateVerdict(
    run: AcceptanceRun, rejection: str = "", note: str = ""
)

What the loop should do about a check that did not pass.

At most one of rejection and note is non-empty. rejection withholds the answer and sends the model back with the raw output; note is appended to the final answer when sending it back would not help.

run instance-attribute

run: AcceptanceRun

rejection class-attribute instance-attribute

rejection: str = ''

note class-attribute instance-attribute

note: str = ''

discover_acceptance_command

discover_acceptance_command(
    cwd: str | PathLike[str] | None = None,
) -> str | None

The conventional test entry point for the project at cwd, if any.

The allowlist is deliberately short. Every entry runs code from the repository — conftest.py at collection time, build.rs, TestMain — so "conservative" here means "a standard test entry point for an ecosystem whose manifest is sitting right here", not "harmless". npm test and make test are excluded because their bodies are arbitrary user scripts with no conventional meaning; declaring them via AGENTICX_ACCEPTANCE_CMD is how you ask for those.

Source code in src/dashscope_agenticx/acceptance.py
 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
def discover_acceptance_command(
    cwd: str | os.PathLike[str] | None = None,
) -> str | None:
    """The conventional test entry point for the project at ``cwd``, if any.

    The allowlist is deliberately short. Every entry runs code from the
    repository — ``conftest.py`` at collection time, ``build.rs``, ``TestMain``
    — so "conservative" here means "a standard test entry point for an
    ecosystem whose manifest is sitting right here", not "harmless".
    ``npm test`` and ``make test`` are excluded because their bodies are
    arbitrary user scripts with no conventional meaning; declaring them via
    ``AGENTICX_ACCEPTANCE_CMD`` is how you ask for those.
    """
    root = Path(cwd or os.getcwd())
    if not root.is_dir():
        return None
    if _is_pytest_project(root):
        # This interpreter, not a bare `pytest`: the gate must run against the
        # same environment the agent's own run_command calls use.
        return f"{shlex.quote(sys.executable)} -m pytest -q"
    if (root / "Cargo.toml").is_file():
        return "cargo test --quiet"
    if (root / "go.mod").is_file():
        return "go test ./..."
    return None

collect_deliverables

collect_deliverables(messages: list[dict]) -> list[Path]

Scan tool messages and return existing file paths produced this turn.

Source code in src/dashscope_agenticx/deliverable.py
 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
def collect_deliverables(messages: list[dict]) -> list[Path]:
    """Scan tool messages and return existing file paths produced this turn."""
    deliverables: list[Path] = []
    seen: set[Path] = set()
    cwd = Path.cwd()

    for msg in messages:
        if msg.get("role") != "tool":
            continue
        if msg.get("name", "") not in _DELIVERABLE_TOOL_NAMES:
            continue

        content = msg.get("content", "")
        if isinstance(content, list):
            content = " ".join(
                c.get("text", "") for c in content if isinstance(c, dict)
            )

        for token in _candidate_paths(content):
            path = Path(token)
            if not path.is_absolute():
                path = cwd / path
            try:
                path = path.resolve()
            except OSError:
                continue
            if path in seen:
                continue
            seen.add(path)
            if path.exists() and path.is_file():
                deliverables.append(path)

    return deliverables

surface_deliverables

surface_deliverables(
    deliverables: list[Path], auto_open: bool = False
) -> None

Print a summary of generated files and optionally open them.

Source code in src/dashscope_agenticx/deliverable.py
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
def surface_deliverables(
    deliverables: list[Path],
    auto_open: bool = False,
) -> None:
    """Print a summary of generated files and optionally open them."""
    if not deliverables:
        return

    console.print()
    console.print("[dim]─ Generated files ─[/dim]")
    for path in deliverables:
        rel = (
            path.relative_to(Path.cwd())
            if path.is_relative_to(Path.cwd())
            else path
        )
        suffix = path.suffix.lower()
        icon = "📄" if suffix in _OPENABLE_EXTENSIONS else "📦"
        console.print(f"{icon} [cyan]{rel}[/cyan]")

        if auto_open and suffix in _OPENABLE_EXTENSIONS:
            cmd = _open_command()
            if cmd:
                try:
                    subprocess.Popen(  # pylint: disable=consider-using-with
                        [cmd, str(path)],
                        stdout=subprocess.DEVNULL,
                        stderr=subprocess.DEVNULL,
                    )
                except Exception:
                    pass

    console.print(
        "[dim]  Tip: use /open <path> or view in your file manager[/dim]",
    )

Subagents & delegation

SubagentDef dataclass

SubagentDef(
    key: str,
    name: str,
    description: str,
    source: str,
    category: str,
    enabled: bool,
)

Discovered subagent definition.

key instance-attribute

key: str

name instance-attribute

name: str

description instance-attribute

description: str

source instance-attribute

source: str

category instance-attribute

category: str

enabled instance-attribute

enabled: bool

discover_subagents

discover_subagents(config: Config) -> list[SubagentDef]

Scan capabilities to find subagent-type ones.

Source code in src/dashscope_agenticx/agents/subagents.py
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
def discover_subagents(config: Config) -> list[SubagentDef]:
    """Scan capabilities to find subagent-type ones."""
    from dashscope_agenticx.cli import CAPABILITY_CATALOG, _cap_enabled
    from dashscope_agenticx.extensions import current as ext_current

    ext = ext_current()
    ext_cap_keys = {c.key for c in ext.capabilities}

    subagents = []
    for cap in CAPABILITY_CATALOG:
        if cap["key"] not in SUBAGENT_CAPABILITY_KEYS:
            continue
        source = "extension" if cap["key"] in ext_cap_keys else "built-in"
        category = "local" if cap["platform"] == "local" else "remote"
        subagents.append(
            SubagentDef(
                key=cap["key"],
                name=cap["name"],
                description=f"{cap['platform']}.{cap['cap']}",
                source=source,
                category=category,
                enabled=_cap_enabled(config, cap["key"]),
            ),
        )
    return subagents

bind_subagent_context

bind_subagent_context(agent, config)

Bind parent/config for one runtime context without global overwrite.

Source code in src/dashscope_agenticx/agents/subagent.py
65
66
67
68
69
70
71
72
73
74
@contextlib.contextmanager
def bind_subagent_context(agent, config):
    """Bind parent/config for one runtime context without global overwrite."""
    parent_token = _parent_ctx.set(agent)
    config_token = _config_ctx.set(config)
    try:
        yield
    finally:
        _config_ctx.reset(config_token)
        _parent_ctx.reset(parent_token)

register_subagent_tool

register_subagent_tool() -> None

Wire subagent_invoke into the tool registry. Called from tools/platform.register_one_capability when local.subagent is enabled.

Source code in src/dashscope_agenticx/agents/subagent.py
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
def register_subagent_tool() -> None:
    """Wire subagent_invoke into the tool registry. Called from
    tools/platform.register_one_capability when local.subagent is enabled."""
    registry.register_mcp_tool(
        name="subagent_invoke",
        description=(
            "Spawn an isolated sub-agent (same provider, same tools, fresh "
            "context) to handle a self-contained task whose intermediate "
            "reasoning shouldn't pollute the main conversation. Returns "
            "only the sub-agent's final answer as text. Good for: long "
            "code reviews, multi-file scans, speculative exploration. "
            "Pass system_prompt to specialize role (e.g. strict reviewer, "
            "researcher)."
        ),
        parameters={
            "type": "object",
            "properties": {
                "prompt": {
                    "type": "string",
                    "description": (
                        "The task description the sub-agent acts on."
                    ),
                },
                "system_prompt": {
                    "type": "string",
                    "description": (
                        "Optional system prompt to specialize the sub-agent's "
                        "role. Leave empty to inherit parent's default."
                    ),
                },
                "max_turns": {
                    "type": "integer",
                    "description": (
                        "Cap on sub-agent loop iterations "
                        "(default 10, max 50)."
                    ),
                    "default": 10,
                },
            },
            "required": ["prompt"],
        },
        call_fn=_subagent_invoke,
    )

    # Register specialist subagent tools
    _register_specialist_tools()

bind_delegate_context

bind_delegate_context(agent, config)

Bind parent/config for one runtime context without global overwrite.

Source code in src/dashscope_agenticx/agents/delegate.py
62
63
64
65
66
67
68
69
70
71
@contextlib.contextmanager
def bind_delegate_context(agent, config):
    """Bind parent/config for one runtime context without global overwrite."""
    parent_token = _parent_ctx.set(agent)
    config_token = _config_ctx.set(config)
    try:
        yield
    finally:
        _config_ctx.reset(config_token)
        _parent_ctx.reset(parent_token)