Logo : Ai Agent Runtime Architecture

Ai Agent Runtime Architecture

Communauté
peterbamuhigire
ai-agent-runtime-architecture

Use when designing multi-tenant agent runtimes, control loops, state machines, retries, idempotency, step caps, durable resumability, scheduling, cancellation, and workflow boundaries.

Add to TypingMind

Présentation

Éditeurpeterbamuhigire
Dépôtchwezi-dev-engine
Nom de la compétenceai-agent-runtime-architecture
Étoiles
29
Forks
6
Fichiers inclus
9
LicenceMIT
Liens
  • Instructions en Markdown

    Un fichier SKILL.md que le modèle charge à la demande : il ne consomme donc des tokens que lorsqu’une demande correspond réellement à la compétence.

  • Compatible avec tous les LLM

    Les compétences IA sont rédigées en Markdown et non sous forme de code propre à un fournisseur. Elles fonctionnent donc avec GPT, Claude, Gemini, Grok ou un modèle local.

  • Fichiers inclus : 9

    Des scripts, des gabarits et des références que le modèle peut consulter pendant son travail. Les fichiers sont en lecture seule et ne sont jamais exécutés.

  • Open source

    Publiée par peterbamuhigire sur GitHub. Consultez les sources avant de l’installer.

Installation

Installez la compétence IA Ai Agent Runtime Architecture dans TypingMind pour l’utiliser avec n’importe quel LLM, ou ajoutez-la à un autre agent capable de lire SKILL.md.

1

Installer dans TypingMind

TypingMind installe une compétence directement depuis son dossier GitHub : l’application lit SKILL.md, regroupe les fichiers de ressources et enregistre le tout localement.

  1. Ouvrez l’application et accédez à Plugins → Compétences.
  2. Choisissez « Installer depuis GitHub ».
  3. Copiez l’URL ci-dessous, qui pointe vers le dossier de la compétence, puis collez-la et confirmez.
    https://github.com/peterbamuhigire/chwezi-dev-engine/tree/main/skills/ai/ai-agent-runtime-architecture
  4. Activez la compétence dans chaque discussion où vous souhaitez pouvoir l’utiliser.
Plugins → Compétences → Ajouter une compétence → Via une URL GitHub, puis collez l’URL du dossier et appuyez sur Continuer.
2

Installer dans un autre agent

Tout agent capable de lire le format Agent Skills peut utiliser cette compétence : copiez le dossier dans le répertoire des compétences de cet agent.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/peterbamuhigire/chwezi-dev-engine.git /tmp/chwezi-dev-engine
mkdir -p .claude/skills
cp -r /tmp/chwezi-dev-engine/skills/ai/ai-agent-runtime-architecture .claude/skills/ai-agent-runtime-architecture
Redémarrez Claude Code après la copie pour que la nouvelle compétence soit prise en compte.

Utilisez cette compétence dans TypingMind

Activez Ai Agent Runtime Architecture dans n’importe quelle discussion TypingMind et le modèle s’occupe du reste. Le nom et la description de la compétence figurent dans le prompt système. Dès qu’une demande correspond, le modèle charge lui-même l’intégralité des instructions : vous n’avez jamais à l’invoquer manuellement, et elle ne consomme aucun token tant qu’elle n’est pas utilisée.

Le modèle charge automatiquement Ai Agent Runtime Architecture dès qu’une demande correspond à cette compétence.

Compatible avec tous les modèles IA

Les compétences IA sont de simples instructions Markdown, et non du code propre à un fournisseur. Ainsi, la compétence Ai Agent Runtime Architecture n’est pas liée au modèle pour lequel elle a été conçue. Installez-la une seule fois dans TypingMind et utilisez-la avec GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama ou un modèle local que vous exécutez vous-même, le tout avec vos propres clés API.

  • Chargée uniquement en cas de besoin

    Le prompt système ne contient que le nom et la description. Les instructions sont récupérées à la première demande correspondante : une compétence inutilisée ne coûte donc rien.

  • Changez de modèle en cours de discussion

    La compétence étant constituée d’instructions et non de code, elle reste fonctionnelle lorsque vous changez de modèle : le nouveau modèle lit le même fichier SKILL.md.

