Логотип Skill Agent Task Patterns

Skill Agent Task Patterns

Спільнота
javiarmesto
skill-agent-task-patterns

Agent SDK task integration patterns for Business Central. Triggers on: Agent Task Builder, Agent Task Message Builder, Public API, AssignTask, ExternalId, agent session detection, BindSubscription, TryFunction agent task, multi-turn agent conversation, agent attachment, task lifecycle management, OnPrem-only methods, AddToTask, SetRequiresReview, SetSkipMessageSanitization, runtime availability.

Огляд

Видавецьjaviarmesto
РепозиторійALDC-AL-Development-Collection
Назва навичкиskill-agent-task-patterns
Зірки
115
Форки
37
Файли в пакеті
2
ЛіцензіяMIT
Посилання
  • Інструкції у форматі Markdown

    Файл SKILL.md, який модель завантажує за потреби, тож токени витрачаються лише тоді, коли запит справді відповідає навичці.

  • Працює з будь-якою LLM

    Навички ШІ — це звичайний Markdown, а не код для певного постачальника, тому вони працюють із GPT, Claude, Gemini, Grok або локальною моделлю.

  • Файлів у комплекті: 2

    Скрипти, шаблони й довідкові матеріали, які модель може читати під час роботи. Файли доступні лише для читання й ніколи не виконуються.

  • Відкритий вихідний код

    Опубліковано на GitHub користувачем javiarmesto. Перегляньте вихідний вміст перед установленням.

Встановлення

Установіть навичку ШІ Skill Agent Task Patterns у TypingMind, щоб використовувати її з будь-якою LLM, або додайте її до іншого агента, що читає SKILL.md.

1

Встановити в TypingMind

TypingMind встановлює навичку безпосередньо з її папки GitHub — читає SKILL.md, збирає файли ресурсів у пакет і зберігає результат локально.

  1. Відкрийте застосунок і перейдіть до Плагіни → Навички.
  2. Виберіть «Встановити з GitHub».
  3. Вставте наведений нижче URL папки навички та підтвердьте встановлення.
    https://github.com/javiarmesto/ALDC-AL-Development-Collection/tree/main/.claude/skills/skill-agent-task-patterns
  4. Увімкніть навичку в кожному чаті, де хочете її використовувати.
Плагіни → Навички → Нова навичка → За URL GitHub, потім вставте URL папки й натисніть «Продовжити».
2

Встановити в іншому агенті

Будь-який агент, що підтримує формат Agent Skills, може використовувати цю навичку — скопіюйте папку до каталогу навичок цього агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/javiarmesto/ALDC-AL-Development-Collection.git /tmp/ALDC-AL-Development-Collection
mkdir -p .claude/skills
cp -r /tmp/ALDC-AL-Development-Collection/.claude/skills/skill-agent-task-patterns .claude/skills/skill-agent-task-patterns
Після копіювання перезапустіть Claude Code, щоб завантажити нову навичку.

Використовуйте навичку в TypingMind

Увімкніть навичку Skill Agent Task Patterns в будь-якому чаті TypingMind, і далі модель усе зробить сама. Назва й опис навички містяться в системному промпті, а щойно надходить відповідний запит, модель самостійно завантажує повні інструкції — вам не потрібно викликати навичку вручну, і до фактичного використання вона не витрачає токенів.

Модель самостійно завантажує навичку Skill Agent Task Patterns, щойно надходить відповідний запит.

Працює з будь-якою моделлю ШІ

Навички ШІ — це звичайні інструкції Markdown, а не код для певного постачальника, тому навичка Skill Agent Task Patterns не прив’язана до моделі, для якої її створено. Установіть її один раз у TypingMind і використовуйте з GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama або локальною моделлю, яку ви запускаєте самостійно, — усе з вашими власними ключами API.

  • Завантажується лише за потреби

    Системний промпт містить лише назву й опис. Інструкції завантажуються за першого відповідного запиту, тож невикористана навичка нічого не коштує.

  • Змінюйте моделі під час чату

    Оскільки навичка — це інструкції, а не код, зміна моделі не порушує її роботу: наступна модель читає той самий файл SKILL.md.

Інструкції навички

Це вміст файлу SKILL.md, який завантажує модель. Прочитайте його перед установленням — навичка містить інструкції, яких дотримуватиметься ваша модель.

BC Agent Task Integration Patterns

Knowledge base for every Agent SDK task integration pattern, with runtime-availability matrix and Extension-safe workarounds. For SDK architecture and the 3 interfaces, see skill-agent-toolkit.

References:

API availability matrix (Runtime 17.0 / Platform 27.0)

