Skip to content

agents-library

Shared agent utilities, factories, and base classes

agents-library provides shared utilities, base classes, factories, and producer helpers used across the KĀDI multi‑agent orchestration system. It centralizes common logic for worker agents, shadow (backup) agents, event publishing to the KĀDI broker, tool invocation/orchestration helpers for producers, and typed event/tool schemas so that worker, shadow, and producer components can remain small and consistent.

Data flow and key components

  • Producer / Orchestrator
    • Uses producer utilities (invokeShrimTool, orchestrateWithClaude, publishToolEvent) to orchestrate tool invocations and publish standardized events to the KĀDI broker.
    • Result events flow into the broker (KADI) for workers to consume.
  • KĀDI Broker
    • Central pub/sub event bus where TaskAssigned/TaskCompleted/TaskFailed/TaskRejected and Tool events are delivered.
    • KadiEventPublisher handles publishing with retry/connection logic.
  • Worker Agents (artist/designer/programmer)
    • Built with WorkerAgentFactory / BaseWorkerAgent / createWorkerAgent.
    • Consume tasks from broker, run task handlers, publish task lifecycle events.
  • Shadow Agents
    • Built with ShadowAgentFactory / BaseShadowAgent / createShadowAgent.
    • Monitor filesystem and git (chokidar, git monitoring logic lives in shadow factory) and publish BackupEvent(s) to broker for redundancy.
  • Shared Utilities
    • BaseBot: abstract base with circuit-breaker and retry patterns used by agents.
    • BaseAgent: base lifecycle/provider/memory types and behavior.
    • Logging, timer, path utils, vault/config loaders.
  • Types & Validation
    • Zod schemas and TypeScript types for AgentConfig, KadiEvent, ToolInvocation results, and error classification.

How it fits in the AGENTS ecosystem

  • Provides the primitives and conventions that all agent packages (workers, shadows, producers) import to ensure consistent behavior: lifecycle, retry semantics, event schemas, and tool invocation patterns.
  • Keeps orchestration logic (producer) and execution logic (workers) decoupled via well‑typed KADI events and standardized publish/subscribe utilities.

The package exports classes, factories, utilities, and types. Below is a concise reference for the most important exports (names are exact; use type imports where noted).

ExportTypeDescriptionKey parameters / notes
BaseBotclassAbstract base bot with circuit-breaker and retry logicConstruct with BaseBotConfig (exported type)
BaseAgentclassCore agent lifecycle/provider/memory baseSee BaseAgentConfig, BaseAgentProviderConfig, BaseAgentMemoryConfig
KadiEventPublisherclassEvent publisher to KĀDI broker with connection retryConstruct with PublisherConfig
validateTopicPatternfnValidate KĀDI topic patterns(topic: string) => boolean
logger, setLogLevel, setAgentTag, setLogTransportutilitiesCentralized logging helpers and module constantsMODULE_AGENT, MODULE_SLACK_BOT, MODULE_DISCORD_BOT, MODULE_TASK_HANDLER, MODULE_TOOLS
timer, TimerutilityTimer helper for timeouts and schedulingexports timer() and Timer type
isWsl, toNativePathutilsPath utilities used by shadow/worker agentsAccepts strings
loadVaultCredentials, loadModelManagerCredentialsfnLoad secrets from vaults (VAULT integration helpers)Returns VaultCredentials / ModelManagerCredentials types
loadConfig, registerConfigMapping, readConfig, readConfigFile, Configconfig helpersConfig loading and mapping utilities for config.toml or other sourcesUse to load WorkerAgentConfig / ShadowAgentConfig etc.
loadDirectivefnLoad directives used by agentsExports DirectiveContext and DirectiveExport types
invokeShrimToolfnInvoke shrimp-task-manager tools via KĀDI protocol with retry logicSee InvokeOptions, ShrimpToolResult types
isToolSuccess, isToolFailuretype guardsCheck tool invocation result discriminant union(result: ToolInvocationResult) => boolean
orchestrateWithClaudefnClaude API orchestration with tool invocation (Option C pattern)See OrchestrationOptions, OrchestrationResult
publishToolEventfnStandardized tool event publishing to KADI brokerAccepts EventMetadata and tool invocation results
classifyToolErrorfnClassify errors (transient/permanent) to drive retry logicReturns ErrorClassification
BaseWorkerAgent, WorkerAgentFactory, createWorkerAgentfactories/classesWorker agent base and factory utilities for artist/designer/programmer rolesWorkerAgentConfig / WorkerBehaviors types apply
BaseShadowAgent, ShadowAgentFactory, createShadowAgentfactories/classesShadow agent base and factory utilities with filesystem/git monitoringShadowAgentConfig and ShadowAgentConfigSchema (Zod) exported
Types: AgentRole, WorkerAgentConfig, WorkerAgentFullConfig, ShadowAgentConfig, etc.typesAgent configuration types and event/tool schema typesUse for typed config and event validation