Instructions de la compétence

Voici le contenu de SKILL.md que le modèle charge. Lisez-le avant l’installation : une compétence contient des instructions que votre modèle suivra.

AI Agent Runtime Architecture

Operating contract

Inputs

ArtefactRequired?Purpose
Task state model, tools, durability, timeout, retry, cancellation, tenant, memory, and budget boundariesyesDefine safe runtime transitions

Outputs

  • Produce the runtime state machine, persistence contract, failure matrix, operational controls, and test evidence.

Capability and permission boundaries

Read/search are required. Runtime implementation, queue changes, migrations, replay, and cancellation tests require explicit authority and isolated fixtures.

Degraded mode

Fallback without a runnable environment: produce the state machine and unverified test plan; do not claim runtime enforcement.

Decision rules

WorkloadRuntime choiceFailure avoided
Short, deterministic, read-only requestBounded synchronous flowUnnecessary orchestration
Long, retryable, or externally waitingDurable state machineLost or duplicated work
Irreversible or costly stepApproval and checkpointUnbounded blast radius

Anti-Patterns

  • Running side effects in an HTTP request. Fix: use a durable worker.
  • Retrying without idempotency. Fix: derive stable keys from task and step state.
  • Keeping state only in prompts. Fix: persist every transition before the next step.
  • Ignoring cancellation during tool calls. Fix: propagate and test cancellation.
  • Sharing memory or run state across tenants. Fix: enforce tenant-scoped storage and queries. Acknowledgement: Shared by Peter Bamuhigire, techguypeter.com, +256 784 464178.

Use When

  • Standing up an agent runtime as a control-plane service, not as a function inside a web request.
  • Deciding whether the work is an agent (LLM plans), a deterministic workflow (no LLM in the loop), or a cron (scheduled).
  • Designing the state machine so a crashed worker can resume a 30-minute task without re-charging the customer.
  • Adding step caps, wallclock caps, and idempotency so a runaway agent cannot spend USD 40k of provider budget overnight.
  • Wiring agent task lifecycle events (agent.task.started, agent.step.completed, agent.task.paused, agent.task.killed, agent.task.completed) for observability and back-office.

Do Not Use When

  • The task is the fundamentals of the ReAct loop / tool contract — ai-agents-tools.
  • The task is the multi-agent coordination pattern — ai-agent-multi-agent-coordination.
  • The task is long-running (hours-to-days) durability and progress UX — ai-agent-async-and-long-running-tasks builds on this skill.
  • The task is the overall AI architecture — ai-on-saas-architecture.

Required Inputs

  • The AI on SaaS architecture decision (ai-on-saas-architecture) — gateway, audit log, prompt registry.
  • The agent feature catalogue (which features are agentic, which are single-shot).
  • The plan / tier catalogue with agent entitlements (saas-entitlements-and-plan-gating).
  • Tenant-aware queue / worker infrastructure (distributed-systems-patterns, reliability-engineering).
  • The eval and red-team posture (ai-agent-eval, ai-agent-safety-and-red-team).

Workflow

  1. Read this SKILL.md.
  2. Apply the agent vs workflow vs cron decision (§1). Reject "agent" as the default. Many agentic features are actually workflows with an LLM step.
  3. Design the agent loop state machine (§2) with explicit states and idempotent transitions.
  4. Pick the execution substrate (§3) — inline / queue worker / durable execution engine — based on max wallclock and resumability requirements.
  5. Wire step / token / wallclock / cost budgets (§4) into the loop (delegates to ai-agent-cost-and-step-budgets for full enforcement).
  6. Make every step idempotent and resumable (§5).
  7. Emit task lifecycle events (§6) for observability, back-office, and customer-facing UI.
  8. Apply anti-patterns (§7).