Critical: not every documented method works in Extension scope today. Verify here before designing.

MethodScopeStatusWorkaround
AddTaskMessage(From, Text)Extension✅ Available—
AddAttachment(Name, MediaType, InStream)Extension✅ Available—
SetExternalId(Text)Extension✅ Available—
SetRequiresReview(true)OnPrem only❌ Ext. blockedUse IAgentTaskExecution Warning annotation
SetSkipMessageSanitization(true)OnPrem only❌ Ext. blockedPre-format message text upstream
AddToTask(AgentTask)Future❌ Not in 17.0Create a new follow-up task referencing original ExternalId
Custom Agent.GetCustomAgents()Future❌ Not in 17.0Use Agent Setup.OpenAgentLookup()

OnPrem-only methods are documented but throw at runtime when invoked from a cloud Extension. Treat the workarounds as the canonical Extension pattern.

SDK codeunits — quick reference

CodeunitPurposeKey methods
Agent Task BuilderCreate new tasks (fluent API).Initialize(Guid, Text).SetExternalId(Text).AddTaskMessage(Text, Text).Create()
Agent Task Message BuilderBuild messages with options.Initialize(From, Text), .AddAttachment(Name, MediaType, InStream), .AddToTask(Record)
Agent TaskQuery/manage existing tasksGetTaskByExternalId(Guid, Text), CanSetStatusToReady(Record), SetStatusToReady(Record)
Agent MessageRead/update message textGetText(Record), UpdateText(Record, Text)
Agent SetupAgent lookup + setup managementOpenAgentLookup(Enum, var Guid), GetSetupRecord(...), SaveChanges(...)
AgentCore agent operationsSetInstructions(Guid, SecretText), Deactivate(Guid), IsActive(Guid), GetDisplayName(Guid), PopulateDefaultProfile(...)
Agent SessionDetect agent runtime contextIsAgentSession(var Enum), IsAgentSession(Enum), GetCurrentSessionAgentTaskId()

8 integration patterns

Pattern A — Public API (standard entry point)

When: every reusable task-creation surface. All other patterns call through here.

Architecture: Public codeunit (Access = Public) + Internal implementation codeunit.

Contract:

al
// Overload 1: basic task
procedure AssignTask(AgentUserSecurityID: Guid; TaskTitle: Text[150]; From: Text[250]; Message: Text): Record "Agent Task"

// Overload 2: with ExternalId for tracking / multi-turn
procedure AssignTask(AgentUserSecurityID: Guid; TaskTitle: Text[150]; ExternalId: Text[2048]; From: Text[250]; Message: Text): Record "Agent Task"

// Overload 3: with attachments
procedure AssignTaskWithAttachment(AgentUserSecurityID: Guid; TaskTitle: Text[150]; From: Text[250]; Message: Text; var TempAttachments: Record "Agent Task File"): Record "Agent Task"

// Lifecycle
procedure Deactivate(AgentUserSecurityID: Guid)
procedure IsActive(AgentUserSecurityID: Guid): Boolean

Implementation (Impl codeunit, Access = Internal):

al
local procedure AssignTaskInternal(
    AgentUserSecurityID: Guid;
    TaskTitle: Text[150];
    ExternalId: Text[2048];
    From: Text[250];
    Message: Text;
    var TempAttachments: Record "Agent Task File" temporary): Record "Agent Task"
var
    AgentTaskBuilder: Codeunit "Agent Task Builder";
    AgentTaskMsgBuilder: Codeunit "Agent Task Message Builder";
    ContentStream: InStream;
begin
    AgentTaskMsgBuilder.Initialize(From, Message);

    if TempAttachments.FindSet() then
        repeat
            TempAttachments.Content.CreateInStream(ContentStream);
            AgentTaskMsgBuilder.AddAttachment(
                TempAttachments."File Name",
                TempAttachments."Content Type",
                ContentStream);
        until TempAttachments.Next() = 0;

    AgentTaskBuilder := AgentTaskBuilder
        .Initialize(AgentUserSecurityID, TaskTitle)
        .AddTaskMessage(AgentTaskMsgBuilder);

    if ExternalId <> '' then
        AgentTaskBuilder.SetExternalId(ExternalId);

    exit(AgentTaskBuilder.Create());
end;

Pattern B — Page action (user-initiated)

When: a button on a page sends work to an agent.

Flow: AgentSetup.OpenAgentLookup() → user picks agent → PublicAPI.AssignTask().

al
trigger OnAction()
var
    AgentSetup: Codeunit "Agent Setup";
    MyAgentAPI: Codeunit "My Agent Public API";
    AgentUserSecurityId: Guid;