If your code needs to import multiple utilities, prefer named imports. Example import lines are exported from the package root:

export { BaseBot } from './base-bot.js';
export type { BaseBotConfig } from './base-bot.js';
export {
BaseAgent,
type BaseAgentConfig,
type BaseAgentProviderConfig,
type BaseAgentMemoryConfig
} from './base-agent.js';
export { KadiEventPublisher, validateTopicPattern } from './kadi-event-publisher.js';

(These re-exports are part of the package entrypoint and reflect the canonical public API.)

Primary configuration APIs and secrets

  • loadConfig / registerConfigMapping / readConfig / readConfigFile
    • Use loadConfig to load configuration for WorkerAgentConfig, ShadowAgentConfig, or other mapped config shapes. registerConfigMapping lets you register named mappings to simplify loading complex hierarchical configs.
  • Vault & credentials
    • loadVaultCredentials, loadModelManagerCredentials - helpers to load secrets from your vault integration. The package exports VaultCredentials and ModelManagerCredentials types.
  • Environment variables
    • dotenv is included as a dependency — projects using this package typically call dotenv.config() early in startup. The library doesn’t implicitly mutate process.env; application code should load environment variables before calling loadConfig or vault loaders.
  • config.toml and config shape
    • The library expects config objects that conform to the exported types: WorkerAgentConfig, WorkerAgentFullConfig, ShadowAgentConfig, PathConfig, NetworkConfig, etc. Concrete field names are defined in types files (eg. types/agent-config.ts) and validated using Zod schemas (ShadowAgentConfigSchema is exported).
    • Use readConfig/readConfigFile or loadConfig to parse the config source and obtain typed config.
  • Secrets and vault usage
    • Call loadVaultCredentials() to retrieve VaultCredentials used by agents and producers (for example, to authenticate with model managers or broker credentials).
    • loadModelManagerCredentials() helps fetch credentials required for Claude/Anthropic or other model providers.
  • Publisher configuration
    • PublisherConfig type is exported by kadi-event-publisher.js — pass an object of that shape when constructing KadiEventPublisher.

Example pattern for loading config and creating an agent (illustrative):

import { loadConfig, createWorkerAgent, WorkerAgentConfig } from 'agents-library';
async function start() {
// loadConfig will validate the config against your mapped schema
const config = await loadConfig<WorkerAgentConfig>({ /* options: path, mapping, etc. */ });
const agent = createWorkerAgent(config);
await agent.start();
}

(Refer to the WorkerAgentConfig / ShadowAgentConfig TypeScript definitions in the package source to see exact fields and validation constraints.)

Below are representative code snippets showing canonical import and usage patterns. These snippets are intentionally small; consult the implementation files for full lifecycle methods.

  • Re-exports from the package entrypoint (actual code from src/index.ts):
