bugfix: route stickness precedences (transaction in the same intent)

This commit is contained in:
2026-08-20 09:22:03 -03:00
parent bb0ef019bf
commit 9df2467deb
434 changed files with 7098 additions and 281 deletions

6
.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

194
.idea/workspace.xml generated Normal file
View File

@@ -0,0 +1,194 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AutoImportSettings">
<option name="autoReloadType" value="SELECTIVE" />
</component>
<component name="ChangeListManager">
<list default="true" id="30a0e1d8-9d7d-469b-b241-f300911cee8a" name="Changes" comment="Ajustes na documentação e remanejamento dos folders" />
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="ComposerSettings">
<execution />
</component>
<component name="Git.Settings">
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
</component>
<component name="GitHubPullRequestSearchHistory">{
&quot;lastFilter&quot;: {
&quot;state&quot;: &quot;OPEN&quot;,
&quot;assignee&quot;: &quot;hoshikawa2&quot;
}
}</component>
<component name="GithubPullRequestsUISettings">{
&quot;selectedUrlAndAccountId&quot;: {
&quot;url&quot;: &quot;https://github.com/hoshikawa2/agent_platform_oci.git&quot;,
&quot;accountId&quot;: &quot;bd799ac0-7624-42b2-999a-b96e6e11f98a&quot;
}
}</component>
<component name="KubernetesApiPersistence">{}</component>
<component name="KubernetesApiProvider">{
&quot;isMigrated&quot;: true
}</component>
<component name="PhpWorkspaceProjectConfiguration" interpreter_name="PHP 8.1" />
<component name="ProjectCodeStyleSettingsMigration">
<option name="version" value="2" />
</component>
<component name="ProjectColorInfo">{
&quot;customColor&quot;: &quot;&quot;,
&quot;associatedIndex&quot;: 2
}</component>
<component name="ProjectId" id="3FQ8m21arbKaZKgqpTYDVjVGTBf" />
<component name="ProjectViewState">
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent">{
&quot;keyToString&quot;: {
&quot;ASKED_SHARE_PROJECT_CONFIGURATION_FILES&quot;: &quot;true&quot;,
&quot;ModuleVcsDetector.initialDetectionPerformed&quot;: &quot;true&quot;,
&quot;RunOnceActivity.ShowReadmeOnStart&quot;: &quot;true&quot;,
&quot;RunOnceActivity.TerminalTabsStorage.copyFrom.TerminalArrangementManager.252&quot;: &quot;true&quot;,
&quot;RunOnceActivity.git.unshallow&quot;: &quot;true&quot;,
&quot;RunOnceActivity.typescript.service.memoryLimit.init&quot;: &quot;true&quot;,
&quot;SHARE_PROJECT_CONFIGURATION_FILES&quot;: &quot;true&quot;,
&quot;Shell Script.agent_contas.executor&quot;: &quot;Run&quot;,
&quot;Shell Script.agent_frontend.executor&quot;: &quot;Run&quot;,
&quot;Shell Script.agent_template_backend.executor&quot;: &quot;Run&quot;,
&quot;Shell Script.mcp gateway.executor&quot;: &quot;Run&quot;,
&quot;Shell Script.mcp servers.executor&quot;: &quot;Run&quot;,
&quot;git-widget-placeholder&quot;: &quot;main&quot;,
&quot;kotlin-language-version-configured&quot;: &quot;true&quot;,
&quot;last_opened_file_path&quot;: &quot;D:/MSI_Projects/agent_framework_oci&quot;,
&quot;node.js.detected.package.eslint&quot;: &quot;true&quot;,
&quot;node.js.detected.package.tslint&quot;: &quot;true&quot;,
&quot;node.js.selected.package.eslint&quot;: &quot;(autodetect)&quot;,
&quot;node.js.selected.package.tslint&quot;: &quot;(autodetect)&quot;,
&quot;nodejs_package_manager_path&quot;: &quot;npm&quot;,
&quot;settings.editor.selected.configurable&quot;: &quot;project.propVCSSupport.DirectoryMappings&quot;,
&quot;vue.rearranger.settings.migration&quot;: &quot;true&quot;
}
}</component>
<component name="RunManager" selected="Shell Script.agent_contas">
<configuration name="agent_contas" type="ShConfigurationType">
<option name="SCRIPT_TEXT" value="wsl bash -lc &quot;source .venv/bin/activate &amp;&amp; python -m uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload&quot;" />
<option name="INDEPENDENT_SCRIPT_PATH" value="true" />
<option name="SCRIPT_PATH" value="" />
<option name="SCRIPT_OPTIONS" value="" />
<option name="INDEPENDENT_SCRIPT_WORKING_DIRECTORY" value="false" />
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$" />
<option name="INDEPENDENT_INTERPRETER_PATH" value="true" />
<option name="INTERPRETER_PATH" value="powershell.exe" />
<option name="INTERPRETER_OPTIONS" value="" />
<option name="EXECUTE_IN_TERMINAL" value="true" />
<option name="EXECUTE_SCRIPT_FILE" value="false" />
<envs />
<method v="2" />
</configuration>
<configuration name="agent_frontend" type="ShConfigurationType">
<option name="SCRIPT_TEXT" value="wsl bash -lc &quot;source .venv/bin/activate &amp;&amp; cd agent_framework_oci/apps/agent_frontend &amp;&amp; python -m http.server 5173&quot;" />
<option name="INDEPENDENT_SCRIPT_PATH" value="true" />
<option name="SCRIPT_PATH" value="" />
<option name="SCRIPT_OPTIONS" value="" />
<option name="INDEPENDENT_SCRIPT_WORKING_DIRECTORY" value="true" />
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$" />
<option name="INDEPENDENT_INTERPRETER_PATH" value="true" />
<option name="INTERPRETER_PATH" value="powershell.exe" />
<option name="INTERPRETER_OPTIONS" value="" />
<option name="EXECUTE_IN_TERMINAL" value="true" />
<option name="EXECUTE_SCRIPT_FILE" value="false" />
<envs />
<method v="2" />
</configuration>
<configuration name="mcp servers" type="ShConfigurationType">
<option name="SCRIPT_TEXT" value="wsl bash -lc &quot;uv run uvicorn contas_mcp.servers.contas_mcp_server.main:app --host 0.0.0.0 --port 8400&quot;" />
<option name="INDEPENDENT_SCRIPT_PATH" value="true" />
<option name="SCRIPT_PATH" value="" />
<option name="SCRIPT_OPTIONS" value="" />
<option name="INDEPENDENT_SCRIPT_WORKING_DIRECTORY" value="true" />
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$" />
<option name="INDEPENDENT_INTERPRETER_PATH" value="true" />
<option name="INTERPRETER_PATH" value="powershell.exe" />
<option name="INTERPRETER_OPTIONS" value="" />
<option name="EXECUTE_IN_TERMINAL" value="true" />
<option name="EXECUTE_SCRIPT_FILE" value="false" />
<envs />
<method v="2" />
</configuration>
<list>
<item itemvalue="Shell Script.agent_contas" />
<item itemvalue="Shell Script.mcp servers" />
<item itemvalue="Shell Script.agent_frontend" />
</list>
</component>
<component name="SharedIndexes">
<attachedChunks>
<set>
<option value="bundled-jdk-30f59d01ecdd-cffe25b9f5b3-intellij.indexing.shared.core-IU-253.28294.334" />
<option value="bundled-js-predefined-d6986cc7102b-c7e53b3be11b-JavaScript-IU-253.28294.334" />
</set>
</attachedChunks>
</component>
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<changelist id="30a0e1d8-9d7d-469b-b241-f300911cee8a" name="Changes" comment="" />
<created>1781996088468</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1781996088468</updated>
<workItem from="1781996091031" duration="1242000" />
<workItem from="1782038604623" duration="6486000" />
<workItem from="1782047166074" duration="27000" />
<workItem from="1782047194363" duration="961000" />
<workItem from="1782048494672" duration="230000" />
<workItem from="1782592218589" duration="28000" />
<workItem from="1785245181314" duration="79000" />
<workItem from="1785245608367" duration="670000" />
<workItem from="1785326577815" duration="621000" />
<workItem from="1785455932464" duration="228000" />
<workItem from="1785500822622" duration="2349000" />
<workItem from="1786709371666" duration="944000" />
<workItem from="1786736622312" duration="715000" />
<workItem from="1786739151301" duration="953000" />
<workItem from="1787159165094" duration="10002000" />
</task>
<task id="LOCAL-00001" summary="Ajustes na documentação e remanejamento dos folders">
<option name="closed" value="true" />
<created>1782045250014</created>
<option name="number" value="00001" />
<option name="presentableId" value="LOCAL-00001" />
<option name="project" value="LOCAL" />
<updated>1782045250014</updated>
</task>
<task id="LOCAL-00002" summary="Ajustes na documentação e remanejamento dos folders">
<option name="closed" value="true" />
<created>1782045265085</created>
<option name="number" value="00002" />
<option name="presentableId" value="LOCAL-00002" />
<option name="project" value="LOCAL" />
<updated>1782045265085</updated>
</task>
<task id="LOCAL-00003" summary="Ajustes na documentação e remanejamento dos folders">
<option name="closed" value="true" />
<created>1782048304579</created>
<option name="number" value="00003" />
<option name="presentableId" value="LOCAL-00003" />
<option name="project" value="LOCAL" />
<updated>1782048304579</updated>
</task>
<option name="localTasksCounter" value="4" />
<servers />
</component>
<component name="TypeScriptGeneratedFilesManager">
<option name="version" value="3" />
</component>
<component name="VcsManagerConfiguration">
<ignored-roots>
<path value="$PROJECT_DIR$" />
</ignored-roots>
<MESSAGE value="Ajustes na documentação e remanejamento dos folders" />
<option name="LAST_COMMIT_MESSAGE" value="Ajustes na documentação e remanejamento dos folders" />
</component>
</project>

7
.pytest_cache/v/cache/lastfailed vendored Normal file
View File

@@ -0,0 +1,7 @@
{
"agent_framework_oci/tests/unit/test_langgraph_checkpoint_saver.py::test_repository_checkpoint_saver_put_get": true,
"agent_framework_oci/tests/unit/test_resilient_checkpointer.py::test_integrity_envelope_and_recovery_skips_corrupt_latest": true,
"agent_framework_oci/tests/unit/test_resilient_checkpointer.py::test_compaction_keeps_last_n_checkpoints": true,
"agent_framework_oci/tests/unit/test_resilient_checkpointer.py::test_recovery_raises_when_only_corrupt_checkpoints_exist": true,
"agent_framework_oci/tests/unit/test_langgraph_checkpoint_saver.py::test_put_writes_does_not_restore_older_checkpoint": true
}

291
.pytest_cache/v/cache/nodeids vendored Normal file
View File

@@ -0,0 +1,291 @@
[
"agent_framework_oci/tests/test_generic_tool_response_presentation.py::test_generic_lines_mode_preserves_order_shape",
"agent_framework_oci/tests/test_generic_tool_response_presentation.py::test_generic_list_mode_supports_contas_multiple_plans_without_none",
"agent_framework_oci/tests/test_generic_tool_response_presentation.py::test_generic_template_mode_preserves_template_backend_plan_contract",
"agent_framework_oci/tests/test_generic_tool_response_presentation.py::test_missing_renderer_falls_back_without_breaking_runtime",
"agent_framework_oci/tests/test_generic_tool_response_presentation.py::test_no_declared_response_keeps_legacy_fallback",
"agent_framework_oci/tests/test_generic_tool_response_presentation.py::test_renderer_mode_uses_application_registered_renderer",
"agent_framework_oci/tests/test_mcp_parameter_extraction_runtime.py::test_collection_turn_reuses_declarative_parameter_extraction",
"agent_framework_oci/tests/test_mcp_parameter_extraction_runtime.py::test_explicit_order_id_has_precedence_over_contract_key",
"agent_framework_oci/tests/test_mcp_parameter_extraction_runtime.py::test_new_transaction_current_message_overrides_stale_subject_from_context",
"agent_framework_oci/tests/test_mcp_parameter_extraction_runtime.py::test_runtime_extracts_order_id_from_current_message",
"agent_framework_oci/tests/test_mcp_parameter_extraction_runtime.py::test_transaction_extracts_required_fields_before_first_missing_check",
"agent_framework_oci/tests/test_mcp_parameter_extraction_runtime.py::test_unique_transactional_tool_is_selected_after_routing_constrains_allowlist",
"agent_framework_oci/tests/test_route_stickiness_transaction_shift.py::test_explicit_keyword_shift_preempts_stickiness",
"agent_framework_oci/tests/test_route_stickiness_transaction_shift.py::test_same_agent_explicit_intent_shift_must_preempt_stickiness",
"agent_framework_oci/tests/test_route_stickiness_transaction_shift.py::test_same_agent_transaction_keyword_preempts_continuity",
"agent_framework_oci/tests/test_route_stickiness_transaction_shift.py::test_short_generic_keyword_does_not_preempt",
"agent_framework_oci/tests/test_transactional_tool_flow.py::test_closed_transaction_is_not_operational_context_for_next_turn",
"agent_framework_oci/tests/test_transactional_tool_flow.py::test_collecting_parameters_does_not_replace_collected_subject_with_stale_context",
"agent_framework_oci/tests/test_transactional_tool_flow.py::test_new_contestation_does_not_inherit_subject_or_value_from_previous_transaction",
"agent_framework_oci/tests/test_transactional_tool_flow.py::test_runtime_source_contains_persisted_confirmation_contract",
"agent_framework_oci/tests/test_transactional_tool_flow.py::test_terminal_confirmation_closes_active_transaction_and_clears_latches",
"agent_framework_oci/tests/test_transactional_tool_flow.py::test_tool_policy_registry_reads_transactional_confirmation",
"agent_framework_oci/tests/test_transactional_tool_flow.py::test_transaction_waits_then_executes_after_confirmation",
"agent_framework_oci/tests/unit/test_langgraph_checkpoint_saver.py::test_put_writes_does_not_restore_older_checkpoint",
"agent_framework_oci/tests/unit/test_langgraph_checkpoint_saver.py::test_repository_checkpoint_saver_put_get",
"agent_framework_oci/tests/unit/test_resilient_checkpointer.py::test_compaction_keeps_last_n_checkpoints",
"agent_framework_oci/tests/unit/test_resilient_checkpointer.py::test_integrity_envelope_and_recovery_skips_corrupt_latest",
"agent_framework_oci/tests/unit/test_resilient_checkpointer.py::test_recovery_raises_when_only_corrupt_checkpoints_exist",
"agent_framework_oci/tests/unit/test_semantic_route_stickiness.py::test_continue_bypasses_router_without_regex_rules",
"agent_framework_oci/tests/unit/test_semantic_route_stickiness.py::test_continue_without_active_agent_falls_back_to_router",
"agent_framework_oci/tests/unit/test_semantic_route_stickiness.py::test_end_session_is_returned_as_global_route",
"agent_framework_oci/tests/unit/test_semantic_route_stickiness.py::test_global_session_actions_work_without_active_agent",
"agent_framework_oci/tests/unit/test_semantic_route_stickiness.py::test_human_handoff_is_returned_as_global_route",
"agent_framework_oci/tests/unit/test_semantic_route_stickiness.py::test_invalid_output_falls_back_safely",
"agent_framework_oci/tests/unit/test_semantic_route_stickiness.py::test_low_confidence_continue_falls_back_safely",
"agent_framework_oci/tests/unit/test_semantic_route_stickiness.py::test_no_active_agent_still_classifies_global_session_actions",
"agent_framework_oci/tests/unit/test_semantic_route_stickiness.py::test_route_result_falls_back_to_enterprise_router",
"tests/migration/test_backend_wrapper_contract_parity.py::test_cancelamento_aceita_alias_itens_para_contestacao",
"tests/migration/test_backend_wrapper_contract_parity.py::test_cancelamento_aceita_cpf_como_alias_social_sec_no",
"tests/migration/test_backend_wrapper_contract_parity.py::test_cancelamento_falha_operacional_com_candidato_dispara_contestacao",
"tests/migration/test_backend_wrapper_contract_parity.py::test_cancelamento_falha_workflow_preserva_output_parcial_nao_cancelados",
"tests/migration/test_backend_wrapper_contract_parity.py::test_cancelamento_sem_candidatos_nao_dispara_contestacao",
"tests/migration/test_backend_wrapper_contract_parity.py::test_cancelamento_sms_falho_preserva_sucesso_e_flag",
"tests/migration/test_backend_wrapper_contract_parity.py::test_contestacao_wrapper_mapeia_falha_tecnica_como_sistemica",
"tests/migration/test_backend_wrapper_contract_parity.py::test_contestacao_wrapper_preserva_erro_de_negocio_e_protocolo",
"tests/migration/test_backend_wrapper_contract_parity.py::test_contestacao_wrapper_preserva_tipo_atendimento_e_contexto_do_turno",
"tests/migration/test_backend_wrapper_contract_parity.py::test_invoice_explanation_branch_devolver_orquestrador_nao_auto_finaliza",
"tests/migration/test_backend_wrapper_contract_parity.py::test_invoice_explanation_branch_nao_sem_vas_recomenda_nao_resolvido",
"tests/migration/test_backend_wrapper_contract_parity.py::test_invoice_explanation_service_failure_preserva_fraseologia_sem_auto_finalize",
"tests/migration/test_backend_wrapper_contract_parity.py::test_pro_rata_aceite_e_nao_controle_recomendam_resolvido",
"tests/migration/test_backend_wrapper_contract_parity.py::test_pro_rata_branch_devolver_orquestrador_nao_auto_finaliza",
"tests/migration/test_backend_wrapper_contract_parity.py::test_vas_estrategico_rejeitado_declara_rag_para_cada_servico_estrategico",
"tests/migration/test_backend_wrapper_contract_parity.py::test_vas_estrategico_workflow_payload_preserva_tres_itens_e_action_agrupa_duas_linhas",
"tests/migration/test_business_events_and_guardrails.py::test_business_events_are_published_recursively_once",
"tests/migration/test_business_events_and_guardrails.py::test_cached_tool_result_does_not_republish_business_events",
"tests/migration/test_contas_domain_mock.py::test_cancel_vas_is_domain_operation_not_conversation_engine",
"tests/migration/test_contas_domain_mock.py::test_cancelamento_batch_emite_vaa004_quando_falha_operacional",
"tests/migration/test_contas_domain_mock.py::test_cancelamento_batch_emite_vaa_caminho_feliz_uma_vez",
"tests/migration/test_contas_domain_mock.py::test_cancelamento_nao_recancela_servico_inativo_do_historico",
"tests/migration/test_contas_domain_mock.py::test_cancelamento_usa_historico_como_fallback_quando_ativo_nao_encontra",
"tests/migration/test_contas_domain_mock.py::test_contestation_mock",
"tests/migration/test_contas_domain_mock.py::test_finalizacao_com_protocolo_existente_nao_cria_informacional",
"tests/migration/test_contas_domain_mock.py::test_finalizacao_cria_protocolo_informacional_quando_invoice_explanation_executou",
"tests/migration/test_contas_domain_mock.py::test_finalizacao_force_rt15_cria_novo_protocolo_mesmo_com_veb_fechado",
"tests/migration/test_contas_domain_mock.py::test_finalizacao_informacional_cria_protocolo_fechado_sem_duplicar_status",
"tests/migration/test_contas_domain_mock.py::test_finalizacao_informacional_notas_canonicas[types0-Explica\\xe7\\xe3o de VAS Bundle]",
"tests/migration/test_contas_domain_mock.py::test_finalizacao_informacional_notas_canonicas[types1-Explica\\xe7\\xe3o de VAS Estrat\\xe9gico]",
"tests/migration/test_contas_domain_mock.py::test_finalizacao_informacional_notas_canonicas[types2-Explica\\xe7\\xe3o de VAS Avulso]",
"tests/migration/test_contas_domain_mock.py::test_finalizacao_informacional_notas_canonicas[types3-Explica\\xe7\\xe3o de VAS Bundle, VAS Estrat\\xe9gico]",
"tests/migration/test_contas_domain_mock.py::test_finalizacao_informacional_notas_canonicas[types4-Explica\\xe7\\xe3o de VAS Bundle, VAS Avulso]",
"tests/migration/test_contas_domain_mock.py::test_finalizacao_informacional_notas_canonicas[types5-Explica\\xe7\\xe3o de VAS Estrat\\xe9gico, VAS Avulso]",
"tests/migration/test_contas_domain_mock.py::test_finalizacao_informacional_notas_canonicas[types6-Explica\\xe7\\xe3o de VAS Bundle, VAS Estrat\\xe9gico, VAS Avulso]",
"tests/migration/test_contas_domain_mock.py::test_finalizacao_nao_cria_protocolo_apenas_por_prefetch_invoice_explanation",
"tests/migration/test_contas_domain_mock.py::test_finalizacao_nao_duplica_protocolo_quando_contestacao_ja_existe",
"tests/migration/test_contas_domain_mock.py::test_finalizacao_normaliza_status_invalido_e_summary",
"tests/migration/test_contas_domain_mock.py::test_finalizacao_preserva_status_valido_e_prefixa_summary",
"tests/migration/test_contas_domain_mock.py::test_finalizacao_reusa_protocolo_veb_ja_fechado_sem_abrir_outro",
"tests/migration/test_contas_domain_mock.py::test_finalizacao_veb_deferido_suprime_evento_cvn_de_protocolo",
"tests/migration/test_contas_domain_mock.py::test_invoice_explanation_converte_retry_transport_em_rct_por_tentativa",
"tests/migration/test_contas_domain_mock.py::test_invoice_explanation_falha_preserva_rct_das_tres_tentativas",
"tests/migration/test_contas_domain_mock.py::test_read_only_integrations_with_fixtures",
"tests/migration/test_contestation_business_rules_full.py::test_abrir_contestacao_deriva_refund_manual_e_normaliza_barcode_zero",
"tests/migration/test_contestation_business_rules_full.py::test_check_invoice_status_enriquece_prefetch_sem_nova_api",
"tests/migration/test_contestation_business_rules_full.py::test_check_invoice_status_falha_sem_prefetch",
"tests/migration/test_contestation_business_rules_full.py::test_cutdate_da_fatura_define_manual",
"tests/migration/test_contestation_business_rules_full.py::test_cutdate_regra_um_mes",
"tests/migration/test_contestation_business_rules_full.py::test_cutoff_referencia_corrige_bug_mes_seguinte",
"tests/migration/test_contestation_business_rules_full.py::test_dependente_forca_conta_certa_manual",
"tests/migration/test_contestation_business_rules_full.py::test_due_day_iso_e_br",
"tests/migration/test_contestation_business_rules_full.py::test_refund_boleto_para_fatura_em_aberto_com_fatura_normal",
"tests/migration/test_contestation_business_rules_full.py::test_refund_credito_para_dacc_cartao_ou_parcelamento",
"tests/migration/test_contestation_business_rules_full.py::test_refund_credito_para_fatura_paga_ou_ja_contestada",
"tests/migration/test_contestation_failure_mapping.py::test_contestacao_failed_preserva_provider_message_e_protocolo",
"tests/migration/test_contestation_failure_mapping.py::test_contestacao_failed_sem_mensagem_provider_vira_falha_sistemica",
"tests/migration/test_framework_native_structure.py::test_agent_workflow_init_realmente_inicializa_router_agentes_e_graph",
"tests/migration/test_framework_native_structure.py::test_all_active_workflow_actions_registered",
"tests/migration/test_framework_native_structure.py::test_contestacao_workflow_encerra_imediatamente_quando_cval_bloqueia",
"tests/migration/test_framework_native_structure.py::test_domain_does_not_import_langgraph_directly",
"tests/migration/test_framework_native_structure.py::test_guardrail_config_declares_all_execution_stages",
"tests/migration/test_framework_native_structure.py::test_official_templates_use_framework_state_graph",
"tests/migration/test_framework_native_structure.py::test_workflow_runtime_preserva_snapshot_parcial_quando_action_posterior_falha",
"tests/migration/test_mcp_contestation_subject_guard.py::test_correct_subject_is_preserved",
"tests/migration/test_mcp_contestation_subject_guard.py::test_preflight_does_not_replace_explicit_plan_with_vas",
"tests/migration/test_mcp_contestation_subject_guard.py::test_recovers_explicit_contestation_subject_from_original_text",
"tests/migration/test_original_contestation_validation.py::test_contestation_action_calculates_totals_only_for_items_actually_contested",
"tests/migration/test_original_contestation_validation.py::test_contestation_action_classifies_already_contested_and_missing_requested_item",
"tests/migration/test_original_contestation_validation.py::test_validate_contestation_items_aprova_quando_total_ajustes_dentro_do_limite",
"tests/migration/test_original_contestation_validation.py::test_validate_contestation_items_bloqueia_classe_estrategico_canonica",
"tests/migration/test_original_contestation_validation.py::test_validate_contestation_items_bloqueia_item_fora_da_secao_vas",
"tests/migration/test_original_contestation_validation.py::test_validate_contestation_items_bloqueia_item_inexistente",
"tests/migration/test_original_contestation_validation.py::test_validate_contestation_items_bloqueia_quando_total_ajustes_excede_fatura",
"tests/migration/test_original_contestation_validation.py::test_validate_contestation_items_bloqueia_valor_maior_que_o_item",
"tests/migration/test_original_contestation_validation.py::test_validate_contestation_items_bloqueia_vas_estrategico",
"tests/migration/test_original_contestation_validation.py::test_validate_contestation_items_emite_span_quando_aprova",
"tests/migration/test_original_contestation_validation.py::test_validate_contestation_items_emite_spans_quando_bloqueia",
"tests/migration/test_original_contestation_validation.py::test_validate_contestation_items_prefere_evidencia_vas_quando_item_aparece_em_multiplas_visoes",
"tests/migration/test_original_contestation_validation.py::test_validate_contestation_items_reconhece_vas_por_type_do_billing_analysis",
"tests/migration/test_original_contestation_validation.py::test_validate_contestation_items_span_blocked_inclui_contagens",
"tests/migration/test_original_contestation_validation.py::test_validate_contestation_items_usa_classe_avulso_canonica",
"tests/migration/test_original_contestation_validation.py::test_validate_contestation_items_valida_todos_antes_de_retornar",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[A01-fluid-light-x-premium]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[A02-fluid-premium-x-light]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[A03-aya-books-x-audiobooks]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[A04-aya-ensinah-x-books]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[A05-exa-seguranca-x-cloud]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[A06-bancah-jornais-x-premium]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[A07-itgame-light-x-premium]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[A08-aluguel-filme-1-x-2]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[A09-tim-games-mensal-x-semanal]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[A10-kids-plus-x-premium]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[A11-exa-premium-x-protecao]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[A12-tim-games-prefixo]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[A13-fit-app-x-fit-me-app]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[A14-tim-music-plus-x-premium]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[A15-kids-prefixo]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[B01-fitme-16.99-x-17.00]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[B02-fitme-16.99-x-16.98]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[B03-fluid-14.99-x-15.00]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[B04-exa-9.99-x-9.98]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[B05-fitme-prefixo-valor-errado]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[B06-aya-24.90-x-24.91]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[B07-itgame-12.90-x-12.09]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[B08-fitme-16.99-x-169.90]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[C01-hbo-secao-terceiros]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[C02-netflix-em-secao-avulsa]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[C03-youtube-mis-bucket]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[C04-deezer-em-secao-avulsa]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[C05-apple-music-em-secao-avulsa]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[C06-bundle-incluso]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[C07-fitme-classificado-estrategico]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[D01-fitme-dois-candidatos]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[D02-fitme-tres-candidatos]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[D03-aya-tres-marcas]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[D04-mesmo-nome-duas-linhas]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[D05-duplicata-mesma-linha]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[D06-fluid-familia]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[D07-exa-familia]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[D08-bancah-familia]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[E01-prefixo-invertido]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[E02-substring-no-meio]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[E03-sufixo-games-premium]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[E04-token-parcial-tube]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[E05-token-solto-app]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[E06-fitme-fail-closed-por-padrao]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[F01-msisdn-ausente]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[F02-item-na-linha-secundaria]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[F03-secao-sem-classe]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[F04-desc-vazia]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[F05-valor-nao-parseavel]",
"tests/migration/test_original_vas_variation_adversarial.py::test_explicacao_sem_data_nao_altera_nenhum_dos_50[F06-fatura-sem-o-item]",
"tests/migration/test_original_vas_variation_adversarial.py::test_flag_liga_a_segunda_passada_e_so_isso",
"tests/migration/test_original_vas_variation_adversarial.py::test_flag_ligada_nao_reabre_msisdn_nem_ambiguidade",
"tests/migration/test_original_vas_variation_adversarial.py::test_guards_de_prefixo_valem_com_a_flag_ligada[E01-prefixo-invertido]",
"tests/migration/test_original_vas_variation_adversarial.py::test_guards_de_prefixo_valem_com_a_flag_ligada[E02-substring-no-meio]",
"tests/migration/test_original_vas_variation_adversarial.py::test_guards_de_prefixo_valem_com_a_flag_ligada[E03-sufixo-games-premium]",
"tests/migration/test_original_vas_variation_adversarial.py::test_guards_de_prefixo_valem_com_a_flag_ligada[E04-token-parcial-tube]",
"tests/migration/test_original_vas_variation_adversarial.py::test_guards_de_prefixo_valem_com_a_flag_ligada[E05-token-solto-app]",
"tests/migration/test_original_vas_variation_adversarial.py::test_guards_de_prefixo_valem_com_a_flag_ligada[E06-fitme-fail-closed-por-padrao]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[A01-fluid-light-x-premium]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[A02-fluid-premium-x-light]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[A03-aya-books-x-audiobooks]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[A04-aya-ensinah-x-books]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[A05-exa-seguranca-x-cloud]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[A06-bancah-jornais-x-premium]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[A07-itgame-light-x-premium]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[A08-aluguel-filme-1-x-2]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[A09-tim-games-mensal-x-semanal]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[A10-kids-plus-x-premium]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[A11-exa-premium-x-protecao]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[A12-tim-games-prefixo]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[A13-fit-app-x-fit-me-app]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[A14-tim-music-plus-x-premium]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[A15-kids-prefixo]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[B01-fitme-16.99-x-17.00]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[B02-fitme-16.99-x-16.98]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[B03-fluid-14.99-x-15.00]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[B04-exa-9.99-x-9.98]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[B05-fitme-prefixo-valor-errado]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[B06-aya-24.90-x-24.91]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[B07-itgame-12.90-x-12.09]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[B08-fitme-16.99-x-169.90]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[C01-hbo-secao-terceiros]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[C02-netflix-em-secao-avulsa]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[C03-youtube-mis-bucket]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[C04-deezer-em-secao-avulsa]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[C05-apple-music-em-secao-avulsa]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[C06-bundle-incluso]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[C07-fitme-classificado-estrategico]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[D01-fitme-dois-candidatos]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[D02-fitme-tres-candidatos]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[D03-aya-tres-marcas]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[D04-mesmo-nome-duas-linhas]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[D05-duplicata-mesma-linha]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[D06-fluid-familia]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[D07-exa-familia]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[D08-bancah-familia]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[E01-prefixo-invertido]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[E02-substring-no-meio]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[E03-sufixo-games-premium]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[E04-token-parcial-tube]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[E05-token-solto-app]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[E06-fitme-fail-closed-por-padrao]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[F01-msisdn-ausente]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[F02-item-na-linha-secundaria]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[F03-secao-sem-classe]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[F04-desc-vazia]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[F05-valor-nao-parseavel]",
"tests/migration/test_original_vas_variation_adversarial.py::test_matcher_determinístico_nao_produz_falso_positivo[F06-fatura-sem-o-item]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[A01-fluid-light-x-premium]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[A02-fluid-premium-x-light]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[A03-aya-books-x-audiobooks]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[A04-aya-ensinah-x-books]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[A05-exa-seguranca-x-cloud]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[A06-bancah-jornais-x-premium]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[A07-itgame-light-x-premium]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[A08-aluguel-filme-1-x-2]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[A09-tim-games-mensal-x-semanal]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[A10-kids-plus-x-premium]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[A11-exa-premium-x-protecao]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[A12-tim-games-prefixo]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[A13-fit-app-x-fit-me-app]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[A14-tim-music-plus-x-premium]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[A15-kids-prefixo]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[B01-fitme-16.99-x-17.00]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[B02-fitme-16.99-x-16.98]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[B03-fluid-14.99-x-15.00]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[B04-exa-9.99-x-9.98]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[B05-fitme-prefixo-valor-errado]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[B06-aya-24.90-x-24.91]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[B07-itgame-12.90-x-12.09]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[B08-fitme-16.99-x-169.90]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[C01-hbo-secao-terceiros]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[C02-netflix-em-secao-avulsa]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[C03-youtube-mis-bucket]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[C04-deezer-em-secao-avulsa]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[C05-apple-music-em-secao-avulsa]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[C06-bundle-incluso]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[C07-fitme-classificado-estrategico]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[D01-fitme-dois-candidatos]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[D02-fitme-tres-candidatos]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[D03-aya-tres-marcas]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[D04-mesmo-nome-duas-linhas]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[D05-duplicata-mesma-linha]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[D06-fluid-familia]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[D07-exa-familia]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[D08-bancah-familia]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[E01-prefixo-invertido]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[E02-substring-no-meio]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[E03-sufixo-games-premium]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[E04-token-parcial-tube]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[E05-token-solto-app]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[E06-fitme-fail-closed-por-padrao]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[F01-msisdn-ausente]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[F02-item-na-linha-secundaria]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[F03-secao-sem-classe]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[F04-desc-vazia]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[F05-valor-nao-parseavel]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_item_devolvido_e_estrategico_ou_bundle[F06-fatura-sem-o-item]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_threshold_de_similaridade_zera_falso_positivo[0.85]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_threshold_de_similaridade_zera_falso_positivo[0.95]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_threshold_de_similaridade_zera_falso_positivo[0.97]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_threshold_de_similaridade_zera_falso_positivo[0.99]",
"tests/migration/test_original_vas_variation_adversarial.py::test_nenhum_threshold_de_similaridade_zera_falso_positivo[0.9]",
"tests/migration/test_original_vas_variation_adversarial.py::test_shadow_similaridade_tem_overlap_irremovivel",
"tests/migration/test_original_vas_variation_adversarial.py::test_suite_tem_exatamente_50_casos_com_a_distribuicao_exigida",
"tests/migration/test_original_vas_variation_adversarial.py::test_valores_sao_decimal_nunca_float",
"tests/migration/test_tool_policy_operation_types.py::test_contas_tool_policies_accept_all_operation_types",
"tests/migration/test_vas_response_renderer.py::test_vas_renderer_does_not_invent_missing_value",
"tests/migration/test_vas_response_renderer.py::test_vas_renderer_includes_available_values"
]

