跳转至内容

Agent、运行时与事件

Agent 同一时间运行一轮对话,并发出带类型的事件。Runtime 将配置、 Provider、工具与平台连接在一起;RuntimeBuilder 是 CLI 与 SDK 共用的组装入口。

生命周期

Agent 支持 async with 与显式的 await agent.aclose()。SDK 辅助 函数(run_once、run_stream、run_events)会替你关闭 Agent;当你 直接驱动 Agent 时,请自行关闭:

import asyncio

from dashscope_agenticx.sdk import create_agent


async def main():
    async with create_agent(session_id="demo") as agent:
        async for chunk in agent.run_stream("Hello!"):
            print(chunk, end="", flush=True)


asyncio.run(main())

run_events() 与 run_stream() 都是单遍异步生成器。如需提前停止, 请关闭生成器(contextlib.aclosing)— 参见 嵌入式 SDK。

事件类型

每个事件都是 AgentEventEnvelope,其类型来自 AgentEventType:

类型 含义
run.started 一轮对话开始
message.delta 助手文本增量
reasoning.delta 推理/思考文本增量
plan.updated Agent 的计划发生变化
tool.started / tool.finished 工具执行边界
permission.requested / permission.resolved 批准流程
usage.updated token 用量统计
artifact.created 产出了交付文件
compression.completed 执行了上下文压缩
provider.switched 回退/路由切换了 Provider
sandbox.status 沙箱后端状态
turn.finished 本轮对话完成
error 出现了可恢复或致命错误

错误以流内 error 事件的形式传递 — AgenticX 对模型/工具失败没有统一 的异常体系。少数控制流异常参见评测。

Agent

Agent

