This commit is contained in:
2026-11-08 20:08:53 +08:00
parent 7526a5fe4d
commit 9b924747c5
2692 changed files with 394867 additions and 0 deletions

3
ai_agentic/__init__.py Normal file
View File

@@ -0,0 +1,3 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from . import controllers
from . import models

View File

@@ -0,0 +1,48 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'AI',
'category': 'Hidden',
'summary': "A powerful suite of AI tools and agents integrated directly into your Odoo environment",
'description': """
* Create and manage AI agents for various business tasks
* Integrate with popular AI models and services
* Process documents and extract information automatically
* Enhance customer service with AI-powered responses
* Automate routine tasks with intelligent workflows
""",
'depends': ['attachment_indexation', 'ai', 'base_automation'],
'data': [
'security/ir.access.csv',
'data/ir_actions_server_data.xml',
'data/ai_skill_data.xml',
'data/ai_agent_data.xml',
'views/base_automation_views.xml',
'views/ir_actions_server_views.xml',
'views/ai_agent_views.xml',
'views/ai_skill_views.xml',
'views/ai_composer_views.xml',
'views/ai_menus.xml',
'views/ai_prompt_button_views.xml',
],
'assets': {
'web.assets_backend': [
'ai_agentic/static/src/**/*',
],
'web.assets_unit_tests': [
'ai_agentic/static/tests/**/*',
],
'mail.assets_public': [
'ai_agentic/static/src/discuss/core/common/**/*',
],
'im_livechat.assets_embed_core': [
'ai_agentic/static/src/discuss/core/common/**/*',
],
'portal.assets_chatter_helpers': [
'ai_agentic/static/src/discuss/core/common/**/*',
],
},
'application': True,
'author': 'Odoo S.A.',
'license': 'OEEL-1',
'iap_paid_service': True,
}

View File

@@ -0,0 +1,2 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from . import messaging_menu

View File

@@ -0,0 +1,25 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.fields import Domain
from odoo.addons.ai.controllers.messaging_menu import AIMessagingMenuController
class AIAgenticMessagingMenuController(AIMessagingMenuController):
def _get_menu_tab_domain(self, tab_id):
# automation runs get their own tab, and leave the AI chat tab
if tab_id.startswith("ai-chat"):
return super()._get_menu_tab_domain(tab_id) & Domain("from_ai_automation", "=", False)
if tab_id.startswith("ai-automation:"):
agent_id = int(tab_id.split(":")[1])
return (
Domain("channel_type", "=", "ai_chat")
& Domain("from_ai_automation", "=", True)
& self._get_ai_agent_channels_domain(agent_id)
)
return super()._get_menu_tab_domain(tab_id)
def _get_menu_tab_filter_domain(self, tab_id, filter_id):
if tab_id.startswith("ai-automation:") and filter_id == "ai_automation_unread":
return Domain("self_member_id.is_unread", "=", True)
return super()._get_menu_tab_filter_domain(tab_id, filter_id)

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<odoo>
<record id="ai.ai_default_agent" model="ai.agent">
<field name="skill_ids" eval="[(4, ref('ai_agentic.ai_skill_automations'))]"/>
</record>
</odoo>

View File

@@ -0,0 +1,123 @@
<?xml version="1.0" encoding="utf-8"?>
<odoo>
<record id="ai_skill_self_update" model="ai.skill">
<field name="name">Self Update</field>
<field name="description">Lets the agent change its own instructions, add or remove linked skills, create custom skills, and add sources with the standard Search, Create Records, and Update Records tools. Load this skill when the user asks it to remember a rule or learn a procedure, or when no available skill covers the request.</field>
<field name="instructions"># Skill: Self Update
You have native record tools to read and change your own configuration: your name, subtitle and instructions (`ai.agent`), the skills linked to you (`skill_ids`), and to create and add new skills (`ai.skill`) or new sources (`ai.agent.source`). Use `ai_tool_search` to read, `ai_tool_update_records` to change existing records, and `ai_tool_create_records` to create records.
## Rules
- Change your configuration only in the three cases below. Implicit hints, one-off phrasings and your own guesses about what the user "probably wants" are not reasons to self-update.
- A change only exists once `ai_tool_update_records` or `ai_tool_create_records` ran successfully in the SAME turn. Never claim a change you have not made, in any tense: neither "OK, I'll remember that" nor "I've updated my role" is allowed without a successful call in that same turn.
- Every text-field write is a full-field replacement, not a merge. Read the current value with `ai_tool_search` first, and repeat the parts you keep. Your own current `system_prompt` is also visible as `agent_protocol`.
- Get your own id from `&lt;odoo_current_context&gt;`, which contains `{"model": "ai.agent", "id": N}`: every write on yourself needs an exact domain naming that numeric id. If the user explicitly names another agent, find it with `ai_tool_search` and use its exact id; never silently change another agent.
- Pass all the changes of one turn in a single `ai_tool_update_records` call with `preview_menus: []`. One confirmation card covers them all, and that card is the approval: put the reason and confirmation question in `explanation` and do not ask for confirmation in your message text too. Native Create Records and Update Records require confirmation for both blank and configured agents.
- `load_skills` never links a skill. A skill found by catalog search is only a candidate and cannot be loaded until a confirmed `ai_tool_update_records` call has linked it to the current agent's `skill_ids` and returned successfully. The user's original request is not that confirmation. If `load_skills` says a skill is not linked, do not retry it: perform the Update Records step first.
- Only the `agent_protocol` section of your instructions is yours. `global_protocol`, `usage_context`, `knowledge_protocol`, `skills_protocol`, `available_skills`, `loaded_skills` and `agent_setup_state` are injected on every turn: never copy them into your instructions.
- On the FIRST update where you write your own `name` or `system_prompt`, you MUST send an `avatar_role` in that same call: a new agent always leaves its setup with an avatar. Once it is set, never send `avatar_role` again, even with the same value - a later rename or new instructions do not change your avatar - unless the user explicitly asks to change your look.
When you do choose one, use the "Update Records" tool to update your own record. In the `updates` dictionary, set the `avatar_role` field to exactly ONE of the following Role names based on the keywords:
* Worker (Builder, Operational, Hands-on, Practical)
* Headset (Empathetic, Patient, Helpdesk, Assistance)
* Sales (Persuasive, Outreach, Negotiator, Pitching)
* Librarian (Archival, Meticulous, Knowledgeable, Cataloging)
* Hoodie (Hacker, Agile, Startup, Casual, Developer)
* Detective (Investigative, Profiling, Forensic, Auditing)
* Artist (Creative, Aesthetic, Visual, Expressive)
* Architect (Strategic, Visionary, Structural, Blueprint)
Example tool argument:
{"avatar_role": "Sales"}
## Case 1: A capability you are missing
The user asks you to do something none of your loaded or available skills can do.
1. Search the catalog with `ai_tool_search` on `ai.skill`, using `domain: "[]"` and fields `id`, `name`, `description`, `tool_ids` and `is_native_skill`, before telling the user you cannot do it and before ending the turn on a question a catalog skill would let you answer yourself. The returned `tool_ids` are record ids: collect the distinct ids, then search `ir.actions.server` with a domain limited to those ids and fields `id` and `ai_tool_name`, and map the results back to each skill. Never use an empty domain, browse unrelated server actions, or guess ids.
2. Link EVERY skill the full task needs in one `ai_tool_update_records` call, with `x2m_commands` on the exact target agent's `skill_ids`, e.g. `"[(4, 12, 0), (4, 15, 0)]"`. Walk the task end to end first, including every step an automation you are about to create will run later: "reassign my open tickets to Marc Demo" needs both a skill to search records (find the tickets, resolve the user) and a skill to update them; "tag new tickets automatically" needs the skills to build the automation AND to search, create and update the records its steps touch (linking Build Automation always means linking Search Records, Create Records and Update Records with it). One confirmation card must cover all of them: never come back with a second card for skills the same task already needed. Link only what the task needs: prefer the executable skills whose tools cover it, and add a guidance skill only when it supports one of those. Never pad the list with loosely related skills.
3. Phrase the `explanation` as why the task needs those skills, e.g. "To reassign your tickets I need to search and update records. Confirm?"
4. Once that update is confirmed, call `load_skills` with the same ids - not before, the skills are not linked yet and the call fails - then finish the user's original request with their tools in that same turn. Linking and loading are setup, never the answer: an automation the user asked for is still missing until you create it. This follow-up is allowed even if `load_skills` was already called in this request. When changing another agent, do not load its skills into yourself.
5. Never link a skill whose description reserves it for a dedicated flow (e.g. the Livechat lead skill): its tools skip the usual confirmation cards. If only such skills match, treat the search as empty.
6. Only once the search comes up empty may you say the capability is missing. Say what is missing; never invent a skill out of guessed tool ids.
7. Resolve names to records yourself with the linked tools. Ask the user only when a search returns nothing or several ambiguous matches.
This case never touches your instructions.
## Case 2: The user changes you on purpose
Applies to explicit requests: "always answer in French", "stop signing your messages", "remember that...", "from now on...", "learn how to...".
- A correction or a repeatable procedure ("we never sign off with 'Best', use 'Thanks'", "here is how we vet a new supplier") belongs in a custom skill. This is the default destination for learned behavior.
- Identity and rules that must apply to EVERY request whatever the topic (language, persona, tone) belong in `system_prompt`. Keep it small; when in doubt, prefer a skill.
- A workflow that should run on its own on an event or a schedule ("when a ticket is created, set its priority and draft a reply") is not self-configuration: it is an automation to create in Odoo. Handle it as case 1, and a request about WHEN or HOW OFTEN an existing automation runs ("only on working days", "every 2 hours") is an update of that automation's trigger with the automation skill, never of your instructions; and only afterwards consider reflecting the purpose in your instructions.
## Case 3: Keeping your instructions in sync with real usage
Update `system_prompt` when your instructions are still blank and the message reveals a lasting role, when the user pivots the current role ("make it for crypto instead", "we sell to Y now"), or when repeated requests reveal a recurring purpose your instructions do not mention. Small talk, questions and one-off tasks do not count, whatever their scale.
- Ask two or three short questions before writing: WHO it works for and targets (industry, product line, geography, customer type), WHAT it does on each run (steps, sources, quality criteria, how many results), WHERE the output goes in Odoo (which records to create or update, which fields). Do not invent details the user did not state.
- In the turn the answers arrive, write the instructions FIRST, then continue the actual work in the same turn. A complete one-line preference ("always answer briefly") needs no question: write it as is, immediately.
- Structure them as `### Who You Are`, `### What You Do`, `### How You Work`, `### What Makes a Good [Result]` and `### Output`, plus any section the specifications justify. Start your top level at `###`, and at `##` only if the sections nest deeper than two levels: your instructions are read in a narrow panel, where a `#` title takes the whole width. Aim for 150 to 300 words of Markdown addressed to the agent as "You", with no XML tags and no protocol text. Fall back to one or two plain sentences only when the user gave nothing beyond a one-line preference.
- Update `name` and `subtitle` as their own changes, never inside the instructions text. The name is who you are, not what you do: "Company Enricher", not "Company Enrichment". The subtitle is the one line shown under that name: what you do for the user, written in first person as the agent describing itself, at most about 60 characters ("I find and qualify new leads every Monday", "I qualify and tag tickets in progress"). Never write it in third person or as an infinitive ("Finds and qualifies new leads", "Qualifies tickets"). Whenever you write `name` or `system_prompt`, write `subtitle` in the SAME call: a setup that leaves it at its default is incomplete.
- Announce the change in first person about yourself ("I've set myself up as your recruiting screener"), never as something happening to the user, then offer the next step: a test run now, by calling the run automation tool (its "Run" / "Not now" card is the offer, never a question in your text), or a recurring schedule. When changing another agent, name that agent instead.
- When you create an automation for yourself while your name or instructions are still the defaults, set them in the same turn: an agent that runs on its own needs a name and a role that say what it runs. That same update must also link every skill the automation's steps will need when it runs (searching, creating, updating the records it touches), so the user confirms once: a second card asking for more skills right after is a failure.
- Native `ai_tool_update_records` always asks the user to confirm, for both blank and configured agents.
- If the new instructions center on one business record type (a lead, a task, an invoice…), after writing them offer to become that model's default AI assistant:
1. Resolve the model's `id` (`ai_tool_search` on `ir.model`), then search `ai.composer` for `[('interface_key', '=', 'chatter_ai_button'), ('focused_model_id', '=', &lt;ir_model_id&gt;)]` (fields `id`, `ai_agent_id`, `available_prompt_ids`). One rule exists per model, whatever the agent: reuse the row if found, never create a second.
2. In the same turn as the instructions confirmation, announce and offer: "I've set myself up as your &lt;role&gt;. Since your role is centered on &lt;Model name&gt;, I could also become the default assistant summoned by the top-right AI button on a &lt;Model name&gt; record." (if the found row is another agent's, add that binding would replace it). Then `ai_tool_ask_user_question`, `question` = "From your instructions, it looks like you'll need me while working on &lt;Model name&gt; records. Should I be the default agent summoned when you click the top-right AI button on a &lt;Model name&gt;?", `choices` = ["Yes, make me the default on &lt;Model name&gt;", "No, keep the current default"], `multi_select` = false, `allow_free_text` = false.
3. On "No", stop. On "Yes", pick 2 to 4 concrete action names from the new `system_prompt` ("Qualify Lead", never a category like "Qualify"), bridge in one line ("OK, then let's set that up — the next card saves the default prompt and default actions for the &lt;Model name&gt; AI button."), then write the rule as yourself with `name` = the model's display name ("Lead", not "&lt;Agent name&gt; on Lead") and `is_system_default` false:
- Found a row → `ai_tool_update_records`: `ai_agent_id` = your id, `available_prompt_ids` via `x2m_commands = "[(5, 0, 0), (0, 0, {'name': '&lt;label&gt;', 'prompt': '&lt;prompt&gt;'}), …]"`.
- No row → `ai_tool_create_records` on `ai.composer` (`interface_key='chatter_ai_button'`, `focused_model_id`, `ai_agent_id` = your id), then one on `ai.prompt.button` per action (`name`, `prompt`, `composer_id`).
## Writing a skill
- You cannot create tools and `ai_tool_search` only exposes tool identities through existing skills, so a skill you write never has tools of its own. It is a guidance skill: the vocabulary, rules and procedure that make an existing capability behave the way the user wants.
- Capability always comes from linking an existing catalog skill (case 1), never from assembling tools yourself. If no catalog skill performs the action, say what is missing instead of writing a skill for it.
- Create and link it with `ai_tool_create_records` on `ai.skill`: one `field_values` entry containing `name`, `description`, `instructions` and `{"field":"agent_ids","x2m_link_ids":[N]}`, where `N` is the exact target agent id. Omit `preview_menu_id` and never set `is_native_skill`.
- Only create a skill when the user teaches a repeatable procedure no existing skill covers. Search first: link an equivalent skill instead of duplicating it.
- Name in its description the executable skill it supports: both load together when relevant.
- A skill you create is linked but not loaded: for your own agent, call `load_skills` with its returned id when you need its instructions in this conversation. Do not load it when changing another agent.
- Write it for an agent with zero prior context: one coherent task, each rule with its trigger ("when the user asks to cancel a subscription..."), one short example per non-obvious rule, and what to do when information is missing or the request is ambiguous. Headers and short bullets over dense prose. Cut any line that does not change a decision ("always be professional").
- Never modify a native skill. If asked to change one, create a custom skill instead.
## Adding a source
- A source needs content of its own: `ai_tool_create_records` creates the `ai.agent.source` record and attaches it to the target agent, it never produces the file or the article behind it.
- When that content does not exist yet, treat it as case 1: link the skills that create the attachment, knowledge article or document, create the content with them, then come back here and create the source pointing at it with `attachment_id`.
- Create it with `ai_tool_create_records` on `ai.agent.source`, passing `name`, the existing `attachment_id`, and the exact target `agent_id` as simple field values. Omit `preview_menu_id`; the native tool never sets `agent_id` for you.
- Sources can be added, never changed or removed: for that, ask the user to use the agent panel.
## After any change
Briefly confirm to the user what changed.</field>
<field name="tool_ids" eval="[(6, 0, [
ref('ai.ir_actions_server_search'),
ref('ai.ir_actions_server_create_records'),
ref('ai.ir_actions_server_update_records'),
])]"/>
<field name="is_native_skill" eval="True"/>
</record>
<record id="ai_skill_automations" model="ai.skill">
<field name="name">Build Automation</field>
<field name="description">Create and update persistent automations for actions you should perform later, repeatedly or in response to record event. Use this skill when the user asks you to perform an action or send a reminder at a future time, on a recurring schedule, or when records are created, changed, deleted, messaged, or meet specified conditions. The user may refer to them as "Triggers".
This skill only allows to update or create automations.
This skill requires the Search Records, Create Records and Update Records skills: an automation's steps always search, create or update records. Whenever you link this skill to an agent, link those three in the SAME update (never in a later one) and load them together with it.</field>
<field name="tool_ids" eval="[(6, 0, [
ref('ir_actions_server_ai_create_update_automation'),
ref('ir_actions_server_ai_run_automation')
])]"/>
<field name="instructions">
An automation is a `base.automation` record with a prompt linked to an agent. When the automation triggers, the agent processes the prompt.
You can only create or edit automations that are linked to you ('ai_agent_id', '=', AGENT_ID). The automations that you create will be automatically linked to you.
Only use the tool `ai_tool_create_update_automation` to create or update `base.automation` records.
Enable/Disable existing automations using the `active` field. When searching for automations linked to you, search for active and inactive ones.
## Trigger type info
Prefer time-based triggers: "when a ticket is created, …" is `on_time_created` (with a 1 minute delay), "whenever a record is updated, …" is `on_time_updated`, a date-relative rule is `on_time`. They run the agent shortly after the event without blocking the user's save. Use `on_create` / `on_create_or_write` only when the user explicitly asks the action to happen immediately during the save, or for a transition on specific fields that needs `filter_pre_domain`.
## Domains
The trigger determines when an automation is evaluated. Its applicable domains determine whether it runs. Use both `filter_pre_domain` and `filter_domain` when the request describes a transition, rather than merely a final state.
## Action Prompt
The automation action will be run by you, so write `ai_action_prompt` as a clear description of what you should do when the automation triggers.
**Critical: Capability Verification**
You will have the same skills and tools as you currently have when the automation runs. Therefore, before creating or updating a prompt, you must verify that you have the skills/tools required to execute every step.
The Search Records, Create Records and Update Records skills are part of this skill's requirements (an automation's steps always search, create or update records): if any of them is not linked to you yet, link all the missing ones together with this skill in ONE Self Update, and load them with it.
- If your current linked skills do not cover every step of the prompt (e.g., it updates records but you lack the 'Update Records' skill), use the Self Update skill to link ALL the missing skills to yourself in ONE update, never one skill at a time: walk every step of the prompt first and collect what each needs.
- Only after the required skills are linked and loaded should you proceed to create the automation.
Posting the result in the automation's own chat needs no tool: the run's final message lands there automatically.
</field>
</record>
</odoo>

