Skip to content

Dependency Injection, Custom Implementations & Overrides

AGBoss includes a deterministic dependency injection container modeled on Angular and NestJS. Every component (@Injectable, @Tool, @ToolInterceptor, @Action, @Router, @Arbiter, @Judge, @Compaction, @InputGuardrail, @OutputGuardrail, @PiiPolicy, @ModelProvider, @Channel, @ReplyInterpreter, @Rag, @Budget, @HealthCheck) declares its constructor dependencies in deps: [...], and the container resolves them at application startup.

Because AGBoss resolves infrastructure contracts by class inheritance or typed handler interfaces rather than hardcoding vendor SDKs, you can plug in your own custom @Rag vector databases, custom @ModelProvider gateways (OpenRouter, vLLM, Ollama, LiteLLM, or custom SDK transports via ModelProviderHandler), custom @Compaction knowledge-graph handlers (CompactionStrategy.Custom), custom @Channel transports, and custom Postgres/Redis stores — and swap any dependency in tests with override(Base, Fake).


Complete example: DI, custom @Rag, custom @ModelProvider & override() test

Section titled “Complete example: DI, custom @Rag, custom @ModelProvider & override() test”

How custom implementations & overrides work for every contract

Section titled “How custom implementations & overrides work for every contract”

AGBoss never locks you into built-in adapters. Every external integration is defined as an abstract base class or TypeScript interface that you can implement in production and override in tests:

Contract Type How to Implement Your Own in Production How to Register It How to Override / Test It
Knowledge Base (@Rag) Decorate with @Rag({ name, description, topK, deps }) and either implements RagConnector (retrieve(query, { topK, signal }) for Pinecone, Qdrant, pgvector, Elasticsearch) or extends SqliteFtsConnector (built-in BM25). Referenced in @Agent({ rag: [{ use: MyRag, mode: RagMode.Tool | RagMode.Context }] }); its deps go in @Workflow({ providers }). testRag(MyRag, { overrides: [override(VectorClient, FakeVectorClient)] }) or mockRag(MyRag) in testWith(App).
Model Gateway (@ModelProvider) Decorate with @ModelProvider({ name: "...-model-provider", serves, cost, reasoning, promptCaching, retryPolicy, rateLimitPolicy, circuitBreakerPolicy }) and extend OpenRouterProvider, OpenAiCompatibleProvider (vLLM, Ollama, LiteLLM, Azure), or implements ModelProviderHandler (complete(request) with deps: [...] for AWS Bedrock / Vertex AI / mTLS gateways). Listed in @Application({ providers: [MyModelProvider, DecisionsModelProvider] }). testWith(App) automatically intercepts model calls above the transport so unit tests never hit live endpoints.
Custom Compaction (@Compaction) Decorate with @Compaction({ name: "...-compaction", strategy: CompactionStrategy.Custom, turnsBetweenCompactions, deps }) and implement CompactionHandler (compact(input)). Bound on @Application, @Workflow, @Agent, or @Router via compaction: MyCompaction. testCompaction(MyCompaction, { overrides }) or mockOf(Service) in testWith(App).
Tool Interceptor (@ToolInterceptor) Decorate with @ToolInterceptor({ name: "...-tool-interceptor", description, deps }) and implement BeforeToolCall and/or AfterToolCall. Bound via toolInterceptors: [MyToolInterceptor] on @Application, @Workflow, @Agent, @Tool, or @McpTool. testToolInterceptor(MyToolInterceptor, { overrides }).
Approval Channel (@Channel) Declare @ChannelRole({ approves, answerer, replyInterpreter }) export abstract class MyRole extends ChannelOf<MyRole> {}, then implement @Channel({ name, deps }) export class SlackChannel extends MyRole (send() and optional onPauseClosed()). Listed in @Application({ providers: [SlackChannel] }) (matched to MyRole by class inheritance). In testWith(App), pass overrides: [override(MyRole, AutoApproveChannel)] or override SlackService via override(SlackService, FakeSlackService).
7 Durable Stores (Persistence) Subclass any of the 7 contracts (extends BaseCheckpointSaver, PausedExecutionRepository, ExecutionRecordRepository, CostLedgerRepository, ExecutionLeaseRepository, ExecutionTreeRepository, RateLimitRepository) or subclass a Sqlite* class (extends SqliteExecutionLeaseRepository). Listed in @Application({ providers: [PostgresLeaseRepository, ...] }). Default InMemory* stores run automatically when omitted; or pass overrides: [override(ExecutionLeaseRepository, FaultyLeaseRepo)] in testWith.
Domain Services (@Injectable) Decorate with @Injectable({ deps: [...] }) (and optional OnInit, OnStart, OnStop, OnDestroy hooks). Listed in @Workflow({ providers: [MyService] }) (or @Application({ providers }) when shared by app-level guards/observers). override(MyService, FakeMyService) or mockOf(MyService, { method: vi.fn() }) in testWith and all 10 unit runners.
Value Tokens (InjectionToken<T>) Create const CONFIG = new InjectionToken<MyConfig>("CONFIG") and bind with provide(CONFIG, { ... }). (Note: passing a class to provide(Class, instance) is rejected by [di.instance-provider]). Listed in @Workflow({ providers: [provide(CONFIG, value)] }). Pass provide(CONFIG, testValue) in overrides.

Instead of calling Date.now(), process.env, or global singletons, AGBoss components inject framework contracts through deps:

  • Clock (deps: [Clock]): Every timestamp and sleep (this.clock.now(), await this.clock.sleep(seconds(30))) goes through the application’s Clock. Under testWith, the container provides a VirtualClock that advances instantly with await clock.advance(seconds(30)).
  • ApplicationContext (deps: [ApplicationContext]): Provides this.applicationContext.environment (typed by your AppEnvironment contract), environmentName, and instanceId. Components always inject ApplicationContext rather than AppEnvironment directly.
  • ExecutionContext (deps: [ExecutionContext]): Provides read-only access to the current step’s frame (executionId, rootExecutionId, parentExecutionId, depth, threadId, ownerId, tenant.tenantId, signal, and step.idempotencyKey), isolated via AsyncLocalStorage across concurrent runs and parallel branches.
  • TenantContext (deps: [MyTenantContext]): Subclass TenantContext to pass typed per-request tenant metadata (plan, region, dailyBudgetUsd) into tools, actions, and budgets.

Every component the container creates can implement any combination of OnInit, OnStart, OnStop, and OnDestroy:

Hook When It Runs Typical Use Case
onInit() After the component’s own deps have been created and completed their onInit Opening database pools, preparing statements, warming caches (failing onInit aborts startup and runs onDestroy on already-initialized dependencies)
onStart() After every component in the application has completed onInit, before execute Starting background listeners, readiness checks, or startup audit logs
onStop() When app.close() or SIGTERM arrives (new executions refused with ApplicationStoppingError, active ones draining up to shutdownTimeout) Stopping intake queues and flushing pending operations
onDestroy() After all running executions have finished, paused, or released their 30s leases to another instance Closing database pools, sockets, and telemetry exporters