begin
    if not AgentSetup.OpenAgentLookup(
        Enum::"Agent Metadata Provider"::"My Agent", AgentUserSecurityId) then
        exit;

    MyAgentAPI.AssignTask(
        AgentUserSecurityId,
        CopyStr(StrSubstNo('Process: %1', Rec.Name), 1, 150),
        'LEAD-' + Rec."No.",
        CopyStr(UserId(), 1, 250),
        StrSubstNo('Please process customer %1 (No. %2).', Rec.Name, Rec."No."));
end;

Pattern C — Business event (automated)

When: a business event (posting, releasing, approval) auto-triggers an agent task.

Non-negotiable rules:

  1. Always wrap in [TryFunction] — never block the business event on agent failure.
  2. Always filter by business condition BEFORE creating the task — not inside the TryFunction.
  3. Always log failures via Session.LogMessage with category and GetLastErrorText().
al
[EventSubscriber(ObjectType::Codeunit, Codeunit::"Release Sales Document",
                 OnBeforeReleaseSalesDoc, '', false, false)]
local procedure OnBeforeRelease(var SalesHeader: Record "Sales Header")
begin
    if SalesHeader."Document Type" <> SalesHeader."Document Type"::Order then exit;
    if not MeetsCondition(SalesHeader) then exit;

    if not TryCreateTask(SalesHeader) then
        Session.LogMessage('BCA2A-FAIL',
            StrSubstNo('Task creation failed for %1: %2', SalesHeader."No.", GetLastErrorText()),
            Verbosity::Error, DataClassification::SystemMetadata,
            TelemetryScope::ExtensionPublisher, 'Category', 'BCA2A');
end;

[TryFunction]
local procedure TryCreateTask(var SalesHeader: Record "Sales Header")
var
    PublicAPI: Codeunit "My Agent Public API";
begin
    PublicAPI.AssignTask(
        GetAgentSecurityId(),
        'Validate SO ' + SalesHeader."No.",
        'SO-' + SalesHeader."No.",
        'System',
        BuildMessage(SalesHeader));
end;

Pattern D — Attachment task

When: agent needs to process files (PDFs, images, CSVs, Excel).

Signature: AddAttachment(Name: Text[250]; MediaType: Text; ContentStream: InStream)

al
procedure CreateTaskWithAttachment(AgentUserId: Guid; var DocumentBlob: Codeunit "Temp Blob")
var
    AgentTaskBuilder: Codeunit "Agent Task Builder";
    AgentTaskMsgBuilder: Codeunit "Agent Task Message Builder";
    ContentStream: InStream;
begin
    DocumentBlob.CreateInStream(ContentStream);

    AgentTaskMsgBuilder.Initialize(CopyStr(UserId(), 1, 250), 'Review attached document.');
    AgentTaskMsgBuilder.AddAttachment('Document.pdf', 'application/pdf', ContentStream);

    AgentTaskBuilder := AgentTaskBuilder
        .Initialize(AgentUserId, 'Process Document')
        .SetExternalId('DOC-1001')
        .AddTaskMessage(AgentTaskMsgBuilder);

    AgentTaskBuilder.Create();
end;

Common MIME types: application/pdf, image/png, image/jpeg, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet (Excel xlsx), text/csv.

When you need a canonical end-to-end example combining attachment + business condition + telemetry + lead handoff, load examples/lead-handoff-with-attachment.md.

Pattern E — Multi-turn conversation

When: continue an existing task with follow-up messages.

Flow: GetTaskByExternalId() → build follow-up → workaround needed (see below) → SetStatusToReady().

Status (Runtime 17.0): AgentTaskMessageBuilder.AddToTask() is not available in Extension scope yet. Until it ships, create a new task that references the original ExternalId:

al
procedure SendFollowUpTask(AgentUserId: Guid; OriginalExternalId: Text; AdditionalInfo: Text)
var
    AgentTaskBuilder: Codeunit "Agent Task Builder";
    AgentTaskMsgBuilder: Codeunit "Agent Task Message Builder";
begin
    AgentTaskMsgBuilder.Initialize(CopyStr(UserId(), 1, 250), AdditionalInfo);

    AgentTaskBuilder := AgentTaskBuilder
        .Initialize(AgentUserId, CopyStr('Update for ' + OriginalExternalId, 1, 150))
        .SetExternalId(OriginalExternalId + '-UPD')
        .AddTaskMessage(AgentTaskMsgBuilder);

    AgentTaskBuilder.Create();
end;

When AddToTask becomes available in a future runtime, the canonical pattern will be:

al
// FUTURE — not yet in Extension scope
AgentTaskRecord := AgentTaskCU.GetTaskByExternalId(AgentSecurityId, ExternalId);
AgentTaskMsgBuilder.Initialize('User', FollowUpText);
AgentTaskMsgBuilder.AddToTask(AgentTaskRecord);
if AgentTaskCU.CanSetStatusToReady(AgentTaskRecord) then
    AgentTaskCU.SetStatusToReady(AgentTaskRecord);

Pattern F — Lifecycle management

When: monitor, restart, or stop tasks programmatically.

OperationMethod
Check activeAgent.IsActive(AgentUserSecurityId)
DeactivateAgent.Deactivate(AgentUserSecurityId)
Find by ExternalIdAgentTask.GetTaskByExternalId(AgentUserId, ExternalId)
Resume paused taskif AgentTask.CanSetStatusToReady(Rec) then AgentTask.SetStatusToReady(Rec)
Display name lookupAgent.GetDisplayName(AgentUserSecurityId)

Pattern G — Agent session detection

When: AL code must run only inside an agent session (not in normal user sessions).

al
// Any agent
var
    AgentSession: Codeunit "Agent Session";
    Provider: Enum "Agent Metadata Provider";
begin
    if not AgentSession.IsAgentSession(Provider) then exit;
    // agent-specific logic
end;

// Specific agent
if not AgentSession.IsAgentSession(Enum::"Agent Metadata Provider"::"Lead Qualifier") then exit;

Pattern H — Agent session event binding (performance)

When: event subscribers should be active only during agent tasks, never in normal user sessions.

Architecture: SingleInstance codeunit + BindSubscription on System Initialization.OnAfterInitialization.

al
codeunit 52120 "My Agent Session Events"
{
    Access = Internal;
    SingleInstance = true;

    [EventSubscriber(ObjectType::Codeunit, Codeunit::"System Initialization",
                     OnAfterInitialization, '', false, false)]
    local procedure OnInit()
    var
        AgentSession: Codeunit "Agent Session";
    begin
        if not AgentSession.IsAgentSession(
            Enum::"Agent Metadata Provider"::"My Agent") then exit;

        GlobalEvents.SetAgentTaskID(AgentSession.GetCurrentSessionAgentTaskId());
        if BindSubscription(GlobalEvents) then;
    end;

    var
        GlobalEvents: Codeunit "My Agent Events";
}

Human review without SetRequiresReview

SetRequiresReview is OnPrem-only. To force human review from an Extension, add a Warning annotation in IAgentTaskExecution.AnalyzeAgentTaskMessage:

al
procedure AnalyzeAgentTaskMessage(
    AgentTaskMessage: Record "Agent Task Message";
    var Annotations: Record "Agent Annotation")
var
    AgentMessage: Codeunit "Agent Message";
    MessageText: Text;
begin
    MessageText := AgentMessage.GetText(AgentTaskMessage);

    if MessageText.Contains('DISQUALIFICATION') then begin
        Annotations.Severity := Annotations.Severity::Warning;
        Annotations.Message :=
            'Disqualification requires human approval. Review before proceeding.';
        Annotations.Insert();
    end;
end;

Warning annotations trigger the user-intervention flow via GetAgentTaskUserInterventionSuggestions. Error annotations stop the task.

Agent discovery — current state

Until Custom Agent.GetCustomAgents() becomes available in Extension scope, use Agent Setup.OpenAgentLookup() for user selection and Agent.GetDisplayName(Guid) for display:

al
trigger OnLookup(var Text: Text): Boolean
var
    AgentSetup: Codeunit "Agent Setup";
    SelectedAgentUserId: Guid;
begin
    if AgentSetup.OpenAgentLookup(
        Enum::"Agent Metadata Provider"::"Quote Builder", SelectedAgentUserId) then begin
        Rec."Target Agent Security ID" := SelectedAgentUserId;
        Text := Format(SelectedAgentUserId);
        exit(true);
    end;
    exit(false);
end;

local procedure GetAgentDisplayText(AgentSecurityId: Guid): Text
var
    AgentCU: Codeunit Agent;
begin
    if IsNullGuid(AgentSecurityId) then exit('');
    exit(AgentCU.GetDisplayName(AgentSecurityId) + ' (' + Format(AgentSecurityId) + ')');
end;

Pattern selection guide

SituationPattern(s)
Standard reusable task creationA (Public API)
User clicks button to assign workB → A
Business event triggers agentC → A
Agent processes uploaded filesD + (A, B, or C)
Follow-up on existing taskE
Monitor / restart / stop tasksF
Code runs only in agent contextG
Performance: subscribers only during tasksH
Need to force human review (Extension)Warning annotation in AnalyzeAgentTaskMessage