View File

@@ -0,0 +1,141 @@
<?xml version="1.0" encoding="utf-8"?>
<odoo>
<record id="ir_actions_server_ai_run_automation" model="ir.actions.server">
<field name="name">AI Tool: Run Automation</field>
<field name="ai_tool_name">ai_tool_run_trigger</field>
<field name="state">code</field>
<field name="use_in_ai" eval="True"/>
<field name="code">ai['result'] = record._ai_tool_run_automation(ai, base_automation_id)</field>
<field name="model_id" ref="model_ai_tool"/>
<field name="ai_tool_thinking_text">Running the automation</field>
<field name="ai_tool_description">
Runs a time-based automation right now, exactly as its schedule would: spawns an duplicate of the agent that executes the actions instructions in a headless run, and shows the result of it in the chat.
Use it when the user asks to run, test or try an automation now, instead of ever executing the automation's steps yourself in the conversation. Only time-based automations (scheduled actions and time rules) can run on demand; an event-based rule is tested by creating or updating a record that matches its trigger.
After creating a time-based automation, offer the user to run it once by CALLING this tool right away: its confirmation card ("Run" / "Not now") is the offer. Never ask "should I run it?" in your message text instead, that leaves the user without the Run button.
</field>
<field name="ai_tool_schema">
{
"type": "object",
"properties": {
"base_automation_id": {
"type": "integer",
"description": "Id of the automation to run."
}
},
"required": ["base_automation_id"]
}
</field>
</record>
<record id="ir_actions_server_ai_create_update_automation" model="ir.actions.server">
<field name="name">AI Tool: Create or Update Automation</field>
<field name="ai_tool_name">ai_tool_create_update_automation</field>
<field name="state">code</field>
<field name="code">ai['result'] = record._ai_tool_create_update_automation(ai, automation_id, name, description, active, trigger, ai_action_prompt, explanation)</field>
<field name="use_in_ai" eval="True"/>
<field name="model_id" ref="model_ai_tool"/>
<field name="ai_tool_thinking_text">Working on your automation</field>
<field name="ai_tool_description">
Create and update persistent automations for actions you should perform later, repeatedly or in response to record event. Use this tool when the user asks you to perform an action or send a reminder at a future time, on a recurring schedule, or when records are created, changed, deleted, messaged, or meet specified conditions.
When creating a new automation, `name`, `description`, `trigger`, `ai_action_prompt` and `explanation` are required.
When editing an existing automation, `automation_id` and `explanation` are required. For the other parameters, only provide the ones that need to be updated.
## Trigger type
Prefer the time-based triggers (`on_time_created`, `on_time_updated`, `on_time`) over the synchronous ones (`on_create`, `on_create_or_write`): they run shortly after the event instead of during the user's save. "When a ticket is created, …" is `on_time_created` with a 1 minute delay; "whenever a lead is updated, …" is `on_time_updated`. Use `on_create` / `on_create_or_write` only when the user explicitly asks for an immediate, synchronous action, or for a transition on specific fields that needs `filter_pre_domain`.
## Trigger examples
- Tag every new ticket (preferred creation trigger): `{"trigger": {"type": "on_time_created", "target_model": "helpdesk.ticket", "date_offset_or_interval": {"amount": 1, "unit": "minutes"}}}`
- Trigger when the tag "Bug" is added on my tasks (a field transition, hence `on_create_or_write`): `{"trigger": {"type": "on_create_or_write", "observed_fields": ["tag_ids"], "filter_pre_domain": "[('tag_ids', 'not in', ['Bug'])]", "filter_domain": "[('tag_ids', 'in', ['Bug']), ('user_id', '=', 3)]"}}` (if the ID of the user is 3).
- Trigger the day before the expected closing date: `{"trigger": {"type": "on_time", "observed_fields": "date_deadline", "date_offset_or_interval": {"direction": "before", "amount": 1, "unit": "day"}}}`
- Trigger on creation if the record is unassigned: `{"trigger": {"type": "on_time_created", "filter_domain": "[('user_id', '=', False)]", "date_offset_or_interval": {"amount": 5, "unit": "minutes"}}}`
- Trigger on each Monday: `{"trigger": {"type": "on_schedule", "date_offset_or_interval": {"amount": 7, "unit": "day", "next_trigger_date": "2026-08-24 09:00:00"}}}` (if next Monday is 2026-08-24)
</field>
<field name="ai_tool_schema">
{
"type": "object",
"properties": {
"automation_id": {
"type": "integer",
"description": "The ID of the `base.automation` record to update. Leave empty to create a new one"
},
"name": {
"type": "string",
"description": "Name of the automation"
},
"description": {
"type": "string",
"description": "Short description of the automation. It should explain when the automation triggers, and what it does when triggered"
},
"active": {
"type": "boolean",
"description": "Whether the automation should be enabled or disabled"
},
"trigger": {
"type": "object",
"properties": {
"type": {
"type": "string",
"description": "When the automation should trigger. PREFER the time-based triggers: they run the agent shortly after the event, without blocking the user's save.\n- When a record is created ('when a ticket is created, …'): `on_time_created`, with a short delay in `date_offset_or_interval` (e.g. 1 minute). This is the default choice for creation.\n- When a record is created or updated ('whenever a lead changes, …'): `on_time_updated`, same short delay. This is the default choice for updates.\n- Only when the user EXPLICITLY asks the action to happen immediately, synchronously, during the save itself: `on_create` or `on_create_or_write`. `on_create_or_write` is also required for a transition on specific fields (needs `filter_pre_domain` / `filter_domain`).\n- When archived or unarchived: `on_archive` or `on_unarchive`\n- When a value changes in the UI before the record is saved: `on_change`\n- On deletion: `on_unlink`\n- When an external message is received on or sent from a record: `on_message_received` or `on_message_sent` (internal notes and system notifications are excluded)\n- Relative to a date or datetime field: `on_time`\n- On a clock-based recurrence: `on_schedule`"
},
"target_model": {
"type": "string",
"description": "Technical name of the model on which the automation should trigger (eg. `crm.lead`). Leave empty for clock-based recurrent triggers."
},
"filter_pre_domain": {
"type": "string",
"description": "Serialized Odoo domain a record must match before an update. Only allowed and optional for `on_create_or_write` (ignored when a record is created), `on_message_received` and `on_message_sent`."
},
"filter_domain": {
"type": "string",
"description": "Serialized Odoo domain a record must match when the automation is evaluated. Only allowed and optional for `on_create`, `on_create_or_write`, `on_archive`, `on_unarchive`, `on_change`, `on_unlink`, `on_time`, `on_time_created`, and `on_time_updated`."
},
"observed_fields": {
"anyOf": [
{
"type": "array",
"description": "List of fields of the target model whose modification should trigger the automation. Optional for `on_create_or_write` (leave empty to observe all fields) and required for `on_change_fields`.",
"items": {"type": "string"}
},
{
"type": "string",
"description": "Datetime field to observe, for `on_time`."
}
]
},
"date_offset_or_interval": {
"type": "object",
"description": "For time-based triggers, the offset at which the automation should trigger (eg. 'the day before the value of the deadline field'). For `on_schedule`, use it to set the interval at which the automation should trigger (eg. 'Every monday'), and set the `next_trigger_date`.",
"properties": {
"direction": {
"type": "string",
"enum": ["before", "after"]
},
"amount": {
"type": "integer",
"description": "amount of units"
},
"unit": {
"type": "string",
"enum": ["minutes", "hour", "day", "month"]
},
"next_trigger_date": {
"type": "string",
"description": "The next datetime at which the automation should trigger (UTC). Only for `on_schedule`."
}
},
"required": ["amount", "unit"]
}
},
"required": []
},
"ai_action_prompt": {
"type": "string",
"description": "The prompt that the agent (you) will receive when the automation triggers.\n- Must be a detailed prompt written in HTML markup: `&lt;h3&gt;` headings, `&lt;ol&gt;`/`&lt;ul&gt;` lists, `&lt;p&gt;` paragraphs. NEVER use Markdown syntax (`###`, `**bold**`, `1.` lists): the field renders HTML only, Markdown shows as raw text.\n- It should start with a short sentence saying why the agent is invoked. Eg. \"This automation runs because the tag `Bug` was added on the lead\" or \"This automation runs every Monday\".\n- It should contain the steps to take, in execution order, and should end by asking to provide a short summary of what was accomplished.\n- You can inline record field values using `&lt;span data-ai-field=\"field.path\"&gt;Label&lt;/span&gt;`, never with a bare `{{field.path}}`, which might save some information-retrieval steps when the automation is fired. This is not supported with clock-based automations (use the information-retrieval skill instead). Make sure to adapt it if the trigger type changes.\n- Embed an \"Execution context\" block containing useful resolved models, field names, and stable IDs as raw integers, to remove the need for information-retrieval calls.\n- When a step creates a record that has `partner_id`, also set `partner_invoice_id` and `partner_shipping_id` explicitly to the same ID, to avoid the onchange cascade that hangs on newly created customers.\n- When the request references incoming messages, emails, or replies, direct the agent to read the record's chatter (its latest messages), not a stored field like `description`.\n- Do not add a step that posts a chatter note or message explaining what was done, unless the user explicitly asked for one: the run already reports its reasoning in the automation chat.\n- When a step must email someone, direct the agent to create a `mail.mail` record (`email_to`, `subject`, and `body_html`; queued and sent automatically), never a `mail.message`: that is an internal chatter note and sends nothing."
},
"explanation": {
"type": "string",
"description": "An explanation of the tool call. It MUST end asking for user's CONFIRMATION"
}
},
"required": ["explanation"]
}
</field>
</record>
</odoo>

1107
ai_agentic/i18n/ar.po Normal file

File diff suppressed because it is too large Load Diff

1087
ai_agentic/i18n/az.po Normal file

File diff suppressed because it is too large Load Diff

1089
ai_agentic/i18n/bg.po Normal file

File diff suppressed because it is too large Load Diff

1088
ai_agentic/i18n/bs.po Normal file

File diff suppressed because it is too large Load Diff

1095
ai_agentic/i18n/ca.po Normal file

File diff suppressed because it is too large Load Diff

1095
ai_agentic/i18n/cs.po Normal file

File diff suppressed because it is too large Load Diff

1116
ai_agentic/i18n/da.po Normal file

File diff suppressed because it is too large Load Diff

1119
ai_agentic/i18n/de.po Normal file

File diff suppressed because it is too large Load Diff

1089
ai_agentic/i18n/el.po Normal file

File diff suppressed because it is too large Load Diff

1108
ai_agentic/i18n/es.po Normal file

File diff suppressed because it is too large Load Diff

1221
ai_agentic/i18n/es_419.po Normal file

File diff suppressed because it is too large Load Diff

1095
ai_agentic/i18n/et.po Normal file

File diff suppressed because it is too large Load Diff

1092
ai_agentic/i18n/fa.po Normal file

File diff suppressed because it is too large Load Diff

1117
ai_agentic/i18n/fi.po Normal file

File diff suppressed because it is too large Load Diff

1116
ai_agentic/i18n/fr.po Normal file

File diff suppressed because it is too large Load Diff

1093
ai_agentic/i18n/he.po Normal file

File diff suppressed because it is too large Load Diff

1105
ai_agentic/i18n/hi.po Normal file

File diff suppressed because it is too large Load Diff

1090
ai_agentic/i18n/hr.po Normal file

File diff suppressed because it is too large Load Diff

1092
ai_agentic/i18n/hu.po Normal file

File diff suppressed because it is too large Load Diff

1115
ai_agentic/i18n/id.po Normal file

File diff suppressed because it is too large Load Diff

1116
ai_agentic/i18n/it.po Normal file

File diff suppressed because it is too large Load Diff

1203
ai_agentic/i18n/ja.po Normal file

File diff suppressed because it is too large Load Diff

1084
ai_agentic/i18n/kab.po Normal file

File diff suppressed because it is too large Load Diff

1107
ai_agentic/i18n/ko.po Normal file

File diff suppressed because it is too large Load Diff

1086
ai_agentic/i18n/ku.po Normal file

File diff suppressed because it is too large Load Diff

1079
ai_agentic/i18n/lo.po Normal file

File diff suppressed because it is too large Load Diff

1091
ai_agentic/i18n/lt.po Normal file

File diff suppressed because it is too large Load Diff

1090
ai_agentic/i18n/lv.po Normal file

File diff suppressed because it is too large Load Diff

1092
ai_agentic/i18n/mn.po Normal file

File diff suppressed because it is too large Load Diff

1086
ai_agentic/i18n/my.po Normal file

File diff suppressed because it is too large Load Diff

1089
ai_agentic/i18n/nb.po Normal file

File diff suppressed because it is too large Load Diff

1118
ai_agentic/i18n/nl.po Normal file

File diff suppressed because it is too large Load Diff

1109
ai_agentic/i18n/pl.po Normal file

File diff suppressed because it is too large Load Diff

1105
ai_agentic/i18n/pt.po Normal file

File diff suppressed because it is too large Load Diff

1143
ai_agentic/i18n/pt_BR.po Normal file

File diff suppressed because it is too large Load Diff

1109
ai_agentic/i18n/ro.po Normal file

File diff suppressed because it is too large Load Diff

1108
ai_agentic/i18n/ru.po Normal file

File diff suppressed because it is too large Load Diff

1090
ai_agentic/i18n/sk.po Normal file

File diff suppressed because it is too large Load Diff

1090
ai_agentic/i18n/sl.po Normal file

File diff suppressed because it is too large Load Diff

1093
ai_agentic/i18n/sr@latin.po Normal file

File diff suppressed because it is too large Load Diff

1108
ai_agentic/i18n/sv.po Normal file

File diff suppressed because it is too large Load Diff

1098
ai_agentic/i18n/th.po Normal file