Agent(
    provider: LLMProvider,
    executor: Executor,
    max_turns: int = 50,
    memory: MemoryProvider | None = None,
    user_name: str = "",
    provider_name: str = "",
    model_name: str = "",
    session_path: Path | None = None,
    disabled_caps_provider=None,
    directives_provider=None,
    system_prompt: str | None = None,
    allow_delegate: bool = True,
    allowed_tools: list[str] | None = None,
    hook_bus: HookBus | None = None,
    memory_manager: MemoryManager | None = None,
    tool_registry: ToolRegistry | None = None,
    skill_manager=None,
    session_manager=None,
    runtime_config=None,
    runtime_id: str = "",
    agent_id: str = "",
    capability_tools: dict[str, set[str]] | None = None,
    json_mode: bool = False,
    oneshot: bool = False,
)
Source code in src/dashscope_agenticx/agent.py
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
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
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
def __init__(
    self,
    provider: LLMProvider,
    executor: Executor,
    max_turns: int = 50,
    memory: MemoryProvider | None = None,
    user_name: str = "",
    provider_name: str = "",
    model_name: str = "",
    session_path: Path | None = None,
    disabled_caps_provider=None,
    directives_provider=None,
    system_prompt: str | None = None,
    allow_delegate: bool = True,
    allowed_tools: list[str] | None = None,
    hook_bus: HookBus | None = None,
    memory_manager: MemoryManager | None = None,
    tool_registry: ToolRegistry | None = None,
    skill_manager=None,
    session_manager=None,
    runtime_config=None,
    runtime_id: str = "",
    agent_id: str = "",
    capability_tools: dict[str, set[str]] | None = None,
    json_mode: bool = False,
    oneshot: bool = False,
):
    self.provider = provider
    self.executor = executor
    self.tool_registry = tool_registry or registry.current()
    self.skill_manager = skill_manager or get_skill_manager()
    if session_manager is None:
        from dashscope_agenticx.session import get_session_manager

        session_manager = get_session_manager()
    self.session_manager = session_manager
    self.runtime_config = runtime_config
    self.runtime_id = runtime_id or uuid.uuid4().hex
    self.agent_id = agent_id or uuid.uuid4().hex
    self.capability_tools = (
        capability_tools if capability_tools is not None else {}
    )
    self._event_sink: Callable[[AgentEvent], None] | None = None
    self._event_context: dict[str, str] = {}
    self._event_sequence = 0
    self._closed = False
    self.executor.set_permission_observer(self._on_permission_event)
    self.model_invoker = ModelInvoker()
    self.tool_coordinator = ToolCoordinator()
    self.run_guards = RunGuards()
    self.session_persistence = SessionPersistence()
    self.max_turns = max_turns
    self.system_prompt = system_prompt
    self.allow_delegate = allow_delegate
    self.allowed_tools = allowed_tools
    self.hook_bus = hook_bus or create_hook_bus()
    self.json_mode = json_mode
    self.oneshot = oneshot
    # Hard stop for read-only stalls in oneshot (benchmark/script) mode.
    # Env override: AGENTICX_READONLY_HARD_CAP (0 disables).
    try:
        self.readonly_hard_cap = int(
            os.environ.get("AGENTICX_READONLY_HARD_CAP", "40"),
        )
    except ValueError:
        self.readonly_hard_cap = 40
    # Turn-level retry: re-run the current turn (only when nothing was
    # streamed yet, to avoid duplicate output) up to turn_retry_max times
    # with capped exponential backoff. Covers providers that carry no
    # retry layer of their own; a HardenedProvider that exhausted its own
    # budget slowly (stalled endpoint, not a refused connection) is not
    # re-paid here — see _budget_burned_slowly.
    # Env override: AGENTICX_TURN_RETRY_MAX (0 disables).
    try:
        self.turn_retry_max = int(
            os.environ.get("AGENTICX_TURN_RETRY_MAX", "2"),
        )
    except ValueError:
        self.turn_retry_max = 2
    self.turn_retry_delay = 5.0
    self.turn_retry_backoff_cap = 30.0
    # Empty-turn backstop (oneshot only): a turn that ends with no tool
    # calls and no content is a provider failure shape, not "done". An
    # autonomous run must not exit on it while budget remains — nudge
    # and continue, bounded so a persistently empty endpoint still
    # terminates. Interactive keeps the historical break: there the
    # user sees the notice and simply speaks again.
    self._empty_turns = 0
    self._empty_turn_max = 2
    # Budget-aware convergence nudge (oneshot only): as the turn budget is
    # consumed, tell the agent to switch approach if plateaued, lock in an
    # already-passing result, then finalize. Covers productive-but-stuck
    # iteration that ReflectionTracker (failures) and StagnationTracker
    # (read-only stalls) both miss. Environment:
    # AGENTICX_CONVERGE_SOFT/_HARD (ratios;
    # soft >= 1.0 disables).
    try:
        self.converge_soft_ratio = float(
            os.environ.get("AGENTICX_CONVERGE_SOFT", "0.6"),
        )
    except ValueError:
        self.converge_soft_ratio = 0.6
    try:
        self.converge_hard_ratio = float(
            os.environ.get("AGENTICX_CONVERGE_HARD", "0.85"),
        )
    except ValueError:
        self.converge_hard_ratio = 0.85
    # Wall-clock budget nudge (oneshot only): the turn-count convergence
    # hint never fires when a run is few-but-huge generations, yet the
    # harness kills the run on wall time all the same — and the hard-set
    # tasks that died so (dna-assembly, write-compressor) all died with
    # their deliverable never written. The bench adapter injects the
    # in-container `timeout` value as AGENTICX_TIME_BUDGET_SEC; unset/<=0
    # disables. Ratios: AGENTICX_TIME_SOFT / AGENTICX_TIME_HARD.
    try:
        self.time_budget_sec = float(
            os.environ.get("AGENTICX_TIME_BUDGET_SEC", "0"),
        )
    except ValueError:
        self.time_budget_sec = 0.0
    try:
        self.time_soft_ratio = float(
            os.environ.get("AGENTICX_TIME_SOFT", "0.5"),
        )
    except ValueError:
        self.time_soft_ratio = 0.5
    try:
        self.time_hard_ratio = float(
            os.environ.get("AGENTICX_TIME_HARD", "0.8"),
        )
    except ValueError:
        self.time_hard_ratio = 0.8
    # Monotonic anchor for the budget above, set on the first turn: a
    # wall clock would credit host-suspend time the process never had.
    self._run_started: float | None = None
    # Silence nudge: one reminder per turn after N tool calls have gone by
    # without any prose reaching the user. Mode-independent on purpose —
    # the shape this exists for is an interactive turn of *distinct*
    # run_command calls, which every existing backstop misses:
    # StagnationTracker's read-only classifier counts run_command as
    # mutating and so resets its streak, its repeat counters need
    # byte-identical calls, and _convergence_section is oneshot-only.
    # Env: AGENTICX_SILENT_TOOL_NUDGE (0 disables).
    try:
        self.silent_tool_nudge = int(
            os.environ.get("AGENTICX_SILENT_TOOL_NUDGE", "6"),
        )
    except ValueError:
        self.silent_tool_nudge = 6
    # Hard acceptance gate (oneshot only): run the project's test command
    # before accepting a final answer, and send the raw output back when
    # it fails. Built here, ahead of the policy text below, so the prompt
    # can promise the gate only when one is actually armed.
    # Environment: AGENTICX_ACCEPTANCE (0 disables),
    # AGENTICX_ACCEPTANCE_CMD (overrides discovery),
    # AGENTICX_ACCEPTANCE_RETRIES, AGENTICX_ACCEPTANCE_TIMEOUT.
    self._acceptance_gate = AcceptanceGate.from_env(self.oneshot)
    # Load custom system prompt: workspace
    # .agenticx/system-prompt.md first,
    # then global ~/.agenticx/system-prompt.md, then built-in default.
    # runners.py pre-populates system_prompt via _load_system_prompt();
    # this fallback ensures direct Agent construction (SDK, tests,
    # subagents) also respects the global file.
    if self.system_prompt is None:
        from dashscope_agenticx.cli.startup import (
            _compose_system_prompt,
            _load_system_prompt,
        )

        self.system_prompt = _compose_system_prompt(_load_system_prompt())
    if self.oneshot:
        self.system_prompt = (self.system_prompt or SYSTEM_PROMPT) + (
            "\n\nTask execution policy (autonomous mode):\n"
            "- Work from a written plan, not from memory: early in the "
            "run, write a short plan file (goal, acceptance check, "
            "ordered steps); after each step, record in it what is done "
            "and what remains; before reporting completion, re-read it "
            "and verify each item. Sketch the deliverable itself first, "
            "then iterate on it. Never spend a whole turn only "
            "thinking — every turn must land something on disk: a file, "
            "a measurement, or an updated plan.\n"
            "- If the request has a measurable acceptance criterion "
            "(numeric threshold, size/time limit, test suite, "
            "similarity/accuracy target), iterate until it is met: "
            "implement -> measure against the criterion -> refine. Do "
            "not stop at the first version that merely runs; optimize "
            "toward the target — but once the criterion is met, lock it "
            "in and finish rather than risk regressing a passing result. "
            "Heed any budget-check hint: it tells you when to converge "
            "or switch to a different approach. A wall-clock hint means "
            "the run is killed when time runs out: get the required "
            "deliverable written early, then keep improving it.\n"
            "- Before reporting completion, turn every stated "
            "requirement into its own executable check and run them "
            "all — the measurable criterion, the format rules, and "
            "any constraint that mentions components the deliverable "
            "must contain. Where a check depends on domain facts, "
            "state the fact explicitly first (a wrong assumption is "
            "worse than a flagged unknown). Fix what fails instead "
            "of handing back a near miss.\n"
            "- When a check fails close to the target, treat it as "
            "actionable feedback: change the approach based on what "
            "the measurement shows, then re-measure.\n"
            "- Do not stake a large share of the remaining budget on "
            "one long unverified command: before an install, compile "
            "or download that could run for minutes, spend seconds "
            "probing that the path can succeed at all (package "
            "available, toolchain present); give long commands an "
            "explicit timeout so a stuck one fails fast and frees "
            "the rest of the budget."
        )
        if self._acceptance_gate.active:
            # An armed gate implies oneshot — from_env hands back an empty
            # command otherwise — so this belongs inside the block above.
            # Naming the command beats a generic promise: the model can
            # run it itself first instead of meeting the gate at the exit.
            check = self._acceptance_gate.command
            self.system_prompt += (
                f"\n- Verification gate: `{check}` runs before your "
                "final answer is accepted. If it fails, the answer is "
                "withheld and the raw output comes back to you as the "
                "next requirement. Make it pass by fixing the code — "
                "never by editing, skipping, or weakening the check "
                "itself."
            )
    # Discover project instructions from CWD (rules.jsonl,
    # .cursorrules, etc.)
    from dashscope_agenticx.prompt import discover_project_instructions

    project_instructions = discover_project_instructions()
    self._prompt_pipeline = default_pipeline(
        base_prompt=self.system_prompt or SYSTEM_PROMPT,
        project_instructions=project_instructions,
        skills_summary_fn=skills_summary_for_llm,
        active_prompts_fn=self.skill_manager.active_prompts,
    )
    self.messages: list[dict] = []
    self.artifacts: list[dict] = []
    self.last_output: str = ""
    self.memory = memory
    self.provider_name = provider_name
    self.model_name = model_name
    self.user_name = user_name
    self.session_path = session_path
    # Callable[[], str] returning a system-prompt fragment describing
    # currently-disabled capabilities. Called fresh each turn so
    # /capability toggles take effect on the next user input without
    # re-instantiating the agent.
    self.disabled_caps_provider = disabled_caps_provider
    # Callable[[], list[str]] returning user-declared operational rules
    # to be injected unconditionally each turn (see _directives_section).
    self.directives_provider = directives_provider

    # Sub-agents reuse the parent's memory_manager; top-level agents
    # create their own instance.
    if memory_manager is not None:
        self.memory_manager = memory_manager
    else:
        workspace_dir = WORKSPACE_DIR
        self.memory_manager = MemoryManager(workspace_dir)
    self.memory_manager.session.bind_projection(
        self.session_manager,
        self._session_topic,
    )
    self.run_guards.bind(
        self.memory_manager.session.reflection,
        self.memory_manager.session.stagnation,
    )

    # Resolved once: the compression token budget tracks the model's real
    # context window instead of a fixed 128k.
    self._context_window = context_window_for_model(model_name or "")

    # Convenience references for backward compatibility
    self.trace_logger = self.memory_manager.trace
    self.experience_tracker = self.memory_manager.persistent.experience

    # Track tools used in current turn for experience recording
    self._current_turn_tools: list[str] = []
    self._turn_tool_successes = 0
    self._turn_tool_failures = 0
    self._reflection_lesson_recorded = False
    self._reflection_hint_injected = False
    # Per-turn counters for the TUI status line
    self.turn_tool_calls = 0
    self.turn_subagents = 0
    self.turn_mcp_calls = 0
    self.turn_skills = 0
    # Consecutive tool calls that streamed no prose, and whether the
    # silence nudge has already been spent this turn.
    self._silent_tool_calls = 0
    self._silent_nudge_injected = False
    # Compression observability toward the model: the event is set by
    # either compression path and spent once by _compression_section;
    # the ratio is refreshed by the mid-turn guard's estimate.
    self._compression_event: tuple[int, int] | None = None
    self._context_ratio = 0.0
    # Explicit /skill invocations to count on the next turn
    self._pending_skill_names: list[str] = []