Non-negotiable rules

  1. Public API is the entry point — all other patterns call through it.
  2. TryFunction for event-driven creation — never block posting, releasing, approval.
  3. Filter before creating — business condition checked outside the TryFunction.
  4. Log failures to telemetry — Session.LogMessage with category and error text.
  5. Mensaje contiene todo el contexto — el agente solo sabe lo que le pasas por el mensaje + attachments.
  6. ExternalId follows {PREFIX}-{No.} — SO-1001, LEAD-001, EMAIL-{threadId}. Never GUIDs or auto-increments.
  7. Use Agent Task Message Builder for attachments — never manipulate the underlying records directly.
  8. Verify availability against the matrix above before designing — don't ship code that relies on OnPrem-only methods.

Examples

Load an example only when you need its concrete template:

  • When implementing an end-to-end attachment + business condition + telemetry + handoff flow, load examples/lead-handoff-with-attachment.md.
  • When wiring Pattern H with a companion Events codeunit, load examples/session-events-binding.md.

Файли в пакеті

Модель читає ці файли за потреби, поки навичку завантажено. Вони доступні для читання й ніколи не виконуються.

Поширені запитання

Що робить навичка ШІ Skill Agent Task Patterns?

Agent SDK task integration patterns for Business Central. Triggers on: Agent Task Builder, Agent Task Message Builder, Public API, AssignTask, ExternalId, agent session detection, BindSubscription, TryFunction agent task, multi-turn agent conversation, agent attachment, task lifecycle management, OnPrem-only methods, AddToTask, SetRequiresReview, SetSkipMessageSanitization, runtime availability.

Навіщо використовувати Skill Agent Task Patterns у TypingMind?

Тому що ви встановлюєте її один раз і використовуєте з будь-якою моделлю. Skill Agent Task Patterns — це звичайний Markdown, а не код для конкретного постачальника, тому та сама навичка працює з GPT-5, Claude, Gemini, Grok або локальною моделлю. Ви можете змінити модель навіть посеред чату, і навичка продовжить працювати. TypingMind використовує ваші власні ключі API, тож ви платите безпосередньо постачальникам замість передплати за кожне місце користувача, а ваші навички й чати залишаються у вашому сховищі.

Як встановити Skill Agent Task Patterns у TypingMind?

Відкрийте в TypingMind Плагіни → Навички → Встановити з GitHub і вставте https://github.com/javiarmesto/ALDC-AL-Development-Collection/tree/main/.claude/skills/skill-agent-task-patterns. TypingMind прочитає файл SKILL.md, додасть супровідні файли та встановить навичку, яку можна вмикати окремо для кожного чату.

Які моделі ШІ можуть використовувати Skill Agent Task Patterns?

Будь-яка модель, яку ви підключите в TypingMind. Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для конкретного постачальника, тому GPT, Claude, Gemini, Grok і локальні моделі можуть завантажувати цю навичку, коли запит їй відповідає.

Зі скількома моделями ШІ можна використовувати Skill Agent Task Patterns?

Зі скількома забажаєте. Якщо модель підтримує навички, ви можете використовувати з нею Skill Agent Task Patterns — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama та інші — усе в TypingMind із власними ключами API.

Чи безкоштовна навичка ШІ Skill Agent Task Patterns?

Так. Навичку опубліковано на GitHub: javiarmesto, за ліцензією MIT. Ви платите лише своєму постачальнику ШІ за використані токени.

Що таке навички ШІ?

Навичка ШІ — це багаторазовий набір інструкцій, який навчає модель ШІ виконувати одне конкретне завдання. Він відповідає відкритому формату Agent Skills: файл SKILL.md із назвою та описом, а також скрипти, шаблони чи довідкові файли, які можуть знадобитися моделі. Модель читає інструкції лише тоді, коли ваш запит відповідає навичці, тому встановлена навичка нічого не коштує, доки її не використано.

Чим навички ШІ відрізняються від плагінів або серверів MCP?

Плагін або сервер MCP надає моделі нові інструменти для виклику — код, який десь виконується й повертає результат. Натомість навичка ШІ надає моделі знання та порядок дій: як підійти до завдання, яких кроків дотримуватися та яким має бути якісний результат. Навички — це звичайний Markdown, тож їм не потрібні ні сервер, ні ключ API, ні середовище виконання, і вони працюють із будь-якою моделлю.

Усі

Створіть власний ШІ-простір уже зараз

Підпишіться на нашу розсилку, щоб дізнаватися про нові функції та майбутні розіграші 👇