Quality Standards

  • The agent runtime is a separate deployment from request-serving web/API workers. Crash-isolated.
  • Every task has a task_id, tenant_id, feature, model_pin, prompt_version, tool_set_version, step_budget, wallclock_budget, cost_budget, created_at, state.
  • Every step writes a row to agent_steps with step_index, state_before, action, observation, tokens, usd_cost, latency_ms before the next step runs.
  • A worker crash mid-step does not re-execute irreversible actions on restart — idempotency keys are mandatory on side-effects.
  • A task that exceeds any budget is terminated cleanly, emits agent.task.budget_exceeded, and surfaces in the agent inbox.
  • Every task has a per-tenant kill-switch the back-office can flip in < 5 seconds (ai-agent-safety-and-red-team, saas-admin-backoffice-tooling).
  • An agent task is never started inside an HTTP request handler with max_execution_time > 30s. Always queued.

Anti-Patterns

  • "Agent" implemented as a while (not_done) { call_llm(); execute_tool(); } inside a Flask/Express request handler. First failure leaves orphan side-effects.
  • No state machine. Worker restart re-plans from scratch and re-sends the email it already sent.
  • No idempotency keys on tools. Retried send_email sends twice.
  • No max-step cap (maxSteps not enforced or set to 100). One bad prompt drains USD-thousands.
  • Step / token / wallclock budgets only logged, not enforced. Logging is not a control.
  • Agent loop and tool execution in the same process as the web app. A runaway agent OOMs the API.
  • No feature or prompt_version recorded on the task row. Replay impossible.

Outputs

  • Agent vs workflow vs cron decision table for every candidate feature.
  • agent_tasks and agent_steps table schemas.
  • State-machine diagram + transitions.
  • Execution substrate decision (inline / queue / Temporal-class) with rationale.
  • Budget enforcement integration points.
  • Task lifecycle event taxonomy.

Evidence Produced

CategoryArtifactFormatExample
CorrectnessAgent runtime service specMarkdown + diagramdocs/ai/agent-runtime.md
CorrectnessState-machine transition test suiteCI reporttests/ai/agent_state_machine_test.py
Release evidenceResumability drill reportMarkdowndocs/runbooks/agent-resumability-drill.md
OperabilityTask lifecycle event taxonomyYAMLops/events/agent-task-events.yaml

References

  • references/agent-loop-state-machine.md — formal state machine, transitions, idempotency contract.
  • references/agent-vs-workflow-vs-cron-decision.md — decision matrix with worked examples.
  • references/agentic-ai-operating-model-source-synthesis.md - autonomy ladder, production spine, tool contracts, memory/RAG discipline, multi-agent roles, deployment stages, and human-agent operating model distilled from supplied agentic AI source material.
  • Companion: ai-agents-tools, ai-agent-tool-catalogue-and-action-gating, ai-agent-cost-and-step-budgets, ai-agent-observability-and-replay, ai-agent-async-and-long-running-tasks, ai-on-saas-architecture, distributed-systems-patterns, reliability-engineering.

§1 Agent vs Workflow vs Cron — The First Decision

Most "we need an agent" requests are workflows in disguise. An agent is only the right tool when:

  • The steps cannot be enumerated in advance.
  • Branching depends on intermediate observations only the LLM can interpret.
  • Tool choice itself depends on the observation, not the input.

If steps are fixed, prefer a workflow — same LLM calls, deterministic order, vastly cheaper to test, debug, and operate. See references/agent-vs-workflow-vs-cron-decision.md.

2. The agent loop state machine

text
QUEUED -> PLANNING -> ACTING -> OBSERVING -> COMPLETED
                    |             |
                    |             +-> PLANNING (continue or revise)
                    +-> AWAITING_APPROVAL -> ACTING or terminal rejection

Any active state may transition to FAILED, BUDGET_EXCEEDED, KILLED, or ABANDONED.

Terminal states: COMPLETED, FAILED, BUDGET_EXCEEDED, KILLED, ABANDONED.

All state transitions write to agent_steps before the next state is entered. A worker crash between two steps re-enters the loop in the last persisted state. See references/agent-loop-state-machine.md.

§3 Execution Substrate

Wallclock capResumability requirementSubstrate
< 30sBest-effortInline in HTTP request (only for read-only agents)
< 5 minAt-least-onceQueue worker (BullMQ, Celery, RQ, Sidekiq)
< 1 hourExactly-onceDurable workflow engine (Temporal, Inngest, Restate)
Hours / daysExactly-once + resume on deployDurable workflow engine, mandatory

