main bea12b2e2d8e cached
396 files
3.9 MB
1.0M tokens
1 requests
Download .txt
Showing preview only (4,132K chars total). Download the full file or copy to clipboard to get everything.
Repository: christopherkarani/SwiftAgents
Branch: main
Commit: bea12b2e2d8e
Files: 396
Total size: 3.9 MB

Directory structure:
gitextract_l9ml5ppr/

├── .github/
│   ├── FUNDING.yml
│   ├── pull_request_template.md
│   └── workflows/
│       ├── claude-code-review.yml
│       ├── claude.yml
│       ├── docs.yml
│       └── swift.yml
├── .gitignore
├── .swiftformat
├── .swiftlint.yml
├── CLAUDE.md
├── Examples/
│   └── CodeReviewer/
│       ├── .gitignore
│       ├── Package.swift
│       ├── Sources/
│       │   └── CodeReviewer/
│       │       ├── Agents/
│       │       │   └── .gitkeep
│       │       ├── Output/
│       │       │   ├── .gitkeep
│       │       │   └── StreamRenderer.swift
│       │       ├── Tools/
│       │       │   └── .gitkeep
│       │       └── main.swift
│       └── Tests/
│           └── CodeReviewerTests/
│               ├── Fixtures/
│               │   └── .gitkeep
│               └── StreamRendererTests.swift
├── LICENSE
├── Package.swift
├── README.md
├── Sources/
│   ├── Swarm/
│   │   ├── Agents/
│   │   │   ├── Agent+Workspace.swift
│   │   │   └── Agent.swift
│   │   ├── Core/
│   │   │   ├── AgentConfiguration+InferenceOptions.swift
│   │   │   ├── AgentConfiguration.swift
│   │   │   ├── AgentEnvironment.swift
│   │   │   ├── AgentError.swift
│   │   │   ├── AgentEvent.swift
│   │   │   ├── AgentResponse.swift
│   │   │   ├── AgentResult.swift
│   │   │   ├── AgentRuntime+Identity.swift
│   │   │   ├── AgentRuntime.swift
│   │   │   ├── CallableAgent.swift
│   │   │   ├── CircularBuffer.swift
│   │   │   ├── ContextProfile.swift
│   │   │   ├── Conversation.swift
│   │   │   ├── ConversationBranching.swift
│   │   │   ├── Environment.swift
│   │   │   ├── EnvironmentAgent.swift
│   │   │   ├── EventStreamHooks.swift
│   │   │   ├── Execution/
│   │   │   │   ├── AgentContext.swift
│   │   │   │   └── ContextKey.swift
│   │   │   ├── Handoff/
│   │   │   │   ├── Handoff.swift
│   │   │   │   ├── HandoffBuilder.swift
│   │   │   │   ├── HandoffConfiguration+Lookup.swift
│   │   │   │   ├── HandoffConfiguration.swift
│   │   │   │   ├── HandoffOptions.swift
│   │   │   │   ├── WorkflowError.swift
│   │   │   │   └── WorkflowValidationError.swift
│   │   │   ├── InferenceStreamEvent.swift
│   │   │   ├── Logger+Swarm.swift
│   │   │   ├── ModelSettings.swift
│   │   │   ├── ObservedAgent.swift
│   │   │   ├── PartialToolCallUpdate.swift
│   │   │   ├── PromptEnvelope.swift
│   │   │   ├── PromptTokenCounter.swift
│   │   │   ├── ReasoningConfig.swift
│   │   │   ├── ResponseTracker.swift
│   │   │   ├── RunHooks.swift
│   │   │   ├── RuntimeMetadata.swift
│   │   │   ├── SendableValue.swift
│   │   │   ├── StreamHelper.swift
│   │   │   ├── StreamOperations.swift
│   │   │   ├── StructuredOutput.swift
│   │   │   ├── SwarmColonySPI.swift
│   │   │   ├── SwarmConfiguration.swift
│   │   │   ├── SwarmTranscript.swift
│   │   │   └── TokenUsage.swift
│   │   ├── Extensions/
│   │   │   └── Extensions.swift
│   │   ├── Guardrails/
│   │   │   ├── Guardrail.swift
│   │   │   ├── GuardrailError.swift
│   │   │   ├── GuardrailResult.swift
│   │   │   ├── GuardrailRunner.swift
│   │   │   ├── InputGuardrail.swift
│   │   │   ├── OutputGuardrail.swift
│   │   │   └── ToolGuardrails.swift
│   │   ├── Integration/
│   │   │   ├── Membrane/
│   │   │   │   ├── MembraneAgentAdapter.swift
│   │   │   │   ├── MembraneInternalTools.swift
│   │   │   │   ├── SessionMembraneAgentAdapter.swift
│   │   │   │   └── WaxMembraneStorage.swift
│   │   │   └── Wax/
│   │   │       ├── WaxEmbeddingProviderAdapters.swift
│   │   │       ├── WaxIntegration.swift
│   │   │       └── WaxMemory.swift
│   │   ├── Internal/
│   │   │   ├── GraphRuntime/
│   │   │   │   ├── ChatGraph.swift
│   │   │   │   ├── GraphAgent.swift
│   │   │   │   ├── HiveChatCompatibility.swift
│   │   │   │   ├── HiveCodableJSONCodec.swift
│   │   │   │   ├── RetryPolicyBridge.swift
│   │   │   │   ├── RuntimeHardening.swift
│   │   │   │   └── ToolRegistryAdapter.swift
│   │   │   └── SwarmRuntimeEnvironment.swift
│   │   ├── MCP/
│   │   │   ├── HTTPMCPServer.swift
│   │   │   ├── MCPCapabilities.swift
│   │   │   ├── MCPClient.swift
│   │   │   ├── MCPError.swift
│   │   │   ├── MCPProtocol.swift
│   │   │   ├── MCPResource.swift
│   │   │   ├── MCPServer.swift
│   │   │   └── MCPToolBridge.swift
│   │   ├── Macros/
│   │   │   └── MacroDeclarations.swift
│   │   ├── Memory/
│   │   │   ├── AgentMemory.swift
│   │   │   ├── Backends/
│   │   │   │   ├── InMemoryBackend.swift
│   │   │   │   └── SwiftDataBackend.swift
│   │   │   ├── CompositeMemory.swift
│   │   │   ├── ContextCoreMemory.swift
│   │   │   ├── ConversationMemory.swift
│   │   │   ├── DefaultAgentMemory.swift
│   │   │   ├── EmbeddingProvider.swift
│   │   │   ├── HybridMemory.swift
│   │   │   ├── InMemorySession.swift
│   │   │   ├── InferenceProviderSummarizer.swift
│   │   │   ├── MemoryMessage.swift
│   │   │   ├── MemoryPromptDescriptor.swift
│   │   │   ├── MemoryRetrievalPolicy.swift
│   │   │   ├── MemorySessionLifecycle.swift
│   │   │   ├── PersistedMessage.swift
│   │   │   ├── PersistentMemory.swift
│   │   │   ├── PersistentMemoryBackend.swift
│   │   │   ├── PersistentSession.swift
│   │   │   ├── Session.swift
│   │   │   ├── SlidingWindowMemory.swift
│   │   │   ├── Summarizer.swift
│   │   │   ├── SummaryMemory.swift
│   │   │   ├── SwiftDataMemory.swift
│   │   │   ├── TokenEstimator.swift
│   │   │   └── VectorMemory.swift
│   │   ├── Observability/
│   │   │   ├── AgentTracer.swift
│   │   │   ├── ConsoleTracer.swift
│   │   │   ├── MetricsCollector.swift
│   │   │   ├── OSLogTracer.swift
│   │   │   ├── PerformanceMetrics.swift
│   │   │   ├── SwiftLogTracer.swift
│   │   │   ├── TraceContext.swift
│   │   │   ├── TraceEvent.swift
│   │   │   ├── TraceEventPublicLogSanitizer.swift
│   │   │   ├── TraceSpan.swift
│   │   │   └── TracingHelper.swift
│   │   ├── Providers/
│   │   │   ├── Conduit/
│   │   │   │   ├── ConduitInferenceProvider.swift
│   │   │   │   ├── ConduitProviderSelection.swift
│   │   │   │   ├── LLM.swift
│   │   │   │   ├── MLXPromptProvider.swift
│   │   │   │   ├── OllamaSettings.swift
│   │   │   │   └── OpenRouterRouting.swift
│   │   │   ├── ConversationInferenceProvider.swift
│   │   │   ├── DefaultInferenceProviderFactory.swift
│   │   │   ├── InferenceProviderMetadata.swift
│   │   │   ├── LanguageModelSession.swift
│   │   │   ├── LanguageModelSessionHelpers.swift
│   │   │   ├── MultiProvider.swift
│   │   │   ├── TextOnlyConversationInferenceProviderAdapter.swift
│   │   │   └── ToolCallStreamingInferenceProvider.swift
│   │   ├── Resilience/
│   │   │   ├── CircuitBreaker.swift
│   │   │   ├── FallbackChain.swift
│   │   │   ├── RateLimiter.swift
│   │   │   ├── Resilience.swift
│   │   │   └── RetryPolicy.swift
│   │   ├── Swarm.swift
│   │   ├── Tools/
│   │   │   ├── AgentTool.swift
│   │   │   ├── ArithmeticParser.swift
│   │   │   ├── BuiltInTools.swift
│   │   │   ├── ParallelToolExecutor.swift
│   │   │   ├── SemanticCompactorTool.swift
│   │   │   ├── Tool.swift
│   │   │   ├── ToolBridgeHelper.swift
│   │   │   ├── ToolBridging.swift
│   │   │   ├── ToolCallGoal.swift
│   │   │   ├── ToolCollection.swift
│   │   │   ├── ToolExecutionEngine.swift
│   │   │   ├── ToolExecutionResult.swift
│   │   │   ├── ToolExecutionSemantics.swift
│   │   │   ├── ToolParameterBuilder.swift
│   │   │   ├── Web/
│   │   │   │   └── WebSearchSupport.swift
│   │   │   ├── WebSearchTool.swift
│   │   │   └── ZoniSearchTool.swift
│   │   ├── Workflow/
│   │   │   ├── Workflow+Durable.swift
│   │   │   ├── Workflow.swift
│   │   │   ├── WorkflowCheckpointCodec.swift
│   │   │   ├── WorkflowCheckpointStore.swift
│   │   │   ├── WorkflowCheckpointing.swift
│   │   │   ├── WorkflowDurableEngine.swift
│   │   │   └── WorkflowResultSnapshot.swift
│   │   └── Workspace/
│   │       ├── AgentWorkspace.swift
│   │       ├── WorkspaceMemory.swift
│   │       └── WorkspaceWriter.swift
│   ├── SwarmCapabilityShowcase/
│   │   └── main.swift
│   ├── SwarmCapabilityShowcaseSupport/
│   │   └── CapabilityShowcase.swift
│   ├── SwarmDemo/
│   │   ├── AgentTest.swift
│   │   └── SwarmPlayground.playground/
│   │       ├── Pages/
│   │       │   └── New.xcplaygroundpage/
│   │       │       └── Contents.swift
│   │       └── contents.xcplayground
│   ├── SwarmMCP/
│   │   ├── SwarmMCPErrorMapper.swift
│   │   ├── SwarmMCPServerService.swift
│   │   ├── SwarmMCPToolAdapter.swift
│   │   ├── SwarmMCPToolMapper.swift
│   │   └── SwarmMCPValueMapper.swift
│   ├── SwarmMCPServerDemo/
│   │   └── main.swift
│   ├── SwarmMacros/
│   │   ├── AgentMacro.swift
│   │   ├── BuilderMacro.swift
│   │   ├── InlineToolMacro.swift
│   │   ├── ParameterMacro.swift
│   │   ├── Plugin.swift
│   │   ├── PromptMacro.swift
│   │   ├── ToolMacro.swift
│   │   └── TraceableMacro.swift
│   ├── SwarmMembrane/
│   │   └── SwarmMembrane.swift
│   └── SwarmOpenTelemetry/
│       ├── OpenTelemetryAgentRuntime.swift
│       ├── OpenTelemetryAnyInferenceProvider.swift
│       ├── OpenTelemetryAttributes.swift
│       ├── OpenTelemetryInferenceProvider.swift
│       └── SwarmTypeAliases.swift
├── Tests/
│   ├── HiveSwarmTests/
│   │   ├── ChatGraphTests.swift
│   │   ├── GraphAgentStreamingTests.swift
│   │   ├── MembraneHiveCheckpointTests.swift
│   │   ├── ModelRouterTests.swift
│   │   ├── RetryPolicyBridgeTests.swift
│   │   └── WorkflowHiveEngineTests.swift
│   ├── SwarmCapabilityShowcaseTests/
│   │   └── CapabilityShowcaseTests.swift
│   ├── SwarmMacrosTests/
│   │   ├── AgentMacroTests.swift
│   │   ├── InlineToolMacroTests.swift
│   │   ├── MacroIntegrationTests.swift
│   │   ├── PromptMacroTests.swift
│   │   ├── PromptStringTestSupport.swift
│   │   ├── ToolMacroTests.swift
│   │   └── TraceableMacroTests.swift
│   ├── SwarmOpenTelemetryTests/
│   │   ├── OpenTelemetryInferenceProviderTests.swift
│   │   └── OpenTelemetryPublicAPITests.swift
│   └── SwarmTests/
│       ├── APIAuditTests.swift
│       ├── Agents/
│       │   ├── AgentCodexReviewFixesTests.swift
│       │   ├── AgentConduitProviderSelectionStreamingTests.swift
│       │   ├── AgentDefaultInferenceProviderTests.swift
│       │   ├── AgentHandoffRuntimeTests.swift
│       │   ├── AgentLiveToolCallStreamingTests.swift
│       │   ├── AgentReliabilityTests.swift
│       │   ├── AgentResponseContinuationTests.swift
│       │   ├── AgentStructuredInferenceProviderTests.swift
│       │   ├── AgentTests.swift
│       │   ├── AgentToolOutputTextTests.swift
│       │   ├── AgentTranscriptContractTests.swift
│       │   ├── StreamingEventTests.swift
│       │   └── Strict4kPromptEnvelopeTests.swift
│       ├── ContextCoreIntegrationTests.swift
│       ├── Core/
│       │   ├── AgentConfigurationInferenceOptionsTests.swift
│       │   ├── AgentErrorTests.swift
│       │   ├── AgentEventTests+Integration.swift
│       │   ├── AgentEventTests+ToolCall.swift
│       │   ├── AgentEventTests+ToolResult.swift
│       │   ├── AgentEventTests.swift
│       │   ├── AgentObserverTests.swift
│       │   ├── AgentResultRuntimeEngineTests.swift
│       │   ├── ContextProfileTests.swift
│       │   ├── ConversationTests.swift
│       │   ├── CoreTests.swift
│       │   ├── HandoffBehaviorTests.swift
│       │   ├── InferenceTypesTests.swift
│       │   ├── ModelSettingsTests+Enums.swift
│       │   ├── ModelSettingsTests+Validation.swift
│       │   ├── ModelSettingsTests.swift
│       │   ├── ReasoningConfigTests.swift
│       │   ├── ResponseTrackerTests+BasicTests.swift
│       │   ├── ResponseTrackerTests+CleanupTests.swift
│       │   ├── ResponseTrackerTests+ConcurrencyTests.swift
│       │   ├── ResponseTrackerTests+HistoryTests.swift
│       │   ├── ResponseTrackerTests.swift
│       │   ├── RunHooksTests.swift
│       │   ├── StreamOperationsTests.swift
│       │   ├── SwarmConfigurationTests.swift
│       │   └── SwarmRuntimeEnvironmentTests.swift
│       ├── DocumentationFreshnessTests.swift
│       ├── Extensions/
│       │   └── DurationExtensionsTests.swift
│       ├── Guardrails/
│       │   ├── AgentRunGuardrailBehaviorTests.swift
│       │   ├── GuardrailErrorTests.swift
│       │   ├── GuardrailIntegrationTests.swift
│       │   ├── GuardrailResultTests.swift
│       │   ├── InputGuardrailTests.swift
│       │   ├── OutputGuardrailTests.swift
│       │   └── ToolGuardrailTests.swift
│       ├── HiveSwarm/
│       │   └── ToolRegistryAdapterTests.swift
│       ├── Integration/
│       │   ├── FullAPIScenarioTests.swift
│       │   ├── MCPIntegrationTests.swift
│       │   ├── SessionIntegrationTests.swift
│       │   ├── WaxIntegrationTests.swift
│       │   └── WorkflowResumeIntegrationTests.swift
│       ├── MCP/
│       │   ├── HTTPMCPServerRetryTests.swift
│       │   ├── HTTPMCPServerTests.swift
│       │   ├── MCPClientTests+Caching.swift
│       │   ├── MCPClientTests+Mocks.swift
│       │   ├── MCPClientTests.swift
│       │   ├── MCPProtocolTests.swift
│       │   ├── SwarmMCPServerServiceTests+Mocks.swift
│       │   └── SwarmMCPServerServiceTests.swift
│       ├── Macros/
│       │   └── AgentActorMacroConformanceTests.swift
│       ├── MembraneIntegrationTests.swift
│       ├── Memory/
│       │   ├── ContextCoreDefaultMemoryTests.swift
│       │   ├── ConversationMemoryTests.swift
│       │   ├── HybridMemoryTests.swift
│       │   ├── InMemorySessionTests.swift
│       │   ├── MemoryClearGenerationTests.swift
│       │   ├── MemoryIngestionPolicyTests.swift
│       │   ├── MemoryMessageTests.swift
│       │   ├── PersistentMemoryTests.swift
│       │   ├── PersistentSessionTests.swift
│       │   ├── SessionTests.swift
│       │   ├── SlidingWindowMemoryTests.swift
│       │   ├── SummarizerTests.swift
│       │   ├── SummaryMemoryTests.swift
│       │   ├── SwiftDataMemoryTests.swift
│       │   ├── TokenEstimatorTests.swift
│       │   ├── VectorMemorySemanticRetrievalTests.swift
│       │   └── WaxMemoryTests.swift
│       ├── Mocks/
│       │   ├── MockAgentMemory.swift
│       │   ├── MockAgentRuntime.swift
│       │   ├── MockEmbeddingProvider.swift
│       │   ├── MockInferenceProvider.swift
│       │   ├── MockSummarizer.swift
│       │   ├── MockTool.swift
│       │   └── SwarmConfigurationTestIsolation.swift
│       ├── Observability/
│       │   ├── ObservabilityPrivacyTests.swift
│       │   ├── ObservabilityTests+Metrics.swift
│       │   ├── ObservabilityTests+TraceEvents.swift
│       │   ├── ObservabilityTests+Tracers.swift
│       │   ├── ObservabilityTests.swift
│       │   ├── PerformanceMetricsTests.swift
│       │   ├── TraceContextTests.swift
│       │   ├── TraceSpanTests.swift
│       │   ├── TracerTests+Buffered.swift
│       │   ├── TracerTests+EdgeCases.swift
│       │   ├── TracerTests+Integration.swift
│       │   ├── TracerTests+NoOp.swift
│       │   ├── TracerTests+TypeErasure.swift
│       │   └── TracerTests.swift
│       ├── Providers/
│       │   ├── ConduitAdvancedCompatibility.swift
│       │   ├── ConduitInferenceProviderTests.swift
│       │   ├── ConduitProviderSelectionTests.swift
│       │   ├── ConduitStructuredMessageBridgeTests.swift
│       │   ├── ConduitToolCallStreamingBridgeTests.swift
│       │   ├── FoundationModelsToolCallingTests.swift
│       │   ├── InferenceProviderCertificationTests.swift
│       │   ├── LLMPresetsTests.swift
│       │   ├── LanguageModelSessionTests.swift
│       │   ├── MultiProviderTests.swift
│       │   ├── ProviderCertificationSupport.swift
│       │   └── TextOnlyConversationInferenceProviderAdapterTests.swift
│       ├── Regression/
│       │   └── FrameworkDXRegressionTests.swift
│       ├── Resilience/
│       │   ├── ResilienceTests+CircuitBreaker.swift
│       │   ├── ResilienceTests+Fallback.swift
│       │   ├── ResilienceTests+Integration.swift
│       │   ├── ResilienceTests+RateLimiter.swift
│       │   ├── ResilienceTests+Retry.swift
│       │   └── ResilienceTests.swift
│       ├── SwiftAgentsTests.swift
│       ├── Tools/
│       │   ├── AgentToolTests.swift
│       │   ├── AnyToolTests.swift
│       │   ├── ArithmeticParserTests.swift
│       │   ├── CalculatorToolTests.swift
│       │   ├── FunctionToolTests.swift
│       │   ├── ParallelToolExecutorTests+Advanced.swift
│       │   ├── ParallelToolExecutorTests+Mocks.swift
│       │   ├── ParallelToolExecutorTests.swift
│       │   ├── SemanticCompactorToolBehaviorTests.swift
│       │   ├── ToolParameterTests.swift
│       │   ├── ToolSchemaIntegrationTests.swift
│       │   ├── WebSearchSupportTests.swift
│       │   ├── WebSearchToolBehaviorTests.swift
│       │   └── ZoniSearchToolTests.swift
│       ├── V2SurfaceAuditTests.swift
│       ├── V3/
│       │   ├── AgentCanonicalInitTests.swift
│       │   ├── AgentEvalTests.swift
│       │   ├── AgentModifiersTests.swift
│       │   ├── GuardrailFactoryTests.swift
│       │   ├── MemoryFactoryTests.swift
│       │   ├── MemoryFactoryV3Tests.swift
│       │   ├── ProviderFactoryTests.swift
│       │   ├── ReadmeProviderCompileTests.swift
│       │   ├── SwarmConfigTests.swift
│       │   ├── ToolBuilderV3Tests.swift
│       │   ├── ToolCollectionTests.swift
│       │   └── ZombieAPIRemovalTests.swift
│       ├── Workflow/
│       │   ├── WorkflowDurableTests.swift
│       │   └── WorkflowTests.swift
│       └── Workspace/
│           └── AgentWorkspaceTests.swift
├── docs/
│   ├── .vitepress/
│   │   ├── config.ts
│   │   └── theme/
│   │       ├── index.ts
│   │       └── style.css
│   ├── guide/
│   │   ├── agent-workspace.md
│   │   ├── capability-showcase.md
│   │   ├── getting-started.md
│   │   ├── opentelemetry-tracing.md
│   │   └── why-swarm.md
│   ├── index.md
│   ├── public/
│   │   └── CNAME
│   ├── reference/
│   │   ├── api-catalog.md
│   │   ├── durable-runtime-hardening.md
│   │   ├── front-facing-api.md
│   │   └── overview.md
│   └── release/
│       └── release-checklist.md
└── package.json

================================================
FILE CONTENTS
================================================

================================================
FILE: .github/FUNDING.yml
================================================
github: christopherkarani


================================================
FILE: .github/pull_request_template.md
================================================
# Pull Request

## Thank you for contributing to Swarm! 🎉

We appreciate your effort to improve the framework. This template helps ensure high-quality contributions that align with the project's standards.

---

## Description

### What does this PR do?
<!-- Provide a clear and concise description of your changes -->


### Motivation and Context
<!-- Why is this change needed? What problem does it solve? -->
<!-- If it fixes an open issue, please link to the issue here using #issue_number -->

Fixes # (issue)

---

## Type of Change

Please check the relevant option(s):

- [ ] 🐛 **Bug fix** (non-breaking change which fixes an issue)
- [ ] ✨ **New feature** (non-breaking change which adds functionality)
- [ ] 🔨 **Refactoring** (code improvement without functional changes)
- [ ] 📚 **Documentation** (updates to README, inline docs, or examples)
- [ ] ⚠️ **Breaking change** (fix or feature that would cause existing functionality to not work as expected)
- [ ] 🧪 **Test improvement** (adding missing tests or improving existing ones)
- [ ] 🔧 **Build/CI** (changes to build process, dependencies, or CI configuration)

---

## Changes Made

### Implementation Details
<!-- Describe the technical implementation. Include architectural decisions, design patterns used, and reasoning behind your approach -->


### Files Changed
<!-- List the main files modified and briefly explain why -->

- `path/to/file.swift` - Description of changes
- `path/to/another/file.swift` - Description of changes

### API Changes (if applicable)
<!-- Describe any new public APIs, protocol changes, or modifications to existing interfaces -->


---

## Testing

### Test Coverage
<!-- Describe the tests you added or modified to cover your changes -->

- [ ] I have followed **Test-Driven Development (TDD)** practices (wrote tests first, then implementation)
- [ ] All new code is covered by unit tests
- [ ] I have added tests for edge cases and error conditions
- [ ] I have used mock protocols for external dependencies (LLM providers, network, etc.)

### Test Results
```bash
# Paste the output of: swift test
```

### Manual Testing
<!-- If applicable, describe any manual testing performed -->


---

## Breaking Changes

<!-- If this PR introduces breaking changes, describe them here and provide migration guidance -->

**Does this PR introduce breaking changes?**
- [ ] Yes (please describe below)
- [ ] No

### Breaking Change Details
<!-- If yes, describe what breaks and how users should migrate -->


---

## Pre-Submission Checklist

### Code Quality
- [ ] My code follows the Swift 6.2 standards and project conventions
- [ ] I have performed a self-review of my own code
- [ ] I have run `swift build` and ensured no compilation errors
- [ ] I have run `swift test` and all tests pass
- [ ] I have run SwiftFormat: `swiftformat Sources Tests --lint --config .swiftformat`
- [ ] I have run SwiftLint and fixed any warnings: `swiftlint lint`

### Concurrency & Safety
- [ ] All public types conform to `Sendable` where appropriate
- [ ] I have used `async/await` and structured concurrency correctly
- [ ] I have properly applied `@MainActor`, `actor`, or `nonisolated` annotations
- [ ] My code is free from data races and concurrency issues

### Documentation
- [ ] I have added/updated documentation comments for public APIs
- [ ] I have updated the README.md if needed
- [ ] I have added examples to `Sources/Swarm/Examples/` if introducing new features
- [ ] My code does not use `print()` statements (uses `swift-log` instead)

### Testing (TDD Required)
- [ ] I wrote tests **before** writing the implementation (Red phase)
- [ ] I wrote minimal code to make tests pass (Green phase)
- [ ] I refactored while keeping tests green (Refactor phase)
- [ ] Mock protocols are used for external dependencies

### Version Compatibility
- [ ] My code supports the minimum requirements: iOS 26+, macOS 26+, tvOS 26+, Swift 6.2
- [ ] I have not introduced dependencies that break compatibility

---

## Additional Context

### Screenshots (if applicable)
<!-- Add screenshots or screen recordings for UI changes or examples -->


### Related Issues/PRs
<!-- Link to related issues or pull requests -->

- Related to #
- Depends on #
- Blocks #

### Questions or Concerns
<!-- Any questions for reviewers or areas you'd like specific feedback on? -->


---

## Reviewer Checklist (for maintainers)

- [ ] Code follows project architecture and patterns
- [ ] Tests are comprehensive and follow TDD principles
- [ ] Documentation is clear and complete
- [ ] No security vulnerabilities introduced (SQL injection, XSS, command injection, etc.)
- [ ] Performance implications are acceptable
- [ ] Breaking changes are properly documented
- [ ] CI/CD checks pass

---

**Thank you again for your contribution!** Your efforts help make Swarm better for the entire Swift community. If you have any questions, feel free to ask in the comments below.


================================================
FILE: .github/workflows/claude-code-review.yml
================================================
name: Claude Code Review

on:
  pull_request:
    types: [opened, synchronize]
    # Optional: Only run on specific file changes
    # paths:
    #   - "src/**/*.ts"
    #   - "src/**/*.tsx"
    #   - "src/**/*.js"
    #   - "src/**/*.jsx"

jobs:
  claude-review:
    # Optional: Filter by PR author
    # if: |
    #   github.event.pull_request.user.login == 'external-contributor' ||
    #   github.event.pull_request.user.login == 'new-developer' ||
    #   github.event.pull_request.author_association == 'FIRST_TIME_CONTRIBUTOR'

    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: read
      issues: read
      id-token: write

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Setup Swift 6.2
        uses: swift-actions/setup-swift@v3
        with:
          swift-version: "6.2"
          skip-verify-signature: true

      - name: Install SwiftLint and SwiftFormat
        run: |
          /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
          eval "$(/home/linuxbrew/.linuxbrew/bin/brew shellenv)"
          echo "/home/linuxbrew/.linuxbrew/bin" >> $GITHUB_PATH
          brew install swiftlint swiftformat

      - name: Cache Swift packages
        uses: actions/cache@v4
        with:
          path: .build
          key: ${{ runner.os }}-swift-${{ hashFiles('Package.swift') }}
          restore-keys: |
            ${{ runner.os }}-swift-

      - name: Run Claude Code Review
        id: claude-review
        uses: anthropics/claude-code-action@v1
        env:
          REPO_NAME: ${{ github.repository }}
          PR_NUMBER: ${{ github.event.pull_request.number }}
        with:
          claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
          prompt: |
            You are reviewing a pull request.
            Repository: Use the REPO_NAME environment variable
            PR Number: Use the PR_NUMBER environment variable

            Please review this pull request and provide feedback on:
            - Code quality and best practices
            - Potential bugs or issues
            - Performance considerations
            - Security concerns
            - Test coverage

            IMPORTANT: You have access to Swift build tools. After reviewing the code:
            1. Run `swift build` to verify the code compiles
            2. Run `swift test` to verify tests pass
            3. Run `swiftlint lint --strict --config .swiftlint.yml Sources Tests` to check for style violations
            4. Include build/test results in your review

            Use the repository's CLAUDE.md for guidance on style and conventions. Be constructive and helpful in your feedback.

            Use `gh pr comment` with your Bash tool to leave your review as a comment on the PR.

          claude_args: >-
            --allowed-tools
            "Bash(swift build:*),Bash(swift test:*),Bash(swift package:*),Bash(swiftlint:*),Bash(swiftformat:*),Bash(gh issue view:*),Bash(gh search:*),Bash(gh issue list:*),Bash(gh pr comment:*),Bash(gh pr diff:*),Bash(gh pr view:*),Bash(gh pr list:*)"


================================================
FILE: .github/workflows/claude.yml
================================================
name: Claude Code

on:
  issue_comment:
    types: [created]
  pull_request_review_comment:
    types: [created]
  issues:
    types: [opened, assigned]
  pull_request_review:
    types: [submitted]

jobs:
  claude:
    if: |
      (github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
      (github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
      (github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) ||
      (github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude')))
    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: read
      issues: read
      id-token: write
      actions: read # Required for Claude to read CI results on PRs
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Setup Swift 6.2
        uses: swift-actions/setup-swift@v3
        with:
          swift-version: "6.2"
          skip-verify-signature: true

      - name: Install SwiftLint and SwiftFormat
        run: |
          /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
          eval "$(/home/linuxbrew/.linuxbrew/bin/brew shellenv)"
          echo "/home/linuxbrew/.linuxbrew/bin" >> $GITHUB_PATH
          brew install swiftlint swiftformat

      - name: Cache Swift packages
        uses: actions/cache@v4
        with:
          path: .build
          key: ${{ runner.os }}-swift-${{ hashFiles('Package.swift') }}
          restore-keys: |
            ${{ runner.os }}-swift-

      - name: Run Claude Code
        id: claude
        uses: anthropics/claude-code-action@v1
        with:
          claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}

          additional_permissions: |
            actions: read

          # Claude can build, test, lint, and format Swift code
          claude_args: >-
            --allowed-tools
            "Bash(swift build:*),Bash(swift test:*),Bash(swift package:*),Bash(swiftlint:*),Bash(swiftformat:*),Bash(gh issue view:*),Bash(gh search:*),Bash(gh issue list:*),Bash(gh pr comment:*),Bash(gh pr diff:*),Bash(gh pr view:*),Bash(gh pr list:*),Bash(gh pr create:*),Bash(git:*)"


================================================
FILE: .github/workflows/docs.yml
================================================
name: Deploy Docs

on:
  pull_request:
    paths:
      - "docs/**"
      - "package.json"
      - "package-lock.json"
      - ".github/workflows/docs.yml"
  push:
    branches: [main]
  workflow_dispatch:

permissions:
  contents: read
  pages: write
  id-token: write

concurrency:
  group: pages
  cancel-in-progress: false

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm
      - run: npm ci
      - run: npm run docs:build
      - uses: actions/upload-pages-artifact@v3
        with:
          path: docs/.vitepress/dist

  deploy:
    if: github.event_name == 'push' && github.ref == 'refs/heads/main'
    needs: build
    runs-on: ubuntu-latest
    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}
    steps:
      - id: deployment
        uses: actions/deploy-pages@v4


================================================
FILE: .github/workflows/swift.yml
================================================
# Swarm CI Workflow
# Builds and tests on macOS; verifies the Linux core build lane on Ubuntu

name: Swift CI

on:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]
  workflow_dispatch:

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  # macOS Build & Test (full features including SwiftData)
  build-macos:
    name: Build & Test (macOS)
    runs-on: macos-15

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Setup Swift 6.2
        uses: swift-actions/setup-swift@v3
        with:
          swift-version: "6.2"

      - name: Show Swift version
        run: swift --version

      - name: Cache Swift packages
        uses: actions/cache@v4
        with:
          path: .build
          key: ${{ runner.os }}-swift-6.2-${{ hashFiles('Package.swift') }}
          restore-keys: |
            ${{ runner.os }}-swift-6.2-

      - name: Resolve dependencies
        run: swift package resolve

      - name: Build
        run: swift build

      - name: Run tests
        run: swift test --no-parallel

      - name: Run Hive integration tests
        run: swift test --no-parallel --filter HiveSwarmTests

      - name: Run capability showcase matrix
        run: swift run SwarmCapabilityShowcase matrix

      - name: Test CodeReviewer example
        run: SWARM_CORE_ONLY=1 swift test
        working-directory: Examples/CodeReviewer

  # Linux Build & Test (default graph, including Hive)
  build-linux:
    name: Build (Linux Core)
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Setup Swift 6.2
        uses: swift-actions/setup-swift@v3
        with:
          swift-version: "6.2"
          skip-verify-signature: true

      - name: Verify Swift version
        run: swift --version

      - name: Cache Swift packages
        uses: actions/cache@v4
        with:
          path: .build
          key: linux-swift-${{ hashFiles('Package.swift') }}
          restore-keys: |
            linux-swift-

      - name: Resolve dependencies
        run: swift package resolve

      - name: Build default Swarm + Hive graph
        run: swift build

      - name: Build tests including Hive integration
        run: swift build --build-tests

      - name: Run tests
        run: swift test --no-parallel

      - name: Run Hive integration tests
        run: swift test --no-parallel --filter HiveSwarmTests

  # Code Quality (macOS only - SwiftLint/SwiftFormat)
  code-quality:
    name: Code Quality
    runs-on: macos-15

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Install SwiftLint
        run: brew install swiftlint

      - name: Run SwiftLint
        run: swiftlint lint --strict --config .swiftlint.yml Sources Tests

      - name: Install SwiftFormat
        run: brew install swiftformat

      - name: Run SwiftFormat (check mode)
        run: swiftformat Sources Tests --lint --config .swiftformat