File diff suppressed because it is too large Load Diff

1111
ai_agentic/i18n/tr.po Normal file

File diff suppressed because it is too large Load Diff

1096
ai_agentic/i18n/uk.po Normal file

File diff suppressed because it is too large Load Diff

1167
ai_agentic/i18n/uz.po Normal file

File diff suppressed because it is too large Load Diff

1108
ai_agentic/i18n/vi.po Normal file

File diff suppressed because it is too large Load Diff

1111
ai_agentic/i18n/zh_CN.po Normal file

File diff suppressed because it is too large Load Diff

1108
ai_agentic/i18n/zh_TW.po Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,8 @@
from . import ai_agent
from . import ai_agent_source
from . import ai_session
from . import ai_automation_trigger
from . import ai_tool
from . import base_automation
from . import discuss_channel
from . import ir_actions_server

View File

@@ -0,0 +1,205 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import random
from odoo import SUPERUSER_ID, _, api, fields, models
from odoo.tools import BinaryBytes, file_open
from odoo.addons.ai.utils.ai_utils import markdown_format
AVATAR_NUMBERS = (1, 2, 3) # silhouettes per color, shared between naked and role variants
AVATAR_COLORS = ('Purple', 'Blue', 'Red', 'Teal', 'Yellow')
AVATAR_ROLES = ('Worker', 'Headset', 'Sales', 'Librarian', 'Hoodie', 'Detective', 'Artist', 'Architect')
NO_CUSTOM_INSTRUCTIONS_NOTE = """
This agent has no custom instructions yet and runs on a generic default role.
- Spend the turn on the user's actual request first. Greetings, questions, lookups and one-off tasks (even bulk ones) are WORK — never persist a setup for them.
- If the message reveals a lasting ROLE — a business domain the agent should specialize in ("we sell tables to companies", "help me qualify inbound leads"), a recurring workflow, or a stated behavior preference ("you are my …", "always …"), you need to first establish its operating framework from the information the user already provided:
* WHO it works for and targets: industry, product line, geo, customer type.
* WHAT it should do on each run: sources or steps, quality criteria, roughly how many results.
If not enough information is provided, ask questions through `ai_tool_ask_user_question` to get the full overview. A turn that only asks questions makes no changes. Any mention of the update should describe what you will change once the user answers, never imply that you have already changed it.
Once you have the full picture, load the Self Update skill and use it on the exact `ai.agent` id in `<odoo_current_context>` FIRST — persisting its `name`, `subtitle` and full operating framework as `system_prompt` — and only THEN continue the actual work in the same turn. Never invent details the user did not state (e.g. do not write "table manufacturing" when the user only said "we sell tables").
- A complete one-line behavior preference ("you are my helpdesk triage assistant, always answer briefly") needs NO clarifying questions: commit it immediately as-is.
- The role belongs to YOU, not to the user: once the update call has succeeded, announce the commit in first person about yourself ("I've set myself up as your lead prospector"), never as something happening to the user ("I've set up your new role"). Use that past tense only after the call returned successfully in this turn.
"""
SELF_UPDATE_SKILLS_PROTOCOL = """
- If the user asks you to remember a preference or rule, permanently change how you behave, or learn a new skill (e.g. "remember…", "from now on…", "always/never…", "note that…", "stop doing X", "learn how to…"), treat it as a self-configuration request: load the Self Update skill to persist it, instead of only acknowledging it or reaching for a generic create/email tool.
- For a missing capability, use a matching skill from other_skills. Add it in the agent configuration update, load it after the normal confirmation, and continue. If none exists, state that it is unavailable and stop.
- A recurring business workflow ("when/whenever a <record> is created/updated, do …", "every day at …, do …") is a request to CREATE an Automation in Odoo. Treat it as a task needing the automation skill — never as a preference to merely remember or acknowledge.
- The once-per-request limit does not block newly linked skills: after a successful Create Records or Update Records call links skills to the current agent, call `load_skills` with those new skill ids immediately. That follow-up is allowed even if `load_skills` was already used earlier in this request. Never load a skill merely because another agent was changed.
"""
class AIAgent(models.Model):
_inherit = 'ai.agent'
# Computed, not stored: the LLM only ever writes this once (self-update),
# never reads it back, and the avatar image already encodes the role.
avatar_role = fields.Selection(
[(role, role) for role in AVATAR_ROLES],
string="Avatar Role",
compute='_compute_avatar_role',
inverse='_inverse_avatar_role',
readonly=False,
help="Job role the agent depicts. Setting it redraws the avatar in the agent's own color.",
)
automation_ids = fields.One2many(
'base.automation',
'ai_agent_id',
string="Triggers",
help="Automation rules that run this agent by themselves.",
context={"active_test": False},
)
custom_skill_ids = fields.Many2many(
'ai.skill',
compute='_compute_custom_skill_ids',
inverse='_inverse_custom_skill_ids',
string="Custom Skills",
help="Skills configured by the user, excluding built-in native skills.",
)
system_prompt_rendered = fields.Html(
string="Rendered Instructions", compute='_compute_system_prompt_rendered', sanitize_style=True,
help="Read-only rendering of the Markdown instructions, shown in the agent panel.",
)
@api.depends('system_prompt')
def _compute_system_prompt_rendered(self):
for agent in self:
agent.system_prompt_rendered = markdown_format(agent.system_prompt or '')
@api.depends('skill_ids.is_native_skill')
def _compute_custom_skill_ids(self):
for agent in self:
agent.custom_skill_ids = agent.skill_ids.filtered(lambda skill: not skill.is_native_skill)
def _inverse_custom_skill_ids(self):
for agent in self:
agent.skill_ids = agent.custom_skill_ids | agent.skill_ids.filtered('is_native_skill')
def _avatar_attachment(self):
self.ensure_one()
return self.env['ir.attachment'].sudo().search([
('res_model', '=', 'res.partner'),
('res_field', '=', 'image_1920'),
('res_id', '=', self.partner_id.id),
], limit=1)
def _apply_avatar(self, key):
self.ensure_one()
with file_open(f'ai/static/avatars/{key}.png', 'rb') as f:
self.image_128 = BinaryBytes(f.read())
self._avatar_attachment().name = key
@api.depends('image_128')
def _compute_avatar_role(self):
for agent in self:
role = (agent._avatar_attachment().name or '').rpartition('-')[2]
agent.avatar_role = role if role in AVATAR_ROLES else False
def _inverse_avatar_role(self):
for agent in self.filtered('avatar_role'):
base = '-'.join(agent._avatar_attachment().name.split('-')[:2])
agent._apply_avatar(f"{base}-{agent.avatar_role}")
def write(self, vals):
prompt = vals.get('system_prompt')
if prompt and '\\n' in prompt and '\n' not in prompt:
# The LLM sometimes double-escapes newlines in its tool arguments
vals.update(system_prompt=prompt.replace('\\r\\n', '\n').replace('\\n', '\n'))
return super().write(vals)
def _store_agent_fields(self, res):
super()._store_agent_fields(res)
res.attr("has_automation_channels", self.env.user.has_group('base.group_system') and bool(
self.env['discuss.channel'].sudo().search_count([
('ai_agent_id', '=', self.id), ('from_ai_automation', '=', True),
], limit=1)))
def _get_setup_protocol(self):
self_update_skill = self.env.ref('ai_agentic.ai_skill_self_update', raise_if_not_found=False)
if not self_update_skill or self_update_skill not in self._get_available_skills():
return ""
if (self.system_prompt or '').strip():
return ""
# a blank agent self-configures via Self Update when it detects a role signal
return NO_CUSTOM_INSTRUCTIONS_NOTE
def _get_available_skills(self):
skills = super()._get_available_skills()
if self.env.context.get('ai_automation_run'):
self_update_skill = self.env.ref('ai_agentic.ai_skill_self_update', raise_if_not_found=False)
if self_update_skill:
skills -= self_update_skill
return skills
def _get_skills_protocol(self):
protocol = super()._get_skills_protocol()
self_update_skill = self.env.ref('ai_agentic.ai_skill_self_update', raise_if_not_found=False)
if self_update_skill and self_update_skill in self._get_available_skills():
protocol += SELF_UPDATE_SKILLS_PROTOCOL
return protocol
def _create_ai_automation_channel(self, channel_name, kickoff_body):
"""Create the inspection channel of an automation run: OdooBot posts
the kickoff and leaves, so the agent stays the only member and the
chat wears its avatar."""
self.ensure_one()
channel = self.with_user(SUPERUSER_ID)._create_ai_chat_channel(channel_name)
bot_partner = channel.env.user.partner_id
channel.from_ai_automation = True
channel.message_post(
body=kickoff_body,
author_id=bot_partner.id,
message_type='comment',
subtype_xmlid='mail.mt_comment',
)
channel.channel_member_ids.filtered(lambda m: m.partner_id == bot_partner).unlink()
# Join the audience allowed to inspect runs (admins), so they get it live.
channel.sudo()._add_members(
partners=self.env.ref("base.group_system").all_user_ids.partner_id,
post_joined_message=False,
)
return channel
@api.model
def action_create_agent(self):
agent = self.create({'name': _("My agent")})
# Pick a random silhouette and tag its attachment so the color/number
# stick through a later role redraw.
agent._apply_avatar(f"Avatar{random.choice(AVATAR_NUMBERS)}-{random.choice(AVATAR_COLORS)}")
return agent.open_agent_chat()
def open_agent_chat(self):
self.ensure_one()
session = self.env['ai.session'].sudo().search([
('create_uid', '=', self.env.uid),
('agent_id', '=', self.id),
('ai_composer_id', '=', False),
('channel_id.has_message', '=', False),
], order='id DESC', limit=1)
if session:
channel = session.channel_id
else:
channel = self._create_ai_chat_channel()
self.env['ai.session'].sudo().create({
'agent_id': self.id,
'channel_id': channel.id,
})
action = self.env['ir.actions.actions']._for_xml_id('mail.action_discuss')
action['context'] = {
'active_id': f'discuss.channel_{channel.id}',
'scoped_ai_agent_id': self.id,
}
return action
class AISkill(models.Model):
_inherit = 'ai.skill'
agent_ids = fields.Many2many(
'ai.agent',
relation='ai_agent_ai_skill_rel',
column1='ai_skill_id',
column2='ai_agent_id',
string="Agents",
)

View File

@@ -0,0 +1,25 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class AiAgentSource(models.Model):
_inherit = "ai.agent.source"
file_sources_count = fields.Integer('Number of file sources', compute="_compute_file_sources_count")
@api.depends('child_ids')
def _compute_file_sources_count(self):
for source in self:
descendants = source._get_descendants().filtered(lambda s: not s.is_folder)
source.file_sources_count = len(descendants)
@api.model
def get_agent_sources_tree(self, agent_id, fields, unfolded_ids=None):
"""Return the sources shown by the sources browser in the agent panel:
top-level sources, plus the children of whichever folders are unfolded.
"""
domain = [
('agent_id', '=', agent_id),
'|', ('parent_id', '=', False), ('parent_id', 'in', unfolded_ids or []),
]
return self.search_read(domain, list({*fields, 'parent_id'}))

View File

@@ -0,0 +1,49 @@
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models
INTERVAL_TYPE = {
'minutes': relativedelta(minutes=1),
'hour': relativedelta(hours=1),
'day': relativedelta(days=1),
'week': relativedelta(days=7),
'month': relativedelta(months=1),
False: relativedelta(0),
}
class AIAutomationTrigger(models.Model):
_name = "ai.automation.trigger"
_description = "AI Automation Trigger"
automation_id = fields.Many2one(
"base.automation",
string="Automation",
ondelete="cascade",
index="btree_not_null",
)
prev_trigger_date = fields.Datetime(string="Last Trigger Date", compute="_compute_prev_trigger_date")
next_trigger_date = fields.Datetime(string="Next Trigger Date", required=True, default=fields.Datetime.now)
@api.depends('next_trigger_date', 'automation_id.trg_date_range', 'automation_id.trg_date_range_type')
def _compute_prev_trigger_date(self):
for trigger in self:
trigger.prev_trigger_date = (
trigger.next_trigger_date - INTERVAL_TYPE[trigger.automation_id.trg_date_range_type] * trigger.automation_id.trg_date_range
if trigger.next_trigger_date else False
)
def _advance_next_trigger_date(self):
"""Move `next_trigger_date` to the next slot the rule has not fired yet.
Based on the `trigger_interval` and `trigger_interval_type` fields of the
automation.
"""
now = fields.Datetime.now()
for trigger in self:
interval = INTERVAL_TYPE[trigger.automation_id.trg_date_range_type] * trigger.automation_id.trg_date_range
if not interval:
continue
next_date = trigger.next_trigger_date or now
while next_date <= now:
next_date += interval
trigger.next_trigger_date = next_date

View File

@@ -0,0 +1,18 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class AiSession(models.Model):
_inherit = "ai.session"
def _get_request_context_snapshot(self, context=None):
snapshot = super()._get_request_context_snapshot(context)
if self.env.context.get('ai_automation_run') or (self.request_context or {}).get('ai_automation_run'):
snapshot['ai_automation_run'] = True
return snapshot
def _finish_exchange(self, status='completed', *, content=None):
super()._finish_exchange(status, content=content)
if (self.request_context or {}).get("ai_automation_run"):
self.auto_confirm = False

View File

