argos-cli 0.3.1__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 (96) hide show
  1. argos/__init__.py +5 -0
  2. argos/__main__.py +4 -0
  3. argos/adapters/__init__.py +9 -0
  4. argos/adapters/_libreoffice_worker.py +111 -0
  5. argos/adapters/ai.py +1506 -0
  6. argos/adapters/ai_remote.py +654 -0
  7. argos/adapters/attachment_conversion.py +132 -0
  8. argos/adapters/capabilities.py +31 -0
  9. argos/adapters/chart_render.py +72 -0
  10. argos/adapters/docx_pdf.py +2953 -0
  11. argos/adapters/limesurvey.py +1079 -0
  12. argos/adapters/model_call.py +274 -0
  13. argos/adapters/report_publication.py +1530 -0
  14. argos/adapters/url_fetch.py +146 -0
  15. argos/adapters/xlsx.py +454 -0
  16. argos/analytics.py +731 -0
  17. argos/assets.py +257 -0
  18. argos/audit_result.py +369 -0
  19. argos/booleans.py +105 -0
  20. argos/catalog.py +1205 -0
  21. argos/cli.py +606 -0
  22. argos/contracts.py +532 -0
  23. argos/core.py +325 -0
  24. argos/default_skills/README.md +23 -0
  25. argos/default_skills/criar-matriz-planejamento/SKILL.md +200 -0
  26. argos/default_skills/elaborar-survey-limesurvey/SKILL.md +106 -0
  27. argos/default_skills/operar-argos/SKILL.md +74 -0
  28. argos/default_skills/verificar-diretrizes-fiscalizacao/SKILL.md +129 -0
  29. argos/default_skills/verificar-diretrizes-fiscalizacao/assets/relatorio-avaliacao.md +54 -0
  30. argos/default_skills/verificar-diretrizes-fiscalizacao/references/contrato-saidas.md +36 -0
  31. argos/default_skills/verificar-diretrizes-fiscalizacao/references/papeis-das-pastas.md +37 -0
  32. argos/default_skills/verificar-diretrizes-fiscalizacao/references/roteiro-verificacoes.md +27 -0
  33. argos/default_skills/verificar-diretrizes-fiscalizacao/scripts/avaliacao.py +253 -0
  34. argos/engines/__init__.py +3 -0
  35. argos/engines/adjustments.py +571 -0
  36. argos/engines/analytics.py +195 -0
  37. argos/engines/audit.py +2730 -0
  38. argos/engines/evaluation.py +6088 -0
  39. argos/engines/index.py +1683 -0
  40. argos/engines/matrix.py +5736 -0
  41. argos/engines/matrix_html.py +698 -0
  42. argos/engines/model_request.py +201 -0
  43. argos/engines/report_document.py +137 -0
  44. argos/engines/reports.py +1200 -0
  45. argos/engines/survey.py +4445 -0
  46. argos/envfile.py +53 -0
  47. argos/errors.py +29 -0
  48. argos/evidence_staging.py +293 -0
  49. argos/executions.py +565 -0
  50. argos/findings_matrix.py +2549 -0
  51. argos/fingerprints.py +487 -0
  52. argos/index_dsl.py +2100 -0
  53. argos/matrix_markdown.py +475 -0
  54. argos/matrix_widths.py +280 -0
  55. argos/pipeline.py +1745 -0
  56. argos/products.py +220 -0
  57. argos/progress.py +221 -0
  58. argos/project.py +608 -0
  59. argos/report_config.py +158 -0
  60. argos/resources/ESPECIFICACAO_MARKDOWN_MATRIZ_ACHADOS.md +539 -0
  61. argos/resources/ESPECIFICACAO_MARKDOWN_MATRIZ_PLANEJAMENTO.md +1000 -0
  62. argos/resources/ESPECIFICACAO_UNIFICADA_MATRIZES_V1_3.md +1142 -0
  63. argos/resources/anexo-evidencias-base.docx +0 -0
  64. argos/resources/argos-index-dsl-v1.schema.json +539 -0
  65. argos/resources/argos-report-config-v1.schema.json +113 -0
  66. argos/resources/diretrizes-projeto.md +476 -0
  67. argos/resources/env.example +37 -0
  68. argos/resources/exemplos/matriz_achados_boilerplate.md +61 -0
  69. argos/resources/exemplos/matriz_achados_draft.md +106 -0
  70. argos/resources/exemplos/matriz_achados_larguras_v1_3.md +114 -0
  71. argos/resources/exemplos/matriz_achados_v1_3.md +107 -0
  72. argos/resources/exemplos/matriz_planejamento_boilerplate.md +64 -0
  73. argos/resources/exemplos/matriz_planejamento_larguras_v1_3.md +115 -0
  74. argos/resources/exemplos/matriz_planejamento_v1_3.md +108 -0
  75. argos/resources/template-base-estilos-sigiloso.docx +0 -0
  76. argos/resources/template-base-estilos.docx +0 -0
  77. argos/resources/template-matriz-planejamento.docx +0 -0
  78. argos/resources/template-relatorio-consolidado-comum.docx +0 -0
  79. argos/resources/template-relatorio-consolidado-institucional.docx +0 -0
  80. argos/response_profiles.py +856 -0
  81. argos/scheduler.py +142 -0
  82. argos/status.py +367 -0
  83. argos/store.py +1228 -0
  84. argos/survey_collection.py +832 -0
  85. argos/telemetry.py +84 -0
  86. argos/tui.py +1262 -0
  87. argos/tui.tcss +827 -0
  88. argos/tui_models.py +466 -0
  89. argos/tui_path.py +155 -0
  90. argos/tui_widgets.py +482 -0
  91. argos/version.py +3 -0
  92. argos_cli-0.3.1.dist-info/METADATA +570 -0
  93. argos_cli-0.3.1.dist-info/RECORD +96 -0
  94. argos_cli-0.3.1.dist-info/WHEEL +5 -0
  95. argos_cli-0.3.1.dist-info/entry_points.txt +2 -0
  96. argos_cli-0.3.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,654 @@