View File

@@ -35,3 +35,7 @@ grep -R "agente_contas_tim" app mcp config
``` ```
Deve retornar zero ocorrências. Deve retornar zero ocorrências.
## V10 - VAS response renderer
`consultar_vas` agora usa `response.mode: renderer` com `renderer: contas.vas`. O renderer inclui o valor de cada serviço quando a tool o fornece (por exemplo `details.valor`) e nunca inventa preço quando ausente.

207
agent_framework_oci/.env Normal file
View File

@@ -0,0 +1,207 @@
###############################################################################
# AI AGENT PLATFORM - CONFIGURAÇÃO ÚNICA
# Este arquivo é lido por Pydantic Settings no framework e no backend template.
###############################################################################
APP_NAME=ai-agent-template
APP_ENV=local
LOG_LEVEL=INFO
API_HOST=0.0.0.0
API_PORT=8000
CORS_ORIGINS=http://localhost:5173,http://127.0.0.1:5173
###############################################################################
# LLM - OCI Generative AI como provider principal
###############################################################################
# Opções: mock, oci_openai, oci_sdk, openai_compatible
LLM_PROVIDER=oci_sdk
LLM_TEMPERATURE=0.2
LLM_MAX_TOKENS=2048
LLM_TIMEOUT_SECONDS=120
# OCI OpenAI-compatible endpoint
OCI_GENAI_BASE_URL=https://inference.generativeai.us-chicago-1.oci.oraclecloud.com
OCI_GENAI_MODEL=openai.gpt-4.1
OCI_GENAI_API_KEY=sk-ph3FgX6iP3fxAQCXb9IpPIDTadkeeYAWntUWhzcWysIM6zsS
OCI_GENAI_PROJECT_OCID=
#OCI_GENAI_BASE_URL=https://pegruagntaiatenddev.pe.inference.generativeai.sa-saopaulo-1.oci.oraclecloud.com
#OCI_GENAI_MODEL=openai.gpt-4.1
#OCI_GENAI_API_KEY=
#OCI_GENAI_PROJECT_OCID=
# OCI_AUTH_MODE=config_file|instance_principal|resource_principal
OCI_AUTH_MODE=config_file
# OCI SDK / signer / profiles
OCI_CONFIG_FILE=~/.oci/config
OCI_PROFILE=LATINOAMERICA-Chicago
OCI_COMPARTMENT_ID=ocid1.compartment.oc1..aaaaaaaaexpiw4a7dio64mkfv2t273s2hgdl6mgfvvyv7tycalnjlvpvfl3q
OCI_REGION=us-chicago-1
###############################################################################
# Persistência
###############################################################################
# Opções: memory, autonomous, mongodb
SESSION_REPOSITORY_PROVIDER=autonomous
MEMORY_REPOSITORY_PROVIDER=autonomous
CHECKPOINT_REPOSITORY_PROVIDER=autonomous
# Autonomous Database
ADB_USER=admin
ADB_PASSWORD=Moniquinha19721972
ADB_DSN=oradb23ai_high
ADB_WALLET_LOCATION=/mnt/d/Dropbox/ORACLE/LatinoAmerica/Wallet_ORADB23ai
ADB_WALLET_PASSWORD=Moniquinha1972
ADB_TABLE_PREFIX=AGENTFW
# MongoDB - também pode representar Autonomous usando API compatível com Mongo, se habilitada no ambiente
MONGODB_URI=mongodb://mongo:mongopassword@localhost:27017
MONGODB_DATABASE=agent_platform
# Redis
REDIS_URL=redis://localhost:6379/0
ENABLE_REDIS_CACHE=false
###############################################################################
# RAG / Vector / Graph
###############################################################################
VECTOR_STORE_PROVIDER=autonomous
GRAPH_STORE_PROVIDER=autonomous
RAG_TOP_K=5
EMBEDDING_PROVIDER=oci
OCI_EMBEDDING_MODEL=cohere.embed-multilingual-v3.0
RAG_FILE_GLOBS=*.md,*.txt,*.yaml,*.yml,*.json
###############################################################################
# Observabilidade
###############################################################################
ENABLE_LANGFUSE=true
# Opcional: verbose, compact
LANGFUSE_TRACE_MODE=compact
# Nome customizado do trace pai, ex.: backoffice.checklist.workflow ou backoffice.emulador.workflow
LANGFUSE_COMPACT_VISIBLE_EVENT_PREFIXES=AGA.,NOC., IC.
LANGFUSE_COMPACT_SUPPRESSED_PREFIXES=llm.chat_completion
LANGFUSE_IGNORE_HEALTHCHECKS=true
LANGFUSE_IGNORED_PATHS=/health,/ready,/metrics
LANGFUSE_PUBLIC_KEY=pk-lf-4a1e3921-5158-4fd3-a16d-7a77549fb312
LANGFUSE_SECRET_KEY=sk-lf-efc6fd59-c5ec-4858-b6ec-4aa129734915
LANGFUSE_HOST=http://localhost:3005
ENABLE_OTEL=false
OTEL_EXPORTER_OTLP_ENDPOINT=
OTEL_SERVICE_NAME=ai-agent-template
ENABLE_LANGFUSE_OPENAI_AUTO_INSTRUMENTATION=true
ENABLE_LANGFUSE_ANALYTICS_PUBLISHER=false
###############################################################################
# Analytics / Observer corporativo
###############################################################################
# Quando true, AgentObserver publica eventos IC.*, NOC.* e GRL.* nos providers abaixo.
ENABLE_ANALYTICS=false
# Providers aceitos: oci_streaming,pubsub,noop
ANALYTICS_PROVIDERS=oci_streaming
# Compatibilidade FIRST/TIM: pode informar AGENT_PUBSUB_TOPIC diretamente.
AGENT_PUBSUB_TOPIC=
GCP_PUBSUB_TOPIC_PATH=
GCP_PROJECT_ID=
GCP_PUBSUB_TOPIC=
GCP_PUBSUB_TIMEOUT_SECONDS=30
# Credencial GCP segue padrão Google:
# GOOGLE_APPLICATION_CREDENTIALS=/secrets/gcp-service-account.json
###############################################################################
# OCI Streaming
###############################################################################
ENABLE_OCI_STREAMING=false
OCI_STREAM_ENDPOINT=
OCI_STREAM_OCID=
OCI_STREAM_PARTITION_KEY=agent-events
###############################################################################
# Guardrails, Judges, Supervisor
###############################################################################
ENABLE_INPUT_GUARDRAILS=true
ENABLE_OUTPUT_GUARDRAILS=true
ENABLE_JUDGES=true
ENABLE_SUPERVISOR=true
ENABLE_OUTPUT_SUPERVISOR=true
ENABLE_PARALLEL_GUARDRAILS=true
GUARDRAILS_FAIL_FAST=true
OUTPUT_SUPERVISOR_MAX_RETRIES=3
GUARDRAILS_CONFIG_PATH=./config/guardrails.yaml
JUDGES_CONFIG_PATH=./config/judges.yaml
PROMPT_POLICY_PATH=./config/prompt_policy.yaml
###############################################################################
# Gateway de canais
###############################################################################
DEFAULT_CHANNEL=web
# embedded = backend may parse simple/native channel payloads.
# external = backend only accepts GatewayRequest normalized by an external Channel Gateway.
FRAMEWORK_CHANNEL_INPUT_MODE=embedded
ENABLE_VOICE_ADAPTER=true
ENABLE_WHATSAPP_ADAPTER=true
ENABLE_TEXT_ADAPTER=true
#################################################
# ENTERPRISE ROUTING
#################################################
# Arquivo YAML com intents, keywords, políticas de estado e fallback.
ROUTING_CONFIG_PATH=./config/routing.yaml
# true = usa LLM para classificar quando keywords/estado não resolverem.
# Em produção, costuma ser útil; em desenvolvimento, false evita custo e latência.
ENABLE_LLM_ROUTER=true
# Semantic route stickiness (optional).
# Uses a lightweight LLM profile to decide only CONTINUE vs ROUTE.
# There are no regexes or deterministic language rules.
ENABLE_ROUTE_STICKINESS=true
ROUTE_STICKINESS_LLM_PROFILE=route_continuity
ROUTE_STICKINESS_CONFIDENCE_THRESHOLD=0.90
ROUTE_STICKINESS_HISTORY_TURNS=2
ROUTE_STICKINESS_MAX_TOKENS=80
HUMAN_HANDOFF_MESSAGE=Vou encaminhar seu atendimento para uma pessoa.
END_SESSION_MESSAGE=Atendimento encerrado. Obrigado pelo contato.
###############################################################################
# MCP / Tools
###############################################################################
ENABLE_MCP_TOOLS=true
MCP_SERVERS_CONFIG_PATH=./config/mcp_servers.yaml
TOOLS_CONFIG_PATH=./config/tools.yaml
MCP_TOOL_TIMEOUT_SECONDS=30
# router = EnterpriseRouter seleciona um agente; supervisor = pode acionar múltiplos agentes
ROUTING_MODE=router
# Usage/cost accounting
USAGE_REPOSITORY_PROVIDER=autonomous
IDENTITY_CONFIG_PATH=./config/identity.yaml
MCP_PARAMETER_MAPPING_PATH=./config/mcp_parameter_mapping.yaml
# -----------------------------------------------------------------------------
# ConversationSummaryMemory / compressão de contexto conversacional
# -----------------------------------------------------------------------------
ENABLE_CONVERSATION_SUMMARY_MEMORY=true
MEMORY_CONTEXT_STRATEGY=summary
MEMORY_HISTORY_LIMIT=80
MEMORY_RECENT_MESSAGES_LIMIT=8
MEMORY_SUMMARY_TRIGGER_MESSAGES=20
MEMORY_MAX_SUMMARY_CHARS=6000
MEMORY_SUMMARY_USE_LLM=true
MEMORY_INJECT_RECENT_MESSAGES=true
MEMORY_INJECT_SUMMARY=true
###############################################################################
# LONG-TERM MEMORY
###############################################################################
ENABLE_LONG_TERM_MEMORY=true
LONG_TERM_MEMORY_PROVIDER=sqlite
LONG_TERM_MEMORY_SQLITE_PATH=./data/agent_framework.db
LONG_TERM_MEMORY_TABLE=agentfw_long_term_memory
# For Autonomous/Oracle, defaults to ${ADB_TABLE_PREFIX}_LONG_TERM_MEMORY
# LONG_TERM_MEMORY_ORACLE_TABLE=AGENTFW_LONG_TERM_MEMORY
LONG_TERM_MEMORY_MAX_CONTEXT_ITEMS=20
LONG_TERM_MEMORY_MIN_CONFIDENCE=0.70
LONG_TERM_MEMORY_AUTO_EXTRACT=true
LONG_TERM_MEMORY_INJECT_CONTEXT=true

View File

@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="TemplatesService">
<option name="TEMPLATE_FOLDERS">
<list>
<option value="$MODULE_DIR$/templates" />
</list>
</option>
</component>
</module>

8
agent_framework_oci/.idea/modules.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/agent_platform_oci.iml" filepath="$PROJECT_DIR$/.idea/agent_platform_oci.iml" />
</modules>
</component>
</project>

6
agent_framework_oci/.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

130
agent_framework_oci/.idea/workspace.xml generated Normal file
View File

@@ -0,0 +1,130 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AutoImportSettings">
<option name="autoReloadType" value="SELECTIVE" />
</component>
<component name="ChangeListManager">
<list default="true" id="30a0e1d8-9d7d-469b-b241-f300911cee8a" name="Changes" comment="Ajustes na documentação e remanejamento dos folders" />
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="ComposerSettings">
<execution />
</component>
<component name="Git.Settings">
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
</component>
<component name="GitHubPullRequestSearchHistory">{
&quot;lastFilter&quot;: {
&quot;state&quot;: &quot;OPEN&quot;,
&quot;assignee&quot;: &quot;hoshikawa2&quot;
}
}</component>
<component name="GithubPullRequestsUISettings">{
&quot;selectedUrlAndAccountId&quot;: {
&quot;url&quot;: &quot;https://github.com/hoshikawa2/agent_platform_oci.git&quot;,
&quot;accountId&quot;: &quot;bd799ac0-7624-42b2-999a-b96e6e11f98a&quot;
}
}</component>
<component name="KubernetesApiPersistence">{}</component>
<component name="KubernetesApiProvider">{
&quot;isMigrated&quot;: true
}</component>
<component name="PhpWorkspaceProjectConfiguration" interpreter_name="PHP 8.1" />
<component name="ProjectCodeStyleSettingsMigration">
<option name="version" value="2" />
</component>
<component name="ProjectColorInfo">{
&quot;customColor&quot;: &quot;&quot;,
&quot;associatedIndex&quot;: 2
}</component>
<component name="ProjectId" id="3FQ8m21arbKaZKgqpTYDVjVGTBf" />
<component name="ProjectViewState">
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent"><![CDATA[{
"keyToString": {
"ASKED_SHARE_PROJECT_CONFIGURATION_FILES": "true",
"ModuleVcsDetector.initialDetectionPerformed": "true",
"RunOnceActivity.ShowReadmeOnStart": "true",
"RunOnceActivity.git.unshallow": "true",
"RunOnceActivity.typescript.service.memoryLimit.init": "true",
"SHARE_PROJECT_CONFIGURATION_FILES": "true",
"git-widget-placeholder": "master",
"kotlin-language-version-configured": "true",
"last_opened_file_path": "D:/Dropbox/ORACLE/TIM/FY27/Wave_2/Ajuste para manter o agente atual ou voltar ao roteamento/agent_framework_oci",
"node.js.detected.package.eslint": "true",
"node.js.detected.package.tslint": "true",
"node.js.selected.package.eslint": "(autodetect)",
"node.js.selected.package.tslint": "(autodetect)",
"nodejs_package_manager_path": "npm",
"settings.editor.selected.configurable": "configurable.group.appearance",
"vue.rearranger.settings.migration": "true"
}
}]]></component>
<component name="SharedIndexes">
<attachedChunks>
<set>
<option value="bundled-jdk-9823dce3aa75-fbdcb00ec9e3-intellij.indexing.shared.core-IU-251.29188.36" />
<option value="bundled-js-predefined-d6986cc7102b-09060db00ec0-JavaScript-IU-251.29188.36" />
</set>
</attachedChunks>
</component>
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<changelist id="30a0e1d8-9d7d-469b-b241-f300911cee8a" name="Changes" comment="" />
<created>1781996088468</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1781996088468</updated>
<workItem from="1781996091031" duration="1242000" />
<workItem from="1782038604623" duration="6486000" />
<workItem from="1782047166074" duration="27000" />
<workItem from="1782047194363" duration="961000" />
<workItem from="1782048494672" duration="230000" />
<workItem from="1782592218589" duration="28000" />
<workItem from="1785245181314" duration="79000" />
<workItem from="1785245608367" duration="670000" />
<workItem from="1785326458404" duration="86000" />
<workItem from="1785414225783" duration="148000" />
<workItem from="1785414447653" duration="704000" />
<workItem from="1785630146329" duration="316000" />
</task>
<task id="LOCAL-00001" summary="Ajustes na documentação e remanejamento dos folders">
<option name="closed" value="true" />
<created>1782045250014</created>
<option name="number" value="00001" />
<option name="presentableId" value="LOCAL-00001" />
<option name="project" value="LOCAL" />
<updated>1782045250014</updated>
</task>
<task id="LOCAL-00002" summary="Ajustes na documentação e remanejamento dos folders">
<option name="closed" value="true" />
<created>1782045265085</created>
<option name="number" value="00002" />
<option name="presentableId" value="LOCAL-00002" />
<option name="project" value="LOCAL" />
<updated>1782045265085</updated>
</task>
<task id="LOCAL-00003" summary="Ajustes na documentação e remanejamento dos folders">
<option name="closed" value="true" />
<created>1782048304579</created>
<option name="number" value="00003" />
<option name="presentableId" value="LOCAL-00003" />
<option name="project" value="LOCAL" />
<updated>1782048304579</updated>
</task>
<option name="localTasksCounter" value="4" />
<servers />
</component>
<component name="TypeScriptGeneratedFilesManager">
<option name="version" value="3" />
</component>
<component name="VcsManagerConfiguration">
<MESSAGE value="Ajustes na documentação e remanejamento dos folders" />
<option name="LAST_COMMIT_MESSAGE" value="Ajustes na documentação e remanejamento dos folders" />
</component>
</project>