executor instance-attribute

executor = executor

tool_registry instance-attribute

tool_registry = tool_registry or registry.current()

skill_manager instance-attribute

skill_manager = skill_manager or get_skill_manager()

session_manager instance-attribute

session_manager = session_manager

runtime_config instance-attribute

runtime_config = runtime_config

runtime_id instance-attribute

runtime_id = runtime_id or uuid.uuid4().hex

agent_id instance-attribute

agent_id = agent_id or uuid.uuid4().hex

capability_tools instance-attribute

capability_tools = (
    capability_tools if capability_tools is not None else {}
)

model_invoker instance-attribute

model_invoker = ModelInvoker()

tool_coordinator instance-attribute

tool_coordinator = ToolCoordinator()

run_guards instance-attribute

run_guards = RunGuards()

session_persistence instance-attribute

session_persistence = SessionPersistence()

max_turns instance-attribute

max_turns = max_turns

system_prompt instance-attribute

system_prompt = system_prompt

allow_delegate instance-attribute

allow_delegate = allow_delegate

allowed_tools instance-attribute

allowed_tools = allowed_tools

hook_bus instance-attribute

hook_bus = hook_bus or create_hook_bus()

json_mode instance-attribute

json_mode = json_mode

oneshot instance-attribute

oneshot = oneshot