For anything writing to customer state, never run inline in the HTTP handler. The customer's request times out and the agent keeps spending.

§4 Budgets Wired Into the Loop

Before entering PLANNING and ACTING, the loop checks four budgets:

BudgetCheck pointAction on exceed
step_budget (max iterations)Before each PLANNINGTransition to BUDGET_EXCEEDED, emit event, summarise progress
wallclock_budget_secondsBefore each state transitionSame
cost_budget_usdAfter each LLM callSame
tool_cost_budget_usdBefore each ACTINGSame

Budgets come from ai-agent-cost-and-step-budgets. The runtime is the enforcement point.

§5 Idempotency and Resumability

Every side-effecting tool call carries an idempotency key derived from (task_id, step_index, tool_name, arg_hash). If a worker crashes after the side-effect but before persistence, the next worker's tool call short-circuits to the recorded result.

python
def execute_tool_with_idempotency(task_id, step_idx, tool_name, args):
    idem_key = sha256(f"{task_id}:{step_idx}:{tool_name}:{stable_json(args)}")
    cached = idempotency_store.get(idem_key)
    if cached:
        return cached  # tool already ran; replay the recorded observation
    result = tools[tool_name].run(args, idempotency_key=idem_key)
    idempotency_store.put(idem_key, result, ttl_days=30)
    return result

Tools that cannot accept an idempotency key (legacy APIs) must be wrapped in an outbox pattern with a deduplication table. See distributed-systems-patterns.

§6 Task Lifecycle Events

EventWhenUsed by
agent.task.createdEnqueueAudit log, observability
agent.task.startedWorker claimsObservability, agent inbox UI
agent.step.completedAfter OBSERVINGTrace, replay
agent.task.awaiting_approvalHITL transitionApproval UI, mobile push
agent.task.approved / agent.task.rejectedHITL outcomeAudit, resume
agent.task.budget_exceededBudget hitCost ops, support
agent.task.killedManual killBack-office, audit
agent.task.completedSuccessCustomer notification, eval
agent.task.failedUnrecoverable errorSupport, eval

§7 Anti-Pattern Reminders

  • Implementing the loop inline in the API handler.
  • Treating step-budget as a comment.
  • Tool-call idempotency keys derived from random.uuid().
  • Logging the plan but not persisting it — replay is impossible.
  • The agent loop process is the same process as the web app — runaway OOM crashes API.

§8 Compliance-Evidence Emissions (Enhancement)

Every state-machine transition emits a compliance event onto the hash-chained action audit log (ai-agent-audit-log-integrity). The runtime is the canonical source of compliance evidence for ai-agent-soc2-controls CC7.2 (monitoring), PI1.1 (processing integrity), and ai-agent-iso27001-controls A.8.15 (logging, ISO/IEC 27001:2022).

Minimum event taxonomy emitted by the loop:

Transitionevent_classRequired fields
Task acceptedtask_acceptedtask_id, tenant_id, agent_id, intent_summary, policy_version
Plan committedplan_committedtask_id, plan_hash, step_count
Tool call startedtool_call_startedtask_id, step_index, tool_name, tool_version, reversibility, data_class
Tool call endedtool_call_endedtask_id, step_index, outcome, idempotency_key, latency_ms
Approval requiredapproval_requiredtask_id, step_index, tool_name, approver_role
Approval receivedapproval_receivedtask_id, step_index, approval_id, approver_id
Kill-switch flippedkill_switch_flippedscope, actor, reason, drill_run_id (nullable)
Budget breachedbudget_breachedtask_id, budget_kind, threshold, observed
Memory writememory_writetask_id, tier, retention_class, subject_id (hashed)
Erasure steperasure_steprequest_id, step, status
Task closedtask_closedtask_id, terminal_state, verdict_ref

Every event carries policy_version so historical authority checks resolve correctly (see ai-agent-compliance-controls/references/ai-agent-approval-audit-completeness). Emissions are synchronous on the critical path for irreversible-action transitions and kill_switch_flipped; everything else may be batched with at-most-1s drain.