@@ -0,0 +1,300 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from markupsafe import Markup
from odoo import api, fields, models
from odoo.addons.ai.utils.ai_utils import (
UserInputResponse,
is_ai_internal_model,
make_confirmation_request_preview,
make_create_preview,
make_records_update_preview,
)
from odoo.addons.ai.utils.ai_fields_tools import parse_ai_prompt_values
from odoo.addons.base_automation.models.base_automation import TIME_TRIGGERS
SELF_UPDATE_SKILL_XMLID = 'ai_agentic.ai_skill_self_update'
def check_automation_skill_is_loaded(env, tool_context):
if not (automation_skill := env.ref('ai_agentic.ai_skill_automations', raise_if_not_found=False)):
raise ValueError("The Automations skill is required to write on base.automation records")
if not automation_skill.id in (tool_context['state'] or []).get('loaded_skills', []):
raise ValueError("The Automations skill needs to be loaded to update automations")
class AITool(models.AbstractModel):
_inherit = 'ai.tool'
@api.model
def _check_agent_model_access(self, model_name, operation='read'):
if operation == 'read' and model_name in {'base.automation', 'ir.model', 'ir.model.fields', 'ir.model.fields.selection'}:
return
return super()._check_agent_model_access(model_name, operation)
def _check_tool_scope(self, tool_context, tool_xmlid, model_names):
tool = self.env.ref(tool_xmlid, raise_if_not_found=False)
self_update_skill = self.env.ref(SELF_UPDATE_SKILL_XMLID, raise_if_not_found=False)
if not tool or not self_update_skill or not tool_context.get('agent_id'):
return
agent_skills = self._get_calling_agent(tool_context)._get_available_skills().sudo()
if agent_skills.filtered(lambda s: tool in s.tool_ids) != self_update_skill:
return
out_of_scope = [m for m in dict.fromkeys(model_names) if not is_ai_internal_model(m)]
if out_of_scope:
raise ValueError(
f"The Self Update skill only lets you read and change the AI configuration "
f"models, not {', '.join(out_of_scope)}. "
"Link a skill that provides this tool to use it on other records."
)
def _ai_tool_update_records(self, tool_context, explanation, preview_menus, updates):
self._check_tool_scope(
tool_context, 'ai.ir_actions_server_update_records',
[update['model_name'] for update in updates],
)
return super()._ai_tool_update_records(tool_context, explanation, preview_menus, updates)
@api.model
def _get_preview_links(self, mode, record_by_model, action_by_model=None):
links = []
if mode == 'write' and record_by_model.get('ai.agent'):
record_by_model = {model: records for model, records in record_by_model.items() if model != 'ai.agent'}
links.append(Markup('<span>%s</span>') % self.env._("self-updated its configuration"))
return links + super()._get_preview_links(mode, record_by_model, action_by_model)
def _ai_tool_create_records(self, tool_context, explanation, preview_menu_id, model_name, values):
self._check_tool_scope(tool_context, 'ai.ir_actions_server_create_records', [model_name])
return super()._ai_tool_create_records(tool_context, explanation, preview_menu_id, model_name, values)
def _is_automation_skill_required(self, tool_context):
# A hook to be overridable
return True
def _is_base_automation_server_action(self, tool_context):
# A hook to be overridable
return True
def _ai_tool_run_automation(self, tool_context, base_automation_id):
"""Run a time-based automation NOW, exactly as its schedule would: the
headless agent run lands in the automation's own chat."""
automation = self.env['base.automation'].browse(base_automation_id)
if not automation.trigger in TIME_TRIGGERS:
raise ValueError(
f"'{automation.name}' is not a time based trigger, test it by "
"creating or updating a record that matches its trigger instead."
)
if not tool_context.get('tool_request_confirmed'):
tool_context['user_input_request'] = {
'type': 'confirmation',
'body': self.env['ir.qweb']._render('ai.ai_records_preview', {
'template': 'create',
'explanation': self.env._('Run this automation now?'),
'sections': [{'items': [{'label': self.env._('Automation'), 'value': automation.name}]}],
}),
'choices': [{'label': self.env._("Run"), 'value': UserInputResponse.CONFIRM_ONCE}, {'label': self.env._("Not now"), 'value': UserInputResponse.DECLINE}],
'allow_free_text': False,
}
return None
automation.action_ai_run_now()
tool_context["preview_links"] = [
Markup('<div class="o_mail_notification">%s</div>') % self.env._("has run %s", automation._get_html_link()),
]
return {
'response': self.env._(
'"%s" ran. The full transcript is in its own chat, under the Automation tab.',
automation.name,
),
'summary': {'icon': 'flash_on', 'text': self.env._("Ran the trigger %(name)s", name=automation.name)}
}
def _ai_tool_create_update_automation(self, tool_context, automation_id=None, name=None, description=None, active=None, trigger=None, ai_action_prompt=None, explanation=None):
if not automation_id and not (name and description and trigger and ai_action_prompt):
raise ValueError("'name', 'description', 'trigger' and 'ai_action_prompt' are required when creating an automation")
automation = self._get_automation_to_update(tool_context, automation_id)
automation_vals = self._compute_automation_header_vals(automation, name, description, active)
trigger_type = (trigger or {}).get('type') or automation.trigger
model_name = automation.model_name
if trigger:
trigger_vals, model_name = self._compute_trigger_vals(automation, trigger, trigger_type)
automation_vals.update(trigger_vals)
automation_vals.update(self._compute_trigger_prompt_vals(automation, ai_action_prompt, model_name, model_changed='model_id' in automation_vals))
if not automation:
if trigger_type != 'on_schedule':
automation_vals['last_run'] = fields.Datetime.to_string(fields.Datetime.now())
automation_vals['ai_agent_id'] = tool_context['agent_id']
if not tool_context['tool_request_confirmed']:
tool_context['user_input_request'] = make_confirmation_request_preview(
self.env, self._render_automation_preview(automation, automation_vals, explanation),
)
return None
if automation:
automation.write(automation_vals)
mode = 'update'
summary = {'icon': 'edit', 'text': self.env._("Updated a Trigger")}
else:
automation = automation.create(automation_vals)
mode = 'create'
summary = {'icon': 'edit_square', 'text': self.env._("Created a Trigger")}
tool_context["preview_links"] = self._get_preview_links(mode, {automation._name: automation})
return {
'response': f"Successfully {mode}d automation with id {automation.id}",
'client_tool': {'name': 'reload', 'oneway': True},
'summary': summary,
}
def _get_automation_to_update(self, tool_context, automation_id):
if not automation_id:
return self.env['base.automation']
if not (automation := self.env['base.automation'].browse(automation_id).exists()):
raise ValueError(f"The automation with id '{automation_id}' does not exist")
if automation.ai_agent_id.id != tool_context['agent_id']:
raise ValueError("You can only update your own automations.")
return automation
def _compute_automation_header_vals(self, automation, name, description, active):
vals = {}
if name and name != automation.name:
vals['name'] = name
if description and description != automation.description:
vals['description'] = description
if active is not None and active != automation.active:
vals['active'] = active
return vals
def _compute_trigger_vals(self, automation, trigger, trigger_type):
vals, model_name = self._compute_trigger_type_vals(automation, trigger, trigger_type)
vals.update(self._compute_trigger_domain_vals(automation, trigger, trigger_type, model_name))
vals.update(self._compute_observed_fields_vals(automation, trigger, trigger_type, model_name))
vals.update(self._compute_time_trigger_vals(automation, trigger, trigger_type))
return vals, model_name
def _compute_trigger_type_vals(self, automation, trigger, trigger_type):
vals = {}
if trigger.get('type') and trigger_type != automation.trigger:
if trigger_type not in automation._fields['trigger']._selection and trigger_type != 'on_schedule':
raise ValueError(f"Unsupported trigger type '{trigger_type}'")
vals['trigger'] = 'on_time' if trigger_type == 'on_schedule' else trigger_type
if (model_name := trigger.get('target_model')) and model_name != automation.model_name:
if model_name not in self.env:
raise ValueError(f"Model {model_name} not found")
vals['model_id'] = self.env['ir.model']._get_id(model_name)
elif trigger_type == 'on_schedule':
model_name = 'ai.automation.trigger'
if model_name != automation.model_name:
vals['model_id'] = self.env['ir.model']._get_id(model_name)
return vals, model_name or automation.model_name
def _compute_trigger_domain_vals(self, automation, trigger, trigger_type, model_name):
vals = {}
unsupported = {
'filter_pre_domain': {'on_time', 'on_time_created', 'on_time_updated', 'on_create', 'on_unlink', 'on_change', 'on_webhook'},
'filter_domain': {'on_webhook'},
}
for fname, forbidden_triggers in unsupported.items():
if not (domain := trigger.get(fname) or automation[fname]):
continue
if trigger_type in forbidden_triggers:
raise ValueError(f"'{fname}' is not supported with trigger of type '{trigger_type}'")
if domain != automation[fname]:
vals[fname] = str(self._parse_domain(model_name, domain))
elif model_name != automation.model_name:
# make sure it's still valid with the current model
self._parse_domain(model_name, domain)
return vals
def _compute_observed_fields_vals(self, automation, trigger, trigger_type, model_name):
vals = {}
fnames = trigger.get('observed_fields') or []
if isinstance(fnames, str):
fnames = [fnames]
if trigger_type in {'on_create_or_write', 'on_change'}:
ids_by_fname = self.env['ir.model.fields']._get_ids(model_name)
observed_field_ids = []
for fname in fnames:
if not (fid := ids_by_fname.get(fname)):
raise ValueError(f"field '{fname}' does not exist on '{model_name}'")
observed_field_ids.append(fid)
if trigger_type == 'on_change':
if not fnames and not automation.on_change_field_ids:
raise ValueError("Trigger of type 'on_change' requires at least one observed field")
if observed_field_ids != automation.on_change_field_ids.ids:
vals['on_change_field_ids'] = observed_field_ids
elif fnames and observed_field_ids != automation.trigger_field_ids.ids:
vals['trigger_field_ids'] = observed_field_ids
elif trigger_type == 'on_time':
fname = fnames[0] if fnames else False
if not fname:
if not automation.trg_date_id:
raise ValueError("Trigger of type 'on_time' requires a date(time) field to observe")
if (trg_name := automation.trg_date_id.name) not in self.env[model_name]._fields:
raise ValueError(f"Observed field {trg_name} does not exist on '{model_name}'")
else:
if fname not in self.env[model_name]._fields:
raise ValueError(f"Observed field {fname} does not exist on '{model_name}'")
trg_date_id = self.env['ir.model.fields']._get(model_name, fname).id
if trg_date_id != automation.trg_date_id.id:
vals['trg_date_id'] = trg_date_id
elif trigger_type == 'on_schedule':
trg_date_id = self.env['ir.model.fields']._get('ai.automation.trigger', 'prev_trigger_date').id
if trg_date_id != automation.trg_date_id.id:
vals['trg_date_id'] = trg_date_id
elif fnames:
raise ValueError(f"'observed_fields' is not supported with trigger of type '{trigger_type}'")
return vals
def _compute_time_trigger_vals(self, automation, trigger, trigger_type):
vals = {}
if not (date_params := trigger.get('date_offset_or_interval')):
return vals
if trigger_type not in {'on_time', 'on_time_created', 'on_time_updated', 'on_schedule'}:
raise ValueError(f"'date_offset_or_interval' is not supported with trigger of type '{trigger_type}'")
if trigger_type == 'on_time':
if (direction := date_params.get('direction')) and direction != automation.trg_date_range_mode:
vals['trg_date_range_mode'] = direction
elif not automation.trg_date_range_mode:
vals['trg_date_range_mode'] = 'after'
elif trigger_type == 'on_schedule':
if automation.trg_date_range_mode != 'after':
vals['trg_date_range_mode'] = 'after'
if not (next_trigger_date := date_params.get('next_trigger_date')) and not automation.ai_next_trigger_date:
raise ValueError("`on_schedule` requires a `next_trigger_date`")
if next_trigger_date != automation.ai_next_trigger_date:
vals['ai_next_trigger_date'] = next_trigger_date
if (amount := date_params.get('amount')) and amount != automation.trg_date_range:
vals['trg_date_range'] = amount
elif not automation.trg_date_range:
vals['trg_date_range'] = 5
if (unit := date_params.get('unit')) and unit != automation.trg_date_range_type:
vals['trg_date_range_type'] = unit
elif not automation.trg_date_range_type:
vals['trg_date_range_type'] = "minutes"
return vals
def _compute_trigger_prompt_vals(self, automation, ai_action_prompt, model_name, model_changed):
vals = {}
action_prompt = ai_action_prompt or automation.ai_action_prompt
if action_prompt == automation.ai_action_prompt and not model_changed:
return vals
__, context_fields, __ = parse_ai_prompt_values(self.env, action_prompt, None)
for field_path in context_fields:
try:
self.env[model_name].mapped(field_path)
except KeyError as e:
raise ValueError(f"Invalid field {e} in '{field_path}' in prompt")
if action_prompt != automation.ai_action_prompt:
vals['ai_action_prompt'] = action_prompt
return vals
def _render_automation_preview(self, automation, vals, explanation):
if not automation:
return make_create_preview(self.env, explanation, 'base.automation', [{
'field_values': [{'field': field, 'value': value} for field, value in vals.items()],
}])
return self.env['ir.qweb']._render('ai.ai_records_preview', {
'template': 'update',
'explanation': explanation,
'sections': [{
'label': self.env._("Automation Rule %(name)s", name=automation.name),
'items': make_records_update_preview(automation, vals),
}],
})

View File

@@ -0,0 +1,133 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, Command, fields, models
SCHEDULE_TRIGGER = "on_schedule"
SCHEDULE_MODEL = 'ai.automation.trigger'
SCHEDULE_FIELD = 'prev_trigger_date'
def _is_schedule_automation(automation):
automation.ensure_one()
return automation.ai_agent_id and automation.model_name == SCHEDULE_MODEL and automation.trigger == 'on_time'
class BaseAutomation(models.Model):
_inherit = "base.automation"
ai_agent_id = fields.Many2one(
"ai.agent",
string="AI Agent",
ondelete='restrict',
help="Agent that runs the AI actions of this automation rule. Its tool calls are "
"auto-confirmed and each run is kept in a chat for inspection.",
context={"active_test": False},
)
ai_automation_trigger_ids = fields.One2many(
"ai.automation.trigger",
"automation_id",
string="AI Automation Triggers",
)
ai_next_trigger_date = fields.Datetime(
compute="_compute_ai_next_trigger_date",
inverse="_inverse_ai_next_trigger_date",
)
ai_action_prompt = fields.Html(
compute="_compute_ai_action_prompt",
inverse="_inverse_ai_action_prompt",
)
@api.model
def default_get(self, fields):
"""A scheduled trigger runs on its own `ai.automation.trigger` row, not
on a business model: preset the target model so the rest computes."""
defaults = super().default_get(fields)
if self.env.context.get('ai_preset_trigger') == SCHEDULE_TRIGGER and 'model_id' in fields:
defaults['model_id'] = self.env['ir.model']._get_id(SCHEDULE_MODEL)
defaults['trg_date_id'] = self.env['ir.model.fields']._get(SCHEDULE_MODEL, SCHEDULE_FIELD).id
return defaults
@api.depends('model_id')
def _compute_trigger(self):
super()._compute_trigger()
if preset_trigger := self.env.context.get('ai_preset_trigger'):
self.trigger = 'on_time' if preset_trigger == SCHEDULE_TRIGGER else preset_trigger
@api.depends('trigger', 'model_id')
def _compute_trg_date_id(self):
schedule_automations = self.filtered(_is_schedule_automation)
schedule_automations.trg_date_id = self.env['ir.model.fields']._get(SCHEDULE_MODEL, SCHEDULE_FIELD)
super(BaseAutomation, self - schedule_automations)._compute_trg_date_id()
@api.depends('ai_automation_trigger_ids.next_trigger_date', 'ai_agent_id', 'model_name', 'trigger')
def _compute_ai_next_trigger_date(self):
for rule in self:
if _is_schedule_automation(rule):
rule.ai_next_trigger_date = rule.ai_automation_trigger_ids[:1].next_trigger_date
else:
rule.ai_next_trigger_date = False
def _inverse_ai_next_trigger_date(self):
for rule in self:
if _is_schedule_automation(rule) and rule.ai_next_trigger_date:
if trigger := rule.ai_automation_trigger_ids:
trigger.next_trigger_date = rule.ai_next_trigger_date
else:
self.env['ai.automation.trigger'].create({
'automation_id': rule.id,
'next_trigger_date': rule.ai_next_trigger_date,
})
@api.depends('action_server_ids.ai_action_prompt', 'ai_agent_id')
def _compute_ai_action_prompt(self):
for automation in self:
if automation.ai_agent_id:
automation.ai_action_prompt = automation.action_server_ids.ai_action_prompt
else:
automation.ai_action_prompt = False
def _inverse_ai_action_prompt(self):
for automation in self:
if automation.ai_agent_id and automation.ai_action_prompt:
if action := automation.action_server_ids:
action.ai_action_prompt = automation.ai_action_prompt
else:
automation.action_server_ids = [Command.create({
'ai_action_prompt': automation.ai_action_prompt,
'model_id': automation.model_id.id,
'name': automation._get_ai_action_name(),
'state': 'ai',
'usage': 'base_automation',
})]
@api.depends('ai_agent_id', 'model_id')
def _compute_action_server_ids(self):
for rule in (agent_rules := self.filtered(lambda rule: rule.ai_agent_id and rule.model_id)):
# agent automations are tied to one server action of type AI.
action_to_keep = rule.action_server_ids.filtered(lambda action: action.state == 'ai' and action.model_id == rule.model_id)[:1]
rule.action_server_ids = [Command.delete(action.id) for action in rule.action_server_ids - action_to_keep]
super(BaseAutomation, self - agent_rules)._compute_action_server_ids()
def write(self, vals):
res = super().write(vals)
if {'model_id', 'model_name', 'trigger', 'ai_agent_id'} & vals.keys():
(self - self.filtered(_is_schedule_automation)).ai_automation_trigger_ids.unlink()
return res
def _process(self, records, domain_post=None, trigger=''):
"""Advance the schedule before running: a failing agent run then costs one
slot instead of being retried — and re-billed — on every cron pass."""
super()._process(records, domain_post=domain_post, trigger=trigger)
if trigger != 'manual' and records._name == SCHEDULE_MODEL:
records.sudo()._advance_next_trigger_date()
def _get_ai_action_name(self):
self.ensure_one()
return self.env._("%(agent)s: %(automation)s", agent=self.ai_agent_id.name, automation=self.name)
def action_ai_run_now(self):
"""Run the automation scheduler now."""
self.ensure_one()
if self.model_name != SCHEDULE_MODEL:
self.env.ref('base_automation.ir_cron_data_base_automation_check').method_direct_trigger()
return
self.sudo()._process(self.ai_automation_trigger_ids, trigger='manual')

View File

@@ -0,0 +1,26 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
from odoo.addons.mail.tools.discuss import Store
class DiscussChannel(models.Model):
_inherit = "discuss.channel"
from_ai_automation = fields.Boolean(
"From AI Automation",
help="Channel opened by an automation rule or scheduled action.",
)
def _store_ai_fields(self, res: Store.FieldList):
super()._store_ai_fields(res)
res.attr("from_ai_automation", predicate=lambda c: c.channel_type == "ai_chat")
def open_chat_window_action(self):
self.ensure_one()
self.check_access('read')
if self.from_ai_automation and not self.is_member:
# `ai_chat` channels are readable by their members only, and a run
# starts with the agent as sole member
self.sudo()._add_members(users=self.env.user)
return super().open_chat_window_action()