================================================
FILE: .gitignore
================================================
.DS_Store
/.build
/Packages
xcuserdata/
DerivedData/
.swiftpm/configuration/registries.json
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
.netrc

# Git worktrees
.worktrees/

# Code Coverage
*.profdata
*.profraw
.build/coverage/
coverage/

# Claude Code / AI development configuration
.claude/
.mcp.json
.agent_context.md
AGENTS.md

# Internal development artifacts
IMPLEMENTATION_PLAN.md
HIVE_EXTENSIBILITY_INTEGRATION_PLAN.md
PRODUCTION_READINESS_AUDIT.md
tasks/
scripts/
!scripts/
scripts/*
!scripts/ci/
!scripts/ci/**

# Internal documentation (plans, prompts, work packages, validation)
docs/plans/
docs/prompts/
docs/superpowers/plans/
docs/work-packages/
docs/validation/
docs/migration-plan_*.md
docs/subagent-context-findings.md

# Build & dev tool artifacts
.build-audit/
.worktrees/
.home/
.vscode/
Swarm.xcworkspace/

# Website (separate project)
website/

# Git worktrees
.worktrees/

# Internal test planning artifacts
Tests/**/INTEGRATION_TEST_SUMMARY.md
Tests/**/QUICK_REFERENCE.md

