agenticreq 0.1.0a1__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.
- agenticreq/__init__.py +3 -0
- agenticreq/ast/__init__.py +5 -0
- agenticreq/ast/agent_discovery.py +845 -0
- agenticreq/ast/body_analysis.py +354 -0
- agenticreq/ast/classify.py +386 -0
- agenticreq/ast/constants.py +143 -0
- agenticreq/ast/effects.py +736 -0
- agenticreq/ast/envvalues.py +147 -0
- agenticreq/ast/evaluate.py +793 -0
- agenticreq/ast/extract_support.py +782 -0
- agenticreq/ast/extractor.py +574 -0
- agenticreq/ast/framework.py +389 -0
- agenticreq/ast/limits.py +391 -0
- agenticreq/ast/paths.py +211 -0
- agenticreq/ast/schema.py +317 -0
- agenticreq/ast/signals.py +711 -0
- agenticreq/ast/symbols.py +283 -0
- agenticreq/ast/tool_binding.py +928 -0
- agenticreq/ast/tool_discovery.py +550 -0
- agenticreq/capture/__init__.py +15 -0
- agenticreq/capture/discover.py +582 -0
- agenticreq/capture/entry.py +15 -0
- agenticreq/capture/gates.py +112 -0
- agenticreq/capture/guard.py +458 -0
- agenticreq/capture/hook.py +175 -0
- agenticreq/capture/importers.py +85 -0
- agenticreq/capture/responder.py +477 -0
- agenticreq/capture/runner.py +373 -0
- agenticreq/capture/wire.py +193 -0
- agenticreq/cli.py +1129 -0
- agenticreq/coverage_table.py +86 -0
- agenticreq/data/__init__.py +41 -0
- agenticreq/data/action_verbs.yml +30 -0
- agenticreq/data/framework_defaults.yml +19 -0
- agenticreq/data/known_injected_tools.yml +30 -0
- agenticreq/data/model_pins.yml +17 -0
- agenticreq/data/provider_pinning.yml +19 -0
- agenticreq/data/supported_versions.yml +23 -0
- agenticreq/defaults/__init__.py +189 -0
- agenticreq/defaults/profiles/baseline.yml +4 -0
- agenticreq/defaults/profiles/finance.yml +10 -0
- agenticreq/derived.py +128 -0
- agenticreq/detectors/__init__.py +78 -0
- agenticreq/engine.py +275 -0
- agenticreq/export/__init__.py +300 -0
- agenticreq/fix/__init__.py +315 -0
- agenticreq/graph/__init__.py +1 -0
- agenticreq/graph/analysis.py +190 -0
- agenticreq/graph/builder.py +219 -0
- agenticreq/graph/origin.py +122 -0
- agenticreq/jsonschema_util.py +187 -0
- agenticreq/loader/__init__.py +6 -0
- agenticreq/loader/builder.py +163 -0
- agenticreq/loader/fix_spec.py +286 -0
- agenticreq/loader/issues.py +445 -0
- agenticreq/loader/routes.py +99 -0
- agenticreq/loader/yaml_loader.py +546 -0
- agenticreq/mcp/__init__.py +130 -0
- agenticreq/mockgen.py +585 -0
- agenticreq/models/__init__.py +26 -0
- agenticreq/models/confidence.py +89 -0
- agenticreq/models/finding.py +245 -0
- agenticreq/models/observed.py +397 -0
- agenticreq/models/spec.py +392 -0
- agenticreq/models/verdict.py +823 -0
- agenticreq/names.py +53 -0
- agenticreq/not_needed.py +186 -0
- agenticreq/observe.py +100 -0
- agenticreq/params.py +364 -0
- agenticreq/pathutil.py +39 -0
- agenticreq/progress.py +406 -0
- agenticreq/py.typed +0 -0
- agenticreq/pyenv.py +497 -0
- agenticreq/recognizers/__init__.py +63 -0
- agenticreq/recognizers/langgraph.py +98 -0
- agenticreq/report/__init__.py +7 -0
- agenticreq/report/console.py +357 -0
- agenticreq/report/grouping.py +42 -0
- agenticreq/report/json_report.py +102 -0
- agenticreq/report/sarif.py +179 -0
- agenticreq/report/term.py +95 -0
- agenticreq/rules/__init__.py +1 -0
- agenticreq/rules/attest.py +223 -0
- agenticreq/rules/base.py +90 -0
- agenticreq/rules/conformance.py +1594 -0
- agenticreq/rules/fidelity.py +242 -0
- agenticreq/rules/graph.py +461 -0
- agenticreq/rules/hygiene.py +580 -0
- agenticreq/rules/meta.py +334 -0
- agenticreq/rules/numeric.py +124 -0
- agenticreq/rules/registry.py +868 -0
- agenticreq/rules/runtime.py +281 -0
- agenticreq/rules/taint.py +297 -0
- agenticreq/rules/validate.py +417 -0
- agenticreq/scaffold.py +359 -0
- agenticreq/schema.py +102 -0
- agenticreq/shapes.py +217 -0
- agenticreq/signoff.py +116 -0
- agenticreq/spec.schema.json +3698 -0
- agenticreq/subfields.py +170 -0
- agenticreq/thresholds.py +336 -0
- agenticreq/traces/__init__.py +102 -0
- agenticreq/traces/coverage.py +126 -0
- agenticreq/versions.py +219 -0
- agenticreq-0.1.0a1.dist-info/METADATA +191 -0
- agenticreq-0.1.0a1.dist-info/RECORD +109 -0
- agenticreq-0.1.0a1.dist-info/WHEEL +4 -0
- agenticreq-0.1.0a1.dist-info/entry_points.txt +5 -0
- agenticreq-0.1.0a1.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,845 @@
|
|
|
1
|
+
"""Agent constructor calls: one call can build several agents; models, bounds, gates, executors.
|
|
2
|
+
|
|
3
|
+
Moved out of ``extractor.py`` unchanged; each function takes the extractor as ``ex``.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import ast
|
|
9
|
+
import re
|
|
10
|
+
from agenticreq.ast.classify import is_test_file
|
|
11
|
+
from agenticreq.ast.classify import looks_like_model
|
|
12
|
+
from agenticreq.ast.evaluate import Frame
|
|
13
|
+
from agenticreq.ast.evaluate import UNK
|
|
14
|
+
from agenticreq.ast.evaluate import bind_target
|
|
15
|
+
from agenticreq.ast.evaluate import subst
|
|
16
|
+
from agenticreq.ast.paths import gate_coverage
|
|
17
|
+
from agenticreq.ast.schema import _name
|
|
18
|
+
from agenticreq.ast.schema import literal
|
|
19
|
+
from agenticreq.ast.symbols import FileCtx
|
|
20
|
+
from agenticreq.ast.symbols import FuncDef
|
|
21
|
+
from agenticreq.models.finding import SourceRef
|
|
22
|
+
from agenticreq.models.observed import BoundRef
|
|
23
|
+
from agenticreq.models.observed import CodeExecRef
|
|
24
|
+
from agenticreq.models.observed import DeclaredAgent
|
|
25
|
+
from agenticreq.models.observed import GateRef
|
|
26
|
+
from agenticreq.models.observed import UnresolvedAgent
|
|
27
|
+
from typing import Any
|
|
28
|
+
from agenticreq.ast.tool_discovery import _gate_kind
|
|
29
|
+
from agenticreq.ast.extract_support import (
|
|
30
|
+
BIND_CALLS,
|
|
31
|
+
BOUND_CALLS,
|
|
32
|
+
BOUND_KWARGS,
|
|
33
|
+
GATE_HOOK_KWARG,
|
|
34
|
+
GATE_KWARGS,
|
|
35
|
+
MODEL_KWARGS,
|
|
36
|
+
TOOL_LIST_KWARGS,
|
|
37
|
+
TOOL_WRAPPERS,
|
|
38
|
+
_GENERIC_BUILDER,
|
|
39
|
+
_GROUP_CTORS,
|
|
40
|
+
_NAMED_FIRST_ARG,
|
|
41
|
+
_RUN_BUILDERS,
|
|
42
|
+
_RUN_CALLS,
|
|
43
|
+
_TOOL_SCOPED_GATES,
|
|
44
|
+
_kw,
|
|
45
|
+
_ref,
|
|
46
|
+
_str,
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
from typing import TYPE_CHECKING
|
|
50
|
+
|
|
51
|
+
if TYPE_CHECKING:
|
|
52
|
+
from agenticreq.ast.extractor import ProjectExtractor
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
_Instance = tuple[dict[str, ast.expr], "str | None", "str | None", "FileCtx | None"]
|
|
56
|
+
|
|
57
|
+
#: registering a guard: kernel.add_filter(...), app.use_middleware(...), agent.register_hook(...)
|
|
58
|
+
_REGISTER_GUARD = re.compile(
|
|
59
|
+
r"^(add|register|use|attach|set|install|append)_([a-z_]*_)?"
|
|
60
|
+
r"(filter|middleware|hook|interceptor|guard|guardrail|policy)s?$",
|
|
61
|
+
re.IGNORECASE,
|
|
62
|
+
)
|
|
63
|
+
#: a function that asks a person: input(), interrupt(), ask_human(), request_approval(), confirm() ...
|
|
64
|
+
_HUMAN_SIGNAL = re.compile(r"approv|confirm|human|hitl|consent|ask_user|permission|interrupt")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _filter_gate(ex: ProjectExtractor, fc: FileCtx, call: ast.Call, fname: str, ref: SourceRef) -> None:
|
|
68
|
+
"""A registered filter / hook whose body asks a human is an approval gate for the tools it names. Whether it
|
|
69
|
+
covers every path is code, not config, so the coverage stays unverified (UNKNOWN, never a PASS)."""
|
|
70
|
+
if not _REGISTER_GUARD.match(fname or ""):
|
|
71
|
+
return
|
|
72
|
+
for a in [*call.args, *(k.value for k in call.keywords)]:
|
|
73
|
+
r = ex.symbols.resolve(fc, a) if isinstance(a, (ast.Name, ast.Attribute)) else None
|
|
74
|
+
fn: ast.AST | None = None
|
|
75
|
+
if r is not None and r.kind == "function" and isinstance(r.node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
76
|
+
fn = r.node
|
|
77
|
+
elif isinstance(a, ast.Lambda):
|
|
78
|
+
fn = a
|
|
79
|
+
if fn is None:
|
|
80
|
+
continue
|
|
81
|
+
asks, tools = False, []
|
|
82
|
+
for n in ast.walk(fn):
|
|
83
|
+
if isinstance(n, ast.Call) and _HUMAN_SIGNAL.search((_name(n.func) or "").lower()):
|
|
84
|
+
asks = True
|
|
85
|
+
if isinstance(n, ast.Call) and _name(n.func) == "input":
|
|
86
|
+
asks = True
|
|
87
|
+
if isinstance(n, ast.Constant) and isinstance(n.value, str) and n.value in ex.obs.declared_tools:
|
|
88
|
+
tools.append(n.value)
|
|
89
|
+
if asks:
|
|
90
|
+
ex.obs.gates.append(
|
|
91
|
+
GateRef(
|
|
92
|
+
kind="approval_call",
|
|
93
|
+
tools=sorted(set(tools)) or None,
|
|
94
|
+
code_ref=ref,
|
|
95
|
+
coverage="unverified",
|
|
96
|
+
coverage_note="a registered filter/hook asks a human; that it covers every path is not provable",
|
|
97
|
+
)
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _seq_elements(ev: Any, fr: Any, node: ast.AST | None, depth: int = 0) -> list[ast.expr]:
|
|
102
|
+
"""Elements of a sequence expression, through list()/tuple(), `+`, `*x` and names the evaluator can follow."""
|
|
103
|
+
if node is None or depth > 6:
|
|
104
|
+
return []
|
|
105
|
+
if isinstance(node, (ast.List, ast.Tuple, ast.Set)):
|
|
106
|
+
out: list[ast.expr] = []
|
|
107
|
+
for e in node.elts:
|
|
108
|
+
out += _seq_elements(ev, fr, e.value, depth + 1) if isinstance(e, ast.Starred) else [e]
|
|
109
|
+
return out
|
|
110
|
+
if isinstance(node, ast.Call) and _name(node.func) in ("list", "tuple", "set", "sorted") and node.args:
|
|
111
|
+
return _seq_elements(ev, fr, node.args[0], depth + 1)
|
|
112
|
+
if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
|
|
113
|
+
return _seq_elements(ev, fr, node.left, depth + 1) + _seq_elements(ev, fr, node.right, depth + 1)
|
|
114
|
+
if isinstance(node, (ast.Name, ast.Attribute, ast.Subscript)):
|
|
115
|
+
rfr, red = ev.reduce(fr, node)
|
|
116
|
+
if red is not node:
|
|
117
|
+
return _seq_elements(ev, rfr, red, depth + 1)
|
|
118
|
+
return []
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
#: keywords whose text is prose or an identifier of the agent, never a model id (`name="claude-helper-2"`)
|
|
122
|
+
_NOT_A_MODEL_KW = {
|
|
123
|
+
"name",
|
|
124
|
+
"role",
|
|
125
|
+
"description",
|
|
126
|
+
"instructions",
|
|
127
|
+
"instruction",
|
|
128
|
+
"system_message",
|
|
129
|
+
"system_prompt",
|
|
130
|
+
"prompt",
|
|
131
|
+
"goal",
|
|
132
|
+
"backstory",
|
|
133
|
+
"content",
|
|
134
|
+
"text",
|
|
135
|
+
"message",
|
|
136
|
+
"query",
|
|
137
|
+
"title",
|
|
138
|
+
"label",
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _call_facts(ex: ProjectExtractor, fc: FileCtx, call: ast.Call, assigned_to: str | None) -> None:
|
|
143
|
+
fname = _name(call.func)
|
|
144
|
+
ref = _ref(fc.rel, call)
|
|
145
|
+
# direct Python calls of a tool function (not via the model), followed across imports
|
|
146
|
+
r = ex.symbols.resolve(fc, call.func)
|
|
147
|
+
if r is not None and r.kind == "function" and isinstance(r.node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
148
|
+
if (
|
|
149
|
+
id(r.node) not in ex.node_tool
|
|
150
|
+
and r.fc is not fc
|
|
151
|
+
and ex._is_tool_module(r.fc)
|
|
152
|
+
and ast.get_docstring(r.node)
|
|
153
|
+
and not ex._is_mcp_file(r.fc)
|
|
154
|
+
):
|
|
155
|
+
# (a tool has a description; an MCP server's other functions are its transport plumbing)
|
|
156
|
+
# a function from a tool module (its siblings are tools elsewhere) called straight from
|
|
157
|
+
# Python: the model never sees it, so it is invisible at the boundary by construction
|
|
158
|
+
ex._function_tool(r.fc, r.node, None, kind="tool-module function (code pattern)")
|
|
159
|
+
if id(r.node) in ex.node_tool:
|
|
160
|
+
ex.obs.direct_calls.setdefault(ex.node_tool[id(r.node)], []).append(ref)
|
|
161
|
+
# tool binding
|
|
162
|
+
bound = ex._bound_list(fc, call)
|
|
163
|
+
if bound:
|
|
164
|
+
for t in bound:
|
|
165
|
+
ex.obs.bound_tools.setdefault(t, []).append(ref)
|
|
166
|
+
ex._group(fc, call, f"bind:{id(call)}", bound)
|
|
167
|
+
_filter_gate(ex, fc, call, fname, ref)
|
|
168
|
+
if fname.startswith("from_") and isinstance(call.func, ast.Attribute) and _name(call.func.value) in ex.agent_ctors:
|
|
169
|
+
fname = _name(call.func.value) # ReActAgent.from_tools(...) builds a ReActAgent
|
|
170
|
+
# agents
|
|
171
|
+
if fname in ex.agent_ctors:
|
|
172
|
+
instances, why = ex._agent_instances(fc, call)
|
|
173
|
+
if why is not None: # how many agents this builds is not static: one placeholder, reported
|
|
174
|
+
instances = [({}, None, None, None)]
|
|
175
|
+
built: list[DeclaredAgent] = []
|
|
176
|
+
for env, hint, how, site in instances:
|
|
177
|
+
ag = ex._declared_agent(
|
|
178
|
+
fc, call, fname, assigned_to if len(instances) == 1 else None, env, hint, how, bound, ref, site
|
|
179
|
+
)
|
|
180
|
+
built.append(ag)
|
|
181
|
+
seen: set[tuple[Any, ...]] = set() # a factory called twice with the same arguments builds the same agent
|
|
182
|
+
unique = []
|
|
183
|
+
for a in built:
|
|
184
|
+
sig = (a.name, tuple(a.tools), a.system_prompt, tuple(a.handoffs), tuple(a.delegates))
|
|
185
|
+
if sig not in seen:
|
|
186
|
+
seen.add(sig)
|
|
187
|
+
unique.append(a)
|
|
188
|
+
built = unique
|
|
189
|
+
names = [a.name for a in built]
|
|
190
|
+
for i, ag in enumerate(built): # rows the code does not tell apart stay distinct nodes
|
|
191
|
+
if names.count(ag.name) > 1:
|
|
192
|
+
ag.name = f"{ag.name}#{i + 1}"
|
|
193
|
+
for ag in built:
|
|
194
|
+
if any(a.name == ag.name and a.tools == ag.tools and a.kind == ag.kind for a in ex.obs.declared_agents):
|
|
195
|
+
continue # the same agent from another constructor call of one factory (a try / fallback branch)
|
|
196
|
+
ex.obs.declared_agents.append(ag)
|
|
197
|
+
if ag.var:
|
|
198
|
+
ex.agent_vars[ag.var] = ag
|
|
199
|
+
if fname == "CodeAgent":
|
|
200
|
+
ex.obs.prompt_only_tools += [t for t in ag.tools if t not in ex.obs.prompt_only_tools]
|
|
201
|
+
if why is not None:
|
|
202
|
+
ex.obs.unresolved_agents.append(UnresolvedAgent(code_ref=ref, reason=why, name=built[0].name))
|
|
203
|
+
ex._code_executor(fc, call, fname, built[0].name, ref)
|
|
204
|
+
elif fname in _GROUP_CTORS:
|
|
205
|
+
ex._group_agent(fc, call, fname, assigned_to, ref)
|
|
206
|
+
# models
|
|
207
|
+
provider = ex._provider_of(fc, call, fname)
|
|
208
|
+
for kw in MODEL_KWARGS:
|
|
209
|
+
v = _kw(call, kw)
|
|
210
|
+
if v is not None:
|
|
211
|
+
ex._model_from_node(fc, v, ref, provider, call)
|
|
212
|
+
for k in call.keywords: # any keyword holding a model id (Agno `id=`, `engine=`, ...): the value says what it is
|
|
213
|
+
if (
|
|
214
|
+
k.arg
|
|
215
|
+
and k.arg not in MODEL_KWARGS
|
|
216
|
+
and k.arg not in _NOT_A_MODEL_KW
|
|
217
|
+
and isinstance(k.value, ast.Constant)
|
|
218
|
+
and isinstance(k.value.value, str)
|
|
219
|
+
and re.search(r"\d", k.value.value)
|
|
220
|
+
and looks_like_model(k.value.value)
|
|
221
|
+
):
|
|
222
|
+
ex._model_from_node(fc, k.value, ref, provider, call)
|
|
223
|
+
for k in call.keywords: # LiteLLMModel(**model_params) with model_params = {"model_id": model_id, ...}
|
|
224
|
+
if k.arg is None and isinstance(k.value, ast.Name):
|
|
225
|
+
d = ex._assigned_value(fc, k.value.id)
|
|
226
|
+
if isinstance(d, ast.Dict):
|
|
227
|
+
for dk, dv in zip(d.keys, d.values):
|
|
228
|
+
if _str(dk) in MODEL_KWARGS:
|
|
229
|
+
ex._model_from_node(fc, dv, ref, provider, call)
|
|
230
|
+
if (
|
|
231
|
+
fname
|
|
232
|
+
in (
|
|
233
|
+
"ChatOpenAI",
|
|
234
|
+
"ChatAnthropic",
|
|
235
|
+
"OpenAIServerModel",
|
|
236
|
+
"LiteLLMModel",
|
|
237
|
+
"LLM",
|
|
238
|
+
"init_chat_model",
|
|
239
|
+
"OpenAIModel",
|
|
240
|
+
"AnthropicModel",
|
|
241
|
+
"OpenAIChatModel",
|
|
242
|
+
"Agent",
|
|
243
|
+
"LiteLlm",
|
|
244
|
+
"create_react_agent",
|
|
245
|
+
"create_agent",
|
|
246
|
+
"ChatGoogleGenerativeAI",
|
|
247
|
+
"ChatMistralAI",
|
|
248
|
+
"ChatGroq",
|
|
249
|
+
"GroqModel",
|
|
250
|
+
"GoogleModel",
|
|
251
|
+
"GeminiModel",
|
|
252
|
+
"MistralModel",
|
|
253
|
+
"CohereModel",
|
|
254
|
+
"BedrockConverseModel",
|
|
255
|
+
"OpenAIResponsesModel",
|
|
256
|
+
"HuggingFaceModel",
|
|
257
|
+
)
|
|
258
|
+
and call.args
|
|
259
|
+
):
|
|
260
|
+
ex._model_from_node(fc, call.args[0], ref, provider)
|
|
261
|
+
# bounds (an expanded agent call recorded its own, one per agent). A bound on an agent's own constructor belongs
|
|
262
|
+
# to that agent; one on a run / graph call applies to every agent.
|
|
263
|
+
owner = built[0].name if fname in ex.agent_ctors and len(built) == 1 else None
|
|
264
|
+
for k in call.keywords if id(call) not in ex._agent_bounds else []:
|
|
265
|
+
if k.arg in BOUND_KWARGS:
|
|
266
|
+
b = ex._bound_ref(fc, BOUND_KWARGS[k.arg], k.arg, k.value, call)
|
|
267
|
+
b.agent = owner
|
|
268
|
+
ex.obs.bounds.append(b)
|
|
269
|
+
if fname in BOUND_CALLS and call.args and id(call) not in ex._agent_bounds:
|
|
270
|
+
ex.obs.bounds.append(ex._bound_ref(fc, BOUND_CALLS[fname], fname, call.args[0], call))
|
|
271
|
+
# gates
|
|
272
|
+
gate_kind = _gate_kind(ex, fc, call)
|
|
273
|
+
if gate_kind:
|
|
274
|
+
if not any(g.code_ref == ref for g in ex.obs.gates):
|
|
275
|
+
# inside a tool's own body it gates that tool only; in a dispatcher / graph node it gates the tools that
|
|
276
|
+
# function names (string constants equal to a declared tool), else whatever runs there (scope unknown)
|
|
277
|
+
fn = ex._enclosing_fn.get(id(call))
|
|
278
|
+
owner = (ex.node_tool.get(id(fn)) or ex._method_owner.get(id(fn))) if fn is not None else None
|
|
279
|
+
named: list[str] = []
|
|
280
|
+
if owner is None and fn is not None:
|
|
281
|
+
named = sorted(
|
|
282
|
+
{
|
|
283
|
+
n.value
|
|
284
|
+
for n in ast.walk(fn)
|
|
285
|
+
if isinstance(n, ast.Constant) and isinstance(n.value, str) and n.value in ex.obs.declared_tools
|
|
286
|
+
}
|
|
287
|
+
)
|
|
288
|
+
cov, why = (
|
|
289
|
+
gate_coverage(fn, call)
|
|
290
|
+
if owner and fn is not None
|
|
291
|
+
else ("unverified", "gate outside a tool body: which tools it covers is not known")
|
|
292
|
+
)
|
|
293
|
+
ex.obs.gates.append(
|
|
294
|
+
GateRef(
|
|
295
|
+
kind=gate_kind,
|
|
296
|
+
tools=[owner] if owner else (named or None),
|
|
297
|
+
code_ref=ref,
|
|
298
|
+
coverage=cov,
|
|
299
|
+
coverage_note=why,
|
|
300
|
+
)
|
|
301
|
+
)
|
|
302
|
+
for k in call.keywords:
|
|
303
|
+
hook = k.arg not in GATE_KWARGS and bool(GATE_HOOK_KWARG.match(k.arg or ""))
|
|
304
|
+
if (k.arg in GATE_KWARGS or hook) and k.arg != "step_callback":
|
|
305
|
+
ok, val = literal(k.value)
|
|
306
|
+
if ok and val in (False, None, [], (), "NEVER"):
|
|
307
|
+
continue
|
|
308
|
+
if hook and ok and val is not True:
|
|
309
|
+
continue # a hook is a callable: a literal string/number under that name is configuration, not a gate
|
|
310
|
+
where = _ref(fc.rel, k.value)
|
|
311
|
+
if k.arg in _TOOL_SCOPED_GATES:
|
|
312
|
+
# needs_approval / requires_approval belong to ONE tool: the decorated function or the
|
|
313
|
+
# wrapped callable. They never gate the agent's other tools.
|
|
314
|
+
scope: list[str] | None = (
|
|
315
|
+
[ex._decorator_tool[id(call)]]
|
|
316
|
+
if id(call) in ex._decorator_tool
|
|
317
|
+
else (ex._tools_from_expr(fc, call) if fname in TOOL_WRAPPERS else [])
|
|
318
|
+
)
|
|
319
|
+
# needs_approval=True: the framework asks before every call (config, all paths); a callable
|
|
320
|
+
# decides per call at runtime, so its coverage is not known statically
|
|
321
|
+
cov = "all_paths" if scope and ok and val is True else "unverified"
|
|
322
|
+
ex.obs.gates.append(
|
|
323
|
+
GateRef(
|
|
324
|
+
kind=GATE_KWARGS[k.arg] if scope else "needs_approval(unscoped)",
|
|
325
|
+
tools=scope or None,
|
|
326
|
+
code_ref=where,
|
|
327
|
+
coverage=cov,
|
|
328
|
+
coverage_note="framework asks before every call"
|
|
329
|
+
if cov == "all_paths"
|
|
330
|
+
else f"{k.arg}= is not the literal True: the framework decides per call at runtime",
|
|
331
|
+
)
|
|
332
|
+
)
|
|
333
|
+
continue
|
|
334
|
+
if k.arg == "human_input" and fname == "Task":
|
|
335
|
+
# CrewAI Task(human_input=True): a human reviews the task's final answer AFTER its tools
|
|
336
|
+
# ran. It approves no tool call, so it is not an approval gate.
|
|
337
|
+
ex.obs.gates.append(GateRef(kind="output_review", tools=None, code_ref=where))
|
|
338
|
+
continue
|
|
339
|
+
# interrupt_before/after name graph nodes, not tools. On an agent constructor the gate belongs to THAT agent's
|
|
340
|
+
# tools (create_react_agent(tools=[...], interrupt_before=["tools"]) pauses before its tool node); on a
|
|
341
|
+
# graph compile() it applies to whatever those nodes run.
|
|
342
|
+
scope, cov, note = None, "unverified", None
|
|
343
|
+
if fname in ex.agent_ctors and (k.arg in ("interrupt_before", "interrupt_after") or hook):
|
|
344
|
+
tl = _kw(call, "tools")
|
|
345
|
+
owned = bound or (ex._tools_from_expr(fc, tl, in_tool_list=True) if tl is not None else [])
|
|
346
|
+
if owned:
|
|
347
|
+
scope = list(owned)
|
|
348
|
+
if (
|
|
349
|
+
k.arg == "interrupt_before"
|
|
350
|
+
and isinstance(k.value, (ast.List, ast.Tuple))
|
|
351
|
+
and any(_str(e) == "tools" for e in k.value.elts)
|
|
352
|
+
):
|
|
353
|
+
cov, note = "all_paths", "the tool node is paused before it runs"
|
|
354
|
+
ex.obs.gates.append(
|
|
355
|
+
GateRef(
|
|
356
|
+
kind=GATE_KWARGS.get(k.arg or "", "approval_call"),
|
|
357
|
+
tools=scope,
|
|
358
|
+
code_ref=where,
|
|
359
|
+
coverage=cov,
|
|
360
|
+
coverage_note=note,
|
|
361
|
+
)
|
|
362
|
+
)
|
|
363
|
+
if fname in ex.agent_ctors and assigned_to in ex.agent_vars:
|
|
364
|
+
tl = _kw(call, "tools")
|
|
365
|
+
for el in tl.elts if isinstance(tl, (ast.List, ast.Tuple)) else []:
|
|
366
|
+
if isinstance(el, ast.Call) and _name(el.func) == "create_handoff_tool":
|
|
367
|
+
h = ex._static_str(fc, _kw(el, "agent_name") or (el.args[0] if el.args else None))
|
|
368
|
+
if h and h not in ex.agent_vars[assigned_to].handoffs:
|
|
369
|
+
ex.agent_vars[assigned_to].handoffs.append(h)
|
|
370
|
+
if fname == "set_default_openai_client" and call.args:
|
|
371
|
+
ex._default_provider = ex._provider_of_expr(fc, call.args[0]) or ex._default_provider
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def _agent_instances(
|
|
375
|
+
ex: ProjectExtractor, fc: FileCtx, node: ast.AST, depth: int = 0
|
|
376
|
+
) -> tuple[list[_Instance], str | None]:
|
|
377
|
+
"""Every agent one constructor call builds: one per row of the loops / comprehensions around it,
|
|
378
|
+
times one per call of the factory function it sits in (its parameters bound to that call's
|
|
379
|
+
arguments). ``([], reason)`` when the number of agents is not known statically."""
|
|
380
|
+
ev = ex.ev
|
|
381
|
+
par = ev.parents(fc)
|
|
382
|
+
loops: list[tuple[ast.AST, ast.AST, list[ast.expr], ast.AST]] = [] # innermost first
|
|
383
|
+
fn: FuncDef | None = None
|
|
384
|
+
child, cur = node, par.get(id(node))
|
|
385
|
+
while cur is not None:
|
|
386
|
+
if (
|
|
387
|
+
isinstance(cur, (ast.For, ast.AsyncFor))
|
|
388
|
+
and child is not cur.iter
|
|
389
|
+
and child is not cur.target
|
|
390
|
+
and not any(child is s for s in cur.orelse)
|
|
391
|
+
):
|
|
392
|
+
loops.append((cur.target, cur.iter, [], cur))
|
|
393
|
+
elif isinstance(cur, (ast.ListComp, ast.SetComp, ast.GeneratorExp, ast.DictComp)):
|
|
394
|
+
gens = cur.generators
|
|
395
|
+
used = gens[: gens.index(child)] if isinstance(child, ast.comprehension) else gens
|
|
396
|
+
loops += [(g.target, g.iter, list(g.ifs), cur) for g in reversed(used)]
|
|
397
|
+
elif isinstance(cur, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
398
|
+
fn = cur
|
|
399
|
+
break
|
|
400
|
+
elif isinstance(cur, (ast.ClassDef, ast.Lambda)):
|
|
401
|
+
break
|
|
402
|
+
child, cur = cur, par.get(id(cur))
|
|
403
|
+
fr = ev.frame_of(fc, node)
|
|
404
|
+
envs: list[ProjectExtractor._Instance] = [({}, None, None, None)]
|
|
405
|
+
if fn is not None and depth < 3: # a factory: one agent per call site that varies its arguments
|
|
406
|
+
params = {a.arg for a in [*fn.args.posonlyargs, *fn.args.args, *fn.args.kwonlyargs]} - {"self", "cls"}
|
|
407
|
+
mentioned = {
|
|
408
|
+
n.id for x in [node, *(it for _, it, _, _ in loops)] for n in ast.walk(x) if isinstance(n, ast.Name)
|
|
409
|
+
}
|
|
410
|
+
for a in ast.walk(fn): # `kwargs = dict(name=spec.name, ...)` then `Agent(**kwargs)`: the local's sources count
|
|
411
|
+
if isinstance(a, ast.Assign) and any(isinstance(t, ast.Name) and t.id in mentioned for t in a.targets):
|
|
412
|
+
mentioned |= {x.id for x in ast.walk(a.value) if isinstance(x, ast.Name)}
|
|
413
|
+
sites = ex._call_sites(fn) if params & mentioned else []
|
|
414
|
+
if sites:
|
|
415
|
+
envs = []
|
|
416
|
+
for sfc, scall in sites:
|
|
417
|
+
outer, why = ex._agent_instances(sfc, scall, depth + 1)
|
|
418
|
+
if why is not None:
|
|
419
|
+
return [], f"{why} (through factory {fn.name}() called at {sfc.rel}:{scall.lineno})"
|
|
420
|
+
sfr = ev.frame_of(sfc, scall)
|
|
421
|
+
bound_self = (
|
|
422
|
+
isinstance(scall.func, ast.Attribute)
|
|
423
|
+
and bool(fn.args.args)
|
|
424
|
+
and fn.args.args[0].arg in ("self", "cls")
|
|
425
|
+
)
|
|
426
|
+
for oenv, ohint, _, _ in outer:
|
|
427
|
+
penv = ev.call_env(sfr, fn, subst(scall, oenv), bound_self)
|
|
428
|
+
envs.append(
|
|
429
|
+
(
|
|
430
|
+
penv,
|
|
431
|
+
ohint or ex._site_name(sfc, scall),
|
|
432
|
+
f"factory {fn.name}() called at {sfc.rel}:{scall.lineno}",
|
|
433
|
+
sfc,
|
|
434
|
+
)
|
|
435
|
+
)
|
|
436
|
+
for target, it, conds, owner in reversed(loops):
|
|
437
|
+
nxt: list[ProjectExtractor._Instance] = []
|
|
438
|
+
for env, hint, how, site in envs:
|
|
439
|
+
ev.touched.clear()
|
|
440
|
+
rows = ev.rows(fr, subst(it, env))
|
|
441
|
+
if rows is None and not {n.id for n in ast.walk(target) if isinstance(n, ast.Name)} & {
|
|
442
|
+
n.id for n in ast.walk(node) if isinstance(n, ast.Name)
|
|
443
|
+
}:
|
|
444
|
+
nxt.append((env, hint, how, site)) # every iteration builds the same agent
|
|
445
|
+
continue
|
|
446
|
+
if rows is None:
|
|
447
|
+
return [], f"built in a loop over a value only known at runtime: `{ast.unparse(it)[:80]}`"
|
|
448
|
+
src = ", ".join(sorted(ev.touched)) or f"{fc.rel}:{getattr(owner, 'lineno', '?')}"
|
|
449
|
+
for el in rows:
|
|
450
|
+
b = bind_target(target, el)
|
|
451
|
+
if b is None:
|
|
452
|
+
return (
|
|
453
|
+
[],
|
|
454
|
+
f"loop target `{ast.unparse(target)}` does not match the rows of `{ast.unparse(it)[:60]}`",
|
|
455
|
+
)
|
|
456
|
+
e2 = {**env, **b}
|
|
457
|
+
if any((v := ev.value(fr, subst(c, e2))) is not UNK and not v for c in conds):
|
|
458
|
+
continue # a comprehension filter that is statically false for this row
|
|
459
|
+
nxt.append((e2, hint, f"loop over {src}" + (f"; {how}" if how else ""), site))
|
|
460
|
+
envs = nxt
|
|
461
|
+
return envs, None
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def _call_sites(ex: ProjectExtractor, fn: FuncDef) -> list[tuple[FileCtx, ast.Call]]:
|
|
465
|
+
"""Where a project function / method is called (by name, resolved through imports when possible)."""
|
|
466
|
+
if id(fn) in ex._sites:
|
|
467
|
+
return ex._sites[id(fn)]
|
|
468
|
+
unique = len(ex._fn_index.get(fn.name, [])) == 1
|
|
469
|
+
out: list[tuple[FileCtx, ast.Call]] = []
|
|
470
|
+
for fc in ex.files:
|
|
471
|
+
if is_test_file(fc.rel):
|
|
472
|
+
continue # a test calling the factory does not add an agent to the project
|
|
473
|
+
for n in ast.walk(fc.tree):
|
|
474
|
+
if not isinstance(n, ast.Call) or _name(n.func) != fn.name or isinstance(n.func, ast.Subscript):
|
|
475
|
+
continue
|
|
476
|
+
if any(x is n for x in ast.walk(fn)):
|
|
477
|
+
continue # recursion is not another agent
|
|
478
|
+
r = ex.symbols.resolve(fc, n.func)
|
|
479
|
+
if (r is not None and r.node is fn) or (r is None and unique):
|
|
480
|
+
out.append((fc, n))
|
|
481
|
+
ex._sites[id(fn)] = out
|
|
482
|
+
return out
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
def _site_name(ex: ProjectExtractor, fc: FileCtx, call: ast.Call) -> str | None:
|
|
486
|
+
"""The name a call's result is stored under: ``x = f()``, ``self.x = f()``, ``{"x": f()}``."""
|
|
487
|
+
p = ex.ev.parents(fc).get(id(call))
|
|
488
|
+
if isinstance(p, (ast.Assign, ast.AnnAssign)):
|
|
489
|
+
t = p.targets[0] if isinstance(p, ast.Assign) else p.target
|
|
490
|
+
return t.id if isinstance(t, ast.Name) else t.attr if isinstance(t, ast.Attribute) else None
|
|
491
|
+
if isinstance(p, ast.Dict):
|
|
492
|
+
for k, v in zip(p.keys, p.values):
|
|
493
|
+
if v is call:
|
|
494
|
+
return _str(k)
|
|
495
|
+
if isinstance(p, ast.keyword) and p.arg not in (None, "tools", "agents"):
|
|
496
|
+
return p.arg
|
|
497
|
+
return None
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
def _tool_names_in(ex: ProjectExtractor, fr: Any, node: ast.AST) -> list[str]:
|
|
501
|
+
"""Names of declared tools held in a literal list or tuple anywhere in ``node`` (``pick(*spec.tools)``)."""
|
|
502
|
+
for n in ast.walk(node):
|
|
503
|
+
v = ex.ev.value(fr, n) if isinstance(n, ast.expr) else None
|
|
504
|
+
if isinstance(v, (list, tuple)) and v and all(isinstance(x, str) for x in v):
|
|
505
|
+
# tool names (the tools may be declared in a file read later): identifiers, never prose
|
|
506
|
+
if all(re.fullmatch(r"[A-Za-z_][\w.-]{0,63}", x) for x in v):
|
|
507
|
+
return list(v)
|
|
508
|
+
return []
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
def _declared_agent(
|
|
512
|
+
ex: ProjectExtractor,
|
|
513
|
+
fc: FileCtx,
|
|
514
|
+
call: ast.Call,
|
|
515
|
+
fname: str,
|
|
516
|
+
assigned_to: str | None,
|
|
517
|
+
env: dict[str, ast.expr],
|
|
518
|
+
hint: str | None,
|
|
519
|
+
how: str | None,
|
|
520
|
+
bound: list[str] | None,
|
|
521
|
+
ref: SourceRef,
|
|
522
|
+
site: FileCtx | None = None,
|
|
523
|
+
) -> DeclaredAgent:
|
|
524
|
+
"""One agent from a constructor call, with a row's / call site's bindings substituted."""
|
|
525
|
+
ev = ex.ev
|
|
526
|
+
fr = ev.frame_of(fc, call)
|
|
527
|
+
c = subst(call, env) if env else call
|
|
528
|
+
# CrewAI Agent(config=self.agents_config["x"]) / Agent(**spec): key -> (frame, value expression)
|
|
529
|
+
cfg: dict[str, tuple[Frame, ast.expr]] = {}
|
|
530
|
+
for node in [_kw(c, "config"), *(k.value for k in c.keywords if k.arg is None)]:
|
|
531
|
+
if node is None:
|
|
532
|
+
continue
|
|
533
|
+
cfr, d = ev.reduce(fr, node)
|
|
534
|
+
if isinstance(d, ast.Call) and _name(d.func) == "dict" and not d.args: # kwargs = dict(name=spec.name, ...)
|
|
535
|
+
d = subst(d, env) if env else d
|
|
536
|
+
cfg.update({k.arg: (cfr, k.value) for k in d.keywords if k.arg})
|
|
537
|
+
if isinstance(d, ast.Dict):
|
|
538
|
+
cfg.update(
|
|
539
|
+
{
|
|
540
|
+
k.value: (cfr, v)
|
|
541
|
+
for k, v in zip(d.keys, d.values)
|
|
542
|
+
if isinstance(k, ast.Constant) and isinstance(k.value, str)
|
|
543
|
+
}
|
|
544
|
+
)
|
|
545
|
+
|
|
546
|
+
def cfgv(k: str) -> object:
|
|
547
|
+
got = cfg.get(k)
|
|
548
|
+
return ev.value(*got) if got else UNK
|
|
549
|
+
|
|
550
|
+
def sv(k: str) -> str | None:
|
|
551
|
+
node = _kw(c, k)
|
|
552
|
+
return (ex._static_str(fc, node) or ev.string(fr, node)) if node is not None else None
|
|
553
|
+
|
|
554
|
+
def cv(k: str) -> str | None:
|
|
555
|
+
v = cfgv(k)
|
|
556
|
+
return " ".join(v.split()) if isinstance(v, str) and v.strip() else None
|
|
557
|
+
|
|
558
|
+
positional = (
|
|
559
|
+
(ex._static_str(fc, c.args[0]) or ev.string(fr, c.args[0])) if c.args and fname in _NAMED_FIRST_ARG else None
|
|
560
|
+
)
|
|
561
|
+
enclosing = ev.enclosing(fc, call, (ast.FunctionDef, ast.AsyncFunctionDef))
|
|
562
|
+
# CrewAI @agent methods / build_x() helpers name the agent they return
|
|
563
|
+
returned = (
|
|
564
|
+
enclosing.name
|
|
565
|
+
if isinstance(enclosing, (ast.FunctionDef, ast.AsyncFunctionDef))
|
|
566
|
+
and isinstance(ev.parents(fc).get(id(call)), ast.Return)
|
|
567
|
+
and not _GENERIC_BUILDER.match(enclosing.name)
|
|
568
|
+
else None
|
|
569
|
+
)
|
|
570
|
+
name = (
|
|
571
|
+
sv("name") or positional or sv("role") or cv("name") or cv("role") or hint or assigned_to or returned or fname
|
|
572
|
+
)
|
|
573
|
+
name = " ".join(name.split()).strip("\"'") or fname # YAML `role: >` keeps written quotes
|
|
574
|
+
prompt = (
|
|
575
|
+
sv("instructions")
|
|
576
|
+
or sv("system_prompt")
|
|
577
|
+
or sv("backstory")
|
|
578
|
+
or sv("prompt")
|
|
579
|
+
or sv("system_message")
|
|
580
|
+
or sv("description")
|
|
581
|
+
or cv("backstory")
|
|
582
|
+
or cv("instructions")
|
|
583
|
+
or cv("system_prompt")
|
|
584
|
+
or cv("goal")
|
|
585
|
+
)
|
|
586
|
+
tools = list(bound or [])
|
|
587
|
+
if env or not tools:
|
|
588
|
+
node = ex._bound_node(c)
|
|
589
|
+
if node is not None:
|
|
590
|
+
rfr, r = ev.reduce(fr, node)
|
|
591
|
+
tools = ex._tools_from_expr(rfr.fc, r, in_tool_list=True) or (
|
|
592
|
+
ex._tools_from_expr(fc, node, in_tool_list=True) if r is not node else []
|
|
593
|
+
)
|
|
594
|
+
if site is not None and site is not rfr.fc: # tools passed in by a call site in another file
|
|
595
|
+
tools += [t for t in ex._tools_from_expr(site, r, in_tool_list=True) if t not in tools]
|
|
596
|
+
if node is None and "tools" in cfg: # tools listed in the config entry (names or objects)
|
|
597
|
+
cfr, tnode = cfg["tools"]
|
|
598
|
+
tools = ex._tools_from_expr(cfr.fc, tnode, in_tool_list=True)
|
|
599
|
+
if not tools: # tools=pick(*spec.tools): a list of tool names the code looks the tools up by
|
|
600
|
+
tools = _tool_names_in(ex, cfr, tnode)
|
|
601
|
+
for t in tools:
|
|
602
|
+
if ref not in ex.obs.bound_tools.setdefault(t, []):
|
|
603
|
+
ex.obs.bound_tools[t].append(ref)
|
|
604
|
+
handoffs: list[str] = []
|
|
605
|
+
ho = _kw(c, "handoffs") or _kw(c, "sub_agents") or _kw(c, "can_handoff_to")
|
|
606
|
+
if ho is None and fname in ("create_supervisor", "create_swarm"): # langgraph-supervisor / swarm
|
|
607
|
+
ho = _kw(c, "agents") or (c.args[0] if c.args else None)
|
|
608
|
+
if ho is not None:
|
|
609
|
+
handoffs = [h for h in (ex._handoff_target(el) for el in _seq_elements(ev, fr, ho)) if h]
|
|
610
|
+
managed = _kw(c, "managed_agents") # smolagents: the manager calls them like tools
|
|
611
|
+
delegates = [h for h in (ex._handoff_target(el) for el in _seq_elements(ev, fr, managed)) if h]
|
|
612
|
+
deleg = _kw(c, "allow_delegation")
|
|
613
|
+
allow = ev.value(fr, deleg) if deleg is not None else cfgv("allow_delegation")
|
|
614
|
+
if env or cfg: # bounds per agent: max_iter=c.get("max_iter", 6) / config max_iter
|
|
615
|
+
ex._agent_bounds.add(id(call))
|
|
616
|
+
for kw, kind in BOUND_KWARGS.items():
|
|
617
|
+
node = _kw(c, kw)
|
|
618
|
+
v = ev.value(fr, node) if node is not None else cfgv(kw)
|
|
619
|
+
if node is None and v is UNK:
|
|
620
|
+
continue
|
|
621
|
+
orig = _kw(call, kw)
|
|
622
|
+
assumed = None
|
|
623
|
+
if not isinstance(v, (int, float)) and isinstance(node, ast.Attribute): # config.settings.max_turns
|
|
624
|
+
from agenticreq.ast.constants import setting_default
|
|
625
|
+
|
|
626
|
+
got = setting_default(ex.obs.root, node.attr)
|
|
627
|
+
if got is not None:
|
|
628
|
+
v, assumed = got
|
|
629
|
+
ex.obs.bounds.append(
|
|
630
|
+
BoundRef(
|
|
631
|
+
kind=kind,
|
|
632
|
+
name=kw,
|
|
633
|
+
value=float(v) if isinstance(v, (int, float)) and not isinstance(v, bool) else None,
|
|
634
|
+
code_ref=_ref(fc.rel, orig if orig is not None else call),
|
|
635
|
+
agent=name,
|
|
636
|
+
assumed_from=assumed,
|
|
637
|
+
)
|
|
638
|
+
)
|
|
639
|
+
return DeclaredAgent(
|
|
640
|
+
name=name,
|
|
641
|
+
tools=tools,
|
|
642
|
+
system_prompt=prompt,
|
|
643
|
+
handoffs=handoffs,
|
|
644
|
+
kind=fname,
|
|
645
|
+
delegates=delegates,
|
|
646
|
+
var=assigned_to or (hint if how and how.startswith("factory") else None),
|
|
647
|
+
allow_delegation=allow is True,
|
|
648
|
+
code_ref=ref,
|
|
649
|
+
built_from=how,
|
|
650
|
+
)
|
|
651
|
+
|
|
652
|
+
|
|
653
|
+
def _bound_node(ex: ProjectExtractor, call: ast.Call) -> ast.expr | None:
|
|
654
|
+
"""The expression a call passes as its tools (``tools=``, ``bind_tools(x)``, create_react_agent's 2nd arg)."""
|
|
655
|
+
fname = _name(call.func)
|
|
656
|
+
if fname in BIND_CALLS:
|
|
657
|
+
return call.args[0] if call.args else _kw(call, "tools")
|
|
658
|
+
node = next((_kw(call, kw) for kw in TOOL_LIST_KWARGS if _kw(call, kw) is not None), None)
|
|
659
|
+
if node is None and fname == "create_react_agent" and len(call.args) > 1:
|
|
660
|
+
node = call.args[1]
|
|
661
|
+
if (
|
|
662
|
+
node is None
|
|
663
|
+
and call.args
|
|
664
|
+
and fname.startswith(("from_", "create_", "make_", "build_"))
|
|
665
|
+
and "tool" in fname.lower()
|
|
666
|
+
):
|
|
667
|
+
node = call.args[0] # ReActAgent.from_tools(tools, ...), make_tool_agent(tools)
|
|
668
|
+
return node
|
|
669
|
+
|
|
670
|
+
|
|
671
|
+
def _assigned_value(fc: FileCtx, name: str) -> ast.expr | None:
|
|
672
|
+
for n in ast.walk(fc.tree):
|
|
673
|
+
if isinstance(n, ast.Assign) and any(isinstance(t, ast.Name) and t.id == name for t in n.targets):
|
|
674
|
+
return n.value
|
|
675
|
+
return None
|
|
676
|
+
|
|
677
|
+
|
|
678
|
+
def _default_of(ex: ProjectExtractor, fc: FileCtx, node: ast.AST, call: ast.Call | None) -> str | None:
|
|
679
|
+
"""A model id that is a parameter default or a CLI default, not a literal at the call:
|
|
680
|
+
``def main(model_id="o1"): LiteLLMModel(model_id=model_id)`` and
|
|
681
|
+
``parser.add_argument("--model-id", default="o1")`` ... ``args.model_id``."""
|
|
682
|
+
if isinstance(node, ast.Name) and call is not None:
|
|
683
|
+
fn = ex._enclosing_fn.get(id(call))
|
|
684
|
+
if fn is not None:
|
|
685
|
+
a = fn.args
|
|
686
|
+
pos = [*a.posonlyargs, *a.args]
|
|
687
|
+
for arg, default in zip(pos[len(pos) - len(a.defaults) :], a.defaults):
|
|
688
|
+
if arg.arg == node.id:
|
|
689
|
+
return _str(default)
|
|
690
|
+
for arg, kd in zip(a.kwonlyargs, a.kw_defaults):
|
|
691
|
+
if arg.arg == node.id and kd is not None:
|
|
692
|
+
return _str(kd)
|
|
693
|
+
if isinstance(node, ast.Attribute): # args.model_id <- add_argument("--model-id", default=...)
|
|
694
|
+
want = node.attr
|
|
695
|
+
for n in ast.walk(fc.tree):
|
|
696
|
+
if isinstance(n, ast.Call) and _name(n.func) == "add_argument":
|
|
697
|
+
flags = [(_str(x) or "").lstrip("-").replace("-", "_") for x in n.args]
|
|
698
|
+
if want in flags or _str(_kw(n, "dest")) == want:
|
|
699
|
+
return _str(_kw(n, "default"))
|
|
700
|
+
return None
|
|
701
|
+
|
|
702
|
+
|
|
703
|
+
def _code_executor(ex: ProjectExtractor, fc: FileCtx, call: ast.Call, fname: str, agent: str, ref: SourceRef) -> None:
|
|
704
|
+
"""smolagents CodeAgent(executor_type=..., additional_authorized_imports=[...]); AutoGen
|
|
705
|
+
UserProxyAgent(code_execution_config={"use_docker": ...}) / CodeExecutorAgent(code_executor=...)."""
|
|
706
|
+
executor, unrestricted = None, False
|
|
707
|
+
if fname in ("CodeAgent", "CodeActAgent"):
|
|
708
|
+
ok, et = literal(_kw(call, "executor_type"))
|
|
709
|
+
executor = str(et) if ok and et else "local"
|
|
710
|
+
ok, imports = literal(_kw(call, "additional_authorized_imports"))
|
|
711
|
+
if ok and isinstance(imports, (list, tuple)):
|
|
712
|
+
unrestricted = bool({"*", "os", "subprocess", "sys", "shutil", "socket"} & {str(x) for x in imports})
|
|
713
|
+
elif fname == "UserProxyAgent":
|
|
714
|
+
cfg = _kw(call, "code_execution_config")
|
|
715
|
+
ok, val = literal(cfg)
|
|
716
|
+
if ok and val is False:
|
|
717
|
+
return # code execution switched off
|
|
718
|
+
use_docker = None
|
|
719
|
+
if isinstance(cfg, ast.Dict):
|
|
720
|
+
for k, v in zip(cfg.keys, cfg.values):
|
|
721
|
+
if _str(k) == "use_docker":
|
|
722
|
+
use_docker = literal(v)[1]
|
|
723
|
+
executor = "local" if use_docker is False else "docker"
|
|
724
|
+
unrestricted = executor == "local"
|
|
725
|
+
elif fname == "CodeExecutorAgent":
|
|
726
|
+
exec_node = _kw(call, "code_executor") or (call.args[1] if len(call.args) > 1 else None)
|
|
727
|
+
exname = (
|
|
728
|
+
_name(exec_node.func)
|
|
729
|
+
if isinstance(exec_node, ast.Call)
|
|
730
|
+
else _name(exec_node)
|
|
731
|
+
if exec_node is not None
|
|
732
|
+
else ""
|
|
733
|
+
)
|
|
734
|
+
executor = "docker" if "Docker" in exname else "jupyter" if "Jupyter" in exname else "local"
|
|
735
|
+
unrestricted = executor == "local"
|
|
736
|
+
if executor is not None:
|
|
737
|
+
ex.obs.code_executors.append(
|
|
738
|
+
CodeExecRef(agent=agent, kind=fname, executor=executor, unrestricted=unrestricted, code_ref=ref)
|
|
739
|
+
)
|
|
740
|
+
|
|
741
|
+
|
|
742
|
+
def _group_agent(
|
|
743
|
+
ex: ProjectExtractor, fc: FileCtx, call: ast.Call, fname: str, assigned_to: str | None, ref: SourceRef
|
|
744
|
+
) -> None:
|
|
745
|
+
"""A team / workflow / hierarchical crew is a coordinator that hands work to each participant."""
|
|
746
|
+
members = _kw(call, "participants") or _kw(call, "agents") or (call.args[0] if call.args else None)
|
|
747
|
+
if fname == "Crew":
|
|
748
|
+
proc = _kw(call, "process")
|
|
749
|
+
if proc is None or "hierarchical" not in ast.unparse(proc):
|
|
750
|
+
return # a sequential crew passes outputs along a list: no delegation unless allow_delegation
|
|
751
|
+
manager = _kw(call, "manager_agent")
|
|
752
|
+
if isinstance(manager, ast.Name) and isinstance(members, (ast.List, ast.Tuple)):
|
|
753
|
+
mgr = ex.agent_vars.get(manager.id)
|
|
754
|
+
if mgr is not None:
|
|
755
|
+
mgr.handoffs += [
|
|
756
|
+
h
|
|
757
|
+
for h in (ex._handoff_target(e) for e in members.elts)
|
|
758
|
+
if h and h not in mgr.handoffs and h != manager.id
|
|
759
|
+
]
|
|
760
|
+
return
|
|
761
|
+
if not isinstance(members, (ast.List, ast.Tuple)):
|
|
762
|
+
return
|
|
763
|
+
names = [h for h in (ex._handoff_target(e) for e in members.elts) if h]
|
|
764
|
+
if names:
|
|
765
|
+
ex.obs.declared_agents.append(
|
|
766
|
+
DeclaredAgent(name=assigned_to or fname, kind="group_chat", handoffs=names, var=assigned_to, code_ref=ref)
|
|
767
|
+
)
|
|
768
|
+
|
|
769
|
+
|
|
770
|
+
def _tool_body_delegation(ex: ProjectExtractor) -> None:
|
|
771
|
+
"""A tool whose body runs another agent (`await research_agent.run(q)`, `writer.invoke(...)`) is
|
|
772
|
+
delegation: the agent holding the tool calls that agent and gets its answer back (PydanticAI agent
|
|
773
|
+
delegation, and the same pattern in any framework)."""
|
|
774
|
+
holders: dict[str, list[DeclaredAgent]] = {}
|
|
775
|
+
for ag in ex.obs.declared_agents:
|
|
776
|
+
for t in ag.tools:
|
|
777
|
+
holders.setdefault(t, []).append(ag)
|
|
778
|
+
for fc in ex.files:
|
|
779
|
+
for n in ast.walk(fc.tree):
|
|
780
|
+
tool = ex.node_tool.get(id(n)) or ex._method_owner.get(id(n))
|
|
781
|
+
if tool is None or not isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
|
|
782
|
+
continue
|
|
783
|
+
for c in ast.walk(n):
|
|
784
|
+
if not (
|
|
785
|
+
isinstance(c, ast.Call)
|
|
786
|
+
and isinstance(c.func, ast.Attribute)
|
|
787
|
+
and c.func.attr in _RUN_CALLS
|
|
788
|
+
and isinstance(c.func.value, ast.Name)
|
|
789
|
+
):
|
|
790
|
+
continue
|
|
791
|
+
target = ex.agent_vars.get(c.func.value.id)
|
|
792
|
+
if target is None:
|
|
793
|
+
continue
|
|
794
|
+
for owner in holders.get(tool, []):
|
|
795
|
+
if owner is not target and target.var and target.var not in owner.delegates:
|
|
796
|
+
owner.delegates.append(target.var)
|
|
797
|
+
|
|
798
|
+
|
|
799
|
+
def _find_run_receivers(ex: ProjectExtractor) -> set[str]:
|
|
800
|
+
"""Names holding something whose call runs a whole agent loop (agent / graph / team / runner)."""
|
|
801
|
+
names = set(ex.agent_vars) | {"Runner"}
|
|
802
|
+
builders: set[str] = set()
|
|
803
|
+
for defs in ex._fn_index.values():
|
|
804
|
+
for _fc, fn in defs:
|
|
805
|
+
if any(
|
|
806
|
+
isinstance(r, ast.Return)
|
|
807
|
+
and isinstance(r.value, ast.Call)
|
|
808
|
+
and _name(r.value.func) in _RUN_BUILDERS | ex.agent_ctors
|
|
809
|
+
for r in ast.walk(fn)
|
|
810
|
+
):
|
|
811
|
+
builders.add(fn.name)
|
|
812
|
+
for fc in ex.files:
|
|
813
|
+
for n in ast.walk(fc.tree):
|
|
814
|
+
if (
|
|
815
|
+
isinstance(n, ast.Assign)
|
|
816
|
+
and isinstance(n.value, ast.Call)
|
|
817
|
+
and _name(n.value.func) in _RUN_BUILDERS | ex.agent_ctors | builders
|
|
818
|
+
):
|
|
819
|
+
names |= {_name(t) for t in n.targets if isinstance(t, (ast.Name, ast.Attribute))}
|
|
820
|
+
return names | builders
|
|
821
|
+
|
|
822
|
+
|
|
823
|
+
def _awaits_run(ex: ProjectExtractor, e: ast.AST, depth: int = 0) -> bool:
|
|
824
|
+
"""The awaited expression runs an agent: directly (`graph.ainvoke(...)`) or through a project
|
|
825
|
+
coroutine whose body does (`async def go(): ... runner.run_async(...)`; `wait_for(go(), 90)`)."""
|
|
826
|
+
for c in ast.walk(e):
|
|
827
|
+
if not isinstance(c, ast.Call):
|
|
828
|
+
continue
|
|
829
|
+
if ex._runs_agent(c):
|
|
830
|
+
return True
|
|
831
|
+
if depth < 2:
|
|
832
|
+
for _fc, fn in ex._fn_index.get(_name(c.func), [])[:2]:
|
|
833
|
+
if any(ex._awaits_run(x, depth + 1) for x in fn.body):
|
|
834
|
+
return True
|
|
835
|
+
return False
|
|
836
|
+
|
|
837
|
+
|
|
838
|
+
def _runs_agent(ex: ProjectExtractor, call: ast.Call) -> bool:
|
|
839
|
+
"""`graph.ainvoke(...)`, `Runner.run(...)`, `crew.kickoff()`, `self.app.invoke(...)`, `build().invoke()`."""
|
|
840
|
+
if _name(call.func) not in _RUN_CALLS or not isinstance(call.func, ast.Attribute):
|
|
841
|
+
return False
|
|
842
|
+
recv = call.func.value
|
|
843
|
+
if isinstance(recv, ast.Call):
|
|
844
|
+
return _name(recv.func) in ex._run_receivers | _RUN_BUILDERS
|
|
845
|
+
return _name(recv) in ex._run_receivers
|