readonly_hard_cap instance-attribute

readonly_hard_cap = int(
    os.environ.get("AGENTICX_READONLY_HARD_CAP", "40")
)

turn_retry_max instance-attribute

turn_retry_max = int(
    os.environ.get("AGENTICX_TURN_RETRY_MAX", "2")
)

turn_retry_delay instance-attribute

turn_retry_delay = 5.0

turn_retry_backoff_cap instance-attribute

turn_retry_backoff_cap = 30.0

converge_soft_ratio instance-attribute

converge_soft_ratio = float(
    os.environ.get("AGENTICX_CONVERGE_SOFT", "0.6")
)

converge_hard_ratio instance-attribute

converge_hard_ratio = float(
    os.environ.get("AGENTICX_CONVERGE_HARD", "0.85")
)

time_budget_sec instance-attribute

time_budget_sec = float(
    os.environ.get("AGENTICX_TIME_BUDGET_SEC", "0")
)

time_soft_ratio instance-attribute

time_soft_ratio = float(
    os.environ.get("AGENTICX_TIME_SOFT", "0.5")
)

time_hard_ratio instance-attribute

time_hard_ratio = float(
    os.environ.get("AGENTICX_TIME_HARD", "0.8")
)

silent_tool_nudge instance-attribute

silent_tool_nudge = int(
    os.environ.get("AGENTICX_SILENT_TOOL_NUDGE", "6")
)

messages instance-attribute

messages: list[dict] = []

artifacts instance-attribute

artifacts: list[dict] = []

last_output instance-attribute

last_output: str = ''

memory instance-attribute

memory = memory

provider_name instance-attribute

provider_name = provider_name

model_name instance-attribute

model_name = model_name

user_name instance-attribute

user_name = user_name

session_path instance-attribute

session_path = session_path

disabled_caps_provider instance-attribute

disabled_caps_provider = disabled_caps_provider

directives_provider instance-attribute

directives_provider = directives_provider

memory_manager instance-attribute

memory_manager = memory_manager

trace_logger instance-attribute

trace_logger = self.memory_manager.trace

experience_tracker instance-attribute

experience_tracker = (
    self.memory_manager.persistent.experience
)

turn_tool_calls instance-attribute

turn_tool_calls = 0

turn_subagents instance-attribute

turn_subagents = 0

turn_mcp_calls instance-attribute

turn_mcp_calls = 0

turn_skills instance-attribute

turn_skills = 0

provider property writable

provider

note_skill_use

note_skill_use(name: str) -> None

Queue an explicit /skill invocation for turn/session stats.

Source code in src/dashscope_agenticx/agent.py
527
528
529
def note_skill_use(self, name: str) -> None:
    """Queue an explicit /skill invocation for turn/session stats."""
    self._pending_skill_names.append(name)

reset

reset()

Clear in-memory messages without deleting the persisted history file.

Source code in src/dashscope_agenticx/agent.py
541
542
543
544
def reset(self):
    """Clear in-memory messages without deleting the persisted history
    file."""
    self.messages = []

load_session

load_session() -> int

Restore self.messages. Returns the number of messages loaded (0 if nothing could be restored).

The per-topic event stream is the source of truth: the latest messages/snapshot wins when present (crash recovery via append-only replay; torn trailing lines are skipped). The history.json file remains as the compat fallback for sessions written before snapshots existed.