View File

@@ -0,0 +1,140 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from lxml import html as lxml_html
from odoo import models
from odoo.addons.ai.models.ir_actions_server import AI_ACTIONS_PROMPT
from odoo.tools.mail import html_sanitize, html_to_inner_content
from odoo.addons.ai_agentic.models.base_automation import SCHEDULE_MODEL
AI_AGENT_RUN_RULES = (
"""Execute EVERY step of the instructions. Any available tool may be used for any step: naming a tool for one step never makes the other tools off-limits, and a tool name that does not exist refers to the closest available one. Never report a step as skipped because a tool was not named for it.
To log a note in a record's chatter, create a `mail.message` record with the create tool: `model` = the record's model, `res_id` = its id, `body` = the note HTML, `message_type` = 'comment' and the internal note subtype. Only post a chatter note when the instructions explicitly ask for one: never log one on your own initiative to explain or justify what you did - that reasoning belongs in the final message of this run, nowhere else.
To SEND an email, create a `mail.mail` record instead: `email_to` = the recipient's address (search `res.partner`/`res.users` when only a name is given), `subject` and `body_html` = the HTML content. It is queued and sent automatically, while a `mail.message` is an internal note that never emails anyone.
Tools taking preview menu parameters (`preview_menus`, `preview_menu_id`) have no menu context in this run: always leave them empty, a guessed menu id fails the whole call.
The "User info" of the context is the account running this automation, not a person the instructions refer to: never assign a field (user, partner, ...) to it, and leave `partner_id` unset when the instructions name no contact.
If a person or record named in the instructions cannot be found, leave that value unset and say so in the final message, rather than substituting the current user or inventing an id.
The final message is the run's report: a factual summary of what was done, listing the records created or updated by display name with the values written, what was found, and anything skipped and why. When the instructions define an output format, follow it."""
)
AI_AGENT_RUN_SELF_EQUIP_NOTE = (
"""# Missing capability
If a step needs a capability none of your loaded tools provide (updating records, posting a chatter message, ...):
- If a skill listed in your available skills covers it, call `load_skills` with its id and continue the step with its tools.
- Otherwise, report the step as skipped, stating exactly which capability was missing."""
)
class IrActionsServer(models.Model):
_inherit = "ir.actions.server"
def _run_action_ai_multi(self, eval_context=None):
records = self._ai_get_records(eval_context)
if not records and (agent := self._ai_resolve_agent()):
self._ai_action_run_agent(records, agent)
return
super()._run_action_ai_multi(eval_context)
def _ai_action_run(self, record):
if not self.ai_tool_ids and (agent := self._ai_resolve_agent()):
return self._ai_action_run_agent(record, agent)
return super()._ai_action_run(record)
def _run(self, records, eval_context):
if self.state == 'multi' and not records and self._ai_resolve_agent():
return self._run_action_multi(eval_context=eval_context)
return super()._run(records, eval_context)
def _ai_resolve_trigger(self):
"""Return the recurring trigger this action hangs off, if any."""
self.ensure_one()
root = self
while root.parent_id:
root = root.parent_id
return (
self.base_automation_id
or root.base_automation_id
or self.env['ir.cron'].sudo().search([('ir_actions_server_id', '=', root.id)], limit=1)
)
def _ai_resolve_agent(self):
return self._ai_resolve_trigger().ai_agent_id
def _ai_run_channel_name(self, record):
"""Name the run's chat after the record the action ran on. A scheduled
trigger has no record and its action is an implementation detail, so name
it after the rule the user actually created."""
self.ensure_one()
if record and record._name != "ai.automation.trigger":
return f"{self.name}: {record.display_name}"
trigger = self._ai_resolve_trigger()
if trigger._name == 'base.automation' and trigger.model_name == SCHEDULE_MODEL:
return trigger.name
return self.name
def _ai_render_kickoff_body(self, record, action_prompt):
"""Kickoff note of an automation run: the action prompt with its field
fields (`/field` command) replaced by their value on the run's record.
Scheduled runs have no record and keep the raw prompt; so does any
rendering failure, which must never break the run."""
self.ensure_one()
tree = lxml_html.fromstring(self.ai_action_prompt)
for field in tree.xpath('//span[@data-ai-field]'):
field.text = html_to_inner_content(record._find_value_from_field_path(field.attrib.get('data-ai-field')))
field.drop_tag()
return html_sanitize(lxml_html.tostring(tree, encoding='unicode'))
def _ai_action_run_agent(self, record, agent):
"""Run the action's prompt through an agent session; `record` is empty
for scheduled runs."""
self.ensure_one()
agent = agent.sudo()
action_prompt, context_fields = self._ai_prepare_prompt_values(record)
instruction = f"{AI_ACTIONS_PROMPT}\n{AI_AGENT_RUN_RULES}\n\n# Action request\n{action_prompt}"
files_parts = []
if record:
self.sudo(record.env.su)._can_execute_action_on_records(record)
record_context, files_parts = record._get_ai_context(context_fields)
instruction += f'\n\n# Context\n## Current record\n{{"model": "{record._name}", "id": {record.id}}}'
if record_context != '{}':
instruction += f"\n## ORM Snapshot\n{record_context}"
if automation := self.base_automation_id:
instruction += (
f'\n\n# This chat is a run of the automation "{automation.name}" '
f'(`base.automation` id {automation.id}). If the user later gives feedback or corrections about '
"this run's behavior or results, apply it to THAT automation (usually its action prompt) so "
"future runs change - never to your own agent instructions, unless explicitly asked."
)
instruction += f"\n\n{AI_AGENT_RUN_SELF_EQUIP_NOTE}"
channel_name = self._ai_run_channel_name(record)
channel = agent._create_ai_automation_channel(channel_name, self._ai_render_kickoff_body(record, action_prompt))
session = self.env['ai.session'].sudo().create({
'agent_id': agent.id,
'channel_id': channel.id,
'res_model': record._name if record else False,
'res_id': record.id if record else False,
'auto_confirm': True,
})
request_context = {
'allowed_company_ids': self.env.companies.ids,
'active_company_ids': self.env.companies.ids,
'ai_automation_run': True,
}
for key in ('lang', 'tz', 'cron_id'):
if self.env.context.get(key):
request_context[key] = self.env.context[key]
session = session.with_context(request_context)
session._submit_agent_request(
[{'type': 'text', 'text': instruction}, *files_parts],
)
return None, []
def _generate_action_name(self):
self.ensure_one()
if self.state == 'ai' and self.base_automation_id.ai_agent_id:
return self.base_automation_id._get_ai_action_name()
return super()._generate_action_name()
def _name_depends(self):
return super()._name_depends() + ["base_automation_id.name", "base_automation_id.ai_agent_id.name"]

View File

@@ -0,0 +1,3 @@
id,name,model_id,group_id/id,operation,domain
access_ai_automation_trigger_user,access_ai_automation_trigger_user,ai.automation.trigger,base.group_user,r,
access_ai_automation_trigger_system,access_ai_automation_trigger_system,ai.automation.trigger,base.group_system,crud,
1 id name model_id group_id/id operation domain
2 access_ai_automation_trigger_user access_ai_automation_trigger_user ai.automation.trigger base.group_user r
3 access_ai_automation_trigger_system access_ai_automation_trigger_system ai.automation.trigger base.group_system crud

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

View File

@@ -0,0 +1,9 @@
<svg width="50" height="50" viewBox="0 0 50 50" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M2.7749 35.3007C7.43947 30.1179 14.1706 28.9766 17.748 28.9766C21.4809 28.9765 27.6225 30.1941 32.5765 35.1481C34.1386 36.7102 34.1386 39.2429 32.5765 40.805C31.0144 42.3671 28.4817 42.3671 26.9196 40.805C23.8736 37.759 20.0152 36.9765 17.7481 36.9766C15.3256 36.9766 11.2567 37.8353 8.72126 40.6524C7.24342 42.2945 4.71426 42.4276 3.07222 40.9497C1.43018 39.4719 1.29707 36.9427 2.7749 35.3007Z" fill="#985184"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M2.11621 36.3008L14.1162 10.3008L21.3799 13.6532L9.37989 39.6532L2.11621 36.3008Z" fill="#712258"/>
<path d="M39.748 8.97656C41.9572 8.97656 43.748 10.7674 43.748 12.9766V37.9766C43.748 40.1857 41.9572 41.9766 39.748 41.9766C37.5389 41.9766 35.748 40.1857 35.748 37.9766V12.9766C35.748 10.7674 37.5389 8.97656 39.748 8.97656Z" fill="#FBB945"/>
<path d="M9.37916 39.6533C9.20939 40.0211 8.98977 40.35 8.73366 40.6377C8.72933 40.6425 8.72528 40.6475 8.72096 40.6523C8.49348 40.9051 8.24022 41.1219 7.96999 41.3027C7.71217 41.4747 7.43551 41.6148 7.14674 41.7227C6.40539 41.9989 5.59656 42.0511 4.82741 41.8701C4.57205 41.8095 4.31904 41.7226 4.07155 41.6084C3.9489 41.5518 3.83012 41.4899 3.71608 41.4229C3.4903 41.2894 3.27399 41.1324 3.07155 40.9502C2.87135 40.77 2.6935 40.5741 2.53834 40.3662C2.47529 40.2814 2.41654 40.1937 2.36061 40.1045C2.31372 40.0299 2.26836 39.9549 2.22682 39.8779C2.08635 39.6173 1.97671 39.3413 1.89674 39.0566C1.69617 38.3387 1.6973 37.5739 1.90749 36.8535C1.96228 36.6671 2.03164 36.4825 2.11549 36.3008L2.12428 36.2803C2.28747 35.9321 2.50414 35.6014 2.77467 35.3008C6.14588 31.5552 10.5962 29.9203 14.1555 29.3018L9.37916 39.6533Z" fill="#985184"/>
<path d="M15.876 8.4412C16.9321 7.88294 18.2252 7.80253 19.3955 8.33183C19.4092 8.338 19.4229 8.34405 19.4366 8.35038C21.4335 9.28012 22.3035 11.6505 21.3799 13.6521L17.7481 21.5193L14.1172 13.6521C13.3085 11.8995 13.8741 9.863 15.3682 8.75956C15.4312 8.71303 15.4961 8.66937 15.5616 8.62675C15.6627 8.56086 15.7674 8.49861 15.876 8.4412Z" fill="#712258"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M16.0728 8.34471C14.067 9.27047 13.1914 11.647 14.1172 13.6528L26.1172 39.6528C27.043 41.6586 29.4195 42.5341 31.4253 41.6084C33.4311 40.6826 34.3066 38.3061 33.3809 36.3003L21.3809 10.3003C20.4551 8.29451 18.0786 7.41896 16.0728 8.34471Z" fill="#FBB945"/>
<path d="M21.3457 29.3135C24.8066 29.9432 29.0013 31.5726 32.5771 35.1484C32.9173 35.4886 33.183 35.8749 33.375 36.2871L33.3818 36.3008C33.4099 36.3616 33.4362 36.4229 33.4609 36.4844C34.0397 37.9261 33.745 39.6366 32.5771 40.8047C32.3551 41.0268 32.1122 41.2161 31.8564 41.375C31.7191 41.4599 31.5761 41.539 31.4258 41.6084C31.364 41.6369 31.3017 41.6634 31.2393 41.6885C30.3753 42.035 29.4155 42.0677 28.5332 41.7871C28.2985 41.7121 28.0709 41.6158 27.8535 41.499C27.7855 41.4624 27.7185 41.4236 27.6523 41.3828C27.4996 41.2889 27.3526 41.1847 27.2129 41.0703C27.1844 41.0469 27.1569 41.0223 27.1289 40.998C26.7126 40.6374 26.364 40.185 26.1182 39.6523L21.3457 29.3135Z" fill="#953B24"/>
</svg>

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

View File

@@ -0,0 +1,93 @@
import { Component, t, usePlugin, useProps, useScope } from "@odoo/owl";
import { _t } from "@web/core/l10n/translation";
import { normalize } from "@web/core/l10n/utils";
import { ORM } from "@web/core/orm_plugin";
import { registry } from "@web/core/registry";
import { useService } from "@web/core/utils/hooks";
import { imageUrl } from "@web/core/utils/urls";
const commandProviderRegistry = registry.category("command_provider");
const commandCategoryRegistry = registry.category("command_categories");
commandCategoryRegistry.add("AI_AGENTS", { namespace: "@", name: _t("Agents") }, { sequence: 30 });
export class AICommand extends Component {
static template = "ai_agentic.AICommand";
props = useProps({
executeCommand: t.function(),
name: t.string(),
subtitle: t.string(),
imgUrl: t.string(),
action: t.object().optional(),
searchValue: t.string(),
slots: t.object(),
});
setup() {
super.setup();
this.ui = useService("ui");
}
}
export class AICommandPalette {
constructor(options) {
this.options = options;
this.orm = usePlugin(ORM);
this.ui = useService("ui");
this.actions = useService("action");
this.commands = [];
this.options = options;
this.cleanedTerm = normalize(this.options.searchValue);
this.agents = [];
}
async fetch() {
this.agents = await this.orm.searchRead(
"ai.agent",
[],
["id", "name", "subtitle", "partner_id"],
{ load: false }
);
}
async buildResults(filtered) {
this.agents
.filter(
(agent) =>
(normalize(agent.name).includes(this.cleanedTerm) ||
(agent.subtitle && normalize(agent.subtitle).includes(this.cleanedTerm))) &&
(!filtered || !filtered.has(agent))
)
.slice(0, 5)
.forEach((agent) => {
this.commands.push({
Component: AICommand,
action: async () => {
const result = await this.orm.call("ai.agent", "open_agent_chat", [
agent.id,
]);
if (result) {
this.actions.doAction(result, { clearBreadcrumbs: true });
}
},
name: agent.name,
props: {
imgUrl: imageUrl("ai.agent", agent.id, "image_128"),
subtitle: agent.subtitle ? agent.subtitle : "",
},
category: "AI_AGENTS",
});
});
}
}
commandProviderRegistry.add("chat_with_agent", {
namespace: "@",
async provide(options) {
const scope = useScope();
const palette = scope.run(() => new AICommandPalette(options));
await palette.fetch();
palette.buildResults();
return palette.commands;
},
});

View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8" ?>
<templates xml:space="preserve">
<t t-name="ai_agentic.AICommand">
<div class="o-mail-DiscussCommand o_command_default d-flex align-items-center ps-3 pe-4" t-att-class="{ 'o-uiSmall': this.ui.isSmall }">
<i class="oi oi-fw oi-filled opacity-50 text-muted me-2" data-icon="settings"/>
<img class="rounded me-2 object-fit-cover" t-if="this.props.imgUrl" t-att-src="this.props.imgUrl" style="width: 25px; height: 25px"/>
<span class="pe-1 text-ellipsis d-flex align-items-center fw-bold">
<t t-call-slot="name" />
</span>
<span t-if="this.props.subtitle" class="text-muted smaller text-truncate mw-50" t-out="'- ' + this.props.subtitle"/>
</div>
</t>
</templates>

View File