View File

@@ -0,0 +1,64 @@
# Implementação — workflows transacionais determinísticos
## Entrega
Foi adicionada ao `agent_framework_oci` uma capacidade opcional para executar transações multi-etapas como workflows determinísticos compilados em LangGraph.
### Módulo novo
`libs/agent_framework/src/agent_framework/workflows/`
- `models.py`: contratos Pydantic e validação estrutural;
- `repository.py`: resolução de versão ativa e leitura de YAML imutável;
- `registry.py`: registro desacoplado de actions sync/async;
- `runtime.py`: compilação, cache e execução do StateGraph;
- `tool_executor.py`: integração com a política da tool;
- `__init__.py`: API pública.
### Política expandida
`ToolPolicy` agora aceita:
```yaml
execution:
mode: direct_tool | workflow | agent
workflow: nome_do_workflow
version: active | 1
```
O default permanece `direct_tool`, preservando compatibilidade.
### Configuração
Foram adicionados:
- `ENABLE_TRANSACTIONAL_WORKFLOWS=false`;
- `WORKFLOWS_PATH=./workflows`.
### Template
Inclui um exemplo completo de devolução de pedido com:
- confirmação e campos obrigatórios pela política;
- workflow YAML versionado;
- actions de domínio no backend;
- bifurcação determinística baseada no resultado da validação.
## Validação realizada
- `tests/unit/test_tool_policies.py`: 4 testes aprovados;
- compilação Python de framework, template e novos testes: aprovada;
- o teste funcional novo do LangGraph foi criado, mas não pôde ser executado neste container porque `langgraph` não está instalado no ambiente. A dependência já está declarada no `pyproject.toml` do framework.
## Escopo e segurança
Esta entrega cria o motor e a integração de política. Para operações críticas em produção ainda é necessário conectar:
- execution store persistente;
- idempotência de negócio nas actions/APIs;
- autorização por escopo;
- telemetria IC/NOC específica de workflow;
- compensação/Saga quando aplicável;
- estratégia corporativa de timeout e retry.
Esses itens foram explicitamente documentados para evitar a falsa impressão de que retry por si só garante segurança transacional.

View File

@@ -0,0 +1,987 @@
# Implementando Basic Auth
Para validar **todo o circuito com Basic Auth**, você precisa configurar três relações distintas:
```text
Cliente de teste
└─ Basic Auth A ─► Agent Gateway :8010
└─ Basic Auth B ─► Agent Backend :8000
└─ Basic Auth C ─► MCP Gateway :8300
```
Há um detalhe importante: no pacote atual, a autenticação Basic já funciona para chamadas **de entrada**, mas os clientes internos ainda não enviam Basic Auth:
* `Agent Gateway → Agent Backend` não envia credencial;
* `Agent Backend → MCP Gateway` envia apenas Bearer Token.
Portanto, para testar o circuito inteiro com Basic Auth, faça os dois pequenos ajustes de código descritos abaixo.
---
# 1. Preparar o ambiente
Considere que o ZIP foi extraído em:
```bash
cd agent_framework_oci_authentication_v2_1
```
Crie um único ambiente virtual para facilitar o teste:
```bash
python -m venv .venv
source .venv/bin/activate
```
No Windows PowerShell:
```powershell
python -m venv .venv
.\.venv\Scripts\Activate.ps1
```
Instale o framework e as dependências dos três componentes:
```bash
pip install -U pip
pip install -e ./libs/agent_framework
pip install \
-r ./Tuning-Performance/Authentication/agent_template_backend_authentication/requirements.txt \
-r ./apps/agent_gateway/requirements.txt \
-r ./apps/mcp_gateway/requirements.txt
```
Confirme a importação:
```bash
python -c "from agent_framework.security import install_authentication; print('framework ok')"
```
---
# 2. Criar três pares de Client ID e Secret
Use credenciais diferentes para cada trecho. Para teste local:
| Fluxo | Client ID | Secret de teste |
| ----------------------- | -------------------- | --------------------------- |
| Cliente → Agent Gateway | `tia-test` | `TiaGateway-Test-2026!` |
| Agent Gateway → Backend | `agent-gateway-test` | `GatewayBackend-Test-2026!` |
| Backend → MCP Gateway | `agent-backend-test` | `BackendMcp-Test-2026!` |
Esses valores são apenas para ambiente local. Não os reutilize em produção.
## Gerar os hashes
O script está em:
```text
Tuning-Performance/Authentication/
agent_template_backend_authentication/
scripts/generate_secret_hash.py
```
Execute:
```bash
python Tuning-Performance/Authentication/agent_template_backend_authentication/scripts/generate_secret_hash.py \
--secret 'TiaGateway-Test-2026!'
```
Depois:
```bash
python Tuning-Performance/Authentication/agent_template_backend_authentication/scripts/generate_secret_hash.py \
--secret 'GatewayBackend-Test-2026!'
```
E:
```bash
python Tuning-Performance/Authentication/agent_template_backend_authentication/scripts/generate_secret_hash.py \
--secret 'BackendMcp-Test-2026!'
```
Você receberá três valores semelhantes a:
```text
pbkdf2_sha256:310000:<salt>:<digest>
```
Guarde-os temporariamente:
```bash
HASH_CLIENT_GATEWAY='pbkdf2_sha256:310000:...'
HASH_GATEWAY_BACKEND='pbkdf2_sha256:310000:...'
HASH_BACKEND_MCP='pbkdf2_sha256:310000:...'
```
O hash muda a cada execução porque o salt é aleatório. Isso é esperado.
---
# 3. Configurar o Agent Gateway
Entre no diretório:
```bash
cd apps/agent_gateway
```
Copie o exemplo:
```bash
cp .env.example .env
```
Adicione ao final do `.env`:
```env
# Entrada: cliente/TIA -> Agent Gateway
AGENT_GATEWAY_AUTH_ENABLED=true
AGENT_GATEWAY_AUTH_MODE=basic
AGENT_GATEWAY_AUTH_BASIC_CLIENT_ID=tia-test
AGENT_GATEWAY_AUTH_BASIC_SECRET_HASH=COLE_AQUI_HASH_CLIENT_GATEWAY
AGENT_GATEWAY_AUTH_BASIC_REALM=agent-gateway
AGENT_GATEWAY_AUTH_PUBLIC_PATHS=/health,/docs,/openapi.json,/redoc
AGENT_GATEWAY_AUTH_PUBLIC_PREFIXES=
# Saída: Agent Gateway -> Agent Backend
BACKEND_AUTH_MODE=basic
BACKEND_AUTH_CLIENT_ID=agent-gateway-test
BACKEND_AUTH_SECRET=GatewayBackend-Test-2026!
```
Não coloque aspas no `.env`:
```env
BACKEND_AUTH_SECRET=GatewayBackend-Test-2026!
```
O arquivo de backends já aponta o backend Contas para:
```yaml
contas:
url: http://localhost:8000
```
Arquivo:
```text
apps/agent_gateway/config/backends.yaml
```
Para este teste, mantenha apenas o backend `contas` ou force o backend no payload. Caso contrário, pedidos sobre ofertas e suporte podem ser roteados para portas em que nenhum backend está rodando.
---
# 4. Fazer o Agent Gateway enviar Basic Auth ao backend
Abra:
```text
libs/agent_framework/src/agent_framework/global_supervisor/client.py
```
Substitua a classe `BackendClient` por uma versão que aceite autenticação Basic.
No início do arquivo, adicione:
```python
import os
```
Altere o construtor:
```python
class BackendClient:
def __init__(
self,
timeout_seconds: float = 120.0,
basic_client_id: str | None = None,
basic_secret: str | None = None,
):
self.timeout_seconds = timeout_seconds
self.basic_client_id = basic_client_id
self.basic_secret = basic_secret
def _auth(self) -> httpx.BasicAuth | None:
if self.basic_client_id and self.basic_secret:
return httpx.BasicAuth(
username=self.basic_client_id,
password=self.basic_secret,
)
return None
```
No método `call_message`, troque:
```python
resp = await client.post(url, json=payload)
```
por:
```python
resp = await client.post(
url,
json=payload,
auth=self._auth(),
)
```
No método `health`, você pode manter `/health` público. Caso queira enviar autenticação também, use:
```python
resp = await client.get(url, auth=self._auth())
```
Agora abra:
```text
apps/agent_gateway/app/main.py
```
Adicione:
```python
import os
```
Troque:
```python
backend_client = BackendClient(
timeout_seconds=settings.BACKEND_TIMEOUT_SECONDS
)
```
por:
```python
backend_client = BackendClient(
timeout_seconds=settings.BACKEND_TIMEOUT_SECONDS,
basic_client_id=os.getenv("BACKEND_AUTH_CLIENT_ID"),
basic_secret=os.getenv("BACKEND_AUTH_SECRET"),
)
```
Isso implementa:
```text
Agent Gateway → Agent Backend
Authorization: Basic base64(agent-gateway-test:GatewayBackend-Test-2026!)
```
---
# 5. Configurar o Agent Backend autenticado
Entre no diretório:
```bash
cd Tuning-Performance/Authentication/agent_template_backend_authentication
```
Copie o exemplo:
```bash
cp .env.example .env
```
Ajuste a seção de autenticação:
```env
# Entrada: Agent Gateway -> Agent Backend
AGENT_AUTH_ENABLED=true
AGENT_AUTH_MODE=basic
AGENT_AUTH_BASIC_CLIENT_ID=agent-gateway-test
AGENT_AUTH_BASIC_SECRET_HASH=COLE_AQUI_HASH_GATEWAY_BACKEND
AGENT_AUTH_BASIC_REALM=agent-contas
AGENT_AUTH_PUBLIC_PATHS=/health,/docs,/openapi.json,/redoc
AGENT_AUTH_PUBLIC_PREFIXES=
```
Para usar o MCP Gateway:
```env
MCP_GATEWAY_ENABLED=true
MCP_GATEWAY_URL=http://localhost:8300
MCP_GATEWAY_TIMEOUT_SECONDS=60
# Saída: Agent Backend -> MCP Gateway
MCP_GATEWAY_AUTH_MODE=basic
MCP_GATEWAY_BASIC_CLIENT_ID=agent-backend-test
MCP_GATEWAY_BASIC_SECRET=BackendMcp-Test-2026!
```
Para evitar dependências externas durante o primeiro teste, configure também:
```env
LLM_PROVIDER=mock
ENABLE_LANGFUSE=false
ENABLE_ANALYTICS=false
SESSION_REPOSITORY_PROVIDER=memory
MEMORY_REPOSITORY_PROVIDER=memory
CHECKPOINT_REPOSITORY_PROVIDER=memory
CACHE_PROVIDER=memory
USAGE_REPOSITORY_PROVIDER=memory
```
Os nomes exatos de alguns providers podem depender do arquivo de configuração atual do framework. Caso o `.env.example` já contenha valores locais ou mock, preserve-os.
---
# 6. Fazer o Backend enviar Basic Auth ao MCP Gateway
Abra:
```text
libs/agent_framework/src/agent_framework/gateways/mcp_gateway_client.py
```
Substitua a implementação por:
```python
from __future__ import annotations
import base64
from typing import Any
import httpx
class MCPGatewayClient:
def __init__(
self,
base_url: str,
token: str | None = None,
timeout_seconds: int = 60,
auth_mode: str | None = None,
basic_client_id: str | None = None,
basic_secret: str | None = None,
):
self.base_url = base_url.rstrip("/")
self.token = token
self.timeout_seconds = timeout_seconds
self.auth_mode = (auth_mode or "").strip().lower()
self.basic_client_id = basic_client_id
self.basic_secret = basic_secret
def _headers(self) -> dict[str, str]:
if (
self.auth_mode == "basic"
and self.basic_client_id
and self.basic_secret
):
raw = f"{self.basic_client_id}:{self.basic_secret}".encode("utf-8")
encoded = base64.b64encode(raw).decode("ascii")
return {"Authorization": f"Basic {encoded}"}
if self.token:
return {"Authorization": f"Bearer {self.token}"}
return {}
async def list_tools(self) -> dict[str, Any]:
async with httpx.AsyncClient(
timeout=self.timeout_seconds
) as client:
response = await client.get(
f"{self.base_url}/v1/tools",
headers=self._headers(),
)
response.raise_for_status()
return response.json()
async def invoke_tool(
self,
*,
tenant_id: str,
agent_id: str,
channel: str | None,
tool_name: str,
arguments: dict[str, Any] | None = None,
business_context: dict[str, Any] | None = None,
metadata: dict[str, Any] | None = None,
) -> dict[str, Any]:
payload = {
"tenant_id": tenant_id,
"agent_id": agent_id,
"channel": channel,
"tool_name": tool_name,
"arguments": arguments or {},
"business_context": business_context or {},
"metadata": metadata or {},
}
async with httpx.AsyncClient(
timeout=self.timeout_seconds
) as client:
response = await client.post(
f"{self.base_url}/v1/tools/{tool_name}/invoke",
json=payload,
headers=self._headers(),
)
response.raise_for_status()
return response.json()
```
Agora abra:
```text
libs/agent_framework/src/agent_framework/mcp/tool_router.py
```
Localize:
```python
MCPGatewayClient(
base_url=getattr(
settings,
"MCP_GATEWAY_URL",
"http://localhost:8300",
),
token=getattr(settings, "MCP_GATEWAY_TOKEN", None),
timeout_seconds=getattr(
settings,
"MCP_GATEWAY_TIMEOUT_SECONDS",
settings.MCP_TOOL_TIMEOUT_SECONDS,
),
)
```
Altere para:
```python
MCPGatewayClient(
base_url=getattr(
settings,
"MCP_GATEWAY_URL",
"http://localhost:8300",
),
token=getattr(settings, "MCP_GATEWAY_TOKEN", None),
timeout_seconds=getattr(
settings,
"MCP_GATEWAY_TIMEOUT_SECONDS",
settings.MCP_TOOL_TIMEOUT_SECONDS,
),
auth_mode=getattr(
settings,
"MCP_GATEWAY_AUTH_MODE",
None,
),
basic_client_id=getattr(
settings,
"MCP_GATEWAY_BASIC_CLIENT_ID",
None,
),
basic_secret=getattr(
settings,
"MCP_GATEWAY_BASIC_SECRET",
None,
),
)
```
Adicione estes campos em:
```text
libs/agent_framework/src/agent_framework/config/settings.py
```
Próximo das configurações existentes de MCP Gateway:
```python
MCP_GATEWAY_AUTH_MODE: str | None = None
MCP_GATEWAY_BASIC_CLIENT_ID: str | None = None
MCP_GATEWAY_BASIC_SECRET: str | None = None
```
Há também uma factory local em:
```text
Tuning-Performance/Authentication/
agent_template_backend_authentication/
app/mcp_gateway_client_factory.py
```
Ajuste para:
```python
from __future__ import annotations
import os
from agent_framework.gateways import MCPGatewayClient
def build_mcp_gateway_client() -> MCPGatewayClient | None:
if os.getenv("MCP_GATEWAY_ENABLED", "true").lower() != "true":
return None
return MCPGatewayClient(
base_url=os.getenv(
"MCP_GATEWAY_URL",
"http://localhost:8300",
),
token=os.getenv("MCP_GATEWAY_TOKEN") or None,
timeout_seconds=int(
os.getenv("MCP_GATEWAY_TIMEOUT_SECONDS", "60")
),
auth_mode=os.getenv("MCP_GATEWAY_AUTH_MODE"),
basic_client_id=os.getenv(
"MCP_GATEWAY_BASIC_CLIENT_ID"
),
basic_secret=os.getenv(
"MCP_GATEWAY_BASIC_SECRET"
),
)
```
---
# 7. Configurar o MCP Gateway
Entre no diretório:
```bash
cd apps/mcp_gateway
```
Crie `.env`:
```bash
cp .env.example .env
```
Adicione:
```env
# Entrada: Agent Backend -> MCP Gateway
MCP_GATEWAY_AUTH_ENABLED=true
MCP_GATEWAY_AUTH_MODE=basic
MCP_GATEWAY_AUTH_BASIC_CLIENT_ID=agent-backend-test
MCP_GATEWAY_AUTH_BASIC_SECRET_HASH=COLE_AQUI_HASH_BACKEND_MCP
MCP_GATEWAY_AUTH_BASIC_REALM=mcp-gateway
MCP_GATEWAY_AUTH_PUBLIC_PATHS=/health,/ready,/docs,/openapi.json,/redoc
MCP_GATEWAY_AUTH_PUBLIC_PREFIXES=
MCP_GATEWAY_CONFIG_PATH=config/mcp_gateway.yaml
```
## Desabilitar o mecanismo Bearer legado
O MCP Gateway ainda possui um segundo mecanismo antigo, configurado dentro de:
```text
apps/mcp_gateway/config/mcp_gateway.yaml
```
Localize a seção:
```yaml
auth:
enabled: true
```
Altere para:
```yaml
auth:
enabled: false
```
Isso é necessário porque o novo middleware já faz a autenticação Basic. Caso o `auth_check()` legado continue habilitado, a requisição passará pelo Basic e depois será rejeitada por não possuir Bearer Token.
---
# 8. Subir os componentes
Use quatro terminais.
## Terminal 1 — MCP Servers
O MCP Gateway precisa ter pelo menos um servidor MCP disponível para demonstrar uma chamada real.
Na raiz do projeto:
```bash
source .venv/bin/activate
```
Suba o servidor telecom:
```bash
uvicorn mcp.servers.telecom_mcp_server.main:app \
--host 0.0.0.0 \
--port 8100 \
--reload
```
Em outro terminal, caso queira também o retail:
```bash
uvicorn mcp.servers.retail_mcp_server.main:app \
--host 0.0.0.0 \
--port 8200 \
--reload
```
Confira as URLs configuradas em:
```text
apps/mcp_gateway/config/mcp_gateway.yaml
```
Para execução local, devem apontar para:
```yaml
url: http://localhost:8100
```
e:
```yaml
url: http://localhost:8200
```
---
## Terminal 2 — MCP Gateway
```bash
cd apps/mcp_gateway
source ../../.venv/bin/activate
```
Suba usando `--env-file`. Isso é importante porque o middleware lê variáveis com `os.getenv()`:
```bash
uvicorn app.main:app \
--host 0.0.0.0 \
--port 8300 \
--reload \
--env-file .env
```
Teste a saúde pública:
```bash
curl http://localhost:8300/health
```
Teste um endpoint protegido sem credencial:
```bash
curl -i http://localhost:8300/v1/tools
```
Esperado:
```text
HTTP/1.1 401 Unauthorized
```
Teste com Basic Auth:
```bash
curl -i \
-u 'agent-backend-test:BackendMcp-Test-2026!' \
http://localhost:8300/v1/tools
```
Esperado:
```text
HTTP/1.1 200 OK
```
---
## Terminal 3 — Agent Backend
```bash
cd Tuning-Performance/Authentication/agent_template_backend_authentication
source ../../../.venv/bin/activate
```
Suba:
```bash
uvicorn app.main:app \
--host 0.0.0.0 \
--port 8000 \
--reload \
--env-file .env
```
Teste saúde:
```bash
curl http://localhost:8000/health
```
Teste endpoint protegido sem credencial:
```bash
curl -i http://localhost:8000/agents
```
Esperado:
```text
HTTP/1.1 401 Unauthorized
```
Teste com a credencial usada pelo Agent Gateway:
```bash
curl -i \
-u 'agent-gateway-test:GatewayBackend-Test-2026!' \
http://localhost:8000/agents
```
Esperado:
```text
HTTP/1.1 200 OK
```
Teste mensagem diretamente:
```bash
curl -X POST http://localhost:8000/gateway/message \
-u 'agent-gateway-test:GatewayBackend-Test-2026!' \
-H 'Content-Type: application/json' \
-d '{
"channel": "web",
"agent_id": "telecom_contas",
"tenant_id": "default",
"payload": {
"text": "Quero consultar minha fatura",
"session_id": "teste-backend-001",
"user_id": "user-001",
"customer_id": "12345",
"message_id": "msg-001"
}
}'
```
---
## Terminal 4 — Agent Gateway
```bash
cd apps/agent_gateway
source ../../.venv/bin/activate
```
Suba:
```bash
uvicorn app.main:app \
--host 0.0.0.0 \
--port 8010 \
--reload \
--env-file .env
```
Teste saúde:
```bash
curl http://localhost:8010/health
```
Teste endpoint protegido sem credencial:
```bash
curl -i http://localhost:8010/backends
```
Esperado:
```text
HTTP/1.1 401 Unauthorized
```
Teste com a credencial externa:
```bash
curl -i \
-u 'tia-test:TiaGateway-Test-2026!' \
http://localhost:8010/backends
```
Esperado:
```text
HTTP/1.1 200 OK
```
---
# 9. Validar o circuito completo
Force o backend `contas` para evitar que o roteador selecione um backend não iniciado:
```bash
curl -X POST http://localhost:8010/gateway/message \
-u 'tia-test:TiaGateway-Test-2026!' \
-H 'Content-Type: application/json' \
-d '{
"channel": "web",
"backend_id": "contas",
"tenant_id": "default",
"agent_id": "telecom_contas",
"session_id": "circuito-basic-001",
"payload": {
"text": "Quero consultar minha fatura",
"session_id": "circuito-basic-001",
"user_id": "user-001",
"customer_id": "12345",
"message_id": "msg-circuito-001"
}
}'
```
O circuito esperado é:
```text
curl
│ Basic tia-test
Agent Gateway :8010
│ Basic agent-gateway-test
Agent Backend :8000
│ Basic agent-backend-test
MCP Gateway :8300
MCP Server :8100 ou :8200
```
---
# 10. Como comprovar cada autenticação
Faça testes negativos em cada trecho.
## Secret externo incorreto
```bash
curl -i \
-u 'tia-test:senha-errada' \
http://localhost:8010/backends
```
Resultado esperado:
```text
401 Unauthorized
```
## Secret do gateway para backend incorreto
Altere temporariamente no `apps/agent_gateway/.env`:
```env
BACKEND_AUTH_SECRET=senha-errada
```
Reinicie o Agent Gateway e envie uma mensagem.
O gateway deverá retornar erro de backend, normalmente:
```text
502 Bad Gateway
```
O erro interno será originado por um:
```text
401 Unauthorized
```
do Agent Backend.
## Secret do backend para MCP incorreto
Altere temporariamente:
```env
MCP_GATEWAY_BASIC_SECRET=senha-errada
```
Reinicie o backend e execute uma frase que acione uma ferramenta MCP.
O backend deverá registrar falha na chamada ao MCP Gateway com:
```text
401 Unauthorized
```
---
# 11. Verificação rápida de portas
No Linux ou WSL:
```bash
ss -lntp | grep -E ':8000|:8010|:8100|:8200|:8300'
```
No Windows PowerShell:
```powershell
Get-NetTCPConnection -State Listen |
Where-Object LocalPort -in 8000,8010,8100,8200,8300 |
Sort-Object LocalPort
```
Você deverá ver:
```text
8000 Agent Backend
8010 Agent Gateway
8100 Telecom MCP Server
8200 Retail MCP Server
8300 MCP Gateway
```
## Observação importante
O segredo original precisa existir no componente cliente:
```text
TIA ou curl:
TiaGateway-Test-2026!
Agent Gateway:
GatewayBackend-Test-2026!
Agent Backend:
BackendMcp-Test-2026!
```
Os componentes servidores armazenam apenas os hashes:
```text
Agent Gateway:
hash de TiaGateway-Test-2026!
Agent Backend:
hash de GatewayBackend-Test-2026!
MCP Gateway:
hash de BackendMcp-Test-2026!
```
Em produção, os segredos originais e hashes devem vir de Vault ou Kubernetes Secret, não de arquivos `.env`.

View File

@@ -3,5 +3,8 @@ from __future__ import annotations
# Compatibilidade local do template/backend. # Compatibilidade local do template/backend.
# A implementação oficial agora fica no framework para evitar duplicação entre agentes. # A implementação oficial agora fica no framework para evitar duplicação entre agentes.
from agent_framework.runtime import AgentRuntimeMixin, MessageBuilder, RuntimeContext from agent_framework.runtime import AgentRuntimeMixin, MessageBuilder, RuntimeContext
from app.presentation import register_tool_renderers
register_tool_renderers()
__all__ = ["AgentRuntimeMixin", "MessageBuilder", "RuntimeContext"] __all__ = ["AgentRuntimeMixin", "MessageBuilder", "RuntimeContext"]

View File

@@ -0,0 +1,3 @@
from .tool_renderers import register_tool_renderers
__all__ = ["register_tool_renderers"]

View File