Source code in src/dashscope_agenticx/agent.py
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
def load_session(self) -> int:
    """Restore self.messages. Returns the number of messages loaded
    (0 if nothing could be restored).

    The per-topic event stream is the source of truth: the latest
    ``messages/snapshot`` wins when present (crash recovery via
    append-only replay; torn trailing lines are skipped). The
    ``history.json`` file remains as the compat fallback for
    sessions written before snapshots existed.
    """
    if not self.session_path:
        return 0
    try:
        from dashscope_agenticx.session_events import (
            EVENTS_FILENAME,
            SessionEventLog,
            project_session_state,
        )

        state = project_session_state(
            SessionEventLog(
                self.session_path.parent / EVENTS_FILENAME,
            ).read_raw(),
        )
        memory_manager = getattr(self, "memory_manager", None)
        if memory_manager is not None:
            memory_manager.session.plan.restore(state.get("plan"))
        self.artifacts = list(state.get("artifacts", []))
        resumed = state.get("messages", [])
        if resumed:
            self.messages = resumed
            return len(resumed)
    except Exception:
        pass
    if not self.session_path.exists():
        return 0
    try:
        data = json.loads(self.session_path.read_text())
        if isinstance(data, list):
            self.messages = data
            return len(data)
    except (json.JSONDecodeError, OSError):
        pass
    return 0

save_session

save_session() -> None

Persist self.messages atomically. No-op when session_path is unset.

Source code in src/dashscope_agenticx/agent.py
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
def save_session(self) -> None:
    """Persist self.messages atomically. No-op when session_path is
    unset."""
    if not self.session_path:
        return
    try:
        from dashscope_agenticx.utils.paths import atomic_write_text

        self.session_path.parent.mkdir(parents=True, exist_ok=True)
        atomic_write_text(
            self.session_path,
            json.dumps(
                sanitize(self.messages),
                ensure_ascii=False,
                indent=2,
            ),
        )
    except OSError:
        pass
    # Update session meta message count
    try:
        topic = self.session_path.parent.name
        self.session_manager.update_message_count(
            len(self.messages),
            topic,
        )
    except Exception:
        pass

update_system_prompt

update_system_prompt(system_prompt: str | None) -> None

Refresh instructions without discarding conversation state.

Source code in src/dashscope_agenticx/agent.py
650
651
652
653
654
655
656
657
658
def update_system_prompt(self, system_prompt: str | None) -> None:
    """Refresh instructions without discarding conversation state."""
    from dashscope_agenticx.prompt import discover_project_instructions

    self.system_prompt = system_prompt
    self._prompt_pipeline.update_base_prompt(
        system_prompt or SYSTEM_PROMPT,
        discover_project_instructions(),
    )

aclose async

aclose() -> None

Release the owning Runtime, or this standalone Agent's provider.

Source code in src/dashscope_agenticx/agent.py
983
984
985
986
987
988
989
990
991
992
993
994
async def aclose(self) -> None:
    """Release the owning Runtime, or this standalone Agent's provider."""
    if self._closed:
        return
    self._closed = True
    runtime = getattr(self, "runtime", None)
    if runtime is not None:
        await runtime.aclose()
    else:
        from dashscope_agenticx.providers.base import close_provider

        await close_provider(self.provider)

run_events async

run_events(user_input) -> AsyncGenerator[AgentEvent, None]

Run one turn as a typed event stream.

This is the canonical public execution API. run_stream is a text compatibility projection over the message-delta events emitted here.

Source code in src/dashscope_agenticx/agent.py
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
async def run_events(self, user_input) -> AsyncGenerator[AgentEvent, None]:
    """Run one turn as a typed event stream.

    This is the canonical public execution API. ``run_stream`` is a text
    compatibility projection over the message-delta events emitted here.
    """
    runtime = getattr(self, "runtime", None)
    if self._closed or (runtime is not None and runtime._closed):
        raise RuntimeError("Agent Runtime is closed")
    if self._event_sink is not None:
        raise RuntimeError(
            "an Agent may only run one event stream at a time",
        )

    pending: list[AgentEvent] = []
    run_id = uuid.uuid4().hex
    self._event_context = {
        "session_id": (
            self.session_path.parent.name if self.session_path else ""
        ),
        "run_id": run_id,
        "turn_id": uuid.uuid4().hex,
    }
    self._event_sequence = 0
    self._event_sink = pending.append

    try:
        self._emit_event(
            AgentEventType.RUN_STARTED,
            {"input": sanitize(text_of(user_input))},
        )
        while pending:
            yield pending.pop(0)
        async with contextlib.aclosing(
            self._run_text_stream(user_input),
        ) as chunks:
            async for chunk in chunks:
                while pending:
                    yield pending.pop(0)
                payload = {"text": str(chunk)}
                if isinstance(chunk, ToolDisplayText):
                    payload.update(
                        kind="tool",
                        tool_call_id=chunk.tool_call_id,
                        name=chunk.name,
                    )
                self._emit_event(AgentEventType.MESSAGE_DELTA, payload)
                while pending:
                    yield pending.pop(0)
        while pending:
            yield pending.pop(0)
        self._emit_artifact_events()
        while pending:
            yield pending.pop(0)
        self._emit_event(
            AgentEventType.TURN_FINISHED,
            {
                "output": self.last_output,
                "tools": list(self._current_turn_tools),
            },
        )
        while pending:
            yield pending.pop(0)
    except GeneratorExit:
        raise
    except BaseException as exc:
        self._emit_event(
            AgentEventType.ERROR,
            {
                "error_type": type(exc).__name__,
                "message": sanitize_text(str(exc))[:1000],
            },
        )
        while pending:
            yield pending.pop(0)
        raise
    finally:
        self._event_sink = None
        self._event_context = {}
        parent_executor = getattr(self.executor, "_usage_parent", None)
        if parent_executor is not None:
            parent_executor.absorb_child_usage(self.executor)