export { BaseBot } from './base-bot.js';
export type { BaseBotConfig } from './base-bot.js';
export {
BaseAgent,
type BaseAgentConfig,
type BaseAgentProviderConfig,
type BaseAgentMemoryConfig
} from './base-agent.js';
export { KadiEventPublisher, validateTopicPattern } from './kadi-event-publisher.js';
export type { PublisherConfig } from './kadi-event-publisher.js';
export { logger, setLogLevel, setAgentTag, setLogTransport, MODULE_AGENT, MODULE_SLACK_BOT, MODULE_DISCORD_BOT, MODULE_TASK_HANDLER, MODULE_TOOLS } from './utils/logger.js';
export { timer, type Timer } from './utils/timer.js';
export { isWsl, toNativePath } from './utils/path-utils.js';
export { loadVaultCredentials, loadModelManagerCredentials, type VaultCredentials, type ModelManagerCredentials } from './utils/vault.js';
export { loadConfig, registerConfigMapping, type LoadConfigResult } from './utils/config.js';
export { loadDirective, type DirectiveContext, type DirectiveExport } from './utils/directive.js';
export { Config, readConfig, readConfigFile } from './utils/read-config.js';
export {
invokeShrimTool,
isToolSuccess,
isToolFailure,
orchestrateWithClaude,
publishToolEvent,
type InvokeOptions,
type ShrimpToolResult,
type ToolDefinition,
type ToolInvocation,
type OrchestrationOptions,
type OrchestrationResult,
type EventMetadata
} from './producer-tool-utils.js';
  • Typical producer invocation flow (patternic example):
import { invokeShrimTool, publishToolEvent } from 'agents-library';
async function runToolAndPublish(toolDef, params, publisher, metadata) {
const result = await invokeShrimTool({
tool: toolDef,
params,
// optional retry/timeout options are passed via InvokeOptions
});
// Type guards
if (isToolSuccess(result)) {
await publishToolEvent(publisher, {
...metadata,
result
});
} else {
// handle failure classification / retry decisions
const classification = classifyToolError(result.error);
// use classification to decide whether to retry or mark permanent failure
}
}
  • Worker creation (conventional pattern):
import { createWorkerAgent, loadConfig } from 'agents-library';
async function main() {
const cfg = await loadConfig({ /* mapping for WorkerAgentConfig */ });
const agent = createWorkerAgent(cfg);
await agent.start();
}

Note: Exact function/option shapes (InvokeOptions, WorkerAgentConfig, PublisherConfig, etc.) are exported as types from the package; consult their declarations in the source for full signatures and validation rules.

Runtime dependencies (from package.json)

  • @anthropic-ai/sdk ^0.32.1 — used by orchestrateWithClaude or other Claude/Anthropic integrations.
  • chokidar ^3.6.0 — filesystem watcher used by ShadowAgentFactory / BaseShadowAgent.
  • dotenv ^16.3.1 — typical environment variable loading in host applications (not automatically loaded by the library).
  • zod ^3.22.4 — runtime validation for configs and schemas (ShadowAgentConfigSchema etc).

Dev dependencies

  • typescript, vitest, vitest/coverage-v8, vitest/ui — for development and tests.

Internal dependency graph (high level)

  • worker-agent-factory imports BaseAgent, BaseBot, KadiEventPublisher, utils/logger, and producer-tool-utils when workers need to invoke tools or publish events.
  • shadow-agent-factory relies on chokidar and path-utils, plus KadiEventPublisher to emit BackupEvent(s).
  • producer-tool-utils depends on the model manager credentials helpers and the tool invocation schemas/types.
  • kadi-event-publisher is used by both workers and shadows to publish standard KADI events.

Who depends on agents-library

  • agent-producer packages (producers/orchestrators) — for tool orchestration, invoking tools and publishing events.
  • worker agent implementations (artist, designer, programmer) — for consistent lifecycle, event handling, and task processing contracts.
  • shadow agent implementations — for backup/monitoring behavior and publishing backup events.
  • When modifying exported types (AgentRole, WorkerAgentConfig, ShadowAgentConfig), ensure corresponding Zod schemas (where present) are updated to keep runtime validation in sync.
  • Changes to producer-tool-utils such as invokeShrimTool or orchestrateWithClaude affect retry and classification semantics — keep error classification and isToolSuccess/isToolFailure guards stable for downstream consumers.
  • Keep KadiEvent topics validated via validateTopicPattern to prevent silent mis-publishing.
  • Add new public API exports to src/index.ts so downstream packages can import them from the package root.

If you need more detailed field-level docs (e.g., every property of WorkerAgentConfig or ShadowAgentConfig), point me at the specific source file (types/agent-config.ts or shadow-agent-factory.ts) and I will extract the exact fields and Zod schema details into this page.