@@ -0,0 +1,241 @@
import { Component, proxy, signal, t, useProps } from "@odoo/owl";
import { Dialog } from "@web/core/dialog/dialog";
import { _t } from "@web/core/l10n/translation";
import { useAutofocus, useService } from "@web/core/utils/hooks";
import { getDataURLFromFile } from "@web/core/utils/urls";
import { AiAgentPanelCard } from "@ai_agentic/components/ai_agent_panel_card/ai_agent_panel_card";
class AgentSourceURLDialog extends Component {
static template = "ai.AgentSourceURLDialog";
static components = {
Dialog,
};
props = useProps({
addURLSources: t.function(),
close: t.function(),
});
autofocusRef = signal.ref();
setup() {
super.setup();
useAutofocus({ ref: this.autofocusRef });
this.state = proxy({
urls: "",
});
}
onConfirm() {
this.props.addURLSources(this.state.urls);
this.props.close();
}
}
export class AgentSourceAddDialog extends Component {
static template = "ai.AgentSourceAddDialog";
static components = { AiAgentPanelCard, Dialog };
props = useProps({
agentId: t.number(),
onSourcesAdded: t.function(),
close: t.function(),
});
fileInputRef = signal.ref();
setup() {
super.setup();
this.agentId = this.props.agentId;
this.orm = useService("orm");
this.notification = useService("notification");
this.actionService = useService("action");
this.dialog = useService("dialog");
this.state = proxy({
loading: false,
});
}
async onSourcesAdded() {
await this.props.onSourcesAdded();
this.props.close();
}
onAddFileSourceClick() {
this.fileInputRef().click();
}
validateFileTypes(files) {
const validFiles = [];
const invalidFiles = [];
for (const file of files) {
const fileExtension = "." + file.name.split(".").pop().toLowerCase();
if (this.allowedExtensions.includes(fileExtension)) {
validFiles.push(file);
} else {
invalidFiles.push(file);
}
}
return { validFiles, invalidFiles };
}
async addAttachmentSources(ev) {
const files = ev.target.files;
if (!files || !files.length) {
return;
}
// Validate file types
const { validFiles, invalidFiles } = this.validateFileTypes(Array.from(files));
if (invalidFiles.length > 0 && validFiles.length > 0) {
const invalidFileNames = invalidFiles.map((file) => file.name).join(", ");
this.notification.add(
_t(
"Some files have invalid formats and were skipped: %s. Only PDF, Word, PowerPoint, Excel, Text, CSV, and OpenDocument files are allowed.",
invalidFileNames
),
{
type: "warning",
}
);
}
if (validFiles.length === 0) {
this.notification.add(
_t(
"No valid files to upload. Only PDF, Word, PowerPoint, Excel, Text, CSV, OpenDocument, and Markdown files are allowed."
),
{
type: "danger",
}
);
ev.target.value = "";
return;
}
this.state.loading = true;
try {
const files_list = await Promise.all(
validFiles.map(async (file) => ({
name: file.name,
raw: (await getDataURLFromFile(file)).split(",")[1],
}))
);
const files_datas = [];
for (const attachment_data of files_list) {
files_datas.push({
name: attachment_data.name,
raw: attachment_data.raw,
});
}
await this.orm.call("ai.agent.source", "create_from_binary_files", [
files_datas,
this.agentId,
]);
} finally {
this.state.loading = false;
ev.target.value = "";
}
return this.onSourcesAdded();
}
onAddLinkSourceClick() {
this.dialog.add(AgentSourceURLDialog, {
addURLSources: async (urls_string) => await this.addURLSources(urls_string),
});
}
validateAndFilterURLs(urls_list) {
const validUrls = [];
const invalidUrls = [];
for (const url of urls_list) {
if (
url &&
(url.startsWith("https://") ||
url.startsWith("http://") ||
url.startsWith("ftp://"))
) {
validUrls.push(url);
} else {
invalidUrls.push(url);
}
}
return { validUrls, invalidUrls };
}
async addURLSources(urls_string) {
if (!urls_string) {
return;
}
const urls_list = [
...new Set(
urls_string
.split("\n")
.map((url) => url.trim())
.filter((url) => url !== "")
),
];
if (urls_list.length > 0) {
const { validUrls, invalidUrls } = this.validateAndFilterURLs(urls_list);
if (validUrls.length > 0) {
this.state.loading = true;
try {
await this.orm.call("ai.agent.source", "create_from_urls", [
validUrls,
this.agentId,
]);
} finally {
this.state.loading = false;
}
if (invalidUrls.length > 0) {
this.notification.add(
_t(
"Some URLs are invalid and were skipped. URLs must start with http://, https://, or ftp://"
),
{
type: "warning",
}
);
}
return this.onSourcesAdded();
} else {
this.notification.add(_t("No valid URLs found to process."), {
type: "danger",
});
}
}
}
get cardsData() {
return [
{
icon: "upload",
title: _t("Upload a File"),
onClick: () => this.onAddFileSourceClick(),
},
{
icon: "link",
title: _t("Add a Link"),
onClick: () => this.onAddLinkSourceClick(),
},
];
}
get allowedExtensions() {
return [
".pdf",
".docx",
".doc",
".pptx",
".ppt",
".xlsx",
".xls",
".odt",
".ods",
".txt",
".csv",
".md",
];
}
}

View File

@@ -0,0 +1,62 @@
<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space="preserve">
<t t-name="ai.AgentSourceURLDialog">
<Dialog title.translate="Add Links" size="'md'">
<div class="row gy-4 p-3">
<textarea
t-model.proxy="this.state.urls"
class="form-control p-2"
rows="4"
placeholder="Paste your links, one per line"
t-ref="this.autofocusRef"
required="required"/>
</div>
<t t-set-slot="footer">
<button class="btn btn-primary" t-on-click="this.onConfirm">Save</button>
<button class="btn btn-secondary" t-on-click="this.props.close">Discard</button>
</t>
</Dialog>
</t>
<t t-name="ai.AgentSourceAddDialog">
<Dialog title.translate="Add Sources" size="'lg'">
<div class="position-relative" style="min-height: 250px;" >
<p class="mb-1">Add sources to your AI Agent to get answers based on specific content.</p>
<input
type="file"
t-ref="this.fileInputRef"
multiple="true"
class="o_input_file d-none"
t-att-accept="this.allowedExtensions"
t-on-change.stop="this.addAttachmentSources"
/>
<div class="pt-2" t-att-class="this.state.loading ? 'opacity-50 pe-none' : ''">
<div t-if="this.state.loading" class="d-flex justify-content-center w-100 position-absolute" style="bottom: 15px;">
<div class="text-muted">
<i class="oi oi-spin me-2" data-icon="progress_activity"></i>
Adding sources...
</div>
</div>
<div class="row gy-3 justify-content-center">
<t t-foreach="this.cardsData" t-as="card" t-key="card.title">
<div class="col col-md-6">
<AiAgentPanelCard
icon="card.icon"
image="card.image"
title="card.title"
description="card.description"
onClick="card.onClick"
/>
</div>
</t>
</div>
</div>
</div>
<t t-set-slot="footer">
<button class="btn btn-primary" t-on-click="this.props.close">Close</button>
</t>
</Dialog>
</t>
</templates>

View File

@@ -0,0 +1,76 @@
import { Component, t, useProps } from "@odoo/owl";
import { Dialog } from "@web/core/dialog/dialog";
import { _t } from "@web/core/l10n/translation";
import { useService } from "@web/core/utils/hooks";
import { AiAgentPanelCard } from "@ai_agentic/components/ai_agent_panel_card/ai_agent_panel_card";
const HELP_PROMPT = _t(
"Let's create a new Trigger together, I'm not sure what setup is best for my use case."
);
export class AgentTriggerAddDialog extends Component {
static template = "ai_agentic.AgentTriggerAddDialog";
static components = { AiAgentPanelCard, Dialog };
props = useProps({
agentId: t.number(),
close: t.function(),
});
setup() {
this.action = useService("action");
this.store = useService("mail.store");
this.dialog = useService("dialog");
}
get cardsData() {
return [
{
image: "/ai_agentic/static/src/img/ai_trigger_cron.svg",
title: _t("On a Schedule"),
description: _t("Run automatically at a set frequency, e.g. on Mondays 8AM"),
// targets ai.automation.trigger, not a business model: see BaseAutomation.default_get
onClick: () => this.openAutomationForm("on_schedule"),
},
{
image: "/ai_agentic/static/src/img/ai_trigger_on_date.svg",
title: _t("Based on a Date Field"),
description: _t("Run once per record, when a specific date is reached"),
onClick: () => this.openAutomationForm("on_time"),
},
{
image: "/ai_agentic/static/src/img/ai_trigger_create.svg",
title: _t("After Creation"),
description: _t("Run whenever a new record is added"),
onClick: () => this.openAutomationForm("on_time_created"),
},
{
image: "/ai_agentic/static/src/img/ai_trigger_update.svg",
title: _t("After Update"),
description: _t("Run whenever a specific field gets updated"),
onClick: () => this.openAutomationForm("on_time_updated"),
},
];
}
openAutomationForm(trigger) {
this.openTriggerForm("base.automation", { ai_preset_trigger: trigger });
}
openTriggerForm(resModel, context) {
this.props.close();
this.action.doAction({
type: "ir.actions.act_window",
res_model: resModel,
views: [[false, "form"]],
context: { default_ai_agent_id: this.props.agentId, ...context },
});
}
async onClickHelp() {
const thread = this.store.discuss.thread;
this.dialog.closeAll();
thread.open({ focus: true, fromMessagingMenu: true, bypassCompact: true });
await thread.post(HELP_PROMPT.toString());
}
}

View File

@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space="preserve">
<t t-name="ai_agentic.AgentTriggerAddDialog">
<Dialog title.translate="When should your agent be triggered?" size="'lg'">
<div class="row gy-3 justify-content-center">
<t t-foreach="this.cardsData" t-as="card" t-key="card.title">
<div class="col col-md-6">
<AiAgentPanelCard
image="card.image"
title="card.title"
description="card.description"
onClick="card.onClick"
/>
</div>
</t>
</div>
<button class="btn btn-link ps-0 pt-3" t-on-click="this.onClickHelp">
I need help to choose
</button>
<t t-set-slot="footer">
<button class="btn btn-primary" t-on-click="this.props.close">Close</button>
</t>
</Dialog>
</t>
</templates>

View File

@@ -0,0 +1,14 @@
import { Component, t, useProps } from "@odoo/owl";
/** One clickable option in a "how do you want to do this?" dialog. */
export class AiAgentPanelCard extends Component {
static template = "ai_agentic.AiAgentPanelCard";
props = useProps({
icon: t.string().optional(),
image: t.string().optional(),
title: t.string(),
description: t.string().optional(),
onClick: t.function(),
});
}

View File

@@ -0,0 +1,31 @@
.o_agent_choice_card {
min-height: 180px;
.card-body {
background: linear-gradient(to right, $card-bg, rgba($card-bg, .95));
border-radius: inherit;
}
&:hover {
background: $o-action;
border-radius: inherit;
}
.o_agent_choice_card_icon {
&.oi {
font-size: 48px;
line-height: 48px;
}
}
.o_agent_choice_card_image {
max-width: 64px;
max-height: 64px;
object-fit: contain;
}
.o_agent_choice_card_title {
font-size: 0.9rem;
line-height: 1.3;
}
}

View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space="preserve">
<t t-name="ai_agentic.AiAgentPanelCard">
<div class="o_agent_choice_card card shadow-sm cursor-pointer rounded-3 h-100" t-on-click="this.props.onClick">
<div class="card-body d-flex flex-column justify-content-center align-items-center text-center p-3">
<div class="mb-2">
<img t-if="this.props.image" t-att-src="this.props.image" t-att-alt="this.props.title" class="o_agent_choice_card_image"/>
<i t-elif="this.props.icon" class="oi o_agent_choice_card_icon" t-att-data-icon="this.props.icon" t-att-title="this.props.title"/>
</div>
<h5 class="o_agent_choice_card_title card-title mb-0 text-truncate w-100" t-out="this.props.title" t-att-title="this.props.title"/>
<p t-if="this.props.description" class="card-text text-muted small mb-0 mt-1" t-out="this.props.description"/>
</div>
</div>
</t>
</templates>

View File

@@ -0,0 +1,39 @@
import { Record } from "@web/model/relational_model/record";
import { useAutofocus } from "@web/core/utils/hooks";
import { useInputField } from "@web/views/fields/input_field_hook";
import { Component, signal, t, useProps } from "@odoo/owl";
export class AiAgentSystemPromptEditor extends Component {
static template = "ai_agentic.AiAgentSystemPromptEditor";
props = useProps({
record: t.instanceOf(Record),
placeholder: t.string(),
});
isEditing = signal(false);
textareaRef = signal.ref();
setup() {
useAutofocus({ ref: this.textareaRef });
useInputField({
ref: this.textareaRef,
fieldName: "system_prompt",
getValue: () => this.props.record.data.system_prompt || "",
});
}
get isEmpty() {
return !(this.props.record.data.system_prompt || "").trim();
}
startEditing() {
this.isEditing.set(true);
}
async stopEditing() {
await this.props.record.isDirty(); // forces the pending edit to commit first
this.isEditing.set(false);
}
}

View File

@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space="preserve">
<t t-name="ai_agentic.AiAgentSystemPromptEditor">
<div class="o_ai_agent_system_prompt_editor d-flex flex-column h-100 pt-2">
<textarea
t-if="this.isEditing()"
t-ref="this.textareaRef"
class="flex-grow-1 w-100 h-100 p-0 border-0 bg-transparent overflow-y-auto text-break"
t-att-placeholder="this.props.placeholder"
t-on-blur="this.stopEditing"
/>
<div
t-else=""
class="o_ai_agent_system_prompt_editor_preview flex-grow-1 w-100 overflow-y-auto text-break"
t-on-click="this.startEditing"
>
<span t-if="this.isEmpty" class="text-muted text-prewrap" t-out="this.props.placeholder"/>
<t t-else="" t-out="this.props.record.data.system_prompt_rendered"/>
</div>
</div>
</t>
</templates>

View File

@@ -0,0 +1,11 @@
import { AiAgent } from "@ai/discuss/core/common/ai_agent_model";
import { patch } from "@web/core/utils/patch";
patch(AiAgent.prototype, {
setup() {
super.setup(...arguments);
/** Whether inspectable automation runs exist, feeding the scoped Automation tab. */
this.has_automation_channels = false;
},
});

View File

@@ -0,0 +1,10 @@
import { DiscussChannel } from "@mail/discuss/core/common/discuss_channel_model";
import { patch } from "@web/core/utils/patch";
patch(DiscussChannel.prototype, {
setup() {
super.setup(...arguments);
this.from_ai_automation = false;
},
});

View File

@@ -0,0 +1,16 @@
import { ActionPanel } from "@mail/discuss/core/common/action_panel";
import { Component, t, useProps } from "@odoo/owl";
import { AiAgentPanel } from "@ai_agentic/discuss/core/web/ai_agent_panel/ai_agent_panel";
/** The agent panel as a thread action panel, for the chats opened outside the agent's page. */
export class AiAgentActionPanel extends Component {
static template = "ai_agentic.AiAgentActionPanel";
static components = { ActionPanel, AiAgentPanel };
props = useProps({
agent: t.any(),
close: t.function().optional(),
});
}

View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space="preserve">
<t t-name="ai_agentic.AiAgentActionPanel">
<ActionPanel close="this.props.close" minWidth="240" initialWidth="420">
<AiAgentPanel agent="this.props.agent"/>
</ActionPanel>
</t>
</templates>

View File