@@ -0,0 +1,74 @@
from __future__ import annotations
from typing import Any
from agent_framework.presentation import register_tool_response_renderer
def _money_brl(value: Any) -> str:
try:
return f"{float(value):.2f}".replace(".", ",")
except (TypeError, ValueError):
return str(value)
def render_telecom_invoice(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None:
return f"[{agent_label}] Fatura consultada: {result}."
def render_telecom_plan(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None:
plano = result.get("plano")
if plano is None:
return None
parts = [f"[{agent_label}] Seu plano é {plano}"]
internet_gb = result.get("internet_gb")
status = result.get("status")
if internet_gb is not None:
parts.append(f"com {internet_gb} GB")
if status is not None:
parts.append(f"status {status}")
return ", ".join(parts) + "."
def render_retail_order(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None:
order_id = result.get("order_id")
status = result.get("status")
if order_id is None or status is None:
return None
lines = [f"[{agent_label}] Pedido {order_id}: status {status}."]
total = result.get("valor_total")
if total is not None:
lines.append(f"Valor total: R$ {_money_brl(total)}.")
items = result.get("itens") or []
rendered_items: list[str] = []
if isinstance(items, list):
for item in items:
if isinstance(item, dict):
value = item.get("descricao") or item.get("nome") or item.get("sku")
else:
value = item
if value not in (None, ""):
rendered_items.append(str(value))
if rendered_items:
lines.append("Itens: " + "; ".join(rendered_items) + ".")
return " ".join(lines)
def render_retail_delivery(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None:
order_id = result.get("order_id")
transportadora = result.get("transportadora")
codigo = result.get("codigo_rastreio")
previsao = result.get("previsao_entrega")
if any(v is None for v in (order_id, transportadora, codigo, previsao)):
return None
return (
f"[{agent_label}] Entrega do pedido {order_id}: transportadora {transportadora}, "
f"rastreio {codigo}, previsão {previsao}."
)
def register_tool_renderers() -> None:
register_tool_response_renderer("telecom.invoice", render_telecom_invoice)
register_tool_response_renderer("telecom.plan", render_telecom_plan)
register_tool_response_renderer("retail.order", render_retail_order)
register_tool_response_renderer("retail.delivery", render_retail_delivery)

View File

@@ -60,6 +60,18 @@ mcp_parameter_mapping:
mensagem. mensagem.
pattern: (?i)\\b(?:pedido|order)\\s*[:#-]?\\s*([A-Z0-9-]+)\\b pattern: (?i)\\b(?:pedido|order)\\s*[:#-]?\\s*([A-Z0-9-]+)\\b
group: 1 group: 1
cancelar_pedido:
map:
session_key: session_id
extract:
order_id:
from: message
type: string
strategy: hybrid
description: Extraia somente o identificador do pedido informado explicitamente pelo usuário. Retorne null quando não houver identificador de pedido na mensagem.
pattern: (?i)\\b(?:pedido|order)\\s*[:#-]?\\s*([A-Z0-9-]+)\\b
group: 1
solicitar_troca: solicitar_troca:
map: map:
session_key: session_id session_key: session_id

View File

@@ -79,6 +79,25 @@ intents:
- Quero saber sobre meu pacote de internet. - Quero saber sobre meu pacote de internet.
- Tenho roaming internacional? - Tenho roaming internacional?
- name: retail_order_cancel
domain: retail
agent: orders_agent
description: Cancelamento explícito de pedido ou compra.
priority: 20
mcp_tools:
- consultar_pedido
- cancelar_pedido
keywords:
- cancelar pedido
- cancelamento do pedido
- cancelar a compra
- cancelar compra
examples:
- Quero cancelar meu pedido.
- Cancele o pedido.
- Quero cancelar a compra.
- name: retail_order_tracking - name: retail_order_tracking
domain: retail domain: retail
agent: orders_agent agent: orders_agent

View File

@@ -7,6 +7,12 @@ defaults:
require_confirmation: false require_confirmation: false
tool_policies: tool_policies:
cancelar_pedido:
operation_type: transactional
require_confirmation: true
requires: [order_id]
solicitar_troca: solicitar_troca:
operation_type: transactional operation_type: transactional
require_confirmation: true require_confirmation: true

View File

@@ -10,6 +10,9 @@ tools:
- fatura - fatura
- conta - conta
- boleto - boleto
response:
mode: renderer
renderer: telecom.invoice
consultar_pagamentos: consultar_pagamentos:
description: Consulta histórico de pagamentos do cliente. description: Consulta histórico de pagamentos do cliente.
mcp_server: telecom mcp_server: telecom
@@ -28,6 +31,9 @@ tools:
asset_id: string asset_id: string
selection_keywords: selection_keywords:
- plano - plano
response:
mode: renderer
renderer: telecom.plan
listar_servicos: listar_servicos:
description: Lista serviços ativos e adicionais VAS. description: Lista serviços ativos e adicionais VAS.
mcp_server: telecom mcp_server: telecom
@@ -49,6 +55,9 @@ tools:
- consultar pedido - consultar pedido
- status do pedido - status do pedido
- pedido - pedido
response:
mode: renderer
renderer: retail.order
consultar_entrega: consultar_entrega:
description: Consulta entrega e rastreamento do pedido. description: Consulta entrega e rastreamento do pedido.
mcp_server: retail mcp_server: retail
@@ -61,6 +70,26 @@ tools:
- rastreamento - rastreamento
- transportadora - transportadora
- previsão - previsão
response:
mode: renderer
renderer: retail.delivery
cancelar_pedido:
description: Simula o cancelamento de um pedido de varejo.
mcp_server: retail
enabled: true
tool_type: action
requires:
- order_id
confirmation_required: true
args_schema:
order_id: string
selection_keywords:
- cancelar pedido
- cancelamento do pedido
- cancelar compra
- cancelar a compra
solicitar_troca: solicitar_troca:
description: Simula abertura de solicitação de troca. description: Simula abertura de solicitação de troca.
mcp_server: retail mcp_server: retail

View File

@@ -0,0 +1,3 @@
from .tool_renderers import register_tool_renderers
__all__ = ["register_tool_renderers"]

View File

@@ -0,0 +1,74 @@
from __future__ import annotations
from typing import Any
from agent_framework.presentation import register_tool_response_renderer
def _money_brl(value: Any) -> str:
try:
return f"{float(value):.2f}".replace(".", ",")
except (TypeError, ValueError):
return str(value)
def render_telecom_invoice(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None:
return f"[{agent_label}] Fatura consultada: {result}."
def render_telecom_plan(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None:
plano = result.get("plano")
if plano is None:
return None
parts = [f"[{agent_label}] Seu plano é {plano}"]
internet_gb = result.get("internet_gb")
status = result.get("status")
if internet_gb is not None:
parts.append(f"com {internet_gb} GB")
if status is not None:
parts.append(f"status {status}")
return ", ".join(parts) + "."
def render_retail_order(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None:
order_id = result.get("order_id")
status = result.get("status")
if order_id is None or status is None:
return None
lines = [f"[{agent_label}] Pedido {order_id}: status {status}."]
total = result.get("valor_total")
if total is not None:
lines.append(f"Valor total: R$ {_money_brl(total)}.")
items = result.get("itens") or []
rendered_items: list[str] = []
if isinstance(items, list):
for item in items:
if isinstance(item, dict):
value = item.get("descricao") or item.get("nome") or item.get("sku")
else:
value = item
if value not in (None, ""):
rendered_items.append(str(value))
if rendered_items:
lines.append("Itens: " + "; ".join(rendered_items) + ".")
return " ".join(lines)
def render_retail_delivery(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None:
order_id = result.get("order_id")
transportadora = result.get("transportadora")
codigo = result.get("codigo_rastreio")
previsao = result.get("previsao_entrega")
if any(v is None for v in (order_id, transportadora, codigo, previsao)):
return None
return (
f"[{agent_label}] Entrega do pedido {order_id}: transportadora {transportadora}, "
f"rastreio {codigo}, previsão {previsao}."
)
def register_tool_renderers() -> None:
register_tool_response_renderer("telecom.invoice", render_telecom_invoice)
register_tool_response_renderer("telecom.plan", render_telecom_plan)
register_tool_response_renderer("retail.order", render_retail_order)
register_tool_response_renderer("retail.delivery", render_retail_delivery)

View File

@@ -60,6 +60,18 @@ mcp_parameter_mapping:
mensagem. mensagem.
pattern: (?i)\\b(?:pedido|order)\\s*[:#-]?\\s*([A-Z0-9-]+)\\b pattern: (?i)\\b(?:pedido|order)\\s*[:#-]?\\s*([A-Z0-9-]+)\\b
group: 1 group: 1
cancelar_pedido:
map:
session_key: session_id
extract:
order_id:
from: message
type: string
strategy: hybrid
description: Extraia somente o identificador do pedido informado explicitamente pelo usuário. Retorne null quando não houver identificador de pedido na mensagem.
pattern: (?i)\\b(?:pedido|order)\\s*[:#-]?\\s*([A-Z0-9-]+)\\b
group: 1
solicitar_troca: solicitar_troca:
map: map:
session_key: session_id session_key: session_id

View File

@@ -79,6 +79,25 @@ intents:
- Quero saber sobre meu pacote de internet. - Quero saber sobre meu pacote de internet.
- Tenho roaming internacional? - Tenho roaming internacional?
- name: retail_order_cancel
domain: retail
agent: orders_agent
description: Cancelamento explícito de pedido ou compra.
priority: 20
mcp_tools:
- consultar_pedido
- cancelar_pedido
keywords:
- cancelar pedido
- cancelamento do pedido
- cancelar a compra
- cancelar compra
examples:
- Quero cancelar meu pedido.
- Cancele o pedido.
- Quero cancelar a compra.
- name: retail_order_tracking - name: retail_order_tracking
domain: retail domain: retail
agent: orders_agent agent: orders_agent

View File

@@ -7,6 +7,12 @@ defaults:
require_confirmation: false require_confirmation: false
tool_policies: tool_policies:
cancelar_pedido:
operation_type: transactional
require_confirmation: true
requires: [order_id]
solicitar_troca: solicitar_troca:
operation_type: transactional operation_type: transactional
require_confirmation: true require_confirmation: true

View File

@@ -10,6 +10,9 @@ tools:
- fatura - fatura
- conta - conta
- boleto - boleto
response:
mode: renderer
renderer: telecom.invoice
consultar_pagamentos: consultar_pagamentos:
description: Consulta histórico de pagamentos do cliente. description: Consulta histórico de pagamentos do cliente.
mcp_server: telecom mcp_server: telecom
@@ -28,6 +31,9 @@ tools:
asset_id: string asset_id: string
selection_keywords: selection_keywords:
- plano - plano
response:
mode: renderer
renderer: telecom.plan
listar_servicos: listar_servicos:
description: Lista serviços ativos e adicionais VAS. description: Lista serviços ativos e adicionais VAS.
mcp_server: telecom mcp_server: telecom
@@ -49,6 +55,9 @@ tools:
- consultar pedido - consultar pedido
- status do pedido - status do pedido
- pedido - pedido
response:
mode: renderer
renderer: retail.order
consultar_entrega: consultar_entrega:
description: Consulta entrega e rastreamento do pedido. description: Consulta entrega e rastreamento do pedido.
mcp_server: retail mcp_server: retail
@@ -61,6 +70,26 @@ tools:
- rastreamento - rastreamento
- transportadora - transportadora
- previsão - previsão
response:
mode: renderer
renderer: retail.delivery
cancelar_pedido:
description: Simula o cancelamento de um pedido de varejo.
mcp_server: retail
enabled: true
tool_type: action
requires:
- order_id
confirmation_required: true
args_schema:
order_id: string
selection_keywords:
- cancelar pedido
- cancelamento do pedido
- cancelar compra
- cancelar a compra
solicitar_troca: solicitar_troca:
description: Simula abertura de solicitação de troca. description: Simula abertura de solicitação de troca.
mcp_server: retail mcp_server: retail

View File

@@ -3,5 +3,8 @@ from __future__ import annotations
# Compatibilidade local do template/backend. # Compatibilidade local do template/backend.
# A implementação oficial agora fica no framework para evitar duplicação entre agentes. # A implementação oficial agora fica no framework para evitar duplicação entre agentes.
from agent_framework.runtime import AgentRuntimeMixin, MessageBuilder, RuntimeContext from agent_framework.runtime import AgentRuntimeMixin, MessageBuilder, RuntimeContext
from app.presentation import register_tool_renderers
register_tool_renderers()
__all__ = ["AgentRuntimeMixin", "MessageBuilder", "RuntimeContext"] __all__ = ["AgentRuntimeMixin", "MessageBuilder", "RuntimeContext"]

View File

@@ -0,0 +1,3 @@
from .tool_renderers import register_tool_renderers
__all__ = ["register_tool_renderers"]

View File

@@ -0,0 +1,74 @@
from __future__ import annotations
from typing import Any
from agent_framework.presentation import register_tool_response_renderer
def _money_brl(value: Any) -> str:
try:
return f"{float(value):.2f}".replace(".", ",")
except (TypeError, ValueError):
return str(value)
def render_telecom_invoice(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None:
return f"[{agent_label}] Fatura consultada: {result}."
def render_telecom_plan(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None:
plano = result.get("plano")
if plano is None:
return None
parts = [f"[{agent_label}] Seu plano é {plano}"]
internet_gb = result.get("internet_gb")
status = result.get("status")
if internet_gb is not None:
parts.append(f"com {internet_gb} GB")
if status is not None:
parts.append(f"status {status}")
return ", ".join(parts) + "."
def render_retail_order(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None:
order_id = result.get("order_id")
status = result.get("status")
if order_id is None or status is None:
return None
lines = [f"[{agent_label}] Pedido {order_id}: status {status}."]
total = result.get("valor_total")
if total is not None:
lines.append(f"Valor total: R$ {_money_brl(total)}.")
items = result.get("itens") or []
rendered_items: list[str] = []
if isinstance(items, list):
for item in items:
if isinstance(item, dict):
value = item.get("descricao") or item.get("nome") or item.get("sku")
else:
value = item
if value not in (None, ""):
rendered_items.append(str(value))
if rendered_items:
lines.append("Itens: " + "; ".join(rendered_items) + ".")
return " ".join(lines)
def render_retail_delivery(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None:
order_id = result.get("order_id")
transportadora = result.get("transportadora")
codigo = result.get("codigo_rastreio")
previsao = result.get("previsao_entrega")
if any(v is None for v in (order_id, transportadora, codigo, previsao)):
return None
return (
f"[{agent_label}] Entrega do pedido {order_id}: transportadora {transportadora}, "
f"rastreio {codigo}, previsão {previsao}."
)
def register_tool_renderers() -> None:
register_tool_response_renderer("telecom.invoice", render_telecom_invoice)
register_tool_response_renderer("telecom.plan", render_telecom_plan)
register_tool_response_renderer("retail.order", render_retail_order)
register_tool_response_renderer("retail.delivery", render_retail_delivery)

View File

@@ -60,6 +60,18 @@ mcp_parameter_mapping:
mensagem. mensagem.
pattern: (?i)\\b(?:pedido|order)\\s*[:#-]?\\s*([A-Z0-9-]+)\\b pattern: (?i)\\b(?:pedido|order)\\s*[:#-]?\\s*([A-Z0-9-]+)\\b
group: 1 group: 1
cancelar_pedido:
map:
session_key: session_id
extract:
order_id:
from: message
type: string
strategy: hybrid
description: Extraia somente o identificador do pedido informado explicitamente pelo usuário. Retorne null quando não houver identificador de pedido na mensagem.
pattern: (?i)\\b(?:pedido|order)\\s*[:#-]?\\s*([A-Z0-9-]+)\\b
group: 1
solicitar_troca: solicitar_troca:
map: map:
session_key: session_id session_key: session_id

View File

@@ -79,6 +79,25 @@ intents:
- Quero saber sobre meu pacote de internet. - Quero saber sobre meu pacote de internet.
- Tenho roaming internacional? - Tenho roaming internacional?
- name: retail_order_cancel
domain: retail
agent: orders_agent
description: Cancelamento explícito de pedido ou compra.
priority: 20
mcp_tools:
- consultar_pedido
- cancelar_pedido
keywords:
- cancelar pedido
- cancelamento do pedido
- cancelar a compra
- cancelar compra
examples:
- Quero cancelar meu pedido.
- Cancele o pedido.
- Quero cancelar a compra.
- name: retail_order_tracking - name: retail_order_tracking
domain: retail domain: retail
agent: orders_agent agent: orders_agent

View File

@@ -7,6 +7,12 @@ defaults:
require_confirmation: false require_confirmation: false
tool_policies: tool_policies:
cancelar_pedido:
operation_type: transactional
require_confirmation: true
requires: [order_id]
solicitar_troca: solicitar_troca:
operation_type: transactional operation_type: transactional
require_confirmation: true require_confirmation: true

View File

@@ -10,6 +10,9 @@ tools:
- fatura - fatura
- conta - conta
- boleto - boleto
response:
mode: renderer
renderer: telecom.invoice
consultar_pagamentos: consultar_pagamentos:
description: Consulta histórico de pagamentos do cliente. description: Consulta histórico de pagamentos do cliente.
mcp_server: telecom mcp_server: telecom
@@ -28,6 +31,9 @@ tools:
asset_id: string asset_id: string
selection_keywords: selection_keywords:
- plano - plano
response:
mode: renderer
renderer: telecom.plan
listar_servicos: listar_servicos:
description: Lista serviços ativos e adicionais VAS. description: Lista serviços ativos e adicionais VAS.
mcp_server: telecom mcp_server: telecom
@@ -49,6 +55,9 @@ tools:
- consultar pedido - consultar pedido
- status do pedido - status do pedido
- pedido - pedido
response:
mode: renderer
renderer: retail.order
consultar_entrega: consultar_entrega:
description: Consulta entrega e rastreamento do pedido. description: Consulta entrega e rastreamento do pedido.
mcp_server: retail mcp_server: retail
@@ -61,6 +70,26 @@ tools:
- rastreamento - rastreamento
- transportadora - transportadora
- previsão - previsão
response:
mode: renderer
renderer: retail.delivery
cancelar_pedido:
description: Simula o cancelamento de um pedido de varejo.
mcp_server: retail
enabled: true
tool_type: action
requires:
- order_id
confirmation_required: true
args_schema:
order_id: string
selection_keywords:
- cancelar pedido
- cancelamento do pedido
- cancelar compra
- cancelar a compra
solicitar_troca: solicitar_troca:
description: Simula abertura de solicitação de troca. description: Simula abertura de solicitação de troca.
mcp_server: retail mcp_server: retail

View File

@@ -3,5 +3,8 @@ from __future__ import annotations
# Compatibilidade local do template/backend. # Compatibilidade local do template/backend.
# A implementação oficial agora fica no framework para evitar duplicação entre agentes. # A implementação oficial agora fica no framework para evitar duplicação entre agentes.
from agent_framework.runtime import AgentRuntimeMixin, MessageBuilder, RuntimeContext from agent_framework.runtime import AgentRuntimeMixin, MessageBuilder, RuntimeContext
from app.presentation import register_tool_renderers
register_tool_renderers()
__all__ = ["AgentRuntimeMixin", "MessageBuilder", "RuntimeContext"] __all__ = ["AgentRuntimeMixin", "MessageBuilder", "RuntimeContext"]

View File

@@ -0,0 +1,3 @@
from .tool_renderers import register_tool_renderers
__all__ = ["register_tool_renderers"]

View File

@@ -0,0 +1,74 @@
from __future__ import annotations
from typing import Any
from agent_framework.presentation import register_tool_response_renderer
def _money_brl(value: Any) -> str:
try:
return f"{float(value):.2f}".replace(".", ",")
except (TypeError, ValueError):
return str(value)
def render_telecom_invoice(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None:
return f"[{agent_label}] Fatura consultada: {result}."
def render_telecom_plan(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None:
plano = result.get("plano")
if plano is None:
return None
parts = [f"[{agent_label}] Seu plano é {plano}"]
internet_gb = result.get("internet_gb")
status = result.get("status")
if internet_gb is not None:
parts.append(f"com {internet_gb} GB")
if status is not None:
parts.append(f"status {status}")
return ", ".join(parts) + "."
def render_retail_order(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None:
order_id = result.get("order_id")
status = result.get("status")
if order_id is None or status is None:
return None
lines = [f"[{agent_label}] Pedido {order_id}: status {status}."]
total = result.get("valor_total")
if total is not None:
lines.append(f"Valor total: R$ {_money_brl(total)}.")
items = result.get("itens") or []
rendered_items: list[str] = []
if isinstance(items, list):
for item in items:
if isinstance(item, dict):
value = item.get("descricao") or item.get("nome") or item.get("sku")
else:
value = item
if value not in (None, ""):
rendered_items.append(str(value))
if rendered_items:
lines.append("Itens: " + "; ".join(rendered_items) + ".")
return " ".join(lines)
def render_retail_delivery(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None:
order_id = result.get("order_id")
transportadora = result.get("transportadora")
codigo = result.get("codigo_rastreio")
previsao = result.get("previsao_entrega")
if any(v is None for v in (order_id, transportadora, codigo, previsao)):
return None
return (
f"[{agent_label}] Entrega do pedido {order_id}: transportadora {transportadora}, "
f"rastreio {codigo}, previsão {previsao}."
)
def register_tool_renderers() -> None:
register_tool_response_renderer("telecom.invoice", render_telecom_invoice)
register_tool_response_renderer("telecom.plan", render_telecom_plan)
register_tool_response_renderer("retail.order", render_retail_order)
register_tool_response_renderer("retail.delivery", render_retail_delivery)

View File

@@ -60,6 +60,18 @@ mcp_parameter_mapping:
mensagem. mensagem.
pattern: (?i)\\b(?:pedido|order)\\s*[:#-]?\\s*([A-Z0-9-]+)\\b pattern: (?i)\\b(?:pedido|order)\\s*[:#-]?\\s*([A-Z0-9-]+)\\b
group: 1 group: 1
cancelar_pedido:
map:
session_key: session_id
extract:
order_id:
from: message
type: string
strategy: hybrid
description: Extraia somente o identificador do pedido informado explicitamente pelo usuário. Retorne null quando não houver identificador de pedido na mensagem.
pattern: (?i)\\b(?:pedido|order)\\s*[:#-]?\\s*([A-Z0-9-]+)\\b
group: 1
solicitar_troca: solicitar_troca:
map: map:
session_key: session_id session_key: session_id

View File

@@ -79,6 +79,25 @@ intents:
- Quero saber sobre meu pacote de internet. - Quero saber sobre meu pacote de internet.
- Tenho roaming internacional? - Tenho roaming internacional?
- name: retail_order_cancel
domain: retail
agent: orders_agent
description: Cancelamento explícito de pedido ou compra.
priority: 20
mcp_tools:
- consultar_pedido
- cancelar_pedido
keywords:
- cancelar pedido
- cancelamento do pedido
- cancelar a compra
- cancelar compra
examples:
- Quero cancelar meu pedido.
- Cancele o pedido.
- Quero cancelar a compra.
- name: retail_order_tracking - name: retail_order_tracking
domain: retail domain: retail
agent: orders_agent agent: orders_agent

View File

@@ -7,6 +7,12 @@ defaults:
require_confirmation: false require_confirmation: false
tool_policies: tool_policies:
cancelar_pedido:
operation_type: transactional
require_confirmation: true
requires: [order_id]
solicitar_troca: solicitar_troca:
operation_type: transactional operation_type: transactional
require_confirmation: true require_confirmation: true

View File

@@ -10,6 +10,9 @@ tools:
- fatura - fatura
- conta - conta
- boleto - boleto
response:
mode: renderer
renderer: telecom.invoice
consultar_pagamentos: consultar_pagamentos:
description: Consulta histórico de pagamentos do cliente. description: Consulta histórico de pagamentos do cliente.
mcp_server: telecom mcp_server: telecom
@@ -28,6 +31,9 @@ tools:
asset_id: string asset_id: string
selection_keywords: selection_keywords:
- plano - plano
response:
mode: renderer
renderer: telecom.plan
listar_servicos: listar_servicos:
description: Lista serviços ativos e adicionais VAS. description: Lista serviços ativos e adicionais VAS.
mcp_server: telecom mcp_server: telecom
@@ -49,6 +55,9 @@ tools:
- consultar pedido - consultar pedido
- status do pedido - status do pedido
- pedido - pedido
response:
mode: renderer
renderer: retail.order
consultar_entrega: consultar_entrega:
description: Consulta entrega e rastreamento do pedido. description: Consulta entrega e rastreamento do pedido.
mcp_server: retail mcp_server: retail
@@ -61,6 +70,26 @@ tools:
- rastreamento - rastreamento
- transportadora - transportadora
- previsão - previsão
response:
mode: renderer
renderer: retail.delivery
cancelar_pedido:
description: Simula o cancelamento de um pedido de varejo.
mcp_server: retail
enabled: true
tool_type: action
requires:
- order_id
confirmation_required: true
args_schema:
order_id: string
selection_keywords:
- cancelar pedido
- cancelamento do pedido
- cancelar compra
- cancelar a compra
solicitar_troca: solicitar_troca:
description: Simula abertura de solicitação de troca. description: Simula abertura de solicitação de troca.
mcp_server: retail mcp_server: retail

View File

@@ -60,6 +60,18 @@ mcp_parameter_mapping:
mensagem. mensagem.
pattern: (?i)\\b(?:pedido|order)\\s*[:#-]?\\s*([A-Z0-9-]+)\\b pattern: (?i)\\b(?:pedido|order)\\s*[:#-]?\\s*([A-Z0-9-]+)\\b
group: 1 group: 1
cancelar_pedido:
map:
session_key: session_id
extract:
order_id:
from: message
type: string
strategy: hybrid
description: Extraia somente o identificador do pedido informado explicitamente pelo usuário. Retorne null quando não houver identificador de pedido na mensagem.
pattern: (?i)\\b(?:pedido|order)\\s*[:#-]?\\s*([A-Z0-9-]+)\\b
group: 1
solicitar_troca: solicitar_troca:
map: map:
session_key: session_id session_key: session_id

View File

@@ -79,6 +79,25 @@ intents:
- Quero saber sobre meu pacote de internet. - Quero saber sobre meu pacote de internet.
- Tenho roaming internacional? - Tenho roaming internacional?
- name: retail_order_cancel
domain: retail
agent: orders_agent
description: Cancelamento explícito de pedido ou compra.
priority: 20
mcp_tools:
- consultar_pedido
- cancelar_pedido
keywords:
- cancelar pedido
- cancelamento do pedido
- cancelar a compra
- cancelar compra
examples:
- Quero cancelar meu pedido.
- Cancele o pedido.
- Quero cancelar a compra.
- name: retail_order_tracking - name: retail_order_tracking
domain: retail domain: retail
agent: orders_agent agent: orders_agent

View File

@@ -7,6 +7,12 @@ defaults:
require_confirmation: false require_confirmation: false
tool_policies: tool_policies:
cancelar_pedido:
operation_type: transactional
require_confirmation: true
requires: [order_id]
solicitar_troca: solicitar_troca:
operation_type: transactional operation_type: transactional
require_confirmation: true require_confirmation: true

View File

@@ -61,6 +61,23 @@ tools:
- rastreamento - rastreamento
- transportadora - transportadora
- previsão - previsão
cancelar_pedido:
description: Simula o cancelamento de um pedido de varejo.
mcp_server: retail
enabled: true
tool_type: action
requires:
- order_id
confirmation_required: true
args_schema:
order_id: string
selection_keywords:
- cancelar pedido
- cancelamento do pedido
- cancelar compra
- cancelar a compra
solicitar_troca: solicitar_troca:
description: Simula abertura de solicitação de troca. description: Simula abertura de solicitação de troca.
mcp_server: retail mcp_server: retail

View File

@@ -2,7 +2,7 @@
O backend de produção de `WorkflowRuntime` continua sendo **LangGraph**. A ausência do pacote `langgraph` em produção é erro de configuração. O backend de produção de `WorkflowRuntime` continua sendo **LangGraph**. A ausência do pacote `langgraph` em produção é erro de configuração.
Para builders restritos/offline, o runtime aceita `allow_deterministic_fallback=True`. Esse modo é deliberadamente opt-in e existe somente para exercitar a DSL do framework (actions, edges, condições, pause/resume e trace) de forma reproduzível em testes offline/regressão. Quando `allow_deterministic_fallback=True`, o backend determinístico é selecionado explicitamente mesmo que LangGraph esteja instalado. Ele nunca é selecionado automaticamente em produção. Para builders restritos/offline, o runtime aceita `allow_deterministic_fallback=True`. Esse modo é deliberadamente opt-in e existe somente para exercitar a DSL do framework (actions, edges, condições, pause/resume e trace) quando a dependência externa não pode ser instalada. Ele não é selecionado automaticamente.
Exemplo de teste: Exemplo de teste:

View File

@@ -3,5 +3,8 @@ from __future__ import annotations
# Compatibilidade local do template/backend. # Compatibilidade local do template/backend.
# A implementação oficial agora fica no framework para evitar duplicação entre agentes. # A implementação oficial agora fica no framework para evitar duplicação entre agentes.
from agent_framework.runtime import AgentRuntimeMixin, MessageBuilder, RuntimeContext from agent_framework.runtime import AgentRuntimeMixin, MessageBuilder, RuntimeContext
from app.presentation import register_tool_renderers
register_tool_renderers()
__all__ = ["AgentRuntimeMixin", "MessageBuilder", "RuntimeContext"] __all__ = ["AgentRuntimeMixin", "MessageBuilder", "RuntimeContext"]

View File

@@ -0,0 +1,3 @@
from .tool_renderers import register_tool_renderers
__all__ = ["register_tool_renderers"]

View File

@@ -0,0 +1,74 @@
from __future__ import annotations
from typing import Any
from agent_framework.presentation import register_tool_response_renderer
def _money_brl(value: Any) -> str:
try:
return f"{float(value):.2f}".replace(".", ",")
except (TypeError, ValueError):
return str(value)
def render_telecom_invoice(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None:
return f"[{agent_label}] Fatura consultada: {result}."
def render_telecom_plan(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None:
plano = result.get("plano")
if plano is None:
return None
parts = [f"[{agent_label}] Seu plano é {plano}"]
internet_gb = result.get("internet_gb")
status = result.get("status")
if internet_gb is not None:
parts.append(f"com {internet_gb} GB")
if status is not None:
parts.append(f"status {status}")
return ", ".join(parts) + "."
def render_retail_order(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None:
order_id = result.get("order_id")
status = result.get("status")
if order_id is None or status is None:
return None
lines = [f"[{agent_label}] Pedido {order_id}: status {status}."]
total = result.get("valor_total")
if total is not None:
lines.append(f"Valor total: R$ {_money_brl(total)}.")
items = result.get("itens") or []
rendered_items: list[str] = []
if isinstance(items, list):
for item in items:
if isinstance(item, dict):
value = item.get("descricao") or item.get("nome") or item.get("sku")
else:
value = item
if value not in (None, ""):
rendered_items.append(str(value))
if rendered_items:
lines.append("Itens: " + "; ".join(rendered_items) + ".")
return " ".join(lines)
def render_retail_delivery(*, tool_name: str, result: dict[str, Any], state: dict[str, Any], agent_label: str) -> str | None:
order_id = result.get("order_id")
transportadora = result.get("transportadora")
codigo = result.get("codigo_rastreio")
previsao = result.get("previsao_entrega")
if any(v is None for v in (order_id, transportadora, codigo, previsao)):
return None
return (
f"[{agent_label}] Entrega do pedido {order_id}: transportadora {transportadora}, "
f"rastreio {codigo}, previsão {previsao}."
)
def register_tool_renderers() -> None:
register_tool_response_renderer("telecom.invoice", render_telecom_invoice)
register_tool_response_renderer("telecom.plan", render_telecom_plan)
register_tool_response_renderer("retail.order", render_retail_order)
register_tool_response_renderer("retail.delivery", render_retail_delivery)

View File

@@ -60,6 +60,18 @@ mcp_parameter_mapping:
mensagem. mensagem.
pattern: (?i)\\b(?:pedido|order)\\s*[:#-]?\\s*([A-Z0-9-]+)\\b pattern: (?i)\\b(?:pedido|order)\\s*[:#-]?\\s*([A-Z0-9-]+)\\b
group: 1 group: 1
cancelar_pedido:
map:
session_key: session_id
extract:
order_id:
from: message
type: string
strategy: hybrid
description: Extraia somente o identificador do pedido informado explicitamente pelo usuário. Retorne null quando não houver identificador de pedido na mensagem.
pattern: (?i)\\b(?:pedido|order)\\s*[:#-]?\\s*([A-Z0-9-]+)\\b
group: 1
solicitar_troca: solicitar_troca:
map: map:
session_key: session_id session_key: session_id

View File

@@ -79,6 +79,25 @@ intents:
- Quero saber sobre meu pacote de internet. - Quero saber sobre meu pacote de internet.
- Tenho roaming internacional? - Tenho roaming internacional?
- name: retail_order_cancel
domain: retail
agent: orders_agent
description: Cancelamento explícito de pedido ou compra.
priority: 20
mcp_tools:
- consultar_pedido
- cancelar_pedido
keywords:
- cancelar pedido
- cancelamento do pedido
- cancelar a compra
- cancelar compra
examples:
- Quero cancelar meu pedido.
- Cancele o pedido.
- Quero cancelar a compra.
- name: retail_order_tracking - name: retail_order_tracking
domain: retail domain: retail
agent: orders_agent agent: orders_agent

View File

@@ -7,6 +7,12 @@ defaults:
require_confirmation: false require_confirmation: false
tool_policies: tool_policies:
cancelar_pedido:
operation_type: transactional
require_confirmation: true
requires: [order_id]
solicitar_troca: solicitar_troca:
operation_type: transactional operation_type: transactional
require_confirmation: true require_confirmation: true

View File

@@ -10,6 +10,9 @@ tools:
- fatura - fatura
- conta - conta
- boleto - boleto
response:
mode: renderer
renderer: telecom.invoice
consultar_pagamentos: consultar_pagamentos:
description: Consulta histórico de pagamentos do cliente. description: Consulta histórico de pagamentos do cliente.
mcp_server: telecom mcp_server: telecom
@@ -28,6 +31,9 @@ tools:
asset_id: string asset_id: string
selection_keywords: selection_keywords:
- plano - plano
response:
mode: renderer
renderer: telecom.plan
listar_servicos: listar_servicos:
description: Lista serviços ativos e adicionais VAS. description: Lista serviços ativos e adicionais VAS.
mcp_server: telecom mcp_server: telecom
@@ -49,6 +55,9 @@ tools:
- consultar pedido - consultar pedido
- status do pedido - status do pedido
- pedido - pedido
response:
mode: renderer
renderer: retail.order
consultar_entrega: consultar_entrega:
description: Consulta entrega e rastreamento do pedido. description: Consulta entrega e rastreamento do pedido.
mcp_server: retail mcp_server: retail
@@ -61,6 +70,26 @@ tools:
- rastreamento - rastreamento
- transportadora - transportadora
- previsão - previsão
response:
mode: renderer
renderer: retail.delivery
cancelar_pedido:
description: Simula o cancelamento de um pedido de varejo.
mcp_server: retail
enabled: true
tool_type: action
requires:
- order_id
confirmation_required: true
args_schema:
order_id: string
selection_keywords:
- cancelar pedido
- cancelamento do pedido
- cancelar compra
- cancelar a compra
solicitar_troca: solicitar_troca:
description: Simula abertura de solicitação de troca. description: Simula abertura de solicitação de troca.
mcp_server: retail mcp_server: retail

View File

@@ -60,6 +60,18 @@ mcp_parameter_mapping:
mensagem. mensagem.
pattern: (?i)\\b(?:pedido|order)\\s*[:#-]?\\s*([A-Z0-9-]+)\\b pattern: (?i)\\b(?:pedido|order)\\s*[:#-]?\\s*([A-Z0-9-]+)\\b
group: 1 group: 1
cancelar_pedido:
map:
session_key: session_id
extract:
order_id:
from: message
type: string
strategy: hybrid
description: Extraia somente o identificador do pedido informado explicitamente pelo usuário. Retorne null quando não houver identificador de pedido na mensagem.
pattern: (?i)\\b(?:pedido|order)\\s*[:#-]?\\s*([A-Z0-9-]+)\\b
group: 1
solicitar_troca: solicitar_troca:
map: map:
session_key: session_id session_key: session_id

View File

@@ -79,6 +79,25 @@ intents:
- Quero saber sobre meu pacote de internet. - Quero saber sobre meu pacote de internet.
- Tenho roaming internacional? - Tenho roaming internacional?
- name: retail_order_cancel
domain: retail
agent: orders_agent
description: Cancelamento explícito de pedido ou compra.
priority: 20
mcp_tools:
- consultar_pedido
- cancelar_pedido
keywords:
- cancelar pedido
- cancelamento do pedido
- cancelar a compra
- cancelar compra
examples:
- Quero cancelar meu pedido.
- Cancele o pedido.
- Quero cancelar a compra.
- name: retail_order_tracking - name: retail_order_tracking
domain: retail domain: retail
agent: orders_agent agent: orders_agent

View File

@@ -7,6 +7,12 @@ defaults:
require_confirmation: false require_confirmation: false
tool_policies: tool_policies:
cancelar_pedido:
operation_type: transactional
require_confirmation: true
requires: [order_id]
solicitar_troca: solicitar_troca:
operation_type: transactional operation_type: transactional
require_confirmation: true require_confirmation: true

View File

@@ -61,6 +61,23 @@ tools:
- rastreamento - rastreamento
- transportadora - transportadora
- previsão - previsão
cancelar_pedido:
description: Simula o cancelamento de um pedido de varejo.
mcp_server: retail
enabled: true
tool_type: action
requires:
- order_id
confirmation_required: true
args_schema:
order_id: string
selection_keywords:
- cancelar pedido
- cancelamento do pedido
- cancelar compra
- cancelar a compra
solicitar_troca: solicitar_troca:
description: Simula abertura de solicitação de troca. description: Simula abertura de solicitação de troca.
mcp_server: retail mcp_server: retail

View File

@@ -0,0 +1,165 @@
# Autenticação / Authentication
> Feature do `agent_framework_oci` — guia bilíngue PT-BR / EN.
**Implementação principal / Main implementation:** `security/authentication.py`
---
## Português (PT-BR)
### 1. O que é
Verifica quem pode acessar APIs, gateways e serviços protegidos antes que a requisição chegue ao agente.
### 2. Problema que resolve
Em agentes de produção, não é suficiente pedir ao LLM que “faça a coisa certa”. Esta feature move uma responsabilidade específica para uma camada controlada do framework, reduzindo comportamento imprevisível e código duplicado nos agentes de domínio.
### 3. Fluxo simplificado
```text
Cliente/Sistema
Authentication Provider
credencial válida?
├─ não → 401/nega acesso
└─ sim → principal autenticado → agente
```
### 4. Como funciona internamente
O framework contém uma abstração `AuthenticationProvider` e implementações para cenários diferentes. Entre as implementações atuais estão `NoAuthenticationProvider`, `DenyAuthenticationProvider`, `BasicAuthenticationProvider`, `ApiKeyAuthenticationProvider`, `StaticBearerAuthenticationProvider`, `JwtAuthenticationProvider`, `OAuth2IntrospectionAuthenticationProvider` e `TrustedProxyAuthenticationProvider`.
A autenticação produz um `AuthenticatedPrincipal` com `subject`, `scheme` e, quando aplicável, `claims`. A regra de negócio do agente não deve validar senha/token diretamente.
### 5. Como ativar/configurar
A ativação exata depende do template/agente. Verifique o arquivo de settings, YAMLs de configuração e o template usado pelo serviço. Nem toda feature precisa de uma flag global: algumas são ativadas pelo contrato retornado por uma tool/workflow.
### 6. Exemplo
```python
from agent_framework.security.authentication import BasicAuthenticationProvider
provider = BasicAuthenticationProvider(
client_id="client-a",
secret_hash="pbkdf2_sha256:...",
)
result = await provider.authenticate(request)
if not result.authenticated:
# negar acesso
...
```
Segredos podem ser verificados em formato simples, SHA-256 ou PBKDF2; em produção, prefira hashes fortes e secret stores.
### 7. Telemetria e observabilidade
Quando a feature participa de uma execução de agente, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id` e demais chaves de correlação no estado/eventos. Isso permite acompanhar a decisão no Langfuse/Observer sem colocar lógica de observabilidade dentro do domínio.
### 8. Como testar
1. Crie um teste unitário do comportamento principal.
2. Crie um teste de integração do runtime quando houver estado entre turns.
3. Verifique o caso feliz e pelo menos um caso de falha/negação.
4. Confirme que não há side effects duplicados em retry/replay quando a feature toca transações.
5. Em produção, valide também telemetria e correlação de IDs.
### 9. Erros comuns
- Basic auth retornando 401: validar `Authorization: Basic ...` e o secret configurado.
- Confundir autenticação do usuário com `OCI_AUTH_MODE`: são problemas diferentes.
- Usar `NoAuthenticationProvider` em produção sem decisão explícita de arquitetura.
### 10. Relação com outras features
Esta feature deve ser usada junto das demais capacidades horizontais do framework, em vez de criar uma implementação paralela no agente de domínio. Em fluxos transacionais, considere especialmente **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery** e **Guardrails**.
### 11. Referências no repositório
- `libs/agent_framework/src/agent_framework/security/authentication.py`
- `Tuning-Performance/`
- `Documentacao/`
- `libs/agent_framework/docs/`
---
## English (EN)
### 1. What it is
Checks who may access protected APIs, gateways, and services before the request reaches the agent.
### 2. Problem it solves
Production agents should not rely on prompts alone to “do the right thing”. This feature moves a specific responsibility into a controlled framework layer, reducing unpredictable behavior and duplicate domain-agent code.
### 3. Simplified flow
```text
Client/System
Authentication Provider
valid credential?
├─ no → 401/deny
└─ yes → authenticated principal → agent
```
### 4. How it works internally
The framework exposes an `AuthenticationProvider` abstraction with multiple implementations. Current providers include `NoAuthenticationProvider`, `DenyAuthenticationProvider`, `BasicAuthenticationProvider`, `ApiKeyAuthenticationProvider`, `StaticBearerAuthenticationProvider`, `JwtAuthenticationProvider`, `OAuth2IntrospectionAuthenticationProvider`, and `TrustedProxyAuthenticationProvider`.
Authentication produces an `AuthenticatedPrincipal` containing `subject`, `scheme`, and optional `claims`. Domain code should not validate credentials directly.
### 5. How to enable/configure
Exact activation depends on the template/agent. Check framework settings, YAML configuration, and the service template. Not every feature requires a global flag: some are activated by the contract returned from a tool/workflow.
### 6. Example
```python
from agent_framework.security.authentication import BasicAuthenticationProvider
provider = BasicAuthenticationProvider(
client_id="client-a",
secret_hash="pbkdf2_sha256:...",
)
result = await provider.authenticate(request)
if not result.authenticated:
# deny access
...
```
Secrets may be verified as plain, SHA-256, or PBKDF2 values; for production, prefer strong hashes and managed secret stores.
### 7. Telemetry and observability
When the feature participates in an agent execution, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id`, and other correlation keys in state/events. This makes the decision observable through Langfuse/Observer without embedding observability logic in the domain.
### 8. How to test
1. Add a unit test for the core behavior.
2. Add a runtime integration test when state spans multiple turns.
3. Test the happy path and at least one failure/rejection path.
4. Confirm retries/replays do not duplicate side effects for transactional features.
5. In production, also validate telemetry and ID correlation.
### 9. Common mistakes
- Basic auth returns 401: validate the `Authorization: Basic ...` header and configured secret.
- Do not confuse API authentication with `OCI_AUTH_MODE`; they solve different problems.
- Avoid `NoAuthenticationProvider` in production unless explicitly accepted by architecture.
### 10. Relationship with other features
Use this feature together with the framework's horizontal capabilities rather than creating a parallel implementation in domain-agent code. For transactional journeys, pay special attention to **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery**, and **Guardrails**.
### 11. Repository references
- `libs/agent_framework/src/agent_framework/security/authentication.py`
- `Tuning-Performance/`
- `Documentacao/`
- `libs/agent_framework/docs/`

View File

@@ -0,0 +1,183 @@
# Workflow Transacional Determinístico / Deterministic Transactional Workflow
> Feature do `agent_framework_oci` — guia bilíngue PT-BR / EN.
**Implementação principal / Main implementation:** `workflows/runtime.py + mcp/tool_policy.py`
---
## Português (PT-BR)
### 1. O que é
Garante que operações que alteram estado sigam passos previsíveis, com confirmação e controle de execução, em vez de depender da criatividade do LLM.
### 2. Problema que resolve
Em agentes de produção, não é suficiente pedir ao LLM que “faça a coisa certa”. Esta feature move uma responsabilidade específica para uma camada controlada do framework, reduzindo comportamento imprevisível e código duplicado nos agentes de domínio.
### 3. Fluxo simplificado
```text
Mensagem do cliente
LLM entende intenção
Tool policy = transactional
Workflow determinístico
confirmação
execução controlada
resultado
```
### 4. Como funciona internamente
O LLM pode ajudar a interpretar a intenção e extrair parâmetros, mas não deve decidir a sequência crítica de uma transação. O `ToolPolicyRegistry` classifica tools, e `operation_type: transactional` ativa a política transacional. O `WorkflowRuntime` executa o workflow, mantém estado e integra pause/resume e recuperação de erro.
A configuração `ENABLE_TRANSACTIONAL_WORKFLOWS` controla a capability global, e `WORKFLOWS_PATH` aponta para os YAMLs.
### 5. Como ativar/configurar
A ativação exata depende do template/agente. Verifique o arquivo de settings, YAMLs de configuração e o template usado pelo serviço. Nem toda feature precisa de uma flag global: algumas são ativadas pelo contrato retornado por uma tool/workflow.
### 6. Exemplo
```yaml
tools:
cancelar_servico:
operation_type: transactional
requires_confirmation: true
```
```text
1. localizar serviço
2. validar elegibilidade
3. pedir confirmação
4. PAUSE
5. receber confirmação
6. RESUME
7. executar side effect
```
### 7. Telemetria e observabilidade
Quando a feature participa de uma execução de agente, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id` e demais chaves de correlação no estado/eventos. Isso permite acompanhar a decisão no Langfuse/Observer sem colocar lógica de observabilidade dentro do domínio.
### 8. Como testar
1. Crie um teste unitário do comportamento principal.
2. Crie um teste de integração do runtime quando houver estado entre turns.
3. Verifique o caso feliz e pelo menos um caso de falha/negação.
4. Confirme que não há side effects duplicados em retry/replay quando a feature toca transações.
5. Em produção, valide também telemetria e correlação de IDs.
### 9. Erros comuns
- Marcar uma tool de escrita como `read_only` elimina proteções transacionais.
- Reexecutar steps anteriores ao pause pode duplicar side effects; use o runtime oficial.
- Não use prompt como única garantia de confirmação.
### 10. Relação com outras features
Esta feature deve ser usada junto das demais capacidades horizontais do framework, em vez de criar uma implementação paralela no agente de domínio. Em fluxos transacionais, considere especialmente **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery** e **Guardrails**.
### 11. Referências no repositório
- `libs/agent_framework/src/agent_framework/workflows/runtime.py`
- `libs/agent_framework/src/agent_framework/mcp/tool_policy.py`
- `Tuning-Performance/`
- `Documentacao/`
- `libs/agent_framework/docs/`
---
## English (EN)
### 1. What it is
Ensures state-changing operations follow predictable steps with confirmation and execution control instead of depending on LLM creativity.
### 2. Problem it solves
Production agents should not rely on prompts alone to “do the right thing”. This feature moves a specific responsibility into a controlled framework layer, reducing unpredictable behavior and duplicate domain-agent code.
### 3. Simplified flow
```text
Customer message
LLM understands intent
Tool policy = transactional
Deterministic workflow
confirmation
controlled execution
result
```
### 4. How it works internally
The LLM may help interpret intent and extract parameters, but it should not decide the critical sequence of a transaction. `ToolPolicyRegistry` classifies tools, and `operation_type: transactional` activates transactional behavior. `WorkflowRuntime` executes the workflow, preserves state, and integrates pause/resume and error recovery.
`ENABLE_TRANSACTIONAL_WORKFLOWS` controls the capability globally, while `WORKFLOWS_PATH` points to workflow YAML files.
### 5. How to enable/configure
Exact activation depends on the template/agent. Check framework settings, YAML configuration, and the service template. Not every feature requires a global flag: some are activated by the contract returned from a tool/workflow.
### 6. Example
```yaml
tools:
cancel_service:
operation_type: transactional
requires_confirmation: true
```
```text
1. locate service
2. validate eligibility
3. ask for confirmation
4. PAUSE
5. receive confirmation
6. RESUME
7. execute side effect
```
### 7. Telemetry and observability
When the feature participates in an agent execution, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id`, and other correlation keys in state/events. This makes the decision observable through Langfuse/Observer without embedding observability logic in the domain.
### 8. How to test
1. Add a unit test for the core behavior.
2. Add a runtime integration test when state spans multiple turns.
3. Test the happy path and at least one failure/rejection path.
4. Confirm retries/replays do not duplicate side effects for transactional features.
5. In production, also validate telemetry and ID correlation.
### 9. Common mistakes
- Marking a write tool as `read_only` bypasses transactional protections.
- Re-running steps before a pause can duplicate side effects; use the official runtime.
- Do not use prompts as the only confirmation guarantee.
### 10. Relationship with other features
Use this feature together with the framework's horizontal capabilities rather than creating a parallel implementation in domain-agent code. For transactional journeys, pay special attention to **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery**, and **Guardrails**.
### 11. Repository references
- `libs/agent_framework/src/agent_framework/workflows/runtime.py`
- `libs/agent_framework/src/agent_framework/mcp/tool_policy.py`
- `Tuning-Performance/`
- `Documentacao/`
- `libs/agent_framework/docs/`

View File

@@ -0,0 +1,157 @@
# Composição por LLM Solicitada pelo Domínio / Domain Requested LLM Composition
> Feature do `agent_framework_oci` — guia bilíngue PT-BR / EN.
**Implementação principal / Main implementation:** `runtime/agent_runtime.py`
---
## Português (PT-BR)
### 1. O que é
Permite que a regra de negócio calcule o resultado e peça ao LLM apenas para redigir a resposta final.
### 2. Problema que resolve
Em agentes de produção, não é suficiente pedir ao LLM que “faça a coisa certa”. Esta feature move uma responsabilidade específica para uma camada controlada do framework, reduzindo comportamento imprevisível e código duplicado nos agentes de domínio.
### 3. Fluxo simplificado
```text
Regra de negócio calcula
requires_llm_composition=true
framework impede resposta MCP direta
LLMProvider oficial
redação natural
```
### 4. Como funciona internamente
O domínio retorna dados confiáveis e uma instrução de composição. O `AgentRuntimeMixin` detecta `requires_llm_composition` de forma recursiva no resultado da tool/workflow e não encerra a resposta pelo caminho direto de MCP. A composição segue pelo LLM oficial do agente, preservando profiles, tracing, usage e políticas do framework.
O LLM deve redigir; ele não deve recalcular valores nem decidir regras de negócio já resolvidas.
### 5. Como ativar/configurar
A ativação exata depende do template/agente. Verifique o arquivo de settings, YAMLs de configuração e o template usado pelo serviço. Nem toda feature precisa de uma flag global: algumas são ativadas pelo contrato retornado por uma tool/workflow.
### 6. Exemplo
```json
{
"success": true,
"refund_amount": "38,00",
"requires_llm_composition": true,
"response_instruction": "Explique a devolução usando somente os valores calculados."
}
```
### 7. Telemetria e observabilidade
Quando a feature participa de uma execução de agente, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id` e demais chaves de correlação no estado/eventos. Isso permite acompanhar a decisão no Langfuse/Observer sem colocar lógica de observabilidade dentro do domínio.
### 8. Como testar
1. Crie um teste unitário do comportamento principal.
2. Crie um teste de integração do runtime quando houver estado entre turns.
3. Verifique o caso feliz e pelo menos um caso de falha/negação.
4. Confirme que não há side effects duplicados em retry/replay quando a feature toca transações.
5. Em produção, valide também telemetria e correlação de IDs.
### 9. Erros comuns
- Instrução muito aberta pode fazer o LLM adicionar conteúdo não autorizado.
- Não envie ao LLM a responsabilidade de recalcular valores determinísticos.
- Se não houver necessidade de redação livre, prefira resposta determinística direta.
### 10. Relação com outras features
Esta feature deve ser usada junto das demais capacidades horizontais do framework, em vez de criar uma implementação paralela no agente de domínio. Em fluxos transacionais, considere especialmente **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery** e **Guardrails**.
### 11. Referências no repositório
- `libs/agent_framework/src/agent_framework/runtime/agent_runtime.py`
- `Tuning-Performance/`
- `Documentacao/`
- `libs/agent_framework/docs/`
---
## English (EN)
### 1. What it is
Lets domain logic compute the authoritative result and ask the LLM only to compose the final user-facing response.
### 2. Problem it solves
Production agents should not rely on prompts alone to “do the right thing”. This feature moves a specific responsibility into a controlled framework layer, reducing unpredictable behavior and duplicate domain-agent code.
### 3. Simplified flow
```text
Domain logic computes
requires_llm_composition=true
framework prevents direct MCP answer
official LLMProvider
natural-language response
```
### 4. How it works internally
The domain returns authoritative data plus a composition instruction. `AgentRuntimeMixin` recursively detects `requires_llm_composition` in tool/workflow results and avoids terminating through the direct MCP-answer path. Composition then uses the agent's official LLM provider, preserving profiles, tracing, usage accounting, and framework policies.
The LLM should compose language, not recalculate values or override already-resolved business rules.
### 5. How to enable/configure
Exact activation depends on the template/agent. Check framework settings, YAML configuration, and the service template. Not every feature requires a global flag: some are activated by the contract returned from a tool/workflow.
### 6. Example
```json
{
"success": true,
"refund_amount": "38.00",
"requires_llm_composition": true,
"response_instruction": "Explain the refund using only the computed values."
}
```
### 7. Telemetry and observability
When the feature participates in an agent execution, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id`, and other correlation keys in state/events. This makes the decision observable through Langfuse/Observer without embedding observability logic in the domain.
### 8. How to test
1. Add a unit test for the core behavior.
2. Add a runtime integration test when state spans multiple turns.
3. Test the happy path and at least one failure/rejection path.
4. Confirm retries/replays do not duplicate side effects for transactional features.
5. In production, also validate telemetry and ID correlation.
### 9. Common mistakes
- An overly broad instruction may let the LLM add unauthorized content.
- Do not delegate deterministic calculations back to the LLM.
- If free-form wording is unnecessary, prefer a deterministic direct response.
### 10. Relationship with other features
Use this feature together with the framework's horizontal capabilities rather than creating a parallel implementation in domain-agent code. For transactional journeys, pay special attention to **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery**, and **Guardrails**.
### 11. Repository references
- `libs/agent_framework/src/agent_framework/runtime/agent_runtime.py`
- `Tuning-Performance/`
- `Documentacao/`
- `libs/agent_framework/docs/`

View File

@@ -0,0 +1,167 @@
# RAG Solicitado pelo Domínio / Domain Requested RAG
> Feature do `agent_framework_oci` — guia bilíngue PT-BR / EN.
**Implementação principal / Main implementation:** `runtime/agent_runtime.py`
---
## Português (PT-BR)
### 1. O que é
Permite que uma tool ou workflow declare que a resposta precisa consultar conhecimento externo, mesmo quando já existe resultado MCP.
### 2. Problema que resolve
Em agentes de produção, não é suficiente pedir ao LLM que “faça a coisa certa”. Esta feature move uma responsabilidade específica para uma camada controlada do framework, reduzindo comportamento imprevisível e código duplicado nos agentes de domínio.
### 3. Fluxo simplificado
```text
Tool/Workflow
requires_rag=true
rag_query / rag_queries
RagService do framework
Retrieval Guardrails
LLM/resposta
```
### 4. Como funciona internamente
Normalmente o framework pode pular RAG quando MCP já trouxe informação suficiente (`SKIP_RAG_WHEN_MCP_SUFFICIENT`). Esta feature permite que o domínio substitua essa decisão para um caso específico. O resultado pode declarar `requires_rag`, `rag_query` ou `rag_queries`; o runtime usa essas queries como override e executa o `RagService`.
O domínio informa **o que precisa saber**. Ele não implementa cliente de vetor, retriever ou prompt RAG paralelo.
### 5. Como ativar/configurar
A ativação exata depende do template/agente. Verifique o arquivo de settings, YAMLs de configuração e o template usado pelo serviço. Nem toda feature precisa de uma flag global: algumas são ativadas pelo contrato retornado por uma tool/workflow.
### 6. Exemplo
```json
{
"requires_rag": true,
"rag_queries": [
"Como cancelar YouTube Premium?",
"Como cancelar Aya Books?"
]
}
```
Configurações relacionadas incluem `RAG_TOP_K` e `SKIP_RAG_WHEN_MCP_SUFFICIENT`.
### 7. Telemetria e observabilidade
Quando a feature participa de uma execução de agente, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id` e demais chaves de correlação no estado/eventos. Isso permite acompanhar a decisão no Langfuse/Observer sem colocar lógica de observabilidade dentro do domínio.
### 8. Como testar
1. Crie um teste unitário do comportamento principal.
2. Crie um teste de integração do runtime quando houver estado entre turns.
3. Verifique o caso feliz e pelo menos um caso de falha/negação.
4. Confirme que não há side effects duplicados em retry/replay quando a feature toca transações.
5. Em produção, valide também telemetria e correlação de IDs.
### 9. Erros comuns
- Declarar RAG para fatos transacionais já resolvidos pela API pode aumentar custo e latência.
- Query genérica demais reduz relevância.
- Nunca confie no retrieval sem `Retrieval Guardrails` quando o dado influencia resposta crítica.
### 10. Relação com outras features
Esta feature deve ser usada junto das demais capacidades horizontais do framework, em vez de criar uma implementação paralela no agente de domínio. Em fluxos transacionais, considere especialmente **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery** e **Guardrails**.
### 11. Referências no repositório
- `libs/agent_framework/src/agent_framework/runtime/agent_runtime.py`
- `Tuning-Performance/`
- `Documentacao/`
- `libs/agent_framework/docs/`
---
## English (EN)
### 1. What it is
Allows a tool or workflow to declare that external knowledge retrieval is required even when an MCP result already exists.
### 2. Problem it solves
Production agents should not rely on prompts alone to “do the right thing”. This feature moves a specific responsibility into a controlled framework layer, reducing unpredictable behavior and duplicate domain-agent code.
### 3. Simplified flow
```text
Tool/Workflow
requires_rag=true
rag_query / rag_queries
framework RagService
Retrieval Guardrails
LLM/response
```
### 4. How it works internally
Normally the framework may skip RAG when MCP already provides sufficient data (`SKIP_RAG_WHEN_MCP_SUFFICIENT`). This feature lets the domain override that decision for a specific case. A result may declare `requires_rag`, `rag_query`, or `rag_queries`; the runtime uses those queries as overrides and invokes `RagService`.
The domain declares **what knowledge is needed**. It does not implement its own vector client, retriever, or parallel RAG prompt stack.
### 5. How to enable/configure
Exact activation depends on the template/agent. Check framework settings, YAML configuration, and the service template. Not every feature requires a global flag: some are activated by the contract returned from a tool/workflow.
### 6. Example
```json
{
"requires_rag": true,
"rag_queries": [
"How to cancel YouTube Premium?",
"How to cancel Aya Books?"
]
}
```
Related settings include `RAG_TOP_K` and `SKIP_RAG_WHEN_MCP_SUFFICIENT`.
### 7. Telemetry and observability
When the feature participates in an agent execution, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id`, and other correlation keys in state/events. This makes the decision observable through Langfuse/Observer without embedding observability logic in the domain.
### 8. How to test
1. Add a unit test for the core behavior.
2. Add a runtime integration test when state spans multiple turns.
3. Test the happy path and at least one failure/rejection path.
4. Confirm retries/replays do not duplicate side effects for transactional features.
5. In production, also validate telemetry and ID correlation.
### 9. Common mistakes
- Requesting RAG for transactional facts already resolved by an API adds unnecessary cost and latency.
- Queries that are too broad reduce relevance.
- Do not trust retrieved content for critical responses without Retrieval Guardrails.
### 10. Relationship with other features
Use this feature together with the framework's horizontal capabilities rather than creating a parallel implementation in domain-agent code. For transactional journeys, pay special attention to **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery**, and **Guardrails**.
### 11. Repository references
- `libs/agent_framework/src/agent_framework/runtime/agent_runtime.py`
- `Tuning-Performance/`
- `Documentacao/`
- `libs/agent_framework/docs/`

View File

@@ -0,0 +1,167 @@
# Memória de Longo Prazo / Long Term Memory
> Feature do `agent_framework_oci` — guia bilíngue PT-BR / EN.
**Implementação principal / Main implementation:** `memory/long_term_memory.py + memory/long_term_store.py`
---
## Português (PT-BR)
### 1. O que é
Permite lembrar informações úteis entre sessões diferentes, sem depender do histórico completo de uma conversa.
### 2. Problema que resolve
Em agentes de produção, não é suficiente pedir ao LLM que “faça a coisa certa”. Esta feature move uma responsabilidade específica para uma camada controlada do framework, reduzindo comportamento imprevisível e código duplicado nos agentes de domínio.
### 3. Fluxo simplificado
```text
Sessão A
extração de memória relevante
Long Term Memory Store
... dias depois ...
Sessão B
recupera contexto relevante
agente
```
### 4. Como funciona internamente
A memória de longo prazo é diferente de histórico de mensagens e de checkpoint. Ela persiste fatos/preferências úteis e os recupera como contexto de uma nova sessão. O framework oferece providers `memory`, `sqlite`, `autonomous` e `oracle`.
Configurações importantes: `ENABLE_LONG_TERM_MEMORY`, `LONG_TERM_MEMORY_PROVIDER`, `LONG_TERM_MEMORY_MAX_CONTEXT_ITEMS`, `LONG_TERM_MEMORY_MIN_CONFIDENCE`, `LONG_TERM_MEMORY_AUTO_EXTRACT` e `LONG_TERM_MEMORY_INJECT_CONTEXT`.
### 5. Como ativar/configurar
A ativação exata depende do template/agente. Verifique o arquivo de settings, YAMLs de configuração e o template usado pelo serviço. Nem toda feature precisa de uma flag global: algumas são ativadas pelo contrato retornado por uma tool/workflow.
### 6. Exemplo
```env
ENABLE_LONG_TERM_MEMORY=true
LONG_TERM_MEMORY_PROVIDER=oracle
LONG_TERM_MEMORY_MAX_CONTEXT_ITEMS=20
LONG_TERM_MEMORY_MIN_CONFIDENCE=0.70
LONG_TERM_MEMORY_AUTO_EXTRACT=true
LONG_TERM_MEMORY_INJECT_CONTEXT=true
```
### 7. Telemetria e observabilidade
Quando a feature participa de uma execução de agente, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id` e demais chaves de correlação no estado/eventos. Isso permite acompanhar a decisão no Langfuse/Observer sem colocar lógica de observabilidade dentro do domínio.
### 8. Como testar
1. Crie um teste unitário do comportamento principal.
2. Crie um teste de integração do runtime quando houver estado entre turns.
3. Verifique o caso feliz e pelo menos um caso de falha/negação.
4. Confirme que não há side effects duplicados em retry/replay quando a feature toca transações.
5. Em produção, valide também telemetria e correlação de IDs.
### 9. Erros comuns
- Não confundir LTM com replay de toda conversa.
- Memória irrelevante ou de baixa confiança não deveria ser injetada.
- Em múltiplas réplicas, prefira storage durável compartilhado em vez de memória local.
### 10. Relação com outras features
Esta feature deve ser usada junto das demais capacidades horizontais do framework, em vez de criar uma implementação paralela no agente de domínio. Em fluxos transacionais, considere especialmente **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery** e **Guardrails**.
### 11. Referências no repositório
- `libs/agent_framework/src/agent_framework/memory/long_term_memory.py`
- `libs/agent_framework/src/agent_framework/memory/long_term_store.py`
- `Tuning-Performance/`
- `Documentacao/`
- `libs/agent_framework/docs/`
---
## English (EN)
### 1. What it is
Allows useful information to persist across different sessions without depending on the full transcript of a previous conversation.
### 2. Problem it solves
Production agents should not rely on prompts alone to “do the right thing”. This feature moves a specific responsibility into a controlled framework layer, reducing unpredictable behavior and duplicate domain-agent code.
### 3. Simplified flow
```text
Session A
extract relevant memory
Long Term Memory Store
... days later ...
Session B
retrieve relevant context
agent
```
### 4. How it works internally
Long-term memory is different from message history and checkpoints. It persists useful facts/preferences and retrieves them as context for a future session. The framework supports `memory`, `sqlite`, `autonomous`, and `oracle` providers.
Important settings include `ENABLE_LONG_TERM_MEMORY`, `LONG_TERM_MEMORY_PROVIDER`, `LONG_TERM_MEMORY_MAX_CONTEXT_ITEMS`, `LONG_TERM_MEMORY_MIN_CONFIDENCE`, `LONG_TERM_MEMORY_AUTO_EXTRACT`, and `LONG_TERM_MEMORY_INJECT_CONTEXT`.
### 5. How to enable/configure
Exact activation depends on the template/agent. Check framework settings, YAML configuration, and the service template. Not every feature requires a global flag: some are activated by the contract returned from a tool/workflow.
### 6. Example
```env
ENABLE_LONG_TERM_MEMORY=true
LONG_TERM_MEMORY_PROVIDER=oracle
LONG_TERM_MEMORY_MAX_CONTEXT_ITEMS=20
LONG_TERM_MEMORY_MIN_CONFIDENCE=0.70
LONG_TERM_MEMORY_AUTO_EXTRACT=true
LONG_TERM_MEMORY_INJECT_CONTEXT=true
```
### 7. Telemetry and observability
When the feature participates in an agent execution, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id`, and other correlation keys in state/events. This makes the decision observable through Langfuse/Observer without embedding observability logic in the domain.
### 8. How to test
1. Add a unit test for the core behavior.
2. Add a runtime integration test when state spans multiple turns.
3. Test the happy path and at least one failure/rejection path.
4. Confirm retries/replays do not duplicate side effects for transactional features.
5. In production, also validate telemetry and ID correlation.
### 9. Common mistakes
- Do not confuse LTM with replaying the entire transcript.
- Irrelevant or low-confidence memories should not be injected.
- For multiple replicas, prefer shared durable storage over local memory.
### 10. Relationship with other features
Use this feature together with the framework's horizontal capabilities rather than creating a parallel implementation in domain-agent code. For transactional journeys, pay special attention to **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery**, and **Guardrails**.
### 11. Repository references
- `libs/agent_framework/src/agent_framework/memory/long_term_memory.py`
- `libs/agent_framework/src/agent_framework/memory/long_term_store.py`
- `Tuning-Performance/`
- `Documentacao/`
- `libs/agent_framework/docs/`

View File

@@ -0,0 +1,163 @@
# Regressão Offline de Workflow / Offline Workflow Regression
> Feature do `agent_framework_oci` — guia bilíngue PT-BR / EN.
**Implementação principal / Main implementation:** `workflows/runtime.py + Tuning-Performance/Offline_Workflow_Regression`
---
## Português (PT-BR)
### 1. O que é
Permite testar a lógica de workflows sem exigir toda a infraestrutura de produção.
### 2. Problema que resolve
Em agentes de produção, não é suficiente pedir ao LLM que “faça a coisa certa”. Esta feature move uma responsabilidade específica para uma camada controlada do framework, reduzindo comportamento imprevisível e código duplicado nos agentes de domínio.
### 3. Fluxo simplificado
```text
Teste
backend determinístico explicitamente habilitado
run → PAUSED
resume → COMPLETED
asserts de estado/side effects
```
### 4. Como funciona internamente
O `WorkflowRuntime` possui um caminho determinístico/offline **explicitamente opt-in para testes**. Ele permite validar DSL, condições, pause/resume e proteção contra reexecução sem exigir LangGraph, banco, OCI ou APIs externas.
O comportamento de produção continua usando LangGraph. O modo offline não deve virar fallback silencioso quando LangGraph falha ou está ausente em produção.
### 5. Como ativar/configurar
A ativação exata depende do template/agente. Verifique o arquivo de settings, YAMLs de configuração e o template usado pelo serviço. Nem toda feature precisa de uma flag global: algumas são ativadas pelo contrato retornado por uma tool/workflow.
### 6. Exemplo
```text
run(workflow)
action_a = 1 execução
status = PAUSED
resume(workflow)
action_a continua com 1 execução
action_b = 1 execução
status = COMPLETED
```
### 7. Telemetria e observabilidade
Quando a feature participa de uma execução de agente, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id` e demais chaves de correlação no estado/eventos. Isso permite acompanhar a decisão no Langfuse/Observer sem colocar lógica de observabilidade dentro do domínio.
### 8. Como testar
1. Crie um teste unitário do comportamento principal.
2. Crie um teste de integração do runtime quando houver estado entre turns.
3. Verifique o caso feliz e pelo menos um caso de falha/negação.
4. Confirme que não há side effects duplicados em retry/replay quando a feature toca transações.
5. Em produção, valide também telemetria e correlação de IDs.
### 9. Erros comuns
- Usar o backend offline em produção mascara problemas reais.
- Mockar tanto que o teste deixa de validar a DSL real.
- Não verificar side effects anteriores ao pause pode esconder duplicações.
### 10. Relação com outras features
Esta feature deve ser usada junto das demais capacidades horizontais do framework, em vez de criar uma implementação paralela no agente de domínio. Em fluxos transacionais, considere especialmente **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery** e **Guardrails**.
### 11. Referências no repositório
- `libs/agent_framework/src/agent_framework/workflows/runtime.py`
- `libs/agent_framework/src/agent_framework/Tuning-Performance/Offline_Workflow_Regression`
- `Tuning-Performance/`
- `Documentacao/`
- `libs/agent_framework/docs/`
---
## English (EN)
### 1. What it is
Allows workflow logic to be regression-tested without requiring the full production infrastructure.
### 2. Problem it solves
Production agents should not rely on prompts alone to “do the right thing”. This feature moves a specific responsibility into a controlled framework layer, reducing unpredictable behavior and duplicate domain-agent code.
### 3. Simplified flow
```text
Test
explicit deterministic test backend
run → PAUSED
resume → COMPLETED
state/side-effect assertions
```
### 4. How it works internally
`WorkflowRuntime` includes an **explicitly opt-in deterministic/offline test backend**. It can validate DSL rules, conditions, pause/resume behavior, and duplicate-execution protection without requiring LangGraph, a database, OCI, or external APIs.
Production behavior still uses LangGraph. Offline mode must never become a silent fallback when LangGraph fails or is unavailable in production.
### 5. How to enable/configure
Exact activation depends on the template/agent. Check framework settings, YAML configuration, and the service template. Not every feature requires a global flag: some are activated by the contract returned from a tool/workflow.
### 6. Example
```text
run(workflow)
action_a = executed once
status = PAUSED
resume(workflow)
action_a remains executed once
action_b = executed once
status = COMPLETED
```
### 7. Telemetry and observability
When the feature participates in an agent execution, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id`, and other correlation keys in state/events. This makes the decision observable through Langfuse/Observer without embedding observability logic in the domain.
### 8. How to test
1. Add a unit test for the core behavior.
2. Add a runtime integration test when state spans multiple turns.
3. Test the happy path and at least one failure/rejection path.
4. Confirm retries/replays do not duplicate side effects for transactional features.
5. In production, also validate telemetry and ID correlation.
### 9. Common mistakes
- Using the offline backend in production hides real issues.
- Over-mocking can stop the test from validating real DSL behavior.
- Failing to assert pre-pause side effects may hide duplicate execution.
### 10. Relationship with other features
Use this feature together with the framework's horizontal capabilities rather than creating a parallel implementation in domain-agent code. For transactional journeys, pay special attention to **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery**, and **Guardrails**.
### 11. Repository references
- `libs/agent_framework/src/agent_framework/workflows/runtime.py`
- `libs/agent_framework/src/agent_framework/Tuning-Performance/Offline_Workflow_Regression`
- `Tuning-Performance/`
- `Documentacao/`
- `libs/agent_framework/docs/`

View File

@@ -0,0 +1,165 @@
# Pause / Resume de Workflow / Pause / Resume Workflow
> Feature do `agent_framework_oci` — guia bilíngue PT-BR / EN.
**Implementação principal / Main implementation:** `workflows/runtime.py + workflows/graph.py`
---
## Português (PT-BR)
### 1. O que é
Permite interromper um workflow em um ponto seguro, persistir o estado e continuar depois com a resposta do usuário ou outro evento.
### 2. Problema que resolve
Em agentes de produção, não é suficiente pedir ao LLM que “faça a coisa certa”. Esta feature move uma responsabilidade específica para uma camada controlada do framework, reduzindo comportamento imprevisível e código duplicado nos agentes de domínio.
### 3. Fluxo simplificado
```text
Workflow
ações prévias
PAUSE
checkpoint/estado
nova mensagem
RESUME
ações seguintes
```
### 4. Como funciona internamente
`WorkflowRuntime` expõe `arun(...)` e `aresume(...)`. O nó de pause é separado da action anterior para evitar reexecutar side effects quando o workflow retoma. O mesmo `execution_id/thread_id` identifica a execução pausada e retomada.
O runtime suporta condições declarativas como `all`, `any`, `not`, `eq`, `neq` e `exists`, permitindo definir quando pausar ou continuar sem colocar lógica conversacional no prompt.
### 5. Como ativar/configurar
A ativação exata depende do template/agente. Verifique o arquivo de settings, YAMLs de configuração e o template usado pelo serviço. Nem toda feature precisa de uma flag global: algumas são ativadas pelo contrato retornado por uma tool/workflow.
### 6. Exemplo
```text
status = await runtime.arun(...)
# status == PAUSED
status = await runtime.aresume(execution_id, input={"confirmed": true})
# status == COMPLETED
```
### 7. Telemetria e observabilidade
Quando a feature participa de uma execução de agente, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id` e demais chaves de correlação no estado/eventos. Isso permite acompanhar a decisão no Langfuse/Observer sem colocar lógica de observabilidade dentro do domínio.
### 8. Como testar
1. Crie um teste unitário do comportamento principal.
2. Crie um teste de integração do runtime quando houver estado entre turns.
3. Verifique o caso feliz e pelo menos um caso de falha/negação.
4. Confirme que não há side effects duplicados em retry/replay quando a feature toca transações.
5. Em produção, valide também telemetria e correlação de IDs.
### 9. Erros comuns
- Perder o `execution_id` impede retomar a execução correta.
- Reexecutar o workflow do zero após confirmação pode repetir side effects.
- Pause sem storage/checkpoint compartilhado é frágil em múltiplas réplicas.
### 10. Relação com outras features
Esta feature deve ser usada junto das demais capacidades horizontais do framework, em vez de criar uma implementação paralela no agente de domínio. Em fluxos transacionais, considere especialmente **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery** e **Guardrails**.
### 11. Referências no repositório
- `libs/agent_framework/src/agent_framework/workflows/runtime.py`
- `libs/agent_framework/src/agent_framework/workflows/graph.py`
- `Tuning-Performance/`
- `Documentacao/`
- `libs/agent_framework/docs/`
---
## English (EN)
### 1. What it is
Allows a workflow to stop at a safe point, persist state, and continue later using user input or another event.
### 2. Problem it solves
Production agents should not rely on prompts alone to “do the right thing”. This feature moves a specific responsibility into a controlled framework layer, reducing unpredictable behavior and duplicate domain-agent code.
### 3. Simplified flow
```text
Workflow
pre-pause actions
PAUSE
checkpoint/state
new message
RESUME
remaining actions
```
### 4. How it works internally
`WorkflowRuntime` exposes `arun(...)` and `aresume(...)`. The pause node is separated from the preceding action so previous side effects are not executed again on resume. The same `execution_id/thread_id` identifies the paused and resumed execution.
The runtime supports declarative conditions such as `all`, `any`, `not`, `eq`, `neq`, and `exists`, so pause/continue decisions do not need to live in the prompt.
### 5. How to enable/configure
Exact activation depends on the template/agent. Check framework settings, YAML configuration, and the service template. Not every feature requires a global flag: some are activated by the contract returned from a tool/workflow.
### 6. Example
```text
status = await runtime.arun(...)
# status == PAUSED
status = await runtime.aresume(execution_id, input={"confirmed": true})
# status == COMPLETED
```
### 7. Telemetry and observability
When the feature participates in an agent execution, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id`, and other correlation keys in state/events. This makes the decision observable through Langfuse/Observer without embedding observability logic in the domain.
### 8. How to test
1. Add a unit test for the core behavior.
2. Add a runtime integration test when state spans multiple turns.
3. Test the happy path and at least one failure/rejection path.
4. Confirm retries/replays do not duplicate side effects for transactional features.
5. In production, also validate telemetry and ID correlation.
### 9. Common mistakes
- Losing the `execution_id` prevents resuming the right execution.
- Restarting the workflow from scratch after confirmation may duplicate side effects.
- Pause without shared checkpoint/state storage is fragile across multiple replicas.
### 10. Relationship with other features
Use this feature together with the framework's horizontal capabilities rather than creating a parallel implementation in domain-agent code. For transactional journeys, pay special attention to **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery**, and **Guardrails**.
### 11. Repository references
- `libs/agent_framework/src/agent_framework/workflows/runtime.py`
- `libs/agent_framework/src/agent_framework/workflows/graph.py`
- `Tuning-Performance/`
- `Documentacao/`
- `libs/agent_framework/docs/`

View File

@@ -0,0 +1,151 @@
# Aderência de Rota / Route Stickiness
> Feature do `agent_framework_oci` — guia bilíngue PT-BR / EN.
**Implementação principal / Main implementation:** `routing/enterprise_router.py + runtime/agent_runtime.py`
---
## Português (PT-BR)
### 1. O que é
Evita que pequenas mensagens de continuação façam a conversa trocar de agente sem necessidade.
### 2. Problema que resolve
Em agentes de produção, não é suficiente pedir ao LLM que “faça a coisa certa”. Esta feature move uma responsabilidade específica para uma camada controlada do framework, reduzindo comportamento imprevisível e código duplicado nos agentes de domínio.
### 3. Fluxo simplificado
```text
mensagem atual
+ histórico curto
+ rota anterior
continuidade semântica
manter rota ou handoff
```
### 4. Como funciona internamente
Route Stickiness avalia se a nova mensagem continua semanticamente ligada ao assunto/agente atual. Isso reduz ping-pong de agentes em mensagens como “e esse valor?”, “sim”, “o segundo” ou “e no mês passado?”.
Configurações existentes incluem `ENABLE_ROUTE_STICKINESS`, `ROUTE_STICKINESS_LLM_PROFILE`, `ROUTE_STICKINESS_CONFIDENCE_THRESHOLD`, `ROUTE_STICKINESS_HISTORY_TURNS` e `ROUTE_STICKINESS_MAX_TOKENS`. A decisão pode permitir handoff quando há evidência suficiente de mudança de assunto.
### 5. Como ativar/configurar
A ativação exata depende do template/agente. Verifique o arquivo de settings, YAMLs de configuração e o template usado pelo serviço. Nem toda feature precisa de uma flag global: algumas são ativadas pelo contrato retornado por uma tool/workflow.
### 6. Exemplo
```env
ENABLE_ROUTE_STICKINESS=true
ROUTE_STICKINESS_CONFIDENCE_THRESHOLD=0.90
ROUTE_STICKINESS_HISTORY_TURNS=2
ROUTE_STICKINESS_MAX_TOKENS=80
```
### 7. Telemetria e observabilidade
Quando a feature participa de uma execução de agente, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id` e demais chaves de correlação no estado/eventos. Isso permite acompanhar a decisão no Langfuse/Observer sem colocar lógica de observabilidade dentro do domínio.
### 8. Como testar
1. Crie um teste unitário do comportamento principal.
2. Crie um teste de integração do runtime quando houver estado entre turns.
3. Verifique o caso feliz e pelo menos um caso de falha/negação.
4. Confirme que não há side effects duplicados em retry/replay quando a feature toca transações.
5. Em produção, valide também telemetria e correlação de IDs.
### 9. Erros comuns
- Threshold muito baixo pode prender o cliente no agente errado.
- Threshold alto demais perde continuidade em mensagens curtas.
- Stickiness não deve bloquear handoff explícito quando a intenção realmente mudou.
### 10. Relação com outras features
Esta feature deve ser usada junto das demais capacidades horizontais do framework, em vez de criar uma implementação paralela no agente de domínio. Em fluxos transacionais, considere especialmente **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery** e **Guardrails**.
### 11. Referências no repositório
- `libs/agent_framework/src/agent_framework/routing/enterprise_router.py`
- `libs/agent_framework/src/agent_framework/runtime/agent_runtime.py`
- `Tuning-Performance/`
- `Documentacao/`
- `libs/agent_framework/docs/`
---
## English (EN)
### 1. What it is
Prevents short follow-up messages from unnecessarily switching the conversation to another agent.
### 2. Problem it solves
Production agents should not rely on prompts alone to “do the right thing”. This feature moves a specific responsibility into a controlled framework layer, reducing unpredictable behavior and duplicate domain-agent code.
### 3. Simplified flow
```text
current message
+ short history
+ previous route
semantic continuity
keep route or handoff
```
### 4. How it works internally
Route Stickiness evaluates whether a new message is semantically continuous with the current subject/agent. It reduces agent ping-pong for messages such as “what about that amount?”, “yes”, “the second one”, or “and last month?”.
Existing settings include `ENABLE_ROUTE_STICKINESS`, `ROUTE_STICKINESS_LLM_PROFILE`, `ROUTE_STICKINESS_CONFIDENCE_THRESHOLD`, `ROUTE_STICKINESS_HISTORY_TURNS`, and `ROUTE_STICKINESS_MAX_TOKENS`. The decision may still allow handoff when there is enough evidence of a topic change.
### 5. How to enable/configure
Exact activation depends on the template/agent. Check framework settings, YAML configuration, and the service template. Not every feature requires a global flag: some are activated by the contract returned from a tool/workflow.
### 6. Example
```env
ENABLE_ROUTE_STICKINESS=true
ROUTE_STICKINESS_CONFIDENCE_THRESHOLD=0.90
ROUTE_STICKINESS_HISTORY_TURNS=2
ROUTE_STICKINESS_MAX_TOKENS=80
```
### 7. Telemetry and observability
When the feature participates in an agent execution, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id`, and other correlation keys in state/events. This makes the decision observable through Langfuse/Observer without embedding observability logic in the domain.
### 8. How to test
1. Add a unit test for the core behavior.
2. Add a runtime integration test when state spans multiple turns.
3. Test the happy path and at least one failure/rejection path.
4. Confirm retries/replays do not duplicate side effects for transactional features.
5. In production, also validate telemetry and ID correlation.
### 9. Common mistakes
- A threshold that is too low may trap the user on the wrong agent.
- A threshold that is too high may lose continuity on short follow-ups.
- Stickiness should not block explicit handoff when the user clearly changes intent.
### 10. Relationship with other features
Use this feature together with the framework's horizontal capabilities rather than creating a parallel implementation in domain-agent code. For transactional journeys, pay special attention to **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery**, and **Guardrails**.
### 11. Repository references
- `libs/agent_framework/src/agent_framework/routing/enterprise_router.py`
- `libs/agent_framework/src/agent_framework/runtime/agent_runtime.py`
- `Tuning-Performance/`
- `Documentacao/`
- `libs/agent_framework/docs/`

View File

@@ -0,0 +1,153 @@
# Replay em Interrupções de Voz / Voice Interruption Replay
> Feature do `agent_framework_oci` — guia bilíngue PT-BR / EN.
**Implementação principal / Main implementation:** `channels/interruption.py`
---
## Português (PT-BR)
### 1. O que é
Decide se um áudio recebido durante a fala do agente representa uma nova intenção, um ruído/backchannel ou algo que deve apenas repetir/continuar a última fala.
### 2. Problema que resolve
Em agentes de produção, não é suficiente pedir ao LLM que “faça a coisa certa”. Esta feature move uma responsabilidade específica para uma camada controlada do framework, reduzindo comportamento imprevisível e código duplicado nos agentes de domínio.
### 3. Fluxo simplificado
```text
áudio durante fala
InterruptionPolicy
├─ process → nova mensagem
├─ classify → classificador leve
└─ replay → última fala
```
### 4. Como funciona internamente
A política fica no framework, não no domínio. Ela diferencia sessão terminal, `idle_nudge`, fala não interrompível e fala potencialmente interrompível. Quando necessário, pode usar um classificador leve baseado no `LLMProvider`; quando a classificação falha, a política é conservadora e pode optar por replay.
O objetivo é evitar que “aham”, ruído, eco ou fragmentos residuais sejam tratados como uma nova intenção completa.
### 5. Como ativar/configurar
A ativação exata depende do template/agente. Verifique o arquivo de settings, YAMLs de configuração e o template usado pelo serviço. Nem toda feature precisa de uma flag global: algumas são ativadas pelo contrato retornado por uma tool/workflow.
### 6. Exemplo
```text
Agente: "Sua fatura possui..."
Cliente: "aham"
→ replay/continua
Agente: "Sua fatura possui..."
Cliente: "espera, quero falar de outra coisa"
→ processa nova intenção
```
### 7. Telemetria e observabilidade
Quando a feature participa de uma execução de agente, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id` e demais chaves de correlação no estado/eventos. Isso permite acompanhar a decisão no Langfuse/Observer sem colocar lógica de observabilidade dentro do domínio.
### 8. Como testar
1. Crie um teste unitário do comportamento principal.
2. Crie um teste de integração do runtime quando houver estado entre turns.
3. Verifique o caso feliz e pelo menos um caso de falha/negação.
4. Confirme que não há side effects duplicados em retry/replay quando a feature toca transações.
5. Em produção, valide também telemetria e correlação de IDs.
### 9. Erros comuns
- Classificar todo ruído com LLM aumenta latência e custo.
- Permitir interrupção em fala transacional não interrompível pode corromper UX/estado.
- Replay deve usar uma fala real anterior, não um envelope técnico.
### 10. Relação com outras features
Esta feature deve ser usada junto das demais capacidades horizontais do framework, em vez de criar uma implementação paralela no agente de domínio. Em fluxos transacionais, considere especialmente **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery** e **Guardrails**.
### 11. Referências no repositório
- `libs/agent_framework/src/agent_framework/channels/interruption.py`
- `Tuning-Performance/`
- `Documentacao/`
- `libs/agent_framework/docs/`
---
## English (EN)
### 1. What it is
Decides whether audio received while the agent is speaking represents a new intent, a backchannel/noise event, or something that should simply replay/continue the previous speech.
### 2. Problem it solves
Production agents should not rely on prompts alone to “do the right thing”. This feature moves a specific responsibility into a controlled framework layer, reducing unpredictable behavior and duplicate domain-agent code.
### 3. Simplified flow
```text
audio during speech
InterruptionPolicy
├─ process → new message
├─ classify → lightweight classifier
└─ replay → previous speech
```
### 4. How it works internally
The policy lives in the framework rather than domain code. It distinguishes terminal sessions, `idle_nudge`, non-interruptible speech, and potentially interruptible speech. When needed, it may use a lightweight classifier backed by `LLMProvider`; on classification failure, it can fail safely to replay.
The goal is to prevent “uh-huh”, noise, echo, or residual audio fragments from being interpreted as a full new intent.
### 5. How to enable/configure
Exact activation depends on the template/agent. Check framework settings, YAML configuration, and the service template. Not every feature requires a global flag: some are activated by the contract returned from a tool/workflow.
### 6. Example
```text
Agent: "Your invoice contains..."
User: "uh-huh"
→ replay/continue
Agent: "Your invoice contains..."
User: "wait, I want to ask something else"
→ process new intent
```
### 7. Telemetry and observability
When the feature participates in an agent execution, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id`, and other correlation keys in state/events. This makes the decision observable through Langfuse/Observer without embedding observability logic in the domain.
### 8. How to test
1. Add a unit test for the core behavior.
2. Add a runtime integration test when state spans multiple turns.
3. Test the happy path and at least one failure/rejection path.
4. Confirm retries/replays do not duplicate side effects for transactional features.
5. In production, also validate telemetry and ID correlation.
### 9. Common mistakes
- Sending every noise fragment to an LLM increases latency and cost.
- Allowing interruption during non-interruptible transactional speech may corrupt UX/state.
- Replay should use a real previous utterance, not a technical envelope.
### 10. Relationship with other features
Use this feature together with the framework's horizontal capabilities rather than creating a parallel implementation in domain-agent code. For transactional journeys, pay special attention to **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery**, and **Guardrails**.
### 11. Repository references
- `libs/agent_framework/src/agent_framework/channels/interruption.py`
- `Tuning-Performance/`
- `Documentacao/`
- `libs/agent_framework/docs/`

View File

@@ -0,0 +1,167 @@
# Recuperação de Erro em Workflow / Workflow Error Recovery
> Feature do `agent_framework_oci` — guia bilíngue PT-BR / EN.
**Implementação principal / Main implementation:** `workflows/runtime.py`
---
## Português (PT-BR)
### 1. O que é
Preserva o estado parcial de uma execução quando um passo posterior falha, permitindo entender o que já aconteceu e evitar repetir side effects.
### 2. Problema que resolve
Em agentes de produção, não é suficiente pedir ao LLM que “faça a coisa certa”. Esta feature move uma responsabilidade específica para uma camada controlada do framework, reduzindo comportamento imprevisível e código duplicado nos agentes de domínio.
### 3. Fluxo simplificado
```text
passo A ✅
passo B ✅
passo C ❌
FAILED + snapshot parcial
recovery decide o que pode continuar/repetir
```
### 4. Como funciona internamente
O runtime preserva o snapshot parcial do LangGraph quando uma etapa posterior falha e produz `error_details` genérico. Quando a exceção externa possui informações estruturadas, podem ser preservados status HTTP, body, número de tentativas, code e metadata.
A feature não significa “tentar tudo de novo”. Recuperação segura depende de conhecer o estado já executado, a idempotência e a natureza do erro.
### 5. Como ativar/configurar
A ativação exata depende do template/agente. Verifique o arquivo de settings, YAMLs de configuração e o template usado pelo serviço. Nem toda feature precisa de uma flag global: algumas são ativadas pelo contrato retornado por uma tool/workflow.
### 6. Exemplo
```json
{
"status": "FAILED",
"error_details": {
"status": 503,
"attempts": 3,
"code": "UPSTREAM_UNAVAILABLE"
},
"state": {
"protocol_created": true,
"operation_completed": true,
"sms_sent": false
}
}
```
### 7. Telemetria e observabilidade
Quando a feature participa de uma execução de agente, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id` e demais chaves de correlação no estado/eventos. Isso permite acompanhar a decisão no Langfuse/Observer sem colocar lógica de observabilidade dentro do domínio.
### 8. Como testar
1. Crie um teste unitário do comportamento principal.
2. Crie um teste de integração do runtime quando houver estado entre turns.
3. Verifique o caso feliz e pelo menos um caso de falha/negação.
4. Confirme que não há side effects duplicados em retry/replay quando a feature toca transações.
5. Em produção, valide também telemetria e correlação de IDs.
### 9. Erros comuns
- Retry indiscriminado pode repetir transações.
- Se a exceção externa perde metadata, a recuperação fica menos precisa.
- Combine sempre com Durable Idempotency em side effects críticos.
### 10. Relação com outras features
Esta feature deve ser usada junto das demais capacidades horizontais do framework, em vez de criar uma implementação paralela no agente de domínio. Em fluxos transacionais, considere especialmente **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery** e **Guardrails**.
### 11. Referências no repositório
- `libs/agent_framework/src/agent_framework/workflows/runtime.py`
- `Tuning-Performance/`
- `Documentacao/`
- `libs/agent_framework/docs/`
---
## English (EN)
### 1. What it is
Preserves partial execution state when a later step fails, making it possible to know what already happened and avoid repeating side effects.
### 2. Problem it solves
Production agents should not rely on prompts alone to “do the right thing”. This feature moves a specific responsibility into a controlled framework layer, reducing unpredictable behavior and duplicate domain-agent code.
### 3. Simplified flow
```text
step A ✅
step B ✅
step C ❌
FAILED + partial snapshot
recovery decides what may continue/retry
```
### 4. How it works internally
The runtime preserves the partial LangGraph snapshot when a later step fails and produces generic `error_details`. When an external exception provides structured information, HTTP status, body, attempt count, code, and metadata may be preserved.
This feature does not mean “retry everything”. Safe recovery depends on knowing what already executed, idempotency guarantees, and the nature of the failure.
### 5. How to enable/configure
Exact activation depends on the template/agent. Check framework settings, YAML configuration, and the service template. Not every feature requires a global flag: some are activated by the contract returned from a tool/workflow.
### 6. Example
```json
{
"status": "FAILED",
"error_details": {
"status": 503,
"attempts": 3,
"code": "UPSTREAM_UNAVAILABLE"
},
"state": {
"protocol_created": true,
"operation_completed": true,
"sms_sent": false
}
}
```
### 7. Telemetry and observability
When the feature participates in an agent execution, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id`, and other correlation keys in state/events. This makes the decision observable through Langfuse/Observer without embedding observability logic in the domain.
### 8. How to test
1. Add a unit test for the core behavior.
2. Add a runtime integration test when state spans multiple turns.
3. Test the happy path and at least one failure/rejection path.
4. Confirm retries/replays do not duplicate side effects for transactional features.
5. In production, also validate telemetry and ID correlation.
### 9. Common mistakes
- Blind retries may repeat transactions.
- If external exceptions discard metadata, recovery becomes less precise.
- Always combine with Durable Idempotency for critical side effects.
### 10. Relationship with other features
Use this feature together with the framework's horizontal capabilities rather than creating a parallel implementation in domain-agent code. For transactional journeys, pay special attention to **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery**, and **Guardrails**.
### 11. Repository references
- `libs/agent_framework/src/agent_framework/workflows/runtime.py`
- `Tuning-Performance/`
- `Documentacao/`
- `libs/agent_framework/docs/`

View File

@@ -0,0 +1,169 @@
# Clarificação / Clarification
> Feature do `agent_framework_oci` — guia bilíngue PT-BR / EN.
**Implementação principal / Main implementation:** `runtime/agent_runtime.py`
---
## Português (PT-BR)
### 1. O que é
Quando faltam dados ou uma tool encontra múltiplas opções, o framework pergunta ao usuário em vez de adivinhar.
### 2. Problema que resolve
Em agentes de produção, não é suficiente pedir ao LLM que “faça a coisa certa”. Esta feature move uma responsabilidade específica para uma camada controlada do framework, reduzindo comportamento imprevisível e código duplicado nos agentes de domínio.
### 3. Fluxo simplificado
```text
pedido ambíguo
NEEDS_CLARIFICATION
pergunta + opções
usuário responde
framework resolve
retoma mesma tool/workflow
```
### 4. Como funciona internamente
O runtime suporta clarificação tanto de parâmetros faltantes quanto de resultados de tools. Para tool-result clarification, um resultado com `status: NEEDS_CLARIFICATION` pode trazer opções; o runtime persiste `pending_tool_clarification`, entra em `TOOL_RESULT_CLARIFICATION` e consegue resolver respostas por ordinal ou nome.
Depois da escolha, o framework reutiliza a mesma tool e injeta os argumentos resolvidos, evitando que o roteador trate a resposta curta como uma intenção nova.
### 5. Como ativar/configurar
A ativação exata depende do template/agente. Verifique o arquivo de settings, YAMLs de configuração e o template usado pelo serviço. Nem toda feature precisa de uma flag global: algumas são ativadas pelo contrato retornado por uma tool/workflow.
### 6. Exemplo
```json
{
"status": "NEEDS_CLARIFICATION",
"question": "Qual serviço?",
"options": [
{"id": "tim_music", "label": "TIM Music"},
{"id": "hbo_max", "label": "HBO Max"}
]
}
```
Usuário: `o segundo``hbo_max`.
### 7. Telemetria e observabilidade
Quando a feature participa de uma execução de agente, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id` e demais chaves de correlação no estado/eventos. Isso permite acompanhar a decisão no Langfuse/Observer sem colocar lógica de observabilidade dentro do domínio.
### 8. Como testar
1. Crie um teste unitário do comportamento principal.
2. Crie um teste de integração do runtime quando houver estado entre turns.
3. Verifique o caso feliz e pelo menos um caso de falha/negação.
4. Confirme que não há side effects duplicados em retry/replay quando a feature toca transações.
5. Em produção, valide também telemetria e correlação de IDs.
### 9. Erros comuns
- Não descarte `pending_tool_clarification` entre turns.
- Uma resposta curta deve ser resolvida contra as opções antes do roteamento normal.
- Opções sem identificador/label consistente pioram a resolução.
### 10. Relação com outras features
Esta feature deve ser usada junto das demais capacidades horizontais do framework, em vez de criar uma implementação paralela no agente de domínio. Em fluxos transacionais, considere especialmente **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery** e **Guardrails**.
### 11. Referências no repositório
- `libs/agent_framework/src/agent_framework/runtime/agent_runtime.py`
- `Tuning-Performance/`
- `Documentacao/`
- `libs/agent_framework/docs/`
---
## English (EN)
### 1. What it is
When required information is missing or a tool finds multiple options, the framework asks the user instead of guessing.
### 2. Problem it solves
Production agents should not rely on prompts alone to “do the right thing”. This feature moves a specific responsibility into a controlled framework layer, reducing unpredictable behavior and duplicate domain-agent code.
### 3. Simplified flow
```text
ambiguous request
NEEDS_CLARIFICATION
question + options
user answers
framework resolves
resume same tool/workflow
```
### 4. How it works internally
The runtime supports clarification for both missing parameters and ambiguous tool results. For tool-result clarification, a result with `status: NEEDS_CLARIFICATION` may include options; the runtime persists `pending_tool_clarification`, moves to `TOOL_RESULT_CLARIFICATION`, and can resolve responses by ordinal or name.
After selection, the framework reuses the same tool and injects resolved arguments, preventing the router from treating a short reply as a brand-new intent.
### 5. How to enable/configure
Exact activation depends on the template/agent. Check framework settings, YAML configuration, and the service template. Not every feature requires a global flag: some are activated by the contract returned from a tool/workflow.
### 6. Example
```json
{
"status": "NEEDS_CLARIFICATION",
"question": "Which service?",
"options": [
{"id": "tim_music", "label": "TIM Music"},
{"id": "hbo_max", "label": "HBO Max"}
]
}
```
User: `the second one``hbo_max`.
### 7. Telemetry and observability
When the feature participates in an agent execution, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id`, and other correlation keys in state/events. This makes the decision observable through Langfuse/Observer without embedding observability logic in the domain.
### 8. How to test
1. Add a unit test for the core behavior.
2. Add a runtime integration test when state spans multiple turns.
3. Test the happy path and at least one failure/rejection path.
4. Confirm retries/replays do not duplicate side effects for transactional features.
5. In production, also validate telemetry and ID correlation.
### 9. Common mistakes
- Do not discard `pending_tool_clarification` between turns.
- A short answer should be resolved against pending options before normal routing.
- Options without stable identifiers/labels reduce resolution quality.
### 10. Relationship with other features
Use this feature together with the framework's horizontal capabilities rather than creating a parallel implementation in domain-agent code. For transactional journeys, pay special attention to **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery**, and **Guardrails**.
### 11. Repository references
- `libs/agent_framework/src/agent_framework/runtime/agent_runtime.py`
- `Tuning-Performance/`
- `Documentacao/`
- `libs/agent_framework/docs/`

View File

@@ -0,0 +1,163 @@
# Idempotência Durável / Durable Idempotency
> Feature do `agent_framework_oci` — guia bilíngue PT-BR / EN.
**Implementação principal / Main implementation:** `idempotency.py`
---
## Português (PT-BR)
### 1. O que é
Impede que a mesma operação crítica seja executada duas vezes, inclusive quando outra réplica/pod recebe a repetição.
### 2. Problema que resolve
Em agentes de produção, não é suficiente pedir ao LLM que “faça a coisa certa”. Esta feature move uma responsabilidade específica para uma camada controlada do framework, reduzindo comportamento imprevisível e código duplicado nos agentes de domínio.
### 3. Fluxo simplificado
```text
requisição
idempotency key
store durável
├─ existe → retorna resultado anterior
└─ não existe → executa → persiste resultado
```
### 4. Como funciona internamente
`create_idempotency_store(settings, ...)` escolhe o backend conforme configuração/plataforma. O framework possui `IdempotencyStore` e `InMemoryIdempotencyStore`, mas produção distribuída deve preferir storage compartilhado. As configurações incluem `IDEMPOTENCY_PROVIDER`, `IDEMPOTENCY_REQUIRE_DURABLE` e `IDEMPOTENCY_TTL_SECONDS`.
Idempotência é diferente de retry: retry repete a tentativa; idempotência garante que a repetição não produza um novo side effect.
### 5. Como ativar/configurar
A ativação exata depende do template/agente. Verifique o arquivo de settings, YAMLs de configuração e o template usado pelo serviço. Nem toda feature precisa de uma flag global: algumas são ativadas pelo contrato retornado por uma tool/workflow.
### 6. Exemplo
```text
Pod A recebe cancelamento
→ key=cliente:servico:operacao
→ executa
→ grava resultado
Pod A cai
Pod B recebe retry
→ mesma key
→ encontra resultado
→ NÃO cancela de novo
```
### 7. Telemetria e observabilidade
Quando a feature participa de uma execução de agente, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id` e demais chaves de correlação no estado/eventos. Isso permite acompanhar a decisão no Langfuse/Observer sem colocar lógica de observabilidade dentro do domínio.
### 8. Como testar
1. Crie um teste unitário do comportamento principal.
2. Crie um teste de integração do runtime quando houver estado entre turns.
3. Verifique o caso feliz e pelo menos um caso de falha/negação.
4. Confirme que não há side effects duplicados em retry/replay quando a feature toca transações.
5. Em produção, valide também telemetria e correlação de IDs.
### 9. Erros comuns
- Usar store em memória com múltiplos pods não é idempotência durável.
- Chave ampla demais pode bloquear operações legítimas; estreita demais permite duplicidade.
- TTL deve ser compatível com a janela real de retry/replay.
### 10. Relação com outras features
Esta feature deve ser usada junto das demais capacidades horizontais do framework, em vez de criar uma implementação paralela no agente de domínio. Em fluxos transacionais, considere especialmente **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery** e **Guardrails**.
### 11. Referências no repositório
- `libs/agent_framework/src/agent_framework/idempotency.py`
- `Tuning-Performance/`
- `Documentacao/`
- `libs/agent_framework/docs/`
---
## English (EN)
### 1. What it is
Prevents the same critical operation from executing twice, including when a retry lands on another replica/pod.
### 2. Problem it solves
Production agents should not rely on prompts alone to “do the right thing”. This feature moves a specific responsibility into a controlled framework layer, reducing unpredictable behavior and duplicate domain-agent code.
### 3. Simplified flow
```text
request
idempotency key
durable store
├─ exists → return previous result
└─ missing → execute → persist result
```
### 4. How it works internally
`create_idempotency_store(settings, ...)` chooses a backend according to configuration/platform. The framework provides `IdempotencyStore` and `InMemoryIdempotencyStore`, but distributed production should prefer shared storage. Settings include `IDEMPOTENCY_PROVIDER`, `IDEMPOTENCY_REQUIRE_DURABLE`, and `IDEMPOTENCY_TTL_SECONDS`.
Idempotency is different from retry: retry repeats an attempt; idempotency guarantees that repetition does not create another side effect.
### 5. How to enable/configure
Exact activation depends on the template/agent. Check framework settings, YAML configuration, and the service template. Not every feature requires a global flag: some are activated by the contract returned from a tool/workflow.
### 6. Example
```text
Pod A receives cancellation
→ key=customer:service:operation
→ executes
→ stores result
Pod A crashes
Pod B receives retry
→ same key
→ finds stored result
→ DOES NOT cancel again
```
### 7. Telemetry and observability
When the feature participates in an agent execution, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id`, and other correlation keys in state/events. This makes the decision observable through Langfuse/Observer without embedding observability logic in the domain.
### 8. How to test
1. Add a unit test for the core behavior.
2. Add a runtime integration test when state spans multiple turns.
3. Test the happy path and at least one failure/rejection path.
4. Confirm retries/replays do not duplicate side effects for transactional features.
5. In production, also validate telemetry and ID correlation.
### 9. Common mistakes
- An in-memory store across multiple pods is not durable idempotency.
- A key that is too broad may block legitimate operations; too narrow may allow duplicates.
- TTL should match the real retry/replay window.
### 10. Relationship with other features
Use this feature together with the framework's horizontal capabilities rather than creating a parallel implementation in domain-agent code. For transactional journeys, pay special attention to **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery**, and **Guardrails**.
### 11. Repository references
- `libs/agent_framework/src/agent_framework/idempotency.py`
- `Tuning-Performance/`
- `Documentacao/`
- `libs/agent_framework/docs/`

View File

@@ -0,0 +1,157 @@
# Estados Transacionais Dinâmicos / Dynamic Transaction States
> Feature do `agent_framework_oci` — guia bilíngue PT-BR / EN.
**Implementação principal / Main implementation:** `runtime/agent_runtime.py + mcp/tool_policy.py`
---
## Português (PT-BR)
### 1. O que é
Permite criar estados de confirmação baseados no agente/domínio atual sem hardcode de todos os domínios dentro do framework.
### 2. Problema que resolve
Em agentes de produção, não é suficiente pedir ao LLM que “faça a coisa certa”. Esta feature move uma responsabilidade específica para uma camada controlada do framework, reduzindo comportamento imprevisível e código duplicado nos agentes de domínio.
### 3. Fluxo simplificado
```text
tool transactional
agente/domínio atual
WAITING_<PREFIX>_CONFIRMATION
confirmação/rejeição
estado seguinte
```
### 4. Como funciona internamente
Em vez de manter estados fixos como `WAITING_BILLING_CONFIRMATION`, `WAITING_PRODUCT_CONFIRMATION` etc. para cada domínio conhecido, o runtime deriva o prefixo do agente atual e gera o estado dinamicamente. A função interna de estado transacional mantém o framework genérico.
A classificação `operation_type` aceita `read_only`, `transactional`, `conversational` e `internal`; somente `transactional` entra no caminho de confirmação transacional.
### 5. Como ativar/configurar
A ativação exata depende do template/agente. Verifique o arquivo de settings, YAMLs de configuração e o template usado pelo serviço. Nem toda feature precisa de uma flag global: algumas são ativadas pelo contrato retornado por uma tool/workflow.
### 6. Exemplo
```text
VasAgent + cancelar_vas
→ WAITING_VAS_CONFIRMATION
AddressAgent + alterar_endereco
→ WAITING_ADDRESS_CONFIRMATION
```
### 7. Telemetria e observabilidade
Quando a feature participa de uma execução de agente, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id` e demais chaves de correlação no estado/eventos. Isso permite acompanhar a decisão no Langfuse/Observer sem colocar lógica de observabilidade dentro do domínio.
### 8. Como testar
1. Crie um teste unitário do comportamento principal.
2. Crie um teste de integração do runtime quando houver estado entre turns.
3. Verifique o caso feliz e pelo menos um caso de falha/negação.
4. Confirme que não há side effects duplicados em retry/replay quando a feature toca transações.
5. Em produção, valide também telemetria e correlação de IDs.
### 9. Erros comuns
- Hardcode de estados no domínio reduz reutilização.
- Classificar uma tool como `conversational` não deve ativar confirmação transacional.
- Mudanças no identificador do agente podem mudar o prefixo; mantenha IDs estáveis.
### 10. Relação com outras features
Esta feature deve ser usada junto das demais capacidades horizontais do framework, em vez de criar uma implementação paralela no agente de domínio. Em fluxos transacionais, considere especialmente **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery** e **Guardrails**.
### 11. Referências no repositório
- `libs/agent_framework/src/agent_framework/runtime/agent_runtime.py`
- `libs/agent_framework/src/agent_framework/mcp/tool_policy.py`
- `Tuning-Performance/`
- `Documentacao/`
- `libs/agent_framework/docs/`
---
## English (EN)
### 1. What it is
Allows confirmation states to be derived from the current agent/domain instead of hardcoding every business domain into the framework.
### 2. Problem it solves
Production agents should not rely on prompts alone to “do the right thing”. This feature moves a specific responsibility into a controlled framework layer, reducing unpredictable behavior and duplicate domain-agent code.
### 3. Simplified flow
```text
transactional tool
current agent/domain
WAITING_<PREFIX>_CONFIRMATION
confirm/reject
next state
```
### 4. How it works internally
Instead of maintaining fixed states such as `WAITING_BILLING_CONFIRMATION`, `WAITING_PRODUCT_CONFIRMATION`, and so on for every known domain, the runtime derives a prefix from the current agent and builds the confirmation state dynamically. This keeps the framework generic.
`operation_type` accepts `read_only`, `transactional`, `conversational`, and `internal`; only `transactional` enters the transactional confirmation path.
### 5. How to enable/configure
Exact activation depends on the template/agent. Check framework settings, YAML configuration, and the service template. Not every feature requires a global flag: some are activated by the contract returned from a tool/workflow.
### 6. Example
```text
VasAgent + cancel_vas
→ WAITING_VAS_CONFIRMATION
AddressAgent + change_address
→ WAITING_ADDRESS_CONFIRMATION
```
### 7. Telemetry and observability
When the feature participates in an agent execution, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id`, and other correlation keys in state/events. This makes the decision observable through Langfuse/Observer without embedding observability logic in the domain.
### 8. How to test
1. Add a unit test for the core behavior.
2. Add a runtime integration test when state spans multiple turns.
3. Test the happy path and at least one failure/rejection path.
4. Confirm retries/replays do not duplicate side effects for transactional features.
5. In production, also validate telemetry and ID correlation.
### 9. Common mistakes
- Hardcoding states in domain code reduces reuse.
- Classifying a tool as `conversational` should not trigger transactional confirmation.
- Changing agent identifiers may change state prefixes; keep IDs stable.
### 10. Relationship with other features
Use this feature together with the framework's horizontal capabilities rather than creating a parallel implementation in domain-agent code. For transactional journeys, pay special attention to **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery**, and **Guardrails**.
### 11. Repository references
- `libs/agent_framework/src/agent_framework/runtime/agent_runtime.py`
- `libs/agent_framework/src/agent_framework/mcp/tool_policy.py`
- `Tuning-Performance/`
- `Documentacao/`
- `libs/agent_framework/docs/`

View File

@@ -0,0 +1,159 @@
# Replay Após Finalização / Post Finalization Replay
> Feature do `agent_framework_oci` — guia bilíngue PT-BR / EN.
**Implementação principal / Main implementation:** `channels/interruption.py + config/settings.py`
---
## Português (PT-BR)
### 1. O que é
Evita que áudio residual ou mensagens tardias reabram uma sessão já finalizada.
### 2. Problema que resolve
Em agentes de produção, não é suficiente pedir ao LLM que “faça a coisa certa”. Esta feature move uma responsabilidade específica para uma camada controlada do framework, reduzindo comportamento imprevisível e código duplicado nos agentes de domínio.
### 3. Fluxo simplificado
```text
sessão terminal
entrada residual
policy detecta finalização
replay última fala/fallback
NÃO reabre LangGraph
```
### 4. Como funciona internamente
A política de interrupção verifica metadata de sessão terminal antes de tratar uma entrada como nova intenção. Quando há texto terminal disponível, usa `last_assistant_text`/`terminal_replay_text`; caso contrário, pode usar a mensagem configurada em `POST_FINALIZE_REPLAY_MESSAGE`.
O objetivo é proteger o fechamento lógico da sessão, especialmente em canais de voz onde pacotes de áudio podem chegar depois do evento de finalização.
### 5. Como ativar/configurar
A ativação exata depende do template/agente. Verifique o arquivo de settings, YAMLs de configuração e o template usado pelo serviço. Nem toda feature precisa de uma flag global: algumas são ativadas pelo contrato retornado por uma tool/workflow.
### 6. Exemplo
```text
Agente: "Atendimento concluído."
→ sessão finalizada
chega fragmento: "ã..."
→ replay "Atendimento concluído."
→ nenhum routing / tool / LLM novo
```
### 7. Telemetria e observabilidade
Quando a feature participa de uma execução de agente, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id` e demais chaves de correlação no estado/eventos. Isso permite acompanhar a decisão no Langfuse/Observer sem colocar lógica de observabilidade dentro do domínio.
### 8. Como testar
1. Crie um teste unitário do comportamento principal.
2. Crie um teste de integração do runtime quando houver estado entre turns.
3. Verifique o caso feliz e pelo menos um caso de falha/negação.
4. Confirme que não há side effects duplicados em retry/replay quando a feature toca transações.
5. Em produção, valide também telemetria e correlação de IDs.
### 9. Erros comuns
- Se o estado terminal não for persistido, outra réplica pode reabrir a jornada.
- Não use replay técnico/JSON como fala do cliente.
- Essa feature não substitui política de nova sessão intencional.
### 10. Relação com outras features
Esta feature deve ser usada junto das demais capacidades horizontais do framework, em vez de criar uma implementação paralela no agente de domínio. Em fluxos transacionais, considere especialmente **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery** e **Guardrails**.
### 11. Referências no repositório
- `libs/agent_framework/src/agent_framework/channels/interruption.py`
- `libs/agent_framework/src/agent_framework/config/settings.py`
- `Tuning-Performance/`
- `Documentacao/`
- `libs/agent_framework/docs/`
---
## English (EN)
### 1. What it is
Prevents residual audio or late messages from reopening a session that has already been finalized.
### 2. Problem it solves
Production agents should not rely on prompts alone to “do the right thing”. This feature moves a specific responsibility into a controlled framework layer, reducing unpredictable behavior and duplicate domain-agent code.
### 3. Simplified flow
```text
terminal session
residual input
policy detects finalization
replay last utterance/fallback
DO NOT reopen LangGraph
```
### 4. How it works internally
The interruption policy checks terminal-session metadata before treating an input as a new intent. When terminal speech is available, it uses `last_assistant_text`/`terminal_replay_text`; otherwise it may use `POST_FINALIZE_REPLAY_MESSAGE`.
The purpose is to protect the logical end of a session, especially on voice channels where audio packets may arrive after the finalization event.
### 5. How to enable/configure
Exact activation depends on the template/agent. Check framework settings, YAML configuration, and the service template. Not every feature requires a global flag: some are activated by the contract returned from a tool/workflow.
### 6. Example
```text
Agent: "The interaction is complete."
→ session finalized
late fragment arrives: "uh..."
→ replay "The interaction is complete."
→ no new routing / tool / LLM call
```
### 7. Telemetry and observability
When the feature participates in an agent execution, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id`, and other correlation keys in state/events. This makes the decision observable through Langfuse/Observer without embedding observability logic in the domain.
### 8. How to test
1. Add a unit test for the core behavior.
2. Add a runtime integration test when state spans multiple turns.
3. Test the happy path and at least one failure/rejection path.
4. Confirm retries/replays do not duplicate side effects for transactional features.
5. In production, also validate telemetry and ID correlation.
### 9. Common mistakes
- If terminal state is not persisted, another replica may reopen the journey.
- Do not replay technical/JSON envelopes as user-facing speech.
- This feature does not replace an intentional new-session policy.
### 10. Relationship with other features
Use this feature together with the framework's horizontal capabilities rather than creating a parallel implementation in domain-agent code. For transactional journeys, pay special attention to **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery**, and **Guardrails**.
### 11. Repository references
- `libs/agent_framework/src/agent_framework/channels/interruption.py`
- `libs/agent_framework/src/agent_framework/config/settings.py`
- `Tuning-Performance/`
- `Documentacao/`
- `libs/agent_framework/docs/`

View File

@@ -0,0 +1,171 @@
# Guardrails de Retrieval e Tools / Retrieval / Tool Guardrails
> Feature do `agent_framework_oci` — guia bilíngue PT-BR / EN.
**Implementação principal / Main implementation:** `guardrails/pipeline.py + guardrails/rails.py`
---
## Português (PT-BR)
### 1. O que é
Aplica proteção não apenas na mensagem do usuário e na resposta final, mas também no conhecimento recuperado por RAG e nos argumentos/resultados de ferramentas.
### 2. Problema que resolve
Em agentes de produção, não é suficiente pedir ao LLM que “faça a coisa certa”. Esta feature move uma responsabilidade específica para uma camada controlada do framework, reduzindo comportamento imprevisível e código duplicado nos agentes de domínio.
### 3. Fluxo simplificado
```text
Usuário
Input Guardrails
RAG → Retrieval Guardrails
LLM/Tool call → Tool Guardrails
API
Output Guardrails
```
### 4. Como funciona internamente
O framework possui stages distintos de guardrails. Para retrieval, rails como `RAGSEC` e `RET_REL` podem validar segurança e relevância do conteúdo recuperado. Para tools, `TOOL_VAL` valida o uso/argumentos antes ou ao redor da execução.
As configurações globais incluem `ENABLE_INPUT_GUARDRAILS`, `ENABLE_OUTPUT_GUARDRAILS`, `ENABLE_PARALLEL_GUARDRAILS`, `GUARDRAILS_FAIL_FAST` e `GUARDRAILS_CONFIG_PATH`. O YAML é a fonte de verdade dos rails ativados por agente.
### 5. Como ativar/configurar
A ativação exata depende do template/agente. Verifique o arquivo de settings, YAMLs de configuração e o template usado pelo serviço. Nem toda feature precisa de uma flag global: algumas são ativadas pelo contrato retornado por uma tool/workflow.
### 6. Exemplo
```yaml
retrieval:
rails:
- RAGSEC
- RET_REL
tool:
rails:
- TOOL_VAL
```
Exemplo: a pergunta é sobre cancelamento de um serviço, mas o RAG retorna documentação de modem. `RET_REL` pode rejeitar o contexto antes que ele seja usado na resposta.
### 7. Telemetria e observabilidade
Quando a feature participa de uma execução de agente, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id` e demais chaves de correlação no estado/eventos. Isso permite acompanhar a decisão no Langfuse/Observer sem colocar lógica de observabilidade dentro do domínio.
### 8. Como testar
1. Crie um teste unitário do comportamento principal.
2. Crie um teste de integração do runtime quando houver estado entre turns.
3. Verifique o caso feliz e pelo menos um caso de falha/negação.
4. Confirme que não há side effects duplicados em retry/replay quando a feature toca transações.
5. Em produção, valide também telemetria e correlação de IDs.
### 9. Erros comuns
- Ter a implementação do rail não significa que ele está ativo: confira `guardrails.yaml`.
- Fail-fast deve ser escolhido conscientemente para cada stage.
- Tool guardrail não substitui validação de negócio dentro da própria API/action.
### 10. Relação com outras features
Esta feature deve ser usada junto das demais capacidades horizontais do framework, em vez de criar uma implementação paralela no agente de domínio. Em fluxos transacionais, considere especialmente **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery** e **Guardrails**.
### 11. Referências no repositório
- `libs/agent_framework/src/agent_framework/guardrails/pipeline.py`
- `libs/agent_framework/src/agent_framework/guardrails/rails.py`
- `Tuning-Performance/`
- `Documentacao/`
- `libs/agent_framework/docs/`
---
## English (EN)
### 1. What it is
Applies safety and validation not only to user input and final output, but also to RAG-retrieved knowledge and tool arguments/results.
### 2. Problem it solves
Production agents should not rely on prompts alone to “do the right thing”. This feature moves a specific responsibility into a controlled framework layer, reducing unpredictable behavior and duplicate domain-agent code.
### 3. Simplified flow
```text
User
Input Guardrails
RAG → Retrieval Guardrails
LLM/Tool call → Tool Guardrails
API
Output Guardrails
```
### 4. How it works internally
The framework has distinct guardrail stages. For retrieval, rails such as `RAGSEC` and `RET_REL` can validate retrieved-content safety and relevance. For tools, `TOOL_VAL` validates usage/arguments before or around execution.
Global settings include `ENABLE_INPUT_GUARDRAILS`, `ENABLE_OUTPUT_GUARDRAILS`, `ENABLE_PARALLEL_GUARDRAILS`, `GUARDRAILS_FAIL_FAST`, and `GUARDRAILS_CONFIG_PATH`. The agent YAML is the source of truth for enabled rails.
### 5. How to enable/configure
Exact activation depends on the template/agent. Check framework settings, YAML configuration, and the service template. Not every feature requires a global flag: some are activated by the contract returned from a tool/workflow.
### 6. Example
```yaml
retrieval:
rails:
- RAGSEC
- RET_REL
tool:
rails:
- TOOL_VAL
```
Example: the question concerns canceling a service, but RAG retrieves modem documentation. `RET_REL` can reject that context before it is used in the answer.
### 7. Telemetry and observability
When the feature participates in an agent execution, preserve `request_id`, `trace_id`, `session_id`, `agent_id`, `message_id`, and other correlation keys in state/events. This makes the decision observable through Langfuse/Observer without embedding observability logic in the domain.
### 8. How to test
1. Add a unit test for the core behavior.
2. Add a runtime integration test when state spans multiple turns.
3. Test the happy path and at least one failure/rejection path.
4. Confirm retries/replays do not duplicate side effects for transactional features.
5. In production, also validate telemetry and ID correlation.
### 9. Common mistakes
- Having a rail implementation does not mean it is enabled: check `guardrails.yaml`.
- Fail-fast behavior should be chosen intentionally for each stage.
- Tool guardrails do not replace business validation inside the API/action itself.
### 10. Relationship with other features
Use this feature together with the framework's horizontal capabilities rather than creating a parallel implementation in domain-agent code. For transactional journeys, pay special attention to **Clarification**, **Pause/Resume**, **Durable Idempotency**, **Workflow Error Recovery**, and **Guardrails**.
### 11. Repository references
- `libs/agent_framework/src/agent_framework/guardrails/pipeline.py`
- `libs/agent_framework/src/agent_framework/guardrails/rails.py`
- `Tuning-Performance/`
- `Documentacao/`
- `libs/agent_framework/docs/`

View File

@@ -1,10 +1,62 @@
# Feature Guides / Guias de Features # Feature Guide — agent_framework_oci
Escolha o idioma / Choose a language: Guia consolidado e bilíngue das principais capabilities horizontais do framework. Cada página contém **Português (PT-BR)** e **English (EN)** no mesmo arquivo.
- [Português (PT-BR)](pt-BR/README.md) Consolidated bilingual guide for the framework's main horizontal capabilities. Each page contains **Portuguese (PT-BR)** and **English (EN)** in the same file.
- [English (EN)](en/README.md)
Os 15 arquivos bilíngues originais continuam neste diretório para compatibilidade, mas as árvores `pt-BR/` e `en/` são as versões recomendadas para leitura e distribuição. | # | Feature |
|---:|---|
| 01 | [Autenticação / Authentication](01_authentication.md) |
| 02 | [Workflow Transacional Determinístico / Deterministic Transactional Workflow](02_deterministic_transactional_workflow.md) |
| 03 | [Composição por LLM Solicitada pelo Domínio / Domain Requested LLM Composition](03_domain_requested_llm_composition.md) |
| 04 | [RAG Solicitado pelo Domínio / Domain Requested RAG](04_domain_requested_rag.md) |
| 05 | [Memória de Longo Prazo / Long Term Memory](05_long_term_memory.md) |
| 06 | [Regressão Offline de Workflow / Offline Workflow Regression](06_offline_workflow_regression.md) |
| 07 | [Pause / Resume de Workflow / Pause / Resume Workflow](07_pause_resume_workflow.md) |
| 08 | [Aderência de Rota / Route Stickiness](08_route_stickiness.md) |
| 09 | [Replay em Interrupções de Voz / Voice Interruption Replay](09_voice_interruption_replay.md) |
| 10 | [Recuperação de Erro em Workflow / Workflow Error Recovery](10_workflow_error_recovery.md) |
| 11 | [Clarificação / Clarification](11_clarification.md) |
| 12 | [Idempotência Durável / Durable Idempotency](12_durable_idempotency.md) |
| 13 | [Estados Transacionais Dinâmicos / Dynamic Transaction States](13_dynamic_transaction_states.md) |
| 14 | [Replay Após Finalização / Post Finalization Replay](14_post_finalization_replay.md) |
| 15 | [Guardrails de Retrieval e Tools / Retrieval / Tool Guardrails](15_retrieval_tool_guardrails.md) |
The original 15 bilingual files remain in this directory for backward compatibility, but the `pt-BR/` and `en/` trees are the recommended versions for reading and distribution. ## Mapa conceitual / Conceptual map
```text
LLM
├── Conversation
│ ├── Clarification
│ ├── Route Stickiness
│ └── Long Term Memory
├── Knowledge
│ ├── Domain Requested RAG
│ └── Retrieval Guardrails
├── Transactions
│ ├── Deterministic Transactional Workflow
│ ├── Pause / Resume
│ ├── Dynamic Transaction States
│ ├── Durable Idempotency
│ └── Workflow Error Recovery
├── Response
│ └── Domain Requested LLM Composition
├── Voice
│ ├── Voice Interruption Replay
│ └── Post Finalization Replay
└── Platform
├── Authentication
└── Offline Workflow Regression
```
## Princípio de arquitetura / Architecture principle
**PT-BR:** o LLM entende e redige; o framework controla estado, segurança, memória, roteamento e transações; o domínio contém regras específicas de negócio.
**EN:** the LLM understands and writes; the framework controls state, security, memory, routing, and transactions; the domain contains business-specific rules.

Some files were not shown because too many files have changed in this diff Show More