# API audit working documents
docs/reference/api-surface-catalog.md
docs/reference/api-improvement-report.md
docs/reference/api-quality-assessment.md
docs/reference/*audit-report.md
docs/reference/docc-audit-report.md
docs/reference/docs-folder-audit-report.md
docs/reference/documentation-*-report.md
docs/reference/documentation-gap-report.md
docs/reference/documentation-improvement-plan.md
docs/reference/documentation-validation-report.md
docs/reference/readme-audit-report.md
docs/reference/twitter-article-*.md
docs/swarm-hacker-news-blog.md
docs/superpowers/

# VitePress / Node
node_modules/
docs/.vitepress/dist/
docs/.vitepress/cache/

# Swift tooling config
.swift-version

# SPM resolved file (library — consumers resolve their own deps)
Package.resolved
marketing/


================================================
FILE: .swiftformat
================================================
--swiftversion 6.2
--exclude .build,.swiftpm,.worktrees,Packages,node_modules,docs/.vitepress
--disable andOperator,blankLineAfterImports,blankLinesAroundMark,blankLinesAtEndOfScope,blankLinesAtStartOfScope,blankLinesBetweenScopes,braces,conditionalAssignment,consecutiveBlankLines,consecutiveSpaces,consistentSwitchCaseSpacing,elseOnSameLine,emptyBraces,enumNamespaces,extensionAccessControl,genericExtensions,headerFileName,hoistAwait,hoistPatternLet,hoistTry,indent,modifierOrder,numberFormatting,opaqueGenericParameters,preferCountWhere,preferKeyPath,redundantFileprivate,redundantInternal,redundantPublic,redundantRawValues,redundantReturn,redundantSelf,redundantType,sortImports,spaceAroundOperators,trailingCommas,trailingSpace,typeSugar,unusedArguments,wrapArguments,wrapLoopBodies,wrapMultilineStatementBraces


================================================
FILE: .swiftlint.yml
================================================
included:
  - Sources
  - Tests

excluded:
  - .build
  - .swiftpm
  - .worktrees
  - Packages
  - node_modules
  - docs/.vitepress

disabled_rules:
  - cyclomatic_complexity
  - file_length
  - for_where
  - force_try
  - function_body_length
  - function_parameter_count
  - identifier_name
  - implicit_optional_initialization
  - large_tuple
  - leading_whitespace
  - line_length
  - nesting
  - opening_brace
  - optional_data_string_conversion
  - orphaned_doc_comment
  - static_over_final_class
  - todo
  - trailing_comma
  - trailing_newline
  - trailing_whitespace
  - type_body_length
  - type_name
  - unneeded_synthesized_initializer
  - vertical_whitespace

strict: true


================================================
FILE: CLAUDE.md
================================================
# CLAUDE.md

Guidance for AI coding assistants (Claude Code, Cursor, etc.) working in this
repository. This file is the canonical, in-repo briefing — read it before making
changes.

## What is Swarm?

Swarm is a Swift 6.2 framework for building **agents and multi-agent
workflows** on Apple platforms (iOS 26+, macOS 26+, tvOS 26+) and Linux. It is
built around:

- **Agents** — `Agent` struct with `@ToolBuilder` trailing closures, an
  `AgentRuntime` protocol, and pluggable inference providers.
- **Workflows** — fluent composition (`.step`, `.parallel`, `.route`,
  `.repeatUntil`) compiled to a DAG with checkpoint/resume.
- **Tools** — the `@Tool` macro generates JSON schemas from Swift structs at
  compile time; `FunctionTool` covers ad-hoc closures.
- **Memory** — conversation, sliding-window, summary, vector, and
  persistent backends.
- **Guardrails / Resilience / Observability** — first-class concerns, not
  bolt-ons.
- **Providers** — Foundation Models, Anthropic, OpenAI, Ollama, Gemini,
  MiniMax, OpenRouter, MLX, all routed through [Conduit](https://github.com/christopherkarani/Conduit).
- **MCP** — Model Context Protocol client and server support.

The package uses Swift 6.2 with `StrictConcurrency` enabled across all targets.
**All public types must be `Sendable`** — the compiler enforces it.

## Repository Layout

```
Swarm/
├── Package.swift                  # SPM manifest (Swift 6.2, products)
├── README.md                      # User-facing overview
├── Sources/
│   ├── Swarm/                     # Main library (156 .swift files)
│   │   ├── Agents/                # Agent struct, workspace integration
│   │   ├── Core/                  # AgentRuntime, Conversation, Environment,
│   │   │                          #   PromptEnvelope, RuntimeMetadata, …
│   │   ├── Workflow/              # Workflow + durable engine + checkpointing
│   │   ├── Tools/                 # Tool protocol, ToolCollection, ParallelExecutor,
│   │   │                          #   built-ins, web tools, schema bridging
│   │   ├── Memory/                # Conversation, sliding window, summary, vector,
│   │   │                          #   SwiftData, ContextCore, hybrid backends
│   │   ├── Providers/             # Conduit adapters, multi-provider, sessions
│   │   ├── Guardrails/            # Input/Output/Tool guardrail specs + runner
│   │   ├── Resilience/            # Retry, circuit breaker, fallback, rate limit
│   │   ├── Observability/         # AgentTracer, SwiftLog/OSLog tracers, metrics
│   │   ├── MCP/                   # MCPClient, MCPServer, ToolBridge, capabilities
│   │   ├── Workspace/             # AgentWorkspace (AGENTS.md, .swarm/ skills)
│   │   ├── Macros/                # Public macro declarations
│   │   ├── Integration/           # Membrane and Wax integrations
│   │   └── Internal/GraphRuntime/ # Compiled DAG runtime (internal)
│   ├── SwarmMacros/               # Compiler plugin (@Tool, @Parameter,
│   │                              #   @Traceable, #Prompt, builders)
│   ├── SwarmMembrane/             # Membrane workflow integration product
│   ├── SwarmMCP/                  # MCP server adapter product
│   ├── SwarmCapabilityShowcase/        # Executable: deterministic showcase CLI
│   ├── SwarmCapabilityShowcaseSupport/ # Library backing the showcase
│   ├── SwarmDemo/                 # (opt-in) demo executable
│   └── SwarmMCPServerDemo/        # (opt-in) MCP server demo
├── Tests/
│   ├── SwarmTests/                # Main test target (mirrors Sources/Swarm)
│   │   └── Mocks/                 # MockAgentRuntime, MockInferenceProvider, …
│   ├── HiveSwarmTests/            # Hive integration tests
│   ├── SwarmMacrosTests/          # Macro expansion tests
│   └── SwarmCapabilityShowcaseTests/
├── Examples/CodeReviewer/         # Standalone example SPM project
├── docs/
│   ├── guide/                     # Getting started, agent workspace, showcase
│   ├── reference/                 # API catalog, front-facing-api, audits
│   └── release/                   # release-checklist.md
└── .github/workflows/             # swift.yml, claude.yml, claude-code-review.yml,
                                   #   docs.yml
```

## Build, Test, Lint

This is a Swift Package — there is no Xcode project committed. All commands run
from the repo root.

```bash
swift package resolve         # Resolve dependencies
swift build                   # Build the library targets
swift test                    # Run all tests
swift test --no-parallel      # Match CI ordering (recommended)
swift test --filter SwarmTests.WorkflowTests   # Run a single suite
```

CI (`.github/workflows/swift.yml`) runs on macOS 15 and Ubuntu with Swift 6.2.
The default Swarm graph includes Hive, so Linux CI explicitly builds and runs
the `HiveSwarmTests` target without opt-in traits or environment flags.

The Hive integration tests live in the `HiveSwarmTests` target and are asserted
explicitly in CI on both macOS and Linux.

### Demo / benchmark executables

The `SwarmDemo` and `SwarmMCPServerDemo` executables are
**opt-in** — they only build when `SWARM_INCLUDE_DEMO=1` is set:

```bash
SWARM_INCLUDE_DEMO=1 swift build
SWARM_INCLUDE_DEMO=1 swift run SwarmDemo
```

### Capability showcase

`SwarmCapabilityShowcase` is always built and exercises the stable surface area
in a deterministic matrix that is CI-safe:

```bash
swift run SwarmCapabilityShowcase list      # Enumerate scenarios
swift run SwarmCapabilityShowcase matrix    # Run the deterministic matrix
swift run SwarmCapabilityShowcase run handoff
swift run SwarmCapabilityShowcase smoke     # Live-provider, opt-in via env vars
```

See `docs/guide/capability-showcase.md` for the full scenario catalog and
smoke-mode environment variables.

### Lint / format

CI runs SwiftLint and SwiftFormat on macOS using the tracked root configs:
`.swiftlint.yml` and `.swiftformat`. Both commands are scoped to
`Sources` and `Tests` so ignored worktrees, dependency checkouts, generated
docs, and Node artifacts do not affect results. If you change Swift files,
match the surrounding style and assume both linters will run in CI.

To format using the SwiftFormat package plugin (per README):

```bash
swift package plugin --allow-writing-to-package-directory swiftformat
```

## Key Conventions

### Concurrency

- Swift 6.2 with `StrictConcurrency` is enabled on the main targets via
  `swarmSwiftSettings`. Macro and showcase targets enable
  `enableExperimentalFeature("StrictConcurrency")` directly.
- **All public types must be `Sendable`.** Don't suppress data-race diagnostics
  with `@unchecked Sendable` unless you have a documented reason.
- Use `actor` for stateful coordinators (e.g. `Conversation`,
  `InMemorySession`), `struct` for value types, and `AsyncThrowingStream` for
  streaming output.

### Agents

- The canonical initializer is `Agent(_ instructions: String, ...)` with an
  unlabeled instructions string and a trailing `@ToolBuilder` closure for
  tools. See `Sources/Swarm/Agents/Agent.swift`.
- Provider resolution order is documented at the top of `Agent.swift`:
  1. explicit provider passed in,
  2. `.environment(\.inferenceProvider, ...)`,
  3. `Swarm.defaultProvider`,
  4. `Swarm.cloudProvider`,
  5. Foundation Models (on-device),
  6. else throw `AgentError.inferenceProviderUnavailable`.
- The `Agent` struct is `Sendable`; tools are stored as `[any AnyJSONTool]`.

### Tools

- Prefer the `@Tool` macro over conforming to `AnyJSONTool` directly. The macro
  generates the JSON schema, parameter parsing, and output encoding.
- Use `@Parameter("description") var name: T` inside a `@Tool` struct.
- For one-off closure tools use `FunctionTool` with `ToolParameter` values.
- Multiple tools can be composed with `@ToolBuilder` (the trailing closure on
  `Agent.init`).

### Workflows

- `Workflow()` is a fluent builder; chain `.step`, `.parallel(_, merge:)`,
  `.route { ... }`, `.repeatUntil`, `.timeout`.
- Durable execution lives in `Workflow+Durable.swift` and
  `WorkflowDurableEngine.swift`. Use
  `.durable.checkpoint(id:policy:)` and `.durable.checkpointing(...)` to enable
  resume-from-checkpoint behavior.
- The `Internal/GraphRuntime` directory is the compiled DAG runtime — treat it
  as an implementation detail.

### Memory & Workspace

- `Memory` factory methods are the user-facing entry point:
  `.conversation(maxMessages:)`, `.slidingWindow(maxTokens:)`,
  `.summary(configuration:summarizer:)`, `.hybrid(configuration:summarizer:)`,
  `.persistent(backend:conversationId:maxMessages:)`, and
  `.vector(embeddingProvider:similarityThreshold:maxResults:)`.
- `AgentWorkspace` (in `Sources/Swarm/Workspace/`) is the on-device workspace
  layout backed by `AGENTS.md` + `.swarm/agents/<id>.md` + `.swarm/skills/` +
  `.swarm/memory/`. **Do not confuse the runtime `AGENTS.md` (workspace
  instructions consumed by Swarm) with this `CLAUDE.md` (briefing for AI coding
  assistants).** The runtime `AGENTS.md` is git-ignored at the repo root.
- Always call `try await workspace.validate()` from new tests that touch the
  workspace.

### Providers

- All inference goes through `InferenceProvider` adapters in
  `Sources/Swarm/Providers/`. Production providers are routed through
  [Conduit](https://github.com/christopherkarani/Conduit) (pinned to `0.3.14`
  in `Package.swift`) with traits enabled for OpenAI, OpenRouter, Anthropic,
  and MLX.
- Foundation Models are now also routed through Conduit (see commits
  `89d7ffa` and `6ae1df6`).

### Mocks & Test Helpers

- `Tests/SwarmTests/Mocks/` contains the canonical mocks: `MockAgentRuntime`,
  `MockInferenceProvider`, `MockAgentMemory`, `MockEmbeddingProvider`,
  `MockSummarizer`, `MockTool`, plus `SwarmConfigurationTestIsolation` for
  isolating `Swarm.defaultProvider`/`Swarm.configure(...)` between tests.
- New tests should reuse these mocks rather than reinventing local stubs.
- Tests that touch `Swarm.configure` global state must use the isolation helper
  to avoid cross-test pollution under `--no-parallel`.

## Development Workflow

1. **Read before you write.** The codebase is large (≈156 source files,
   ≈150 test files). Use `Grep` / `Glob` to find call sites before changing a
   public type.
2. **Mirror the source tree in tests.** A change in
   `Sources/Swarm/Workflow/Foo.swift` should land alongside or update
   `Tests/SwarmTests/Workflow/FooTests.swift`.
3. **Keep public surfaces `Sendable` and DocC-commented.** Public types in this
   package carry rich DocC comments — match that style on anything new.
4. **Don't over-engineer.** Per the project's documentation history, prefer
   small, surgical changes that preserve the existing public API. Audit reports
   live in `docs/reference/` (`api-catalog.md`, `front-facing-api.md`,
   `documentation-*.md`) — consult them before introducing new public types.
5. **Run the deterministic matrix.** Before opening a PR, run
   `swift run SwarmCapabilityShowcase matrix` in addition to `swift test` to
   catch regressions in cross-cutting scenarios.
6. **Never push to `main` directly.** Branch, run tests, open a PR.
7. **Do not commit `Package.resolved`.** It is git-ignored intentionally —
   Swarm is a library and consumers resolve their own dependency graph.

## Things That Are Git-Ignored (and Why)

The `.gitignore` deliberately excludes a number of paths AI assistants might
otherwise want to create or check in. **Do not work around these.**

- `.claude/`, `.mcp.json`, `.agent_context.md`, `AGENTS.md` — local AI tooling
  config, except `AGENTS.md`, which is intentionally tracked as the repo-level
  guardrail for future agents.
- `.swift-version` — contributors keep this locally; CI selects Swift through
  the workflow environment.
- `Package.resolved` — library, not application.
- `docs/plans/`, `docs/prompts/`, `docs/work-packages/`, `docs/validation/`,
  `tasks/`, `scripts/`, `IMPLEMENTATION_PLAN.md`,
  `HIVE_EXTENSIBILITY_INTEGRATION_PLAN.md`, `PRODUCTION_READINESS_AUDIT.md` —
  internal planning artifacts.
- `marketing/`, `website/`, VitePress build output.
- `docs/reference/*audit-report.md`, `docs/reference/documentation-*-report.md`,
  `docs/reference/documentation-improvement-plan.md`,
  `docs/reference/api-quality-assessment.md`,
  `docs/reference/twitter-article-*.md`, `docs/swarm-hacker-news-blog.md`,
  `docs/superpowers/` — internal audit, planning, and marketing artifacts.

`CLAUDE.md` itself was previously git-ignored; it has been intentionally
un-ignored so this guidance can live in-repo.

## Public API Stability

The framework is at `0.5.1` (`Sources/Swarm/Swarm.swift`) and treats its public
surface as semi-stable. The supported public reference documents are
`docs/reference/api-catalog.md`, `docs/reference/front-facing-api.md`, and
`docs/reference/overview.md`. Prefer:

- adding new types over breaking existing ones,
- adding new initializer overloads over changing parameter labels on existing
  ones,
- documenting deprecations rather than silently removing symbols.

## When You're Stuck

- For "what does X do?" questions, search `Sources/Swarm/<Area>/` first, then
  `docs/reference/api-catalog.md`.
- For workflow examples, read `Sources/SwarmCapabilityShowcaseSupport/CapabilityShowcase.swift`
  — it touches every stable subsystem.
- For provider behaviour, look at `Sources/Swarm/Providers/Conduit/` and the
  `LanguageModelSession*` files.
- The `README.md` quick-start, the `docs/guide/getting-started.md` tutorial,
  and `docs/guide/agent-workspace.md` are the user-facing canonical docs —
  keep code samples consistent with them when changing surface area.


================================================
FILE: Examples/CodeReviewer/.gitignore
================================================
.build/
.swiftpm/
*.resolved
DerivedData/


================================================
FILE: Examples/CodeReviewer/Package.swift
================================================
// swift-tools-version: 6.2

import PackageDescription

let package = Package(
    name: "CodeReviewer",
    platforms: [.macOS(.v26)],
    dependencies: [
        .package(name: "Swarm", path: "../../")
    ],
    targets: [
        .executableTarget(
            name: "CodeReviewer",
            dependencies: [
                .product(name: "Swarm", package: "Swarm")
            ],
            path: "Sources/CodeReviewer",
            swiftSettings: [
                .enableExperimentalFeature("StrictConcurrency")
            ]
        ),
        .testTarget(
            name: "CodeReviewerTests",
            dependencies: [
                .target(name: "CodeReviewer"),
                .product(name: "Swarm", package: "Swarm")
            ],
            path: "Tests/CodeReviewerTests",
            swiftSettings: [
                .enableExperimentalFeature("StrictConcurrency")
            ]
        )
    ]
)


================================================
FILE: Examples/CodeReviewer/Sources/CodeReviewer/Agents/.gitkeep
================================================


================================================
FILE: Examples/CodeReviewer/Sources/CodeReviewer/Output/.gitkeep
================================================


================================================
FILE: Examples/CodeReviewer/Sources/CodeReviewer/Output/StreamRenderer.swift
================================================
import Foundation

public enum AgentRole: Sendable {
    case security, performance, style, synthesizer

    var label: String {
        switch self {
        case .security:    return "[Security]"
        case .performance: return "[Performance]"
        case .style:       return "[Style]"
        case .synthesizer: return "[Summary]"
        }
    }

    var emoji: String {
        switch self {
        case .security:    return "🔴"
        case .performance: return "🟡"
        case .style:       return "🔵"
        case .synthesizer: return "🟢"
        }
    }

    var color: String {
        switch self {
        case .security:    return StreamRenderer.ANSICode.red
        case .performance: return StreamRenderer.ANSICode.yellow
        case .style:       return StreamRenderer.ANSICode.blue
        case .synthesizer: return StreamRenderer.ANSICode.green
        }
    }
}

public enum StreamRenderer {
    public enum ANSICode {
        public static let red    = "\u{001B}[31m"
        public static let yellow = "\u{001B}[33m"
        public static let blue   = "\u{001B}[34m"
        public static let green  = "\u{001B}[32m"
        public static let reset  = "\u{001B}[0m"
        public static let bold   = "\u{001B}[1m"
    }

    public static func format(_ text: String, agent: AgentRole) -> String {
        "\(agent.color)\(ANSICode.bold)\(agent.label)\(ANSICode.reset) \(agent.emoji)  \(text)"
    }

    public static func printToken(_ text: String, agent: AgentRole) {
        let formatted = "\(agent.color)\(text)\(ANSICode.reset)"
        print(formatted, terminator: "")
        fflush(stdout)
    }

    public static func printLine(_ text: String, agent: AgentRole) {
        print("\(agent.color)\(ANSICode.bold)\(agent.label)\(ANSICode.reset) \(agent.emoji)  \(text)")
    }

    public static func printDivider(_ title: String) {
        print("\n\(ANSICode.bold)── \(title) ──\(ANSICode.reset)\n")
    }
}


================================================
FILE: Examples/CodeReviewer/Sources/CodeReviewer/Tools/.gitkeep
================================================


================================================
FILE: Examples/CodeReviewer/Sources/CodeReviewer/main.swift
================================================
import Foundation
import Swarm

let arguments = CommandLine.arguments.dropFirst()
let request = try ReviewRequest(arguments: Array(arguments))

if request.showHelp {
    printUsage()
} else {
    let input = try request.loadInput()
    let report = ReviewReport(input: input, sourceDescription: request.sourceDescription)

    StreamRenderer.printDivider("CodeReviewer")
    StreamRenderer.printLine("Input: \(report.sourceDescription)", agent: .synthesizer)
    StreamRenderer.printLine("Lines: \(report.lineCount), characters: \(report.characterCount)", agent: .performance)

    StreamRenderer.printDivider("Review Plan")
    for focus in report.focusAreas {
        StreamRenderer.printLine(focus.message, agent: focus.role)
    }

    StreamRenderer.printDivider("Swarm")
    print("Linked Swarm \(Swarm.version). Configure an inference provider to turn this deterministic CLI into a live multi-agent review.")
}

private func printUsage() {
    print(
        """
        Usage:
          swift run CodeReviewer [file]
          cat diff.patch | swift run CodeReviewer

        The CLI prints a deterministic review plan for the provided file or stdin.
        """
    )
}

struct ReviewRequest {
    let path: String?
    let showHelp: Bool

    init(arguments: [String]) throws {
        if arguments.contains("--help") || arguments.contains("-h") {
            path = nil
            showHelp = true
            return
        }

        guard arguments.count <= 1 else {
            throw CLIError.tooManyArguments
        }

        path = arguments.first
        showHelp = false
    }

    var sourceDescription: String {
        path ?? "stdin"
    }

    func loadInput() throws -> String {
        if let path {
            return try String(contentsOfFile: path, encoding: .utf8)
        }

        let data = FileHandle.standardInput.readDataToEndOfFile()
        guard let input = String(data: data, encoding: .utf8) else {
            throw CLIError.invalidUTF8
        }
        return input
    }
}

struct ReviewReport {
    struct FocusArea {
        let role: AgentRole
        let message: String
    }

    let input: String
    let sourceDescription: String

    var lineCount: Int {
        input.isEmpty ? 0 : input.split(separator: "\n", omittingEmptySubsequences: false).count
    }

    var characterCount: Int {
        input.count
    }

    var focusAreas: [FocusArea] {
        [
            FocusArea(role: .security, message: "Check trust boundaries, secret handling, unsafe file/network access, and authorization assumptions."),
            FocusArea(role: .performance, message: "Check avoidable repeated work, unbounded input growth, blocking calls, and concurrency bottlenecks."),
            FocusArea(role: .style, message: "Check API clarity, naming, test seams, and whether the smallest maintainable change was made."),
            FocusArea(role: .synthesizer, message: "Return findings first with file and line references, then summarize residual test risk.")
        ]
    }
}

enum CLIError: Error, CustomStringConvertible {
    case invalidUTF8
    case tooManyArguments

    var description: String {
        switch self {
        case .invalidUTF8:
            "Input must be valid UTF-8."
        case .tooManyArguments:
            "Pass at most one file path."
        }
    }
}


================================================
FILE: Examples/CodeReviewer/Tests/CodeReviewerTests/Fixtures/.gitkeep
================================================


================================================
FILE: Examples/CodeReviewer/Tests/CodeReviewerTests/StreamRendererTests.swift
================================================
import Foundation
import Testing
@testable import CodeReviewer

@Suite("StreamRenderer")
struct StreamRendererTests {

    @Test("formats security prefix with red color")
    func securityPrefix() {
        let result = StreamRenderer.format("hello", agent: .security)
        #expect(result.contains("[Security]"))
        #expect(result.contains("hello"))
        #expect(result.contains(StreamRenderer.ANSICode.red))
    }

    @Test("formats performance prefix with yellow color")
    func performancePrefix() {
        let result = StreamRenderer.format("world", agent: .performance)
        #expect(result.contains("[Performance]"))
        #expect(result.contains(StreamRenderer.ANSICode.yellow))
    }

    @Test("formats style prefix with blue color")
    func stylePrefix() {
        let result = StreamRenderer.format("test", agent: .style)
        #expect(result.contains("[Style]"))
        #expect(result.contains(StreamRenderer.ANSICode.blue))
    }

    @Test("formats synthesizer prefix with green color")
    func synthesizerPrefix() {
        let result = StreamRenderer.format("summary", agent: .synthesizer)
        #expect(result.contains("[Summary]"))
        #expect(result.contains(StreamRenderer.ANSICode.green))
    }
}

@Suite("ReviewRequest")
struct ReviewRequestTests {
    @Test("parses help flag")
    func helpFlag() throws {
        let request = try ReviewRequest(arguments: ["--help"])
        #expect(request.showHelp)
        #expect(request.path == nil)
    }

    @Test("rejects too many arguments")
    func tooManyArguments() {
        #expect(throws: CLIError.tooManyArguments) {
            _ = try ReviewRequest(arguments: ["one.swift", "two.swift"])
        }
    }

    @Test("loads file input")
    func loadsFileInput() throws {
        let url = FileManager.default.temporaryDirectory
            .appendingPathComponent(UUID().uuidString)
            .appendingPathExtension("swift")
        try "let value = 1\n".write(to: url, atomically: true, encoding: .utf8)
        defer { try? FileManager.default.removeItem(at: url) }

        let request = try ReviewRequest(arguments: [url.path])

        #expect(request.sourceDescription == url.path)
        #expect(try request.loadInput() == "let value = 1\n")
    }
}

@Suite("ReviewReport")
struct ReviewReportTests {
    @Test("counts lines and characters")
    func countsLinesAndCharacters() {
        let report = ReviewReport(input: "one\ntwo\n", sourceDescription: "stdin")

        #expect(report.lineCount == 3)
        #expect(report.characterCount == 8)
        #expect(report.focusAreas.count == 4)
    }
}


================================================
FILE: LICENSE
================================================
MIT License

Copyright (c) 2025 Christopher Karani

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


================================================
FILE: Package.swift
================================================
// swift-tools-version: 6.2
import PackageDescription
import CompilerPluginSupport
import Foundation
let includeDemo = ProcessInfo.processInfo.environment["SWARM_INCLUDE_DEMO"] == "1"
let coreOnly = ProcessInfo.processInfo.environment["SWARM_CORE_ONLY"] == "1"

var packageProducts: [Product] = [
    .library(name: "Swarm", targets: ["Swarm"]),
    .library(name: "SwarmOpenTelemetry", targets: ["SwarmOpenTelemetry"]),
    .library(name: "SwarmMembrane", targets: ["SwarmMembrane"]),
    .library(name: "SwarmMCP", targets: ["SwarmMCP"]),
]

if includeDemo {
    packageProducts.append(.executable(name: "SwarmDemo", targets: ["SwarmDemo"]))
    packageProducts.append(.executable(name: "SwarmMCPServerDemo", targets: ["SwarmMCPServerDemo"]))
}

var packageDependencies: [Package.Dependency] = [
    // swift-syntax range is intentionally widened to include 601/602 lines.
    //
    // Background: Xcode 26 (Swift 6.2.x) ships implicit SwiftPM prebuilts for
    // swift-syntax via the swiftlang "MacroSupport" prebuilt server. The 600.0.1
    // prebuilt is built against an older macOS SDK and fails to load on consumer
    // machines with "SDK does not match" warnings followed by
    // "Unable to find module dependency: 'SwiftSyntax'" errors. That prebuilt
    // download cannot be disabled from a consumer project (SWIFT_USE_PREBUILT_MACROS=NO,
    // IDESwiftPackageEnablePrebuilts=NO, SWIFTPM_DISABLE_PREBUILTS=1 and
    // -skipMacroValidation all fail to suppress it). Widening the range here lets
    // SwiftPM resolve to 601+ on Swift 6.2 toolchains, which does not ship the
    // broken prebuilt. Keep the upper bound below 603 while Conduit 0.3.x is
    // the latest compatible release line used by Swarm and Membrane.
    .package(url: "https://github.com/swiftlang/swift-syntax.git", "600.0.0"..<"603.0.0"),
    .package(url: "https://github.com/apple/swift-log.git", from: "1.12.0"),
    .package(url: "https://github.com/modelcontextprotocol/swift-sdk.git", from: "0.12.1"),
    .package(url: "https://github.com/open-telemetry/opentelemetry-swift-core.git", from: "2.4.1"),
    .package(url: "https://github.com/scinfu/SwiftSoup.git", from: "2.13.5"),
]

let integrationTrait = "Integrations"
if !coreOnly {
    packageDependencies += [
        // Production graph must resolve to the published tag set that is known to build together.
        .package(url: "https://github.com/christopherkarani/Wax.git", exact: "0.1.23"),
        .package(
            url: "https://github.com/christopherkarani/Conduit",
            exact: "0.3.16",
            traits: [
                .trait(name: "OpenAI"),
                .trait(name: "OpenRouter"),
                .trait(name: "Anthropic"),
                .trait(name: "MLX"),
            ]
        ),
        .package(url: "https://github.com/christopherkarani/ContextCore.git", exact: "1.0.0"),
        .package(url: "https://github.com/christopherkarani/Membrane", exact: "0.1.3"),
        .package(url: "https://github.com/christopherkarani/Hive", exact: "0.2.1"),
    ]
}

var swarmDependencies: [Target.Dependency] = [
    "SwarmMacros",
    .product(name: "Logging", package: "swift-log"),
    .product(name: "SwiftSoup", package: "SwiftSoup"),
]

var swarmSwiftSettings: [SwiftSetting] = [
    .enableExperimentalFeature("StrictConcurrency"),
]

if !coreOnly {
    swarmDependencies += [
        .product(name: "Wax", package: "Wax", condition: .when(traits: [integrationTrait])),
        .product(name: "Conduit", package: "Conduit", condition: .when(traits: [integrationTrait])),
        .product(name: "ConduitAdvanced", package: "Conduit", condition: .when(traits: [integrationTrait])),
        .product(name: "ContextCore", package: "ContextCore", condition: .when(traits: [integrationTrait])),
        .product(name: "HiveCore", package: "Hive", condition: .when(traits: [integrationTrait])),
        .product(name: "Membrane", package: "Membrane", condition: .when(traits: [integrationTrait])),
        .product(name: "MembraneCore", package: "Membrane", condition: .when(traits: [integrationTrait])),
        .product(name: "MembraneHive", package: "Membrane", condition: .when(traits: [integrationTrait])),
    ]
    swarmSwiftSettings.append(.define("SWARM_INTEGRATIONS", .when(traits: [integrationTrait])))
}

let swarmCoreOnlyExcludes = [
    "Integration/Wax",
    "Integration/Membrane/SessionMembraneAgentAdapter.swift",
    "Integration/Membrane/WaxMembraneStorage.swift",
    "Internal/GraphRuntime",
    "Memory/ContextCoreMemory.swift",
    "Memory/DefaultAgentMemory.swift",
    "Providers/Conduit",
    "Tools/Web",
    "Workflow/WorkflowCheckpointCodec.swift",
    "Workflow/WorkflowCheckpointStore.swift",
    "Workflow/WorkflowDurableEngine.swift",
]

var packageTargets: [Target] = [
    // MARK: - Macro Implementation (Compiler Plugin)
    .macro(
        name: "SwarmMacros",
        dependencies: [
            .product(name: "SwiftSyntax", package: "swift-syntax"),
            .product(name: "SwiftSyntaxMacros", package: "swift-syntax"),
            .product(name: "SwiftCompilerPlugin", package: "swift-syntax"),
            .product(name: "SwiftSyntaxBuilder", package: "swift-syntax")
        ],
        swiftSettings: [
            .enableExperimentalFeature("StrictConcurrency")
        ]
    ),

    // MARK: - Main Library
    .target(
        name: "Swarm",
        dependencies: swarmDependencies,
        exclude: coreOnly ? swarmCoreOnlyExcludes : [],
        swiftSettings: swarmSwiftSettings
    ),
    .target(
        name: "SwarmOpenTelemetry",
        dependencies: [
            "Swarm",
            .product(name: "OpenTelemetryApi", package: "opentelemetry-swift-core"),
        ],
        swiftSettings: swarmSwiftSettings
    ),
    .target(
        name: "SwarmMembrane",
        dependencies: [
            "Swarm",
        ],
        path: "Sources/SwarmMembrane",
        swiftSettings: swarmSwiftSettings
    ),
    .target(
        name: "SwarmMCP",
        dependencies: [
            "Swarm",
            .product(name: "MCP", package: "swift-sdk"),
        ],
        swiftSettings: swarmSwiftSettings
    ),
    .target(
        name: "SwarmCapabilityShowcaseSupport",
        dependencies: [
            "Swarm",
            "SwarmMCP",
        ],
        swiftSettings: swarmSwiftSettings
    ),
    .executableTarget(
        name: "SwarmCapabilityShowcase",
        dependencies: [
            "SwarmCapabilityShowcaseSupport",
        ],
        swiftSettings: [
            .enableExperimentalFeature("StrictConcurrency")
        ]
    ),

    // MARK: - Tests
    .testTarget(
        name: "SwarmTests",
        dependencies: {
            var dependencies: [Target.Dependency] = [
                "Swarm",
                "SwarmMCP",
            ]
            if !coreOnly {
                dependencies += [
                    .product(name: "Conduit", package: "Conduit"),
                    .product(name: "ConduitAdvanced", package: "Conduit"),
                    .product(name: "Membrane", package: "Membrane"),
                    .product(name: "MembraneCore", package: "Membrane"),
                ]
            }
            return dependencies
        }(),
        resources: [],
        swiftSettings: swarmSwiftSettings
    ),
    .testTarget(
        name: "SwarmMacrosTests",
        dependencies: [
            "Swarm",
            "SwarmMacros",
            .product(name: "SwiftSyntaxMacrosTestSupport", package: "swift-syntax")
        ],
        swiftSettings: [
            .enableExperimentalFeature("StrictConcurrency")
        ]
    ),
    .testTarget(
        name: "SwarmCapabilityShowcaseTests",
        dependencies: [
            "SwarmCapabilityShowcaseSupport",
        ],
        swiftSettings: [
            .enableExperimentalFeature("StrictConcurrency")
        ]
    ),
    .testTarget(
        name: "SwarmOpenTelemetryTests",
        dependencies: [
            "Swarm",
            "SwarmOpenTelemetry",
            .product(name: "OpenTelemetrySdk", package: "opentelemetry-swift-core"),
        ],
        swiftSettings: swarmSwiftSettings
    )
]

if !coreOnly {
    packageTargets.append(
        .testTarget(
            name: "HiveSwarmTests",
            dependencies: [
                "Swarm",
                .product(name: "HiveCore", package: "Hive")
            ],
            swiftSettings: swarmSwiftSettings
        )
    )
}

if includeDemo {
    packageTargets.append(
        .executableTarget(
            name: "SwarmDemo",
            dependencies: ["Swarm"],
            swiftSettings: [
                .enableExperimentalFeature("StrictConcurrency")
            ]
        )
    )

    packageTargets.append(
        .executableTarget(
            name: "SwarmMCPServerDemo",
            dependencies: [
                "Swarm",
                "SwarmMCP",
            ],
            swiftSettings: [
                .enableExperimentalFeature("StrictConcurrency")
            ]
        )
    )
}

let package = Package(
    name: "Swarm",
    platforms: [
        .macOS(.v26),
        .iOS(.v26),
        .tvOS(.v26),
    ],
    products: packageProducts,
    traits: [
        .default(enabledTraits: [integrationTrait]),
        .trait(
            name: integrationTrait,
            description: "Enable provider, memory, graph runtime, Wax, Membrane, ContextCore, Conduit, and Hive integrations."
        ),
    ],
    dependencies: packageDependencies,
    targets: packageTargets
)


================================================
FILE: README.md
================================================
<div align="center">
  <img alt="Swarm Swift Agent Framework" src="docs/public/banner.svg" />

  <p><strong>A Swift framework for building agents and multi-agent workflows.</strong></p>

  <p>
    <a href="https://swift.org"><img src="https://img.shields.io/badge/Swift-6.2-orange.svg" alt="Swift 6.2" /></a>
    <a href="https://swift.org"><img src="https://img.shields.io/badge/Platforms-iOS%2026%2B%20|%20macOS%2026%2B%20|%20Linux-blue.svg" alt="Platforms" /></a>
    <a href="LICENSE"><img src="https://img.shields.io/badge/License-MIT-green.svg" alt="License: MIT" /></a>
    <a href="https://swift.org/package-manager/"><img src="https://img.shields.io/badge/SPM-compatible-brightgreen.svg" alt="SPM Compatible" /></a>
    <a href="https://discord.gg/NHgNh7HJ6M"><img src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fdiscord.com%2Fapi%2Fv10%2Finvites%2FNHgNh7HJ6M%3Fwith_counts%3Dtrue&query=%24.approximate_presence_count&suffix=%20online&logo=discord&label=Discord&color=5865F2&style=flat" alt="Discord" /></a>
  </p>
</div>

```swift
let result = try await Workflow()
    .step(researchAgent)
    .step(writerAgent)
    .run("Summarize the latest WWDC session on Swift concurrency.")
```

<div align="center">
  <img alt="Swarm API Flow" src="docs/public/api-flow.gif" width="600" />
</div>

Two agents, one pipeline, compiled to a DAG with crash recovery and Swift concurrency safety.

## Install

```swift
.package(url: "https://github.com/christopherkarani/Swarm.git", from: "0.4.10")
```


## Quick Start

```swift
import Swarm

// The @Tool macro generates the JSON schema at compile time
@Tool("Looks up the current stock price")
struct PriceTool {
    @Parameter("Ticker symbol") var ticker: String
    func execute() async throws -> String { "182.50" }
}

// Create an agent with unlabeled instructions first and tools in the trailing @ToolBuilder closure
let agent = try Agent("Answer finance questions using real data.",
    configuration: .init(name: "Analyst"),
    inferenceProvider: .anthropic(key: "sk-...")) {
    PriceTool()
    CalculatorTool()
}

let result = try await agent.run("What is AAPL trading at?")
print(result.output) // "Apple (AAPL) is currently trading at $182.50."
```

That is a working agent with type-safe tool calling. Swarm also supports **AGENTS.md** and **SKILL.md** for declarative agent specs and reusable skills — see the [Getting Started guide](docs/guide/getting-started.md) for the full workspace layout.

## Why Swarm

- **Swift concurrency is part of the surface.** Swift 6.2 `StrictConcurrency` is enabled across the package.
- **Tools stay type-safe.** The `@Tool` macro generates JSON schemas from Swift structs.
- **Workflows can survive crashes.** Durable workflow checkpointing lets you resume from an explicit checkpoint ID.
- **Cloud and on-device models use the same abstractions.** Foundation Models, Anthropic, OpenAI, Ollama, Gemini, MiniMax, OpenRouter, and MLX all fit the same shape.
- **It is written in Swift all the way down.** `AsyncThrowingStream`, actors, result builders, and macros are first-class here.

## Examples

### Capability matrix showcase

Swarm now ships with an in-repo capability showcase that exercises the stable surface area in one deterministic matrix:

- agents and tools
- streaming
- conversation plus session persistence
- sequential, parallel, routed, and repeat-until workflows
- handoffs
- memory
- on-device workspace loading
- guardrails
- resilience helpers
- durable checkpoint and resume
- observability
- MCP discovery and tool bridging
- provider selection

Run it locally:

```bash
swift run SwarmCapabilityShowcase list
swift run SwarmCapabilityShowcase matrix
swift run SwarmCapabilityShowcase run handoff
swift run SwarmCapabilityShowcase smoke
```

The deterministic matrix is CI-safe. Live-provider smoke coverage is opt-in through environment variables. See [docs/guide/capability-showcase.md](docs/guide/capability-showcase.md) for the scenario catalog and smoke-mode details.

### Optional demos

Demo executables are opt-in so the default library graph stays focused on the framework products:

```bash
SWARM_INCLUDE_DEMO=1 swift build
SWARM_INCLUDE_DEMO=1 swift run SwarmDemo
SWARM_INCLUDE_DEMO=1 swift run SwarmMCPServerDemo
```

### Multi-agent pipeline

```swift
let researcher = try Agent("Research the topic and extract key facts.",
    inferenceProvider: .anthropic(key: "sk-...")) {
    WebSearchTool()
}

let writer = try Agent("Write a concise summary from the research.",
    inferenceProvider: .anthropic(key: "sk-..."))

let result = try await Workflow()
    .step(researcher)
    .step(writer)
    .run("Latest advances in on-device ML")
```

Each agent resolves its own provider. Pass `inferenceProvider:` per agent (as above), or call `await Swarm.configure(provider: .anthropic(apiKey: "..."))` once at app startup to share a default across every agent that doesn't specify one.

### Parallel fan-out

```swift
let result = try await Workflow()
    .parallel([bullAgent, bearAgent, analystAgent], merge: .structured)
    .run("Evaluate Apple's Q4 earnings.")
// Three perspectives, merged into one output.
```

### Dynamic routing

```swift
let result = try await Workflow()
    .route { input in
        if input.contains("$") { return mathAgent }
        if input.contains("weather") { return weatherAgent }
        return generalAgent
    }
    .run("What is 15% of $240?")
```

### Streaming

```swift
for try await event in agent.stream("Summarize the changelog.") {
    switch event {
    case .output(.token(let t)):           print(t, terminator: "")
    case .tool(.completed(let call, _)):   print("\n[tool: \(call.toolName)]")
    case .lifecycle(.completed(let r)):     print("\nDone in \(r.duration)")
    case .lifecycle(.failed(let error)):    print("\nError: \(error)")
    default: break // Other events include .output(.thinking(...)), .handoff(...), .observation(...), and .lifecycle(.iterationStarted(...)).
    }
}
```

<details>
<summary><strong>More examples</strong></summary>

#### Semantic memory

```swift
let agent = try Agent("You remember past conversations.",
    inferenceProvider: .anthropic(key: "sk-..."),
    memory: .vector(embeddingProvider: myEmbedder, similarityThreshold: 0.75)) {
    // tools
}
```

#### Guardrails

```swift
let agent = try Agent("You are a helpful assistant.",
    inputGuardrails: [InputGuard.maxLength(5000), InputGuard.notEmpty()],
    outputGuardrails: [OutputGuard.maxLength(2000)])
```

#### Closure tools

```swift
let reverse = FunctionTool(
    name: "reverse",
    description: "Reverses a string",
    parameters: [ToolParameter(name: "text", description: "Text to reverse", type: .string, isRequired: true)]
) { args in
    let text = try args.require("text", as: String.self)
    return .string(String(text.reversed()))
}

let agent = try Agent("Text utilities.", tools: [reverse])
```

#### Crash-resumable workflows

```swift
let workflow = Workflow()
    .step(monitor)
    .durable.checkpoint(id: "monitor-v1", policy: .everyStep)
    .durable.checkpointing(.fileSystem(directory: checkpointsURL))

let resumed = try await workflow.durable.execute("watch", resumeFrom: "monitor-v1")
```

#### Provider switching

```swift
// On-device, private, no API key needed
let local = try Agent("Be helpful.", inferenceProvider: .foundationModels())

// Cloud
let cloud = try Agent("Be helpful.", inferenceProvider: .anthropic(key: k))

// Or swap at runtime via environment
let modified = agent.environment(\.inferenceProvider, .ollama(model: "mistral"))
```

#### Conversation

```swift
let conversation = Conversation(with: agent)

let response1 = try await conversation.send("What's the weather?")
let response2 = try await conversation.send("And tomorrow?") // Context preserved

for message in await conversation.messages {
    print("\(message.role): \(message.text)")
}
```

</details>

## How Swarm Compares

| | **Swarm** | LangChain | AutoGen |
|---|---|---|---|
| **Language** | Swift 6.2 | Python | Python |
| **Data race safety** | Compile-time | Runtime | Runtime |
| **On-device LLM** | Foundation Models | n/a | n/a |
| **Execution model** | Typed `Workflow` graph | Loop-based | Loop-based |
| **Crash recovery** | Checkpoints | n/a | Partial |
| **Type-safe tools** | `@Tool` macro (compile-time) | Decorators (runtime) | Runtime |
| **Streaming** | `AsyncThrowingStream` | Callbacks | Callbacks |
| **iOS / macOS native** | First-class | n/a | n/a |

## What's Included

| | |
|---|---|
| **Agents** | `Agent` struct with `@ToolBuilder` trailing closure, `AgentRuntime` protocol |
| **Workflows** | `Workflow`: `.step()`, `.parallel()`, `.route()`, `.repeatUntil()`, `.timeout()` |
| **Tools** | `@Tool` macro, `FunctionTool`, `@ToolBuilder`, parallel execution |
| **Memory** | `.conversation(maxMessages:)`, `.vector(embeddingProvider:similarityThreshold:maxResults:)`, `.slidingWindow(maxTokens:)`, `.summary(configuration:summarizer:)`, `.hybrid(configuration:summarizer:)` |
| **Guardrails** | `InputGuard.maxLength()`, `InputGuard.notEmpty()`, `InputGuard.custom()`, `OutputGuard.maxLength()`, `OutputGuard.custom()` |
| **Conversation** | `Conversation` actor for stateful multi-turn dialogue |
| **Resilience** | 7 backoff strategies, circuit breaker, fallback chains, rate limiting |
| **Observability** | `AgentObserver`, `Tracer`, `SwiftLogTracer`, per-agent token metrics |
| **MCP** | Model Context Protocol client and server support |
| **Providers** | Foundation Models, Anthropic, OpenAI, Ollama, Gemini, MiniMax, OpenRouter, MLX via [Conduit](https://github.com/christopherkarani/Conduit) |
| **Macros** | `@Tool`, `@Parameter`, `@Traceable`, `#Prompt` |

## Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                      Your Application                       │
│          iOS 26+  ·  macOS 26+  ·  Linux (Ubuntu 22.04+)   │
├─────────────────────────────────────────────────────────────┤
│     Workflow  ·  Conversation  ·  .run()  ·  .stream()      │
├─────────────────────────────────────────────────────────────┤
│  Agents              Memory              Tools              │
│  Agent (struct)      Memory factories    @Tool macro        │
│  AgentRuntime        Conversation        FunctionTool       │
│                      (dot-syntax)        @ToolBuilder       │
├─────────────────────────────────────────────────────────────┤
│  InputGuard · OutputGuard · Resilience · Observability · MCP│
├─────────────────────────────────────────────────────────────┤
│              Durable Graph Runtime (internal)               │
│   Workflow Graph  ·  Checkpointing  ·  Deterministic retry │
├─────────────────────────────────────────────────────────────┤
│              InferenceProvider (pluggable)                   │
│ Foundation Models · Anthropic · OpenAI · Ollama · OpenRouter│
└─────────────────────────────────────────────────────────────┘
```

## Requirements

| Platform | Minimum |
|----------|---------|
| Swift    | 6.2+    |
| iOS      | 26.0+   |
| macOS    | 26.0+   |
| tvOS     | 26.0+   |
| Linux    | Ubuntu 22.04+ with Swift 6.2 |

The default Swarm graph is CI-tested on Ubuntu with Swift 6.2. Apple-only features such as Foundation Models, SwiftData, OSLog, and some built-in tool behavior are unavailable or different on Linux; cloud providers and Ollama use the shared `InferenceProvider` surface.

## Documentation

| | |
|---|---|
| [Getting Started](docs/guide/getting-started.md) | Installation, first agent, workflows |
| [OpenTelemetry Tracing](docs/guide/opentelemetry-tracing.md) | Export agent and LLM spans, with optional trace header injection for provider HTTP requests |
| [API Reference](docs/reference/api-catalog.md) | Every type, protocol, and API |
| [Front-Facing API](docs/reference/front-facing-api.md) | Public API surface |
| [Why Swarm?](docs/guide/why-swarm.md) | Design philosophy and architecture |

## Contributing

1. Fork → branch → `swift test` → PR
2. All public types must be `Sendable`; the compiler enforces it
3. Format with `swiftformat Sources Tests --lint --config .swiftformat`

Bug reports and feature requests: [GitHub Issues](https://github.com/christopherkarani/Swarm/issues)

## Community

[GitHub Issues](https://github.com/christopherkarani/Swarm/issues) · [Discussions](https://github.com/christopherkarani/Swarm/discussions) · [@ckarani7](https://x.com/ckarani7)

If Swarm saves you time, [a star](https://github.com/christopherkarani/Swarm) helps others find it.

## License

Released under the [MIT License](LICENSE).


================================================
FILE: Sources/Swarm/Agents/Agent+Workspace.swift
================================================
import Foundation

public extension Agent {
    /// Creates an on-device agent with the recommended defaults and optional workspace-backed memory.
    static func onDevice(
        _ instructions: String,
        workspace: AgentWorkspace? = nil,
        configuration: AgentConfiguration = .onDeviceDefault,
        inferenceProvider: (any InferenceProvider)? = nil,
        @ToolBuilder tools: () -> ToolCollection = { .empty }
    ) throws -> Agent {
        let builtTools = tools().storage
        let globalInstructions = try workspace?.loadAgentInstructions() ?? ""
        let combinedInstructions = [globalInstructions, instructions]
            .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
            .filter { !$0.isEmpty }
            .joined(separator: "\n\n")
        let memory: (any Memory)? = if let workspace {
            try Self.workspaceMemory(
                workspace: workspace,
                activatedSkills: [],
                cacheNamespace: "on-device"
            )
        } else {
            nil
        }
        return try Agent(
            tools: builtTools,
            instructions: combinedInstructions,
            configuration: configuration,
            memory: memory,
            inferenceProvider: inferenceProvider
        )
    }

    /// Creates an on-device agent from an AgentWorkspace spec file.
    static func spec(
        _ id: String,
        in workspace: AgentWorkspace,
        configuration: AgentConfiguration = .onDeviceDefault,
        inferenceProvider: (any InferenceProvider)? = nil,
        @ToolBuilder tools: () -> ToolCollection = { .empty }
    ) throws -> Agent {
        let spec = try workspace.loadAgentSpec(id: id)
        let skills = try workspace.loadSkills(named: spec.skills)
        let globalInstructions = try workspace.loadAgentInstructions()
        let builtTools = tools().storage

        let combinedInstructions = [globalInstructions, spec.body]
            .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
            .filter { !$0.isEmpty }
            .joined(separator: "\n\n")

        return try Agent(
            tools: filterTools(builtTools, using: skills),
            instructions: combinedInstructions,
            configuration: configuration.name(spec.title),
            memory: try workspaceMemory(
                workspace: workspace,
                activatedSkills: skills,
                cacheNamespace: spec.id
            ),
            inferenceProvider: inferenceProvider
        )
    }
}

private extension Agent {
    static func workspaceMemory(
        workspace: AgentWorkspace,
        activatedSkills: [WorkspaceSkill],
        cacheNamespace: String
    ) throws -> any Memory {
        CompositeMemory([
            try makeWorkspaceDefaultMemory(workspace: workspace, cacheNamespace: cacheNamespace),
            WorkspaceMemory(workspace: workspace, activatedSkills: activatedSkills),
        ])
    }

    static func makeWorkspaceDefaultMemory(
        workspace: AgentWorkspace,
        cacheNamespace: String
    ) throws -> any Memory {
        let memoryDirectory = workspace.indexCacheRoot
            .appendingPathComponent("default-agent-memory", isDirectory: true)
            .appendingPathComponent(safeCacheNamespace(cacheNamespace), isDirectory: true)
        try FileManager.default.createDirectory(at: memoryDirectory, withIntermediateDirectories: true)

        #if SWARM_INTEGRATIONS
        return try DefaultAgentMemory(configuration: DefaultAgentMemory.Configuration(
            waxStoreURL: memoryDirectory.appendingPathComponent("wax-memory.mv2s")
        ))
        #else
        return SlidingWindowMemory()
        #endif
    }

    static func safeCacheNamespace(_ rawValue: String) -> String {
        let allowed = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "-_"))
        let sanitizedScalars = rawValue.unicodeScalars.map { scalar in
            allowed.contains(scalar) ? Character(scalar) : "-"
        }
        let sanitized = String(sanitizedScalars)
            .trimmingCharacters(in: CharacterSet(charactersIn: "-_"))
        return sanitized.isEmpty ? "agent" : sanitized
    }

    static func filterTools(_ tools: [any AnyJSONTool], using skills: [WorkspaceSkill]) -> [any AnyJSONTool] {
        let constrainedSkillLists = skills
            .map(\.allowedTools)
            .filter { !$0.isEmpty }

        guard !constrainedSkillLists.isEmpty else {
            return tools
        }

        let allowedToolNames = Set(constrainedSkillLists.flatMap(\.self))

        return tools.filter { allowedToolNames.contains($0.name) }
    }
}


================================================
FILE: Sources/Swarm/Agents/Agent.swift
================================================
// Agent.swift
// Swarm Framework
//
// Tool-calling agent that uses structured LLM tool calling APIs.

import Foundation

// MARK: - Agent

/// An agent that uses structured LLM tool calling APIs for reliable tool invocation.
///
/// Unlike Agent which parses tool calls from text output, Agent
/// leverages the LLM's native tool calling capabilities via `generateWithToolCalls()`
/// for more reliable and type-safe tool invocation.
///
/// If no inference provider is configured, Agent will try to use Apple Foundation Models
/// (on-device) when available. If Foundation Models are unavailable and no provider is set,
/// Agent throws `AgentError.inferenceProviderUnavailable`.
///
/// Provider resolution order is:
/// 1. Apple Foundation Models when `inferencePolicy.privacyRequired` is true
/// 2. An explicit provider passed to `Agent(...)` (including `Agent(_:)`)
/// 3. A provider set via `.environment(\.inferenceProvider, ...)`
/// 4. `Swarm.cloudProvider` (set via `Swarm.configure(cloudProvider:)`, when tool calling is required)
/// 5. `Swarm.defaultProvider` (set via `Swarm.configure(provider:)`)
/// 6. Apple Foundation Models (on-device), if available, including prompt-based tool emulation
/// 7. Otherwise, throw `AgentError.inferenceProviderUnavailable`
///
/// The agent follows a loop-based execution pattern:
/// 1. Build prompt with system instructions + conversation history
/// 2. Call provider with tool schemas
/// 3. If tool calls requested, execute each tool and add results to history
/// 4. If no tool calls, return content as final answer
/// 5. Repeat until done or max iterations reached
///
/// Example:
/// ```swift
/// let agent = Agent(
///     tools: [WeatherTool(), CalculatorTool()],
///     instructions: "You are a helpful assistant with access to tools."
/// )
///
/// let result = try await agent.run("What's the weather in Tokyo?")
/// print(result.output)
/// ```
public struct Agent: AgentRuntime, Sendable {
    // MARK: Public

    // MARK: - Agent Protocol Properties

    /// The tools available to this agent for function calling.
    ///
    /// Tools are registered at initialization and remain immutable throughout the agent's lifetime.
    /// The agent uses these tool schemas to inform the LLM about available capabilities.
    ///
    /// To add tools, use the ``init(_:configuration:memory:inferenceProvider:tracer:inputGuardrails:outputGuardrails:guardrailRunnerConfiguration:handoffs:tools:)`` initializer
    /// with a `@ToolBuilder` closure, or the ``Builder`` API.
    ///
    /// ## Tool Execution
    /// When the LLM requests a tool call, the agent executes the corresponding tool
    /// and returns the result to the LLM for further processing.
    public private(set) var tools: [any AnyJSONTool]

    /// The system instructions that define this agent's behavior and capabilities.
    ///
    /// Instructions are sent to the LLM with every request to guide the agent's responses,
    /// personality, and decision-making. They describe what the agent should do, how it
    /// should behave, and any constraints it should follow.
    ///
    /// If no instructions are provided, a default instruction set is used:
    /// `"You are a helpful AI assistant with access to tools."`
    ///
    /// ## Example Instructions
    /// ```swift
    /// "You are a weather assistant. Be concise and friendly."
    /// ```
    ///
    /// To set instructions, use any of the ``Agent`` initializers or the ``Builder/instructions(_:)`` method.
    public private(set) var instructions: String

    /// The runtime configuration settings for this agent.
    ///
    /// Configuration controls agent behavior such as maximum iterations, timeout duration,
    /// streaming preferences, and the agent's display name. Use this to customize
    /// how the agent executes during a run.
    ///
    /// ## Default Configuration
    /// If not specified, the agent uses ``AgentConfiguration/default`` which provides
    /// sensible defaults for most use cases.
    ///
    /// ## Customizing Configuration
    /// ```swift
    /// let config = AgentConfiguration.default
    ///     .maxIterations(10)
    ///     .timeout(.seconds(30))
    ///
    /// let agent = Agent(instructions: "Helpful assistant", configuration: config)
    /// ```
    ///
    /// See ``AgentConfiguration`` for all available configuration options.
    public private(set) var configuration: AgentConfiguration

    /// The explicitly configured memory system for conversation history and context retrieval.
    ///
    /// When configured, the agent uses memory to:
    /// - Retrieve relevant context from previous conversations (RAG)
    /// - Store conversation summaries for long-term context
    /// - Provide additional context to the LLM beyond the current session
    ///
    /// ## Memory vs Session
    /// - **Memory**: Provides additional context (RAG, summaries) - not for conversation storage
    /// - **Session**: Stores the actual conversation history and is the source of truth for transcripts
    ///
    /// If no explicit memory is set, Swarm still uses a composite default memory
    /// internally: ContextCore for working context and Wax for durable recall.
    /// This property only reflects an explicit override.
    ///
    /// ## Setting Memory
    /// Use ``init(_:configuration:memory:inferenceProvider:tracer:inputGuardrails:outputGuardrails:guardrailRunnerConfiguration:handoffs:tools:)``
    /// or the ``Builder/memory(_:)`` method.
    ///
    /// See ``Memory`` for available memory implementations.
    public private(set) var memory: (any Memory)?
    private let defaultMemory: (any Memory)?

    /// The optional custom inference provider for LLM requests.
    ///
    /// The inference provider determines which LLM backend the agent uses for generating
    /// responses. If not set, the agent follows a resolution order to find a provider:
    ///
    /// 1. Apple Foundation Models when `configuration.inferencePolicy.privacyRequired` is true
    /// 2. Explicit provider passed to ``Agent`` initialization
    /// 3. Provider set via `.environment(\.inferenceProvider, ...)`
    /// 4. ``Swarm/cloudProvider`` (configured via `Swarm.configure(cloudProvider:)`, when tool calling is required)
    /// 5. ``Swarm/defaultProvider`` (configured via `Swarm.configure(provider:)`)
    /// 6. Apple Foundation Models (on-device), if available
    /// 7. Throws ``AgentError/inferenceProviderUnavailable``
    ///
    /// ## Usage
    /// Set a specific provider when you want this agent to use a different LLM than
    /// the globally configured one.
    public private(set) var inferenceProvider: (any InferenceProvider)?

    /// The input validation guardrails for this agent.
    ///
    /// Input guardrails validate user input before it's processed by the agent.
    /// They can reject inappropriate requests, check for safety concerns, or enforce
    /// business rules before the LLM is invoked.
    ///
    /// Guardrails are executed in order during ``run(_:session:observer:)`` and
    /// ``stream(_:session:observer:)`` before any LLM calls are made.
    ///
    /// ## Adding Guardrails
    /// Use the ``Builder/inputGuardrails(_:)`` or ``Builder/addInputGuardrail(_:)`` methods.
    ///
    /// See ``InputGuardrail`` for creating custom guardrails.
    public private(set) var inputGuardrails: [any InputGuardrail]

    /// The output validation guardrails for this agent.
    ///
    /// Output guardrails validate the agent's responses before they are returned to the user.
    /// They can check for harmful content, enforce output format requirements, or
    /// validate that the response meets quality standards.
    ///
    /// Guardrails are executed after the LLM generates a response but before it's
    /// returned in ``run(_:session:observer:)``.
    ///
    /// ## Adding Guardrails
    /// Use the ``Builder/outputGuardrails(_:)`` or ``Builder/addOutputGuardrail(_:)`` methods.
    ///
    /// See ``OutputGuardrail`` for creating custom guardrails.
    public private(set) var outputGuardrails: [any OutputGuardrail]

    /// The optional tracer for observability and debugging.
    ///
    /// When configured, the tracer receives events throughout the agent's execution,
    /// including LLM calls, tool executions, and timing information. This enables
    /// monitoring, debugging, and performance analysis.
    ///
    /// If not set but ``AgentConfiguration/defaultTracingEnabled`` is `true`,
    /// a default ``SwiftLogTracer`` is automatically created.
    ///
    /// ## Setting a Tracer
    /// Use ``init(_:configuration:memory:inferenceProvider:tracer:inputGuardrails:outputGuardrails:guardrailRunnerConfiguration:handoffs:tools:)``
    /// or the ``Builder/tracer(_:)`` method.
    ///
    /// See ``Tracer`` for the protocol definition and available implementations.
    public private(set) var tracer: (any Tracer)?

    /// The configuration for the guardrail runner.
    ///
    /// This configuration controls how input and output guardrails are executed,
    /// including sequential or parallel execution and error handling behavior.
    ///
    /// ## Default Behavior
    /// If not specified, uses ``GuardrailRunnerConfiguration/default`` which runs
    /// guardrails sequentially and stops on the first failure.
    ///
    /// See ``GuardrailRunnerConfiguration`` for customization options.
    public private(set) var guardrailRunnerConfiguration: GuardrailRunnerConfiguration

    /// The configured handoffs for multi-agent orchestration.
    ///
    /// Handoffs enable the agent to transfer control to other agents when appropriate.
    /// Each handoff appears to the LLM as a callable tool, and when invoked,
    /// execution transfers to the target agent.
    ///
    /// ## Multi-Agent Orchestration
    /// Handoffs are the foundation of Swarm's multi-agent patterns. Use them to:
    /// - Route requests to specialized agents
    /// - Build hierarchical agent systems
    /// - Implement agent teams with different expertise
    ///
    /// ## Adding Handoffs
    /// ```swift
    /// let agent = try Agent("Route requests to the right specialist.") {
    ///     handoff(to: billingAgent)
    ///     handoff(to: supportAgent)
    /// }
    /// ```
    ///
    /// See ``AnyHandoffConfiguration`` and ``HandoffOptions`` for more details.
    public var handoffs: [AnyHandoffConfiguration] {
        _handoffs
    }

    // MARK: - Initialization

    /// Creates a new Agent.
    /// - Parameters:
    ///   - tools: Tools available to the agent. Default: []
    ///   - instructions: System instructions defining agent behavior. Default: ""
    ///   - configuration: Agent configuration settings. Default: .default
    ///   - memory: Optional explicit memory override. Default: composite ContextCore + Wax memory
    ///   - inferenceProvider: Optional custom inference provider. Default: nil
    ///   - tracer: Optional tracer for observability. Default: nil
    ///   - inputGuardrails: Input validation guardrails. Default: []
    ///   - outputGuardrails: Output validation guardrails. Default: []
    ///   - guardrailRunnerConfiguration: Configuration for guardrail runner. Default: .default
    ///   - handoffs: Handoff configurations for multi-agent orchestration. Default: []
    /// - Throws: `ToolRegistryError.duplicateToolName` if duplicate tool names are provided.
    @_disfavoredOverload
    public init(
        tools: [any AnyJSONTool] = [],
        instructions: String = "",
        configuration: AgentConfiguration = .default,
        memory: (any Memory)? = nil,
        inferenceProvider: (any InferenceProvider)? = nil,
        tracer: (any Tracer)? = nil,
        inputGuardrails: [any InputGuardrail] = [],
        outputGuardrails: [any OutputGuardrail] = [],
        guardrailRunnerConfiguration: GuardrailRunnerConfiguration = .default,
        handoffs: [AnyHandoffConfiguration] = []
    ) throws {
        self.tools = tools
        self.instructions = instructions
        self.configuration = configuration
        self.memory = memory
        self.defaultMemory = try memory == nil ? Self.makeDefaultMemory() : nil
        self.inferenceProvider = inferenceProvider
        self.tracer = tracer
        self.inputGuardrails = inputGuardrails
        self.outputGuardrails = outputGuardrails
        self.guardrailRunnerConfiguration = guardrailRunnerConfiguration
        _handoffs = handoffs
        toolRegistry = try ToolRegistry(tools: tools)
    }

    /// Convenience initializer that takes an unlabeled inference provider.
    ///
    /// This enables an opinionated, easy setup:
    /// ```swift
    /// let agent = Agent(.anthropic(key: "..."))
    /// ```
    public init(
        _ inferenceProvider: any InferenceProvider,
        tools: [any AnyJSONTool] = [],
        instructions: String = "",
        configuration: AgentConfiguration = .default,
        memory: (any Memory)? = nil,
        tracer: (any Tracer)? = nil,
        inputGuardrails: [any InputGuardrail] = [],
        outputGuardrails: [any OutputGuardrail] = [],
        guardrailRunnerConfiguration: GuardrailRunnerConfiguration = .default,
        handoffs: [AnyHandoffConfiguration] = []
    ) throws {
        try self.init(
            tools: tools,
            instructions: instructions,
            configuration: configuration,
            memory: memory,
            inferenceProvider: inferenceProvider,
            tracer: tracer,
            inputGuardrails: inputGuardrails,
            outputGuardrails: outputGuardrails,
            guardrailRunnerConfiguration: guardrailRunnerConfiguration,
            handoffs: handoffs
        )
    }

    /// Creates a new Agent with typed tools.
    /// - Parameters:
    ///   - tools: Typed tools available to the agent. Default: []
    ///   - instructions: System instructions defining agent behavior. Default: ""
    ///   - configuration: Agent configuration settings. Default: .default
    ///   - memory: Optional explicit memory override. Default: composite ContextCore + Wax memory
    ///   - inferenceProvider: Optional custom inference provider. Default: nil
    ///   - tracer: Optional tracer for observability. Default: nil
    ///   - inputGuardrails: Input validation guardrails. Default: []
    ///   - outputGuardrails: Output validation guardrails. Default: []
    ///   - guardrailRunnerConfiguration: Configuration for guardrail runner. Default: .default
    ///   - handoffs: Handoff configurations for multi-agent orchestration. Default: []
    /// - Throws: `ToolRegistryError.duplicateToolName` if duplicate tool names are provided.
    public init(
        tools: [some Tool] = [],
        instructions: String = "",
        configuration: AgentConfiguration = .default,
        memory: (any Memory)? = nil,
        inferenceProvider: (any InferenceProvider)? = nil,
        tracer: (any Tracer)? = nil,
        inputGuardrails: [any InputGuardrail] = [],
        outputGuardrails: [any OutputGuardrail] = [],
        guardrailRunnerConfiguration: GuardrailRunnerConfiguration = .default,
        handoffs: [AnyHandoffConfiguration] = []
    ) throws {
        let bridged = tools.map { AnyJSONToolAdapter($0) }
        try self.init(
            tools: bridged,
            instructions: instructions,
            configuration: configuration,
            memory: memory,
            inferenceProvider: inferenceProvider,
            tracer: tracer,
            inputGuardrails: inputGuardrails,
            outputGuardrails: outputGuardrails,
            guardrailRunnerConfiguration: guardrailRunnerConfiguration,
            handoffs: handoffs
        )
    }

    /// Creates a new Agent with simplified handoff declaration.
    ///
    /// This convenience initializer accepts an array of `AgentRuntime` conforming agents
    /// and automatically wraps each one as an `AnyHandoffConfiguration`, simplifying
    /// multi-agent orchestration setup.
    ///
    /// Example:
    /// ```swift
    /// let triageAgent = Agent(
    ///     instructions: "Route requests to the right specialist.",
    ///     handoffAgents: [billingAgent, supportAgent, salesAgent]
    /// )
    /// ```
    ///
    /// - Parameters:
    ///   - tools: Tools available to the agent. Default: []
    ///   - instructions: System instructions defining agent behavior. Default: ""
    ///   - configuration: Agent configuration settings. Default: .default
    ///   - memory: Optional explicit memory override. Default: composite ContextCore + Wax memory
    ///   - inferenceProvider: Optional custom inference provider. Default: nil
    ///   - tracer: Optional tracer for observability. Default: nil
    ///   - inputGuardrails: Input validation guardrails. Default: []
    ///   - outputGuardrails: Output validation guardrails. Default: []
    ///   - guardrailRunnerConfiguration: Configuration for guardrail runner. Default: .default
    ///   - handoffAgents: Agents to hand off to, automatically wrapped as handoff configurations.
    /// - Throws: `ToolRegistryError.duplicateToolName` if duplicate tool names are provided.
    @_disfavoredOverload
    public init(
        tools: [any AnyJSONTool] = [],
        instructions: String = "",
        configuration: AgentConfiguration = .default,
        memory: (any Memory)? = nil,
        inferenceProvider: (any InferenceProvider)? = nil,
        tracer: (any Tracer)? = nil,
        inputGuardrails: [any InputGuardrail] = [],
        outputGuardrails: [any OutputGuardrail] = [],
        guardrailRunnerConfiguration: GuardrailRunnerConfiguration = .default,
        handoffAgents: [any AgentRuntime]
    ) throws {
        let configs = handoffAgents.map { agent in
            AnyHandoffConfiguration(
                targetAgent: agent,
                toolNameOverride: nil,
                toolDescription: nil
            )
        }
        try self.init(
            tools: tools,
            instructions: instructions,
            configuration: configuration,
            memory: memory,
            inferenceProvider: inferenceProvider,
            tracer: tracer,
            inputGuardrails: inputGuardrails,
            outputGuardrails: outputGuardrails,
            guardrailRunnerConfiguration: guardrailRunnerConfiguration,
            handoffs: configs
        )
    }

    // MARK: - V3 Canonical Init

    /// V3 canonical initializer — instructions-first, `@ToolBuilder` trailing closure.
    ///
    /// This is the recommended path for creating agents in V3:
    /// ```swift
    /// let agent = try Agent("You are a helpful assistant.") {
    ///     WeatherTool()
    ///     SearchTool()
    /// }
    /// ```
    ///
    /// - Parameters:
    ///   - instructions: System instructions defining agent behavior.
    ///   - configuration: Agent configuration settings. Default: `.default`
    ///   - memory: Optional explicit memory override. Default: composite ContextCore + Wax memory
    ///   - inferenceProvider: Optional custom inference provider. Default: `nil`
    ///   - tracer: Optional tracer for observability. Default: `nil`
    ///   - inputGuardrails: Input validation guardrails. Default: `[]`
    ///   - outputGuardrails: Output validation guardrails. Default: `[]`
    ///   - guardrailRunnerConfiguration: Configuration for guardrail runner. Default: `.default`
    ///   - handoffs: Handoff configurations for multi-agent orchestration. Default: `[]`
    ///   - tools: A `@ToolBuilder` closure producing the agent's tools. Default: empty.
    /// - Throws: `ToolRegistryError.duplicateToolName` if duplicate tool names are provided.
    public init(
        _ instructions: String,
        configuration: AgentConfiguration = .default,
        memory: (any Memory)? = nil,
        inferenceProvider: (any InferenceProvider)? = nil,
        tracer: (any Tracer)? = nil,
        inputGuardrails: [any InputGuardrail] = [],
        outputGuardrails: [any OutputGuardrail] = [],
        guardrailRunnerConfiguration: GuardrailRunnerConfiguration = .default,
        handoffs: [AnyHandoffConfiguration] = [],
        @ToolBuilder tools: () -> ToolCollection = { .empty }
    ) throws {
        try self.init(
            tools: tools().storage,
            instructions: instructions,
            configuration: configuration,
            memory: memory,
            inferenceProvider: inferenceProvider,
            tracer: tracer,
            inputGuardrails: inputGuardrails,
            outputGuardrails: outputGuardrails,
            guardrailRunnerConfiguration: guardrailRunnerConfiguration,
            handoffs: handoffs
        )
    }

    // MARK: - Agent Protocol Methods

    /// Executes the agent with the given input and returns a result.
    /// - Parameters:
    ///   - input: The user's input/query.
    ///   - session: Optional session for conversation history management.
    ///   - observer: Optional run observer for observing agent execution events.
    /// - Returns: The result of the agent's execution.
    /// - Throws: `AgentError` if execution fails, or `GuardrailError` if guardrails trigger.
    public func run(_ input: String, session: (any Session)? = nil, observer: (any AgentObserver)? = nil) async throws -> AgentResult {
        let runID = UUID()
        let task = Task { [self] in
            try await runInternal(input, session: session, observer: observer, structuredOutputRequest: nil)
        }
        await cancellationState.begin(runID: runID, task: task)

        do {
            let result = try await withTaskCancellationHandler(
                operation: {
                    try await task.value.agentResult
                },
                onCancel: {
                    task.cancel()
                }
            )
            await cancellationState.finish(runID: runID)
            return result
        } catch {
            task.cancel()
            await cancellationState.finish(runID: runID)
            throw normalizeCancellation(error)
        }
    }

    /// Executes the agent and enforces a structured output contract for the final assistant response.
    public func runStructured(
        _ input: String,
        request: StructuredOutputRequest,
        session: (any Session)? = nil,
        observer: (any AgentObserver)? = nil
    ) async throws -> StructuredAgentResult {
        let runID = UUID()
        let task = Task { [self] in
            try await runInternal(input, session: session, observer: observer, structuredOutputRequest: request)
        }
        await cancellationState.begin(runID: runID, task: task)

        do {
            let result = try await withTaskCancellationHandler(
                operation: {
                    try await task.value
                },
                onCancel: {
                    task.cancel()
                }
            )
            await cancellationState.finish(runID: runID)

            guard let structuredOutput = result.structuredOutput else {
                throw AgentError.generationFailed(reason: "Structured output request completed without a structured result")
            }

            return StructuredAgentResult(agentResult: result.agentResult, structuredOutput: structuredOutput)
        } catch {
            task.cancel()
            await cancellationState.finish(runID: runID)
            throw normalizeCancellation(error)
        }
    }

    /// Cancels any ongoing execution.
    ///
    public func cancel() async {
        await cancellationState.cancelCurrent()
    }

    /// Streams the agent's execution, yielding events as they occur.
    /// - Parameters:
    ///   - input: The user's input/query.
    ///   - session: Optional session for conversation history management.
    ///   - observer: Optional run observer for observing agent execution events.
    /// - Returns: An async stream of agent events.
    public func stream(_ input: String, session: (any Session)? = nil, observer: (any AgentObserver)? = nil) -> AsyncThrowingStream<AgentEvent, Error> {
        let agent = self
        return StreamHelper.makeTrackedStream(bufferingPolicy: .unbounded) { continuation in
            // Create event bridge observer
            let streamObserver = EventStreamObserver(continuation: continuation)

            // Combine with user-provided observer
            let combinedObserver: any AgentObserver = if let userObserver = observer {
                CompositeObserver(observers: [userObserver, streamObserver])
            } else {
                streamObserver
            }

            do {
                _ = try await agent.run(input, session: session, observer: combinedObserver)
                continuation.finish()
            } catch {
                // Error is handled by EventStreamObserver.onError
                continuation.finish(throwing: error)
            }
        }
    }

    public func runWithResponse(
        _ input: String,
        session: (any Session)? = nil,
        observer: (any AgentObserver)? = nil
    ) async throws -> AgentResponse {
        let result = try await run(input, session: session, observer: observer)
        let responseID = responseID(from: result)
        return makeResponse(from: result, responseID: responseID)
    }

    // MARK: Private

    // MARK: - Conversation History

    private enum ConversationMessage: Sendable {
        case system(String)
        case user(String)
        case assistant(String, toolCalls: [InferenceResponse.ParsedToolCall] = [])
        case toolResult(toolName: String, result: String, toolCallID: String? = nil)

        var formatted: String {
            switch self {
            case let .system(content):
                return "[System]: \(content)"
            case let .user(content):
                return "[User]: \(content)"
            case let .assistant(content, toolCalls):
                if toolCalls.isEmpty {
                    return "[Assistant]: \(content)"
                }

                let summary = toolCalls.map { "Calling tool: \($0.name)" }.joined(separator: ", ")
                if content.isEmpty {
                    return "[Assistant]: \(summary)"
                }

                return "[Assistant]: \(content)\n[Assistant Tool Calls]: \(summary)"
            case let .toolResult(toolName, result, _):
                return "[Tool Result - \(toolName)]: \(result)"
            }
        }

        var inferenceMessage: InferenceMessage {
            switch self {
            case let .system(content):
                return .system(content)
            case let .user(content):
                return .user(content)
            case let .assistant(content, toolCalls):
                return .assistant(content, toolCalls: toolCalls.map(InferenceMessage.ToolCall.init))
            case let .toolResult(toolName, result, toolCallID):
                return .tool(name: toolName, content: result, toolCallID: toolCallID)
            }
        }
    }

    private var _handoffs: [AnyHandoffConfiguration]

    // MARK: - Internal State

    private var toolRegistry: ToolRegistry
    private let cancellationState = ActiveRunCancellationState()
    private static let autoResponseTracker = ResponseTracker()
    private static let defaultMemorySessionTracker = DefaultMemorySessionTracker()
    private static let responseIDMetadataKey = "response.id"
    private static let transcriptSchemaVersionMetadataKey = "swarm.transcript.schema_version"
    private static let transcriptHashMetadataKey = "swarm.transcript.hash"
    private static let structuredOutputJSONMetadataKey = "structured_output.raw_json"
    private static let structuredOutputSourceMetadataKey = "structured_output.source"
    private static let structuredOutputFormatMetadataKey = "structured_output.format"

    private struct InternalRunResult: Sendable {
        let agentResult: AgentResult
        let structuredOutput: StructuredOutputResult?
    }

    private struct ToolLoopOutcome: Sendable {
        let output: String
        let structuredOutput: StructuredOutputResult?
        let transcriptMessages: [MemoryMessage]
    }

    private struct FinalAssistantResponse: Sendable {
        let content: String
        let structuredOutput: StructuredOutputResult?
    }

    private actor ActiveRunCancellationState {
        private var activeRunID: UUID?
        private var activeTask: Task<InternalRunResult, Error>?

        func begin(runID: UUID, task: Task<InternalRunResult, Error>) {
            activeRunID = runID
            activeTask = task
        }

        func finish(runID: UUID) {
            guard activeRunID == runID else { return }
            activeRunID = nil
            activeTask = nil
        }

        func cancelCurrent() {
            activeTask?.cancel()
        }
    }

    private final class TimedOperationCoordinator<T: Sendable>: @unchecked Sendable {
        private let lock = NSLock()
        private var continuation: CheckedContinuation<T, Error>?
        private var operationTask: Task<Void, Never>?
        private var timeoutTask: Task<Void, Never>?
        private var completed = false

        func install(continuation: CheckedContinuation<T, Error>) {
            lock.lock()
            defer { lock.unlock() }
            self.continuation = continuation
        }

        func setOperationTask(_ task: Task<Void, Never>) {
            lock.lock()
            defer { lock.unlock() }
            operationTask = task
        }

        func setTimeoutTask(_ task: Task<Void, Never>) {
            lock.lock()
            defer { lock.unlock() }
            timeoutTask = task
        }

        func finish(returning value: T) {
            complete { continuation in
                continuation.resume(returning: value)
            }
        }

        func finish(throwing error: Error) {
            complete { continuation in
                continuation.resume(throwing: error)
            }
        }

        func cancelPending(with error: Error) {
            let pendingState = takePendingState()
            pendingState.operationTask?.cancel()
            pendingState.timeoutTask?.cancel()
            pendingState.continuation?.resume(throwing: error)
        }

        private func complete(_ resume: (CheckedContinuation<T, Error>) -> Void) {
            let pendingState = takePendingState()
            pendingState.operationTask?.cancel()
            pendingState.timeoutTask?.cancel()
            guard let continuation = pendingState.continuation else { return }
            resume(continuation)
        }

        private func takePendingState() -> (
            continuation: CheckedContinuation<T, Error>?,
            operationTask: Task<Void, Never>?,
            timeoutTask: Task<Void, Never>?
        ) {
            lock.lock()
            defer { lock.unlock() }

            guard completed == false else {
                return (nil, nil, nil)
            }

            completed = true
            let pendingContinuation = continuation
            let pendingOperationTask = operationTask
            let pendingTimeoutTask = timeoutTask
            continuation = nil
            operationTask = nil
            timeoutTask = nil
            return (pendingContinuation, pendingOperationTask, pendingTimeoutTask)
        }
    }

    private actor DefaultMemorySessionTracker {
        private var sessionIDs: [ObjectIdentifier: String] = [:]
        private var activeSessionIDs: [ObjectIdentifier: String] = [:]
        private var activeCounts: [ObjectIdentifier: Int] = [:]
        // Waiters are keyed by a per-call UUID so a cancellation can target the
        // exact parked task without disturbing siblings. `endRun()` resumes any
        // remaining waiters with success; cancellation resumes the targeted
        // waiter with `CancellationError` and removes it from the map.
        private var waiters: [ObjectIdentifier: [UUID: CheckedContinuation<Void, Error>]] = [:]

        func beginRun(for key: ObjectIdentifier, sessionID: String) async throws -> Bool {
            while let activeSessionID = activeSessionIDs[key],
                  activeSessionID != sessionID
            {
                try Task.checkCancellation()
                try await waitForSessionRelease(key: key)
            }

            // Final cancellation check after exiting the wait loop. Closes the
            // race where `endRun` resumes the continuation just as the parent
            // task is cancelled — without this, the resumed task would proceed
            // to claim the slot and trigger memory-clear side effects.
            try Task.checkCancellation()

            let previous = sessionIDs[key]
            sessionIDs[key] = sessionID
            activeSessionIDs[key] = sessionID
            activeCounts[key, default: 0] += 1
            return previous != sessionID
        }

        func endRun(for key: ObjectIdentifier) {
            let remaining = (activeCounts[key] ?? 1) - 1
            if remaining > 0 {
                activeCounts[key] = remaining
                return
            }

            activeCounts[key] = nil
            activeSessionIDs[key] = nil
            let pendingWaiters = waiters.removeValue(forKey: key) ?? [:]
            for (_, continuation) in pendingWaiters {
                continuation.resume()
            }
        }

        /// Park the calling task until either the active session releases (success)
        /// or the calling task is cancelled (throws `CancellationError`). Without
        /// the cancellation arm, a cancelled task would stay parked until the
        /// holder of the active session calls `endRun()`, then wake up and claim
        /// the slot — performing memory clears and other side effects before the
        /// cancellation surfaces deeper in execution.
        private func waitForSessionRelease(key: ObjectIdentifier) async throws {
            let waiterID = UUID()
            try await withTaskCancellationHandler {
                try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
                    if Task.isCancelled {
                        continuation.resume(throwing: CancellationError())
                        return
                    }
                    waiters[key, default: [:]][waiterID] = continuation
                }
            } onCancel: {
                Task { await self.cancelWaiter(key: key, id: waiterID) }
            }
        }

        private func cancelWaiter(key: ObjectIdentifier, id: UUID) {
            if let continuation = waiters[key]?.removeValue(forKey: id) {
                if waiters[key]?.isEmpty == true {
                    waiters[key] = nil
                }
                continuation.resume(throwing: CancellationError())
            }
        }
    }

    private func runInternal(
        _ input: String,
        session: (any Session)? = nil,
        observer: (any AgentObserver)? = nil,
        structuredOutputRequest: StructuredOutputRequest?
    ) async throws -> InternalRunResult {
        guard !input.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
            throw AgentError.invalidInput(reason: "Input cannot be empty")
        }

        let activeTracer = tracer
            ?? AgentEnvironmentValues.current.tracer
            ?? (configuration.defaultTracingEnabled ? SwiftLogTracer(minimumLevel: .debug) : nil)
        let activeMemory = resolvedMemory()
        let lifecycleMemory = activeMemory as? any MemorySessionLifecycle
        let trackedSessionMemory = activeMemory.flatMap(defaultSessionMemory)
        var defaultMemoryRunKey: ObjectIdentifier?

        if let session,
           let trackedSessionMemory
        {
            let trackedMemoryObject = trackedSessionMemory as AnyObject
            let memoryKey = ObjectIdentifier(trackedMemoryObject)
            defaultMemoryRunKey = memoryKey
            if try await Self.defaultMemorySessionTracker.beginRun(for: memoryKey, sessionID: session.sessionId) {
                await trackedSessionMemory.clear()
            }
        }

        let tracing = TracingHelper(
            tracer: activeTracer,
            agentName: configuration.name.isEmpty ? "Agent" : configuration.name
        )
        let runtimeToolRegistry = try await resolvedToolRegistry()
        await tracing.traceStart(input: input)

        // Notify observer of agent start
        await observer?.onAgentStart(context: nil, agent: self, input: input)

        if let lifecycleMemory {
            await lifecycleMemory.beginMemorySession()
        }

        do {
            // Run input guardrails (with observer for event emission)
            let runner = GuardrailRunner(configuration: guardrailRunnerConfiguration, observer: observer)
            _ = try await runner.runInputGuardrails(inputGuardrails, input: input, context: nil)

            // Reset cancellation state and create result builder
            let resultBuilder = AgentResult.Builder()
            _ = resultBuilder.start()
            let responseID = UUID().uuidString
            _ = resultBuilder.setMetadata(Self.responseIDMetadataKey, .string(responseID))
            if let structuredOutputRequest {
                _ = resultBuilder.setMetadata(
                    Self.structuredOutputFormatMetadataKey,
                    .string(Self.structuredOutputFormatDescription(structuredOutputRequest.format))
                )
            }

            // Load conversation history from session (limit to recent messages)
            var sessionHistory: [MemoryMessage] = []
            if let session {
                sessionHistory = try await session.getItems(limit: configuration.sessionHistoryLimit)
            }

            let replayTranscript = SwarmTranscript(memoryMessages: sessionHistory)
            try replayTranscript.validateReplayCompatibility()

            // Seed memory with session history once when the memory is eligible.
            if let activeMemory, session != nil {
                await activeMemory.seedSessionHistoryIfNeeded(sessionHistory)
            }

            // Create user message for this turn
            let userMessage = SwarmTranscriptCodec.encodeMessage(role: .user, content: input)

            // Execute the tool calling loop with session context
            let provider = try await resolvedInferenceProvider(toolRegistry: runtimeToolRegistry)
            let runtimeEnvironment = runtimeEnvironment(for: provider)
            let toolLoopOutcome = try await AgentEnvironmentValues.$current.withValue(runtimeEnvironment) {
                try await executeToolCallingLoop(
                    input: input,
                    toolRegistry: runtimeToolRegistry,
                    provider: provider,
                    sessionHistory: sessionHistory,
                    session: session,
                    resultBuilder: resultBuilder,
                    observer: observer,
                    tracing: tracing,
                    structuredOutputRequest: structuredOutputRequest
                )
            }

            _ = resultBuilder.setOutput(toolLoopOutcome.output)
            applyStructuredOutputMetadata(toolLoopOutcome.structuredOutput, to: resultBuilder)

            // Run output guardrails BEFORE storing in session/memory
            _ = try await runner.runOutputGuardrails(
                outputGuardrails,
                output: toolLoopOutcome.output,
                agent: self,
                context: nil
            )

            // Store turn in session for conversation persistence
            // Session is the source of truth for conversation history
            if let session {
                try await session.addItems([userMessage] + toolLoopOutcome.transcriptMessages)

                let persistedTranscript = SwarmTranscript(memoryMessages: try await session.getAllItems())
                try persistedTranscript.validateReplayCompatibility()
                _ = resultBuilder.setMetadata(
                    Self.transcriptSchemaVersionMetadataKey,
                    .string(persistedTranscript.schemaVersion.rawValue)
                )
                if let transcriptHash = try? persistedTranscript.transcriptHash() {
                    _ = resultBuilder.setMetadata(Self.transcriptHashMetadataKey, .string(transcriptHash))
                }
            } else if let activeMemory, shouldPersistNoSessionTurn(to: activeMemory) {
                await persistNoSessionTurn(
                    userMessage: userMessage,
                    transcriptMessages: toolLoopOutcome.transcriptMessages,
                    to: activeMemory
                )
            }

            // Session remains the transcript source of truth. When no session is supplied,
            // the default memory keeps user/assistant turns available for subsequent runs.

            _ = resultBuilder.setMetadata(RuntimeMetadata.runtimeEngineKey, .string(RuntimeMetadata.nativeRuntimeEngineName))
            let result = resultBuilder.build()
            if configuration.autoPreviousResponseId, let session {
                let response = makeResponse(from: result, responseID: responseID)
                await Self.autoResponseTracker.recordResponse(response, sessionId: session.sessionId)
            }
            await tracing.traceComplete(result: result)

            // Notify observer of agent completion
            await observer?.onAgentEnd(context: nil, agent: self, result: result)

            if let lifecycleMemory {
                await lifecycleMemory.endMemorySession()
            }
            if let defaultMemoryRunKey {
                await Self.defaultMemorySessionTracker.endRun(for: defaultMemoryRunKey)
            }
            return InternalRunResult(agentResult: result, structuredOutput: toolLoopOutcome.structuredOutput)
        } catch {
            let normalizedError = normalizeCancellation(error)
            // Notify observer of error
            await observer?.onError(context: nil, agent: self, error: normalizedError)
            await tracing.traceError(normalizedError)
            if let lifecycleMemory {
                await lifecycleMemory.endMemorySession()
            }
            if let defaultMemoryRunKey {
                await Self.defaultMemorySessionTracker.endRun(for: defaultMemoryRunKey)
            }
            throw normalizedError
        }
    }

    // MARK: - Inference Provider Resolution

    private func resolvedInferenceProvider(toolRegistry: ToolRegistry) async throws -> any InferenceProvider {
        if configuration.inferencePolicy?.privacyRequired == true {
            return try await resolvedPrivateInferenceProvider()
        }

        // 1. Explicit provider on Agent
        if let inferenceProvider {
            return transformedInferenceProvider(inferenceProvider)
        }

        // 2. TaskLocal via .environment()
        if let environmentProvider = AgentEnvironmentValues.current.inferenceProvider {
            return transformedInferenceProvider(environmentProvider)
        }

        // 3. Swarm.cloudProvider (if tool calling is required)
        let hasEnabledTools = await !toolRegistry.schemas.isEmpty
        let needsToolCallingProvider = hasEnabledTools || !_handoffs.isEmpty
        if needsToolCallingProvider, let cloudProvider = await Swarm.cloudProvider {
            return transformedInferenceProvider(cloudProvider)
        }

        // 4. Swarm.defaultProvider (global)
        if let globalProvider = await Swarm.defaultProvider {
            return transformedInferenceProvider(globalProvider)
        }

        // 5. Foundation Models (if available, on Apple platform)
        if let foundationModelsProvider = DefaultInferenceProviderFactory.makeFoundationModelsProviderIfAvailable() {
            return transformedInferenceProvider(foundationModelsProvider)
        }

        // 6. No provider available
        throw AgentError.inferenceProviderUnavailable(
            reason: """
            No inference provider configured and Apple Foundation Models are unavailable.

            Configure a provider globally via `await Swarm.configure(provider: ...)` \
            or pass one explicitly to Agent(...).
            """
        )
    }

    private func resolvedPrivateInferenceProvider() async throws -> any InferenceProvider {
        if let foundationModelsProvider = DefaultInferenceProviderFactory.makeFoundationModelsProviderIfAvailable() {
            return transformedInferenceProvider(foundationModelsProvider)
        }

        if let provider = privateInferenceProvider(inferenceProvider) {
            return transformedInferenceProvider(provider)
        }

        if let provider = privateInferenceProvider(AgentEnvironmentValues.current.inferenceProvider) {
            return transformedInferenceProvider(provider)
        }

        if let globalProvider = await Swarm.defaultProvider,
           let provider = privateInferenceProvider(globalProvider)
        {
            return transformedInferenceProvider(provider)
        }

        // Mirror the non-private resolver's cloud-provider fallback: if the operator
        // configured a privacy-capable provider via `Swarm.configure(cloudProvider: ...)`
        // (common for tool/handoff flows), honor it. The capability filter in
        // `privateInferenceProvider(_:)` ensures we only return it if it actually
        // reports `.privateInference`.
        if let cloudProvider = await Swarm.cloudProvider,
           let provider = privateInferenceProvider(cloudProvider)
        {
            return transformedInferenceProvider(provider)
        }

        throw AgentError.inferenceProviderUnavailable(
            reason: """
            AgentConfiguration.inferencePolicy.privacyRequired is true, but no private inference provider is available.

            Use Apple Foundation Models on a supported device, or configure a provider that reports \
            InferenceProviderCapabilities.privateInference.
            """
        )
    }

    private func privateInferenceProvider(_ provider: (any InferenceProvider)?) -> (any InferenceProvider)? {
        guard let provider else {
            return nil
        }

        let capabilities = InferenceProviderCapabilities.resolved(for: provider)
        guard capabilities.contains(.privateInference) else {
            return nil
        }
        return provider
    }

    private func transformedInferenceProvider(_ provider: any InferenceProvider) -> any InferenceProvider {
        guard let transform = AgentEnvironmentValues.current.inferenceProviderTransform else {
            return provider
        }
        return transform(provider)
    }

    private func resolvedMembraneAdapter() -> (any MembraneAgentAdapter)? {
        let membrane = AgentEnvironmentValues.current.membrane ?? .enabled
        guard membrane.isEnabled else {
            return nil
        }
        if let adapter = membrane.adapter {
            return adapter
        }
        return DefaultMembraneAgentAdapter(configuration: membrane.configuration)
    }

    private func runtimeEnvironment(for provider: any InferenceProvider) -> AgentEnvironment {
        var environment = AgentEnvironmentValues.current
        if let tokenCounter = provider as? any PromptTokenCountingInferenceProvider {
            environment.promptTokenCounter = tokenCounter
        }
        return environment
    }

    private func resolvedMemory() -> (any Memory)? {
        memory ?? AgentEnvironmentValues.current.memory ?? defaultMemory
    }

    private func defaultSessionMemory(from activeMemory: any Memory) -> (any Memory)? {
        if let defaultMemory {
            let activeObject = activeMemory as AnyObject
            let defaultObject = defaultMemory as AnyObject
            if activeObject === defaultObject {
                return defaultMemory
            }
        }

        if let trackingProvider = activeMemory as? any MemorySessionTrackingProvider {
            return trackingProvider.trackedSessionMemory
        }

        return nil
    }

    private func shouldPersistNoSessionTurn(to activeMemory: any Memory) -> Bool {
        guard let defaultMemory else {
            return false
        }

        return activeMemory as AnyObject === defaultMemory as AnyObject
    }

    private func persistNoSessionTurn(
        userMessage: MemoryMessage,
        transcriptMessages: [MemoryMessage],
        to memory: any Memory
    ) async {
        let messages = ([userMessage] + transcriptMessages).filter { message in
            message.role == .user || message.role == .assistant
        }

        for message in messages {
            await memory.add(message)
        }
    }

    static func makeDefaultMemory() throws -> any Memory {
        #if SWARM_INTEGRATIONS
        if SwarmRuntimeEnvironment.isRunningTests {
            let root = FileManager.default.temporaryDirectory
                .appendingPathComponent("SwarmDefaultMemoryTests", isDirectory: true)
                .appendingPathComponent(UUID().uuidString, isDirectory: true)
            try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
            return try DefaultAgentMemory(configuration: DefaultAgentMemory.Configuration(
                waxStoreURL: root.appendingPathComponent("wax-memory.mv2s")
            ))
        }
        return try DefaultAgentMemory()
        #else
        return SlidingWindowMemory()
        #endif
    }

    private func resolvedToolRegistry() async throws -> ToolRegistry {
        let baseTools = await toolRegistry.allTools
        #if SWARM_INTEGRATIONS
        guard !baseTools.contains(where: { $0.name == "websearch" }) else {
            return try ToolRegistry(tools: baseTools)
        }

        let taskLocalWeb = AgentEnvironmentValues.current.webSearch
        let ambientWeb = if let taskLocalWeb { taskLocalWeb } else { await Swarm.webConfiguration }
        guard let ambientWeb,
              ambientWeb.enabled
        else {
            return try ToolRegistry(tools: baseTools)
        }

        var tools = baseTools
        tools.append(WebSearchTool(configuration: ambientWeb))
        return try ToolRegistry(tools: tools)
        #else
        return try ToolRegistry(tools: baseTools)
        #endif
    }

    private func resolvedInferenceOptions(
        session: (any Session)?,
        provider: any InferenceProvider
    ) async -> InferenceOptions {
        var options = configuration.inferenceOptions

        let capabilities = providerCapabilities(for: provider)
        guard capabilities.contains(.responseContinuation) else {
            options.previousResponseId = nil
            return options
        }

        if let explicit = configuration.previousResponseId?.trimmingCharacters(in: .whitespacesAndNewlines),
           !explicit.isEmpty {
            options.previousResponseId = explicit
            return options
        }

        guard configuration.autoPreviousResponseId, let session else {
            return options
        }

        if let latestResponseID = await Self.autoResponseTracker.getLatestResponseId(for: session.sessionId) {
            options.previousResponseId = latestResponseID
        }

        return options
    }

    private func providerCapabilities(for provider: any InferenceProvider) -> InferenceProviderCapabilities {
        InferenceProviderCapabilities.resolved(for: provider)
    }

    private func responseID(from result: AgentResult) -> String {
        if case let .string(value)? = result.metadata[Self.responseIDMetadataKey], !value.isEmpty {
            return value
        }
        return UUID().uuidString
    }

    private func makeResponse(from result: AgentResult, responseID: String) -> AgentResponse {
        let toolCallsById = Dictionary(uniqueKeysWithValues: result.toolCalls.map { ($0.id, $0) })
        let toolCallRecords: [ToolCallRecord] = result.toolResults.compactMap { toolResult in
            guard let toolCall = toolCallsById[toolResult.callId] else {
                Log.agents.warning("Tool result missing matching call: \(toolResult.callId)")
                return nil
            }

            return ToolCallRecord(
                toolName: toolCall.toolName,
                arguments: toolCall.arguments,
                result: toolResult.output,
                duration: toolResult.duration,
                timestamp: toolCall.timestamp,
                isSuccess: toolResult.isSuccess,
                errorMessage: toolResult.errorMessage
            )
        }

        return AgentResponse(
            responseId: responseID,
            output: result.output,
            agentName: configuration.name,
            metadata: result.metadata,
            toolCalls: toolCallRecords,
            usage: result.tokenUsage,
            iterationCount: result.iterationCount
        )
    }

    private func applyStructuredOutputMetadata(
        _ structuredOutput: StructuredOutputResult?,
        to resultBuilder: AgentResult.Builder
    ) {
        guard let structuredOutput else { return }

        _ = resultBuilder.setMetadata(Self.structuredOutputJSONMetadataKey, .string(structuredOutput.rawJSON))
        _ = resultBuilder.setMetadata(Self.structuredOutputSourceMetadataKey, .string(structuredOutput.source.rawValue))
        _ = resultBuilder.setMetadata(
            Self.structuredOutputFormatMetadataKey,
            .string(Self.structuredOutputFormatDescription(structuredOutput.format))
        )
    }

    private func finalizeAssistantResponse(
        content: String,
        request: StructuredOutputRequest?,
        provider: any InferenceProvider
    ) throws -> FinalAssistantResponse {
        guard let request else {
            return FinalAssistantResponse(content: content, structuredOutput: nil)
        }

        let source: StructuredOutputResult.Source = providerCapabilities(for: provider).contains(.structuredOutputs)
            ? .providerNative
            : .promptFallback
        let structuredOutput = try StructuredOutputParser.parse(content, request: request, source: source)
        return FinalAssistantResponse(content: structuredOutput.rawJSON, structuredOutput: structuredOutput)
    }

    private static func structuredOutputFormatDescription(_ format: StructuredOutputFormat) -> String {
        switch format {
        case .jsonObject:
            return "json_object"
        case .jsonSchema(let name, _):
            return "json_schema:\(name)"
        }
    }

    // MARK: - Tool Calling Loop Implementation

    private func executeToolCallingLoop(
        input: String,
        toolRegistry: ToolRegistry,
        provider: any InferenceProvider,
        sessionHistory: [MemoryMessage] = [],
        session: (any Session)?,
        resultBuilder: AgentResult.Builder,
        observer: (any AgentObserver)? = nil,
        tracing: TracingHelper? = nil,
        structuredOutputRequest: StructuredOutputRequest?
    ) async throws -> ToolLoopOutcome {
        var iteration = 0
        let startTime = ContinuousClock.now
        var inferenceOptions = await resolvedInferenceOptions(session: session, provider: provider)
        if let structuredOutputRequest {
            inferenceOptions.structuredOutput = structuredOutputRequest
        }

        // Retrieve relevant context from memory (enables RAG for VectorMemory)
        let activeMemory = resolvedMemory()
        var memoryContext = ""
        if let mem = activeMemory {
            let contextProfile = configuration.effectiveContextProfile
            let tokenLimit = contextProfile.memoryTokenLimit
            memoryContext = try await executeWithinRemainingTimeout(startTime: startTime) {
                if let policyAwareMemory = mem as? any MemoryRetrievalPolicyAware {
                    return await policyAwareMemory.context(
                        for: MemoryQuery(
                            text: input,
                            tokenLimit: tokenLimit,
                            maxItems: contextProfile.maxRetrievedItems,
                            maxItemTokens: contextProfile.maxRetrievedItemTokens
                        )
                    )
                }
                return await mem.context(for: input, tokenLimit: tokenLimit)
            }
        }

        var conversationHistory = try buildInitialConversationHistory(
            sessionHistory: sessionHistory,
            input: input,
            memory: activeMemory,
            memoryContext: memoryContext
        )
        var transcriptMessages: [MemoryMessage] = []
        let systemMessage = buildSystemMessage(memory: activeMemory, memoryContext: memoryContext)
        let executionContext = AgentContext(input: input)
        await executionContext.recordExecution(agentName: name)

        let enableStreaming = configuration.enableStreaming && observer != nil
        let capabilities = providerCapabilities(for: provider)
        let structuredToolStreamingProvider = provider as? any ToolCallStreamingConversationInferenceProvider
        let promptToolStreamingProvider = provider as? any ToolCallStreamingInferenceProvider
        let useToolStreaming = enableStreaming
            && capabilities.contains(.streamingToolCalls)
            && (structuredToolStreamingProvider != nil || promptToolStreamingProvider != nil)
        let membraneAdapter = resolvedMembraneAdapter()

        while iteration < configuration.maxIterations {
            iteration += 1
            _ = resultBuilder.incrementIteration()
            await observer?.onIterationStart(context: nil, agent: self, number: iteration)

            do {
                try checkCancellationAndTimeout(startTime: startTime)

                let rawPrompt: String
                if configuration.effectiveContextProfile.preset == .strict4k {
                    // Use ContextCore's intelligent windowing if available.
                    // DefaultAgentMemory wraps ContextCoreMemory internally.
                    let historyBudget = configuration.effectiveContextProfile.budget.workingTokens
                    let lastMsg = conversationHistory.last
                    let query: String
                    switch lastMsg {
                    case .assistant(let content, _):
                        query = content
                    case .toolResult(_, let output, _):
                        query = String(output.prefix(200))
                    default:
                        query = input
                    }
                    var windowedContext = ""
                    #if SWARM_INTEGRATIONS
                    if let defaultMem = activeMemory as? DefaultAgentMemory {
                        windowedContext = await defaultMem.context(for: query, tokenLimit: historyBudget)
                    } else if let ccMemory = activeMemory as? ContextCoreMemory {
                        windowedContext = await ccMemory.context(for: query, tokenLimit: historyBudget)
                    }
                    #endif
                    if !windowedContext.isEmpty {
                        let livePrompt = buildPrompt(from: conversationHistory)
                        rawPrompt = """
                        [Retrieved Context]
                        \(windowedContext)

                        [Current Conversation]
                        \(livePrompt)
                        """
                    } else {
                        // Fallback: manual pruning with summarization.
                        var capped = conversationHistory
                        for i in capped.indices {
                            if case .toolResult(let toolName, let output, let toolCallID) = capped[i], output.count > 400 {
                                capped[i] = .toolResult(toolName: toolName, result: String(output.prefix(400)) + "\n[... truncated ...]", toolCallID: toolCallID)
                            }
                            if case .assistant(let content, let toolCalls) = capped[i], !toolCalls.isEmpty {
                                let nameOnlyCalls = toolCalls.map { tc in
                                    InferenceResponse.ParsedToolCall(id: tc.id, name: tc.name, arguments: [:])
                                }
                                capped[i] = .assistant(content, toolCalls: nameOnlyCalls)
                            }
                        }
                        if capped.count > 6 {
                            let head = capped.prefix(2)
                            let tail = capped.suffix(3)
                            let middle = capped.dropFirst(2).dropLast(3)
                            var summaryParts: [String] = []
                            for msg in middle {
                                switch msg {
                                case .assistant(_, let toolCalls) where !toolCalls.isEmpty:
                                    summaryParts.append("called " + toolCalls.map(\.name).joined(separator: ", "))
                                case .toolResult(let toolName, let output, _):
                                    summaryParts.append("\(toolName): \(output.prefix(40).replacingOccurrences(of: "\n", with: " "))")
                                default:
                                    break
                                }
                            }
                            var pruned = Array(head)
                            pruned.append(.assistant("[summary: \(summaryParts.joined(separator: "; "))]", toolCalls: []))
                            pruned.append(contentsOf: tail)
                            rawPrompt = buildPrompt(from: pruned)
                        } else if capped.count > 5 {
                            var pruned = Array(capped.prefix(2))
                            pruned.append(.assistant("[... truncated ...]", toolCalls: []))
                            pruned.append(contentsOf: capped.suffix(3))
                            rawPrompt = buildPrompt(from: pruned)
                        } else {
                            rawPrompt = buildPrompt(from: capped)
                        }
                    }
                } else {
                    rawPrompt = buildPrompt(from: conversationHistory)
                }
                let unplannedSchemas = await buildToolSchemasWithHandoffs(
                    toolRegistry: toolRegistry,
                    context: executionContext
                )
                var plannedPrompt = rawPrompt
                var plannedSchemas = MembraneInternalTools.sortedSchemas(unplannedSchemas)

                if let membraneAdapter {
                    do {
                        let plan = try await membraneAdapter.plan(
                            prompt: rawPrompt,
                            toolSchemas: unplannedSchemas,
                            profile: configuration.effectiveContextProfile
                        )
                        plannedPrompt = plan.prompt
                        plannedSchemas = MembraneInternalTools.sortedSchemas(plan.toolSchemas)
                        _ = resultBuilder.setMetadata("membrane.mode", .string(plan.mode))
                    } catch {
                        _ = resultBuilder.setMetadata("membrane.fallback.used", .bool(true))
                        _ = resultBuilder.setMetadata("membrane.fallback.error", .string(fallbackDiagnosticMessage(for: error)))
                        plannedPrompt = rawPrompt
                        plannedSchemas = MembraneInternalTools.sortedSchemas(unplannedSchemas)
                    }
                }

                let prompt = await PromptEnvelope.enforce(
                    prompt: plannedPrompt,
                    profile: configuration.effectiveContextProfile
                )
                let toolSchemas: [ToolSchema] = {
                    var schemas = MembraneInternalTools.sortedSchemas(plannedSchemas)
                    // For strict4k, strip tool descriptions to save ~120 tokens.
                    if configuration.effectiveContextProfile.preset == .strict4k {
                        schemas = schemas.map { ToolSchema(name: $0.name, description: $0.name, parameters: $0.parameters) }
                    }
                    return schemas
                }()
                let providerAcceptsStructuredMessages = provider is any ConversationInferenceProvider
                let structuredMessages: [InferenceMessage]? = if configuration.effectiveContextProfile.preset == .strict4k {
                    nil
                } else if providerAcceptsStructuredMessages {
                    conversationHistory.map(\.inferenceMessage)
                } else if prompt == rawPrompt {
                    conversationHistory.map(\.inferenceMessage)
                } else {
                    nil
                }

                // If no tools defined, generate without tool calling
                if toolSchemas.isEmpty {
                    let loopInferenceOptions = inferenceOptions
                    let response = try await executeWithinRemainingTimeout(startTime: startTime) {
                        try await generateWithoutTools(
                            provider: provider,
                            prompt: prompt,
                            messages: structuredMessages,
                            systemPrompt: systemMessage,
                            inferenceOptions: loopInferenceOptions,
                            enableStreaming: enableStreaming,
                            observer: observer
                        )
                    }
                    transcriptMessages.append(
                        SwarmTranscriptCodec.encodeMessage(
                            role: .assistant,
                            content: response.content,
                            toolCalls: [],
                            structuredOutput: response.structuredOutput
                        )
                    )
                    await observer?.onIterationEnd(context: nil, agent: self, number: iteration)
                    return ToolLoopOutcome(
                        output: response.content,
                        structuredOutput: response.structuredOutput,
                        transcriptMessages: transcriptMessages
                    )
                }

                // Generate response with tool calls
                let loopInferenceOptions = inferenceOptions
                let response = if useToolStreaming {
                    try await executeWithinRemainingTimeout(startTime: startTime) {
                        try await generateWithToolsStreaming(
                            provider: provider,
                            prompt: prompt,
                            messages: structuredMessages,
                            tools: toolSchemas,
                            inferenceOptions: loopInferenceOptions,
                            systemPrompt: systemMessage,
                            observer: observer
                        )
                    }
                } else {
                    try await executeWithinRemainingTimeout(startTime: startTime) {
                        try await generateWithTools(
                            provider: provider,
                            prompt: prompt,
                            messages: structuredMessages,
                            tools: toolSchemas,
                            inferenceOptions: loopInferenceOptions,
                            systemPrompt: systemMessage,
                            observer: observer,
                            emitOutputTokens: enableStreaming
                        )
                    }
                }

                if response.hasToolCalls {
                    let handoffResult = try await processToolCallsWithHandoffs(
                        response: response,
                        toolRegistry: toolRegistry,
                        conversationHistory: &conversationHistory,
                        transcriptMessages: &transcriptMessages,
                        resultBuilder: resultBuilder,
                        observer: observer,
                        tracing: tracing,
                        membraneAdapter: membraneAdapter,
                        context: executionContext,
                        startTime: startTime
                    )
                    // If a handoff occurred, return the target agent's result
                    if let handoffOutput = handoffResult {
                        await observer?.onIterationEnd(context: nil, agent: self, number: iteration)
                        return ToolLoopOutcome(
                            output: handoffOutput.content,
                            structuredOutput: handoffOutput.structuredOutput,
                            transcriptMessages: transcriptMessages
                        )
                    }
                } else {
                    guard let content = response.content else {
                        throw AgentError.generationFailed(reason: "Model returned no content or tool calls")
                    }
                    let finalResponse = try finalizeAssistantResponse(
                        content: content,
                        request: structuredOutputRequest,
                        provider: provider
                    )
                    transcriptMessages.append(
                        SwarmTranscriptCodec.encodeMessage(
                            role: .assistant,
                            content: finalResponse.content,
                            toolCalls: [],
                            structuredOutput: finalResponse.structuredOutput
                        )
                    )
                    await observer?.onIterationEnd(context: nil, agent: self, number: iteration)
                    return ToolLoopOutcome(
                        output: finalResponse.content,
                        structuredOutput: finalResponse.structuredOutput,
                        transcriptMessages: transcriptMessages
                    )
                }

                await observer?.onIterationEnd(context: nil, agent: self, number: iteration)
            } catch {
                await observer?.onIterationEnd(context: nil, agent: self, number: iteration)
                throw normalizeCancellation(error)
            }
        }

        throw AgentError.maxIterationsExceeded(iterations: iteration)
    }

    /// Builds the initial conversation history from session history and user input.
    private func buildInitialConversationHistory(
        sessionHistory: [MemoryMessage],
        input: String,
        memory: (any Memory)?,
        memoryContext: String = ""
    ) throws -> [ConversationMessage] {
        let transcript = SwarmTranscript(memoryMessages: sessionHistory)
        try transcript.validateReplayCompatibility()

        var history: [ConversationMessage] = []
        history.append(.system(buildSystemMessage(memory: memory, memoryContext: memoryContext)))

        for entry in transcript.entries {
            switch entry.role {
            case .user:
                history.append(.user(entry.content))
            case .assistant:
                history.append(.assistant(
                    entry.content,
                    toolCalls: entry.toolCalls.map {
                        InferenceResponse.ParsedToolCall(id: $0.id, name: $0.name, arguments: $0.arguments)
                    }
                ))
            case .system:
                history.append(.system(entry.content))
            case .tool:
                history.append(.toolResult(
                    toolName: entry.toolName ?? "previous",
                    result: entry.content,
                    toolCallID: entry.toolCallID
                ))
            }
        }

        history.append(.user(input))
        return history
    }

    /// Checks for cancellation and timeout conditions.
    private func checkCancellationAndTimeout(startTime: ContinuousClock.Instant) throws {
        // Use Task.checkCancellation() for reliable cancellation detection
        // This is the standard Swift concurrency pattern
        try Task.checkCancellation()

        let elapsed = ContinuousClock.now - startTime
        if elapsed > configuration.timeout {
            throw AgentError.timeout(duration: configuration.timeout)
        }
    }

    private func executeWithinRemainingTimeout<T: Sendable>(
        startTime: ContinuousClock.Instant,
        operation: @escaping @Sendable () async throws -> T
    ) async throws -> T {
        try Task.checkCancellation()

        let remaining = configuration.timeout - (ContinuousClock.now - startTime)
        if remaining <= .zero {
            throw AgentError.timeout(duration: configuration.timeout)
        }

        let coordinator = TimedOperationCoordinator<T>()

        return try await withTaskCancellationHandler(
            operation: {
                try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<T, Error>) in
                    coordinator.install(continuation: continuation)

                    let operationTask = Task {
                        do {
                            coordinator.finish(returning: try await operation())
                        } catch {
                            coordinator.finish(throwing: error)
                        }
                    }
                    coordinator.setOperationTask(operationTask)

                    let timeoutTask = Task { [timeout = configuration.timeout, remaining] in
                        do {
                            try await Task.sleep(for: remaining)
                            operationTask.cancel()
                            coordinator.finish(throwing: AgentError.timeout(duration: timeout))
                        } catch is CancellationError {
                            return
                        } catch {
                            coordinator.finish(throwing: error)
                        }
                    }
                    coordinator.setTimeoutTask(timeoutTask)
                }
            },
            onCancel: {
                coordinator.cancelPending(with: CancellationError())
            }
        )
    }

    private func normalizeCancellation(_ error: Error) -> Error {
        if error is CancellationError {
            return AgentError.cancelled
        }
        if let agentError = error as? AgentError, agentError == .cancelled {
            return agentError
        }
        return error
    }

    private func fallbackDiagnosticMessage(for error: Error) -> String {
        let described = String(describing: error)
        if described != String(describing: type(of: error)) {
            return described
        }

        let localized = error.localizedDescription
        if !localized.isEmpty {
            return localized
        }

        return String(describing: type(of: error))
    }

    /// Generates a response without tool calling.
    private func generateWithoutTools(
        provider: any InferenceProvider,
        prompt: String,
        messages: [InferenceMessage]?,
        systemPrompt: String,
        inferenceOptions: InferenceOptions,
        enableStreaming: Bool = false,
        observer: (any AgentObserver)?
    ) async throws -> FinalAssistantResponse {
        await observer?.onLLMStart(context: nil, agent: self, systemPrompt: systemPrompt, inputMessages: [MemoryMessage.user(prompt)])

        let options = optionsWithMembraneRuntimeSettings(inferenceOptions)
        let content: String
        let structuredOutput: StructuredOutputResult?
        if let request = options.structuredOutput {
            let result: StructuredOutputResult
            if let messages,
               let nativeProvider = provider as? any StructuredOutputConversationInferenceProvider
            {
                result = try await nativeProvider.generateStructured(messages: messages, request: request, options: options)
            } else if let messages,
                      let conversationProvider = provider as? any ConversationInferenceProvider
            {
                result = try await conversationProvider.generateStructured(messages: messages, request: request, options: options)
            } else if let nativeProvider = provider as? any StructuredOutputInferenceProvider {
                result = try await nativeProvider.generateStructured(prompt: prompt, request: request, options: options)
            } else {
                result = try await provider.generateStructured(prompt: prompt, request: request, options: options)
            }
            content = result.rawJSON
            structuredOutput = result
        } else if enableStreaming {
            var streamedContent = ""
            streamedContent.reserveCapacity(1024)
            let stream: AsyncThrowingStream<String, Error>
            if let messages,
               let conversationProvider = provider as? any StreamingConversationInferenceProvider {
                stream = conversationProvider.stream(messages: messages, options: options)
            } else {
                stream = provider.stream(prompt: prompt, options: options)
            }
            for try await token in stream {
                if !token.isEmpty {
                    streamedContent += token
                }
                await observer?.onOutputToken(context: nil, agent: self, token: token)
            }
            content = streamedContent
            structuredOutput = nil
        } else {
            if let messages,
               let conversationProvider = provider as? any ConversationInferenceProvider {
                content = try await conversationProvider.generate(messages: messages, options: options)
            } else {
                content = try await provider.generate(
                    prompt: prompt,
                    options: options
                )
            }
            structuredOutput = nil
        }

        await observer?.onLLMEnd(context: nil, agent: self, response: content, usage: nil)
        return FinalAssistantResponse(content: content, structuredOutput: structuredOutput)
    }

    /// Processes tool calls from the model response.
    private func processToolCalls(
        response: InferenceResponse,
        toolRegistry: ToolRegistry,
        conversationHistory: inout [ConversationMessage],
        transcriptMessages: inout [MemoryMessage],
        resultBuilder: AgentResult.Builder,
        observer: (any AgentObserver)?,
        tracing: TracingHelper?,
        membraneAdapter: (any MembraneAgentAdapter)?
    ) async throws {
        let toolCallSummary = response.toolCalls.map { "Calling tool: \($0.name)" }.joined(separator: ", ")
        let assistantContent = response.content ?? toolCallSummary
        conversationHistory.append(.assistant(assistantContent, toolCalls: response.toolCalls))
        transcriptMessages.append(
            SwarmTranscriptCodec.encodeMessage(
                role: .assistant,
                content: assistantContent,
                toolCalls: response.toolCalls
            )
        )

        for parsedCall in response.toolCalls {
            try await executeSingleToolCall(
                parsedCall: parsedCall,
                toolRegistry: toolRegistry,
                conversationHistory: &conversationHistory,
                transcriptMessages: &transcriptMessages,
                resultBuilder: resultBuilder,
                observer: observer,
                tracing: tracing,
                membraneAdapter: membraneAdapter,
                startTime: ContinuousClock.now
            )
        }
    }

    /// Executes a single tool call and updates conversation history.
    private func executeSingleToolCall(
        parsedCall: InferenceResponse.ParsedToolCall,
        toolRegistry: ToolRegistry,
        conversationHistory: inout [ConversationMessage],
        transcriptMessages: inout [MemoryMessage],
        resultBuilder: AgentResult.Builder,
        observer: (any AgentObserver)?,
        tracing: TracingHelper?,
        membraneAdapter: (any MembraneAgentAdapter)?,
        startTime: ContinuousClock.Instant
    ) async throws {
        let activeMemory = resolvedMemory()

        if let membraneAdapter,
           MembraneInternalTools.isInternalTool(parsedCall.name) {
            let call = ToolCall(
                providerCallId: parsedCall.id,
                toolName: parsedCall.name,
                arguments: parsedCall.arguments
            )
            _ = resultBuilder.addToolCall(call)
            await observer?.onToolStart(context: nil, agent: self, call: call)

            let spanID = await tracing?.traceToolCall(name: parsedCall.name, arguments: parsedCall.arguments)
            let toolStartTime = ContinuousClock.now

            do {
                let output = try await executeWithinRemainingTimeout(startTime: startTime) {
                    try await membraneAdapter.handleInternalToolCall(
                        name: parsedCall.name,
                        arguments: parsedCall.arguments
                    ) ?? "ok"
                }

                let duration = ContinuousClock.now - toolStartTime
                let result = ToolResult.success(callId: call.id, output: .string(output), duration: duration)
                _ = resultBuilder.addToolResult(result)
                conversationHistory.append(.toolResult(
                    toolName: parsedCall.name,
                    result: output,
                    toolCallID: parsedCall.id
                ))
                transcriptMessages.append(
                    SwarmTranscriptCodec.encodeMessage(
                        role: .tool,
                        content: output,
                        toolName: parsedCall.name,
                        toolCallID: parsedCall.id
                    )
                )
                if let activeMemory {
                    await activeMemory.add(.tool(output, toolName: parsedCall.name))
                }
                if let spanID {
                    await tracing?.traceToolResult(
                        spanId: spanID,
                        name: parsedCall.name,
                        result: output,
                        duration: duration
                    )
                }
                await observer?.onToolEnd(context: nil, agent: self, result: result)
                return
            } catch {
                let duration = ContinuousClock.now - toolStartTime
                let message = error.localizedDescription
                let result = ToolResult.failure(callId: call.id, error: message, duration: duration)
                _ = resultBuilder.addToolResult(result)
                if let spanID {
                    await tracing?.traceToolError(spanId: spanID, name: parsedCall.name, error: error)
                }
                await observer?.onToolEnd(context: nil, agent: self, result: result)
                if configuration.stopOnToolError {
                    throw AgentError.toolExecutionFailed(toolName: parsedCall.name, underlyingError: message)
                }
                conversationHistory.append(.toolResult(
                    toolName: parsedCall.name,
                    result: "[TOOL ERROR] Execution failed: \(message). Please try a different approach or tool.",
                    toolCallID: parsedCall.id
                ))
                transcriptMessages.append(
                    SwarmTranscriptCodec.encodeMessage(
                        role: .tool,
                        content: "[TOOL ERROR] Execution failed: \(message). Please try a different approach or tool.",
                        toolName: parsedCall.name,
                        toolCallID: parsedCall.id
                    )
                )
                if let activeMemory {
                    await activeMemory.add(.tool("Error - \(message)", toolName: parsedCall.name))
                }
                return
            }
        }

        let engine = ToolExecutionEngine()
        let outcome = try await executeWithinRemainingTimeout(startTime: startTime) {
            try await engine.execute(
                parsedCall,
                registry: toolRegistry,
                agent: self,
                context: nil,
                resultBuilder: resultBuilder,
                observer: observer,
                tracing: tracing,
                stopOnToolError: false
            )
        }

        if outcome.result.isSuccess {
            var toolOutputText = Self.toolOutputText(for: outcome.result.output)
            if let membraneAdapter {
                do {
                    let currentToolOutput = toolOutputText
                    let transformed = try await executeWithinRemainingTimeout(startTime: startTime) {
                        try await membraneAdapter.transformToolResult(
                            toolName: parsedCall.name,
                            output: currentToolOutput,
                            profile: configuration.effectiveContextProfile
                        )
                    }
                    toolOutputText = transformed.textForConversation
                    if let pointerID = transformed.pointerID {
                        _ = resultBuilder.setMetadata("membrane.pointerized", .bool(true))
                        _ = resultBuilder.setMetadata("membrane.pointer.last_id", .string(pointerID))
                    }
                } catch {
                    _ = resultBuilder.setMetadata("membrane.fallback.used", .bool(true))
                    _ = resultBuilder.setMetadata("membrane.fallback.error", .string(fallbackDiagnosticMessage(for: error)))
                }
            }

            conversationHistory.append(.toolResult(
                toolName: parsedCall.name,
                result: toolOutputText,
                toolCallID: parsedCall.id
            ))
            transcriptMessages.append(
                SwarmTranscriptCodec.encodeMessage(
                    role: .tool,
                    content: toolOutputText,
                    toolName: parsedCall.name,
                    toolCallID: parsedCall.id
                )
            )
            if let activeMemory {
                await activeMemory.add(.tool(toolOutputText, toolName: parsedCall.name))
            }
        } else {
            let errorMessage = outcome.result.errorMessage ?? "Unknown error"
            conversationHistory.append(.toolResult(
                toolName: parsedCall.name,
                result: "[TOOL ERROR] Execution failed: \(errorMessage). Please try a different approach or tool.",
                toolCallID: parsedCall.id
            ))
            transcriptMessages.append(
                SwarmTranscriptCodec.encodeMessage(
                    role: .tool,
                    content: "[TOOL ERROR] Execution failed: \(errorMessage). Please try a different approach or tool.",
                    toolName: parsedCall.name,
                    toolCallID: parsedCall.id
                )
            )
            if let activeMemory {
                await activeMemory.add(.tool("Error - \(errorMessage)", toolName: parsedCall.name))
            }

            if configuration.stopOnToolError {
                throw AgentError.toolExecutionFailed(toolName: parsedCall.name, underlyingError: errorMessage)
            }
        }
    }

    /// Serializes a non-string tool result as canonical JSON so downstream
    /// consumers (Membrane pointerization, transcript replay, model context)
    /// receive a parsable contract rather than `SendableValue.description`'s
    /// JSON-ish format which does not escape quotes, backslashes, or newlines.
    ///
    /// Plain-string results pass through unchanged. Falls back to
    /// `description` if the value contains a non-finite double — `JSONSerialization`
    /// raises an Objective-C `NSException` (not a Swift error) on NaN/Infinity,
    /// so we must screen the value before serializing rather than relying on
    /// `do/catch`.
    static func toolOutputText(for output: SendableValue) -> String {
        if let string = output.stringValue {
            return string
        }

        guard !containsNonFiniteDouble(output) else {
            return output.description
        }

        do {
            let object = output.toJSONObject()
            let data = try JSONSerialization.data(
                withJSONObject: object,
                options: [.sortedKeys, .fragmentsAllowed]
            )
            if let text = String(data: data, encoding: .utf8) {
                return text
            }
        } catch {
            Log.agents.warning("Tool output JSON serialization failed; falling back to description: \(error)")
        }

        return output.description
    }

    private static func containsNonFiniteDouble(_ value: SendableValue) -> Bool {
        switch value {
        case let .double(number):
            return !number.isFinite
        case let .array(values):
            return values.contains(where: containsNonFiniteDouble)
        case let .dictionary(values):
            return values.values.contains(where: containsNonFiniteDouble)
        case .null, .bool, .int, .string:
            return false
        }
    }

    // MARK: - Handoff Tool Schema Integration

    /// Builds tool schemas including handoff tool schemas.
    ///
    /// This merges regular tool schemas with handoff-generated schemas,
    /// allowing handoffs to appear as callable tools in the LLM prompt.
    private func buildToolSchemasWithHandoffs(
        toolRegistry: ToolRegistry,
        context: AgentContext
    ) async -> [ToolSchema] {
        var schemas = await toolRegistry.schemas

        for handoff in await activeHandoffs(context: context) {
            let handoffSchema = ToolSchema(
                name: handoff.effectiveToolName,
                description: handoff.effectiveToolDescription,
                parameters: [
                    ToolParameter(
                        name: "reason",
                        description: "Reason for the handoff",
                        type: .string,
                        isRequired: false
                    ),
                ]
            )
            schemas.append(handoffSchema)
        }

        return MembraneInternalTools.sortedSchemas(schemas)
    }

    private func activeHandoffs(context: AgentContext) async -> [AnyHandoffConfiguration] {
        var active: [AnyHandoffConfiguration] = []

        for handoff in _handoffs {
            if let when = handoff.when, await !when(context, handoff.targetAgent) {
                continue
            }
            active.append(handoff)
        }

        return active
    }

    /// Processes tool calls, handling both regular tools and handoff tools.
    ///
    /// When a tool call matches a handoff's `effectiveToolName`, the target agent
    /// is executed with the original user input and its result is returned.
    /// Returns the handoff output if a handoff was executed, nil otherwise.
    private func processToolCallsWithHandoffs(
        response: InferenceResponse,
        toolRegistry: ToolRegistry,
        conversationHistory: inout [ConversationMessage],
        transcriptMessages: inout [MemoryMessage],
        resultBuilder: AgentResult.Builder,
        observer: (any AgentObserver)?,
        tracing: TracingHelper?,
        membraneAdapter: (any MembraneAgentAdapter)?,
        context: AgentContext,
        startTime: ContinuousClock.Instant
    ) async throws -> FinalAssistantResponse? {
        let handoffMap = Dictionary(
            uniqueKeysWithValues: _handoffs.map { ($0.effectiveToolName, $0) }
        )

        let toolCallSummary = response.toolCalls.map { "Calling tool: \($0.name)" }.joined(separator: ", ")
        let assistantContent = response.content ?? toolCallSummary
        conversationHistory.append(.assistant(assistantContent, toolCalls: response.toolCalls))
        transcriptMessages.append(
            SwarmTranscriptCodec.encodeMessage(
                role: .assistant,
                content: assistantContent,
                toolCalls: response.toolCalls
            )
        )

        for parsedCall in response.toolCalls {
            // Check if this is a handoff tool call
            if let handoffConfig = handoffMap[parsedCall.name] {
                if let when = handoffConfig.when, await !when(context, handoffConfig.targetAgent) {
                    let message = "Handoff is not enabled"
                    let handoffCall = ToolCall(
                        providerCallId: parsedCall.id,
                        toolName: parsedCall.name,
                        arguments: parsedCall.arguments
                    )
                    _ = resultBuilder.addToolCall(handoffCall)
                    let result = ToolResult.failure(callId: handoffCall.id, error: message, duration: .zero)
                    _ = resultBuilder.addToolResult(result)

                    if configuration.stopOnToolError {
                        throw AgentError.toolExecutionFailed(toolName: parsedCall.name, underlyingError: message)
                    }

                    let toolError = "[TOOL ERROR] Execution failed: \(message). Please try a different approach or tool."
                    conversationHistory.append(.toolResult(
                        toolName: parsedCall.name,
                        result: toolError,
                        toolCallID: parsedCall.id
                    ))
                    transcriptMessages.append(
                        SwarmTranscriptCodec.encodeMessage(
                            role: .tool,
                            content: toolError,
                            toolName: parsedCall.name,
                            toolCallID: parsedCall.id
                        )
                    )
                    continue
                }

                let reason = parsedCall.arguments["reason"]?.stringValue ?? ""
                let targetAgent = handoffConfig.targetAgent

                let handoffStart = ContinuousClock.now
                let spanId = await tracing?.traceToolCall(name: parsedCall.name, arguments: parsedCall.arguments)
                let handoffCall = ToolCall(
                    providerCallId: parsedCall.id,
                    toolName: parsedCall.name,
                    arguments: parsedCall.arguments
                )
                _ = resultBuilder.addToolCall(handoffCall)
                await observer?.onHandoff(context: context, fromAgent: self, toAgent: targetAgent)

                // Find the last user message to use as handoff input
                let lastUserMessage = conversationHistory.last(where: {
                    if case .user = $0 { return true }
                    return false
                })
                let handoffInput: String = if case let .user(content) = lastUserMessage {
                    content
                } else {
                    reason.isEmpty ? "Continue the conversation" : reason
                }

                let initialHandoffData = HandoffInputData(
                    sourceAgentName: name,
                    targetAgentName: targetAgent.name,
                    input: handoffInput,
                    context: await context.snapshot,
                    metadata: reason.isEmpty ? [:] : ["reason": .string(reason)]
                )

                if let onTransfer = handoffConfig.onTransfer {
                    do {
                        try await onTransfer(context, initialHandoffData)
                    } catch {
                        Log.agents.warning("Handoff onTransfer callback failed for \(parsedCall.name): \(error)")
                    }
                }

                let handoffData = HandoffInputData(
                    sourceAgentName: initialHandoffData.sourceAgentName,
                    targetAgentName: initialHandoffData.targetAgentName,
                    input: initialHandoffData.input,
                    context: await context.snapshot,
                    metadata: initialHandoffData.metadata
                )
                let transformedData = handoffConfig.transform?(handoffData) ?? handoffData
                let requestContext = transformedData.context.merging(transformedData.metadata) { _, new in new }
                let handoffContext = await context.copy(additionalValues: requestContext)
                await applyContextValues(requestContext, to: handoffContext)
                await preserveExecutionPath(from: context, in: handoffContext)
                if handoffConfig.nestHandoffHistory {
                    await addNestedHandoffHistory(
                        conversationHistory,
                        to: handoffContext,
                        skippingToolCallID: parsedCall.id
                    )
                }

                let handoffRequest = HandoffRequest(
                    sourceAgentName: transformedData.sourceAgentName,
                    targetAgentName: transformedData.targetAgentName,
                    input: transformedData.input,
                    reason: reason.isEmpty ? nil : reason,
                    context: requestContext
                )

                let result: AgentResult
                do {
                    result = try await executeWithinRemainingTimeout(startTime: startTime) {
                        if let receiver = targetAgent as? any HandoffReceiver {
                            return try await receiver.handleHandoff(handoffRequest, context: handoffContext)
                        } else {
                            let handoffSession = try await makeNestedHandoffSession(
                                from: handoffContext,
                                enabled: handoffConfig.nestHandoffHistory
                            )
                            return try await targetAgent.run(
                                transformedData.input,
                                session: handoffSession,
                                observer: observer
                            )
                        }
                    }
                } catch {
                    let handoffDuration = ContinuousClock.now - handoffStart
                    _ = resultBuilder.addToolResult(
                        ToolResult.failure(
                            callId: handoffCall.id,
                            error: error.localizedDescription,
                            duration: handoffDuration
                        )
                    )
                    if let spanId {
                        await tracing?.traceToolError(spanId: spanId, name: parsedCall.name, error: error)
                    }
                    throw error
                }
                conversationHistory.append(.toolResult(
                    toolName: parsedCall.name,
                    result: result.output,
                    toolCallID: parsedCall.id
                ))
                transcriptMessages.append(
                    SwarmTranscriptCodec.encodeMessage(
                        role: .tool,
                        content: result.output,
                        toolName: parsedCall.name,
                        toolCallID: parsedCall.id
                    )
                )

                let handoffDuration = ContinuousClock.now - handoffStart
                _ = resultBuilder.addToolResult(
                    ToolResult.success(
                        callId: handoffCall.id,
                        output: .string(result.output),
                        duration: handoffDuration
                    )
                )
                if let spanId {
                    await tracing?.traceToolResult(spanId: spanId, name: parsedCall.name, result: result.output, duration: handoffDuration)
                }

                // Merge handoff result metadata into current agent's result builder
                // This preserves token counts, tool calls, and metadata from the target agent
                for toolCall in result.toolCalls {
                    _ = resultBuilder.addToolCall(toolCall)
                }
                for toolResult in result.toolResults {
                    _ = resultBuilder.addToolResult(toolResult)
                }
                if let usage = result.tokenUsage {
                    _ = resultBuilder.setTokenUsage(usage)
                }
                for (key, value) in result.metadata {
                    _ = resultBuilder.setMetadata(key, value)
                }

                // Return the handoff output to be used as the final result
                return FinalAssistantResponse(content: result.output, structuredOutput: nil)
            }

            // Regular tool call
            try await executeSingleToolCall(
                parsedCall: parsedCall,
                toolRegistry: toolRegistry,
                conversationHistory: &conversationHistory,
                transcriptMessages: &transcriptMessages,
                resultBuilder: resultBuilder,
                observer: observer,
                tracing: tracing,
                membraneAdapter: membraneAdapter,
                startTime: startTime
            )
        }

        return nil
    }

    private func applyContextValues(
        _ values: [String: SendableValue],
        to context: AgentContext
    ) async {
        for (key, value) in values {
            await context.set(key, value: value)
        }
    }

    private func preserveExecutionPath(from source: AgentContext, in target: AgentContext) async {
        let executionPath = await source.getExecutionPath()
        for agentName in executionPath {
            await target.recordExecution(agentName: agentName)
        }
    }

    private func makeNestedHandoffSession(
        from context: AgentContext,
        enabled: Bool
    ) async throws -> (any Session)? {
        guard enabled else {
            return nil
        }

        let messages = await context.getMessages()
        guard !messages.isEmpty else {
            return nil
        }

        let session = InMemorySession()
        try await session.addItems(messages)
        return session
    }

    private func addNestedHandoffHistory(
        _ conversationHistory: [ConversationMessage],
        to context: AgentContext,
        skippingToolCallID skippedToolCallID: String?
    ) async {
        for message in conversationHistory {
            switch message {
            case let .system(content):
                await context.addMessage(SwarmTranscriptCodec.encodeMessage(role: .system, content: content))
            case let .user(content):
                await context.addMessage(SwarmTranscriptCodec.encodeMessage(role: .user, content: content))
            case let .assistant(content, toolCalls):
                let nestedToolCalls = toolCalls.filter { $0.id != skippedToolCallID }
                guard toolCalls.isEmpty || !nestedToolCalls.isEmpty else {
                    continue
                }
                await context.addMessage(
                    SwarmTranscriptCodec.encodeMessage(
                        role: .assistant,
                        content: content,
                        toolCalls: nestedToolCalls
                    )
                )
            case let .toolResult(toolName, result, toolCallID):
                guard toolCallID != skippedToolCallID else {
                    continue
                }
                await context.addMessage(
                    SwarmTranscriptCodec.encodeMessage(
                        role: .tool,
                        content: result,
                        toolName: toolName,
                        toolCallID: toolCallID
                    )
                )
            }
        }
    }

    // MARK: - Prompt Building

    private func buildSystemMessage(
        memory: (any Memory)?,
        memoryContext: String = ""
    ) -> String {
        let baseInstructions = instructions.isEmpty
            ? "You are a helpful AI assistant with access to tools."
            : instructions

        if memoryContext.isEmpty {
            return baseInstructions
        }

        let descriptor = memory as? any MemoryPromptDescriptor
        let title = descriptor?.memoryPromptTitle ?? "Relevant Context from Memory"
        let priority = descriptor?.memoryPriority
        let guidance = descriptor?.memoryPromptGuidance ?? {
            guard priority == .primary else { return nil }
            return "Use the memory context as primary source of truth before calling tools."
        }()

        let guidanceBlock = guidance.flatMap { $0.isEmpty ? nil : $0 }

        if let guidanceBlock {
            return """
            \(baseInstructions)

            \(guidanceBlock)

            \(title):
            \(memoryContext)
            """
        }

        return """
        \(baseInstructions)

        \(title):
        \(memoryContext)
        """
    }

    private func buildPrompt(from history: [ConversationMessage]) -> String {
        history.map(\.formatted).joined(separator: "\n\n")
    }

    // MARK: - Response Generation

    private func generateWithTools(
        provider: any InferenceProvider,
        prompt: String,
        messages: [InferenceMessage]?,
        tools: [ToolSchema],
        inferenceOptions: InferenceOptions,
        systemPrompt: String,
        observer: (any AgentObserver)? = nil,
        emitOutputTokens: Bool = false
    ) async throws -> InferenceResponse {
        var options = inferenceOptions
        options = optionsWithMembraneRuntimeSettings(options)

        // Notify observer of LLM start
        await observer?.onLLMStart(context: nil, agent: self, systemPrompt: systemPrompt, inputMessages: [MemoryMessage.user(prompt)])

        let response: InferenceResponse
        if let messages,
           let conversationProvider = provider as? any ConversationInferenceProvider {
            response = try await conversationProvider.generateWithToolCalls(
                messages: messages,
                tools: tools,
                options: options
            )
        } else {
            response = try await provider.generateWithToolCalls(
                prompt: prompt,
                tools: tools,
                options: options
            )
        }

        if emitOutputTokens, response.toolCalls.isEmpty, let content = response.content, !content.isEmpty {
            await observer?.onOutputToken(context: nil, agent: self, token: content)
        }

        // Notify observer of LLM end
        let responseContent = response.content ?? ""
        await observer?.onLLMEnd(context: nil, agent: self, response: responseContent, usage: response.usage)

        return response
    }

    private func generateWithToolsStreaming(
        provider: any InferenceProvider,
        prompt: String,
        messages: [InferenceMessage]?,
        tools: [ToolSchema],
        inferenceOptions: InferenceOptions,
        systemPrompt: String,
        observer: (any AgentObserver)? = nil
    ) async throws -> InferenceResponse {
        var options = inferenceOptions
        options = optionsWithMembraneRuntimeSettings(options)

        await observer?.onLLMStart(context: nil, agent: self, systemPrompt: systemPrompt, inputMessages: [MemoryMessage.user(prompt)])

        var content = ""
        content.reserveCapacity(1024)
        var parsedToolCalls: [InferenceResponse.ParsedToolCall] = []
        var usage: TokenUsage?
        var stopStreaming = false

        let stream: AsyncThrowingStream<InferenceStreamUpdate, Error>
        if let messages,
           let structuredProvider = provider as? any ToolCallStreamingConversationInferenceProvider {
            stream = structuredProvider.streamWithToolCalls(
                messages: messages,
                tools: tools,
                options: options
            )
        } else if let promptProvider = provider as? any ToolCallStreamingInferenceProvider {
            stream = promptProvider.streamWithToolCalls(prompt: prompt, tools: tools, options: options)
        } else {
            throw AgentError.generationFailed(reason: "Provider does not support tool-call streaming")
        }

        for try await update in stream {
            switch update {
            case let .outputChunk(chunk):
                if !chunk.isEmpty { content += chunk }
                await observer?.onOutputToken(context: nil, agent: self, token: chunk)

            case let .toolCallPartial(partial):
                await observer?.onToolCallPartial(context: nil, agent: self, update: partial)

            case let .toolCallsCompleted(calls):
                parsedToolCalls = calls
                // Tool call streaming is primarily used to reduce latency to tool execution.
                // Once we have completed calls, stop consuming the stream and execute tools.
                stopStreaming = true

            case let .usage(u):
                usage = u
            }

            if stopStreaming { break }
        }

        await observer?.onLLMEnd(context: nil, agent: self, response: content, usage: usage)

        return InferenceResponse(
            content: content.isEmpty ? nil : content,
            toolCalls: parsedToolCalls,
            finishReason: parsedToolCalls.isEmpty ? .completed : .toolCall,
            usage: usage
        )
    }

    private func optionsWithMembraneRuntimeSettings(_ base: InferenceOptions) -> InferenceOptions {
        guard let membrane = AgentEnvironmentValues.current.membrane, membrane.isEnabled else {
            return base
        }

        let flags = membrane.configuration.runtimeFeatureFlags
        let allowlist = membrane.configuration.runtimeModelAllowlist

        if flags.isEmpty, allowlist.isEmpty {
            return base
        }

        var updated = base
        var settings = updated.providerSettings ?? [:]

        for (key, isEnabled) in flags {
            let prefix = "conduit.runtime."
            guard key.hasPrefix(prefix) else { continue }
            let feature = String(key.dropFirst(prefix.count))
            settings["conduit.runtime.policy.\(feature).enabled"] = .bool(isEnabled)
        }

        if !allowlist.isEmpty {
            let uniqueSorted = Array(Set(allowlist)).sorted { $0.utf8.lexicographicallyPrecedes($1.utf8) }
            settings["conduit.runtime.policy.model_allowlist"] = .array(uniqueSorted.map { .string($0) })
        }

        updated.providerSettings = settings.isEmpty ? nil : settings
        return updated
    }
}

// MARK: Agent.Builder

public extension Agent {
    /// Builder for creating Agent instances with a fluent API.
    ///
    /// Uses value semantics (struct) for Swift 6 concurrency safety.
    ///
    /// Example:
    /// ```swift
    /// let agent = Agent.Builder()
    ///     .tools([WeatherTool(), CalculatorTool()])
    ///     .instructions("You are a helpful assistant.")
    ///     .configuration(.default.maxIterations(5))
    ///     .build()
    /// ```
    struct Builder: Sendable {
        // MARK: Public

        // MARK: - Initialization

        /// Creates a new builder.
        public init() {}

        // MARK: - Builder Methods

        /// Sets the tools.
        /// - Parameter tools: The tools to use.
        /// - Returns: A new builder with the tools set.
        @discardableResult
        @available(*, deprecated, message: "Use tools(_:) with typed Tool values or Agent.withTools(@ToolBuilder:) for canonical typed tools.")
        public func tools(_ tools: [any AnyJSONTool]) -> Builder {
            var copy = self
            copy._tools = tools
            return copy
        }

        /// Sets the tools from typed tool instances.
        /// - Parameter tools: The typed tools to use.
        /// - Returns: A new builder with the tools set.
        @discardableResult
        public func tools(_ tools: [some Tool]) -> Builder {
            var copy = self
            copy._tools = tools.map { AnyJSONToolAdapter($0) }
            return copy
        }

        /// Adds a tool (concrete type preferred; Swift resolves `some` before opening `any`).
        /// - Parameter tool: The tool to add.
        /// - Returns: A new builder with the tool added.
        @discardableResult
        @available(*, deprecated, message: "Use addTool(_:) with a typed Tool, or wrap raw tools in a clearly marked advanced adapter.")
        public func addTool(_ tool: some AnyJSONTool) -> Builder {
            var copy = self
            copy._tools.append(tool)
            return copy
        }

        /// Adds a tool from an existential (use when the concrete type is not available at the call site).
        /// - Parameter tool: The tool to add.
        /// - Returns: A new builder with the tool added.
        @discardableResult
        @available(*, deprecated, message: "Use addTool(_:) with a typed Tool, or wrap raw tools in a clearly marked advanced adapter.")
        public func addTool(_ tool: any AnyJSONTool) -> Builder {
            var copy = self
            copy._tools.append(tool)
            return copy
        }

        /// Adds a typed tool.
        /// - Parameter tool: The typed tool to add.
        /// - Returns: A new builder with the tool added.
        @discardableResult
        public func addTool(_ tool: some Tool) -> Builder {
            var copy = self
            copy._tools.append(AnyJSONToolAdapter(tool))
            return copy
        }

        /// Adds built-in tools.
        /// - Returns: A new builder with built-in tools added.
        @discardableResult
        public func withBuiltInTools() -> Builder {
            var copy = self
            copy._tools.append(contentsOf: BuiltInTools.all)
            return copy
        }

        /// Sets the instructions.
        /// - Parameter instructions: The system instructions.
        /// - Returns: A new builder with the instructions set.
        @discardableResult
        public func instructions(_ instructions: String) -> Builder {
            var copy = self
            copy._instructions = instructions
            return copy
        }

        /// Sets the configuration.
        /// - Parameter configuration: The agent configuration.
        /// - Returns: A new builder with the configuration set.
        @discardableResult
        public func configuration(_ configuration: AgentConfiguration) -> Builder {
            var copy = self
            copy._configuration = configuration
            return copy
        }

        /// Sets the memory system.
        /// - Parameter memory: The memory to use.
        /// - Returns: A new builder with the memory set.
        @discardableResult
        public func memory(_ memory: any Memory) -> Builder {
            var copy = self
            copy._memory = memory
            return copy
        }

        /// Sets the inference provider.
        /// - Parameter provider: The provider to use.
        /// - Returns: A new builder with the provider set.
        @discardableResult
        public func inferenceProvider(_ provider: any InferenceProvider) -> Builder {
            var copy = self
            copy._inferenceProvider = provider
            return copy
        }

        /// Sets the tracer for observability.
        /// - Parameter tracer: The tracer to use.
        /// - Returns: A new builder with the tracer set.
        @discardableResult
        public func tracer(_ tracer: any Tracer) -> Builder {
            var copy = self
            copy._tracer = tracer
            return copy
        }

        /// Sets the input guardrails.
        /// - Parameter guardrails: The input guardrails to use.
        /// - Returns: A new builder with the guardrails set.
        @discardableResult
        public func inputGuardrails(_ guardrails: [any InputGuardrail]) -> Builder {
            var copy = self
            copy._inputGuardrails = guardrails
            return copy
        }

        /// Adds an input guardrail.
        /// - Parameter guardrail: The guardrail to add.
        /// - Returns: A new builder with the guardrail added.
        @discardableResult
        public func addInputGuardrail(_ guardrail: any InputGuardrail) -> Builder {
            var copy = self
            copy._inputGuardrails.append(guardrail)
            return copy
        }

        /// Sets the output guardrails.
        /// - Parameter guardrails: The output guardrails to use.
        /// - Returns: A new builder with the guardrails set.
        @discardableResult
        public func outputGuardrails(_ guardrails: [any OutputGuardrail]) -> Builder {
            var copy = self
            copy._outputGuardrails = guardrails
            return copy
        }

        /// Adds an output guardrail.
        /// - Parameter guardrail: The guardrail to add.
        /// - Returns: A new builder with the guardrail added.
        @discardableResult
        public func addOutputGuardrail(_ guardrail: any OutputGuardrail) -> Builder {
            var copy = self
            copy._outputGuardrails.append(guardrail)
            return copy
        }

        /// Sets the guardrail runner configuration.
        /// - Parameter configuration: The guardrail runner configuration.
        /// - Returns: A new builder with the updated configuration.
        @discardableResult
        public func guardrailRunnerConfiguration(_ configuration: GuardrailRunnerConfiguration) -> Builder {
            var copy = self
            copy._guardrailRunnerConfiguration = configuration
            return copy
        }

        /// Sets the handoff configurations.
        /// - Parameter handoffs: The handoff configurations to use.
        /// - Returns: A new builder with the updated handoffs.
        @discardableResult
        public func handoffs(_ handoffs: [AnyHandoffConfiguration]) -> Builder {
            var copy = self
            copy._handoffs = handoffs
            return copy
        }

        /// Adds a handoff configuration.
        /// - Parameter handoff: The handoff configuration to add.
        /// - Returns: A new builder with the handoff added.
        @discardableResult
        public func addHandoff(_ handoff: AnyHandoffConfiguration) -> Builder {
            var copy = self
            copy._handoffs.append(handoff)
            return copy
        }

        /// Adds a handoff target using typed options.
        ///
        /// This is the canonical front-facing handoff API.
        ///
        /// - Parameters:
        ///   - target: The target agent.
        ///   - configure: Optional typed options transformer.
        /// - Returns: A new builder with the handoff added.
        @discardableResult
        public func handoff<Target: AgentRuntime>(
            to target: Target,
            configure: (HandoffOptions<Target>) -> HandoffOptions<Target> = { $0 }
        ) -> Builder {
            var copy = self
            let options = configure(HandoffOptions())
            copy._handoffs.append(options.erasedConfiguration(for: target))
            return copy
        }

        /// Adds multiple handoff targets using Swift parameter packs.
        ///
        /// Example:
        /// ```swift
        /// let agent = try Agent.Builder()
        ///     .handoffs(billingAgent, supportAgent, salesAgent)
        ///     .build()
        /// ```
        @discardableResult
        public func handoffs<each Target: AgentRuntime>(_ targets: repeat each Target) -> Builder {
            var copy = self
            repeat copy._handoffs.append(AnyHandoffConfiguration(targetAgent: each targets))
            return copy
        }

        /// Builds the agent.
        /// - Returns: A new Agent instance.
        /// - Throws: `ToolRegistryError.duplicateToolName` if duplicate tool names are provided.
        public func build() throws -> Agent {
            try Agent(
                tools: _tools,
                instructions: _instructions,
                configuration: _configuration,
                memory: _memory,
                inferenceProvider: _inferenceProvider,
                tracer: _tracer,
                inputGuardrails: _inputGuardrails,
                outputGuardrails: _outputGuardrails,
                guardrailRunnerConfiguration: _guardrailRunnerConfiguration,
                handoffs: _handoffs
            )
        }

        // MARK: Private

        private var _tools: [any AnyJSONTool] = []
        private var _instructions: String = ""
        private var _configuration: AgentConfiguration = .default
        private var _memory: (any Memory)?
        private var _inferenceProvider: (any InferenceProvider)?
        private var _tracer: (any Tracer)?
        private var _inputGuardrails: [any InputGuardrail] = []
        private var _outputGuardrails: [any OutputGuardrail] = []
        private var _guardrailRunnerConfiguration: GuardrailRunnerConfiguration = .default
        private var _handoffs: [AnyHandoffConfiguration] = []
    }
}

// MARK: - Convenience Initializers

public extension Agent {
    /// Creates a new Agent with a name as the first parameter.
    ///
    /// This convenience initializer mirrors the OpenAI Agent SDK pattern
    /// where the agent name is a top-level parameter rather than nested
    /// inside configuration.
    ///
    /// Example:
    /// ```swift
    /// let agent = Agent(name: "Triage", instructions: "Route requests", tools: [weatherTool])
    /// ```
    ///
    /// - Parameters:
    ///   - name: The display name of the agent.
    ///   - instructions: System instructions defining agent behavior. Default: ""
    ///   - tools: Tools available to the agent. Default: []
    ///   - inferenceProvider: Optional custom inference provider. Default: nil
    ///   - memory: Optional explicit memory override. Default: composite ContextCore + Wax memory
    ///   - tracer: Optional tracer for observability. Default: nil
    ///   - configuration: Additional agent configuration settings. Default: .default
    ///   - inputGuardrails: Input validation guardrails. Default: []
    ///   - outputGuardrails: Output validation guardrails. Default: []
    ///   - guardrailRunnerConfiguration: Configuration for guardrail runner. Default: .default
    ///   - handoffs: Handoff configurations for multi-agent orchestration. Default: []
    /// - Throws: `ToolRegistryError.duplicateToolName` if duplicate tool names are provided.
    init(
        name: String,
        instructions: String = "",
        tools: [any AnyJSONTool] = [],
        inferenceProvider: (any InferenceProvider)? = nil,
        memory: (any Memory)? = nil,
        tracer: (any Tracer)? = nil,
        configuration: AgentConfiguration = .default,
        inputGuardrails: [any InputGuardrail] = [],
        outputGuardrails: [any OutputGuardrail] = [],
        guardrailRunnerConfiguration: GuardrailRunnerConfiguration = .default,
        handoffs: [AnyHandoffConfiguration] = []
    ) throws {
        // Merge the name into the configuration
        var config = configuration
        config.name = name
        try self.init(
            tools: tools,
            instructions: instructions,
            configuration: config,
            memory: memory,
            inferenceProvider: inferenceProvider,
            tracer: tracer,
            inputGuardrails: inputGuardrails,
            outputGuardrails: outputGuardrails,
            guardrailRunnerConfiguration: guardrailRunnerConfiguration,
            handoffs: handoffs
        )
    }
}

// MARK: - Simplified Handoff Declaration

public extension Agent {
    /// Creates an Agent with agents directly as handoff targets.
    ///
    /// This convenience initializer eliminates the need to wrap each agent
    /// in `AnyHandoffConfiguration`, inspired by the OpenAI SDK pattern
    /// where you pass agents directly: `Agent(handoffs=[billing, support])`.
    ///
    /// Example:
    /// ```swift
    /// let triage = Agent(
    ///     name: "Triage",
    ///     instructions: "Route requests",
    ///     handoffAgents: [billingAgent, supportAgent]
    /// )
    /// ```
    ///
    /// - Parameters:
    ///   - name: The display name of the agent.
    ///   - instructions: System instructions. Default: ""
    ///   - tools: Tools available to the agent. Default: []
    ///   - inferenceProvider: Optional inference provider. Default: nil
    ///   - memory: Optional explicit memory override. Default: composite ContextCore + Wax memory
    ///   - tracer: Optional tracer. Default: nil
    ///   - configuration: Additional configuration. Default: .default
    ///   - inputGuardrails: Input guardrails. Default: []
    ///   - outputGuardrails: Output guardrails. Default: []
    ///   - guardrailRunnerConfiguration: Guardrail runner config. Default: .default
    ///   - handoffAgents: Agents to use as handoff targets.
    /// - Throws: `ToolRegistryError.duplicateToolName` if duplicate tool names are provided.
    init(
        name: String,
        instructions: String = "",
        tools: [any AnyJSONTool] = [],
        inferenceProvider: (any InferenceProvider)? = nil,
        memory: (any Memory)? = nil,
        tracer: (any Tracer)? = nil,
        configuration: AgentConfiguration = .default,
        inputGuardrails: [any InputGuardrail] = [],
        outputGuardrails: [any OutputGuardrail] = [],
        guardrailRunnerConfiguration: GuardrailRunnerConfiguration = .default,
        handoffAgents: [any AgentRuntime]
    ) throws {
        let handoffs = handoffAgents.map { agent in
            AnyHandoffConfiguration(targetAgent: agent)
        }
        try self.init(
            name: name,
            instructions: instructions,
            tools: tools,
            inferenceProvider: inferenceProvider,
            memory: memory,
            tracer: tracer,
            configuration: configuration,
            inputGuardrails: inputGuardrails,
            outputGuardrails: outputGuardrails,
            guardrailRunnerConfiguration: guardrailRunnerConfiguration,
            handoffs: handoffs
        )
    }
}

// MARK: - V3 Canonical Init with Explicit Provider

public extension Agent {
    /// V3 convenience init with an explicit, non-optional inference provider.
    ///
    /// This overload avoids the optional wrapping when a provider is always known:
    /// ```swift
    /// let agent = try Agent("You are helpful.", provider: .anthropic(key: apiKey)) {
    ///     WeatherTool()
    /// }
    /// ```
    ///
    /// - Parameters:
    ///   - instructions: System instructions defining agent behavior.
    ///   - provider: The inference provider to use.
    ///   - tools: A `@ToolBuilder` closure producing the agent's tools. Default: empty.
    /// - Throws: `ToolRegistryError.duplicateToolName` if duplicate tool names are provided.
    init(
        _ instructions: String,
        provider: some InferenceProvider,
        @ToolBuilder tools: () -> ToolCollection = { .empty }
    ) throws {
        try self.init(
            tools: tools().storage,
            instructions: instructions,
            inferenceProvider: provider
        )
    }
}

// MARK: - V3 Modifiers

public extension Agent {
    /// Sets the memory system. Returns a new Agent with memory configured.
    ///
    /// ```swift
    /// let agent = try Agent("Be helpful.")
    ///     .withMemory(.conversation(maxMessages: 50))
    /// ```
    @discardableResult
    func withMemory(_ memory: some Memory) -> Agent {
        var copy = self
        copy.memory = memory
        return copy
    }

    /// Sets the
Download .txt
gitextract_l9ml5ppr/

├── .github/
│   ├── FUNDING.yml
│   ├── pull_request_template.md
│   └── workflows/
│       ├── claude-code-review.yml
│       ├── claude.yml
│       ├── docs.yml
│       └── swift.yml
├── .gitignore
├── .swiftformat
├── .swiftlint.yml
├── CLAUDE.md
├── Examples/
│   └── CodeReviewer/
│       ├── .gitignore
│       ├── Package.swift
│       ├── Sources/
│       │   └── CodeReviewer/
│       │       ├── Agents/
│       │       │   └── .gitkeep
│       │       ├── Output/
│       │       │   ├── .gitkeep
│       │       │   └── StreamRenderer.swift
│       │       ├── Tools/
│       │       │   └── .gitkeep
│       │       └── main.swift
│       └── Tests/
│           └── CodeReviewerTests/
│               ├── Fixtures/
│               │   └── .gitkeep
│               └── StreamRendererTests.swift
├── LICENSE
├── Package.swift
├── README.md
├── Sources/
│   ├── Swarm/
│   │   ├── Agents/
│   │   │   ├── Agent+Workspace.swift
│   │   │   └── Agent.swift
│   │   ├── Core/
│   │   │   ├── AgentConfiguration+InferenceOptions.swift
│   │   │   ├── AgentConfiguration.swift
│   │   │   ├── AgentEnvironment.swift
│   │   │   ├── AgentError.swift
│   │   │   ├── AgentEvent.swift
│   │   │   ├── AgentResponse.swift
│   │   │   ├── AgentResult.swift
│   │   │   ├── AgentRuntime+Identity.swift
│   │   │   ├── AgentRuntime.swift
│   │   │   ├── CallableAgent.swift
│   │   │   ├── CircularBuffer.swift
│   │   │   ├── ContextProfile.swift
│   │   │   ├── Conversation.swift
│   │   │   ├── ConversationBranching.swift
│   │   │   ├── Environment.swift
│   │   │   ├── EnvironmentAgent.swift
│   │   │   ├── EventStreamHooks.swift
│   │   │   ├── Execution/
│   │   │   │   ├── AgentContext.swift
│   │   │   │   └── ContextKey.swift
│   │   │   ├── Handoff/
│   │   │   │   ├── Handoff.swift
│   │   │   │   ├── HandoffBuilder.swift
│   │   │   │   ├── HandoffConfiguration+Lookup.swift
│   │   │   │   ├── HandoffConfiguration.swift
│   │   │   │   ├── HandoffOptions.swift
│   │   │   │   ├── WorkflowError.swift
│   │   │   │   └── WorkflowValidationError.swift
│   │   │   ├── InferenceStreamEvent.swift
│   │   │   ├── Logger+Swarm.swift
│   │   │   ├── ModelSettings.swift
│   │   │   ├── ObservedAgent.swift
│   │   │   ├── PartialToolCallUpdate.swift
│   │   │   ├── PromptEnvelope.swift
│   │   │   ├── PromptTokenCounter.swift
│   │   │   ├── ReasoningConfig.swift
│   │   │   ├── ResponseTracker.swift
│   │   │   ├── RunHooks.swift
│   │   │   ├── RuntimeMetadata.swift
│   │   │   ├── SendableValue.swift
│   │   │   ├── StreamHelper.swift
│   │   │   ├── StreamOperations.swift
│   │   │   ├── StructuredOutput.swift
│   │   │   ├── SwarmColonySPI.swift
│   │   │   ├── SwarmConfiguration.swift
│   │   │   ├── SwarmTranscript.swift
│   │   │   └── TokenUsage.swift
│   │   ├── Extensions/
│   │   │   └── Extensions.swift
│   │   ├── Guardrails/
│   │   │   ├── Guardrail.swift
│   │   │   ├── GuardrailError.swift
│   │   │   ├── GuardrailResult.swift
│   │   │   ├── GuardrailRunner.swift
│   │   │   ├── InputGuardrail.swift
│   │   │   ├── OutputGuardrail.swift
│   │   │   └── ToolGuardrails.swift
│   │   ├── Integration/
│   │   │   ├── Membrane/
│   │   │   │   ├── MembraneAgentAdapter.swift
│   │   │   │   ├── MembraneInternalTools.swift
│   │   │   │   ├── SessionMembraneAgentAdapter.swift
│   │   │   │   └── WaxMembraneStorage.swift
│   │   │   └── Wax/
│   │   │       ├── WaxEmbeddingProviderAdapters.swift
│   │   │       ├── WaxIntegration.swift
│   │   │       └── WaxMemory.swift
│   │   ├── Internal/
│   │   │   ├── GraphRuntime/
│   │   │   │   ├── ChatGraph.swift
│   │   │   │   ├── GraphAgent.swift
│   │   │   │   ├── HiveChatCompatibility.swift
│   │   │   │   ├── HiveCodableJSONCodec.swift
│   │   │   │   ├── RetryPolicyBridge.swift
│   │   │   │   ├── RuntimeHardening.swift
│   │   │   │   └── ToolRegistryAdapter.swift
│   │   │   └── SwarmRuntimeEnvironment.swift
│   │   ├── MCP/
│   │   │   ├── HTTPMCPServer.swift
│   │   │   ├── MCPCapabilities.swift
│   │   │   ├── MCPClient.swift
│   │   │   ├── MCPError.swift
│   │   │   ├── MCPProtocol.swift
│   │   │   ├── MCPResource.swift
│   │   │   ├── MCPServer.swift
│   │   │   └── MCPToolBridge.swift
│   │   ├── Macros/
│   │   │   └── MacroDeclarations.swift
│   │   ├── Memory/
│   │   │   ├── AgentMemory.swift
│   │   │   ├── Backends/
│   │   │   │   ├── InMemoryBackend.swift
│   │   │   │   └── SwiftDataBackend.swift
│   │   │   ├── CompositeMemory.swift
│   │   │   ├── ContextCoreMemory.swift
│   │   │   ├── ConversationMemory.swift
│   │   │   ├── DefaultAgentMemory.swift
│   │   │   ├── EmbeddingProvider.swift
│   │   │   ├── HybridMemory.swift
│   │   │   ├── InMemorySession.swift
│   │   │   ├── InferenceProviderSummarizer.swift
│   │   │   ├── MemoryMessage.swift
│   │   │   ├── MemoryPromptDescriptor.swift
│   │   │   ├── MemoryRetrievalPolicy.swift
│   │   │   ├── MemorySessionLifecycle.swift
│   │   │   ├── PersistedMessage.swift
│   │   │   ├── PersistentMemory.swift
│   │   │   ├── PersistentMemoryBackend.swift
│   │   │   ├── PersistentSession.swift
│   │   │   ├── Session.swift
│   │   │   ├── SlidingWindowMemory.swift
│   │   │   ├── Summarizer.swift
│   │   │   ├── SummaryMemory.swift
│   │   │   ├── SwiftDataMemory.swift
│   │   │   ├── TokenEstimator.swift
│   │   │   └── VectorMemory.swift
│   │   ├── Observability/
│   │   │   ├── AgentTracer.swift
│   │   │   ├── ConsoleTracer.swift
│   │   │   ├── MetricsCollector.swift
│   │   │   ├── OSLogTracer.swift
│   │   │   ├── PerformanceMetrics.swift
│   │   │   ├── SwiftLogTracer.swift
│   │   │   ├── TraceContext.swift
│   │   │   ├── TraceEvent.swift
│   │   │   ├── TraceEventPublicLogSanitizer.swift
│   │   │   ├── TraceSpan.swift
│   │   │   └── TracingHelper.swift
│   │   ├── Providers/
│   │   │   ├── Conduit/
│   │   │   │   ├── ConduitInferenceProvider.swift
│   │   │   │   ├── ConduitProviderSelection.swift
│   │   │   │   ├── LLM.swift
│   │   │   │   ├── MLXPromptProvider.swift
│   │   │   │   ├── OllamaSettings.swift
│   │   │   │   └── OpenRouterRouting.swift
│   │   │   ├── ConversationInferenceProvider.swift
│   │   │   ├── DefaultInferenceProviderFactory.swift
│   │   │   ├── InferenceProviderMetadata.swift
│   │   │   ├── LanguageModelSession.swift
│   │   │   ├── LanguageModelSessionHelpers.swift
│   │   │   ├── MultiProvider.swift
│   │   │   ├── TextOnlyConversationInferenceProviderAdapter.swift
│   │   │   └── ToolCallStreamingInferenceProvider.swift
│   │   ├── Resilience/
│   │   │   ├── CircuitBreaker.swift
│   │   │   ├── FallbackChain.swift
│   │   │   ├── RateLimiter.swift
│   │   │   ├── Resilience.swift
│   │   │   └── RetryPolicy.swift
│   │   ├── Swarm.swift
│   │   ├── Tools/
│   │   │   ├── AgentTool.swift
│   │   │   ├── ArithmeticParser.swift
│   │   │   ├── BuiltInTools.swift
│   │   │   ├── ParallelToolExecutor.swift
│   │   │   ├── SemanticCompactorTool.swift
│   │   │   ├── Tool.swift
│   │   │   ├── ToolBridgeHelper.swift
│   │   │   ├── ToolBridging.swift
│   │   │   ├── ToolCallGoal.swift
│   │   │   ├── ToolCollection.swift
│   │   │   ├── ToolExecutionEngine.swift
│   │   │   ├── ToolExecutionResult.swift
│   │   │   ├── ToolExecutionSemantics.swift
│   │   │   ├── ToolParameterBuilder.swift
│   │   │   ├── Web/
│   │   │   │   └── WebSearchSupport.swift
│   │   │   ├── WebSearchTool.swift
│   │   │   └── ZoniSearchTool.swift
│   │   ├── Workflow/
│   │   │   ├── Workflow+Durable.swift
│   │   │   ├── Workflow.swift
│   │   │   ├── WorkflowCheckpointCodec.swift
│   │   │   ├── WorkflowCheckpointStore.swift
│   │   │   ├── WorkflowCheckpointing.swift
│   │   │   ├── WorkflowDurableEngine.swift
│   │   │   └── WorkflowResultSnapshot.swift
│   │   └── Workspace/
│   │       ├── AgentWorkspace.swift
│   │       ├── WorkspaceMemory.swift
│   │       └── WorkspaceWriter.swift
│   ├── SwarmCapabilityShowcase/
│   │   └── main.swift
│   ├── SwarmCapabilityShowcaseSupport/
│   │   └── CapabilityShowcase.swift
│   ├── SwarmDemo/
│   │   ├── AgentTest.swift
│   │   └── SwarmPlayground.playground/
│   │       ├── Pages/
│   │       │   └── New.xcplaygroundpage/
│   │       │       └── Contents.swift
│   │       └── contents.xcplayground
│   ├── SwarmMCP/
│   │   ├── SwarmMCPErrorMapper.swift
│   │   ├── SwarmMCPServerService.swift
│   │   ├── SwarmMCPToolAdapter.swift
│   │   ├── SwarmMCPToolMapper.swift
│   │   └── SwarmMCPValueMapper.swift
│   ├── SwarmMCPServerDemo/
│   │   └── main.swift
│   ├── SwarmMacros/
│   │   ├── AgentMacro.swift
│   │   ├── BuilderMacro.swift
│   │   ├── InlineToolMacro.swift
│   │   ├── ParameterMacro.swift
│   │   ├── Plugin.swift
│   │   ├── PromptMacro.swift
│   │   ├── ToolMacro.swift
│   │   └── TraceableMacro.swift
│   ├── SwarmMembrane/
│   │   └── SwarmMembrane.swift
│   └── SwarmOpenTelemetry/
│       ├── OpenTelemetryAgentRuntime.swift
│       ├── OpenTelemetryAnyInferenceProvider.swift
│       ├── OpenTelemetryAttributes.swift
│       ├── OpenTelemetryInferenceProvider.swift
│       └── SwarmTypeAliases.swift
├── Tests/
│   ├── HiveSwarmTests/
│   │   ├── ChatGraphTests.swift
│   │   ├── GraphAgentStreamingTests.swift
│   │   ├── MembraneHiveCheckpointTests.swift
│   │   ├── ModelRouterTests.swift
│   │   ├── RetryPolicyBridgeTests.swift
│   │   └── WorkflowHiveEngineTests.swift
│   ├── SwarmCapabilityShowcaseTests/
│   │   └── CapabilityShowcaseTests.swift
│   ├── SwarmMacrosTests/
│   │   ├── AgentMacroTests.swift
│   │   ├── InlineToolMacroTests.swift
│   │   ├── MacroIntegrationTests.swift
│   │   ├── PromptMacroTests.swift
│   │   ├── PromptStringTestSupport.swift
│   │   ├── ToolMacroTests.swift
│   │   └── TraceableMacroTests.swift
│   ├── SwarmOpenTelemetryTests/
│   │   ├── OpenTelemetryInferenceProviderTests.swift
│   │   └── OpenTelemetryPublicAPITests.swift
│   └── SwarmTests/
│       ├── APIAuditTests.swift
│       ├── Agents/
│       │   ├── AgentCodexReviewFixesTests.swift
│       │   ├── AgentConduitProviderSelectionStreamingTests.swift
│       │   ├── AgentDefaultInferenceProviderTests.swift
│       │   ├── AgentHandoffRuntimeTests.swift
│       │   ├── AgentLiveToolCallStreamingTests.swift
│       │   ├── AgentReliabilityTests.swift
│       │   ├── AgentResponseContinuationTests.swift
│       │   ├── AgentStructuredInferenceProviderTests.swift
│       │   ├── AgentTests.swift
│       │   ├── AgentToolOutputTextTests.swift
│       │   ├── AgentTranscriptContractTests.swift
│       │   ├── StreamingEventTests.swift
│       │   └── Strict4kPromptEnvelopeTests.swift
│       ├── ContextCoreIntegrationTests.swift
│       ├── Core/
│       │   ├── AgentConfigurationInferenceOptionsTests.swift
│       │   ├── AgentErrorTests.swift
│       │   ├── AgentEventTests+Integration.swift
│       │   ├── AgentEventTests+ToolCall.swift
│       │   ├── AgentEventTests+ToolResult.swift
│       │   ├── AgentEventTests.swift
│       │   ├── AgentObserverTests.swift
│       │   ├── AgentResultRuntimeEngineTests.swift
│       │   ├── ContextProfileTests.swift
│       │   ├── ConversationTests.swift
│       │   ├── CoreTests.swift
│       │   ├── HandoffBehaviorTests.swift
│       │   ├── InferenceTypesTests.swift
│       │   ├── ModelSettingsTests+Enums.swift
│       │   ├── ModelSettingsTests+Validation.swift
│       │   ├── ModelSettingsTests.swift
│       │   ├── ReasoningConfigTests.swift
│       │   ├── ResponseTrackerTests+BasicTests.swift
│       │   ├── ResponseTrackerTests+CleanupTests.swift
│       │   ├── ResponseTrackerTests+ConcurrencyTests.swift
│       │   ├── ResponseTrackerTests+HistoryTests.swift
│       │   ├── ResponseTrackerTests.swift
│       │   ├── RunHooksTests.swift
│       │   ├── StreamOperationsTests.swift
│       │   ├── SwarmConfigurationTests.swift
│       │   └── SwarmRuntimeEnvironmentTests.swift
│       ├── DocumentationFreshnessTests.swift
│       ├── Extensions/
│       │   └── DurationExtensionsTests.swift
│       ├── Guardrails/
│       │   ├── AgentRunGuardrailBehaviorTests.swift
│       │   ├── GuardrailErrorTests.swift
│       │   ├── GuardrailIntegrationTests.swift
│       │   ├── GuardrailResultTests.swift
│       │   ├── InputGuardrailTests.swift
│       │   ├── OutputGuardrailTests.swift
│       │   └── ToolGuardrailTests.swift
│       ├── HiveSwarm/
│       │   └── ToolRegistryAdapterTests.swift
│       ├── Integration/
│       │   ├── FullAPIScenarioTests.swift
│       │   ├── MCPIntegrationTests.swift
│       │   ├── SessionIntegrationTests.swift
│       │   ├── WaxIntegrationTests.swift
│       │   └── WorkflowResumeIntegrationTests.swift
│       ├── MCP/
│       │   ├── HTTPMCPServerRetryTests.swift
│       │   ├── HTTPMCPServerTests.swift
│       │   ├── MCPClientTests+Caching.swift
│       │   ├── MCPClientTests+Mocks.swift
│       │   ├── MCPClientTests.swift
│       │   ├── MCPProtocolTests.swift
│       │   ├── SwarmMCPServerServiceTests+Mocks.swift
│       │   └── SwarmMCPServerServiceTests.swift
│       ├── Macros/
│       │   └── AgentActorMacroConformanceTests.swift
│       ├── MembraneIntegrationTests.swift
│       ├── Memory/
│       │   ├── ContextCoreDefaultMemoryTests.swift
│       │   ├── ConversationMemoryTests.swift
│       │   ├── HybridMemoryTests.swift
│       │   ├── InMemorySessionTests.swift
│       │   ├── MemoryClearGenerationTests.swift
│       │   ├── MemoryIngestionPolicyTests.swift
│       │   ├── MemoryMessageTests.swift
│       │   ├── PersistentMemoryTests.swift
│       │   ├── PersistentSessionTests.swift
│       │   ├── SessionTests.swift
│       │   ├── SlidingWindowMemoryTests.swift
│       │   ├── SummarizerTests.swift
│       │   ├── SummaryMemoryTests.swift
│       │   ├── SwiftDataMemoryTests.swift
│       │   ├── TokenEstimatorTests.swift
│       │   ├── VectorMemorySemanticRetrievalTests.swift
│       │   └── WaxMemoryTests.swift
│       ├── Mocks/
│       │   ├── MockAgentMemory.swift
│       │   ├── MockAgentRuntime.swift
│       │   ├── MockEmbeddingProvider.swift
│       │   ├── MockInferenceProvider.swift
│       │   ├── MockSummarizer.swift
│       │   ├── MockTool.swift
│       │   └── SwarmConfigurationTestIsolation.swift
│       ├── Observability/
│       │   ├── ObservabilityPrivacyTests.swift
│       │   ├── ObservabilityTests+Metrics.swift
│       │   ├── ObservabilityTests+TraceEvents.swift
│       │   ├── ObservabilityTests+Tracers.swift
│       │   ├── ObservabilityTests.swift
│       │   ├── PerformanceMetricsTests.swift
│       │   ├── TraceContextTests.swift
│       │   ├── TraceSpanTests.swift
│       │   ├── TracerTests+Buffered.swift
│       │   ├── TracerTests+EdgeCases.swift
│       │   ├── TracerTests+Integration.swift
│       │   ├── TracerTests+NoOp.swift
│       │   ├── TracerTests+TypeErasure.swift
│       │   └── TracerTests.swift
│       ├── Providers/
│       │   ├── ConduitAdvancedCompatibility.swift
│       │   ├── ConduitInferenceProviderTests.swift
│       │   ├── ConduitProviderSelectionTests.swift
│       │   ├── ConduitStructuredMessageBridgeTests.swift
│       │   ├── ConduitToolCallStreamingBridgeTests.swift
│       │   ├── FoundationModelsToolCallingTests.swift
│       │   ├── InferenceProviderCertificationTests.swift
│       │   ├── LLMPresetsTests.swift
│       │   ├── LanguageModelSessionTests.swift
│       │   ├── MultiProviderTests.swift
│       │   ├── ProviderCertificationSupport.swift
│       │   └── TextOnlyConversationInferenceProviderAdapterTests.swift
│       ├── Regression/
│       │   └── FrameworkDXRegressionTests.swift
│       ├── Resilience/
│       │   ├── ResilienceTests+CircuitBreaker.swift
│       │   ├── ResilienceTests+Fallback.swift
│       │   ├── ResilienceTests+Integration.swift
│       │   ├── ResilienceTests+RateLimiter.swift
│       │   ├── ResilienceTests+Retry.swift
│       │   └── ResilienceTests.swift
│       ├── SwiftAgentsTests.swift
│       ├── Tools/
│       │   ├── AgentToolTests.swift
│       │   ├── AnyToolTests.swift
│       │   ├── ArithmeticParserTests.swift
│       │   ├── CalculatorToolTests.swift
│       │   ├── FunctionToolTests.swift
│       │   ├── ParallelToolExecutorTests+Advanced.swift
│       │   ├── ParallelToolExecutorTests+Mocks.swift
│       │   ├── ParallelToolExecutorTests.swift
│       │   ├── SemanticCompactorToolBehaviorTests.swift
│       │   ├── ToolParameterTests.swift
│       │   ├── ToolSchemaIntegrationTests.swift
│       │   ├── WebSearchSupportTests.swift
│       │   ├── WebSearchToolBehaviorTests.swift
│       │   └── ZoniSearchToolTests.swift
│       ├── V2SurfaceAuditTests.swift
│       ├── V3/
│       │   ├── AgentCanonicalInitTests.swift
│       │   ├── AgentEvalTests.swift
│       │   ├── AgentModifiersTests.swift
│       │   ├── GuardrailFactoryTests.swift
│       │   ├── MemoryFactoryTests.swift
│       │   ├── MemoryFactoryV3Tests.swift
│       │   ├── ProviderFactoryTests.swift
│       │   ├── ReadmeProviderCompileTests.swift
│       │   ├── SwarmConfigTests.swift
│       │   ├── ToolBuilderV3Tests.swift
│       │   ├── ToolCollectionTests.swift
│       │   └── ZombieAPIRemovalTests.swift
│       ├── Workflow/
│       │   ├── WorkflowDurableTests.swift
│       │   └── WorkflowTests.swift
│       └── Workspace/
│           └── AgentWorkspaceTests.swift
├── docs/
│   ├── .vitepress/
│   │   ├── config.ts
│   │   └── theme/
│   │       ├── index.ts
│   │       └── style.css
│   ├── guide/
│   │   ├── agent-workspace.md
│   │   ├── capability-showcase.md
│   │   ├── getting-started.md
│   │   ├── opentelemetry-tracing.md
│   │   └── why-swarm.md
│   ├── index.md
│   ├── public/
│   │   └── CNAME
│   ├── reference/
│   │   ├── api-catalog.md
│   │   ├── durable-runtime-hardening.md
│   │   ├── front-facing-api.md
│   │   └── overview.md
│   └── release/
│       └── release-checklist.md
└── package.json
Condensed preview — 396 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (4,222K chars).
[
  {
    "path": ".github/FUNDING.yml",
    "chars": 26,
    "preview": "github: christopherkarani\n"
  },
  {
    "path": ".github/pull_request_template.md",
    "chars": 4941,
    "preview": "# Pull Request\n\n## Thank you for contributing to Swarm! 🎉\n\nWe appreciate your effort to improve the framework. This temp"
  },
  {
    "path": ".github/workflows/claude-code-review.yml",
    "chars": 3199,
    "preview": "name: Claude Code Review\n\non:\n  pull_request:\n    types: [opened, synchronize]\n    # Optional: Only run on specific file"
  },
  {
    "path": ".github/workflows/claude.yml",
    "chars": 2387,
    "preview": "name: Claude Code\n\non:\n  issue_comment:\n    types: [created]\n  pull_request_review_comment:\n    types: [created]\n  issue"
  },
  {
    "path": ".github/workflows/docs.yml",
    "chars": 994,
    "preview": "name: Deploy Docs\n\non:\n  pull_request:\n    paths:\n      - \"docs/**\"\n      - \"package.json\"\n      - \"package-lock.json\"\n "
  },
  {
    "path": ".github/workflows/swift.yml",
    "chars": 3062,
    "preview": "# Swarm CI Workflow\n# Builds and tests on macOS; verifies the Linux core build lane on Ubuntu\n\nname: Swift CI\n\non:\n  pus"
  },
  {
    "path": ".gitignore",
    "chars": 1792,
    "preview": ".DS_Store\n/.build\n/Packages\nxcuserdata/\nDerivedData/\n.swiftpm/configuration/registries.json\n.swiftpm/xcode/package.xcwor"
  },
  {
    "path": ".swiftformat",
    "chars": 819,
    "preview": "--swiftversion 6.2\n--exclude .build,.swiftpm,.worktrees,Packages,node_modules,docs/.vitepress\n--disable andOperator,blan"
  },
  {
    "path": ".swiftlint.yml",
    "chars": 687,
    "preview": "included:\n  - Sources\n  - Tests\n\nexcluded:\n  - .build\n  - .swiftpm\n  - .worktrees\n  - Packages\n  - node_modules\n  - docs"
  },
  {
    "path": "CLAUDE.md",
    "chars": 13620,
    "preview": "# CLAUDE.md\n\nGuidance for AI coding assistants (Claude Code, Cursor, etc.) working in this\nrepository. This file is the "
  },
  {
    "path": "Examples/CodeReviewer/.gitignore",
    "chars": 42,
    "preview": ".build/\n.swiftpm/\n*.resolved\nDerivedData/\n"
  },
  {
    "path": "Examples/CodeReviewer/Package.swift",
    "chars": 926,
    "preview": "// swift-tools-version: 6.2\n\nimport PackageDescription\n\nlet package = Package(\n    name: \"CodeReviewer\",\n    platforms: "
  },
  {
    "path": "Examples/CodeReviewer/Sources/CodeReviewer/Agents/.gitkeep",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "Examples/CodeReviewer/Sources/CodeReviewer/Output/.gitkeep",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "Examples/CodeReviewer/Sources/CodeReviewer/Output/StreamRenderer.swift",
    "chars": 1946,
    "preview": "import Foundation\n\npublic enum AgentRole: Sendable {\n    case security, performance, style, synthesizer\n\n    var label: "
  },
  {
    "path": "Examples/CodeReviewer/Sources/CodeReviewer/Tools/.gitkeep",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "Examples/CodeReviewer/Sources/CodeReviewer/main.swift",
    "chars": 3336,
    "preview": "import Foundation\nimport Swarm\n\nlet arguments = CommandLine.arguments.dropFirst()\nlet request = try ReviewRequest(argume"
  },
  {
    "path": "Examples/CodeReviewer/Tests/CodeReviewerTests/Fixtures/.gitkeep",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "Examples/CodeReviewer/Tests/CodeReviewerTests/StreamRendererTests.swift",
    "chars": 2619,
    "preview": "import Foundation\nimport Testing\n@testable import CodeReviewer\n\n@Suite(\"StreamRenderer\")\nstruct StreamRendererTests {\n\n "
  },
  {
    "path": "LICENSE",
    "chars": 1075,
    "preview": "MIT License\n\nCopyright (c) 2025 Christopher Karani\n\nPermission is hereby granted, free of charge, to any person obtainin"
  },
  {
    "path": "Package.swift",
    "chars": 9510,
    "preview": "// swift-tools-version: 6.2\nimport PackageDescription\nimport CompilerPluginSupport\nimport Foundation\nlet includeDemo = P"
  },
  {
    "path": "README.md",
    "chars": 12597,
    "preview": "<div align=\"center\">\n  <img alt=\"Swarm Swift Agent Framework\" src=\"docs/public/banner.svg\" />\n\n  <p><strong>A Swift fram"
  },
  {
    "path": "Sources/Swarm/Agents/Agent+Workspace.swift",
    "chars": 4663,
    "preview": "import Foundation\n\npublic extension Agent {\n    /// Creates an on-device agent with the recommended defaults and optiona"
  },
  {
    "path": "Sources/Swarm/Agents/Agent.swift",
    "chars": 131117,
    "preview": "// Agent.swift\n// Swarm Framework\n//\n// Tool-calling agent that uses structured LLM tool calling APIs.\n\nimport Foundatio"
  },
  {
    "path": "Sources/Swarm/Core/AgentConfiguration+InferenceOptions.swift",
    "chars": 1874,
    "preview": "// AgentConfiguration+InferenceOptions.swift\n// Swarm Framework\n//\n// Bridges AgentConfiguration + ModelSettings to Infe"
  },
  {
    "path": "Sources/Swarm/Core/AgentConfiguration.swift",
    "chars": 42206,
    "preview": "// AgentConfiguration.swift\n// Swarm Framework\n//\n// Runtime configuration settings for agent execution.\n\nimport Foundat"
  },
  {
    "path": "Sources/Swarm/Core/AgentEnvironment.swift",
    "chars": 2105,
    "preview": "// AgentEnvironment.swift\n// Swarm Framework\n//\n// Task-local environment values for declarative agent configuration.\n\ni"
  },
  {
    "path": "Sources/Swarm/Core/AgentError.swift",
    "chars": 25165,
    "preview": "// AgentError.swift\n// Swarm Framework\n//\n// Comprehensive error types for agent operations.\n\nimport Foundation\n\n// MARK"
  },
  {
    "path": "Sources/Swarm/Core/AgentEvent.swift",
    "chars": 15646,
    "preview": "// AgentEvent.swift\n// Swarm Framework\n//\n// Events emitted during agent execution for streaming and observation.\n\nimpor"
  },
  {
    "path": "Sources/Swarm/Core/AgentResponse.swift",
    "chars": 10713,
    "preview": "// AgentResponse.swift\n// Swarm Framework\n//\n// Response type for agent execution with enhanced tracking capabilities.\n\n"
  },
  {
    "path": "Sources/Swarm/Core/AgentResult.swift",
    "chars": 6852,
    "preview": "// AgentResult.swift\n// Swarm Framework\n//\n// Result type for agent execution.\n\nimport Foundation\n\n// MARK: - AgentResul"
  },
  {
    "path": "Sources/Swarm/Core/AgentRuntime+Identity.swift",
    "chars": 2900,
    "preview": "import Foundation\n\n/// Stable runtime identity for deterministic agent instance matching.\n///\n/// For class/actor-based "
  },
  {
    "path": "Sources/Swarm/Core/AgentRuntime.swift",
    "chars": 19262,
    "preview": "// AgentRuntime.swift\n// Swarm Framework\n//\n// Core AgentRuntime protocol and related inference types.\n\nimport Foundatio"
  },
  {
    "path": "Sources/Swarm/Core/CallableAgent.swift",
    "chars": 2125,
    "preview": "// CallableAgent.swift\n// Swarm Framework\n//\n// @dynamicCallable wrapper enabling callable syntax on any agent.\n\nimport "
  },
  {
    "path": "Sources/Swarm/Core/CircularBuffer.swift",
    "chars": 5273,
    "preview": "// CircularBuffer.swift\n// Swarm Framework\n//\n// Fixed-size circular buffer for bounded memory management.\n\nimport Found"
  },
  {
    "path": "Sources/Swarm/Core/ContextProfile.swift",
    "chars": 20462,
    "preview": "// ContextProfile.swift\n// Swarm Framework\n//\n// Profiles and budgets for managing on-device context allocation.\n\nimport"
  },
  {
    "path": "Sources/Swarm/Core/Conversation.swift",
    "chars": 16488,
    "preview": "import Foundation\n\n/// Stateful multi-turn conversation wrapper for agent interaction.\n///\n/// `Conversation` maintains "
  },
  {
    "path": "Sources/Swarm/Core/ConversationBranching.swift",
    "chars": 479,
    "preview": "import Foundation\n\n/// Internal capability for runtimes that can create an isolated branch of their own execution state."
  },
  {
    "path": "Sources/Swarm/Core/Environment.swift",
    "chars": 830,
    "preview": "// Environment.swift\n// Swarm Framework\n//\n// SwiftUI-style environment property wrapper for AgentEnvironment values.\n\ni"
  },
  {
    "path": "Sources/Swarm/Core/EnvironmentAgent.swift",
    "chars": 3749,
    "preview": "// EnvironmentAgent.swift\n// Swarm Framework\n//\n// LegacyAgent wrapper that applies task-local AgentEnvironment values.\n"
  },
  {
    "path": "Sources/Swarm/Core/EventStreamHooks.swift",
    "chars": 5134,
    "preview": "// EventStreamObserver.swift\n// Swarm Framework\n//\n// Internal hook implementation that pipes events to a stream continu"
  },
  {
    "path": "Sources/Swarm/Core/Execution/AgentContext.swift",
    "chars": 12686,
    "preview": "// AgentContext.swift\n// Swarm Framework\n//\n// Shared context for multi-agent orchestration execution.\n\nimport Foundatio"
  },
  {
    "path": "Sources/Swarm/Core/Execution/ContextKey.swift",
    "chars": 6856,
    "preview": "// ContextKey.swift\n// Swarm Framework\n//\n// Type-safe context keys for AgentContext.\n\nimport Foundation\n\n// MARK: - Con"
  },
  {
    "path": "Sources/Swarm/Core/Handoff/Handoff.swift",
    "chars": 16175,
    "preview": "// Handoff.swift\n// Swarm Framework\n//\n// LegacyAgent handoff system for multi-agent orchestration.\n\nimport Foundation\n\n"
  },
  {
    "path": "Sources/Swarm/Core/Handoff/HandoffBuilder.swift",
    "chars": 11724,
    "preview": "// HandoffBuilder.swift\n// Swarm Framework\n//\n// Fluent builder API for creating handoff configurations.\n\nimport Foundat"
  },
  {
    "path": "Sources/Swarm/Core/Handoff/HandoffConfiguration+Lookup.swift",
    "chars": 645,
    "preview": "// HandoffConfiguration+Lookup.swift\n// Swarm Framework\n//\n// Shared handoff lookup helper to centralize runtime identit"
  },
  {
    "path": "Sources/Swarm/Core/Handoff/HandoffConfiguration.swift",
    "chars": 11231,
    "preview": "// HandoffConfiguration.swift\n// Swarm Framework\n//\n// Configuration types for enhanced agent handoffs with callbacks.\n\n"
  },
  {
    "path": "Sources/Swarm/Core/Handoff/HandoffOptions.swift",
    "chars": 8081,
    "preview": "// HandoffOptions.swift\n// Swarm Framework\n//\n// Modern, typed configuration surface for handoff APIs.\n\nimport Foundatio"
  },
  {
    "path": "Sources/Swarm/Core/Handoff/WorkflowError.swift",
    "chars": 6711,
    "preview": "// WorkflowError.swift\n// Swarm Framework\n//\n// Comprehensive error types for multi-agent workflow operations.\n\nimport F"
  },
  {
    "path": "Sources/Swarm/Core/Handoff/WorkflowValidationError.swift",
    "chars": 1328,
    "preview": "// WorkflowValidationError.swift\n// Swarm Framework\n//\n// Typed validation errors for user-configurable workflow graphs."
  },
  {
    "path": "Sources/Swarm/Core/InferenceStreamEvent.swift",
    "chars": 1793,
    "preview": "// InferenceStreamEvent.swift\n// Swarm Framework\n//\n// Generic stream events for providers that support tool-call stream"
  },
  {
    "path": "Sources/Swarm/Core/Logger+Swarm.swift",
    "chars": 3499,
    "preview": "// Logger+Swarm.swift\n// Swarm Framework\n//\n// Cross-platform structured logging using swift-log.\n\nimport Foundation\nimp"
  },
  {
    "path": "Sources/Swarm/Core/ModelSettings.swift",
    "chars": 19525,
    "preview": "// ModelSettings.swift\n// Swarm Framework\n//\n// Comprehensive model configuration settings for LLM inference.\n\nimport Fo"
  },
  {
    "path": "Sources/Swarm/Core/ObservedAgent.swift",
    "chars": 2373,
    "preview": "import Foundation\n\n/// Internal wrapper that attaches an observer to an existing agent runtime.\nstruct ObservedAgent<Wra"
  },
  {
    "path": "Sources/Swarm/Core/PartialToolCallUpdate.swift",
    "chars": 1240,
    "preview": "// PartialToolCallUpdate.swift\n// Swarm Framework\n//\n// Public, provider-agnostic representation of a partially streamed"
  },
  {
    "path": "Sources/Swarm/Core/PromptEnvelope.swift",
    "chars": 2447,
    "preview": "import Foundation\n\n/// Enforces context-envelope limits for provider prompts.\nenum PromptEnvelope {\n    private static l"
  },
  {
    "path": "Sources/Swarm/Core/PromptTokenCounter.swift",
    "chars": 4811,
    "preview": "// PromptTokenCounter.swift\n// Swarm Framework\n//\n// Shared prompt token counting abstraction for runtime budgeting.\n\nim"
  },
  {
    "path": "Sources/Swarm/Core/ReasoningConfig.swift",
    "chars": 3092,
    "preview": "// ReasoningConfig.swift\n// Swarm Framework\n//\n// Swarm-level mirror of Conduit's ReasoningConfig. Lives at the Swarm bo"
  },
  {
    "path": "Sources/Swarm/Core/ResponseTracker.swift",
    "chars": 20714,
    "preview": "// ResponseTracker.swift\n// Swarm Framework\n//\n// Tracks agent responses for conversation continuation with bounded stor"
  },
  {
    "path": "Sources/Swarm/Core/RunHooks.swift",
    "chars": 23060,
    "preview": "// AgentObserver.swift\n// Swarm Framework\n//\n// Lifecycle observer for observing agent execution events.\n\nimport Foundat"
  },
  {
    "path": "Sources/Swarm/Core/RuntimeMetadata.swift",
    "chars": 292,
    "preview": "// RuntimeMetadata.swift\n// Swarm Framework\n//\n// Shared runtime metadata keys for agent results.\n\nimport Foundation\n\nen"
  },
  {
    "path": "Sources/Swarm/Core/SendableValue.swift",
    "chars": 14496,
    "preview": "// SendableValue.swift\n// Swarm Framework\n//\n// A type-safe, Sendable container for dynamic values used in tool argument"
  },
  {
    "path": "Sources/Swarm/Core/StreamHelper.swift",
    "chars": 7348,
    "preview": "// StreamHelper.swift\n// Swarm Framework\n//\n// Centralized stream creation utilities with safe defaults.\n\nimport Foundat"
  },
  {
    "path": "Sources/Swarm/Core/StreamOperations.swift",
    "chars": 33944,
    "preview": "// StreamOperations.swift\n// Swarm Framework\n//\n// Functional operations on AsyncThrowingStream<AgentEvent, Error> for r"
  },
  {
    "path": "Sources/Swarm/Core/StructuredOutput.swift",
    "chars": 5667,
    "preview": "import Foundation\n\n/// Provider-agnostic structured output request owned by Swarm.\npublic enum StructuredOutputFormat: S"
  },
  {
    "path": "Sources/Swarm/Core/SwarmColonySPI.swift",
    "chars": 7199,
    "preview": "import Foundation\n\n@_spi(ColonyInternal) public enum SwarmChatRole: String, Codable, Sendable, Equatable {\n    case syst"
  },
  {
    "path": "Sources/Swarm/Core/SwarmConfiguration.swift",
    "chars": 3884,
    "preview": "// SwarmConfiguration.swift\n// Swarm Framework\n//\n// Global configuration entry point for the Swarm framework.\n\nimport F"
  },
  {
    "path": "Sources/Swarm/Core/SwarmTranscript.swift",
    "chars": 9185,
    "preview": "import CryptoKit\nimport Foundation\n\npublic enum SwarmTranscriptSchemaVersion: String, Codable, Sendable, Equatable {\n   "
  },
  {
    "path": "Sources/Swarm/Core/TokenUsage.swift",
    "chars": 1140,
    "preview": "// TokenUsage.swift\n// Swarm Framework\n//\n// Token usage statistics for inference calls.\n\nimport Foundation\n\n// MARK: - "
  },
  {
    "path": "Sources/Swarm/Extensions/Extensions.swift",
    "chars": 1348,
    "preview": "// Extensions.swift\n// Swarm Framework\n//\n// Swift standard library and Foundation extensions.\n\nimport Foundation\n\n// MA"
  },
  {
    "path": "Sources/Swarm/Guardrails/Guardrail.swift",
    "chars": 2884,
    "preview": "// Guardrail.swift\n// Swarm Framework\n//\n// Shared guardrail marker protocol.\n\nimport Foundation\n\n/// Base protocol for "
  },
  {
    "path": "Sources/Swarm/Guardrails/GuardrailError.swift",
    "chars": 3526,
    "preview": "// GuardrailError.swift\n// Swarm Framework\n//\n// Comprehensive error types for guardrail execution.\n\nimport Foundation\n\n"
  },
  {
    "path": "Sources/Swarm/Guardrails/GuardrailResult.swift",
    "chars": 11572,
    "preview": "// GuardrailResult.swift\n// Swarm Framework\n//\n// Result type for guardrail validation checks.\n// Indicates whether a tr"
  },
  {
    "path": "Sources/Swarm/Guardrails/GuardrailRunner.swift",
    "chars": 38419,
    "preview": "// GuardrailRunner.swift\n// Swarm Framework\n//\n// Thread-safe guardrail execution orchestrator.\n// Provides sequential a"
  },
  {
    "path": "Sources/Swarm/Guardrails/InputGuardrail.swift",
    "chars": 15909,
    "preview": "// InputGuardrail.swift\n// Swarm Framework\n//\n// Input validation guardrails for agent systems.\n// Provides validation a"
  },
  {
    "path": "Sources/Swarm/Guardrails/OutputGuardrail.swift",
    "chars": 16201,
    "preview": "// OutputGuardrail.swift\n// Swarm Framework\n//\n// Protocol and implementations for validating agent output before return"
  },
  {
    "path": "Sources/Swarm/Guardrails/ToolGuardrails.swift",
    "chars": 13363,
    "preview": "// ToolGuardrails.swift\n// Swarm Framework\n//\n// Tool-level guardrails for validating tool inputs and outputs.\n// Provid"
  },
  {
    "path": "Sources/Swarm/Integration/Membrane/MembraneAgentAdapter.swift",
    "chars": 16249,
    "preview": "import Foundation\n#if SWARM_INTEGRATIONS\nimport Membrane\nimport MembraneHive\n#endif\n\npublic struct MembraneFeatureConfig"
  },
  {
    "path": "Sources/Swarm/Integration/Membrane/MembraneInternalTools.swift",
    "chars": 2818,
    "preview": "import Foundation\n\nenum MembraneInternalToolName {\n    static let loadToolSchema = \"membrane_load_tool_schema\"\n    stati"
  },
  {
    "path": "Sources/Swarm/Integration/Membrane/SessionMembraneAgentAdapter.swift",
    "chars": 5071,
    "preview": "import Foundation\nimport Membrane\nimport MembraneCore\n\npublic actor SessionMembraneAgentAdapter: MembraneAgentAdapter {\n"
  },
  {
    "path": "Sources/Swarm/Integration/Membrane/WaxMembraneStorage.swift",
    "chars": 10122,
    "preview": "import CryptoKit\nimport Foundation\nimport MembraneCore\nimport Wax\n\nprotocol WaxPointerIndex: Sendable {\n    func save(_ "
  },
  {
    "path": "Sources/Swarm/Integration/Wax/WaxEmbeddingProviderAdapters.swift",
    "chars": 2030,
    "preview": "import Foundation\nimport WaxVectorSearch\n\n/// Adapter that exposes a Wax embedding provider to Swarm.\npublic struct Swar"
  },
  {
    "path": "Sources/Swarm/Integration/Wax/WaxIntegration.swift",
    "chars": 428,
    "preview": "import Wax\n\n/// Lightweight helpers for the Wax embedding adapter.\npublic struct WaxIntegration {\n    public init() {}\n\n"
  },
  {
    "path": "Sources/Swarm/Integration/Wax/WaxMemory.swift",
    "chars": 15337,
    "preview": "import Foundation\nimport Wax\nimport WaxVectorSearch\n\n/// Wax-backed memory implementation using the public Memory API.\np"
  },
  {
    "path": "Sources/Swarm/Internal/GraphRuntime/ChatGraph.swift",
    "chars": 42659,
    "preview": "import CryptoKit\nimport Foundation\nimport HiveCore\n\nenum ToolApprovalPolicy: Sendable, Equatable {\n    case never\n    ca"
  },
  {
    "path": "Sources/Swarm/Internal/GraphRuntime/GraphAgent.swift",
    "chars": 29600,
    "preview": "// GraphAgent.swift\n// HiveSwarm\n//\n// Bridge adapter that exposes a Hive-native agent graph as a Swarm `AgentRuntime`.\n"
  },
  {
    "path": "Sources/Swarm/Internal/GraphRuntime/HiveChatCompatibility.swift",
    "chars": 5827,
    "preview": "import Foundation\nimport HiveCore\n\nenum HiveChatRole: String, Codable, Sendable, Equatable {\n    case system\n    case us"
  },
  {
    "path": "Sources/Swarm/Internal/GraphRuntime/HiveCodableJSONCodec.swift",
    "chars": 757,
    "preview": "import Foundation\nimport HiveCore\n\n/// Deterministic JSON codec for Hive checkpointing and task hashing.\n///\n/// - Impor"
  },
  {
    "path": "Sources/Swarm/Internal/GraphRuntime/RetryPolicyBridge.swift",
    "chars": 3921,
    "preview": "// RetryPolicyBridge.swift\n// HiveSwarm\n//\n// Maps Swarm's RetryPolicy to Hive's HiveRetryPolicy for deterministic retry"
  },
  {
    "path": "Sources/Swarm/Internal/GraphRuntime/RuntimeHardening.swift",
    "chars": 48852,
    "preview": "import CryptoKit\nimport Foundation\nimport HiveCore\n\n// MARK: - EventSchemaVersion\n\nenum EventSchemaVersion: Sendable {\n "
  },
  {
    "path": "Sources/Swarm/Internal/GraphRuntime/ToolRegistryAdapter.swift",
    "chars": 8482,
    "preview": "import Foundation\nimport HiveCore\n\nenum ToolRegistryAdapterError: Error, Equatable, Sendable {\n    case invalidArguments"
  },
  {
    "path": "Sources/Swarm/Internal/SwarmRuntimeEnvironment.swift",
    "chars": 952,
    "preview": "import Foundation\n\nenum SwarmRuntimeEnvironment {\n    static var isRunningTests: Bool {\n        let processInfo = Proces"
  },
  {
    "path": "Sources/Swarm/MCP/HTTPMCPServer.swift",
    "chars": 26158,
    "preview": "// HTTPMCPServer.swift\n// Swarm Framework\n//\n// HTTP-based MCP server client implementation.\n\nimport Foundation\n#if canI"
  },
  {
    "path": "Sources/Swarm/MCP/MCPCapabilities.swift",
    "chars": 2709,
    "preview": "// MCPCapabilities.swift\n// Swarm Framework\n//\n// MCP server capability declarations.\n\nimport Foundation\n\n// MARK: - MCP"
  },
  {
    "path": "Sources/Swarm/MCP/MCPClient.swift",
    "chars": 27241,
    "preview": "// MCPClient.swift\n// Swarm Framework\n//\n// A client for managing multiple MCP server connections and aggregating their "
  },
  {
    "path": "Sources/Swarm/MCP/MCPError.swift",
    "chars": 6560,
    "preview": "// MCPError.swift\n// Swarm Framework\n//\n// JSON-RPC 2.0 error types for Model Context Protocol (MCP) operations.\n\nimport"
  },
  {
    "path": "Sources/Swarm/MCP/MCPProtocol.swift",
    "chars": 16510,
    "preview": "// MCPProtocol.swift\n// Swarm Framework\n//\n// JSON-RPC 2.0 request/response types for Model Context Protocol (MCP) opera"
  },
  {
    "path": "Sources/Swarm/MCP/MCPResource.swift",
    "chars": 7131,
    "preview": "// MCPResource.swift\n// Swarm Framework\n//\n// Model Context Protocol resource types for representing server resources.\n\n"
  },
  {
    "path": "Sources/Swarm/MCP/MCPServer.swift",
    "chars": 11896,
    "preview": "// MCPServer.swift\n// Swarm Framework\n//\n// Protocol defining the interface for Model Context Protocol (MCP) servers.\n\ni"
  },
  {
    "path": "Sources/Swarm/MCP/MCPToolBridge.swift",
    "chars": 5669,
    "preview": "// MCPToolBridge.swift\n// Swarm Framework\n//\n// Bridges MCP tools to Swarm Tool protocol.\n\nimport Foundation\n\n// MARK: -"
  },
  {
    "path": "Sources/Swarm/Macros/MacroDeclarations.swift",
    "chars": 16542,
    "preview": "// MacroDeclarations.swift\n// Swarm Framework\n//\n// Public macro declarations for Swarm.\n// These macros significantly r"
  },
  {
    "path": "Sources/Swarm/Memory/AgentMemory.swift",
    "chars": 19278,
    "preview": "// AgentMemory.swift\n// Swarm Framework\n//\n// Core protocol defining memory storage and retrieval for agents.\n\nimport Fo"
  },
  {
    "path": "Sources/Swarm/Memory/Backends/InMemoryBackend.swift",
    "chars": 3518,
    "preview": "// InMemoryBackend.swift\n// Swarm Framework\n//\n// In-memory implementation of PersistentMemoryBackend.\n\nimport Foundatio"
  },
  {
    "path": "Sources/Swarm/Memory/Backends/SwiftDataBackend.swift",
    "chars": 7578,
    "preview": "// SwiftDataBackend.swift\n// Swarm Framework\n//\n// SwiftData implementation of PersistentMemoryBackend.\n\n#if canImport(S"
  },
  {
    "path": "Sources/Swarm/Memory/CompositeMemory.swift",
    "chars": 8040,
    "preview": "import Foundation\n\n/// A memory implementation that fans writes out to multiple memory layers and\n/// combines retrieved"
  },
  {
    "path": "Sources/Swarm/Memory/ContextCoreMemory.swift",
    "chars": 6080,
    "preview": "// ContextCoreMemory.swift\n// Swarm Framework\n//\n// ContextCore-backed memory implementation used by default in Swarm.\n\n"
  },
  {
    "path": "Sources/Swarm/Memory/ConversationMemory.swift",
    "chars": 5531,
    "preview": "// ConversationMemory.swift\n// Swarm Framework\n//\n// Simple FIFO memory that maintains a fixed number of recent messages"
  },
  {
    "path": "Sources/Swarm/Memory/DefaultAgentMemory.swift",
    "chars": 16215,
    "preview": "// DefaultAgentMemory.swift\n// Swarm Framework\n//\n// Default agent memory stack combining ContextCore working context wi"
  },
  {
    "path": "Sources/Swarm/Memory/EmbeddingProvider.swift",
    "chars": 15208,
    "preview": "// EmbeddingProvider.swift\n// Swarm Framework\n//\n// Protocol for text-to-vector embeddings for semantic search.\n\nimport "
  },
  {
    "path": "Sources/Swarm/Memory/HybridMemory.swift",
    "chars": 12692,
    "preview": "// HybridMemory.swift\n// Swarm Framework\n//\n// Combines multiple memory strategies for comprehensive context management."
  },
  {
    "path": "Sources/Swarm/Memory/InMemorySession.swift",
    "chars": 4537,
    "preview": "// InMemorySession.swift\n// Swarm Framework\n//\n// In-memory implementation of the Session protocol.\n\nimport Foundation\n\n"
  },
  {
    "path": "Sources/Swarm/Memory/InferenceProviderSummarizer.swift",
    "chars": 4873,
    "preview": "// InferenceProviderSummarizer.swift\n// Swarm Framework\n//\n// LLM-based summarizer using any InferenceProvider.\n\nimport "
  },
  {
    "path": "Sources/Swarm/Memory/MemoryMessage.swift",
    "chars": 12506,
    "preview": "// MemoryMessage.swift\n// Swarm Framework\n//\n// Core message type for agent memory systems.\n\nimport Foundation\n\n// MARK:"
  },
  {
    "path": "Sources/Swarm/Memory/MemoryPromptDescriptor.swift",
    "chars": 858,
    "preview": "// MemoryPromptDescriptor.swift\n// Swarm Framework\n//\n// Optional prompt metadata for memory implementations.\n\nimport Fo"
  },
  {
    "path": "Sources/Swarm/Memory/MemoryRetrievalPolicy.swift",
    "chars": 1397,
    "preview": "import Foundation\n\n/// Retrieval contract for memory implementations that support item-aware budgeting.\npublic struct Me"
  },
  {
    "path": "Sources/Swarm/Memory/MemorySessionLifecycle.swift",
    "chars": 2419,
    "preview": "import Foundation\n\n/// Optional lifecycle observer for memory implementations that need session scoping.\n///\n/// This is"
  },
  {
    "path": "Sources/Swarm/Memory/PersistedMessage.swift",
    "chars": 5638,
    "preview": "// PersistedMessage.swift\n// Swarm Framework\n//\n// SwiftData model for persistent message storage.\n\n#if canImport(SwiftD"
  },
  {
    "path": "Sources/Swarm/Memory/PersistentMemory.swift",
    "chars": 5640,
    "preview": "// PersistentMemory.swift\n// Swarm Framework\n//\n// Generic persistent memory using pluggable backends.\n\nimport Foundatio"
  },
  {
    "path": "Sources/Swarm/Memory/PersistentMemoryBackend.swift",
    "chars": 6819,
    "preview": "// PersistentMemoryBackend.swift\n// Swarm Framework\n//\n// Protocol for persistent memory storage backends.\n\nimport Found"
  },
  {
    "path": "Sources/Swarm/Memory/PersistentSession.swift",
    "chars": 10649,
    "preview": "// PersistentSession.swift\n// Swarm Framework\n//\n// Persistent session implementation using SwiftDataBackend.\n\n#if canIm"
  },
  {
    "path": "Sources/Swarm/Memory/Session.swift",
    "chars": 7599,
    "preview": "// Session.swift\n// Swarm Framework\n//\n// Protocol defining session-based conversation history management.\n\nimport Found"
  },
  {
    "path": "Sources/Swarm/Memory/SlidingWindowMemory.swift",
    "chars": 8362,
    "preview": "// SlidingWindowMemory.swift\n// Swarm Framework\n//\n// Token-aware memory that maintains messages within a token budget.\n"
  },
  {
    "path": "Sources/Swarm/Memory/Summarizer.swift",
    "chars": 7525,
    "preview": "// Summarizer.swift\n// Swarm Framework\n//\n// LLM summarization abstraction for memory compression.\n\nimport Foundation\n\n/"
  },
  {
    "path": "Sources/Swarm/Memory/SummaryMemory.swift",
    "chars": 11789,
    "preview": "// SummaryMemory.swift\n// Swarm Framework\n//\n// Memory that automatically summarizes old messages to compress history.\n\n"
  },
  {
    "path": "Sources/Swarm/Memory/SwiftDataMemory.swift",
    "chars": 12509,
    "preview": "// SwiftDataMemory.swift\n// Swarm Framework\n//\n// Persistent memory using SwiftData.\n\n#if canImport(SwiftData)\n    impor"
  },
  {
    "path": "Sources/Swarm/Memory/TokenEstimator.swift",
    "chars": 4174,
    "preview": "// TokenEstimator.swift\n// Swarm Framework\n//\n// Token counting abstraction for memory management.\n\nimport Foundation\n\n/"
  },
  {
    "path": "Sources/Swarm/Memory/VectorMemory.swift",
    "chars": 16623,
    "preview": "// VectorMemory.swift\n// Swarm Framework\n//\n// Vector-based semantic memory with embedding support.\n\nimport Foundation\n\n"
  },
  {
    "path": "Sources/Swarm/Observability/AgentTracer.swift",
    "chars": 12270,
    "preview": "// AgentTracer.swift\n// Swarm Framework\n//\n// Tracer protocol and implementations for agent observability.\n// Provides c"
  },
  {
    "path": "Sources/Swarm/Observability/ConsoleTracer.swift",
    "chars": 15776,
    "preview": "// ConsoleTracer.swift\n// Swarm Framework\n//\n// Console-based tracer implementations with formatted output and ANSI colo"
  },
  {
    "path": "Sources/Swarm/Observability/MetricsCollector.swift",
    "chars": 18992,
    "preview": "// MetricsCollector.swift\n// Swarm Framework\n//\n// Metrics collection system for aggregating agent execution data.\n// Pr"
  },
  {
    "path": "Sources/Swarm/Observability/OSLogTracer.swift",
    "chars": 14046,
    "preview": "// OSLogTracer.swift\n// Swarm Framework\n//\n// A tracer that integrates with Apple's unified logging system (os.log).\n// "
  },
  {
    "path": "Sources/Swarm/Observability/PerformanceMetrics.swift",
    "chars": 13853,
    "preview": "// PerformanceMetrics.swift\n// Swarm Framework\n//\n// Performance tracking types for measuring parallel execution benefit"
  },
  {
    "path": "Sources/Swarm/Observability/SwiftLogTracer.swift",
    "chars": 4656,
    "preview": "// SwiftLogTracer.swift\n// Swarm Framework\n//\n// Cross-platform tracer using swift-log.\n\nimport Foundation\nimport Loggin"
  },
  {
    "path": "Sources/Swarm/Observability/TraceContext.swift",
    "chars": 9097,
    "preview": "// TraceContext.swift\n// Swarm Framework\n//\n// Context for grouping related traces together using task-local storage.\n\ni"
  },
  {
    "path": "Sources/Swarm/Observability/TraceEvent.swift",
    "chars": 15368,
    "preview": "// TraceEvent.swift\n// Swarm Framework\n//\n// Detailed trace events for agent execution monitoring.\n// Provides comprehen"
  },
  {
    "path": "Sources/Swarm/Observability/TraceEventPublicLogSanitizer.swift",
    "chars": 2227,
    "preview": "// TraceEventPublicLogSanitizer.swift\n// Swarm Framework\n//\n// Redacts trace event payloads before they are written to p"
  },
  {
    "path": "Sources/Swarm/Observability/TraceSpan.swift",
    "chars": 4947,
    "preview": "// TraceSpan.swift\n// Swarm Framework\n//\n// Represents a single operation span within a trace for distributed tracing.\n\n"
  },
  {
    "path": "Sources/Swarm/Observability/TracingHelper.swift",
    "chars": 14207,
    "preview": "// TracingHelper.swift\n// Swarm Framework\n//\n// Helper for standardized trace event emission across agents.\n\nimport Foun"
  },
  {
    "path": "Sources/Swarm/Providers/Conduit/ConduitInferenceProvider.swift",
    "chars": 29918,
    "preview": "import ConduitAdvanced\nprivate typealias ConduitToolChoice = ConduitAdvanced.ToolChoice\nimport Foundation\n\n/// Bridges a"
  },
  {
    "path": "Sources/Swarm/Providers/Conduit/ConduitProviderSelection.swift",
    "chars": 17630,
    "preview": "// ConduitProviderSelection.swift\n// Swarm Framework\n//\n// Minimal Conduit-backed provider selection for Swarm.\n\nimport "
  },
  {
    "path": "Sources/Swarm/Providers/Conduit/LLM.swift",
    "chars": 20340,
    "preview": "import Conduit\nimport ConduitAdvanced\nimport Foundation\n\n/// Opinionated, beginner-friendly inference presets backed by "
  },
  {
    "path": "Sources/Swarm/Providers/Conduit/MLXPromptProvider.swift",
    "chars": 4942,
    "preview": "#if canImport(MLX)\nimport Conduit\nimport ConduitAdvanced\nimport Foundation\n\nfunc makeMLXInferenceProvider(model: Conduit"
  },
  {
    "path": "Sources/Swarm/Providers/Conduit/OllamaSettings.swift",
    "chars": 1686,
    "preview": "// OllamaSettings.swift\n// Swarm Framework\n//\n// Lightweight Ollama settings without exposing Conduit types.\n\nimport Con"
  },
  {
    "path": "Sources/Swarm/Providers/Conduit/OpenRouterRouting.swift",
    "chars": 3130,
    "preview": "// OpenRouterRouting.swift\n// Swarm Framework\n//\n// Lightweight OpenRouter routing configuration without exposing Condui"
  },
  {
    "path": "Sources/Swarm/Providers/ConversationInferenceProvider.swift",
    "chars": 7138,
    "preview": "// ConversationInferenceProvider.swift\n// Swarm Framework\n//\n// Structured conversation-facing inference protocols and p"
  },
  {
    "path": "Sources/Swarm/Providers/DefaultInferenceProviderFactory.swift",
    "chars": 740,
    "preview": "// DefaultInferenceProviderFactory.swift\n// Swarm Framework\n//\n// Opinionated default inference provider selection.\n//\n/"
  },
  {
    "path": "Sources/Swarm/Providers/InferenceProviderMetadata.swift",
    "chars": 1285,
    "preview": "// InferenceProviderMetadata.swift\n// Swarm Framework\n//\n// Optional metadata for observability integrations.\n\nimport Fo"
  },
  {
    "path": "Sources/Swarm/Providers/LanguageModelSession.swift",
    "chars": 4229,
    "preview": "//\n//  LanguageModelSession.swift\n//  Swarm\n//\n//  Created by Chris Karani on 16/01/2026.\n//\n\nimport Foundation\n\n// Gate"
  },
  {
    "path": "Sources/Swarm/Providers/LanguageModelSessionHelpers.swift",
    "chars": 13945,
    "preview": "//\n//  LanguageModelSessionHelpers.swift\n//  Swarm\n//\n//  Internal helpers for LanguageModelSession prompt building and "
  },
  {
    "path": "Sources/Swarm/Providers/MultiProvider.swift",
    "chars": 21991,
    "preview": "// MultiProvider.swift\n// Swarm Framework\n//\n// Multi-provider routing system for inference provider management.\n\nimport"
  },
  {
    "path": "Sources/Swarm/Providers/TextOnlyConversationInferenceProviderAdapter.swift",
    "chars": 3712,
    "preview": "// TextOnlyConversationInferenceProviderAdapter.swift\n// Swarm Framework\n//\n// Generic text-only inference fallbacks for"
  },
  {
    "path": "Sources/Swarm/Providers/ToolCallStreamingInferenceProvider.swift",
    "chars": 1271,
    "preview": "// ToolCallStreamingInferenceProvider.swift\n// Swarm Framework\n//\n// Provider capability protocol for streaming tool cal"
  },
  {
    "path": "Sources/Swarm/Resilience/CircuitBreaker.swift",
    "chars": 12648,
    "preview": "// CircuitBreaker.swift\n// Swarm Framework\n//\n// Circuit breaker pattern implementation for fault tolerance and service "
  },
  {
    "path": "Sources/Swarm/Resilience/FallbackChain.swift",
    "chars": 11548,
    "preview": "// FallbackChain.swift\n// Swarm Framework\n//\n// Fallback chain for graceful degradation with fluent builder pattern.\n\nim"
  },
  {
    "path": "Sources/Swarm/Resilience/RateLimiter.swift",
    "chars": 3314,
    "preview": "// RateLimiter.swift\n// Swarm Framework\n//\n// Token bucket rate limiter for API calls.\n\nimport Foundation\n\n// MARK: - Ra"
  },
  {
    "path": "Sources/Swarm/Resilience/Resilience.swift",
    "chars": 555,
    "preview": "// Resilience.swift\n// Swarm Framework\n//\n// Resilience patterns for robust agent execution.\n// Includes:\n// - Retry pol"
  },
  {
    "path": "Sources/Swarm/Resilience/RetryPolicy.swift",
    "chars": 10157,
    "preview": "// RetryPolicy.swift\n// Swarm Framework\n//\n// Configurable retry strategies with backoff patterns for robust agent execu"
  },
  {
    "path": "Sources/Swarm/Swarm.swift",
    "chars": 1432,
    "preview": "// Swarm.swift\n// Swarm Framework\n//\n// LangChain for Apple Platforms - A comprehensive Swift framework\n// for building "
  },
  {
    "path": "Sources/Swarm/Tools/AgentTool.swift",
    "chars": 3627,
    "preview": "// AgentTool.swift\n// Swarm Framework\n//\n// Wraps an AgentRuntime as a callable tool for agent composition.\n\nimport Foun"
  },
  {
    "path": "Sources/Swarm/Tools/ArithmeticParser.swift",
    "chars": 11285,
    "preview": "// ArithmeticParser.swift\n// Swarm Framework\n//\n// Pure Swift recursive descent arithmetic parser for cross-platform sup"
  },
  {
    "path": "Sources/Swarm/Tools/BuiltInTools.swift",
    "chars": 13277,
    "preview": "// BuiltInTools.swift\n// Swarm Framework\n//\n// Built-in tools for common agent operations.\n\nimport Foundation\n\n#if canIm"
  },
  {
    "path": "Sources/Swarm/Tools/ParallelToolExecutor.swift",
    "chars": 16036,
    "preview": "// ParallelToolExecutor.swift\n// Swarm Framework\n//\n// Executes multiple tool calls in parallel using structured concurr"
  },
  {
    "path": "Sources/Swarm/Tools/SemanticCompactorTool.swift",
    "chars": 4279,
    "preview": "// SemanticCompactorTool.swift\n// Swarm Framework\n//\n// A tool for compacting and summarizing text using on-device Found"
  },
  {
    "path": "Sources/Swarm/Tools/Tool.swift",
    "chars": 55009,
    "preview": "// Tool.swift\n// Swarm Framework\n//\n// Dynamic (JSON) tool protocol and supporting types for tool execution.\n\nimport Fou"
  },
  {
    "path": "Sources/Swarm/Tools/ToolBridgeHelper.swift",
    "chars": 1293,
    "preview": "// ToolBridgeHelper.swift\n// Swarm Framework\n//\n// Existential opening helper for bridging Tool → AnyJSONTool.\n\nimport F"
  },
  {
    "path": "Sources/Swarm/Tools/ToolBridging.swift",
    "chars": 1887,
    "preview": "// ToolBridging.swift\n// Swarm Framework\n//\n// Bridges typed `Tool` implementations to the dynamic `AnyJSONTool` ABI.\n\ni"
  },
  {
    "path": "Sources/Swarm/Tools/ToolCallGoal.swift",
    "chars": 1847,
    "preview": "// ToolCallGoal.swift\n// Swarm Framework\n//\n// Common representation of a model-requested tool call (a \"tool goal\").\n\nim"
  },
  {
    "path": "Sources/Swarm/Tools/ToolCollection.swift",
    "chars": 1726,
    "preview": "// ToolCollection.swift\n// Swarm Framework\n//\n// Opaque tool collection produced by @ToolBuilder.\n\nimport Foundation\n\n//"
  },
  {
    "path": "Sources/Swarm/Tools/ToolExecutionEngine.swift",
    "chars": 2876,
    "preview": "// ToolExecutionEngine.swift\n// Swarm Framework\n//\n// Shared tool execution implementation used across agents.\n\nimport F"
  },
  {
    "path": "Sources/Swarm/Tools/ToolExecutionResult.swift",
    "chars": 8919,
    "preview": "// ToolExecutionResult.swift\n// Swarm Framework\n//\n// Types for parallel tool execution results and error handling strat"
  },
  {
    "path": "Sources/Swarm/Tools/ToolExecutionSemantics.swift",
    "chars": 1957,
    "preview": "import Foundation\n\n/// Declares the side-effect profile of a tool.\npublic enum ToolSideEffectLevel: String, Codable, Sen"
  },
  {
    "path": "Sources/Swarm/Tools/ToolParameterBuilder.swift",
    "chars": 12065,
    "preview": "// ToolParameterBuilder.swift\n// Swarm Framework\n//\n// Result builder DSL for constructing tool parameters declaratively"
  },
  {
    "path": "Sources/Swarm/Tools/Web/WebSearchSupport.swift",
    "chars": 85509,
    "preview": "import Foundation\nimport Wax\n\n#if canImport(CryptoKit)\nimport CryptoKit\n#endif\n\n#if canImport(SwiftSoup)\nimport SwiftSou"
  },
  {
    "path": "Sources/Swarm/Tools/WebSearchTool.swift",
    "chars": 13803,
    "preview": "// WebSearchTool.swift\n// Swarm Framework\n//\n// A multi-resolution web search, fetch, and grounding tool for strict-cont"
  },
  {
    "path": "Sources/Swarm/Tools/ZoniSearchTool.swift",
    "chars": 4556,
    "preview": "// ZoniSearchTool.swift\n// Swarm Framework\n//\n// Integration tool for Zoni RAG Framework.\n\nimport Foundation\n\n// Note: A"
  },
  {
    "path": "Sources/Swarm/Workflow/Workflow+Durable.swift",
    "chars": 3824,
    "preview": "import Foundation\n\npublic extension Workflow {\n    /// Namespaced access to durable workflow APIs.\n    var durable: Dura"
  },
  {
    "path": "Sources/Swarm/Workflow/Workflow.swift",
    "chars": 34329,
    "preview": "import Foundation\n\n/// Fluent multi-agent workflow composition API.\n///\n/// Use `Workflow` to compose multi-agent execut"
  },
  {
    "path": "Sources/Swarm/Workflow/WorkflowCheckpointCodec.swift",
    "chars": 727,
    "preview": "import Foundation\nimport HiveCore\n\n/// Deterministic JSON codec used by Workflow's durable checkpoint engine.\n///\n/// Th"
  },
  {
    "path": "Sources/Swarm/Workflow/WorkflowCheckpointStore.swift",
    "chars": 4679,
    "preview": "import Foundation\nimport HiveCore\n\nprotocol WorkflowDurableCheckpointStore: Sendable {\n    var runtimeStore: AnyHiveChec"
  },
  {
    "path": "Sources/Swarm/Workflow/WorkflowCheckpointing.swift",
    "chars": 951,
    "preview": "import Foundation\n\n/// Checkpoint persistence configuration for advanced workflows.\npublic struct WorkflowCheckpointing:"
  },
  {
    "path": "Sources/Swarm/Workflow/WorkflowDurableEngine.swift",
    "chars": 12518,
    "preview": "import Dispatch\nimport Foundation\nimport HiveCore\n\nstruct WorkflowDurableContext: Sendable {\n    let workflow: Workflow\n"
  },
  {
    "path": "Sources/Swarm/Workflow/WorkflowResultSnapshot.swift",
    "chars": 1227,
    "preview": "import Foundation\n\nstruct WorkflowResultSnapshot: Codable, Sendable, Equatable {\n    let output: String\n    let toolCall"
  },
  {
    "path": "Sources/Swarm/Workspace/AgentWorkspace.swift",
    "chars": 26593,
    "preview": "import Foundation\n\n/// File-backed workspace for on-device Swarm agents.\npublic struct AgentWorkspace: Sendable {\n    pu"
  },
  {
    "path": "Sources/Swarm/Workspace/WorkspaceMemory.swift",
    "chars": 6600,
    "preview": "import Foundation\n\n/// Workspace-backed memory for skill snippets and durable markdown notes.\npublic actor WorkspaceMemo"
  },
  {
    "path": "Sources/Swarm/Workspace/WorkspaceWriter.swift",
    "chars": 5674,
    "preview": "import Foundation\n\n/// Safe verbs for writing durable workspace memory notes.\npublic actor WorkspaceWriter {\n    private"
  },
  {
    "path": "Sources/SwarmCapabilityShowcase/main.swift",
    "chars": 2007,
    "preview": "import Foundation\nimport SwarmCapabilityShowcaseSupport\n\n#if canImport(Darwin)\nimport Darwin\n#else\nimport Glibc\n#endif\n\n"
  },
  {
    "path": "Sources/SwarmCapabilityShowcaseSupport/CapabilityShowcase.swift",
    "chars": 46023,
    "preview": "import Foundation\nimport Swarm\n\npublic enum CapabilityFamily: String, CaseIterable, Sendable, Hashable {\n    case agentT"
  },
  {
    "path": "Sources/SwarmDemo/AgentTest.swift",
    "chars": 9188,
    "preview": "import Foundation\nimport Swarm\n\n#if canImport(FoundationModels)\nimport FoundationModels\n#endif\n\n#if canImport(AnyLanguag"
  },
  {
    "path": "Sources/SwarmDemo/SwarmPlayground.playground/Pages/New.xcplaygroundpage/Contents.swift",
    "chars": 658,
    "preview": "\nimport Foundation\nimport FoundationModels\nimport Swarm\nimport PlaygroundSupport\n\nPlaygroundSupport.PlaygroundPage.curre"
  },
  {
    "path": "Sources/SwarmDemo/SwarmPlayground.playground/contents.xcplayground",
    "chars": 174,
    "preview": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<playground version='7.0' target-platform='macos' swift-version="
  },
  {
    "path": "Sources/SwarmMCP/SwarmMCPErrorMapper.swift",
    "chars": 9671,
    "preview": "import Foundation\nimport MCP\nimport Swarm\n\nenum SwarmMCPCallToolOutcome {\n    case success(CallTool.Result)\n    case fai"
  },
  {
    "path": "Sources/SwarmMCP/SwarmMCPServerService.swift",
    "chars": 10656,
    "preview": "import Foundation\nimport MCP\nimport Swarm\n\n/// Runtime service that exposes Swarm tools through an MCP server.\npublic ac"
  },
  {
    "path": "Sources/SwarmMCP/SwarmMCPToolAdapter.swift",
    "chars": 1599,
    "preview": "import Foundation\nimport Swarm\n\n/// Tool catalog boundary for exposing Swarm tools over MCP.\npublic protocol SwarmMCPToo"
  },
  {
    "path": "Sources/SwarmMCP/SwarmMCPToolMapper.swift",
    "chars": 3323,
    "preview": "import Foundation\nimport MCP\nimport Swarm\n\nenum SwarmMCPToolMapper {\n    static func mapSchemas(_ schemas: [ToolSchema])"
  },
  {
    "path": "Sources/SwarmMCP/SwarmMCPValueMapper.swift",
    "chars": 1671,
    "preview": "import Foundation\nimport MCP\nimport Swarm\n\nenum SwarmMCPValueMapper {\n    static func mcpValue(from value: SendableValue"
  },
  {
    "path": "Sources/SwarmMCPServerDemo/main.swift",
    "chars": 726,
    "preview": "import Foundation\nimport Swarm\nimport SwarmMCP\n\n@main\nstruct SwarmMCPServerDemo {\n    static func main() async throws {\n"
  },
  {
    "path": "Sources/SwarmMacros/AgentMacro.swift",
    "chars": 20456,
    "preview": "// AgentMacro.swift\n// SwarmMacros\n//\n// Implementation of the @AgentActor macro for generating LegacyAgent protocol con"
  },
  {
    "path": "Sources/SwarmMacros/BuilderMacro.swift",
    "chars": 5563,
    "preview": "// BuilderMacro.swift\n// SwarmMacros\n//\n// Implementation of the @Builder macro for generating fluent setter methods.\n\ni"
  },
  {
    "path": "Sources/SwarmMacros/InlineToolMacro.swift",
    "chars": 8931,
    "preview": "// InlineToolMacro.swift\n// SwarmMacros\n//\n// Implementation of the #Tool freestanding expression macro for inline tool "
  },
  {
    "path": "Sources/SwarmMacros/ParameterMacro.swift",
    "chars": 3101,
    "preview": "// ParameterMacro.swift\n// SwarmMacros\n//\n// Implementation of the @Parameter macro for declaring tool parameters.\n\nimpo"
  }
]

// ... and 196 more files (download for full content)

About this extraction

This page contains the full source code of the christopherkarani/SwiftAgents GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 396 files (3.9 MB), approximately 1.0M tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!