@@ -0,0 +1,186 @@
import { Record } from "@web/model/record";
import { ConfirmationDialog } from "@web/core/confirmation_dialog/confirmation_dialog";
import { Dropdown } from "@web/core/dropdown/dropdown";
import { DropdownItem } from "@web/core/dropdown/dropdown_item";
import { extractFieldsFromArchInfo } from "@web/model/relational_model/utils";
import { CharField } from "@web/views/fields/char/char_field";
import { Field } from "@web/views/fields/field";
import { ImageField } from "@web/views/fields/image/image_field";
import { FormArchParser } from "@web/views/form/form_arch_parser";
import { _t } from "@web/core/l10n/translation";
import { parseXML } from "@web/core/utils/xml";
import { useSetupAction } from "@web/search/action_hook";
import { useService } from "@web/core/utils/hooks";
import { pick } from "@web/core/utils/objects";
import { useDebounced } from "@web/core/utils/timing";
import { AiAgentSystemPromptEditor } from "@ai_agentic/components/ai_agent_system_prompt_editor/ai_agent_system_prompt_editor";
import { AiAgentPanelNativeSkills } from "@ai_agentic/discuss/core/web/ai_agent_panel/ai_agent_panel_skills/ai_agent_panel_native_skills";
import "@ai_agentic/discuss/core/web/ai_agent_panel/ai_agent_panel_skills/ai_agent_panel_skills";
import "@ai_agentic/discuss/core/web/ai_agent_panel/ai_agent_panel_sources/ai_agent_panel_sources";
import "@ai_agentic/discuss/core/web/ai_agent_panel/ai_agent_panel_triggers/ai_agent_panel_triggers";
import { browser } from "@web/core/browser/browser";
import { Component, onWillStart, proxy, t, useProps } from "@odoo/owl";
const AI_AGENT_MODEL = "ai.agent";
const AI_AGENT_PANEL_VIEW_REF = "ai_agentic.ai_agent_view_form";
// Fields shown as the channel name/subtitle (Need to be in sync).
const AI_AGENT_DISPLAY_FIELD_NAMES = ["name", "subtitle"];
const TABS = [
{ id: "instructions", label: _t("Instructions") },
{ id: "skills", label: _t("Skills") },
{ id: "knowledge", label: _t("Knowledge") },
{ id: "triggers", label: _t("Triggers") },
];
const DEFAULT_TAB_ID = TABS[0].id;
const ACTIVE_TAB_IDS_KEY = "ai_agentic.AiAgentPanel.activeTabIds";
function readActiveTabIds() {
try {
return JSON.parse(browser.sessionStorage.getItem(ACTIVE_TAB_IDS_KEY)) ?? {};
} catch {
return {};
}
}
function getFieldNodesByName(archInfo) {
return Object.fromEntries(
Object.values(archInfo.fieldNodes).map((fieldNode) => [fieldNode.name, fieldNode])
);
}
export class AiAgentPanel extends Component {
static components = {
AiAgentSystemPromptEditor,
AiAgentPanelNativeSkills,
CharField,
Dropdown,
DropdownItem,
Field,
ImageField,
Record,
};
static template = "ai_agentic.AiAgentPanel";
tabs = TABS;
setup() {
super.setup();
this.props = useProps({
agent: t.any(),
showAgentActions: t.boolean().optional(),
});
this.viewService = useService("view");
this.actionService = useService("action");
this.dialog = useService("dialog");
onWillStart(() => this.loadPanelView());
this.debouncedSaveAgentChanges = useDebounced(() => this.flushAgentChanges(), 500);
this.recordHooks = {
onRecordChanged: (record) => {
this.record = record;
this.debouncedSaveAgentChanges();
},
};
// Saves before leaving the action: a debounced save can't rely on
// execBeforeUnmount, its RPC is aborted before onWillDestroy runs.
useSetupAction({ beforeLeave: () => this.flushAgentChanges() });
this.state = proxy({ activeTabIds: readActiveTabIds() });
}
/** Single choke point for both the debounce and beforeLeave. */
async flushAgentChanges() {
this.debouncedSaveAgentChanges.cancel();
if (this.record) {
await this.saveAgentChanges(this.record);
}
}
get activeTabId() {
const tabId = this.state.activeTabIds[this.agent?.id];
return TABS.some((tab) => tab.id === tabId) ? tabId : DEFAULT_TAB_ID;
}
isActiveTab(id) {
return this.activeTabId === id;
}
setActiveTab(id) {
this.state.activeTabIds[this.agent.id] = id;
browser.sessionStorage.setItem(ACTIVE_TAB_IDS_KEY, JSON.stringify(this.state.activeTabIds));
}
async loadPanelView() {
const { fields, relatedModels, views } = await this.viewService.loadViews({
context: { form_view_ref: AI_AGENT_PANEL_VIEW_REF },
resModel: AI_AGENT_MODEL,
views: [[false, "form"]],
});
const parser = new FormArchParser();
const arch = views.form.arch;
this.agentArchInfo = parser.parse(parseXML(arch), relatedModels, AI_AGENT_MODEL);
const { activeFields } = extractFieldsFromArchInfo(this.agentArchInfo, fields);
if (!Object.keys(activeFields).length) {
return;
}
this.agentFields = fields;
this.agentActiveFields = activeFields;
this.fieldNodes = getFieldNodesByName(this.agentArchInfo);
}
get agent() {
return this.props.agent;
}
get resModel() {
return AI_AGENT_MODEL;
}
archiveAgent(record) {
this.dialog.add(ConfirmationDialog, {
body: _t("Are you sure that you want to archive this agent?"),
confirmLabel: _t("Archive"),
confirm: async () => {
await this.flushAgentChanges();
await record.archive();
await this.actionService.doAction("ai_agentic.ai_agent_action", {
clearBreadcrumbs: true,
});
},
cancel: () => {},
});
}
async unarchiveAgent(record) {
await this.flushAgentChanges();
await record.unarchive();
}
deleteAgent(record) {
this.dialog.add(ConfirmationDialog, {
body: _t("Are you sure that you want to delete this agent?"),
confirmLabel: _t("Delete"),
confirmClass: "btn-danger",
confirm: async () => {
if ((await record.delete()) !== false) {
this.agent?.delete();
await this.actionService.doAction("ai_agentic.ai_agent_action", {
clearBreadcrumbs: true,
});
}
},
cancel: () => {},
});
}
async saveAgentChanges(record) {
if (
(await record.isDirty()) &&
(await record.checkValidity({ displayNotification: true })) &&
(await record.save({ reload: false }))
) {
this.agent?.update(pick(record.data, ...AI_AGENT_DISPLAY_FIELD_NAMES));
}
}
}

View File