run_stream async

run_stream(user_input) -> AsyncGenerator[str, None]

Yield the legacy text projection of the typed event stream.

Source code in src/dashscope_agenticx/agent.py
1085
1086
1087
1088
1089
1090
async def run_stream(self, user_input) -> AsyncGenerator[str, None]:
    """Yield the legacy text projection of the typed event stream."""
    async with contextlib.aclosing(self.run_events(user_input)) as events:
        async for event in events:
            if event.type == AgentEventType.MESSAGE_DELTA:
                yield str(event.payload.get("text", ""))

Runtime

Runtime dataclass

Runtime(
    config: Config,
    provider: LLMProvider,
    executor: object,
    context: RuntimeContext,
    memory: MemoryProvider | None = None,
)

A configured provider/executor plus isolated runtime state.

config instance-attribute

config: Config

provider instance-attribute

provider: LLMProvider

executor instance-attribute

executor: object

context instance-attribute

context: RuntimeContext

memory class-attribute instance-attribute

memory: MemoryProvider | None = None

track_provider

track_provider(provider) -> None
Source code in src/dashscope_agenticx/runtime.py
125
126
127
128
129
def track_provider(self, provider) -> None:
    if provider is not None:
        if self._closed:
            raise RuntimeError("Runtime is closed")
        self._managed_providers[id(provider)] = provider

activate

activate(*, tool_registry=None)

Bind runtime-owned state for frontend commands and tool calls.

Source code in src/dashscope_agenticx/runtime.py
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
@contextmanager
def activate(self, *, tool_registry=None):
    """Bind runtime-owned state for frontend commands and tool calls."""
    if self._closed:
        raise RuntimeError("Runtime is closed")
    from dashscope_agenticx.cli.mcp import bind_mcp_clients
    from dashscope_agenticx.tools.platform import bind_capability_tools
    from dashscope_agenticx.tools.registry import bind_tool_registry
    from dashscope_agenticx.session import bind_session_manager
    from dashscope_agenticx.permission import bind_permission_policy
    from dashscope_agenticx.extensions import bind_extensions
    from dashscope_agenticx.cli.handlers_profile import bind_memory_client

    with ExitStack() as stack:
        stack.enter_context(
            bind_tool_registry(
                tool_registry
                if tool_registry is not None
                else self.context.tool_registry,
            ),
        )
        stack.enter_context(bind_mcp_clients(self.context.mcp_clients))
        stack.enter_context(
            bind_capability_tools(self.context.capability_tools),
        )
        stack.enter_context(
            bind_session_manager(self.context.session_manager),
        )
        stack.enter_context(
            bind_permission_policy(self.context.permission_policy),
        )
        stack.enter_context(bind_extensions(self.context.extensions))
        stack.enter_context(
            bind_memory_client(self.memory, self._set_memory_client),
        )
        yield self

aclose async

aclose() -> None

Release only this runtime's MCP connections and provider clients.

Source code in src/dashscope_agenticx/runtime.py
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
async def aclose(self) -> None:
    """Release only this runtime's MCP connections and provider clients."""
    if self._closed:
        return
    from dashscope_agenticx.providers.base import close_provider

    clients = list(self.context.mcp_clients.values())
    self.context.mcp_clients.clear()
    resources = {
        id(resource): resource
        for resource in (
            self.provider,
            self.memory,
            *clients,
            *self._managed_providers.values(),
        )
        if resource is not None
    }
    self._managed_providers.clear()
    self._closed = True
    results = await asyncio.gather(
        *(close_provider(resource) for resource in resources.values()),
        return_exceptions=True,
    )
    for result in results:
        if isinstance(result, BaseException):
            raise result

create_agent

create_agent(
    system_prompt: str,
    session_id: str | None = None,
    *,
    oneshot: bool = False
) -> Agent

Construct and fully wire an Agent owned by this Runtime.

