ctx-sdk 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ctx/__init__.py +149 -0
- ctx/agent/README.md +142 -0
- ctx/agent/__init__.py +60 -0
- ctx/agent/agent_runner.py +91 -0
- ctx/agent/agents/__init__.py +61 -0
- ctx/agent/agents/activate.py +156 -0
- ctx/agent/agents/api.py +355 -0
- ctx/agent/agents/discovery.py +113 -0
- ctx/agent/agents/loader.py +197 -0
- ctx/agent/agents/registry.py +190 -0
- ctx/agent/agents/schema.py +172 -0
- ctx/agent/async_utils.py +40 -0
- ctx/agent/background.py +425 -0
- ctx/agent/context/__init__.py +45 -0
- ctx/agent/context/_xml.py +8 -0
- ctx/agent/context/agent_mds.py +134 -0
- ctx/agent/context/git.py +70 -0
- ctx/agent/context/loader.py +51 -0
- ctx/agent/context/skills.py +671 -0
- ctx/agent/context_governance.py +110 -0
- ctx/agent/dispatcher.py +94 -0
- ctx/agent/hooks/__init__.py +45 -0
- ctx/agent/hooks/agent_hook.py +161 -0
- ctx/agent/hooks/bridge.py +333 -0
- ctx/agent/hooks/loader.py +176 -0
- ctx/agent/hooks/registry.py +140 -0
- ctx/agent/hooks/runtime.py +157 -0
- ctx/agent/hooks/types.py +137 -0
- ctx/agent/loop.py +696 -0
- ctx/agent/prompts/__init__.py +35 -0
- ctx/agent/prompts/builder.py +139 -0
- ctx/agent/prompts/env.py +53 -0
- ctx/agent/prompts/registry.py +81 -0
- ctx/agent/prompts/tooling.py +42 -0
- ctx/agent/revert.py +597 -0
- ctx/agent/runtime.py +1842 -0
- ctx/agent/sdk/__init__.py +142 -0
- ctx/agent/sdk/_version.py +9 -0
- ctx/agent/sdk/agent.py +514 -0
- ctx/agent/sdk/approvals.py +104 -0
- ctx/agent/sdk/guardrails/__init__.py +193 -0
- ctx/agent/sdk/guardrails/types.py +132 -0
- ctx/agent/sdk/handoffs.py +162 -0
- ctx/agent/sdk/items.py +145 -0
- ctx/agent/sdk/items_base.py +21 -0
- ctx/agent/sdk/permissions.py +127 -0
- ctx/agent/sdk/results.py +55 -0
- ctx/agent/sdk/run_config.py +67 -0
- ctx/agent/sdk/runner.py +857 -0
- ctx/agent/sdk/sessions.py +260 -0
- ctx/agent/sdk/skills.py +55 -0
- ctx/agent/sdk/tools.py +374 -0
- ctx/agent/session.py +1204 -0
- ctx/agent/skills.py +62 -0
- ctx/agent/skills_refresh.py +168 -0
- ctx/agent/snapshot.py +539 -0
- ctx/agent/subagent.py +505 -0
- ctx/agent/subagents.py +139 -0
- ctx/agent/tools/__init__.py +285 -0
- ctx/agent/tools/base.py +83 -0
- ctx/agent/tools/schema.py +173 -0
- ctx/agent/tools/schema_tool.py +140 -0
- ctx/agent/tools_manager.py +224 -0
- ctx/agent/turn.py +1497 -0
- ctx/ai/README.md +159 -0
- ctx/ai/__init__.py +203 -0
- ctx/ai/_httpcore_patch.py +267 -0
- ctx/ai/base.py +452 -0
- ctx/ai/context_length.py +504 -0
- ctx/ai/dynamic_models.py +1389 -0
- ctx/ai/model_fetcher.py +506 -0
- ctx/ai/models.py +122 -0
- ctx/ai/oauth/__init__.py +157 -0
- ctx/ai/oauth/cline.py +541 -0
- ctx/ai/oauth/codex.py +574 -0
- ctx/ai/oauth/copilot.py +380 -0
- ctx/ai/oauth/deepai.py +427 -0
- ctx/ai/oauth/devin/__init__.py +696 -0
- ctx/ai/oauth/devin/descriptors.pb +0 -0
- ctx/ai/oauth/devin/proto.py +161 -0
- ctx/ai/oauth/dynamic.py +407 -0
- ctx/ai/oauth/freepi.py +118 -0
- ctx/ai/oauth/junie.py +728 -0
- ctx/ai/phase_parser.py +270 -0
- ctx/ai/provider.yaml +783 -0
- ctx/ai/provider_catalog.py +813 -0
- ctx/ai/provider_hooks.py +139 -0
- ctx/ai/providers/__init__.py +57 -0
- ctx/ai/providers/anthropic_sdk.py +315 -0
- ctx/ai/providers/mock.py +279 -0
- ctx/ai/providers/openai_responses_sdk.py +36 -0
- ctx/ai/providers/openai_sdk.py +349 -0
- ctx/ai/providers/sanitize.py +14 -0
- ctx/ai/py.typed +0 -0
- ctx/ai/rate_limit.py +214 -0
- ctx/ai/sdk/__init__.py +13 -0
- ctx/ai/sdk/_sse.py +37 -0
- ctx/ai/sdk/anthropic.py +428 -0
- ctx/ai/sdk/base.py +90 -0
- ctx/ai/sdk/openai.py +545 -0
- ctx/ai/sdk/openai_responses.py +593 -0
- ctx/ai/streaming_json.py +588 -0
- ctx/ai/thinking.py +406 -0
- ctx/ai/tool_parser.py +161 -0
- ctx/core/README.md +173 -0
- ctx/core/__init__.py +135 -0
- ctx/core/bytes_util.py +32 -0
- ctx/core/compaction.py +262 -0
- ctx/core/config.py +1349 -0
- ctx/core/defaults/__init__.py +0 -0
- ctx/core/defaults/config.yml +122 -0
- ctx/core/events.py +335 -0
- ctx/core/handoff.py +51 -0
- ctx/core/harness_config.py +58 -0
- ctx/core/image.py +106 -0
- ctx/core/notify.py +113 -0
- ctx/core/paths.py +78 -0
- ctx/core/permissions.py +238 -0
- ctx/core/py.typed +0 -0
- ctx/core/recap.py +169 -0
- ctx/core/scratchpad.py +54 -0
- ctx/core/session_retention.py +171 -0
- ctx/core/sounds/completion.wav +0 -0
- ctx/core/sounds/error.wav +0 -0
- ctx/core/sounds/permission.wav +0 -0
- ctx/core/themes.py +1150 -0
- ctx/core/token_usage.py +245 -0
- ctx/core/version.py +47 -0
- ctx/git/README.md +91 -0
- ctx/git/__init__.py +1 -0
- ctx/git/gh_app.py +349 -0
- ctx/git/gh_cli.py +83 -0
- ctx/git/git_branch.py +91 -0
- ctx/plugins/README.md +54 -0
- ctx/plugins/__init__.py +98 -0
- ctx/plugins/api.py +697 -0
- ctx/plugins/bootstrap.py +87 -0
- ctx/plugins/builtins/__init__.py +102 -0
- ctx/plugins/builtins/commands.py +59 -0
- ctx/plugins/builtins/hooks.py +143 -0
- ctx/plugins/builtins/services/__init__.py +3 -0
- ctx/plugins/builtins/services/agent_loop.py +50 -0
- ctx/plugins/builtins/services/agents.py +14 -0
- ctx/plugins/builtins/services/compaction.py +14 -0
- ctx/plugins/builtins/services/extensions.py +25 -0
- ctx/plugins/builtins/services/llm.py +22 -0
- ctx/plugins/builtins/services/permissions.py +20 -0
- ctx/plugins/builtins/services/projections.py +46 -0
- ctx/plugins/builtins/services/prompts.py +28 -0
- ctx/plugins/builtins/services/sessions.py +14 -0
- ctx/plugins/builtins/services/skills.py +14 -0
- ctx/plugins/builtins/services/telemetry.py +28 -0
- ctx/plugins/builtins/services/tools.py +21 -0
- ctx/plugins/builtins/tools/__init__.py +10 -0
- ctx/plugins/builtins/tools/_register.py +18 -0
- ctx/plugins/builtins/ui.py +63 -0
- ctx/plugins/bus.py +281 -0
- ctx/plugins/context.py +264 -0
- ctx/plugins/errors.py +41 -0
- ctx/plugins/event_contract.py +499 -0
- ctx/plugins/events.py +232 -0
- ctx/plugins/extensions.py +503 -0
- ctx/plugins/host.py +157 -0
- ctx/plugins/install.py +307 -0
- ctx/plugins/loader.py +328 -0
- ctx/plugins/plugin.py +107 -0
- ctx/plugins/profile.py +170 -0
- ctx/plugins/services.py +587 -0
- ctx/protocol/README.md +170 -0
- ctx/protocol/__init__.py +63 -0
- ctx/protocol/abc.py +30 -0
- ctx/protocol/errors.py +17 -0
- ctx/protocol/types.py +290 -0
- ctx/sdk/__init__.py +524 -0
- ctx/telemetry/README.md +132 -0
- ctx/telemetry/__init__.py +41 -0
- ctx/telemetry/exporters/__init__.py +14 -0
- ctx/telemetry/exporters/console.py +45 -0
- ctx/telemetry/exporters/jsonl.py +84 -0
- ctx/telemetry/processor.py +35 -0
- ctx/telemetry/tracing_impl.py +249 -0
- ctx_sdk-0.1.0.dist-info/METADATA +108 -0
- ctx_sdk-0.1.0.dist-info/RECORD +184 -0
- ctx_sdk-0.1.0.dist-info/WHEEL +4 -0
ctx/__init__.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""Ctx — the minimalist agent harness.
|
|
2
|
+
|
|
3
|
+
Re-exports the whole agent surface. Every name here is resolved lazily through
|
|
4
|
+
:func:`__getattr__`, because importing :mod:`ctx` used to import the entire SDK
|
|
5
|
+
at package-import time.
|
|
6
|
+
|
|
7
|
+
Keep ``_SOURCES`` in this order so a name exported by more than one of them
|
|
8
|
+
still resolves to the same object the eager re-exports produced.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import importlib
|
|
12
|
+
from pkgutil import extend_path
|
|
13
|
+
from typing import TYPE_CHECKING, Any
|
|
14
|
+
|
|
15
|
+
# ``ctx-code`` ships ``ctx.code`` / ``ctx.term`` from its own sources.
|
|
16
|
+
# Editable installs keep the two trees on separate ``sys.path`` entries, so the
|
|
17
|
+
# submodules only resolve if this package's path is extended to cover them.
|
|
18
|
+
__path__ = extend_path(__path__, __name__)
|
|
19
|
+
|
|
20
|
+
if TYPE_CHECKING:
|
|
21
|
+
from ctx.agent.sdk import (
|
|
22
|
+
Agent,
|
|
23
|
+
AllowlistApprove,
|
|
24
|
+
AutoApprove,
|
|
25
|
+
ConsoleTraceProcessor,
|
|
26
|
+
FunctionTool,
|
|
27
|
+
GuardrailFunctionOutput,
|
|
28
|
+
Handoff,
|
|
29
|
+
HandoffCallItem,
|
|
30
|
+
HandoffInputData,
|
|
31
|
+
HandoffOutputItem,
|
|
32
|
+
InMemorySession,
|
|
33
|
+
InputGuardrail,
|
|
34
|
+
InputGuardrailTripwireTriggered,
|
|
35
|
+
JSONLSession,
|
|
36
|
+
JSONLTraceProcessor,
|
|
37
|
+
MessageOutputItem,
|
|
38
|
+
OutputGuardrail,
|
|
39
|
+
OutputGuardrailTripwireTriggered,
|
|
40
|
+
PermissionDecision,
|
|
41
|
+
PermissionPolicy,
|
|
42
|
+
PromptApprove,
|
|
43
|
+
ReasoningItem,
|
|
44
|
+
RunConfig,
|
|
45
|
+
RunItem,
|
|
46
|
+
Runner,
|
|
47
|
+
RunResult,
|
|
48
|
+
RunStreamed,
|
|
49
|
+
Session,
|
|
50
|
+
SessionSettings,
|
|
51
|
+
Span,
|
|
52
|
+
ToolApprovalItem,
|
|
53
|
+
ToolCallItem,
|
|
54
|
+
ToolCallOutputItem,
|
|
55
|
+
ToolGuardrailFunctionOutput,
|
|
56
|
+
ToolInputGuardrailTripwireTriggered,
|
|
57
|
+
ToolOutputGuardrailTripwireTriggered,
|
|
58
|
+
Trace,
|
|
59
|
+
TraceProcessor,
|
|
60
|
+
Usage,
|
|
61
|
+
_ToolApprovalItem,
|
|
62
|
+
add_trace_processor,
|
|
63
|
+
disable_tracing,
|
|
64
|
+
enable_tracing,
|
|
65
|
+
handoff,
|
|
66
|
+
input_guardrail,
|
|
67
|
+
output_guardrail,
|
|
68
|
+
span,
|
|
69
|
+
tool,
|
|
70
|
+
tool_input_guardrail,
|
|
71
|
+
tool_output_guardrail,
|
|
72
|
+
trace,
|
|
73
|
+
)
|
|
74
|
+
from ctx.protocol import Message
|
|
75
|
+
|
|
76
|
+
_SOURCES = ("ctx.agent.sdk", "ctx.protocol")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def __getattr__(name: str) -> Any:
|
|
80
|
+
for module_name in _SOURCES:
|
|
81
|
+
module = importlib.import_module(module_name)
|
|
82
|
+
if (value := getattr(module, name, None)) is not None:
|
|
83
|
+
# Cache into ``__dict__``: PEP 562 only fires ``__getattr__`` while
|
|
84
|
+
# the name is absent, and the import system would otherwise rebind
|
|
85
|
+
# any submodule sharing an exported name onto this package.
|
|
86
|
+
globals()[name] = value
|
|
87
|
+
return value
|
|
88
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def __dir__() -> list[str]:
|
|
92
|
+
return sorted(__all__)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
__all__ = [
|
|
96
|
+
# SDK
|
|
97
|
+
"Agent",
|
|
98
|
+
"AllowlistApprove",
|
|
99
|
+
"AutoApprove",
|
|
100
|
+
"ConsoleTraceProcessor",
|
|
101
|
+
"FunctionTool",
|
|
102
|
+
"GuardrailFunctionOutput",
|
|
103
|
+
"Handoff",
|
|
104
|
+
"HandoffCallItem",
|
|
105
|
+
"HandoffInputData",
|
|
106
|
+
"HandoffOutputItem",
|
|
107
|
+
"InMemorySession",
|
|
108
|
+
"InputGuardrail",
|
|
109
|
+
"InputGuardrailTripwireTriggered",
|
|
110
|
+
"JSONLSession",
|
|
111
|
+
"JSONLTraceProcessor",
|
|
112
|
+
"Message",
|
|
113
|
+
"MessageOutputItem",
|
|
114
|
+
"OutputGuardrail",
|
|
115
|
+
"OutputGuardrailTripwireTriggered",
|
|
116
|
+
"PermissionDecision",
|
|
117
|
+
"PermissionPolicy",
|
|
118
|
+
"PromptApprove",
|
|
119
|
+
"ReasoningItem",
|
|
120
|
+
"RunConfig",
|
|
121
|
+
"RunItem",
|
|
122
|
+
"RunResult",
|
|
123
|
+
"RunStreamed",
|
|
124
|
+
"Runner",
|
|
125
|
+
"Session",
|
|
126
|
+
"SessionSettings",
|
|
127
|
+
"Span",
|
|
128
|
+
"ToolApprovalItem",
|
|
129
|
+
"ToolCallItem",
|
|
130
|
+
"ToolCallOutputItem",
|
|
131
|
+
"ToolGuardrailFunctionOutput",
|
|
132
|
+
"ToolInputGuardrailTripwireTriggered",
|
|
133
|
+
"ToolOutputGuardrailTripwireTriggered",
|
|
134
|
+
"Trace",
|
|
135
|
+
"TraceProcessor",
|
|
136
|
+
"Usage",
|
|
137
|
+
"_ToolApprovalItem",
|
|
138
|
+
"add_trace_processor",
|
|
139
|
+
"disable_tracing",
|
|
140
|
+
"enable_tracing",
|
|
141
|
+
"handoff",
|
|
142
|
+
"input_guardrail",
|
|
143
|
+
"output_guardrail",
|
|
144
|
+
"span",
|
|
145
|
+
"tool",
|
|
146
|
+
"tool_input_guardrail",
|
|
147
|
+
"tool_output_guardrail",
|
|
148
|
+
"trace",
|
|
149
|
+
]
|
ctx/agent/README.md
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
# `ctx.agent`
|
|
2
|
+
|
|
3
|
+
The product-neutral agent harness behind ctx. It owns the turn loop, the composition root, the `BaseTool` contract, prompt and context assembly, sessions, sub-agent dispatch, hooks, and a programmatic SDK. It never imports `ctx.code` or `ctx.term` at module level, so both the TUI and the headless runner drive the same `ConversationRuntime` without the harness depending on either. This package used to be nested at `ctx.ai.agent`, which made `ctx.ai` a 116-module grab bag holding the whole runtime; it is now a top-level sibling of `ctx.ai`, which now contains only provider code.
|
|
4
|
+
|
|
5
|
+
## Usage
|
|
6
|
+
|
|
7
|
+
The SDK is the shortest way in. Build an `Agent`, give it a tool, run it:
|
|
8
|
+
|
|
9
|
+
```python
|
|
10
|
+
import asyncio
|
|
11
|
+
|
|
12
|
+
from ctx.agent.sdk import Agent, Runner, tool
|
|
13
|
+
from ctx.ai.providers.mock import MockProvider
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@tool
|
|
17
|
+
def get_weather(city: str) -> str:
|
|
18
|
+
"""Return the current weather for a city."""
|
|
19
|
+
return f"Sunny in {city}"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
agent = Agent(
|
|
23
|
+
name="Weather bot",
|
|
24
|
+
instructions="Be concise.",
|
|
25
|
+
model="gpt-4o-mini",
|
|
26
|
+
provider=MockProvider(scenario="simple_text"),
|
|
27
|
+
tools=[get_weather],
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
result = asyncio.run(Runner.run(agent, "Weather in Tokyo?"))
|
|
31
|
+
|
|
32
|
+
print(result.stop_reason) # stop
|
|
33
|
+
print(result.final_output) # the assistant's final text
|
|
34
|
+
print(result.usage) # aggregated tokens across every turn
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
`MockProvider` (`ctx.ai.providers.mock`) replays scripted streams, so this runs offline. Drop it and set a provider dict for a real call - the recognised keys are `name`, `sdk`, `api_key`, `base_url`, `model`, `max_tokens`, `temperature`, `thinking_level`, `default_headers`:
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
agent = Agent(name="Ops", model="gpt-4o", provider={"name": "openai"}, tools=[deploy])
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
`Runner.run`, `Runner.run_sync` and `Runner.run_streamed` share one signature: `(starting_agent, input, *, session=None, run_config=None, max_turns=None, cancellation=None, context=None)`.
|
|
44
|
+
|
|
45
|
+
- **`Agent`** is a dataclass: `name`, `instructions` (a string or a callable), `model`, `provider` (a `BaseProvider`, a dict, or `None` for env/config fallback), `tools`, `handoffs`, `output_type`, `input_guardrails`, `output_guardrails`, `tool_use_behavior`, `metadata`, `needs_approval_tools`. `agent.clone(**overrides)` copies it with overrides.
|
|
46
|
+
- **`RunResult`** carries `final_output`, `new_items`, `interruptions`, `state`, `stop_reason`, `usage`, `agent_name`. `to_input_list()` turns the run back into input items you can feed to a later `Runner.run`.
|
|
47
|
+
- **`@tool`** turns a typed Python function into a `BaseTool`. The docstring becomes the model-facing description. Keyword arguments: `name`, `description`, `needs_approval` (default `False`; `True` is meant to pause for approval), `mutating` (default `True`; `False` marks the tool read-only), `input_guardrails`, `output_guardrails`, `tool_icon`. See "Approvals and permissions" below for which of these the runner actually honours today.
|
|
48
|
+
- **`Runner.run_streamed`** returns an async iterable of events; `.result` is only valid after the iterator is exhausted, and raises `RuntimeError` if read earlier.
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
stream = Runner.run_streamed(agent, "Weather in Tokyo?")
|
|
52
|
+
async for event in stream:
|
|
53
|
+
print(type(event).__name__)
|
|
54
|
+
print(stream.result.final_output)
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
- **`handoff(agent, *, tool_name_override, tool_description_override, on_handoff, input_filter, input_type)`** turns another `Agent` into a transfer tool on the caller. Give the caller `handoffs=[handoff(triage, tool_name_override="escalate")]` and the model can hand the conversation over; `on_handoff` runs when the handoff tool executes. `input_type` becomes the handoff tool's parameter schema; `input_filter` is accepted but the runner does not invoke it yet.
|
|
58
|
+
- **`JSONLSession(path=None, *, session_id=None)`** persists a run to the same append-only format the TUI and headless runner use, so a session started from the SDK can be resumed in the TUI and the other way round. Without a `path` it is in-memory only.
|
|
59
|
+
- **`InMemorySession(session_id=None)`** keeps items for the life of the process.
|
|
60
|
+
- **`SessionSettings(limit=...)`** caps how much history a session replays into a run.
|
|
61
|
+
- **`RunConfig`** is the per-run knob bag: `max_turns` (default 50), `permission_policy`, `session_settings`, `tracing_disabled`, `trace_include_sensitive_data`, `nest_handoff_history`, `session_input_callback`, `custom`.
|
|
62
|
+
|
|
63
|
+
[docs/sdk.md](../../docs/sdk.md) covers the SDK in depth: the runner, agents and handoffs, tools, approvals, permissions, guardrails, sessions, skills, and tracing.
|
|
64
|
+
|
|
65
|
+
## Approvals and permissions
|
|
66
|
+
|
|
67
|
+
Read this section as the intended design, not the shipped behaviour. The types and the pause branch exist, but nothing feeds them yet:
|
|
68
|
+
|
|
69
|
+
- `PermissionPolicy` / `AutoApprove` / `AllowlistApprove` / `PromptApprove` / `PermissionCallback` are defined in `sdk/permissions.py`, and `RunConfig.permission_policy` accepts one per run -- but `Runner` never reads it.
|
|
70
|
+
- `needs_approval=True` on `@tool` and `Agent.needs_approval_tools` are stored but never consulted.
|
|
71
|
+
- `RunResult.interruptions` / `.state` and the `stop_reason="tool_use"` pause branch in `_run_impl` exist, but `pending_tool_calls` is never populated, so a run never actually pauses for approval.
|
|
72
|
+
- `RunState.approve` / `.reject` / `.decision_for` work as data structures; `decision_for` is never called from the runner, and there is no way to pass a `RunState` back into `Runner.run`.
|
|
73
|
+
|
|
74
|
+
What *does* gate tool calls is the turn engine's `ctx.core.permissions.check_permission` against `~/.ctx/config.yml` (`permissions.mode`, default `"prompt"`). Under `prompt`, a `mutating=True` tool makes the engine emit a `ToolApprovalEvent` whose future the SDK runner never resolves, so the run hangs until `cancellation` fires. In practice: mark SDK tools `mutating=False`, or run with `permissions.mode: auto`.
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
from ctx.agent.sdk import Agent, Runner, RunConfig, AllowlistApprove
|
|
78
|
+
|
|
79
|
+
# permission_policy is accepted but currently ignored by Runner.
|
|
80
|
+
result = await Runner.run(
|
|
81
|
+
agent, "Ship v2", run_config=RunConfig(permission_policy=AllowlistApprove(["read", "grep"]))
|
|
82
|
+
)
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
`ToolApprovalItem.to_input_item()` raises by design - filter approvals out before sending an input list back to the model.
|
|
86
|
+
|
|
87
|
+
## Composition root
|
|
88
|
+
|
|
89
|
+
`ConversationRuntime` (`runtime.py`) is the object both run surfaces drive. It takes a cwd, a model selection, an explicit tool list and optional agent-registry and event-bus wiring, and it owns provider construction, tool activation, model and thinking-level switches, compaction, handoff, sessions, and the background-task manager.
|
|
90
|
+
|
|
91
|
+
It also reads two services off the plugin composition the process booted, and falls back to the built-in path when a run has none mounted: `ctx.prompts` for system-prompt assembly and `ctx.agentLoop` for which driver builds the engine. See `ctx.plugins` and `docs/plugins.md`.
|
|
92
|
+
|
|
93
|
+
`DispatcherContext` (`dispatcher.py`) is the single parent-state slot that dispatching tools read: provider, model, `thinking_level`, `agent_registry`, `cwd`, `system_prompt`, and the product-installed `progress_callback`. `ConversationRuntime` repopulates it on initialise, agent change, model change and thinking-level change. A process with no runtime has no dispatcher context, which is why background sub-agent dispatch is unavailable in a bare headless test harness.
|
|
94
|
+
|
|
95
|
+
## The turn loop
|
|
96
|
+
|
|
97
|
+
Three modules, in order:
|
|
98
|
+
|
|
99
|
+
- `turn.py` (`run_single_turn`) is one request/response cycle: streaming, tool calls, permission checks, retries, cancellation.
|
|
100
|
+
- `agent_runner.py` (`run_agent_turn`) is a provider-agnostic single-turn wrapper around it.
|
|
101
|
+
- `loop.py` (`Agent.run`) is the outer loop: compaction between turns, follow-up and steer queues, background-task draining.
|
|
102
|
+
|
|
103
|
+
`context_governance.py` (`prepare_for_model(messages)`) sits in front of every model call. It is a pure function with no I/O: it drops `ToolResultMessage` entries whose `tool_call_id` no preceding assistant tool call matches (orphans from cancelled turns) and truncates any tool result over the per-result budget, replacing the body with a summary so the model keeps a pointer without carrying all of it.
|
|
104
|
+
|
|
105
|
+
`prompts/builder.py` (`build_system_prompt(cwd, context, tools, *, base_content, include_git_context, include_ponytail, extra_instructions, extra_instructions_mode, skills)`) assembles the prompt from the section modules `identity`, `tooling`, `env` and `ponytail`. `context/` holds the pieces it reads: AGENTS.md discovery, the skills catalog, and the git snapshot.
|
|
106
|
+
|
|
107
|
+
## Tools
|
|
108
|
+
|
|
109
|
+
`tools/base.py` (`BaseTool`) is the contract; `tools/__init__.py` is the global registry (`register_tool`, `register_tools`, `unregister_tool`, `get_tool`, `get_all_tools`, `get_default_tools`, `get_parent_only_tools`, `get_tool_definitions`) plus the JSON-schema slimming that keeps LLM tool definitions small. `tools/schema.py` converts JSON schema to Pydantic for argument validation.
|
|
110
|
+
|
|
111
|
+
**The harness ships no tools.** Every concrete tool — `ask_user`, `delegate_subagent`, `web`, `bash`, `read`, `skill`, `codemode`, `tool_search`, and friends — is implemented by a product package (`ctx/code/tools/` for the coding agent) and mounted through plugin rows, which is why a bare `import ctx.agent.tools` sees an empty registry while a booted composition sees the product's full tool set.
|
|
112
|
+
|
|
113
|
+
Tools marked parent-only at mount time (`ask_user`, `delegate_subagent` in the coding product) are excluded from sub-agent tool surfaces, so a sub-agent cannot recursively spawn one or block on a user prompt.
|
|
114
|
+
|
|
115
|
+
## Sub-agents
|
|
116
|
+
|
|
117
|
+
`delegate_subagent` is the only dispatch path. The harness keeps the dispatch *builder* in `subagent.py` (spec resolution, tool-list composition, system prompt, session creation, the run loop, progress events, scheduler admission); the tool itself — `TaskTool`/`TaskParams` — is implemented by the product (`ctx/code/tools/subagent.py`) on top of that API. It was renamed from `task` to avoid ambiguity with the todo list - a model told to "check the task" could mean the todo list or the dispatcher.
|
|
118
|
+
|
|
119
|
+
There are **no built-in sub-agent presets**. `subagent_type` resolves against user-defined agents in `.ctx/agent/` and `~/.ctx/agent/`; an empty or unknown name runs a default sub-agent with the parent's tool surface minus the parent-only tools, capped at `DEFAULT_MAX_TURNS = 200`. Results are truncated to `MAX_RESULT_CHARS = 32_000`, and transcripts are shown up to `MAX_TRANSCRIPT_LINES = 200` with a "... (n more)" tail.
|
|
120
|
+
|
|
121
|
+
Every dispatch goes through `SubagentScheduler` (`subagents.py`), a FIFO admission queue:
|
|
122
|
+
|
|
123
|
+
- The limit comes from `task.max_concurrent` in `ctx.core.config`, default `4`; `0` means uncapped. `SubagentScheduler.DEFAULT_MAX_CONCURRENT` is the fallback when config cannot be read.
|
|
124
|
+
- **A sub-agent over the cap waits for its slot before it builds a session or a provider.** Waiting happens in `_run_subagent` before `_run_admitted_subagent`, so `running` and `queued` are real counts the UI can render, not estimates.
|
|
125
|
+
- `set_limit()` resizes after a config reload without pre-empting anything in flight; it holds new arrivals only until the running count drops below the new limit. `reset_scheduler()` drops all queue state.
|
|
126
|
+
- The scheduler is deliberately dumb: one asyncio loop, one queue, no priorities, no cross-process state.
|
|
127
|
+
|
|
128
|
+
`subagent_type` resolution, session creation, provider derivation, the run loop and progress events are all internal to `_run_admitted_subagent`. Products override the runner through an explicit hook:
|
|
129
|
+
|
|
130
|
+
```python
|
|
131
|
+
from ctx.agent.subagent import set_subagent_runner, resolve_subagent_runner
|
|
132
|
+
|
|
133
|
+
set_subagent_runner(my_runner) # installs a replacement
|
|
134
|
+
resolve_subagent_runner() # returns it, or the built-in _run_subagent
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
That hook replaced three call sites that re-imported `ctx.agent.subagent` looking for a divergent `_run_subagent`. The module re-exports the very same function object, so the lookup could never have differed, and the back-edge to the product layer existed only to keep old monkeypatches alive.
|
|
138
|
+
|
|
139
|
+
`background: true` schedules through `BackgroundTaskManager` instead and returns a `task_id` immediately. Cancellation differs by design: a background task is not cancelled by the parent's `cancel_event` (its call already returned) and stops only explicitly or via `ConversationRuntime.close()`.
|
|
140
|
+
|
|
141
|
+
Sub-agents auto-approve their own approval prompts and answer `ask_user` with an empty response. They have no way to reach the user's terminal.
|
|
142
|
+
|
ctx/agent/__init__.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""The product-neutral harness: loop, turns, sessions, tools, extensions, SDK.
|
|
2
|
+
|
|
3
|
+
``ctx.agent`` owns the engine. The product layer (``ctx.code``) injects
|
|
4
|
+
everything engine-side: the system-prompt builder, the context loader, the tool
|
|
5
|
+
registry, and the user's configuration.
|
|
6
|
+
|
|
7
|
+
The names re-exported here are the ones call sites have always imported from
|
|
8
|
+
``ctx.agent``. They now live in :mod:`ctx.plugins`, because the event contract,
|
|
9
|
+
the extension API, and extension discovery are composition concerns; this module
|
|
10
|
+
keeps the historical import path working rather than breaking every caller.
|
|
11
|
+
|
|
12
|
+
The re-exports are lazy: importing this package used to mount the whole plugin
|
|
13
|
+
kernel, so reaching any leaf like ``ctx.agent.context.skills`` through it cost
|
|
14
|
+
~550ms the leaf does not use. Submodule imports (``from ctx.agent import
|
|
15
|
+
revert``) are unaffected — they fall through to the real submodule.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
import importlib
|
|
19
|
+
from typing import TYPE_CHECKING, Any
|
|
20
|
+
|
|
21
|
+
if TYPE_CHECKING:
|
|
22
|
+
from ctx.plugins.api import (
|
|
23
|
+
CommandOutcome,
|
|
24
|
+
ExtensionAPI,
|
|
25
|
+
ExtensionCommand,
|
|
26
|
+
ExtensionRecord,
|
|
27
|
+
ExtensionTool,
|
|
28
|
+
)
|
|
29
|
+
from ctx.plugins.event_contract import AGENT_CHANGED, AGENT_START
|
|
30
|
+
from ctx.plugins.extensions import LoadedExtensions, load_for_runtime
|
|
31
|
+
|
|
32
|
+
# Historical import order, so a name exported by more than one source still
|
|
33
|
+
# resolves to the object the eager re-exports produced.
|
|
34
|
+
_SOURCES = ("ctx.plugins.api", "ctx.plugins.event_contract", "ctx.plugins.extensions")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def __getattr__(name: str) -> Any:
|
|
38
|
+
for module_name in _SOURCES:
|
|
39
|
+
module = importlib.import_module(module_name)
|
|
40
|
+
if (value := getattr(module, name, None)) is not None:
|
|
41
|
+
globals()[name] = value
|
|
42
|
+
return value
|
|
43
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def __dir__() -> list[str]:
|
|
47
|
+
return sorted(__all__)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
__all__ = [
|
|
51
|
+
"AGENT_CHANGED",
|
|
52
|
+
"AGENT_START",
|
|
53
|
+
"CommandOutcome",
|
|
54
|
+
"ExtensionAPI",
|
|
55
|
+
"ExtensionCommand",
|
|
56
|
+
"ExtensionRecord",
|
|
57
|
+
"ExtensionTool",
|
|
58
|
+
"LoadedExtensions",
|
|
59
|
+
"load_for_runtime",
|
|
60
|
+
]
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Provider-agnostic single-turn execution engine.
|
|
2
|
+
|
|
3
|
+
A thin, transport-free function that runs one LLM turn and yields its events.
|
|
4
|
+
The product/transport loop in :mod:`ctx.loop` owns sessions, UI events,
|
|
5
|
+
and persistence; this module owns only the turn itself.
|
|
6
|
+
|
|
7
|
+
Today this delegates to :func:`ctx.turn.run_single_turn` so behavior is
|
|
8
|
+
unchanged. Later phases (stop-condition recovery, mid-turn injection,
|
|
9
|
+
checkpoint/resume, context governance) extend *this* function without touching
|
|
10
|
+
the TUI/headless/sdk callers of the loop.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import asyncio
|
|
14
|
+
from collections.abc import AsyncIterator, Callable
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from ctx.agent.hooks.agent_hook import AgentHook
|
|
19
|
+
from ctx.agent.tools import BaseTool
|
|
20
|
+
from ctx.ai import BaseProvider
|
|
21
|
+
from ctx.core.events import Event
|
|
22
|
+
from ctx.plugins.bus import EventBus
|
|
23
|
+
from ctx.protocol.types import Message
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass
|
|
27
|
+
class AgentRunSpec:
|
|
28
|
+
"""Input contract for one engine turn.
|
|
29
|
+
|
|
30
|
+
Intentionally small and additive — later phases add optional fields
|
|
31
|
+
(injection_callback, checkpoint_callback, hooks) without breaking callers
|
|
32
|
+
that only pass the required core fields.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
provider: BaseProvider
|
|
36
|
+
messages: list[Message]
|
|
37
|
+
tools: list[BaseTool]
|
|
38
|
+
system_prompt: str | None = None
|
|
39
|
+
turn: int = 0
|
|
40
|
+
cancel_event: asyncio.Event | None = None
|
|
41
|
+
extensions: EventBus | None = None
|
|
42
|
+
retry_delays: list[int] | None = None
|
|
43
|
+
# Optional callback polled after tool execution to inject follow-up user
|
|
44
|
+
# messages (sub-agent completions, queued prompts) mid-turn. Returning a
|
|
45
|
+
# non-empty list of messages extends the turn instead of ending it.
|
|
46
|
+
injection_callback: Callable[[], Any] | None = None
|
|
47
|
+
# Optional callback invoked after each tool batch to persist partial
|
|
48
|
+
# turn state (text so far + tool results) for cancel/resume. Receives a
|
|
49
|
+
# dict snapshot; return value is ignored.
|
|
50
|
+
checkpoint_callback: Callable[[dict[str, Any]], Any] | None = None
|
|
51
|
+
# In-process lifecycle hooks (AgentHook). Fired by the engine around
|
|
52
|
+
# run/iteration boundaries and stream deltas.
|
|
53
|
+
hooks: list[AgentHook] | None = None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
async def run_agent_turn(spec: AgentRunSpec) -> AsyncIterator[Event]:
|
|
57
|
+
"""Execute one turn and yield its events.
|
|
58
|
+
|
|
59
|
+
Faithful delegation to :func:`ctx.turn.run_single_turn`: same
|
|
60
|
+
:class:`~ctx.events.StreamEvent` sequence, same terminal
|
|
61
|
+
:class:`~ctx.events.TurnEndEvent`. The loop keeps consuming that event
|
|
62
|
+
unchanged. Later phases will own the recovery/injection loop here instead
|
|
63
|
+
of inside the turn module.
|
|
64
|
+
"""
|
|
65
|
+
from ctx.agent.turn import run_single_turn
|
|
66
|
+
|
|
67
|
+
async for event in run_single_turn(
|
|
68
|
+
provider=spec.provider,
|
|
69
|
+
messages=spec.messages,
|
|
70
|
+
tools=spec.tools,
|
|
71
|
+
system_prompt=spec.system_prompt,
|
|
72
|
+
turn=spec.turn,
|
|
73
|
+
cancel_event=spec.cancel_event,
|
|
74
|
+
retry_delays=spec.retry_delays,
|
|
75
|
+
extensions=spec.extensions,
|
|
76
|
+
injection_callback=spec.injection_callback,
|
|
77
|
+
checkpoint_callback=spec.checkpoint_callback,
|
|
78
|
+
hooks=_build_composite(spec.hooks),
|
|
79
|
+
):
|
|
80
|
+
yield event
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _build_composite(hooks: list[AgentHook] | None) -> AgentHook | None:
|
|
84
|
+
"""Build a CompositeHook from the spec hooks, or None if empty."""
|
|
85
|
+
if not hooks:
|
|
86
|
+
return None
|
|
87
|
+
# Imported lazily to keep the engine import-light and avoid any chance of
|
|
88
|
+
# a circular import at module load time.
|
|
89
|
+
from ctx.agent.hooks.agent_hook import CompositeHook
|
|
90
|
+
|
|
91
|
+
return CompositeHook(list(hooks))
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Switchable handoff agents (``.ctx/agent/<name>.py``).
|
|
2
|
+
|
|
3
|
+
A user-facing "agent" is a named, switchable bundle of:
|
|
4
|
+
|
|
5
|
+
* system-prompt instructions (appended or replacing the base identity)
|
|
6
|
+
* optional model / provider / thinking / max-turns overrides
|
|
7
|
+
* an optional tool allow/deny list
|
|
8
|
+
* agent-scoped local tools, slash commands, and permission gates
|
|
9
|
+
* agent-scoped extensions (Python files loaded only when this agent is active)
|
|
10
|
+
|
|
11
|
+
The discovery, loader, and registry mirror :mod:`ctx.extensions`. The
|
|
12
|
+
:class:`ctx.ConversationRuntime` holds an :class:`AgentRegistry` and a
|
|
13
|
+
single active :class:`LoadedAgent`; the active agent's tool/command set
|
|
14
|
+
replaces the runtime defaults when the runtime is set up.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
from .activate import (
|
|
20
|
+
active_permission_gates,
|
|
21
|
+
active_permission_mode,
|
|
22
|
+
compose_active_commands,
|
|
23
|
+
compose_active_tools,
|
|
24
|
+
)
|
|
25
|
+
from .api import AgentAPI, LoadedAgent
|
|
26
|
+
from .discovery import find_agent_paths
|
|
27
|
+
from .loader import AgentLoadError, load_agent, load_all_agents
|
|
28
|
+
from .registry import AgentRegistry
|
|
29
|
+
from .schema import AGENT_NAME_RE, MAX_AGENT_NAME_LEN, AgentDef, PermissionAction, PermissionGate
|
|
30
|
+
|
|
31
|
+
__all__ = [
|
|
32
|
+
"AGENT_ACTIVATED",
|
|
33
|
+
"AGENT_CHANGED",
|
|
34
|
+
"AGENT_NAME_RE",
|
|
35
|
+
"MAX_AGENT_NAME_LEN",
|
|
36
|
+
"TOOL_GROUP_CHANGED",
|
|
37
|
+
"AgentAPI",
|
|
38
|
+
"AgentDef",
|
|
39
|
+
"AgentLoadError",
|
|
40
|
+
"AgentRegistry",
|
|
41
|
+
"LoadedAgent",
|
|
42
|
+
"PermissionAction",
|
|
43
|
+
"PermissionGate",
|
|
44
|
+
"active_permission_gates",
|
|
45
|
+
"active_permission_mode",
|
|
46
|
+
"compose_active_commands",
|
|
47
|
+
"compose_active_tools",
|
|
48
|
+
"find_agent_paths",
|
|
49
|
+
"load_agent",
|
|
50
|
+
"load_all_agents",
|
|
51
|
+
]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def __getattr__(name: str) -> str:
|
|
55
|
+
if name in ("AGENT_ACTIVATED", "AGENT_CHANGED", "TOOL_GROUP_CHANGED"):
|
|
56
|
+
from ctx.plugins import event_contract as _contract
|
|
57
|
+
|
|
58
|
+
value = getattr(_contract, name)
|
|
59
|
+
globals()[name] = value
|
|
60
|
+
return value
|
|
61
|
+
raise AttributeError(f"module 'ctx.agent.agents' has no attribute {name!r}")
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"""Compose the active tool/command set from a base + the active agent.
|
|
2
|
+
|
|
3
|
+
The active tool set is::
|
|
4
|
+
|
|
5
|
+
built_in_tools (filtered by DEFAULT_TOOLS or runtime override)
|
|
6
|
+
+ session_extensions.tools (ExtensionAPI.register_tool)
|
|
7
|
+
+ active_agent.definition.extensions[].tools (loaded extensions per agent)
|
|
8
|
+
+ active_agent.local_tools (AgentAPI.local_tool)
|
|
9
|
+
- active_agent.tools_deny
|
|
10
|
+
intersect with active_agent.tools_allow (when non-empty)
|
|
11
|
+
|
|
12
|
+
Same formula for commands.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
# ``ExtensionCommand`` is imported lazily in :func:`compose_active_commands`
|
|
18
|
+
# to avoid a circular import at module load (extensions -> tools -> agents
|
|
19
|
+
# -> activate -> extensions).
|
|
20
|
+
from ctx.agent.agents.api import LoadedAgent
|
|
21
|
+
from ctx.agent.agents.registry import AgentRegistry
|
|
22
|
+
from ctx.agent.tools import BaseTool
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _filter(
|
|
26
|
+
base_names: list[str],
|
|
27
|
+
base_pool: dict[str, BaseTool],
|
|
28
|
+
extra_pool: dict[str, BaseTool],
|
|
29
|
+
allow: list[str] | None,
|
|
30
|
+
deny: list[str],
|
|
31
|
+
*,
|
|
32
|
+
always_keep: set[str] | None = None,
|
|
33
|
+
) -> list[BaseTool]:
|
|
34
|
+
seen: set[str] = set()
|
|
35
|
+
result: list[BaseTool] = []
|
|
36
|
+
always_keep = always_keep or set()
|
|
37
|
+
|
|
38
|
+
# 1. Built-in tools named in base_names (or in allow)
|
|
39
|
+
to_load = list(base_names)
|
|
40
|
+
if allow:
|
|
41
|
+
for n in allow:
|
|
42
|
+
if n in base_pool and n not in to_load:
|
|
43
|
+
to_load.append(n)
|
|
44
|
+
|
|
45
|
+
for n in to_load:
|
|
46
|
+
if n in seen:
|
|
47
|
+
continue
|
|
48
|
+
tool = base_pool.get(n)
|
|
49
|
+
if tool is not None:
|
|
50
|
+
result.append(tool)
|
|
51
|
+
seen.add(n)
|
|
52
|
+
|
|
53
|
+
# 2. Extra tools (extension tools + agent-scoped local tools)
|
|
54
|
+
for n, tool in extra_pool.items():
|
|
55
|
+
if n in seen:
|
|
56
|
+
continue
|
|
57
|
+
result.append(tool)
|
|
58
|
+
seen.add(n)
|
|
59
|
+
|
|
60
|
+
# 3. Apply deny. The ``always_keep`` set exempts tools the agent
|
|
61
|
+
# explicitly contributed: a local tool registered via
|
|
62
|
+
# ``api.local_tool`` is part of the agent's profile and must not be
|
|
63
|
+
# stripped by the agent's own deny list. (Mirrors how extension
|
|
64
|
+
# tools win over built-ins — the agent's contributions are first-class.)
|
|
65
|
+
if deny:
|
|
66
|
+
deny_set = set(deny) - always_keep
|
|
67
|
+
result = [t for t in result if t.name not in deny_set]
|
|
68
|
+
|
|
69
|
+
# 4. Apply allow (if non-empty, intersect). Tools in ``always_keep``
|
|
70
|
+
# are exempt so the agent can ship its own local tools alongside a
|
|
71
|
+
# restrictive allow list.
|
|
72
|
+
if allow:
|
|
73
|
+
allow_set = set(allow) | always_keep
|
|
74
|
+
result = [t for t in result if t.name in allow_set]
|
|
75
|
+
|
|
76
|
+
return result
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def compose_active_tools(
|
|
80
|
+
*,
|
|
81
|
+
base_tool_names: list[str],
|
|
82
|
+
base_tool_pool: dict[str, BaseTool],
|
|
83
|
+
extension_tools: list[BaseTool],
|
|
84
|
+
active_agent: LoadedAgent | None,
|
|
85
|
+
) -> list[BaseTool]:
|
|
86
|
+
"""Compute the active tool list for the runtime.
|
|
87
|
+
|
|
88
|
+
``extension_tools`` should be the full list of tools contributed by
|
|
89
|
+
session-scoped extensions (``ExtensionAPI.register_tool``), already
|
|
90
|
+
with extension-wins-over-built-in ordering applied.
|
|
91
|
+
"""
|
|
92
|
+
extra: dict[str, BaseTool] = {t.name: t for t in extension_tools}
|
|
93
|
+
if active_agent is not None:
|
|
94
|
+
for t in active_agent.local_tools.values():
|
|
95
|
+
extra[t.name] = t # agent-local tools win over session extensions
|
|
96
|
+
|
|
97
|
+
allow = active_agent.definition.tools_allow if active_agent else None
|
|
98
|
+
deny = active_agent.definition.tools_deny if active_agent else []
|
|
99
|
+
# The agent's own local tools are exempt from its allow/deny filters:
|
|
100
|
+
# they were explicitly contributed by the agent, not pulled from the
|
|
101
|
+
# base pool. This lets a profile ship local tools while still
|
|
102
|
+
# restricting the built-in set.
|
|
103
|
+
always_keep = set(active_agent.local_tools.keys()) if active_agent else set()
|
|
104
|
+
|
|
105
|
+
return _filter(base_tool_names, base_tool_pool, extra, allow, deny, always_keep=always_keep)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def compose_active_commands(*, base_commands: dict, active_agent: LoadedAgent | None) -> dict:
|
|
109
|
+
"""Compute the active slash-command dict for the runtime.
|
|
110
|
+
|
|
111
|
+
Local commands are wrapped in an :class:`ExtensionCommand` so the
|
|
112
|
+
TUI can show the owner consistently with session commands.
|
|
113
|
+
|
|
114
|
+
``ExtensionCommand`` is imported lazily here to break the
|
|
115
|
+
``ctx.tools`` -> ``ctx.agents`` -> ``ctx.agents.activate`` ->
|
|
116
|
+
``ctx.extensions`` -> ``ctx.tools`` cycle at module load.
|
|
117
|
+
"""
|
|
118
|
+
from ctx.agent import ExtensionCommand
|
|
119
|
+
|
|
120
|
+
if active_agent is None:
|
|
121
|
+
return dict(base_commands)
|
|
122
|
+
merged = dict(base_commands)
|
|
123
|
+
for name, handler in active_agent.local_commands.items():
|
|
124
|
+
merged[name] = ExtensionCommand(
|
|
125
|
+
name=name,
|
|
126
|
+
description=f"(agent: {active_agent.definition.name}) {name}",
|
|
127
|
+
handler=handler,
|
|
128
|
+
owner=active_agent.definition.name,
|
|
129
|
+
)
|
|
130
|
+
return merged
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def active_permission_mode(registry: AgentRegistry, default: str) -> str:
|
|
134
|
+
"""Return the active agent's ``permission_mode`` (or the default)."""
|
|
135
|
+
if registry.active is not None and registry.active.definition.permission_mode is not None:
|
|
136
|
+
return registry.active.definition.permission_mode
|
|
137
|
+
return default
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def active_permission_gates(registry: AgentRegistry) -> list:
|
|
141
|
+
"""Return the union of declarative + imperative gates for the active agent."""
|
|
142
|
+
if registry.active is None:
|
|
143
|
+
return []
|
|
144
|
+
out = list(registry.active.definition.permission_gates)
|
|
145
|
+
for gates in registry.active.local_gates.values():
|
|
146
|
+
out.extend(gates)
|
|
147
|
+
return out
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
__all__ = [
|
|
151
|
+
"_filter",
|
|
152
|
+
"active_permission_gates",
|
|
153
|
+
"active_permission_mode",
|
|
154
|
+
"compose_active_commands",
|
|
155
|
+
"compose_active_tools",
|
|
156
|
+
]
|