Cross-links: ai-agent-audit-log-integrity, ai-agent-soc2-controls, ai-agent-evidence-automation, ai-agent-compliance-controls/references/ai-agent-approval-audit-completeness.

Consolidated Child References

  • Load references/routing.md to map retired AI child skill slugs to their reference modules.
  • Load ../../sdlc-meta/references/book-driven-system-decision-and-agent-orchestration.md for autonomy, side-effect, escalation, rollback, and currentness controls.

Fichiers inclus

Le modèle lit ces fichiers à la demande lorsque la compétence est chargée. Ils sont accessibles en lecture et ne sont jamais exécutés.

Foire aux questions

À quoi sert la compétence IA Ai Agent Runtime Architecture ?

Use when designing multi-tenant agent runtimes, control loops, state machines, retries, idempotency, step caps, durable resumability, scheduling, cancellation, and workflow boundaries.

Pourquoi utiliser Ai Agent Runtime Architecture sur TypingMind ?

Parce que vous l’installez une seule fois pour l’utiliser avec n’importe quel modèle. Ai Agent Runtime Architecture se compose de simples instructions en Markdown plutôt que de code propre à un fournisseur. La même compétence fonctionne donc avec GPT-5, Claude, Gemini, Grok ou un modèle local, et vous pouvez changer de modèle en cours de discussion sans perturber son fonctionnement. TypingMind utilise vos propres clés API : vous payez donc directement les fournisseurs plutôt qu’un abonnement par siège, et vos compétences et discussions restent dans votre propre espace de stockage.

Comment installer Ai Agent Runtime Architecture dans TypingMind ?

Dans TypingMind, ouvrez Plugins → Compétences → Installer depuis GitHub et collez https://github.com/peterbamuhigire/chwezi-dev-engine/tree/main/skills/ai/ai-agent-runtime-architecture. TypingMind lit le fichier SKILL.md, regroupe les fichiers associés et installe le tout sous forme de compétence que vous pouvez activer pour chaque discussion.

Quels modèles d’IA peuvent utiliser Ai Agent Runtime Architecture ?

N’importe quel modèle que vous connectez dans TypingMind. Les compétences IA sont de simples instructions en Markdown, et non du code propre à un fournisseur. GPT, Claude, Gemini, Grok et les modèles locaux peuvent donc tous charger cette compétence lorsqu’une demande lui correspond.

Combien de modèles d’IA puis-je utiliser avec Ai Agent Runtime Architecture ?

Autant que vous le souhaitez. Vous pouvez utiliser Ai Agent Runtime Architecture avec tout modèle qui prend en charge les compétences : GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama et bien d’autres, le tout dans TypingMind avec vos propres clés API.

La compétence IA Ai Agent Runtime Architecture est-elle gratuite ?

Oui. Cette compétence est publiée sur GitHub par peterbamuhigire sous licence MIT. Vous ne payez que votre propre fournisseur d’IA pour les tokens utilisés.

Que sont les compétences IA ?

Une compétence IA est un ensemble d’instructions réutilisables qui apprend à un modèle d’IA à accomplir une tâche précise. Elle suit le format ouvert Agent Skills : un fichier SKILL.md contenant un nom et une description, ainsi que les éventuels scripts, gabarits ou fichiers de référence dont le modèle peut avoir besoin. Le modèle ne lit les instructions que lorsque votre demande correspond à la compétence. Une compétence installée ne coûte donc rien tant qu’elle n’est pas utilisée.

En quoi les compétences IA diffèrent-elles des plugins ou des serveurs MCP ?

Un plugin ou un serveur MCP fournit au modèle de nouveaux outils à appeler : du code qui s’exécute quelque part et renvoie un résultat. Une compétence IA lui apporte plutôt des connaissances et une méthode : comment aborder une tâche, quelles étapes suivre et à quoi ressemble un bon résultat. Les compétences sont de simples instructions en Markdown. Elles ne nécessitent donc ni serveur, ni clé API, ni environnement d’exécution, et fonctionnent avec n’importe quel modèle.

Tout voir

Créez votre propre espace de travail IA dès maintenant

Abonnez-vous à notre newsletter pour être informé des nouvelles fonctionnalités et des prochains cadeaux à gagner 👇