llm-wf-core 0.5.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.
@@ -0,0 +1,45 @@
1
+ """
2
+ llm-wf — Moteur de workflow LLM basé sur des graphes d'agents.
3
+
4
+ Exécute des pipelines d'agents LLM connectés par leurs variables,
5
+ avec parallélisation automatique des agents indépendants.
6
+
7
+ Usage CLI : llmwf -w workflow.yaml -v var=valeur
8
+ """
9
+
10
+ from llm_wf_core.agent import WorkflowAgent
11
+ from llm_wf_core.agent_services import ToolError
12
+ from llm_wf_core.agent_tools import ToolResult, register_tool, unregister_tool
13
+ from llm_wf_core.config import WorkflowConfig
14
+ from llm_wf_core.diagram import export_diagram, generate_plantuml
15
+ from llm_wf_core.executor import WorkflowCancelled, WorkflowExecutor
16
+ from llm_wf_core.graph import WorkflowGraph
17
+ from llm_wf_core.loader import load_file
18
+ from llm_wf_core.memory import MemoryStore
19
+ from llm_wf_core.providers import LLMProvider, build_provider, escape_markdown
20
+
21
+ from importlib.metadata import version, PackageNotFoundError
22
+
23
+ try:
24
+ __version__ = version("llm-wf-core")
25
+ except PackageNotFoundError:
26
+ __version__ = "unknown"
27
+
28
+ __all__ = [
29
+ "WorkflowAgent",
30
+ "register_tool",
31
+ "unregister_tool",
32
+ "ToolError",
33
+ "ToolResult",
34
+ "WorkflowConfig",
35
+ "WorkflowCancelled",
36
+ "WorkflowExecutor",
37
+ "WorkflowGraph",
38
+ "MemoryStore",
39
+ "export_diagram",
40
+ "generate_plantuml",
41
+ "load_file",
42
+ "LLMProvider",
43
+ "build_provider",
44
+ "escape_markdown",
45
+ ]
llm_wf_core/agent.py ADDED
@@ -0,0 +1,161 @@
1
+ import re
2
+ from dataclasses import dataclass, field
3
+
4
+ from llm_wf_core.agent_tools import TOOLS
5
+
6
+ AGENT_TYPES = ("llm", "agent")
7
+ MAX_STEPS_LIMIT = 100
8
+ MAX_DELEGATIONS_LIMIT = 50
9
+ _RAG_KEYS = frozenset({"base", "query", "top_k", "as"})
10
+ _IDENT_RE = re.compile(r"^[^\W\d]\w*$")
11
+ _DOMAIN_RE = re.compile(r"^(\*\.)?[A-Za-z0-9]([A-Za-z0-9.-]*[A-Za-z0-9])?$")
12
+
13
+
14
+ @dataclass
15
+ class ToolCall:
16
+ """Appel d'outil demandé par le LLM (format neutre, indépendant du fournisseur)."""
17
+
18
+ id: str
19
+ name: str
20
+ args: dict
21
+
22
+
23
+ @dataclass
24
+ class Turn:
25
+ """Un tour de LLM dans une boucle d'agent : texte et/ou appels d'outils."""
26
+
27
+ text: str = ""
28
+ tool_calls: list[ToolCall] = field(default_factory=list)
29
+ usage: dict = field(default_factory=dict)
30
+ # Contenu natif de la réponse, à rejouer tel quel dans l'historique (ex. blocs `thinking` d'Anthropic,
31
+ # exigés pour poursuivre un tour d'outils). Opaque pour la boucle ; ignoré par les providers qui n'en ont pas besoin.
32
+ raw: object = None
33
+
34
+
35
+ @dataclass
36
+ class WorkflowAgent:
37
+ """
38
+ Un nœud du workflow : agent LLM avec son prompt et ses variables.
39
+
40
+ - 1 output → la réponse LLM brute est assignée à cette variable
41
+ - N outputs → le prompt doit retourner un JSON {"var1": "...", ...}
42
+
43
+ `type` :
44
+ - "llm" (défaut) : un appel unique au LLM ;
45
+ - "agent" : boucle d'outils (`tools`), au plus `max_steps` tours et `timeout` secondes au total.
46
+ """
47
+
48
+ id: str
49
+ prompt_file: str
50
+ service: str
51
+ model: str
52
+ url: str = "None"
53
+ api_key: str = "None"
54
+ inputs: list[str] = field(default_factory=list)
55
+ outputs: list[str] = field(default_factory=list)
56
+ type: str = "llm"
57
+ tools: list[str] = field(default_factory=list)
58
+ max_steps: int = 10
59
+ timeout: float = 300.0
60
+ # Options des agents : sorties lues dans des fichiers (variable → chemin dans l'espace de travail),
61
+ # domaines que fetch_url peut contacter, nombre d'appels de ask_model par exécution.
62
+ output_files: dict = field(default_factory=dict)
63
+ allowed_domains: list[str] = field(default_factory=list)
64
+ max_delegations: int = 5
65
+ # RAG (cf. rag.py). `rag` (chatbot ou agent) : récupération automatique avant l'appel, {base, query, top_k, as} ;
66
+ # `knowledge` (agent) : bases que l'outil search_knowledge peut interroger.
67
+ rag: dict = field(default_factory=dict)
68
+ knowledge: list[str] = field(default_factory=list)
69
+ # Définition en code : template Jinja2 du prompt donné directement (au lieu d'un fichier). Dans ce cas
70
+ # `prompt_file` reste vide (""). Les deux ensemble sont refusés.
71
+ prompt_text: str = ""
72
+
73
+ def __post_init__(self):
74
+ self._check_rag()
75
+ if not self.id:
76
+ raise ValueError("L'identifiant de l'agent ne peut pas être vide")
77
+ if self.prompt_file and self.prompt_text:
78
+ raise ValueError(f"Agent '{self.id}' : prompt_file et prompt_text sont exclusifs")
79
+ if not (self.prompt_file or self.prompt_text.strip()):
80
+ raise ValueError(f"Agent '{self.id}' : prompt_file (ou prompt_text) requis")
81
+ if not self.service:
82
+ raise ValueError(f"Agent '{self.id}' : service requis")
83
+ if not self.model:
84
+ raise ValueError(f"Agent '{self.id}' : model requis")
85
+ if not self.outputs:
86
+ raise ValueError(f"Agent '{self.id}' : outputs ne peut pas être vide")
87
+ if self.type not in AGENT_TYPES:
88
+ raise ValueError(
89
+ f"Agent '{self.id}' : type '{self.type}' inconnu (attendu : {', '.join(AGENT_TYPES)})"
90
+ )
91
+ if self.type == "llm":
92
+ for name, value in (("tools", self.tools), ("output_files", self.output_files),
93
+ ("allowed_domains", self.allowed_domains), ("knowledge", self.knowledge)):
94
+ if value:
95
+ raise ValueError(f"Agent '{self.id}' : '{name}' n'a de sens que pour type: agent")
96
+ return
97
+ if not self.tools:
98
+ raise ValueError(f"Agent '{self.id}' : un agent (type: agent) doit déclarer au moins un outil")
99
+ unknown = [t for t in self.tools if t not in TOOLS]
100
+ if unknown:
101
+ raise ValueError(
102
+ f"Agent '{self.id}' : outil(s) inconnu(s) {unknown} "
103
+ f"(disponibles : {', '.join(sorted(TOOLS))})"
104
+ )
105
+ if len(set(self.tools)) != len(self.tools):
106
+ raise ValueError(f"Agent '{self.id}' : outils dupliqués dans 'tools'")
107
+ if not isinstance(self.max_steps, int) or not 1 <= self.max_steps <= MAX_STEPS_LIMIT:
108
+ raise ValueError(f"Agent '{self.id}' : max_steps doit être un entier entre 1 et {MAX_STEPS_LIMIT}")
109
+ if not self.timeout or self.timeout <= 0:
110
+ raise ValueError(f"Agent '{self.id}' : timeout doit être positif")
111
+ if not isinstance(self.max_delegations, int) or not 1 <= self.max_delegations <= MAX_DELEGATIONS_LIMIT:
112
+ raise ValueError(f"Agent '{self.id}' : max_delegations doit être un entier entre 1 et {MAX_DELEGATIONS_LIMIT}")
113
+ # Sorties lues dans des fichiers de l'espace de travail
114
+ if not isinstance(self.output_files, dict):
115
+ raise ValueError(f"Agent '{self.id}' : output_files doit associer une variable à un chemin")
116
+ for var, rel in self.output_files.items():
117
+ if var not in self.outputs:
118
+ raise ValueError(f"Agent '{self.id}' : output_files « {var} » n'est pas l'une de ses sorties")
119
+ parts = str(rel).replace("\\", "/").split("/")
120
+ if not isinstance(rel, str) or not rel.strip() or rel.startswith("/") or ".." in parts:
121
+ raise ValueError(f"Agent '{self.id}' : chemin invalide pour output_files « {var} » "
122
+ f"(relatif à l'espace de travail, sans « .. »)")
123
+ if "submit_result" in self.tools and all(o in self.output_files for o in self.outputs):
124
+ raise ValueError(f"Agent '{self.id}' : submit_result a besoin d'au moins une sortie qui ne vient pas d'un fichier")
125
+ # Réseau : fetch_url ne contacte que des domaines déclarés (sans domaine, il refuse tout)
126
+ if self.allowed_domains and "fetch_url" not in self.tools:
127
+ raise ValueError(f"Agent '{self.id}' : allowed_domains n'a de sens qu'avec l'outil fetch_url")
128
+ if not isinstance(self.allowed_domains, list) or not all(
129
+ isinstance(d, str) and _DOMAIN_RE.match(d.strip()) for d in self.allowed_domains):
130
+ raise ValueError(f"Agent '{self.id}' : allowed_domains attend des noms de domaine "
131
+ f"(ex. example.org ou *.example.org), sans schéma ni chemin")
132
+ # Bases de connaissances : l'outil search_knowledge et la liste `knowledge` vont ensemble
133
+ if not isinstance(self.knowledge, list) or not all(isinstance(b, str) and b for b in self.knowledge):
134
+ raise ValueError(f"Agent '{self.id}' : 'knowledge' doit être une liste d'identifiants de bases")
135
+ if "search_knowledge" in self.tools and not self.knowledge:
136
+ raise ValueError(f"Agent '{self.id}' : search_knowledge exige 'knowledge' (ex. [cours])")
137
+ if self.knowledge and "search_knowledge" not in self.tools:
138
+ raise ValueError(f"Agent '{self.id}' : 'knowledge' n'a de sens qu'avec l'outil search_knowledge")
139
+ if len(set(self.knowledge)) != len(self.knowledge):
140
+ raise ValueError(f"Agent '{self.id}' : bases dupliquées dans 'knowledge'")
141
+
142
+ def _check_rag(self) -> None:
143
+ """Récupération automatique (`rag`), pour un chatbot comme pour un agent."""
144
+ if not self.rag:
145
+ return
146
+ r = self.rag
147
+ if not isinstance(r, dict) or set(r) - _RAG_KEYS:
148
+ raise ValueError(f"Agent '{self.id}' : 'rag' attend {{base, query, top_k, as}}")
149
+ if not isinstance(r.get("base"), str) or not r["base"]:
150
+ raise ValueError(f"Agent '{self.id}' : rag.base (identifiant de base de connaissances) requis")
151
+ if r.get("query") not in self.inputs:
152
+ raise ValueError(f"Agent '{self.id}' : rag.query doit être l'une des entrées de la tâche "
153
+ f"({', '.join(self.inputs) or 'aucune'})")
154
+ top_k = r.get("top_k")
155
+ if top_k is not None and (not isinstance(top_k, int) or isinstance(top_k, bool) or not 1 <= top_k <= 20):
156
+ raise ValueError(f"Agent '{self.id}' : rag.top_k doit être un entier entre 1 et 20")
157
+ name = r.get("as", "contexte")
158
+ if not isinstance(name, str) or not _IDENT_RE.match(name):
159
+ raise ValueError(f"Agent '{self.id}' : rag.as doit être un nom de variable valide")
160
+ if name in self.inputs or name in self.outputs:
161
+ raise ValueError(f"Agent '{self.id}' : rag.as « {name} » est déjà une entrée ou une sortie")
@@ -0,0 +1,205 @@
1
+ """
2
+ Boucle d'un nœud « agent » : le LLM appelle des outils, observe, recommence, puis répond.
3
+
4
+ La boucle ne connaît ni le provider, ni le retry, ni le circuit breaker : l'exécuteur lui fournit
5
+ `call_turn(messages, specs) -> Turn` (un tour de LLM déjà protégé). Les outils renvoient leurs erreurs au
6
+ LLM sous forme de texte (cf. `agent_tools.call_tool`) ; seule une défaillance du LLM lui-même remonte.
7
+
8
+ Limites : `agent.max_steps` tours, `agent.timeout` secondes pour l'ensemble (un appel LLM déjà parti n'est pas
9
+ interrompu). Si une limite est atteinte, un dernier tour avec `tool_choice="none"` (aucun appel d'outil permis)
10
+ demande la réponse finale.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import time
17
+ from collections.abc import Callable
18
+ from dataclasses import dataclass, field
19
+
20
+ from llm_wf_core.agent import Turn, WorkflowAgent
21
+ from llm_wf_core.agent_tools import Workspace, call_tool, tool_specs
22
+
23
+ TRACE_CHARS = 2000 # taille maximale d'un argument ou résultat dans la trace
24
+
25
+ MAX_REMINDERS = 2 # rappels envoyés à un agent qui s'apprête à conclure sans avoir fini son travail
26
+ SUBMIT_REMINDER = (
27
+ "Tu n'as pas remis ton résultat. Appelle maintenant l'outil submit_result, avec une valeur pour chacune de ces "
28
+ "sorties : {sorties}."
29
+ )
30
+ FILES_REMINDER = (
31
+ "Le fichier attendu comme sortie n'existe pas dans ton espace de travail : {fichiers}. Écris-le avec write_file"
32
+ "{suite}."
33
+ )
34
+
35
+ FINAL_REQUEST = (
36
+ "Limite atteinte ({raison}). Donne maintenant ta réponse finale à partir de ce qui a déjà été fait, "
37
+ "sans appeler d'outil."
38
+ )
39
+
40
+
41
+ @dataclass
42
+ class AgentLoopResult:
43
+ text: str
44
+ ended: str # "answer" | "submitted" (submit_result) | "max_steps" | "timeout"
45
+ steps: int = 0
46
+ tool_calls: int = 0
47
+ input_tokens: int = 0
48
+ output_tokens: int = 0
49
+ trace: str = "" # Markdown, pour --prompts-dir
50
+ workspace: str = ""
51
+ errors: list[str] = field(default_factory=list) # erreurs d'outils rencontrées (pour le diagnostic)
52
+
53
+
54
+ def _missing_output_files(agent: WorkflowAgent, workspace: Workspace) -> list[str]:
55
+ """Fichiers de sortie déclarés (`output_files`) que l'agent n'a pas produits."""
56
+ missing = []
57
+ for rel in agent.output_files.values():
58
+ try:
59
+ if not workspace.resolve(rel).is_file():
60
+ missing.append(rel)
61
+ except Exception:
62
+ missing.append(rel)
63
+ return missing
64
+
65
+
66
+ def _exit_reminder(agent: WorkflowAgent, workspace: Workspace, submitted: bool) -> str | None:
67
+ """Rappel à envoyer à un agent qui s'apprête à conclure alors que son travail n'est pas fini : résultat non
68
+ remis avec submit_result, ou fichier de sortie absent. None si tout est en ordre."""
69
+ parts = []
70
+ if "submit_result" in agent.tools and not submitted:
71
+ parts.append(SUBMIT_REMINDER.format(sorties=", ".join(workspace.services.outputs)))
72
+ missing = _missing_output_files(agent, workspace)
73
+ if missing:
74
+ suite = " ; si tu avais déjà remis ton résultat, rappelle submit_result ensuite" if "submit_result" in agent.tools else ""
75
+ parts.append(FILES_REMINDER.format(fichiers=", ".join(missing), suite=suite))
76
+ return " ".join(parts) or None
77
+
78
+
79
+ def _clip(text: str, limit: int = TRACE_CHARS) -> str:
80
+ return text if len(text) <= limit else text[:limit] + f"\n[… {len(text) - limit} caractère(s) omis]"
81
+
82
+
83
+ def _fmt_args(args) -> str:
84
+ try:
85
+ return json.dumps(args, ensure_ascii=False, indent=1) if isinstance(args, dict) else repr(args)
86
+ except (TypeError, ValueError):
87
+ return repr(args)
88
+
89
+
90
+ def run_agent_loop(
91
+ agent: WorkflowAgent,
92
+ system_prompt: str,
93
+ user_prompt: str,
94
+ workspace: Workspace,
95
+ call_turn: Callable[[list[dict], list[dict], str], Turn],
96
+ check_cancelled: Callable[[], None] = lambda: None,
97
+ on_step: Callable[[dict], None] | None = None,
98
+ clock: Callable[[], float] = time.monotonic,
99
+ ) -> AgentLoopResult:
100
+ specs = tool_specs(agent.tools, workspace.services)
101
+ messages: list[dict] = [{"role": "user", "content": user_prompt}]
102
+ deadline = clock() + agent.timeout
103
+ res = AgentLoopResult(text="", ended="max_steps", workspace=str(workspace.root))
104
+ trace = [f"# Trace de l'agent `{agent.id}`\n",
105
+ f"Modèle : {agent.service}/{agent.model} — outils : {', '.join(agent.tools)} — "
106
+ f"max_steps={agent.max_steps}, timeout={agent.timeout:g} s\n",
107
+ f"Espace de travail : `{workspace.root}`\n"]
108
+
109
+ def account(turn: Turn) -> None:
110
+ res.input_tokens += turn.usage.get("input_tokens", 0) or 0
111
+ res.output_tokens += turn.usage.get("output_tokens", 0) or 0
112
+
113
+ reminders = 0
114
+ for step in range(1, agent.max_steps + 1):
115
+ check_cancelled()
116
+ if clock() >= deadline + workspace.services.paused: # l'attente de l'utilisateur n'use pas le délai
117
+ res.ended = "timeout"
118
+ break
119
+
120
+ turn = call_turn(messages, specs, "auto")
121
+ res.steps = step
122
+ account(turn)
123
+ trace.append(f"\n## Tour {step}\n")
124
+ if turn.text.strip():
125
+ trace.append(f"**Assistant** :\n\n{_clip(turn.text)}\n")
126
+
127
+ messages.append({"role": "assistant", "text": turn.text, "tool_calls": turn.tool_calls, "raw": turn.raw})
128
+ if not turn.tool_calls:
129
+ reminder = _exit_reminder(agent, workspace, workspace.services.submitted is not None)
130
+ if reminder and reminders < MAX_REMINDERS:
131
+ # L'agent conclut en texte alors qu'il doit remettre ses sorties avec submit_result, ou sans avoir
132
+ # écrit un fichier de sortie : sans ce rappel, le moteur échouerait plus loin avec un message
133
+ # trompeur (« aucun JSON trouvé », « fichier introuvable »).
134
+ reminders += 1
135
+ trace.append("\n*Conclusion prématurée : rappel envoyé à l'agent.*\n")
136
+ messages.append({"role": "user", "content": reminder})
137
+ continue
138
+ res.text, res.ended = turn.text, "answer"
139
+ trace.append("\n*Réponse finale.*\n")
140
+ break
141
+
142
+ for call in turn.tool_calls:
143
+ res.tool_calls += 1
144
+ if clock() >= deadline + workspace.services.paused:
145
+ content, is_error = "Non exécuté : délai global de l'agent dépassé.", True
146
+ else:
147
+ r = call_tool(workspace, call.name, call.args, agent.tools)
148
+ content, is_error = r.content, r.is_error
149
+ if is_error:
150
+ res.errors.append(f"{call.name} : {content.splitlines()[0] if content else ''}")
151
+ trace.append(
152
+ f"\n### Appel `{call.name}`{' — ERREUR' if is_error else ''}\n\n"
153
+ f"Arguments :\n~~~~json\n{_clip(_fmt_args(call.args))}\n~~~~\n\n"
154
+ f"Résultat :\n~~~~\n{_clip(content)}\n~~~~\n"
155
+ )
156
+ messages.append({"role": "tool", "tool_call_id": call.id, "name": call.name,
157
+ "content": content, "is_error": is_error})
158
+ if on_step:
159
+ on_step({"step": step, "tool": call.name, "error": is_error})
160
+ submitted = workspace.services.submitted
161
+ if submitted is not None and _missing_output_files(agent, workspace) and reminders < MAX_REMINDERS:
162
+ # Résultat remis mais un fichier de sortie manque : on rouvre la remise, l'agent doit d'abord l'écrire.
163
+ reminders += 1
164
+ workspace.services.submitted = None
165
+ trace.append("\n*Résultat remis sans le fichier de sortie : rappel envoyé à l'agent.*\n")
166
+ messages.append({"role": "user", "content": FILES_REMINDER.format(
167
+ fichiers=", ".join(_missing_output_files(agent, workspace)),
168
+ suite=" ; rappelle ensuite submit_result")})
169
+ continue
170
+ if submitted is not None: # submit_result : le travail est remis, pas besoin d'un tour de plus
171
+ res.text = next(iter(submitted.values())) if len(submitted) == 1 else json.dumps(submitted, ensure_ascii=False)
172
+ res.ended = "submitted"
173
+ trace.append("\n*Résultat remis par submit_result.*\n")
174
+ break
175
+ else:
176
+ res.ended = "max_steps"
177
+
178
+ if res.ended not in ("answer", "submitted"):
179
+ raison = (f"{agent.max_steps} tours" if res.ended == "max_steps"
180
+ else f"délai de {agent.timeout:g} s")
181
+ trace.append(f"\n## Limite atteinte ({raison}) : demande de réponse finale\n")
182
+ check_cancelled()
183
+ messages.append({"role": "user", "content": FINAL_REQUEST.format(raison=raison)})
184
+ turn = call_turn(messages, specs, "none") # outils décrits (l'historique en contient) mais interdits
185
+ account(turn)
186
+ res.text = turn.text
187
+ trace.append(f"{_clip(turn.text) or '(aucune réponse)'}\n")
188
+ if not turn.text.strip():
189
+ res.trace = "".join(trace)
190
+ raise AgentLimitError(
191
+ f"l'agent '{agent.id}' n'a pas produit de réponse finale ({raison} atteint)", res
192
+ )
193
+
194
+ trace.append(f"\n---\n{res.steps} tour(s), {res.tool_calls} appel(s) d'outil, "
195
+ f"{res.input_tokens} tokens en entrée, {res.output_tokens} en sortie.\n")
196
+ res.trace = "".join(trace)
197
+ return res
198
+
199
+
200
+ class AgentLimitError(RuntimeError):
201
+ """Limite atteinte sans réponse finale ; `result` garde la trace pour le diagnostic."""
202
+
203
+ def __init__(self, message: str, result: AgentLoopResult):
204
+ super().__init__(message)
205
+ self.result = result
@@ -0,0 +1,199 @@
1
+ """
2
+ Services mis à disposition des outils d'un agent, en plus de son espace de travail.
3
+
4
+ Un outil qui sort de l'espace de travail (dossier du projet, mémoire, réseau, utilisateur, autre appel au modèle)
5
+ passe par un service explicite, fourni par l'exécuteur : sans service, l'outil refuse de s'exécuter. Rien n'est
6
+ accessible par défaut.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import os
13
+ import re
14
+ import tempfile
15
+ import threading
16
+ import time
17
+ from collections.abc import Callable
18
+ from dataclasses import dataclass, field
19
+ from pathlib import Path
20
+
21
+ MAX_READ_CHARS = 20_000 # taille d'un texte renvoyé à l'agent en une fois (le reste via `offset`)
22
+ NOTE_KEY_RE = re.compile(r"^[A-Za-z0-9_.-]{1,64}$")
23
+ MAX_NOTE_CHARS = 20_000
24
+ MAX_NOTES = 200
25
+
26
+
27
+ class ToolError(Exception):
28
+ """Erreur d'outil dont le message est destiné au LLM."""
29
+
30
+
31
+ def slice_text(text: str, offset: int = 0, limit: int = MAX_READ_CHARS) -> str:
32
+ """Tranche de `text` à partir de `offset` (`limit` caractères au plus), avec l'indication pour lire la suite."""
33
+ if offset < 0:
34
+ raise ToolError("offset doit être positif")
35
+ chunk = text[offset:offset + limit]
36
+ end = offset + len(chunk)
37
+ if end < len(text):
38
+ chunk += f"\n[… tronqué : {len(text) - end} caractère(s) restant(s), relire avec offset={end}]"
39
+ return chunk if (chunk or text) else "(fichier vide)"
40
+
41
+
42
+ class NoteStore:
43
+ """Notes d'un agent (`memory_save` / `memory_recall`), persistées dans un fichier JSON si `path` est donné
44
+ (dossier de la mémoire persistante `--memory-dir`), sinon conservées pour la durée de l'exécution."""
45
+
46
+ def __init__(self, path: str | Path | None = None):
47
+ self.path = Path(path) if path else None
48
+ self._lock = threading.Lock()
49
+ self._data: dict[str, str] = {}
50
+ if self.path and self.path.is_file():
51
+ try:
52
+ data = json.loads(self.path.read_text(encoding="utf-8"))
53
+ if isinstance(data, dict):
54
+ self._data = {str(k): str(v) for k, v in data.items()}
55
+ except (OSError, ValueError):
56
+ pass
57
+
58
+ @property
59
+ def persistent(self) -> bool:
60
+ return self.path is not None
61
+
62
+ def keys(self) -> list[str]:
63
+ with self._lock:
64
+ return sorted(self._data)
65
+
66
+ def get(self, key: str) -> str | None:
67
+ with self._lock:
68
+ return self._data.get(key)
69
+
70
+ def set(self, key: str, text: str) -> None:
71
+ with self._lock:
72
+ if key not in self._data and len(self._data) >= MAX_NOTES:
73
+ raise ValueError(f"trop de notes ({MAX_NOTES} au plus)")
74
+ self._data[key] = text
75
+ self._flush()
76
+
77
+ def delete(self, key: str) -> bool:
78
+ with self._lock:
79
+ found = self._data.pop(key, None) is not None
80
+ if found:
81
+ self._flush()
82
+ return found
83
+
84
+ def _flush(self) -> None:
85
+ if not self.path:
86
+ return
87
+ self.path.parent.mkdir(parents=True, exist_ok=True)
88
+ fd, tmp = tempfile.mkstemp(dir=self.path.parent, prefix=".notes-", suffix=".tmp")
89
+ try:
90
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
91
+ json.dump(self._data, f, ensure_ascii=False, indent=1, sort_keys=True)
92
+ os.replace(tmp, self.path)
93
+ except BaseException:
94
+ try:
95
+ os.unlink(tmp)
96
+ except OSError:
97
+ pass
98
+ raise
99
+
100
+
101
+ @dataclass
102
+ class ToolServices:
103
+ """Ce que l'exécuteur accorde à un agent au-delà de son espace de travail (tout est facultatif)."""
104
+
105
+ project_dir: Path | None = None # lecture seule du projet (list_project_dir, read_project_file)
106
+ protected: frozenset = frozenset() # fichiers du projet interdits (workflow YAML : clés d'API)
107
+ variables: dict[str, str] = field(default_factory=dict) # variables du workflow, lecture seule
108
+ notes: NoteStore | None = None # mémoire de l'agent
109
+ network: "NetworkPolicy | None" = None # réseau : None = interdit
110
+ ask_user: Callable[[str], str] | None = None # interroger l'utilisateur
111
+ ask_model: Callable[[str], str] | None = None # déléguer une question à un modèle (sans outils)
112
+ knowledge: tuple[str, ...] = () # bases de connaissances interrogeables (search_knowledge)
113
+ search_knowledge: Callable[[str, str, int | None], str] | None = None # (base, requête, k) -> passages
114
+ outputs: list[str] = field(default_factory=list) # sorties attendues de l'agent (submit_result)
115
+ submitted: dict | None = None # résultat remis par submit_result
116
+ paused: float = 0.0 # secondes passées à attendre l'utilisateur (hors délai)
117
+ count_search: Callable[[], None] | None = None # décompte d'une recherche web (quota, mode serveur)
118
+ questions_left: int = 5
119
+ delegations_left: int = 5
120
+
121
+
122
+ NETWORK_TOOLS = frozenset({"fetch_url", "web_search"}) # outils qui accèdent au réseau (hors sandbox)
123
+
124
+
125
+ class NetworkPermissionError(RuntimeError):
126
+ """Le workflow accède au réseau mais l'utilisateur ne l'a pas autorisé explicitement."""
127
+
128
+
129
+ def agents_using_network(agents) -> list[str]:
130
+ """Identifiants des agents (type: agent) dont les outils accèdent au réseau."""
131
+ return [a.id for a in agents if getattr(a, "type", "llm") == "agent" and NETWORK_TOOLS & set(a.tools)]
132
+
133
+
134
+ def require_network_permission(agents, allow_network: bool = False) -> bool:
135
+ """True si un agent accède au réseau et que c'est autorisé ; False s'il n'y en a aucun ; sinon refus."""
136
+ users = agents_using_network(agents)
137
+ if not users:
138
+ return False
139
+ if not allow_network:
140
+ raise NetworkPermissionError(
141
+ f"Agent(s) {users} : les outils fetch_url / web_search accèdent au réseau ; relancer avec "
142
+ f"--allow-network pour l'autoriser.")
143
+ return True
144
+
145
+
146
+ class QuestionBroker:
147
+ """Passerelle entre un agent qui pose une question (`ask_user`) et l'interface qui la présente à l'utilisateur.
148
+
149
+ `ask` bloque le thread de l'agent jusqu'à `answer` (appelé par l'interface), l'annulation de l'exécution ou
150
+ l'expiration du délai. Une seule question à la fois : les agents parallèles font la queue."""
151
+
152
+ def __init__(self, timeout: float = 900.0, poll: float = 0.2):
153
+ self.timeout = timeout
154
+ self.poll = poll
155
+ self.cancelled: Callable[[], bool] = lambda: False
156
+ self.pending: tuple[str, str] | None = None # (agent, question) en attente de réponse
157
+ self._answer: str | None = None
158
+ self._turn = threading.Lock()
159
+ self._cond = threading.Condition()
160
+
161
+ def ask(self, agent_id: str, question: str) -> str:
162
+ with self._turn:
163
+ with self._cond:
164
+ self.pending, self._answer = (agent_id, question), None
165
+ deadline = time.monotonic() + self.timeout
166
+ try:
167
+ with self._cond:
168
+ while self._answer is None:
169
+ if self.cancelled():
170
+ raise RuntimeError("question annulée : l'exécution a été arrêtée")
171
+ if time.monotonic() >= deadline:
172
+ raise TimeoutError("l'utilisateur n'a pas répondu dans le délai")
173
+ self._cond.wait(self.poll)
174
+ return self._answer
175
+ finally:
176
+ with self._cond:
177
+ self.pending, self._answer = None, None
178
+
179
+ def answer(self, text: str) -> None:
180
+ with self._cond:
181
+ if self.pending is not None:
182
+ self._answer = text if text is not None else ""
183
+ self._cond.notify_all()
184
+
185
+
186
+ @dataclass
187
+ class NetworkPolicy:
188
+ """Réseau accordé à un agent : domaines autorisés pour `fetch_url` (« example.org » couvre aussi ses
189
+ sous-domaines)."""
190
+
191
+ allowed_domains: tuple[str, ...] = ()
192
+
193
+ def allows(self, host: str) -> bool:
194
+ host = (host or "").lower().rstrip(".")
195
+ for d in self.allowed_domains:
196
+ d = d.lower().strip().lstrip("*.").rstrip(".")
197
+ if d and (host == d or host.endswith("." + d)):
198
+ return True
199
+ return False