Source code in src/dashscope_agenticx/runtime.py
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
def create_agent(
    self,
    system_prompt: str,
    session_id: str | None = None,
    *,
    oneshot: bool = False,
) -> Agent:
    """Construct and fully wire an Agent owned by this Runtime."""
    if self._closed:
        raise RuntimeError("Runtime is closed")
    from dashscope_agenticx.agent import Agent
    from dashscope_agenticx.tools.platform import (
        disabled_capabilities_hint,
    )

    session_path: Path | None = None
    if session_id:
        session_path = self.context.session_manager.get_history_path(
            session_id,
        )

    tool_registry = self.context.tool_registry
    if self._agent_count:
        tool_registry = tool_registry.clone()
    agent = Agent(
        provider=self.provider,
        executor=self.executor
        if self._agent_count == 0
        else self.executor.fork_for_child(),
        max_turns=self.config.max_turns,
        memory=self.memory,
        user_name=self.config.user_name,
        provider_name=self.config.provider,
        model_name=self.config.model,
        system_prompt=system_prompt,
        session_path=session_path,
        disabled_caps_provider=lambda: disabled_capabilities_hint(
            self.config,
        ),
        directives_provider=lambda: self.config.user_directives,
        hook_bus=self.context.hook_bus,
        tool_registry=tool_registry,
        skill_manager=self.context.skill_manager,
        session_manager=self.context.session_manager,
        runtime_config=self.config,
        runtime_id=self.context.runtime_id,
        capability_tools=self.context.capability_tools,
        oneshot=oneshot,
    )
    with self.activate(tool_registry=tool_registry):
        wire_agent_runtime(
            self.config,
            agent,
            self.context.hook_bus,
            tool_registry=tool_registry,
            skill_manager=self.context.skill_manager,
            capability_tools=self.context.capability_tools,
            mcp_clients=self.context.mcp_clients,
        )
    # Keep the owning Runtime alive for future lifecycle/close APIs.
    agent.runtime = self
    self.track_provider(agent.provider)
    self._agent_count += 1
    return agent

RuntimeBuilder

RuntimeBuilder(
    config: Config, *, extensions_prepared: bool = False
)

Build a Runtime without leaking mutable registries across instances.

Source code in src/dashscope_agenticx/runtime.py
277
278
279
280
281
282
283
284
def __init__(
    self,
    config: Config,
    *,
    extensions_prepared: bool = False,
):
    self.config = config
    self.extensions_prepared = extensions_prepared

config instance-attribute

config = config

extensions_prepared instance-attribute

extensions_prepared = extensions_prepared

build

build() -> Runtime

Prepare extensions, provider, executor, memory, and context.

Source code in src/dashscope_agenticx/runtime.py
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
def build(self) -> Runtime:
    """Prepare extensions, provider, executor, memory, and context."""
    from dashscope_agenticx.executor import Executor
    from dashscope_agenticx.providers import get_provider_chain

    if not self.extensions_prepared:
        prepare_extensions(self.config)
    context = RuntimeContext.create(self.config)
    return Runtime(
        config=self.config,
        provider=get_provider_chain(self.config),
        executor=Executor(
            auto_approve=self.config.auto_approve,
            confirm_mode=self.config.confirm_mode,
        ),
        context=context,
        memory=create_runtime_memory(self.config),
    )

RuntimeContext dataclass

RuntimeContext(
    runtime_id: str = (lambda: uuid.uuid4().hex)(),
    tool_registry: ToolRegistry | None = None,
    skill_manager: SkillManager | None = None,
    hook_bus: HookBus | None = None,
    session_manager: SessionManager | None = None,
    capability_tools: dict[str, set[str]] = dict(),
    mcp_clients: dict = dict(),
    permission_policy: object | None = None,
    extensions: object | None = None,
)

Instance-local mutable registries owned by one Runtime.

runtime_id class-attribute instance-attribute

runtime_id: str = field(
    default_factory=lambda: uuid.uuid4().hex
)

tool_registry class-attribute instance-attribute

tool_registry: ToolRegistry | None = None

skill_manager class-attribute instance-attribute

skill_manager: SkillManager | None = None

hook_bus class-attribute instance-attribute

hook_bus: HookBus | None = None

session_manager class-attribute instance-attribute

session_manager: SessionManager | None = None

capability_tools class-attribute instance-attribute

capability_tools: dict[str, set[str]] = field(
    default_factory=dict
)

mcp_clients class-attribute instance-attribute

mcp_clients: dict = field(default_factory=dict)

permission_policy class-attribute instance-attribute

permission_policy: object | None = None

extensions class-attribute instance-attribute

extensions: object | None = None

create classmethod

create(config: Config) -> 'RuntimeContext'

Create an isolated context from the imported built-in baseline.

Source code in src/dashscope_agenticx/runtime.py
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
@classmethod
def create(cls, config: Config) -> "RuntimeContext":
    """Create an isolated context from the imported built-in baseline."""
    del config  # reserved for later policy/session factories
    import_builtin_tools()

    from dashscope_agenticx.hooks import create_hook_bus
    from dashscope_agenticx.session import SessionManager
    from dashscope_agenticx.skills.manager import SkillManager
    from dashscope_agenticx.tools.registry import registry
    from dashscope_agenticx.permission import (
        get_permission_policy,
        load_permission_policy,
    )
    from dashscope_agenticx.extensions import current

    tool_registry = registry.clone()
    return cls(
        runtime_id=uuid.uuid4().hex,
        tool_registry=tool_registry,
        skill_manager=SkillManager(tool_registry=tool_registry),
        hook_bus=create_hook_bus(),
        session_manager=SessionManager(),
        capability_tools={},
        permission_policy=load_permission_policy(
            copy.deepcopy(get_permission_policy()),
        ),
        extensions=copy.deepcopy(current()),
    )

import_builtin_tools

import_builtin_tools() -> None

Populate the default registry with all built-in static tools.

