agents_core 0.3.3
agents_core: ^0.3.3 copied to clipboard
A Dart library for orchestrating multi-agent AI workflows with LM Studio integration. Create agents, manage conversations, execute Python in Docker, and coordinate multi-step pipelines.
Changelog #
0.3.3 — 2026-03-27 #
Features #
Smart Loop Detection
- New
LoopDetectionConfig— immutable configuration class controlling loop detection thresholds:maxConsecutiveIdenticalToolCalls(default 3),maxConsecutiveIdenticalOutputs(default 3), andsimilarityThreshold(default 0.85). Supportsconstconstruction, value equality, andtoString(). - New
LoopDetector— stateful detector that tracks consecutive identical tool-call sequences (via sorted fingerprints) and near-identical text outputs (via bigram Sørensen–Dice similarity). CallrecordToolCalls()/recordOutput()per iteration, thencheck()to get aLoopCheckResult. Includesreset()for reuse across tasks. - New
LoopCheckResult— result type withisLoopingflag and human-readablereason. Provides a staticLoopCheckResult.okconstant for the non-looping case. LoopDetector.bigramSimilarity()— static utility that computes the Sørensen–Dice coefficient over character bigrams for fuzzy string comparison.
ReActAgent Integration
ReActAgentnow accepts an optionalloopDetectionConfigparameter. When provided, aLoopDetectoris created perrun()invocation and checks for repetitive tool-call sequences or near-identical outputs after each iteration. Detected loops stop the agent withstoppedReason: "loop_detected".
AgentLoop Integration
AgentLoopnow accepts an optionalloopDetectionConfigparameter. When provided, producer outputs are tracked each iteration and the loop stops early withstoppedReason: "loop_detected"if repetitive patterns are found.AgentLoopResultgains astoppedReasonfield ("accepted","max_iterations", or"loop_detected") and two new convenience getters:loopDetectedand an updatedreachedMaxIterationsthat excludes loop-detection stops.
0.3.2 — 2026-03-27 #
Examples #
- New
bugfix_pipeline.dart— realistic 5-step end-to-end bugfix workflow demonstratingReActAgentwith file-context tools,AgentLoopStep.dynamicproduce-review loops,AgentStep.dynamicwith conditional execution, custombuildProducerPromptfor reviewer-feedback injection, andStepResultpattern matching for post-run inspection. Seven specialised agents collaborate across triage → root-cause analysis → fix → regression tests → PR summary, all orchestrated by a singleOrchestrator.run()call.
0.3.1 — 2026-03-26 #
Bug Fixes #
LM Studio Client
- Fixed HTTP request body encoding in
LmStudioHttpClient— replacedrequest.write()withrequest.add(utf8.encode(...))in bothpostStreamand the internal_sendRequesthelper. The previous implementation could corrupt non-ASCII characters (e.g. Unicode prompts) becausewrite()uses the platform default encoding, which is not guaranteed to be UTF-8.
0.3.0 — 2026-03-26 #
Previously, orchestrator pipelines only supported single-agent steps, forcing
produce-review loops to be managed outside the pipeline. This release introduces
a step hierarchy that lets you mix single-agent tasks and iterative review cycles
in the same orchestrator, enabling end-to-end workflows like "research → develop
→ review" without glue code. Existing AgentStep usage is fully backward-compatible.
Migration Notes #
OrchestratorResult.stepResults type change
stepResults changed from List<AgentResult> to List<StepResult>. Code
that accessed AgentResult properties directly needs to use the common
StepResult accessors or unwrap via pattern matching:
// Before (0.2.x)
for (final agentResult in result.stepResults) {
print(agentResult.output);
print(agentResult.stoppedReason);
}
// After (0.3.0) — common accessors work on all subtypes
for (final stepResult in result.stepResults) {
print(stepResult.output); // available on all StepResult subtypes
print(stepResult.tokensUsed); // available on all StepResult subtypes
// Type-specific access via pattern matching
if (stepResult is AgentStepResult) {
print(stepResult.agentResult.stoppedReason);
} else if (stepResult is AgentLoopStepResult) {
print(stepResult.accepted);
print(stepResult.iterationCount);
}
}
Orchestrator.steps type widened
steps changed from List<AgentStep> to List<OrchestratorStep>. Existing
code that passes a List<AgentStep> continues to work without changes since
AgentStep now extends OrchestratorStep.
Features #
Orchestrator Step Hierarchy
OrchestratorStep— abstract base class for all pipeline steps withtaskPromptand optionalconditionguard. Enables polymorphic step pipelines.AgentLoopStep— new step type that embeds a produce-review loop directly inside anOrchestratorpipeline. Supports static and dynamic (AgentLoopStep.dynamic) task prompts, custom prompt builders, and configurablemaxIterations.StepResult— abstract base for step results with uniformoutputandtokensUsedaccessors.AgentStepResult— wrapsAgentResultfrom a single-agent step.AgentLoopStepResult— wrapsAgentLoopResultfrom a produce-review loop step, withacceptedanditerationCountconvenience accessors.
Orchestrator Refactoring
Orchestrator.stepsnow acceptsList<OrchestratorStep>(wasList<AgentStep>), enabling mixed pipelines ofAgentStepandAgentLoopStep.OrchestratorResult.stepResultschanged fromList<AgentResult>toList<StepResult>— useis AgentStepResultoris AgentLoopStepResultfor type-specific access.AgentStepnow extendsOrchestratorStep(backward-compatible — existingAgentStepusage continues to work unchanged).
Examples #
- New
orchestrator_with_agent_loop.dart— 3-step pipeline mixingAgentStepwithAgentLoopStep. - New
feature_development_pipeline.dart— realistic 5-stage software development pipeline withPersistingAgentdecorator, dynamic prompts, conditional steps, andAgentLoopStepwith custom prompt builders.
0.2.1 — 2026-03-26 #
- Expand
README.mdwith detailedAgentLoopusage and examples
0.2.0 — 2026-03-26 #
Features #
Agent Loop
AgentLoop— producer/reviewer orchestration loop that iterates a producer agent and a reviewer agent until an approval pattern is matched ormaxIterationsis reached.AgentLoopIteration— immutable record of a single loop iteration capturingindex,producerResult, andreviewerResult.AgentLoopResult— aggregated result withiterations,approvedflag, totalduration, and combinederrors.- New
example/agent_loop.dartdemonstrating a developer + QA review loop.
Bug Fixes #
File Context
- Fixed
FileContext._resolveto useUri.fileinstead ofUri.parseso that workspace paths containing spaces are handled correctly without percent-encoding artifacts.
0.1.2 — 2026-03-25 #
Improvements #
LM Studio Client
LmStudioHttpClientnow correctly throwsLmStudioHttpExceptionfor 4xx client errors instead of misclassifying them — improves error handling for authentication failures, not-found, and rate-limit responses.- Retry logic refined to only retry on transient (5xx/network) errors, not client errors.
Bug Fixes
- Fixed flaky retry-related test expectations caused by timing sensitivity in exponential backoff verification.
0.1.1 — 2026-03-25 #
Add API_KEY to AgentsCoreConfig
Configuration
- Optional
apiKeyparameter onAgentsCoreConfig— sent as aBearertoken in theAuthorizationheader when the LM Studio server requires authentication. Readable fromAGENTS_API_KEYviafromEnvironment(). Masked intoString()output to prevent accidental credential leakage. AgentsCoreConfig.copyWith()supportsclearApiKeyto explicitly remove an API key.
0.1.0 — 2026-03-25 #
First feature-complete release of agents_core.
Features #
Agent Framework
Agentabstract base class withrun(String task, {FileContext? context})method.SimpleAgent— single-round chat completion agent.ReActAgent— multi-turn Reason + Act loop with tool calling, configurablemaxIterationsandmaxTotalTokensbudget.AgentResult— structured output withoutput,tokensUsed,toolCallsMade,filesModified, andstoppedReason.
LM Studio Client
LmStudioClient— high-level typed API for LM Studio's OpenAI-compatible endpoints (chatCompletion,chatCompletionStream,chatCompletionStreamText,completion,completionStream,listModels).LmStudioHttpClient— HTTP transport with automatic retry and exponential backoff (maxRetries, configurabledelay).SseParser— Server-Sent Events stream transformer that handles multi-line data and[DONE]sentinels.
Data Models (OpenAI-compatible)
ChatMessageandChatMessageRoleenum (system,user,assistant,tool).ChatCompletionRequest/ChatCompletionResponse/ChatCompletionChoice.ChatCompletionChunk/ChatCompletionChunkChoice/ChatCompletionDeltafor streaming responses.CompletionRequest/CompletionResponse/CompletionChoice.CompletionUsage— token usage tracking.ToolDefinitionandToolCall/ToolCallFunctionfor function calling.LmModel— model listing response.
Configuration
AgentsCoreConfig— central configuration withlmStudioBaseUrl,defaultModel,requestTimeout,dockerImage,workspacePath, andlogger.AgentsCoreConfig.fromEnvironment()factory — readsLM_STUDIO_BASE_URL,AGENTS_DEFAULT_MODEL,AGENTS_DOCKER_IMAGE,AGENTS_WORKSPACE_PATH, andAGENTS_REQUEST_TIMEOUT_SECONDSfrom environment variables.AgentsCoreConfig.copyWith()for immutable modifications.Loggerabstraction withStderrLoggerandSilentLoggerimplementations.
File Context
FileContext— sandboxed file-system abstraction withread,write,append,delete,exists, andlistFiles(with glob filtering).- Path traversal protection on all file operations.
- Pre-built tool definitions:
readFileTool,writeFileTool,listFilesTool,appendFileTool, andcreateHandlers()factory.
Orchestrator
Orchestrator— sequential agent pipeline with sharedFileContext.AgentStep— static or dynamic (AgentStep.dynamic) task prompts with optionalconditionguards.OrchestratorResult— collectsstepResults,duration, anderrors.OrchestratorErrorPolicy—stop(default) orcontinueOnError.
Docker Integration
DockerClient— run containers, check availability, pull images.DockerRunResult— capturesstdout,stderr, andexitCode.
Python Execution
PythonToolAgent— pre-configuredReActAgentwith Docker-based Python execution and optional file tools.PythonExecutionTool— tool definition and handler factory for running Python code in sandboxed Docker containers.
Quick Functions
ask()— one-shot chat completion that manages client lifecycle.askStream()— streaming one-shot chat completion.Conversation— stateful multi-turn wrapper withsend(),sendStream(),setSystemPrompt(), andclearHistory().
Exception Hierarchy
AgentsCoreException— library base exception.LmStudioHttpException— non-2xx HTTP responses.LmStudioApiException— structured API errors withisModelNotFound,isContextLengthExceeded, andisRateLimitedhelpers.LmStudioConnectionException— transport failures withsocketError,httpError,timeout, andfromExceptionfactories.DockerNotAvailableException/DockerExecutionException.FileNotFoundException/PathTraversalException.SseParseException— malformed SSE data.
0.0.1 #
- Initial project scaffold.