Baida07 commited on
Commit
9c8cd5d
·
verified ·
1 Parent(s): dfd7335

sync: 186 file da Baida98/AI@d7fa54a1 (2026-08-25 19:09 UTC) [deploy-all]

Browse files
api/agent.py CHANGED
@@ -825,6 +825,12 @@ async def stream_agent_task(task_id: str, request: Request, resume: int = 0, rol
825
  raise HTTPException(404, detail=f'Task {task_id} non trovato')
826
 
827
  task = _agent_tasks[task_id]
 
 
 
 
 
 
828
  _last_event_id = request.headers.get("Last-Event-ID") or request.headers.get("last-event-id")
829
  _resume_from = int(_last_event_id) if (_last_event_id and _last_event_id.isdigit()) else resume
830
 
 
825
  raise HTTPException(404, detail=f'Task {task_id} non trovato')
826
 
827
  task = _agent_tasks[task_id]
828
+ # I task restaurati da persistenza potrebbero non contenere metadata runtime.
829
+ # Ricostruire la policy dal goal mantiene il resume fail-closed.
830
+ if "forbid_tools" not in task or "literal_response" not in task:
831
+ _restored_policy = build_task_tool_policy(task.get("goal", ""))
832
+ task["forbid_tools"] = _restored_policy.forbid_tools
833
+ task["literal_response"] = _restored_policy.literal_response
834
  _last_event_id = request.headers.get("Last-Event-ID") or request.headers.get("last-event-id")
835
  _resume_from = int(_last_event_id) if (_last_event_id and _last_event_id.isdigit()) else resume
836
 
api/scheduler.py CHANGED
@@ -28,6 +28,7 @@ import datetime
28
  import json
29
  from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
30
  from .state import safe_json_dumps
 
31
  import os
32
  import time
33
  import uuid
@@ -246,6 +247,10 @@ async def _run_goal(goal: str, conversation_id: Optional[str] = None, risk: str
246
  Esegue il goal tramite UnifiedAgentLoop (stesso path di api/agent.py).
247
  Timeout: derivato da Policy Engine per risk level (safe=30s, medium=90s, risky=180s, dangerous=300s).
248
  """
 
 
 
 
249
  try:
250
  from agents.unified_loop import UnifiedAgentLoop
251
  from api.state import (
@@ -274,7 +279,8 @@ async def _run_goal(goal: str, conversation_id: Optional[str] = None, risk: str
274
 
275
  _timeout_s = float(_POLICY_TIMEOUT_S.get(risk, 120))
276
  result = await asyncio.wait_for(
277
- loop.run(goal=goal, context="", max_steps=8),
 
278
  timeout=_timeout_s,
279
  )
280
  if isinstance(result, dict):
 
28
  import json
29
  from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
30
  from .state import safe_json_dumps
31
+ from .task_tool_policy import build_task_tool_policy
32
  import os
33
  import time
34
  import uuid
 
247
  Esegue il goal tramite UnifiedAgentLoop (stesso path di api/agent.py).
248
  Timeout: derivato da Policy Engine per risk level (safe=30s, medium=90s, risky=180s, dangerous=300s).
249
  """
250
+ _task_policy = build_task_tool_policy(goal)
251
+ if _task_policy.literal_response:
252
+ return _task_policy.literal_response
253
+
254
  try:
255
  from agents.unified_loop import UnifiedAgentLoop
256
  from api.state import (
 
279
 
280
  _timeout_s = float(_POLICY_TIMEOUT_S.get(risk, 120))
281
  result = await asyncio.wait_for(
282
+ loop.run(goal=goal, context="", max_steps=8,
283
+ allow_tools=not _task_policy.forbid_tools),
284
  timeout=_timeout_s,
285
  )
286
  if isinstance(result, dict):
api/webhook.py CHANGED
@@ -5,6 +5,7 @@ from fastapi import APIRouter, Depends, HTTPException, Request
5
  from pydantic import BaseModel, field_validator
6
  from .state import _get_mem_manager, _get_executor, _get_planner
7
  from .auth_guard import require_role, AuthRole # GAP-WEBHOOK-ADMIN-FIX
 
8
 
9
  import logging
10
  _logger = logging.getLogger("api.webhook")
@@ -211,6 +212,13 @@ async def inbound_webhook(webhook_token: str, body: WebhookPayload):
211
  if webhook_token != _expected:
212
  raise HTTPException(status_code=401, detail='Unauthorized: token non valido')
213
 
 
 
 
 
 
 
 
214
  try:
215
  from agents.unified_loop import UnifiedAgentLoop
216
  from models.ai_client import AIClient
@@ -233,7 +241,8 @@ async def inbound_webhook(webhook_token: str, body: WebhookPayload):
233
  try:
234
  result = await asyncio.wait_for(
235
  loop.run(goal=body.goal, context=context_str,
236
- max_steps=body.max_steps, on_step=lambda _s: None),
 
237
  timeout=float(os.getenv('AGENT_STREAM_TIMEOUT', '120')),
238
  )
239
  except asyncio.TimeoutError:
@@ -274,6 +283,13 @@ async def public_chat(payload: PublicChatPayload, request: Request):
274
  if not token or token != _expected:
275
  raise HTTPException(status_code=401, detail='Unauthorized: token non valido.')
276
 
 
 
 
 
 
 
 
277
  try:
278
  from agents.unified_loop import UnifiedAgentLoop
279
  from models.ai_client import AIClient
@@ -295,7 +311,8 @@ async def public_chat(payload: PublicChatPayload, request: Request):
295
  try:
296
  result = await asyncio.wait_for(
297
  loop.run(goal=payload.message, context='',
298
- max_steps=payload.max_steps, on_step=lambda _s: None),
 
299
  timeout=float(os.getenv('AGENT_STREAM_TIMEOUT', '120')),
300
  )
301
  except asyncio.TimeoutError:
 
5
  from pydantic import BaseModel, field_validator
6
  from .state import _get_mem_manager, _get_executor, _get_planner
7
  from .auth_guard import require_role, AuthRole # GAP-WEBHOOK-ADMIN-FIX
8
+ from .task_tool_policy import build_task_tool_policy
9
 
10
  import logging
11
  _logger = logging.getLogger("api.webhook")
 
212
  if webhook_token != _expected:
213
  raise HTTPException(status_code=401, detail='Unauthorized: token non valido')
214
 
215
+ _task_policy = build_task_tool_policy(body.goal)
216
+ if _task_policy.literal_response:
217
+ return {
218
+ 'ok': True, 'output': _task_policy.literal_response, 'engine': 'policy',
219
+ 'goal': body.goal, 'steps': 0,
220
+ }
221
+
222
  try:
223
  from agents.unified_loop import UnifiedAgentLoop
224
  from models.ai_client import AIClient
 
241
  try:
242
  result = await asyncio.wait_for(
243
  loop.run(goal=body.goal, context=context_str,
244
+ max_steps=body.max_steps, on_step=lambda _s: None,
245
+ allow_tools=not _task_policy.forbid_tools),
246
  timeout=float(os.getenv('AGENT_STREAM_TIMEOUT', '120')),
247
  )
248
  except asyncio.TimeoutError:
 
283
  if not token or token != _expected:
284
  raise HTTPException(status_code=401, detail='Unauthorized: token non valido.')
285
 
286
+ _task_policy = build_task_tool_policy(payload.message)
287
+ if _task_policy.literal_response:
288
+ return {
289
+ 'ok': True, 'response': _task_policy.literal_response, 'engine': 'policy',
290
+ 'conversation_id': payload.conversation_id, 'steps': 0,
291
+ }
292
+
293
  try:
294
  from agents.unified_loop import UnifiedAgentLoop
295
  from models.ai_client import AIClient
 
311
  try:
312
  result = await asyncio.wait_for(
313
  loop.run(goal=payload.message, context='',
314
+ max_steps=payload.max_steps, on_step=lambda _s: None,
315
+ allow_tools=not _task_policy.forbid_tools),
316
  timeout=float(os.getenv('AGENT_STREAM_TIMEOUT', '120')),
317
  )
318
  except asyncio.TimeoutError:
tests/test_entrypoint_policy_contracts.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Contratti di integrazione per policy tool nei diversi entry point backend.
2
+
3
+ Gli endpoint sono invocati direttamente con finti loop/provider. Ogni test misura la
4
+ policy effettivamente passata al loop o dimostra che un contratto letterale termina
5
+ prima di provider, notifiche, planner e tool.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import asyncio
10
+ import os
11
+ import sys
12
+ import types
13
+ import unittest
14
+ from unittest.mock import patch
15
+
16
+ _BACKEND = os.path.join(os.path.dirname(__file__), "..")
17
+ if _BACKEND not in sys.path:
18
+ sys.path.insert(0, _BACKEND)
19
+
20
+
21
+ NO_TOOL_PROMPT = "Spiega il concetto senza usare strumenti, tool, rete o file."
22
+ LITERAL_PROMPT = (
23
+ "Rispondi ESCLUSIVAMENTE con TEST_E2E_OK. Non usare strumenti, tool, "
24
+ "comandi shell, file, rete, servizi esterni, azioni o card."
25
+ )
26
+
27
+
28
+ class _Request:
29
+ def __init__(self, headers: dict[str, str] | None = None) -> None:
30
+ self.headers = headers or {}
31
+
32
+
33
+ class _CallbackRequest(_Request):
34
+ async def json(self) -> dict[str, object]:
35
+ raise AssertionError("bad secret must not parse payload")
36
+
37
+
38
+ class _RecordingLoop:
39
+ calls: list[dict] = []
40
+
41
+ def __init__(self, **_kwargs: object) -> None:
42
+ pass
43
+
44
+ async def run(self, **kwargs: object) -> dict[str, object]:
45
+ self.__class__.calls.append(dict(kwargs))
46
+ return {"success": True, "output": "safe textual result", "steps": []}
47
+
48
+
49
+ class _FakeAIClient:
50
+ pass
51
+
52
+
53
+ def _fake_loop_modules() -> dict[str, types.ModuleType]:
54
+ agents = types.ModuleType("agents")
55
+ agents.__path__ = [] # type: ignore[attr-defined]
56
+ unified = types.ModuleType("agents.unified_loop")
57
+ unified.UnifiedAgentLoop = _RecordingLoop # type: ignore[attr-defined]
58
+ models = types.ModuleType("models")
59
+ models.__path__ = [] # type: ignore[attr-defined]
60
+ ai_client = types.ModuleType("models.ai_client")
61
+ ai_client.AIClient = _FakeAIClient # type: ignore[attr-defined]
62
+ return {
63
+ "agents": agents,
64
+ "agents.unified_loop": unified,
65
+ "models": models,
66
+ "models.ai_client": ai_client,
67
+ }
68
+
69
+
70
+ async def _noop(*_args: object, **_kwargs: object) -> None:
71
+ return None
72
+
73
+
74
+ class EntryPointPolicyContracts(unittest.IsolatedAsyncioTestCase):
75
+ def setUp(self) -> None:
76
+ _RecordingLoop.calls.clear()
77
+
78
+ async def test_telegram_callback_fails_closed_before_payload_or_outbound_work(self) -> None:
79
+ from api import webhook
80
+
81
+ with patch.dict(os.environ, {"TELEGRAM_WEBHOOK_SECRET": ""}, clear=False):
82
+ result = await webhook.telegram_callback(_CallbackRequest())
83
+
84
+ self.assertEqual(result, {"ok": True, "ignored": "bad_secret"})
85
+
86
+ async def test_webhook_literal_contract_returns_before_loop_or_notification(self) -> None:
87
+ from api import webhook
88
+
89
+ payload = webhook.WebhookPayload(goal=LITERAL_PROMPT)
90
+ with patch.dict(os.environ, {"WEBHOOK_TOKEN": "test-webhook-token"}, clear=False), \
91
+ patch.object(webhook, "_tg_start", side_effect=AssertionError("notification forbidden")), \
92
+ patch.object(webhook, "_get_mem_manager", side_effect=AssertionError("provider forbidden")):
93
+ result = await webhook.inbound_webhook("test-webhook-token", payload)
94
+
95
+ self.assertEqual(result["output"], "TEST_E2E_OK")
96
+ self.assertEqual(result["steps"], 0)
97
+ self.assertEqual(_RecordingLoop.calls, [])
98
+
99
+ async def test_public_chat_literal_contract_returns_before_loop_or_notification(self) -> None:
100
+ from api import webhook
101
+
102
+ payload = webhook.PublicChatPayload(message=LITERAL_PROMPT, conversation_id="conv-safe")
103
+ with patch.dict(os.environ, {"PUBLIC_API_TOKEN": "public-test-token"}, clear=False), \
104
+ patch.object(webhook, "_tg_start", side_effect=AssertionError("notification forbidden")), \
105
+ patch.object(webhook, "_get_mem_manager", side_effect=AssertionError("provider forbidden")):
106
+ result = await webhook.public_chat(
107
+ payload,
108
+ _Request({"authorization": "Bearer public-test-token"}),
109
+ )
110
+
111
+ self.assertEqual(result["response"], "TEST_E2E_OK")
112
+ self.assertEqual(result["conversation_id"], "conv-safe")
113
+ self.assertEqual(_RecordingLoop.calls, [])
114
+
115
+ async def test_webhook_and_public_chat_propagate_no_tool_policy_to_loop(self) -> None:
116
+ from api import webhook
117
+
118
+ fake_modules = _fake_loop_modules()
119
+ with patch.dict(sys.modules, fake_modules), \
120
+ patch.dict(os.environ, {"WEBHOOK_TOKEN": "test-webhook-token", "PUBLIC_API_TOKEN": "public-test-token"}, clear=False), \
121
+ patch.object(webhook, "_get_mem_manager", return_value=object()), \
122
+ patch.object(webhook, "_get_executor", return_value=object()), \
123
+ patch.object(webhook, "_get_planner", return_value=object()), \
124
+ patch.object(webhook, "_tg_start", _noop), \
125
+ patch.object(webhook, "_tg_done", _noop):
126
+ webhook_result = await webhook.inbound_webhook(
127
+ "test-webhook-token", webhook.WebhookPayload(goal=NO_TOOL_PROMPT)
128
+ )
129
+ public_result = await webhook.public_chat(
130
+ webhook.PublicChatPayload(message=NO_TOOL_PROMPT),
131
+ _Request({"authorization": "Bearer public-test-token"}),
132
+ )
133
+
134
+ self.assertTrue(webhook_result["ok"])
135
+ self.assertTrue(public_result["ok"])
136
+ self.assertEqual(len(_RecordingLoop.calls), 2)
137
+ self.assertTrue(all(call["allow_tools"] is False for call in _RecordingLoop.calls))
138
+
139
+ async def test_scheduler_literal_contract_skips_provider_initialization(self) -> None:
140
+ from api import scheduler
141
+
142
+ with patch.object(scheduler, "_get_ai_client", side_effect=AssertionError("provider forbidden"), create=True):
143
+ result = await scheduler._run_goal(LITERAL_PROMPT)
144
+
145
+ self.assertEqual(result, "TEST_E2E_OK")
146
+ self.assertEqual(_RecordingLoop.calls, [])
147
+
148
+ async def test_scheduler_propagates_no_tool_policy_to_loop(self) -> None:
149
+ from api import scheduler
150
+ import api.state as state
151
+
152
+ fake_modules = _fake_loop_modules()
153
+ async def fake_memory() -> object:
154
+ return object()
155
+
156
+ with patch.dict(sys.modules, fake_modules), \
157
+ patch.object(state, "_get_ai_client", return_value=object()), \
158
+ patch.object(state, "_get_mem_manager_async", fake_memory), \
159
+ patch.object(state, "_get_executor", return_value=object()), \
160
+ patch.object(state, "_get_planner", return_value=object()):
161
+ result = await scheduler._run_goal(NO_TOOL_PROMPT, risk="safe")
162
+
163
+ self.assertEqual(result, "safe textual result")
164
+ self.assertEqual(len(_RecordingLoop.calls), 1)
165
+ self.assertIs(_RecordingLoop.calls[0]["allow_tools"], False)
166
+
167
+ async def test_restored_sse_task_rebuilds_literal_policy_before_task_start(self) -> None:
168
+ from api import agent
169
+
170
+ task_id = "resume-literal-policy"
171
+ original = dict(agent._agent_tasks)
172
+ agent._agent_tasks.clear()
173
+ agent._agent_tasks[task_id] = {"id": task_id, "goal": LITERAL_PROMPT, "status": "QUEUED"}
174
+ try:
175
+ with patch.object(agent, "sb_update_status", _noop):
176
+ response = await agent.stream_agent_task(task_id, _Request())
177
+ payload = b"".join([
178
+ chunk.encode() if isinstance(chunk, str) else chunk
179
+ async for chunk in response.body_iterator
180
+ ]).decode()
181
+ finally:
182
+ agent._agent_tasks.clear()
183
+ agent._agent_tasks.update(original)
184
+
185
+ self.assertIn('"event": "task_done"', payload)
186
+ self.assertIn("TEST_E2E_OK", payload)
187
+ self.assertNotIn("task_start", payload)
188
+ self.assertTrue(agent._agent_tasks == original or task_id not in agent._agent_tasks)
189
+
190
+
191
+ if __name__ == "__main__":
192
+ unittest.main()