AbstractRuntime 0.2.0__py3-none-any.whl → 0.4.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.
Files changed (36) hide show
  1. abstractruntime/__init__.py +7 -2
  2. abstractruntime/core/config.py +14 -1
  3. abstractruntime/core/event_keys.py +62 -0
  4. abstractruntime/core/models.py +12 -1
  5. abstractruntime/core/runtime.py +2444 -14
  6. abstractruntime/core/vars.py +95 -0
  7. abstractruntime/evidence/__init__.py +10 -0
  8. abstractruntime/evidence/recorder.py +325 -0
  9. abstractruntime/integrations/abstractcore/__init__.py +3 -0
  10. abstractruntime/integrations/abstractcore/constants.py +19 -0
  11. abstractruntime/integrations/abstractcore/default_tools.py +134 -0
  12. abstractruntime/integrations/abstractcore/effect_handlers.py +255 -6
  13. abstractruntime/integrations/abstractcore/factory.py +95 -10
  14. abstractruntime/integrations/abstractcore/llm_client.py +456 -52
  15. abstractruntime/integrations/abstractcore/mcp_worker.py +586 -0
  16. abstractruntime/integrations/abstractcore/observability.py +80 -0
  17. abstractruntime/integrations/abstractcore/summarizer.py +154 -0
  18. abstractruntime/integrations/abstractcore/tool_executor.py +481 -24
  19. abstractruntime/memory/__init__.py +21 -0
  20. abstractruntime/memory/active_context.py +746 -0
  21. abstractruntime/memory/active_memory.py +452 -0
  22. abstractruntime/memory/compaction.py +105 -0
  23. abstractruntime/rendering/__init__.py +17 -0
  24. abstractruntime/rendering/agent_trace_report.py +256 -0
  25. abstractruntime/rendering/json_stringify.py +136 -0
  26. abstractruntime/scheduler/scheduler.py +93 -2
  27. abstractruntime/storage/__init__.py +3 -1
  28. abstractruntime/storage/artifacts.py +20 -5
  29. abstractruntime/storage/json_files.py +15 -2
  30. abstractruntime/storage/observable.py +99 -0
  31. {abstractruntime-0.2.0.dist-info → abstractruntime-0.4.0.dist-info}/METADATA +5 -1
  32. abstractruntime-0.4.0.dist-info/RECORD +49 -0
  33. abstractruntime-0.4.0.dist-info/entry_points.txt +2 -0
  34. abstractruntime-0.2.0.dist-info/RECORD +0 -32
  35. {abstractruntime-0.2.0.dist-info → abstractruntime-0.4.0.dist-info}/WHEEL +0 -0
  36. {abstractruntime-0.2.0.dist-info → abstractruntime-0.4.0.dist-info}/licenses/LICENSE +0 -0
@@ -21,6 +21,7 @@ SCRATCHPAD = "scratchpad"
21
21
  RUNTIME = "_runtime"
22
22
  TEMP = "_temp"
23
23
  LIMITS = "_limits" # Canonical storage for runtime resource limits
24
+ NODE_TRACES = "node_traces" # _runtime namespace key for per-node execution traces
24
25
 
25
26
 
26
27
  def ensure_namespaces(vars: Dict[str, Any]) -> Dict[str, Any]:
@@ -79,6 +80,29 @@ def ensure_limits(vars: Dict[str, Any]) -> Dict[str, Any]:
79
80
  return get_limits(vars)
80
81
 
81
82
 
83
+ def get_node_traces(vars: Dict[str, Any]) -> Dict[str, Any]:
84
+ """Return the runtime-owned per-node trace mapping.
85
+
86
+ Stored under `run.vars["_runtime"]["node_traces"]`.
87
+ This is intended for host UX/debugging and for exposing traces to higher layers.
88
+ """
89
+ runtime_ns = get_runtime(vars)
90
+ traces = runtime_ns.get(NODE_TRACES)
91
+ if not isinstance(traces, dict):
92
+ traces = {}
93
+ runtime_ns[NODE_TRACES] = traces
94
+ return traces
95
+
96
+
97
+ def get_node_trace(vars: Dict[str, Any], node_id: str) -> Dict[str, Any]:
98
+ """Return a single node trace object (always a dict)."""
99
+ traces = get_node_traces(vars)
100
+ trace = traces.get(node_id)
101
+ if isinstance(trace, dict):
102
+ return trace
103
+ return {"node_id": node_id, "steps": []}
104
+
105
+
82
106
  def _default_limits() -> Dict[str, Any]:
83
107
  """Return default limits dict."""
84
108
  return {
@@ -92,3 +116,74 @@ def _default_limits() -> Dict[str, Any]:
92
116
  "warn_tokens_pct": 80,
93
117
  }
94
118
 
119
+
120
+ def parse_vars_path(path: str) -> list[Any]:
121
+ """Parse a path for inspecting `RunState.vars`.
122
+
123
+ Supports:
124
+ - dot paths: "scratchpad.research.sources[0].title"
125
+ - JSON pointer-ish paths: "/scratchpad/research/sources/0/title"
126
+ """
127
+ import re
128
+
129
+ raw = str(path or "").strip()
130
+ if not raw:
131
+ return []
132
+
133
+ tokens: list[Any] = []
134
+
135
+ if raw.startswith("/"):
136
+ for part in [p for p in raw.split("/") if p]:
137
+ part = part.replace("~1", "/").replace("~0", "~")
138
+ if part.isdigit():
139
+ tokens.append(int(part))
140
+ else:
141
+ tokens.append(part)
142
+ return tokens
143
+
144
+ for part in [p for p in raw.split(".") if p]:
145
+ # Allow list indexing as a bare segment: `foo.0.bar`
146
+ if "[" not in part and part.isdigit():
147
+ tokens.append(int(part))
148
+ continue
149
+
150
+ # Split `foo[0][1]` into ["foo", 0, 1]
151
+ for m in re.finditer(r"([^\[\]]+)|\[(\d+)\]", part):
152
+ key = m.group(1)
153
+ idx = m.group(2)
154
+ if key is not None:
155
+ tokens.append(key)
156
+ elif idx is not None:
157
+ tokens.append(int(idx))
158
+
159
+ return tokens
160
+
161
+
162
+ def resolve_vars_path(root: Any, tokens: list[Any]) -> Any:
163
+ """Resolve tokens against nested dict/list structures."""
164
+ cur: Any = root
165
+ at: list[str] = []
166
+
167
+ for tok in tokens:
168
+ if isinstance(tok, int):
169
+ if not isinstance(cur, list):
170
+ where = ".".join([p for p in at if p]) or "(root)"
171
+ raise ValueError(f"Expected list at {where} but found {type(cur).__name__}")
172
+ if tok < 0 or tok >= len(cur):
173
+ where = ".".join([p for p in at if p]) or "(root)"
174
+ raise ValueError(f"Index {tok} out of range at {where} (len={len(cur)})")
175
+ cur = cur[tok]
176
+ at.append(str(tok))
177
+ continue
178
+
179
+ key = str(tok)
180
+ if not isinstance(cur, dict):
181
+ where = ".".join([p for p in at if p]) or "(root)"
182
+ raise ValueError(f"Expected object at {where} but found {type(cur).__name__}")
183
+ if key not in cur:
184
+ where = ".".join([p for p in at if p]) or "(root)"
185
+ raise ValueError(f"Missing key '{key}' at {where}")
186
+ cur = cur[key]
187
+ at.append(key)
188
+
189
+ return cur
@@ -0,0 +1,10 @@
1
+ """abstractruntime.evidence
2
+
3
+ Runtime-owned evidence capture and indexing.
4
+ """
5
+
6
+ from .recorder import EvidenceRecorder, DEFAULT_EVIDENCE_TOOL_NAMES
7
+
8
+ __all__ = ["EvidenceRecorder", "DEFAULT_EVIDENCE_TOOL_NAMES"]
9
+
10
+
@@ -0,0 +1,325 @@
1
+ """abstractruntime.evidence.recorder
2
+
3
+ Evidence is "provenance-first": a durable record of what the system actually observed at
4
+ external boundaries (web + process execution), stored as artifacts with a small JSON index
5
+ in run state.
6
+
7
+ Design goals:
8
+ - Always-on capture for a small default set of tools (web_search/fetch_url/execute_command).
9
+ - Keep RunState.vars JSON-safe and bounded: store large payloads in ArtifactStore and keep refs.
10
+ - Make later indexing/storage upgrades possible (Elastic/vector/etc) without changing semantics.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ from dataclasses import dataclass
17
+ from datetime import datetime, timezone
18
+ from typing import Any, Dict, List, Optional, Sequence
19
+
20
+ from ..core.models import RunState
21
+ from ..storage.artifacts import ArtifactStore, artifact_ref, is_artifact_ref
22
+
23
+
24
+ DEFAULT_EVIDENCE_TOOL_NAMES: tuple[str, ...] = ("web_search", "fetch_url", "execute_command")
25
+
26
+
27
+ def utc_now_iso() -> str:
28
+ return datetime.now(timezone.utc).isoformat()
29
+
30
+
31
+ def _ensure_memory_spans(run: RunState) -> list[dict[str, Any]]:
32
+ runtime_ns = run.vars.get("_runtime")
33
+ if not isinstance(runtime_ns, dict):
34
+ runtime_ns = {}
35
+ run.vars["_runtime"] = runtime_ns
36
+ spans = runtime_ns.get("memory_spans")
37
+ if not isinstance(spans, list):
38
+ spans = []
39
+ runtime_ns["memory_spans"] = spans
40
+ return spans
41
+
42
+
43
+ def _preview(text: str, *, limit: int = 160) -> str:
44
+ s = str(text or "").strip()
45
+ if len(s) <= limit:
46
+ return s
47
+ return s[: max(0, limit - 1)] + "…"
48
+
49
+
50
+ def _json_loads_maybe(text: str) -> Optional[Any]:
51
+ if not isinstance(text, str):
52
+ return None
53
+ t = text.strip()
54
+ if not t:
55
+ return None
56
+ if not (t.startswith("{") or t.startswith("[")):
57
+ return None
58
+ try:
59
+ return json.loads(t)
60
+ except Exception:
61
+ return None
62
+
63
+
64
+ def _store_text(
65
+ store: ArtifactStore,
66
+ *,
67
+ text: str,
68
+ run_id: str,
69
+ tags: Dict[str, str],
70
+ content_type: str = "text/plain",
71
+ ) -> Optional[Dict[str, str]]:
72
+ s = str(text or "")
73
+ if not s:
74
+ return None
75
+ meta = store.store_text(s, content_type=content_type, run_id=run_id, tags=tags)
76
+ return artifact_ref(meta.artifact_id)
77
+
78
+
79
+ def _store_json(
80
+ store: ArtifactStore,
81
+ *,
82
+ data: Any,
83
+ run_id: str,
84
+ tags: Dict[str, str],
85
+ ) -> Optional[Dict[str, str]]:
86
+ if data is None:
87
+ return None
88
+ meta = store.store_json(data, run_id=run_id, tags=tags)
89
+ return artifact_ref(meta.artifact_id)
90
+
91
+
92
+ @dataclass(frozen=True)
93
+ class EvidenceCaptureStats:
94
+ recorded: int = 0
95
+
96
+
97
+ class EvidenceRecorder:
98
+ """Runtime-side recorder for always-on evidence."""
99
+
100
+ def __init__(
101
+ self,
102
+ *,
103
+ artifact_store: ArtifactStore,
104
+ tool_names: Sequence[str] = DEFAULT_EVIDENCE_TOOL_NAMES,
105
+ ):
106
+ self._store = artifact_store
107
+ self._tool_names = {str(n).strip() for n in tool_names if isinstance(n, str) and n.strip()}
108
+
109
+ def record_tool_calls(
110
+ self,
111
+ *,
112
+ run: RunState,
113
+ node_id: str,
114
+ tool_calls: list[Any],
115
+ tool_results: Dict[str, Any],
116
+ ) -> EvidenceCaptureStats:
117
+ if not isinstance(tool_results, dict):
118
+ return EvidenceCaptureStats(recorded=0)
119
+ results = tool_results.get("results", [])
120
+ if not isinstance(results, list) or not results:
121
+ return EvidenceCaptureStats(recorded=0)
122
+ if not isinstance(tool_calls, list):
123
+ tool_calls = []
124
+
125
+ spans = _ensure_memory_spans(run)
126
+ recorded = 0
127
+
128
+ for idx, r in enumerate(results):
129
+ if not isinstance(r, dict):
130
+ continue
131
+ call = tool_calls[idx] if idx < len(tool_calls) and isinstance(tool_calls[idx], dict) else {}
132
+ tool_name = str(r.get("name") or call.get("name") or "").strip()
133
+ if not tool_name or tool_name not in self._tool_names:
134
+ continue
135
+
136
+ ok = bool(r.get("success") is True)
137
+ call_id = str(r.get("call_id") or call.get("call_id") or "")
138
+ error = r.get("error")
139
+ error_text = str(error).strip() if isinstance(error, str) and error.strip() else None
140
+ args = call.get("arguments") if isinstance(call, dict) else None
141
+ args_dict = dict(args) if isinstance(args, dict) else {}
142
+
143
+ output = r.get("output")
144
+ # Tool executors vary: output may be str/dict/None.
145
+ output_dict = dict(output) if isinstance(output, dict) else None
146
+ output_text = str(output or "") if isinstance(output, str) else None
147
+
148
+ created_at = utc_now_iso()
149
+ tags: Dict[str, str] = {"kind": "evidence", "tool": tool_name}
150
+
151
+ evidence_payload: Dict[str, Any] = {
152
+ "tool_name": tool_name,
153
+ "call_id": call_id,
154
+ "success": ok,
155
+ "error": error_text,
156
+ "created_at": created_at,
157
+ "run_id": run.run_id,
158
+ "workflow_id": run.workflow_id,
159
+ "node_id": node_id,
160
+ "arguments": args_dict,
161
+ }
162
+ if run.actor_id:
163
+ evidence_payload["actor_id"] = str(run.actor_id)
164
+ if getattr(run, "session_id", None):
165
+ evidence_payload["session_id"] = str(run.session_id)
166
+
167
+ artifacts: Dict[str, Any] = {}
168
+
169
+ if tool_name == "fetch_url":
170
+ url = str(args_dict.get("url") or "")
171
+ if url:
172
+ tags["url"] = url[:200]
173
+
174
+ if isinstance(output_dict, dict):
175
+ # Store and strip large text fields from the tool output dict.
176
+ raw_text = output_dict.pop("raw_text", None)
177
+ norm_text = output_dict.pop("normalized_text", None)
178
+ content_type = output_dict.get("content_type")
179
+ content_type_str = str(content_type) if isinstance(content_type, str) else ""
180
+
181
+ raw_ref = None
182
+ if isinstance(raw_text, str) and raw_text:
183
+ raw_ref = _store_text(
184
+ self._store,
185
+ text=raw_text,
186
+ run_id=run.run_id,
187
+ tags={**tags, "part": "raw"},
188
+ content_type=content_type_str or "text/plain",
189
+ )
190
+ output_dict["raw_artifact"] = raw_ref
191
+ artifacts["raw"] = raw_ref
192
+
193
+ norm_ref = None
194
+ if isinstance(norm_text, str) and norm_text:
195
+ norm_ref = _store_text(
196
+ self._store,
197
+ text=norm_text,
198
+ run_id=run.run_id,
199
+ tags={**tags, "part": "normalized"},
200
+ content_type="text/plain",
201
+ )
202
+ output_dict["normalized_artifact"] = norm_ref
203
+ artifacts["normalized_text"] = norm_ref
204
+
205
+ evidence_payload["url"] = str(output_dict.get("url") or url)
206
+ evidence_payload["final_url"] = str(output_dict.get("final_url") or "")
207
+ evidence_payload["content_type"] = content_type_str
208
+ evidence_payload["size_bytes"] = output_dict.get("size_bytes")
209
+ if artifacts:
210
+ evidence_payload["artifacts"] = artifacts
211
+
212
+ # Write back the stripped/augmented dict into the tool result so run state stays small.
213
+ r["output"] = output_dict
214
+
215
+ elif tool_name == "execute_command":
216
+ cmd = str(args_dict.get("command") or "")
217
+ if cmd:
218
+ tags["command"] = _preview(cmd, limit=200)
219
+
220
+ if isinstance(output_dict, dict):
221
+ stdout = output_dict.pop("stdout", None)
222
+ stderr = output_dict.pop("stderr", None)
223
+
224
+ stdout_ref = None
225
+ if isinstance(stdout, str) and stdout:
226
+ stdout_ref = _store_text(
227
+ self._store,
228
+ text=stdout,
229
+ run_id=run.run_id,
230
+ tags={**tags, "part": "stdout"},
231
+ )
232
+ output_dict["stdout_artifact"] = stdout_ref
233
+ artifacts["stdout"] = stdout_ref
234
+
235
+ stderr_ref = None
236
+ if isinstance(stderr, str) and stderr:
237
+ stderr_ref = _store_text(
238
+ self._store,
239
+ text=stderr,
240
+ run_id=run.run_id,
241
+ tags={**tags, "part": "stderr"},
242
+ )
243
+ output_dict["stderr_artifact"] = stderr_ref
244
+ artifacts["stderr"] = stderr_ref
245
+
246
+ evidence_payload["command"] = str(output_dict.get("command") or cmd)
247
+ evidence_payload["return_code"] = output_dict.get("return_code")
248
+ evidence_payload["duration_s"] = output_dict.get("duration_s")
249
+ evidence_payload["working_directory"] = output_dict.get("working_directory")
250
+ evidence_payload["platform"] = output_dict.get("platform")
251
+ if artifacts:
252
+ evidence_payload["artifacts"] = artifacts
253
+
254
+ r["output"] = output_dict
255
+
256
+ elif isinstance(output_text, str) and output_text:
257
+ out_ref = _store_text(
258
+ self._store,
259
+ text=output_text,
260
+ run_id=run.run_id,
261
+ tags={**tags, "part": "output"},
262
+ )
263
+ if out_ref is not None:
264
+ artifacts["output"] = out_ref
265
+ evidence_payload["artifacts"] = artifacts
266
+
267
+ elif tool_name == "web_search":
268
+ query = str(args_dict.get("query") or "")
269
+ if query:
270
+ tags["query"] = _preview(query, limit=200)
271
+ evidence_payload["query"] = query
272
+
273
+ if isinstance(output_text, str) and output_text:
274
+ parsed = _json_loads_maybe(output_text)
275
+ if parsed is not None:
276
+ out_ref = _store_json(self._store, data=parsed, run_id=run.run_id, tags={**tags, "part": "results"})
277
+ else:
278
+ out_ref = _store_text(self._store, text=output_text, run_id=run.run_id, tags={**tags, "part": "results"})
279
+ if out_ref is not None:
280
+ artifacts["results"] = out_ref
281
+ evidence_payload["artifacts"] = artifacts
282
+ elif isinstance(output_dict, dict):
283
+ out_ref = _store_json(self._store, data=output_dict, run_id=run.run_id, tags={**tags, "part": "results"})
284
+ if out_ref is not None:
285
+ artifacts["results"] = out_ref
286
+ evidence_payload["artifacts"] = artifacts
287
+
288
+ # Store the evidence record itself (small JSON with artifact refs).
289
+ record_ref = _store_json(self._store, data=evidence_payload, run_id=run.run_id, tags=tags)
290
+ if not (isinstance(record_ref, dict) and is_artifact_ref(record_ref)):
291
+ continue
292
+ evidence_id = record_ref["$artifact"]
293
+
294
+ # Append to span-like index for fast listing.
295
+ span_record: Dict[str, Any] = {
296
+ "kind": "evidence",
297
+ "artifact_id": evidence_id,
298
+ "created_at": created_at,
299
+ "from_timestamp": created_at,
300
+ "to_timestamp": created_at,
301
+ "message_count": 0,
302
+ "tool_name": tool_name,
303
+ "call_id": call_id,
304
+ "success": ok,
305
+ }
306
+ if tool_name == "fetch_url":
307
+ span_record["url"] = evidence_payload.get("url") or str(args_dict.get("url") or "")
308
+ elif tool_name == "web_search":
309
+ span_record["query"] = str(args_dict.get("query") or "")
310
+ elif tool_name == "execute_command":
311
+ span_record["command_preview"] = _preview(str(args_dict.get("command") or ""))
312
+
313
+ # Attach span id back to the tool result entry for easy linking in traces/UIs.
314
+ meta = r.get("meta")
315
+ if not isinstance(meta, dict):
316
+ meta = {}
317
+ r["meta"] = meta
318
+ meta["evidence_id"] = evidence_id
319
+
320
+ spans.append(span_record)
321
+ recorded += 1
322
+
323
+ return EvidenceCaptureStats(recorded=recorded)
324
+
325
+
@@ -27,6 +27,7 @@ from .factory import (
27
27
  create_remote_file_runtime,
28
28
  create_remote_runtime,
29
29
  )
30
+ from .observability import attach_global_event_bus_bridge, emit_step_record
30
31
 
31
32
  __all__ = [
32
33
  "AbstractCoreLLMClient",
@@ -44,4 +45,6 @@ __all__ = [
44
45
  "create_hybrid_runtime",
45
46
  "create_local_file_runtime",
46
47
  "create_remote_file_runtime",
48
+ "attach_global_event_bus_bridge",
49
+ "emit_step_record",
47
50
  ]
@@ -0,0 +1,19 @@
1
+ """abstractruntime.integrations.abstractcore.constants
2
+
3
+ Single source of truth for AbstractRuntime orchestration defaults when it
4
+ executes AbstractCore-backed effects (LLM calls and tool calls).
5
+ """
6
+
7
+ # Default *effect* timeouts (seconds).
8
+ #
9
+ # IMPORTANT: These are NOT a "workflow/run TTL". Workflows can be long-lived
10
+ # (hours/days) or even continuous. These limits only apply to a *single*
11
+ # runtime-managed operation (e.g. one LLM HTTP request, one tool call).
12
+ #
13
+ # Rationale:
14
+ # - Local inference can be slow for large contexts.
15
+ # - In an orchestrator, timeouts are policy and should be explicit + consistent.
16
+ DEFAULT_LLM_TIMEOUT_S: float = 7200.0
17
+ DEFAULT_TOOL_TIMEOUT_S: float = 7200.0
18
+
19
+
@@ -0,0 +1,134 @@
1
+ """Default toolsets for AbstractRuntime's AbstractCore integration.
2
+
3
+ This module provides a *host-side* convenience list of common, safe(ish) tools
4
+ that can be wired into a Runtime via MappingToolExecutor.
5
+
6
+ Design notes:
7
+ - We keep the runtime kernel dependency-light; this lives under
8
+ `integrations/abstractcore/` which is the explicit opt-in to AbstractCore.
9
+ - Tool callables are never persisted in RunState; only ToolSpecs (dicts) are.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from typing import Any, Callable, Dict, List, Sequence
15
+
16
+
17
+ ToolCallable = Callable[..., Any]
18
+
19
+
20
+ def _tool_name(func: ToolCallable) -> str:
21
+ tool_def = getattr(func, "_tool_definition", None)
22
+ if tool_def is not None:
23
+ name = getattr(tool_def, "name", None)
24
+ if isinstance(name, str) and name.strip():
25
+ return name.strip()
26
+ name = getattr(func, "__name__", "")
27
+ return str(name or "").strip()
28
+
29
+
30
+ def _tool_spec(func: ToolCallable) -> Dict[str, Any]:
31
+ tool_def = getattr(func, "_tool_definition", None)
32
+ if tool_def is not None and hasattr(tool_def, "to_dict"):
33
+ return dict(tool_def.to_dict())
34
+
35
+ from abstractcore.tools.core import ToolDefinition
36
+
37
+ return dict(ToolDefinition.from_function(func).to_dict())
38
+
39
+
40
+ def get_default_toolsets() -> Dict[str, Dict[str, Any]]:
41
+ """Return default toolsets {id -> {label, tools:[callables]}}."""
42
+ from abstractcore.tools.common_tools import (
43
+ list_files,
44
+ read_file,
45
+ search_files,
46
+ analyze_code,
47
+ write_file,
48
+ edit_file,
49
+ web_search,
50
+ fetch_url,
51
+ execute_command,
52
+ )
53
+
54
+ return {
55
+ "files": {
56
+ "id": "files",
57
+ "label": "Files",
58
+ "tools": [list_files, search_files, analyze_code, read_file, write_file, edit_file],
59
+ },
60
+ "web": {
61
+ "id": "web",
62
+ "label": "Web",
63
+ "tools": [web_search, fetch_url],
64
+ },
65
+ "system": {
66
+ "id": "system",
67
+ "label": "System",
68
+ "tools": [execute_command],
69
+ },
70
+ }
71
+
72
+
73
+ def get_default_tools() -> List[ToolCallable]:
74
+ """Return the flattened list of all default tool callables."""
75
+ toolsets = get_default_toolsets()
76
+ out: list[ToolCallable] = []
77
+ seen: set[str] = set()
78
+ for spec in toolsets.values():
79
+ for tool in spec.get("tools", []):
80
+ if not callable(tool):
81
+ continue
82
+ name = _tool_name(tool)
83
+ if not name or name in seen:
84
+ continue
85
+ seen.add(name)
86
+ out.append(tool)
87
+ return out
88
+
89
+
90
+ def list_default_tool_specs() -> List[Dict[str, Any]]:
91
+ """Return ToolSpecs for UI and LLM payloads (JSON-safe)."""
92
+ toolsets = get_default_toolsets()
93
+ toolset_by_name: Dict[str, str] = {}
94
+ for tid, spec in toolsets.items():
95
+ for tool in spec.get("tools", []):
96
+ if callable(tool):
97
+ name = _tool_name(tool)
98
+ if name:
99
+ toolset_by_name[name] = tid
100
+
101
+ out: list[Dict[str, Any]] = []
102
+ for tool in get_default_tools():
103
+ spec = _tool_spec(tool)
104
+ name = str(spec.get("name") or "").strip()
105
+ if not name:
106
+ continue
107
+ spec["toolset"] = toolset_by_name.get(name) or "other"
108
+ out.append(spec)
109
+
110
+ # Stable ordering: toolset then name
111
+ out.sort(key=lambda s: (str(s.get("toolset") or ""), str(s.get("name") or "")))
112
+ return out
113
+
114
+
115
+ def build_default_tool_map() -> Dict[str, ToolCallable]:
116
+ """Return {tool_name -> callable} for MappingToolExecutor."""
117
+ tool_map: Dict[str, ToolCallable] = {}
118
+ for tool in get_default_tools():
119
+ name = _tool_name(tool)
120
+ if not name:
121
+ continue
122
+ tool_map[name] = tool
123
+ return tool_map
124
+
125
+
126
+ def filter_tool_specs(tool_names: Sequence[str]) -> List[Dict[str, Any]]:
127
+ """Return ToolSpecs for the requested tool names (order preserved)."""
128
+ available = {str(s.get("name")): s for s in list_default_tool_specs() if isinstance(s.get("name"), str)}
129
+ out: list[Dict[str, Any]] = []
130
+ for name in tool_names:
131
+ spec = available.get(name)
132
+ if spec is not None:
133
+ out.append(spec)
134
+ return out