Source code in src/dashscope_agenticx/runtime.py
33
34
35
36
37
38
39
40
41
42
def import_builtin_tools() -> None:
    """Populate the default registry with all built-in static tools."""
    import dashscope_agenticx.tools.filesystem  # noqa: F401
    import dashscope_agenticx.tools.shell  # noqa: F401
    import dashscope_agenticx.tools.web_search  # noqa: F401

    if importlib.util.find_spec("playwright") is not None:
        import dashscope_agenticx.tools.browser  # noqa: F401
    if importlib.util.find_spec("cv2") is not None:
        import dashscope_agenticx.tools.camera  # noqa: F401

create_runtime_memory

create_runtime_memory(
    config: Config,
) -> MemoryProvider | None

Create and publish the configured memory provider, if enabled.

Source code in src/dashscope_agenticx/runtime.py
54
55
56
57
58
59
60
def create_runtime_memory(config: Config) -> MemoryProvider | None:
    """Create and publish the configured memory provider, if enabled."""
    if not config.memory_enabled:
        return None
    from dashscope_agenticx.platforms import get_memory_provider

    return get_memory_provider(config)

事件

AgentEventType

Bases: str, Enum

Stable event names for the public runtime stream.

RUN_STARTED class-attribute instance-attribute

RUN_STARTED = 'run.started'

MESSAGE_DELTA class-attribute instance-attribute

MESSAGE_DELTA = 'message.delta'

REASONING_DELTA class-attribute instance-attribute

REASONING_DELTA = 'reasoning.delta'

PLAN_UPDATED class-attribute instance-attribute

PLAN_UPDATED = 'plan.updated'

COMPRESSION_COMPLETED class-attribute instance-attribute

COMPRESSION_COMPLETED = 'compression.completed'

PROVIDER_SWITCHED class-attribute instance-attribute

PROVIDER_SWITCHED = 'provider.switched'

PERMISSION_REQUESTED class-attribute instance-attribute

PERMISSION_REQUESTED = 'permission.requested'

PERMISSION_RESOLVED class-attribute instance-attribute

PERMISSION_RESOLVED = 'permission.resolved'

TOOL_STARTED class-attribute instance-attribute

TOOL_STARTED = 'tool.started'

TOOL_FINISHED class-attribute instance-attribute

TOOL_FINISHED = 'tool.finished'

USAGE_UPDATED class-attribute instance-attribute

USAGE_UPDATED = 'usage.updated'

ARTIFACT_CREATED class-attribute instance-attribute

ARTIFACT_CREATED = 'artifact.created'

SANDBOX_STATUS class-attribute instance-attribute

SANDBOX_STATUS = 'sandbox.status'

TURN_FINISHED class-attribute instance-attribute

TURN_FINISHED = 'turn.finished'

ERROR class-attribute instance-attribute

ERROR = 'error'

AgentEventEnvelope dataclass

AgentEventEnvelope(
    type: AgentEventType,
    payload: dict[str, Any] = dict(),
    schema_version: str = "1.0",
    runtime_id: str = "",
    agent_id: str = "",
    session_id: str = "",
    run_id: str = "",
    turn_id: str = "",
    sequence: int = 0,
    event_id: str = (lambda: uuid.uuid4().hex)(),
    parent_event_id: str = "",
    timestamp: str = (
        lambda: datetime.now(timezone.utc).isoformat()
    )(),
)

Versioned immutable envelope emitted by an Agent run.

type instance-attribute

type: AgentEventType

payload class-attribute instance-attribute

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

schema_version class-attribute instance-attribute

schema_version: str = '1.0'

runtime_id class-attribute instance-attribute

runtime_id: str = ''

agent_id class-attribute instance-attribute

agent_id: str = ''

session_id class-attribute instance-attribute

session_id: str = ''

run_id class-attribute instance-attribute

run_id: str = ''

turn_id class-attribute instance-attribute

turn_id: str = ''

sequence class-attribute instance-attribute

sequence: int = 0

event_id class-attribute instance-attribute

event_id: str = field(
    default_factory=lambda: uuid.uuid4().hex
)

parent_event_id class-attribute instance-attribute

parent_event_id: str = ''

timestamp class-attribute instance-attribute

timestamp: str = field(
    default_factory=lambda: datetime.now(
        timezone.utc
    ).isoformat()
)

AgentEvent module-attribute

AgentEvent = AgentEventEnvelope

ToolDisplayText

Bases: str

Legacy display text retaining the identity of its tool call.

tool_call_id instance-attribute

tool_call_id: str

name instance-attribute

name: str

iter_message_deltas async

iter_message_deltas(
    agent, user_input
) -> AsyncIterator[str]

Yield display text from the typed API with legacy-agent fallback.

Source code in src/dashscope_agenticx/events.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
async def iter_message_deltas(agent, user_input) -> AsyncIterator[str]:
    """Yield display text from the typed API with legacy-agent fallback."""
    run_events = getattr(type(agent), "run_events", None)
    if run_events is None:
        async for chunk in agent.run_stream(user_input):
            yield chunk
        return

    async for event in agent.run_events(user_input):
        if event.type == AgentEventType.MESSAGE_DELTA:
            yield str(event.payload.get("text", ""))