1
+ """Adapters HTTP de IA: OpenRouter e OpenCode Go (Chat Completions), OpenAI via proxy (Responses)
2
+ e OpenCode Go pelo protocolo Messages da Anthropic.
3
+
4
+ Cada adapter só monta o corpo da requisição e lê a resposta; troca de chave, nova
5
+ tentativa, timeout e erros sanitizados vêm de ``model_call``. Credenciais vêm só do
6
+ ambiente (várias chaves separadas por vírgula) e nunca aparecem em erros ou resultados.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import base64
12
+ import ipaddress
13
+ import json
14
+ import os
15
+ import re
16
+ import threading
17
+ import urllib.error
18
+ import urllib.parse
19
+ import urllib.request
20
+ import uuid
21
+ from typing import Any, Mapping
22
+
23
+ from ..booleans import parse_bool
24
+ from ..core import InputValidationError
25
+ from ..version import __version__
26
+ from .ai import (
27
+ AIRequest,
28
+ AIResponse,
29
+ _credential_source,
30
+ _decode_provider_result,
31
+ _secret_values,
32
+ )
33
+ from .capabilities import ModelCapabilities
34
+ from .model_call import AIServiceError, KeyRing, ModelCallPolicy, call_with_keys, raw_attempts
35
+
36
+ DEFAULT_OPENAI_PROXY_URL = "http://127.0.0.1:8787/v1"
37
+ DEFAULT_OPENCODEGO_URL = "https://opencode.ai/zen/go/v1/chat/completions"
38
+ DEFAULT_OPENCODEGO_ANT_URL = "https://opencode.ai/zen/go/v1/messages"
39
+ ANTHROPIC_VERSION = "2023-06-01"
40
+ DEFAULT_ANTHROPIC_MAX_TOKENS = 32_000
41
+ ANTHROPIC_REASONING_LEVELS = ("low", "medium", "high", "xhigh", "max")
42
+ OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions"
43
+ OPENROUTER_MODELS_URL = "https://openrouter.ai/api/v1/models"
44
+ # Níveis de `reasoning.effort` do OpenRouter; modelos individuais podem aceitar menos.
45
+ OPENROUTER_REASONING_LEVELS = ("none", "minimal", "low", "medium", "high", "xhigh")
46
+ LEVELS_TIMEOUT_SECONDS = 10
47
+ # Palavras-chave de JSON schema que o modo estrito dos providers não aceita; a validação do perfil as impõe.
48
+ _UNSUPPORTED_SCHEMA_KEYWORDS = frozenset({"minLength", "maxLength", "pattern", "format"})
49
+ _NATIVE_PDF_MODEL = re.compile(r"(^|/|:)(o[134])(?:-|$)")
50
+ _PDF_NOTE = (
51
+ "Os arquivos PDF anexados nesta mesma mensagem são parte integrante da evidência. "
52
+ "Analise o conteúdo textual e visual deles."
53
+ )
54
+
55
+
56
+ def openrouter_supports_native_pdf(model: str) -> bool:
57
+ """Modelos do OpenRouter que leem PDF nativamente (Gemini, GPT/ChatGPT e série o)."""
58
+ name = str(model).strip().casefold()
59
+ return (
60
+ name.startswith(("google/", "openai/", "gpt-"))
61
+ or "gemini" in name
62
+ or "chatgpt" in name
63
+ or "/gpt-" in name
64
+ or _NATIVE_PDF_MODEL.search(name) is not None
65
+ )
66
+
67
+
68
+ def strict_json_schema(schema: Mapping[str, Any]) -> dict[str, Any]:
69
+ """Cópia do schema sem as palavras-chave não aceitas pelo modo estrito."""
70
+
71
+ def clean(value: Any) -> Any:
72
+ if isinstance(value, Mapping):
73
+ return {
74
+ key: clean(item)
75
+ for key, item in value.items()
76
+ if key not in _UNSUPPORTED_SCHEMA_KEYWORDS or not isinstance(item, (str, int))
77
+ }
78
+ if isinstance(value, list):
79
+ return [clean(item) for item in value]
80
+ return value
81
+
82
+ return clean(dict(schema))
83
+
84
+
85
+ def _data_url(mime_type: str, raw: bytes) -> str:
86
+ return f"data:{mime_type};base64,{base64.b64encode(raw).decode('ascii')}"
87
+
88
+
89
+ _IMAGE_SIGNATURES = (
90
+ (b"\x89PNG\r\n\x1a\n", "image/png"),
91
+ (b"\xff\xd8\xff", "image/jpeg"),
92
+ (b"GIF87a", "image/gif"),
93
+ (b"GIF89a", "image/gif"),
94
+ )
95
+
96
+
97
+ def _image_media_type(raw: bytes, declared: str) -> str:
98
+ """Tipo da imagem pelos bytes; a Anthropic recusa extensão que não bate com o conteúdo."""
99
+ for signature, media_type in _IMAGE_SIGNATURES:
100
+ if raw.startswith(signature):
101
+ return media_type
102
+ if raw[:4] == b"RIFF" and raw[8:12] == b"WEBP":
103
+ return "image/webp"
104
+ return declared
105
+
106
+
107
+ def _raw(content: bytes | str) -> bytes:
108
+ return content.encode("utf-8") if isinstance(content, str) else content
109
+
110
+
111
+ def _filename(logical_path: str) -> str:
112
+ return logical_path.rsplit("/", 1)[-1] or "evidencia.pdf"
113
+
114
+
115
+ def _http_url(value: str, label: str) -> str:
116
+ parsed = urllib.parse.urlparse(value)
117
+ if parsed.scheme.casefold() not in {"http", "https"} or not parsed.netloc:
118
+ raise InputValidationError(f"{label} deve usar uma URL http(s) válida")
119
+ return value
120
+
121
+
122
+ class _RemoteAdapter:
123
+ """Envio HTTP de um corpo JSON; a política de chamada é a de ``model_call``."""
124
+
125
+ provider = ""
126
+ adapter_name = ""
127
+ key_names: tuple[str, ...] = ()
128
+
129
+ def __init__(self, *, api_key: str | None = None, policy: ModelCallPolicy | None = None) -> None:
130
+ self._keys = _secret_values(api_key, *self.key_names)
131
+ self._ring = KeyRing(self._keys)
132
+ self.credential_source = _credential_source(api_key, *self.key_names)
133
+ self._policy = policy
134
+
135
+ @property
136
+ def policy(self) -> ModelCallPolicy:
137
+ """Política de chamada; o ambiente só é lido (e validado) no primeiro uso."""
138
+ if self._policy is None:
139
+ self._policy = ModelCallPolicy.from_env()
140
+ return self._policy
141
+
142
+ # -- a implementar em cada provider
143
+ def _url(self) -> str:
144
+ raise NotImplementedError
145
+
146
+ def _body(self, request: AIRequest) -> dict[str, Any]:
147
+ raise NotImplementedError
148
+
149
+ def _read(self, response: Any) -> tuple[str, Mapping[str, Any]]:
150
+ """Texto da resposta do modelo e metadados técnicos."""
151
+ raise NotImplementedError
152
+
153
+ def _requires_key(self) -> bool:
154
+ return True
155
+
156
+ def _extra_headers(self) -> dict[str, str]:
157
+ return {}
158
+
159
+ # -- comum
160
+ def _headers(self, key: str) -> dict[str, str]:
161
+ headers = {"Content-Type": "application/json", "User-Agent": f"argos-cli/{__version__}", **self._extra_headers()}
162
+ if key:
163
+ headers["Authorization"] = f"Bearer {key}"
164
+ return headers
165
+
166
+ def generate(self, request: AIRequest) -> AIResponse:
167
+ if not self._keys and self._requires_key():
168
+ raise InputValidationError(
169
+ f"{self.key_names[0]} não configurada; defina a credencial fora do repositório"
170
+ )
171
+ body = json.dumps(self._body(request), ensure_ascii=False).encode("utf-8")
172
+
173
+ def send(key: str) -> tuple[str, Mapping[str, Any]]:
174
+ http_request = urllib.request.Request(self._url(), data=body, headers=self._headers(key), method="POST")
175
+ # A URL é fixa (OpenRouter) ou validada como http(s) no construtor; a chave vai só no cabeçalho.
176
+ with urllib.request.urlopen(http_request, timeout=self.policy.timeout) as response: # nosec B310
177
+ return self._read(response)
178
+
179
+ (text, technical), attempts = call_with_keys(
180
+ send,
181
+ self._ring,
182
+ provider=self.provider,
183
+ policy=self.policy,
184
+ secrets=self._keys,
185
+ on_event=request.on_event,
186
+ )
187
+ result, repaired = _decode_provider_result(text)
188
+ return AIResponse(
189
+ result=result,
190
+ provider=self.provider,
191
+ model=request.model,
192
+ raw={"adapter": self.adapter_name, "json_repaired": repaired, **dict(technical), **raw_attempts(attempts)},
193
+ )
194
+
195
+
196
+ class ChatCompletionsAdapter(_RemoteAdapter):
197
+ """Família Chat Completions: texto, imagens e PDF inline como partes da mensagem.
198
+
199
+ As subclasses só dizem onde está o endpoint e como o nível de raciocínio (e
200
+ qualquer campo extra) entra no corpo.
201
+ """
202
+
203
+ adapter_name = "chat-completions"
204
+
205
+ def _tune(self, body: dict[str, Any], request: AIRequest, native: bool) -> None:
206
+ """Gancho: nível de raciocínio e campos próprios do provider."""
207
+
208
+ def _body(self, request: AIRequest) -> dict[str, Any]:
209
+ parts: list[dict[str, Any]] = [{"type": "text", "text": request.material_prompt()}]
210
+ native = False
211
+ for attachment in request.attachments:
212
+ raw = _raw(attachment.content)
213
+ if attachment.kind == "native":
214
+ native = True
215
+ parts.append(
216
+ {
217
+ "type": "file",
218
+ "file": {
219
+ "filename": _filename(attachment.logical_path),
220
+ "file_data": _data_url(attachment.mime_type, raw),
221
+ },
222
+ }
223
+ )
224
+ elif attachment.kind == "image":
225
+ parts.append({"type": "text", "text": f"Imagem da evidência: {attachment.logical_path}"})
226
+ parts.append({"type": "image_url", "image_url": {"url": _data_url(attachment.mime_type, raw)}})
227
+ else:
228
+ parts.append({"type": "text", "text": f"\n[{attachment.logical_path}]\n{attachment.content}"})
229
+ if native:
230
+ parts.insert(1, {"type": "text", "text": _PDF_NOTE})
231
+ body: dict[str, Any] = {
232
+ "model": request.model,
233
+ "messages": [{"role": "user", "content": parts if len(parts) > 1 else parts[0]["text"]}],
234
+ }
235
+ if request.schema:
236
+ body["response_format"] = {
237
+ "type": "json_schema",
238
+ "json_schema": {"name": "argos_response", "strict": True, "schema": strict_json_schema(request.schema)},
239
+ }
240
+ self._tune(body, request, native)
241
+ return body
242
+
243
+ def _read(self, response: Any) -> tuple[str, Mapping[str, Any]]:
244
+ payload = json.loads(response.read().decode("utf-8"))
245
+ try:
246
+ content = payload["choices"][0]["message"]["content"]
247
+ except (KeyError, IndexError, TypeError) as exc:
248
+ raise AIServiceError(f"resposta {self.provider} sem choices[0].message.content") from exc
249
+ if content is None:
250
+ raise AIServiceError(f"{self.provider} retornou content=null")
251
+ return str(content), {}
252
+
253
+
254
+ class OpenRouterAIService(ChatCompletionsAdapter):
255
+ """OpenRouter: ``reasoning.effort`` e, para PDF nativo, o plugin ``file-parser`` (engine ``native``).
256
+
257
+ Só modelos com leitura nativa de PDF recebem o arquivo; nos demais ele chega como texto.
258
+ """
259
+
260
+ provider = "openrouter"
261
+ adapter_name = "openrouter-chat-completions"
262
+ key_names = ("OPENROUTER_API_KEY", "ARGOS_OPENROUTER_API_KEY")
263
+
264
+ @staticmethod
265
+ def capabilities(model: str) -> ModelCapabilities:
266
+ """PDF nativo e imagens dependem do modelo; catálogo indisponível = imagens aceitas."""
267
+ native = openrouter_supports_native_pdf(model)
268
+ modalities = None if native else openrouter_input_modalities(model)
269
+ return ModelCapabilities(
270
+ pdf="native" if native else "text",
271
+ images=modalities is None or "image" in modalities,
272
+ token_limit=400_000,
273
+ reasoning_levels=OPENROUTER_REASONING_LEVELS,
274
+ )
275
+
276
+ def _url(self) -> str:
277
+ return OPENROUTER_URL
278
+
279
+ def _tune(self, body: dict[str, Any], request: AIRequest, native: bool) -> None:
280
+ if request.reasoning_level:
281
+ body["reasoning"] = {"effort": request.reasoning_level}
282
+ if native:
283
+ body["plugins"] = [{"id": "file-parser", "pdf": {"engine": "native"}}]
284
+
285
+
286
+ class OpenCodeGoAIService(ChatCompletionsAdapter):
287
+ """OpenCode Go: ``reasoning_effort`` no topo do corpo e cabeçalho de sessão exigido pelo gateway.
288
+
289
+ O gateway valida o nível por modelo (HTTP 400 indicando o parâmetro); o ``reasoning.effort``
290
+ aninhado é ignorado. ``ARGOS_OPENCODEGO_ALLOW_ANONYMOUS`` dispensa a chave.
291
+ """
292
+
293
+ provider = "opencodego"
294
+ adapter_name = "opencodego-chat-completions"
295
+ key_names = ("OPENCODEGO_API_KEY", "ARGOS_OPENCODEGO_API_KEY")
296
+
297
+ def __init__(self, *, api_key: str | None = None, base_url: str | None = None, **kwargs: Any) -> None:
298
+ super().__init__(api_key=api_key, **kwargs)
299
+ self._base_url = base_url
300
+ # O gateway recusa o User-Agent padrão do urllib (Cloudflare 1010) e exige uma sessão para rotear.
301
+ self._session_id = str(uuid.uuid4())
302
+
303
+ @property
304
+ def base_url(self) -> str:
305
+ """Endereço do gateway; validado no primeiro uso, não ao criar o adapter."""
306
+ return _http_url(
307
+ self._base_url
308
+ or os.environ.get("ARGOS_OPENCODEGO_BASE_URL")
309
+ or os.environ.get("OPENCODEGO_BASE_URL")
310
+ or DEFAULT_OPENCODEGO_URL,
311
+ "ARGOS_OPENCODEGO_BASE_URL",
312
+ )
313
+
314
+ @staticmethod
315
+ def capabilities(model: str) -> ModelCapabilities:
316
+ """O gateway não publica modalidades: imagens aceitas até que o modelo as recuse."""
317
+ return ModelCapabilities(token_limit=400_000)
318
+
319
+ def _url(self) -> str:
320
+ return self.base_url
321
+
322
+ def _requires_key(self) -> bool:
323
+ return not parse_bool(os.environ.get("ARGOS_OPENCODEGO_ALLOW_ANONYMOUS"), default=False)
324
+
325
+ def _extra_headers(self) -> dict[str, str]:
326
+ return {"x-opencode-session": self._session_id}
327
+
328
+ def _tune(self, body: dict[str, Any], request: AIRequest, native: bool) -> None:
329
+ if request.reasoning_level:
330
+ body["reasoning_effort"] = request.reasoning_level
331
+
332
+
333
+ class AnthropicMessagesAdapter(_RemoteAdapter):
334
+ """Protocolo Messages da Anthropic (``POST /v1/messages``).
335
+
336
+ PDF vai como bloco ``document`` e imagens como bloco ``image`` (base64); o esquema JSON e o
337
+ nível de raciocínio dividem o objeto ``output_config`` (``format`` e ``effort``). A resposta
338
+ traz blocos ``thinking`` e ``text``: só o texto, que tem o JSON, é devolvido.
339
+ """
340
+
341
+ adapter_name = "anthropic-messages"
342
+
343
+ def _max_tokens(self) -> int:
344
+ raw = os.environ.get("ARGOS_ANTHROPIC_MAX_TOKENS")
345
+ if raw in (None, ""):
346
+ return DEFAULT_ANTHROPIC_MAX_TOKENS
347
+ try:
348
+ value = int(str(raw).strip())
349
+ except ValueError:
350
+ value = 0
351
+ if value < 1:
352
+ raise InputValidationError("ARGOS_ANTHROPIC_MAX_TOKENS deve ser um inteiro positivo")
353
+ return value
354
+
355
+ def _headers(self, key: str) -> dict[str, str]:
356
+ headers = {
357
+ "Content-Type": "application/json",
358
+ "User-Agent": f"argos-cli/{__version__}",
359
+ "anthropic-version": ANTHROPIC_VERSION,
360
+ **self._extra_headers(),
361
+ }
362
+ if key:
363
+ headers["x-api-key"] = key
364
+ return headers
365
+
366
+ def _body(self, request: AIRequest) -> dict[str, Any]:
367
+ blocks: list[dict[str, Any]] = []
368
+ native = False
369
+ for attachment in request.attachments:
370
+ raw = _raw(attachment.content)
371
+ encoded = base64.b64encode(raw).decode("ascii")
372
+ if attachment.kind == "native":
373
+ native = True
374
+ blocks.append(
375
+ {
376
+ "type": "document",
377
+ "title": _filename(attachment.logical_path),
378
+ "source": {"type": "base64", "media_type": attachment.mime_type, "data": encoded},
379
+ }
380
+ )
381
+ elif attachment.kind == "image":
382
+ blocks.append({"type": "text", "text": f"Imagem da evidência: {attachment.logical_path}"})
383
+ blocks.append(
384
+ {
385
+ "type": "image",
386
+ "source": {"type": "base64", "media_type": _image_media_type(raw, attachment.mime_type), "data": encoded},
387
+ }
388
+ )
389
+ else:
390
+ blocks.append({"type": "text", "text": f"\n[{attachment.logical_path}]\n{attachment.content}"})
391
+ prompt = request.material_prompt()
392
+ blocks.append({"type": "text", "text": f"{_PDF_NOTE}\n\n{prompt}" if native else prompt})
393
+ body: dict[str, Any] = {
394
+ "model": request.model,
395
+ "max_tokens": self._max_tokens(),
396
+ "messages": [{"role": "user", "content": blocks}],
397
+ }
398
+ output_config: dict[str, Any] = {}
399
+ if request.schema:
400
+ output_config["format"] = {"type": "json_schema", "schema": strict_json_schema(request.schema)}
401
+ if request.reasoning_level:
402
+ output_config["effort"] = request.reasoning_level
403
+ if output_config:
404
+ body["output_config"] = output_config
405
+ return body
406
+
407
+ def _read(self, response: Any) -> tuple[str, Mapping[str, Any]]:
408
+ payload = json.loads(response.read().decode("utf-8"))
409
+ if not isinstance(payload, Mapping) or payload.get("type") != "message":
410
+ raise AIServiceError(f"resposta {self.provider} fora do protocolo Messages")
411
+ stop = str(payload.get("stop_reason") or "")
412
+ if stop == "max_tokens":
413
+ raise AIServiceError(
414
+ f"{self.provider} interrompeu a resposta por max_tokens; "
415
+ "aumente ARGOS_ANTHROPIC_MAX_TOKENS ou reduza o nível de raciocínio"
416
+ )
417
+ if stop == "refusal":
418
+ raise AIServiceError(f"{self.provider} recusou a resposta (stop_reason=refusal)")
419
+ text = "".join(
420
+ str(block["text"])
421
+ for block in payload.get("content") or ()
422
+ if isinstance(block, Mapping) and block.get("type") == "text" and isinstance(block.get("text"), str)
423
+ )
424
+ if not text:
425
+ raise AIServiceError(f"{self.provider} retornou resposta sem bloco de texto")
426
+ usage = payload.get("usage") if isinstance(payload.get("usage"), Mapping) else None
427
+ return text, ({"usage": dict(usage)} if usage else {})
428
+
429
+
430
+ class OpenCodeGoAnthropicAIService(AnthropicMessagesAdapter):
431
+ """OpenCode Go pelo protocolo da Anthropic: o único que serve o ``claude-haiku-5-5``.
432
+
433
+ Mesma credencial do ``opencodego``. O endereço vem de ``ARGOS_OPENCODEGO_ANT_BASE_URL``.
434
+ """
435
+
436
+ provider = "opencodego-ant"
437
+ key_names = ("OPENCODEGO_API_KEY", "ARGOS_OPENCODEGO_API_KEY")
438
+
439
+ def __init__(self, *, api_key: str | None = None, base_url: str | None = None, **kwargs: Any) -> None:
440
+ super().__init__(api_key=api_key, **kwargs)
441
+ self._base_url = base_url
442
+ # O gateway recusa o User-Agent padrão do urllib e exige uma sessão para rotear.
443
+ self._session_id = str(uuid.uuid4())
444
+
445
+ @property
446
+ def base_url(self) -> str:
447
+ """Endereço do gateway; validado no primeiro uso, não ao criar o adapter."""
448
+ return _http_url(
449
+ self._base_url or os.environ.get("ARGOS_OPENCODEGO_ANT_BASE_URL") or DEFAULT_OPENCODEGO_ANT_URL,
450
+ "ARGOS_OPENCODEGO_ANT_BASE_URL",
451
+ )
452
+
453
+ @staticmethod
454
+ def capabilities(model: str) -> ModelCapabilities:
455
+ """PDF nativo e imagens; o gateway não publica o limite, então o padrão é conservador."""
456
+ return ModelCapabilities(pdf="native", token_limit=200_000, reasoning_levels=ANTHROPIC_REASONING_LEVELS)
457
+
458
+ def _url(self) -> str:
459
+ return self.base_url
460
+
461
+ def _extra_headers(self) -> dict[str, str]:
462
+ return {"x-opencode-session": self._session_id}
463
+
464
+
465
+ class OpenAIProxyAIService(_RemoteAdapter):
466
+ """OpenAI consultada por um proxy compatível (por padrão o ``codex-openai-proxy`` local).
467
+
468
+ Usa a Responses API em streaming, PDF como ``input_file`` e imagens como
469
+ ``input_image``. O endereço vem de ``ARGOS_OPENAI_PROXY_BASE_URL`` (ou
470
+ ``OPENAI_BASE_URL``) e, sem chave, só é aceito um endereço local (loopback).
471
+ Os níveis de raciocínio de cada modelo são consultados em
472
+ ``GET {base}/models/{modelo}/reasoning`` (extensão do proxy).
473
+ """
474
+
475
+ provider = "openai-proxy"
476
+ adapter_name = "openai-proxy-responses"
477
+ key_names = ("OPENAI_API_KEY", "ARGOS_OPENAI_API_KEY")
478
+
479
+ def __init__(self, *, base_url: str | None = None, **kwargs: Any) -> None:
480
+ super().__init__(**kwargs)
481
+ self._base_url = base_url
482
+ self._levels: dict[str, tuple[str, ...] | None] = {}
483
+
484
+ @property
485
+ def base_url(self) -> str:
486
+ """Endereço do proxy; validado no primeiro uso, não ao criar o adapter."""
487
+ return _http_url(
488
+ (
489
+ self._base_url
490
+ or os.environ.get("ARGOS_OPENAI_PROXY_BASE_URL")
491
+ or os.environ.get("ARGOS_OPENAI_BASE_URL")
492
+ or os.environ.get("OPENAI_BASE_URL")
493
+ or DEFAULT_OPENAI_PROXY_URL
494
+ ).rstrip("/"),
495
+ "ARGOS_OPENAI_PROXY_BASE_URL",
496
+ )
497
+
498
+ @staticmethod
499
+ def _is_loopback(host: str) -> bool:
500
+ if host.casefold() == "localhost":
501
+ return True
502
+ try:
503
+ return ipaddress.ip_address(host).is_loopback
504
+ except ValueError:
505
+ return False
506
+
507
+ def _requires_key(self) -> bool:
508
+ return not self._is_loopback(urllib.parse.urlparse(self.base_url).hostname or "")
509
+
510
+ def capabilities(self, model: str) -> ModelCapabilities:
511
+ """Níveis de raciocínio do modelo vêm do proxy (``None`` se ele não os informa)."""
512
+ if model not in self._levels:
513
+ self._levels[model] = self._fetch_reasoning_levels(model)
514
+ return ModelCapabilities(pdf="native", token_limit=400_000, reasoning_levels=self._levels[model])
515
+
516
+ def _fetch_reasoning_levels(self, model: str) -> tuple[str, ...] | None:
517
+ url = f"{self.base_url}/models/{urllib.parse.quote(model, safe='')}/reasoning"
518
+ headers = {"User-Agent": f"argos-cli/{__version__}"}
519
+ if self._keys:
520
+ headers["Authorization"] = f"Bearer {self._keys[0]}"
521
+ try:
522
+ # Endereço validado como http(s) no construtor; consulta somente leitura.
523
+ with urllib.request.urlopen( # nosec B310
524
+ urllib.request.Request(url, headers=headers), timeout=LEVELS_TIMEOUT_SECONDS
525
+ ) as response:
526
+ payload = json.loads(response.read().decode("utf-8"))
527
+ except urllib.error.HTTPError as exc:
528
+ exc.close()
529
+ return None
530
+ except (urllib.error.URLError, TimeoutError, OSError, ValueError):
531
+ return None
532
+ entries = payload.get("supported_reasoning_levels") if isinstance(payload, Mapping) else None
533
+ levels = tuple(
534
+ str(item["effort"]).strip().casefold()
535
+ for item in entries or ()
536
+ if isinstance(item, Mapping) and item.get("effort")
537
+ )
538
+ return levels or None
539
+
540
+ def _url(self) -> str:
541
+ return f"{self.base_url}/responses"
542
+
543
+ def _body(self, request: AIRequest) -> dict[str, Any]:
544
+ parts: list[dict[str, Any]] = []
545
+ native = False
546
+ for attachment in request.attachments:
547
+ raw = _raw(attachment.content)
548
+ if attachment.kind == "native":
549
+ native = True
550
+ parts.append(
551
+ {
552
+ "type": "input_file",
553
+ "filename": _filename(attachment.logical_path),
554
+ "file_data": _data_url(attachment.mime_type, raw),
555
+ }
556
+ )
557
+ elif attachment.kind == "image":
558
+ parts.append({"type": "input_text", "text": f"Imagem da evidência: {attachment.logical_path}"})
559
+ parts.append({"type": "input_image", "image_url": _data_url(attachment.mime_type, raw)})
560
+ else:
561
+ parts.append({"type": "input_text", "text": f"\n[{attachment.logical_path}]\n{attachment.content}"})
562
+ prompt = request.material_prompt()
563
+ parts.append({"type": "input_text", "text": f"{_PDF_NOTE}\n\n{prompt}" if native else prompt})
564
+ body: dict[str, Any] = {"model": request.model, "input": [{"role": "user", "content": parts}], "stream": True}
565
+ if request.schema:
566
+ body["text"] = {
567
+ "format": {
568
+ "type": "json_schema",
569
+ "name": "argos_response",
570
+ "strict": True,
571
+ "schema": strict_json_schema(request.schema),
572
+ }
573
+ }
574
+ if request.reasoning_level:
575
+ body["reasoning"] = {"effort": request.reasoning_level}
576
+ return body
577
+
578
+ def _read(self, response: Any) -> tuple[str, Mapping[str, Any]]:
579
+ deltas: list[str] = []
580
+ final: Mapping[str, Any] | None = None
581
+ for raw_line in response:
582
+ line = raw_line.decode("utf-8", errors="replace").strip()
583
+ if not line.startswith("data:"):
584
+ continue
585
+ data = line.removeprefix("data:").strip()
586
+ if not data or data == "[DONE]":
587
+ continue
588
+ try:
589
+ event = json.loads(data)
590
+ except json.JSONDecodeError:
591
+ continue
592
+ kind = event.get("type")
593
+ if kind == "response.output_text.delta" and isinstance(event.get("delta"), str):
594
+ deltas.append(event["delta"])
595
+ elif kind == "response.completed" and isinstance(event.get("response"), Mapping):
596
+ final = event["response"]
597
+ elif kind in {"error", "response.failed", "response.incomplete"}:
598
+ detail = event.get("error") or (event.get("response") or {}).get("error") or kind
599
+ message = detail.get("message") if isinstance(detail, Mapping) else detail
600
+ raise AIServiceError(f"provider {self.provider} interrompeu a resposta: {str(message)[:300]}")
601
+ text = "".join(deltas)
602
+ if not text and final is not None:
603
+ text = str(final.get("output_text") or "")
604
+ if not text:
605
+ text = "\n".join(
606
+ str(part["text"])
607
+ for item in final.get("output") or ()
608
+ if isinstance(item, Mapping)
609
+ for part in item.get("content") or ()
610
+ if isinstance(part, Mapping) and isinstance(part.get("text"), str)
611
+ )
612
+ usage = final.get("usage") if final is not None and isinstance(final.get("usage"), Mapping) else None
613
+ return text, ({"usage": dict(usage)} if usage else {})
614
+
615
+
616
+ # --- catálogo de modalidades do OpenRouter (modelos sem entrada de imagem) ---
617
+ _MODALITIES_LOCK = threading.Lock()
618
+ _MODALITIES: dict[str, frozenset[str]] | None = None
619
+
620
+
621
+ def _load_openrouter_modalities() -> dict[str, frozenset[str]]:
622
+ """Entradas aceitas por modelo, do catálogo público do OpenRouter (vazio se indisponível)."""
623
+ try:
624
+ http_request = urllib.request.Request(OPENROUTER_MODELS_URL, headers={"User-Agent": f"argos-cli/{__version__}"})
625
+ with urllib.request.urlopen(http_request, timeout=15) as response: # nosec B310 - URL fixa https
626
+ payload = json.loads(response.read().decode("utf-8"))
627
+ except (urllib.error.URLError, TimeoutError, OSError, ValueError):
628
+ return {}
629
+ modalities: dict[str, frozenset[str]] = {}
630
+ for item in payload.get("data") or ():
631
+ if not isinstance(item, Mapping) or not item.get("id"):
632
+ continue
633
+ architecture = item.get("architecture") if isinstance(item.get("architecture"), Mapping) else {}
634
+ inputs = architecture.get("input_modalities")
635
+ if isinstance(inputs, list) and inputs:
636
+ modalities[str(item["id"]).casefold()] = frozenset(str(value).casefold() for value in inputs)
637
+ return modalities
638
+
639
+
640
+ def openrouter_input_modalities(model: str) -> frozenset[str] | None:
641
+ """Modalidades de entrada do modelo (``text``, ``image``, ``file``...); ``None`` se desconhecidas."""
642
+ global _MODALITIES
643
+ with _MODALITIES_LOCK:
644
+ if _MODALITIES is None:
645
+ _MODALITIES = _load_openrouter_modalities()
646
+ catalog = _MODALITIES
647
+ name = str(model).strip().casefold()
648
+ return catalog.get(name) or catalog.get(name.split(":", 1)[0])
649
+
650
+
651
+ def reset_openrouter_modalities() -> None:
652
+ global _MODALITIES
653
+ with _MODALITIES_LOCK:
654
+ _MODALITIES = None