@@ -0,0 +1,99 @@
.o_ai_agent_panel_container {
width: 420px;
max-width: 30vw;
}
.o_ai_agent_panel {
.o_ai_agent_panel_header {
.o_input {
color: inherit;
font: inherit;
&:not(:hover):not(:focus) {
--o-input-border-color: transparent;
}
}
.o_ai_agent_panel_subtitle {
font-size: $o-font-size-base-smaller;
.o_input {
overflow: hidden;
text-overflow: ellipsis;
}
}
}
.o_icon_preview {
width: 20px;
height: 20px;
}
.o_ai_agent_panel_tab {
background: none;
border: 0;
border-bottom: 2px solid transparent;
padding: 0.5rem 0 0.25rem;
color: $o-gray-600;
font: inherit;
cursor: pointer;
&.o_ai_agent_panel_tab_active {
color: $o-enterprise-action-color;
border-bottom-color: currentColor;
font-weight: bold;
}
}
.o_ai_agent_panel_tabpanels {
// avoid a hard cut of the scrolled content at the panel's bottom edge
padding-bottom: $spacer * 2;
mask-image: linear-gradient(to bottom, black calc(100% - #{$spacer * 1.5}), transparent);
}
.o_ai_agent_panel_tabpanels textarea {
resize: none;
color: inherit;
font: inherit;
}
.o_ai_agent_system_prompt_editor_preview {
cursor: text;
> :first-child {
margin-top: 0;
}
> :last-child {
margin-bottom: 0;
}
h1 {
font-size: 1.3rem;
}
h2 {
font-size: 1.2rem;
}
:is(h2, h3, h4):not(:first-child) {
margin-top: 12px;
}
}
.o_ai_agent_panel_list_row {
min-height: 2.5rem;
&:has(button):hover {
background-color: mix($o-view-background-color, $o-action, 95%);
}
&.o_ai_agent_panel_list_row_nested {
min-height: 2rem;
border-radius: 0.25rem;
}
}
.o_ai_agent_panel_list_row_menu {
min-width: 9rem;
}
}

View File

@@ -0,0 +1,113 @@
<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space="preserve">
<t t-name="ai_agentic.AiAgentPanelHeader">
<div class="o_ai_agent_panel_header d-flex align-items-center gap-2 py-1">
<div class="flex-shrink-0">
<ImageField name="'image_128'" record="data.record" width="64" height="64" imgClass="'rounded'"/>
</div>
<div class="d-flex flex-column overflow-hidden flex-grow-1 min-w-0 gap-1">
<div class="fw-bold fs-4 lh-sm min-w-0 px-1">
<CharField name="'name'" record="data.record" placeholder.translate="Agent Name"/>
</div>
<div class="text-muted lh-sm min-w-0 o_ai_agent_panel_subtitle px-1">
<CharField name="'subtitle'" record="data.record" placeholder.translate="Agent Subtitle"/>
</div>
</div>
<Dropdown t-if="this.props.showAgentActions" position="'bottom-end'">
<button class="btn btn-light o-no-caret px-1 align-self-start flex-shrink-0" title.translate="Agent Actions">
<i class="oi oi-lg" data-icon="more_vert"/>
</button>
<t t-set-slot="content">
<DropdownItem t-if="data.record.data.active" onSelected="() => this.archiveAgent(data.record)">
<i class="oi me-1" role="img" data-icon="archive"/>Archive
</DropdownItem>
<DropdownItem t-else="" onSelected="() => this.unarchiveAgent(data.record)">
<i class="oi me-1" role="img" data-icon="unarchive"/>Unarchive
</DropdownItem>
<DropdownItem
t-if="!data.record.data.is_system_agent"
class="'text-danger'"
onSelected="() => this.deleteAgent(data.record)"
>
<i class="oi me-1" role="img" data-icon="delete"/>Delete
</DropdownItem>
</t>
</Dropdown>
</div>
</t>
<t t-name="ai_agentic.AiAgentPanel">
<Record
t-if="this.agent?.id and this.agentFields"
t-key="this.agent.id"
fields="this.agentFields"
activeFields="this.agentActiveFields"
resModel="this.resModel"
resId="this.agent.id"
mode="'edit'"
hooks="this.recordHooks"
t-slot-scope="data"
>
<div class="o_ai_agent_panel d-flex flex-column h-100 overflow-x-hidden overflow-y-auto o-scrollbar-thin bg-inherit rounded-4">
<div class="ps-3 pe-2">
<t t-call="ai_agentic.AiAgentPanelHeader"/>
</div>
<div class="o_ai_agent_panel_tabs d-flex flex-column flex-grow-1 min-h-0 overflow-hidden">
<div class="o_ai_agent_panel_tablist d-flex gap-4 flex-shrink-0 flex-nowrap overflow-x-auto o-scrollbar-thin border-bottom px-3">
<t t-foreach="this.tabs" t-as="tab" t-key="tab.id">
<button
role="tab"
tabindex="0"
t-att-class="{ 'o_ai_agent_panel_tab_active': this.isActiveTab(tab.id) }"
class="o_ai_agent_panel_tab flex-shrink-0 text-nowrap"
t-on-click="() => this.setActiveTab(tab.id)"
>
<t t-out="tab.label"/>
</button>
</t>
</div>
<div class="o_ai_agent_panel_tabpanels flex-grow-1 overflow-x-hidden overflow-y-auto o-scrollbar-thin min-h-0 px-3 pt-2">
<div t-if="this.isActiveTab('instructions')" role="tabpanel" class="h-100 pb-2">
<AiAgentSystemPromptEditor
record="data.record"
placeholder.translate="Define your agent's operating framework:&#10;- Which role should it take?&#10;- What can it do?&#10;- How should it work?"
/>
</div>
<div t-if="this.isActiveTab('skills')" role="tabpanel" class="d-flex flex-column w-100 pb-2">
<AiAgentPanelNativeSkills
record="data.record"
name="'skill_ids'"
domain="[['is_native_skill', '=', true]]"
/>
<Field t-foreach="['custom_skill_ids', 'allowed_agent_ids']" t-as="fieldName" t-key="fieldName"
id="fieldName"
name="fieldName"
record="data.record"
fieldInfo="this.fieldNodes[fieldName]"
class="'d-block w-100 min-w-0 mb-3'"
/>
</div>
<div t-if="this.isActiveTab('knowledge')" role="tabpanel" class="d-flex flex-column w-100 pb-2">
<Field
name="'sources_ids'"
record="data.record"
fieldInfo="this.fieldNodes.sources_ids"
class="'d-block w-100 min-w-0'"
/>
</div>
<div t-if="this.isActiveTab('triggers')" role="tabpanel" class="d-flex flex-column w-100 pb-2">
<Field
name="'automation_ids'"
record="data.record"
fieldInfo="this.fieldNodes.automation_ids"
class="'d-block w-100 min-w-0'"
context="{'active_test': False}"
/>
</div>
</div>
</div>
</div>
</Record>
</t>
</templates>

View File

@@ -0,0 +1,16 @@
import { ListRenderer } from "@web/views/list/list_renderer";
export class AiAgentPanelListRenderer extends ListRenderer {
static template = "ai_agentic.AiAgentPanelList";
static rowTemplate = "";
static empty = { icon: "", text: "" };
/** Optional left-hand side of the header row; the add button is shared. */
static headerTemplate = "";
/**
* Shared by every list in this panel (skills, sources, ...).
* From ListRenderer: we can't really use `super.setup()` because it
* expects to be used on a html table which is not the case here.
*/
setup() {}
}

View File

@@ -0,0 +1,32 @@
<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space="preserve">
<t t-name="ai_agentic.AiAgentPanelList.AddButton">
<button class="btn btn-sm btn-primary flex-shrink-0" t-on-click.stop.prevent="() => this.props.onAdd({})">
<i class="oi me-1" data-icon="add"/>Add
</button>
</t>
<t t-name="ai_agentic.AiAgentPanelList">
<t t-set="isEmpty" t-value="!this.props.list.records.length"/>
<div class="o_ai_agent_panel_list d-flex flex-column gap-2 w-100">
<div class="d-flex align-items-center gap-2">
<t t-if="this.constructor.headerTemplate" t-call="{{ this.constructor.headerTemplate }}"/>
<div t-if="!isEmpty" class="ms-auto">
<t t-call="ai_agentic.AiAgentPanelList.AddButton"/>
</div>
</div>
<div t-if="isEmpty" class="text-center text-500 my-3">
<i class="oi oi-2x opacity-50 mb-2 d-block" t-att-data-icon="this.constructor.empty.icon"/>
<p t-out="this.constructor.empty.text"/>
<t t-call="ai_agentic.AiAgentPanelList.AddButton"/>
</div>
<t t-else="">
<t t-foreach="this.props.list.records" t-as="record" t-key="record.id">
<t t-call="{{ this.constructor.rowTemplate }}"/>
</t>
</t>
</div>
</t>
</templates>

View File

@@ -0,0 +1,38 @@
import { _t } from "@web/core/l10n/translation";
import { registry } from "@web/core/registry";
import { X2ManyField, x2ManyField } from "@web/views/fields/x2many/x2many_field";
import { AiAgentPanelListRenderer } from "@ai_agentic/discuss/core/web/ai_agent_panel/ai_agent_panel_list";
export class AiAgentPanelAgentListRenderer extends AiAgentPanelListRenderer {
static rowTemplate = "ai_agentic.AiAgentPanelAgentListRenderer.Row";
static headerTemplate = "ai_agentic.AiAgentPanelAgentListRenderer.Header";
static empty = {
icon: "handshake",
text: _t("Allow this Agent to ask for help to other Agents"),
};
async onClickAgent(record) {
const result = await this.env.services.orm.call("ai.agent", "open_agent_chat", [
record.data.id,
]);
if (result) {
this.env.services.action.doAction(result);
}
}
async onClickRemoveAgent(record) {
await this.activeActions.onDelete?.(record);
}
}
export class AiAgentX2ManyField extends X2ManyField {
static components = {
...X2ManyField.components,
ListRenderer: AiAgentPanelAgentListRenderer,
};
}
registry.category("fields").add("ai_agent_panel_agent_x2many", {
...x2ManyField,
component: AiAgentX2ManyField,
});

View File

@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space="preserve">
<t t-name="ai_agentic.AiAgentPanelAgentListRenderer.Header">
<h6 class="mb-0">Subagents</h6>
</t>
<t t-name="ai_agentic.AiAgentPanelAgentListRenderer.Row">
<div class="o_ai_agent_panel_list_row d-flex align-items-center gap-2 w-100 p-2 border rounded-4 bg-body">
<button
class="btn btn-link text-start text-reset text-decoration-none min-w-0 flex-grow-1 p-0 d-flex align-items-center gap-2"
type="button"
t-on-click="() => this.onClickAgent(record)"
>
<img t-attf-src="/web/image/ai.agent/{{record.data.id}}/avatar_128" class="o_avatar rounded"/>
<span class="fw-bold text-truncate m0" t-out="record.data.name"/>
</button>
<button class="btn btn-sm o-no-caret px-1" t-on-click="() => this.onClickRemoveAgent(record)">
<span class="oi" data-icon="close"/>
</button>
</div>
</t>
</templates>

View File

@@ -0,0 +1,5 @@
import { Many2ManyCheckboxesField } from "@web/views/fields/many2many_checkboxes/many2many_checkboxes_field";
export class AiAgentPanelNativeSkills extends Many2ManyCheckboxesField {
static template = "ai_agentic.AiAgentPanelNativeSkills";
}

View File

@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space="preserve">
<t t-name="ai_agentic.AiAgentPanelNativeSkills">
<div>
<h6 class="mt-2 mb-2">Tools</h6>
<div aria-atomic="true" class="d-flex flex-column gap-2 w-100 mb-3">
<t t-foreach="this.items" t-as="item" t-key="item.id">
<div class="o_ai_agent_panel_list_row d-flex align-items-center justify-content-between gap-2 w-100 p-2 border rounded-4 bg-body">
<span class="text-900 fw-medium text-truncate" t-out="item.display_name"/>
<CheckBox
value="this.isSelected(item)"
onChange="(checked) => this.onChange(item.id, item.display_name, checked)"
className="'o_field_boolean o_boolean_toggle form-switch'"
/>
</div>
</t>
</div>
</div>
</t>
</templates>

View File

@@ -0,0 +1,33 @@
import { _t } from "@web/core/l10n/translation";
import { registry } from "@web/core/registry";
import { X2ManyField, x2ManyField } from "@web/views/fields/x2many/x2many_field";
import { AiAgentPanelListRenderer } from "@ai_agentic/discuss/core/web/ai_agent_panel/ai_agent_panel_list";
export class AiAgentPanelSkillListRenderer extends AiAgentPanelListRenderer {
static rowTemplate = "ai_agentic.AiAgentPanelSkillListRenderer.Row";
static headerTemplate = "ai_agentic.AiAgentPanelSkillListRenderer.Header";
static empty = {
icon: "wand_stars",
text: _t("Add skills to expand what your agent can do."),
};
async onClickEditSkill(record) {
await this.props.openRecord(record);
}
async onClickRemoveSkill(record) {
await this.activeActions.onDelete?.(record);
}
}
export class AiAgentSkillX2ManyField extends X2ManyField {
static components = {
...X2ManyField.components,
ListRenderer: AiAgentPanelSkillListRenderer,
};
}
registry.category("fields").add("ai_agent_panel_skill_x2many", {
...x2ManyField,
component: AiAgentSkillX2ManyField,
});

View File

@@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space="preserve">
<t t-name="ai_agentic.AiAgentPanelSkillListRenderer.Header">
<h6 class="mb-0">Skills</h6>
</t>
<t t-name="ai_agentic.AiAgentPanelSkillListRenderer.Row">
<div class="o_ai_agent_panel_list_row d-flex align-items-center gap-2 w-100 p-2 border rounded-4 bg-body">
<button
class="btn btn-link text-start text-reset text-decoration-none min-w-0 flex-grow-1 p-0 d-flex align-items-center gap-2"
type="button"
t-on-click="() => this.onClickEditSkill(record)"
>
<i class="oi" data-icon="wand_stars"/>
<span class="d-block text-truncate" t-out="record.data.name"/>
</button>
<Dropdown menuClass="'o_ai_agent_panel_list_row_menu'" position="'bottom-end'">
<button class="btn btn-sm o-no-caret px-1" title="Dropdown menu">
<span class="oi" data-icon="more_vert"/>
</button>
<t t-set-slot="content">
<DropdownItem onSelected="() => this.onClickEditSkill(record)">
<i class="oi oi-fw oi-filled me-2" data-icon="edit"/>Edit
</DropdownItem>
<DropdownItem class="'text-danger'" onSelected="() => this.onClickRemoveSkill(record)">
<i class="oi oi-fw oi-filled me-2" data-icon="delete"/>Remove
</DropdownItem>
</t>
</Dropdown>
</div>
</t>
</templates>

View File

@@ -0,0 +1,71 @@
import { AgentSourceAddDialog } from "@ai_agentic/components/agent_add_source_dialog/agent_add_source_dialog";
import { _t } from "@web/core/l10n/translation";
import { registry } from "@web/core/registry";
import { useService } from "@web/core/utils/hooks";
import { BooleanToggleField } from "@web/views/fields/boolean_toggle/boolean_toggle_field";
import { X2ManyField, x2ManyField } from "@web/views/fields/x2many/x2many_field";
import { AiAgentPanelListRenderer } from "@ai_agentic/discuss/core/web/ai_agent_panel/ai_agent_panel_list";
import { AiAgentSourceRow } from "@ai_agentic/discuss/core/web/ai_agent_panel/ai_agent_panel_sources/ai_agent_source_row";
import { AiAgentSourceFolderTreePlugin } from "@ai_agentic/discuss/core/web/ai_agent_panel/ai_agent_panel_sources/ai_agent_source_folder_tree_plugin";
import { onWillStart, providePlugins, usePlugin } from "@odoo/owl";
export class AiAgentPanelSourceListRenderer extends AiAgentPanelListRenderer {
static rowTemplate = "ai_agentic.AiAgentPanelSourceListRenderer.Row";
static headerTemplate = "ai_agentic.AiAgentPanelSourceListRenderer.Header";
static empty = {
icon: "folder_open",
text: _t("Add sources to give your agent the information it needs to answer accurately."),
};
static components = {
...AiAgentPanelListRenderer.components,
AiAgentSourceRow,
BooleanToggleField,
};
setup() {
super.setup();
this.sourcesFolderTree = usePlugin(AiAgentSourceFolderTreePlugin);
}
}
export class AiAgentSourceX2ManyField extends X2ManyField {
static components = {
...X2ManyField.components,
ListRenderer: AiAgentPanelSourceListRenderer,
};
setup() {
super.setup();
this.dialog = useService("dialog");
providePlugins([AiAgentSourceFolderTreePlugin], {
record: this.props.record,
list: this.list,
});
this.sourcesFolderTree = usePlugin(AiAgentSourceFolderTreePlugin);
onWillStart(() => this.sourcesFolderTree.loadTree());
}
get rendererProps() {
return {
...super.rendererProps,
list: { records: this.sourcesFolderTree.rootRecords },
};
}
get canCreate() {
return super.canCreate && this.sourcesFolderTree.canManageSources();
}
onAdd() {
this.dialog.add(AgentSourceAddDialog, {
agentId: this.props.record.resId,
onSourcesAdded: () => this.sourcesFolderTree.reloadAll(),
});
}
}
registry.category("fields").add("ai_agent_panel_source_x2many", {
...x2ManyField,
component: AiAgentSourceX2ManyField,
});

View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space="preserve">
<t t-name="ai_agentic.AiAgentPanelSourceListRenderer.Header">
<div class="d-flex align-items-center gap-2">
<BooleanToggleField name="'restrict_to_sources'" record="this.sourcesFolderTree.record"/>
<span>Restrict answers to Sources</span>
</div>
</t>
<t t-name="ai_agentic.AiAgentPanelSourceListRenderer.Row">
<AiAgentSourceRow record="record"/>
</t>
</templates>

View File

@@ -0,0 +1,86 @@
import { ORM } from "@web/core/orm_plugin";
import { user } from "@web/core/user";
import { Plugin, signal, types as t, useConfig, usePlugin } from "@odoo/owl";
export class AiAgentSourceFolderTreePlugin extends Plugin {
orm = usePlugin(ORM);
record = useConfig("record", t.record());
list = useConfig("list", t.object());
unfoldedIds = signal.Set(new Set(), { type: t.number() });
records = signal.Array([]);
canManageSources = signal(false);
setup() {
user.hasGroup("base.group_system").then((hasGroup) => this.canManageSources.set(hasGroup));
}
get rootRecords() {
return this.records().filter((record) => !record.data.parent_id);
}
get childrenByParentId() {
const records = this.records();
if (this._childrenByParentId?.records !== records) {
const byParentId = new Map();
for (const record of records) {
const parentId = record.data.parent_id && record.data.parent_id[0];
if (parentId) {
if (!byParentId.has(parentId)) {
byParentId.set(parentId, []);
}
byParentId.get(parentId).push(record);
}
}
this._childrenByParentId = { records, byParentId };
}
return this._childrenByParentId.byParentId;
}
childrenOf(parentResId) {
return this.childrenByParentId.get(parentResId) || [];
}
async loadTree() {
const rows = await this.orm.call("ai.agent.source", "get_agent_sources_tree", [
this.record.resId,
Object.keys(this.list.activeFields),
[...this.unfoldedIds()],
]);
this.records.set(rows.map((data) => ({ id: data.id, resId: data.id, data })));
}
async toggleFolder(record) {
if (this.unfoldedIds().has(record.resId)) {
this.unfoldedIds().delete(record.resId);
return;
}
this.unfoldedIds().add(record.resId);
if (!this.childrenOf(record.resId).length) {
await this.loadTree();
}
}
async reloadAll() {
// Only the sources tree needs refreshing here: no field on the agent
// record itself depends on source state, so reloading the parent
// record would be wasted work. Saving first only guards against
// clobbering an in-progress edit to another field (e.g. name).
if (await this.record.isDirty()) {
await this.record.save({ reload: false });
}
await this.loadTree();
}
patchRecord(resId, data) {
this.records.set(
this.records().map((record) =>
record.resId === resId ? { ...record, data: { ...record.data, ...data } } : record
)
);
}
removeRecord(resId) {
this.records.set(this.records().filter((record) => record.resId !== resId));
}
}

View File

@@ -0,0 +1,32 @@
import { _t } from "@web/core/l10n/translation";
export const STATUS_BADGE_CLASS = {
indexed: "text-bg-success",
incomplete: "text-bg-warning",
processing: "text-bg-info",
failed: "text-bg-danger",
};
export const SOURCE_ICON_CONFIGS = {
url: () => ({
type: "icon",
icon: "link",
title: _t("Link"),
}),
binary: (record) => {
const { mimetype } = record.data;
if (mimetype) {
return {
type: "mimetype",
dataMimetype: mimetype,
title: mimetype,
};
}
return SOURCE_ICON_CONFIGS.default(record);
},
default: () => ({
type: "icon",
icon: "description",
title: _t("File"),
}),
};

View File

@@ -0,0 +1,116 @@
import { Dropdown } from "@web/core/dropdown/dropdown";
import { DropdownItem } from "@web/core/dropdown/dropdown_item";
import { _t } from "@web/core/l10n/translation";
import { useService } from "@web/core/utils/hooks";
import { SOURCE_ICON_CONFIGS, STATUS_BADGE_CLASS } from "./ai_agent_source_icons";
import { AiAgentSourceFolderTreePlugin } from "./ai_agent_source_folder_tree_plugin";
import { Component, t, useProps, usePlugin } from "@odoo/owl";
export class AiAgentSourceRow extends Component {
static template = "ai_agentic.AiAgentSourceRow";
static components = { AiAgentSourceRow, Dropdown, DropdownItem };
setup() {
this.props = useProps({
record: t.any(),
isNested: t.boolean().optional(),
});
this.orm = useService("orm");
this.action = useService("action");
this.sourcesFolderTree = usePlugin(AiAgentSourceFolderTreePlugin);
}
get record() {
return this.props.record;
}
get isUnfolded() {
return this.sourcesFolderTree.unfoldedIds().has(this.record.resId);
}
childRecords() {
return this.sourcesFolderTree.childrenOf(this.record.resId);
}
sourceIconConfig() {
const iconConfig = SOURCE_ICON_CONFIGS[this.record.data.type];
return (iconConfig || SOURCE_ICON_CONFIGS.default)(this.record);
}
sourcesCountLabel() {
return "";
}
statusBadgeClass() {
return STATUS_BADGE_CLASS[this.record.data.status] || "text-bg-secondary";
}
statusErrorTooltip() {
const { status, error_details } = this.record.data;
return ["failed", "incomplete"].includes(status) ? error_details : "";
}
canOpenSource() {
const { file_sources_count, is_folder, status, user_has_access } = this.record.data;
return (is_folder && file_sources_count > 0) || (status === "indexed" && user_has_access);
}
canRetryOrReprocess() {
const { status, type } = this.record.data;
return (
status === "failed" ||
status === "incomplete" ||
(status === "indexed" && type !== "binary")
);
}
canToggleActive() {
const { status } = this.record.data;
return status !== "processing" && status !== "failed";
}
retryOrReprocessLabel() {
return this.record.data.status === "indexed" ? _t("Reprocess") : _t("Retry");
}
toggleActiveLabel() {
return this.record.data.is_active ? _t("Disable") : _t("Enable");
}
async onClickSource() {
if (!this.canOpenSource()) {
return;
}
if (this.record.data.is_folder) {
await this.sourcesFolderTree.toggleFolder(this.record);
return;
}
const action = await this.orm.call("ai.agent.source", "action_access_source", [
[this.record.resId],
]);
if (action) {
await this.action.doAction(action);
}
}
async onClickToggleActive() {
const is_active = !this.record.data.is_active;
await this.orm.write("ai.agent.source", [this.record.resId], { is_active });
this.sourcesFolderTree.patchRecord(this.record.resId, { is_active });
}
async onClickRetryOrReprocess() {
const method =
this.record.data.status === "indexed"
? "action_reprocess_index"
: "action_retry_failed_source";
await this.orm.call("ai.agent.source", method, [[this.record.resId]]);
this.sourcesFolderTree.patchRecord(this.record.resId, { status: "processing" });
}
async onClickRemoveSource() {
await this.orm.unlink("ai.agent.source", [this.record.resId]);
this.sourcesFolderTree.removeRecord(this.record.resId);
}
}

View File

@@ -0,0 +1,88 @@
<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space="preserve">
<t t-name="ai_agentic.AiAgentSourceRow">
<t t-set="record" t-value="this.record"/>
<div>
<div
t-attf-class="o_ai_agent_panel_list_row d-flex align-items-center gap-2 w-100 {{ this.props.isNested ? 'o_ai_agent_panel_list_row_nested py-1 px-2 small' : 'p-2 border rounded-4 bg-body' }}"
>
<button
class="btn btn-link text-start text-reset text-decoration-none min-w-0 flex-grow-1 p-0"
type="button"
t-att-class="{ 'cursor-pointer': this.canOpenSource(), 'opacity-50': !record.data.is_active }"
t-on-click="() => this.onClickSource()"
>
<span class="d-flex align-items-center gap-2 min-w-0">
<i
t-if="record.data.is_folder"
class="oi opacity-75" t-att-data-icon="this.isUnfolded ? 'arrow_drop_down' : 'arrow_right'"
/>
<t t-set="icon" t-value="this.sourceIconConfig()"/>
<i t-if="icon.type === 'icon'" class="oi ms-1" t-att-data-icon="icon.icon" t-att-title="icon.title"/>
<i t-elif="icon.type === 'mimetype'" class="o_image o_icon_preview" t-att-data-mimetype="icon.dataMimetype" t-att-title="icon.title"/>
<img t-elif="icon.type === 'image'" class="o_icon_preview" t-att-src="icon.src" t-att-alt="icon.title" t-att-title="icon.title"/>
<span class="min-w-0">
<span class="text-900 fw-medium d-block text-truncate" t-att-title="record.data.name" t-out="record.data.name"/>
<span
t-if="this.sourcesCountLabel()"
class="d-inline-flex align-items-center px-2 py-0 small rounded-pill border bg-light ms-1"
>
<span class="fw-bold" t-out="this.sourcesCountLabel()"/>
</span>
</span>
</span>
</button>
<div class="d-flex align-items-center gap-2 flex-shrink-0">
<span
t-if="record.data.status"
t-attf-class="badge rounded-pill {{ this.statusBadgeClass() }}"
t-att-data-tooltip="this.statusErrorTooltip()"
>
<t t-out="record.data.status"/>
</span>
<Dropdown
t-if="this.sourcesFolderTree.canManageSources()"
menuClass="'o_ai_agent_panel_list_row_menu'"
position="'bottom-end'"
>
<button class="btn btn-sm o-no-caret px-1" title="Dropdown menu">
<span class="oi" data-icon="more_vert"/>
</button>
<t t-set-slot="content">
<DropdownItem
t-if="this.canRetryOrReprocess()"
onSelected="() => this.onClickRetryOrReprocess()"
>
<i class="oi oi-fw me-2" data-icon="refresh"/>
<t t-out="this.retryOrReprocessLabel()"/>
</DropdownItem>
<DropdownItem
t-if="this.canToggleActive()"
onSelected="() => this.onClickToggleActive()"
>
<i class="oi oi-fw me-2" data-icon="block"/>
<t t-out="this.toggleActiveLabel()"/>
</DropdownItem>
<DropdownItem
class="'text-danger'"
onSelected="() => this.onClickRemoveSource()"
>
<i class="oi oi-fw oi-filled me-2" data-icon="delete"/>Remove
</DropdownItem>
</t>
</Dropdown>
</div>
</div>
<div
t-if="record.data.is_folder and this.isUnfolded"
class="ps-4 d-flex flex-column gap-2 mt-2"
>
<t t-foreach="this.childRecords()" t-as="record" t-key="record.resId">
<AiAgentSourceRow record="record" isNested="true"/>
</t>
</div>
</div>
</t>
</templates>

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