mcp-agent-foundry 1.3.1 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/README.md +265 -2
  2. package/dist/background/index.d.ts +33 -0
  3. package/dist/background/index.d.ts.map +1 -0
  4. package/dist/background/index.js +33 -0
  5. package/dist/background/index.js.map +1 -0
  6. package/dist/background/task-runner.d.ts +177 -0
  7. package/dist/background/task-runner.d.ts.map +1 -0
  8. package/dist/background/task-runner.js +551 -0
  9. package/dist/background/task-runner.js.map +1 -0
  10. package/dist/background/types.d.ts +135 -0
  11. package/dist/background/types.d.ts.map +1 -0
  12. package/dist/background/types.js +8 -0
  13. package/dist/background/types.js.map +1 -0
  14. package/dist/config/validator.d.ts +2 -2
  15. package/dist/config/validator.d.ts.map +1 -1
  16. package/dist/config/validator.js +2 -2
  17. package/dist/config/validator.js.map +1 -1
  18. package/dist/failover/health-tracker.d.ts +81 -1
  19. package/dist/failover/health-tracker.d.ts.map +1 -1
  20. package/dist/failover/health-tracker.js +229 -1
  21. package/dist/failover/health-tracker.js.map +1 -1
  22. package/dist/failover/orchestrator.d.ts.map +1 -1
  23. package/dist/failover/orchestrator.js +12 -2
  24. package/dist/failover/orchestrator.js.map +1 -1
  25. package/dist/hooks/hook-executor.d.ts +77 -0
  26. package/dist/hooks/hook-executor.d.ts.map +1 -0
  27. package/dist/hooks/hook-executor.js +308 -0
  28. package/dist/hooks/hook-executor.js.map +1 -0
  29. package/dist/hooks/hook-manager.d.ts +140 -0
  30. package/dist/hooks/hook-manager.d.ts.map +1 -0
  31. package/dist/hooks/hook-manager.js +520 -0
  32. package/dist/hooks/hook-manager.js.map +1 -0
  33. package/dist/hooks/index.d.ts +10 -0
  34. package/dist/hooks/index.d.ts.map +1 -0
  35. package/dist/hooks/index.js +10 -0
  36. package/dist/hooks/index.js.map +1 -0
  37. package/dist/hooks/types.d.ts +221 -0
  38. package/dist/hooks/types.d.ts.map +1 -0
  39. package/dist/hooks/types.js +31 -0
  40. package/dist/hooks/types.js.map +1 -0
  41. package/dist/index.d.ts +1 -1
  42. package/dist/index.js +1 -1
  43. package/dist/mcp/auto-mode.d.ts +221 -0
  44. package/dist/mcp/auto-mode.d.ts.map +1 -0
  45. package/dist/mcp/auto-mode.js +436 -0
  46. package/dist/mcp/auto-mode.js.map +1 -0
  47. package/dist/mcp/index.d.ts +14 -0
  48. package/dist/mcp/index.d.ts.map +1 -0
  49. package/dist/mcp/index.js +22 -0
  50. package/dist/mcp/index.js.map +1 -0
  51. package/dist/mcp/tools/critique-plan.d.ts.map +1 -1
  52. package/dist/mcp/tools/critique-plan.js +57 -4
  53. package/dist/mcp/tools/critique-plan.js.map +1 -1
  54. package/dist/mcp/tools/design-feedback.d.ts.map +1 -1
  55. package/dist/mcp/tools/design-feedback.js +58 -4
  56. package/dist/mcp/tools/design-feedback.js.map +1 -1
  57. package/dist/mcp/tools/invoke-agent.d.ts.map +1 -1
  58. package/dist/mcp/tools/invoke-agent.js +64 -1
  59. package/dist/mcp/tools/invoke-agent.js.map +1 -1
  60. package/dist/mcp/tools/review-code.d.ts.map +1 -1
  61. package/dist/mcp/tools/review-code.js +57 -4
  62. package/dist/mcp/tools/review-code.js.map +1 -1
  63. package/dist/mcp/tools/tasks/delete-task.d.ts +25 -0
  64. package/dist/mcp/tools/tasks/delete-task.d.ts.map +1 -0
  65. package/dist/mcp/tools/tasks/delete-task.js +148 -0
  66. package/dist/mcp/tools/tasks/delete-task.js.map +1 -0
  67. package/dist/mcp/tools/tasks/execute-task.d.ts.map +1 -1
  68. package/dist/mcp/tools/tasks/execute-task.js +74 -5
  69. package/dist/mcp/tools/tasks/execute-task.js.map +1 -1
  70. package/dist/mcp/tools/tasks/index.d.ts +2 -0
  71. package/dist/mcp/tools/tasks/index.d.ts.map +1 -1
  72. package/dist/mcp/tools/tasks/index.js +6 -0
  73. package/dist/mcp/tools/tasks/index.js.map +1 -1
  74. package/dist/observability/debug-logger.d.ts +209 -0
  75. package/dist/observability/debug-logger.d.ts.map +1 -0
  76. package/dist/observability/debug-logger.js +430 -0
  77. package/dist/observability/debug-logger.js.map +1 -0
  78. package/dist/observability/index.d.ts +12 -0
  79. package/dist/observability/index.d.ts.map +1 -0
  80. package/dist/observability/index.js +12 -0
  81. package/dist/observability/index.js.map +1 -0
  82. package/dist/observability/logger.d.ts +180 -0
  83. package/dist/observability/logger.d.ts.map +1 -1
  84. package/dist/observability/logger.js +158 -0
  85. package/dist/observability/logger.js.map +1 -1
  86. package/dist/providers/anthropic.d.ts +40 -6
  87. package/dist/providers/anthropic.d.ts.map +1 -1
  88. package/dist/providers/anthropic.js +120 -8
  89. package/dist/providers/anthropic.js.map +1 -1
  90. package/dist/providers/base.d.ts +6 -3
  91. package/dist/providers/base.d.ts.map +1 -1
  92. package/dist/providers/base.js.map +1 -1
  93. package/dist/router/context-manager.d.ts +214 -1
  94. package/dist/router/context-manager.d.ts.map +1 -1
  95. package/dist/router/context-manager.js +759 -2
  96. package/dist/router/context-manager.js.map +1 -1
  97. package/dist/router/context-types.d.ts +182 -0
  98. package/dist/router/context-types.d.ts.map +1 -0
  99. package/dist/router/context-types.js +8 -0
  100. package/dist/router/context-types.js.map +1 -0
  101. package/dist/router/engine.d.ts +3 -3
  102. package/dist/router/engine.d.ts.map +1 -1
  103. package/dist/router/engine.js +32 -4
  104. package/dist/router/engine.js.map +1 -1
  105. package/dist/router/pattern-executor.d.ts.map +1 -1
  106. package/dist/router/pattern-executor.js +38 -7
  107. package/dist/router/pattern-executor.js.map +1 -1
  108. package/dist/server.d.ts +41 -0
  109. package/dist/server.d.ts.map +1 -1
  110. package/dist/server.js +165 -0
  111. package/dist/server.js.map +1 -1
  112. package/dist/skills/hot-reloader.d.ts +104 -0
  113. package/dist/skills/hot-reloader.d.ts.map +1 -0
  114. package/dist/skills/hot-reloader.js +314 -0
  115. package/dist/skills/hot-reloader.js.map +1 -0
  116. package/dist/skills/index.d.ts +14 -0
  117. package/dist/skills/index.d.ts.map +1 -0
  118. package/dist/skills/index.js +16 -0
  119. package/dist/skills/index.js.map +1 -0
  120. package/dist/skills/skill-executor.d.ts +96 -0
  121. package/dist/skills/skill-executor.d.ts.map +1 -0
  122. package/dist/skills/skill-executor.js +289 -0
  123. package/dist/skills/skill-executor.js.map +1 -0
  124. package/dist/skills/skill-loader.d.ts +147 -0
  125. package/dist/skills/skill-loader.d.ts.map +1 -0
  126. package/dist/skills/skill-loader.js +579 -0
  127. package/dist/skills/skill-loader.js.map +1 -0
  128. package/dist/skills/types.d.ts +198 -0
  129. package/dist/skills/types.d.ts.map +1 -0
  130. package/dist/skills/types.js +21 -0
  131. package/dist/skills/types.js.map +1 -0
  132. package/dist/tasks/coordinator.d.ts +22 -1
  133. package/dist/tasks/coordinator.d.ts.map +1 -1
  134. package/dist/tasks/coordinator.js +83 -0
  135. package/dist/tasks/coordinator.js.map +1 -1
  136. package/dist/tasks/state-coordinator.d.ts +19 -0
  137. package/dist/tasks/state-coordinator.d.ts.map +1 -1
  138. package/dist/tasks/state-coordinator.js +40 -0
  139. package/dist/tasks/state-coordinator.js.map +1 -1
  140. package/dist/types.d.ts +39 -7
  141. package/dist/types.d.ts.map +1 -1
  142. package/dist/types.js +9 -0
  143. package/dist/types.js.map +1 -1
  144. package/package.json +1 -1
package/README.md CHANGED
@@ -24,6 +24,11 @@ Agent Foundry extends Claude Code with multi-provider AI orchestration and git w
24
24
  - **State Persistence** - Survives server restarts with automatic state recovery
25
25
  - **Crash Recovery** - Orphan detection, stuck worktree handling, and cleanup commands
26
26
  - **Intelligent Failover** - Automatic provider switching with health tracking, circuit breakers, and cost-aware routing
27
+ - **Context Manager** - Token tracking per provider/model with 40+ model limits, auto-compact at 90%, blocking at 98%
28
+ - **Hooks System** - 9 event types for customizing agent behavior with variable substitution and hot-reload
29
+ - **Background Task Runner** - Queue-based async task execution with AbortController cancellation and progress tracking
30
+ - **MCP Auto Mode** - Intelligent tool selection under context pressure with priority-based deferral
31
+ - **Skills Hot-Reload** - Custom skill definitions with auto-discovery from user and project directories
27
32
 
28
33
  ---
29
34
 
@@ -153,6 +158,198 @@ Agent Foundry includes automatic provider failover with health tracking:
153
158
  - **Circuit Breakers** - Prevents cascading failures
154
159
  - **Cost-Aware Routing** - Optionally prefer cheaper providers
155
160
  - **Configurable Error Codes** - Define which errors trigger failover
161
+ - **Rate Limit Warnings** - Proactive warnings at 70% capacity with header parsing for OpenAI/Anthropic/generic formats
162
+
163
+ ---
164
+
165
+ ## Session Mode (Claude Code Users)
166
+
167
+ When running inside Claude Code, Agent Foundry can delegate Anthropic-based roles back to the current session—no subprocess, no API key, no additional cost.
168
+
169
+ ### Quick Setup
170
+
171
+ ```yaml
172
+ # ~/.config/agent-foundry/config.yaml
173
+ providers:
174
+ anthropic:
175
+ access_mode: session # or 'auto' for flexibility
176
+ ```
177
+
178
+ ### How It Works
179
+
180
+ Instead of spawning a subprocess or making API calls, Agent Foundry returns a **delegation response** that the current Claude session handles directly:
181
+
182
+ - **orchestrator**, **reviewer**, **researcher** roles → Handled by current session
183
+ - **critic**, **coder**, **designer** roles → External API calls (OpenAI, Gemini, etc.)
184
+
185
+ ### Benefits
186
+
187
+ | Without Session Mode | With Session Mode |
188
+ |---------------------|-------------------|
189
+ | 2-5s subprocess startup | ~0ms direct execution |
190
+ | Message structure lost | Full context preserved |
191
+ | Uses subscription quota | No additional cost |
192
+
193
+ See [Session Delegation Architecture](docs/SESSION_DELEGATION.md) for complete documentation.
194
+
195
+ ---
196
+
197
+ ## Hooks System
198
+
199
+ Agent Foundry provides a flexible hooks system that lets you customize agent behavior by running commands at key lifecycle events.
200
+
201
+ ### Supported Events
202
+
203
+ | Event | Description |
204
+ |-------|-------------|
205
+ | `PreToolUse` | Before a tool is invoked |
206
+ | `PostToolUse` | After a tool completes |
207
+ | `Setup` | During agent initialization |
208
+ | `ToolError` | When a tool encounters an error |
209
+ | `TaskStart` | When a task begins execution |
210
+ | `TaskComplete` | When a task finishes successfully |
211
+ | `TaskFail` | When a task fails |
212
+ | `ProviderError` | When an AI provider returns an error |
213
+ | `Failover` | When switching to a fallback provider |
214
+
215
+ ### Configuration
216
+
217
+ ```yaml
218
+ # In ~/.config/agent-foundry/config.yaml
219
+ hooks:
220
+ enabled: true
221
+ configPath: ~/.agent-foundry/hooks.yaml
222
+ events:
223
+ PreToolUse:
224
+ - command: "echo 'Tool: ${TOOL_NAME}'"
225
+ timeout_ms: 5000
226
+ filter:
227
+ tools: ["execute_task", "invoke_agent"]
228
+ TaskComplete:
229
+ - command: "./notify.sh ${TASK_ID}"
230
+ timeout_ms: 10000
231
+ ProviderError:
232
+ - command: "logger -t agent-foundry 'Provider ${PROVIDER} failed: ${ERROR}'"
233
+ ```
234
+
235
+ ### Variable Substitution
236
+
237
+ Hooks support variable substitution with context-specific values:
238
+ - `${TOOL_NAME}` - Name of the tool being invoked
239
+ - `${TASK_ID}` - Current task identifier
240
+ - `${PROVIDER}` - AI provider name
241
+ - `${ERROR}` - Error message (for error events)
242
+ - `${RESULT}` - Result data (for post-completion events)
243
+
244
+ ### Features
245
+
246
+ - **Filtering** - Run hooks only for specific tools, providers, or roles
247
+ - **Timeouts** - Configurable per-hook timeouts prevent blocking
248
+ - **Hot-Reload** - Changes to hooks.yaml are picked up automatically
249
+
250
+ ---
251
+
252
+ ## Skills Hot-Reload
253
+
254
+ Define custom skills that extend agent capabilities with automatic discovery and hot-reload.
255
+
256
+ ### Skill Locations
257
+
258
+ Skills are loaded from:
259
+ 1. `~/.agent-foundry/skills/` - User-level skills (shared across projects)
260
+ 2. `.agent-foundry/skills/` - Project-level skills (project-specific)
261
+
262
+ ### Skill Definition
263
+
264
+ ```yaml
265
+ # ~/.agent-foundry/skills/code-review.yaml
266
+ name: code-review
267
+ description: Comprehensive code review skill
268
+ context_mode: inherit # inherit | fork | isolated
269
+
270
+ prompts:
271
+ system: |
272
+ You are an expert code reviewer focusing on:
273
+ - Security vulnerabilities
274
+ - Performance issues
275
+ - Best practices
276
+ - Code clarity
277
+
278
+ triggers:
279
+ - pattern: "review this code"
280
+ - pattern: "code review"
281
+
282
+ actions:
283
+ - type: invoke_agent
284
+ role: reviewer
285
+ ```
286
+
287
+ ### Context Modes
288
+
289
+ | Mode | Description |
290
+ |------|-------------|
291
+ | `inherit` | Skill runs in the parent agent's context |
292
+ | `fork` | Skill gets a copy of the parent context |
293
+ | `isolated` | Skill runs with a fresh, empty context |
294
+
295
+ ### Features
296
+
297
+ - **Auto-Discovery** - Skills are automatically loaded on startup
298
+ - **Hot-Reload** - Changes to skill files are picked up without restart
299
+ - **Priority Ordering** - Project skills override user skills with the same name
300
+
301
+ ---
302
+
303
+ ## Context Manager
304
+
305
+ Agent Foundry includes intelligent context management to prevent token limit issues and optimize AI provider usage.
306
+
307
+ ### Features
308
+
309
+ - **Token Tracking** - Tracks token usage per provider/model with 40+ pre-configured model limits
310
+ - **Auto-Compact** - Automatically compacts context when reaching 90% capacity
311
+ - **Blocking Threshold** - Blocks new requests at 98% to prevent errors
312
+ - **Visualization** - Context usage visible in debug logs and status commands
313
+
314
+ ### Configuration
315
+
316
+ ```yaml
317
+ # In ~/.config/agent-foundry/config.yaml
318
+ context:
319
+ autoCompact: true
320
+ compactThreshold: 0.9 # Trigger compaction at 90%
321
+ blockThreshold: 0.98 # Block new requests at 98%
322
+ ```
323
+
324
+ ### Supported Model Limits
325
+
326
+ Pre-configured limits for 40+ models including:
327
+ - OpenAI: GPT-4o (128K), GPT-4 Turbo (128K), o1 (200K)
328
+ - Anthropic: Claude 3.5/4 (200K)
329
+ - Google: Gemini 2.5 Pro (1M), Gemini 2.5 Flash (1M)
330
+ - DeepSeek: DeepSeek R1 (64K), DeepSeek Chat (128K)
331
+ - And many more...
332
+
333
+ ---
334
+
335
+ ## MCP Auto Mode
336
+
337
+ When context pressure builds, MCP Auto Mode intelligently manages tool availability.
338
+
339
+ ### How It Works
340
+
341
+ 1. **Context Budget** - Tool descriptions are deferred when exceeding 10% of context budget
342
+ 2. **Priority-Based Selection** - High-priority tools remain available; lower-priority tools are deferred
343
+ 3. **Automatic Restoration** - Deferred tools become available again when context decreases
344
+
345
+ ### Tool Priorities
346
+
347
+ | Priority | Tools |
348
+ |----------|-------|
349
+ | Critical | `invoke_agent`, `execute_task` |
350
+ | High | `list_agents`, `get_task_status` |
351
+ | Medium | `execute_pipeline`, `compare_agents` |
352
+ | Low | `cleanup_worktrees`, `list_worktrees` |
156
353
 
157
354
  ---
158
355
 
@@ -174,6 +371,7 @@ Agent Foundry includes automatic provider failover with health tracking:
174
371
  | `cleanup_worktrees` | Clean up stale or orphaned worktrees |
175
372
  | `resolve_conflicts` | Resolve merge conflicts using various strategies |
176
373
  | `get_worktree_status` | Get detailed status of a specific worktree |
374
+ | `delete_task` | Delete a task from the queue |
177
375
 
178
376
  ---
179
377
 
@@ -279,6 +477,31 @@ worktrees:
279
477
  enabled: true
280
478
  minAvailable: 2
281
479
  maxSize: 5
480
+
481
+ # Hooks configuration
482
+ hooks:
483
+ enabled: true
484
+ configPath: ~/.agent-foundry/hooks.yaml
485
+ events:
486
+ PreToolUse:
487
+ - command: "echo 'Tool: ${TOOL_NAME}'"
488
+ timeout_ms: 5000
489
+ TaskComplete:
490
+ - command: "./notify.sh ${TASK_ID}"
491
+
492
+ # Skills configuration
493
+ skills:
494
+ enabled: true
495
+ directories:
496
+ - ~/.agent-foundry/skills
497
+ - .agent-foundry/skills
498
+ hotReload: true
499
+
500
+ # Context management
501
+ context:
502
+ autoCompact: true
503
+ compactThreshold: 0.9 # Auto-compact at 90% capacity
504
+ blockThreshold: 0.98 # Block new requests at 98% capacity
282
505
  ```
283
506
 
284
507
  ### Environment Variables
@@ -305,6 +528,11 @@ export FIREWORKS_API_KEY="..."
305
528
 
306
529
  # Web Search
307
530
  export PERPLEXITY_API_KEY="pplx-..."
531
+
532
+ # Debug/Observability
533
+ export AGENT_FOUNDRY_DEBUG=true # Enable debug logging
534
+ export AGENT_FOUNDRY_DEBUG_FILE=/path/to/debug.log # Write debug logs to file
535
+ export AGENT_FOUNDRY_DEBUG_VERBOSE=true # Include verbose details
308
536
  ```
309
537
 
310
538
  ---
@@ -361,7 +589,7 @@ agent-foundry help # Show help
361
589
 
362
590
  | Provider | Models | API Key Env Var | Cost |
363
591
  |----------|--------|-----------------|------|
364
- | **Anthropic** | Claude Opus 4, Claude Sonnet 4 | `ANTHROPIC_API_KEY` | $$$ |
592
+ | **Anthropic** | Claude Opus 4, Claude Sonnet 4 | `ANTHROPIC_API_KEY` or session mode | $$$ (free in session mode) |
365
593
  | **OpenAI** | GPT-4o, GPT-4 Turbo, o1, o1-mini, o3-mini | `OPENAI_API_KEY` | $$$ |
366
594
  | **Google Gemini** | Gemini 2.5 Pro, Gemini 2.5 Flash | `GOOGLE_API_KEY` | $$ |
367
595
  | **DeepSeek** | DeepSeek R1, DeepSeek Chat, DeepSeek Coder | `DEEPSEEK_API_KEY` | $ |
@@ -455,7 +683,8 @@ agent-foundry/
455
683
  │ ├── cli/ # CLI command implementations
456
684
  │ ├── mcp/
457
685
  │ │ ├── tools/ # MCP tool implementations
458
- │ │ └── transport/ # stdio transport
686
+ │ │ ├── transport/ # stdio transport
687
+ │ │ └── auto-mode.ts # MCP Auto Mode - intelligent tool selection
459
688
  │ ├── worktrees/
460
689
  │ │ ├── manager.ts # Worktree lifecycle
461
690
  │ │ ├── branch.ts # Branch operations
@@ -482,6 +711,18 @@ agent-foundry/
482
711
  │ │ ├── orchestrator.ts # Retry and failover logic
483
712
  │ │ ├── health-tracker.ts # Provider health monitoring
484
713
  │ │ └── pricing.ts # Cost-aware routing
714
+ │ ├── background/ # Background task execution
715
+ │ │ └── task-runner.ts # Queue-based async task runner
716
+ │ ├── hooks/ # Hook system
717
+ │ │ ├── hook-executor.ts # Hook command execution
718
+ │ │ └── hook-manager.ts # Hook registration and dispatch
719
+ │ ├── skills/ # Skills hot-reload
720
+ │ │ ├── skill-loader.ts # Skill file discovery and parsing
721
+ │ │ ├── skill-executor.ts # Skill action execution
722
+ │ │ └── hot-reloader.ts # File watcher for hot-reload
723
+ │ ├── observability/ # Logging and debugging
724
+ │ │ ├── logger.ts # Structured logging
725
+ │ │ └── debug-logger.ts # Debug output with environment control
485
726
  │ ├── persistence/ # State persistence
486
727
  │ ├── config/ # Configuration management
487
728
  │ └── router/ # Routing engine
@@ -516,6 +757,28 @@ pnpm lint:fix
516
757
  pnpm typecheck
517
758
  ```
518
759
 
760
+ ### Debug Logging
761
+
762
+ Agent Foundry provides enhanced debug logging controlled via environment variables:
763
+
764
+ ```bash
765
+ # Enable debug logging
766
+ export AGENT_FOUNDRY_DEBUG=true
767
+
768
+ # Write debug logs to a file
769
+ export AGENT_FOUNDRY_DEBUG_FILE=/path/to/debug.log
770
+
771
+ # Include verbose details (API payloads, full stack traces)
772
+ export AGENT_FOUNDRY_DEBUG_VERBOSE=true
773
+ ```
774
+
775
+ Debug logging includes:
776
+ - Provider API calls and responses
777
+ - Failover decisions and health tracking
778
+ - Hook execution and timing
779
+ - Skill loading and hot-reload events
780
+ - Context manager token tracking
781
+
519
782
  ---
520
783
 
521
784
  ## Security
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Background Module
3
+ *
4
+ * Provides background task execution for non-blocking agent invocations
5
+ * and pipeline steps. Supports concurrency control, cancellation,
6
+ * progress tracking, and event-based notifications.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * import { BackgroundTaskRunner } from './background/index.js';
11
+ *
12
+ * const runner = new BackgroundTaskRunner({ maxConcurrent: 3 }, logger);
13
+ *
14
+ * // Submit a background agent invocation
15
+ * const taskId = await runner.run(
16
+ * 'agent_invocation',
17
+ * 'Review authentication code',
18
+ * async () => {
19
+ * return await orchestrator.executeWithFailover('reviewer', messages, options);
20
+ * },
21
+ * { role: 'reviewer', provider: 'openai' }
22
+ * );
23
+ *
24
+ * // Check status later
25
+ * const task = runner.getTask(taskId);
26
+ *
27
+ * // Or wait for completion
28
+ * const completed = await runner.waitFor(taskId, 60000);
29
+ * ```
30
+ */
31
+ export * from './types.js';
32
+ export { BackgroundTaskRunner } from './task-runner.js';
33
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/background/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,cAAc,YAAY,CAAC;AAC3B,OAAO,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC"}
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Background Module
3
+ *
4
+ * Provides background task execution for non-blocking agent invocations
5
+ * and pipeline steps. Supports concurrency control, cancellation,
6
+ * progress tracking, and event-based notifications.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * import { BackgroundTaskRunner } from './background/index.js';
11
+ *
12
+ * const runner = new BackgroundTaskRunner({ maxConcurrent: 3 }, logger);
13
+ *
14
+ * // Submit a background agent invocation
15
+ * const taskId = await runner.run(
16
+ * 'agent_invocation',
17
+ * 'Review authentication code',
18
+ * async () => {
19
+ * return await orchestrator.executeWithFailover('reviewer', messages, options);
20
+ * },
21
+ * { role: 'reviewer', provider: 'openai' }
22
+ * );
23
+ *
24
+ * // Check status later
25
+ * const task = runner.getTask(taskId);
26
+ *
27
+ * // Or wait for completion
28
+ * const completed = await runner.waitFor(taskId, 60000);
29
+ * ```
30
+ */
31
+ export * from './types.js';
32
+ export { BackgroundTaskRunner } from './task-runner.js';
33
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/background/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAEH,cAAc,YAAY,CAAC;AAC3B,OAAO,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC"}
@@ -0,0 +1,177 @@
1
+ /**
2
+ * Background Task Runner
3
+ *
4
+ * Manages background task execution for non-blocking agent invocations
5
+ * and pipeline steps. Supports concurrency limits, cancellation,
6
+ * progress tracking, and event-based notifications.
7
+ */
8
+ import { EventEmitter } from 'events';
9
+ import type { Logger } from '../observability/logger.js';
10
+ import type { BackgroundTask, BackgroundTaskConfig, BackgroundTaskType, SubmitTaskOptions, SerializedBackgroundTask } from './types.js';
11
+ /**
12
+ * Manages background task execution with concurrency control.
13
+ *
14
+ * Features:
15
+ * - Queue-based execution with configurable concurrency
16
+ * - Task cancellation via AbortController
17
+ * - Progress tracking and notifications
18
+ * - Event emission for task lifecycle
19
+ * - Automatic cleanup of old tasks
20
+ *
21
+ * @example
22
+ * ```typescript
23
+ * const runner = new BackgroundTaskRunner({ maxConcurrent: 3 }, logger);
24
+ *
25
+ * // Submit a background task
26
+ * const taskId = await runner.run(
27
+ * 'agent_invocation',
28
+ * 'Review authentication code',
29
+ * async () => {
30
+ * return await orchestrator.executeWithFailover('reviewer', messages, options);
31
+ * },
32
+ * { role: 'reviewer', provider: 'openai' }
33
+ * );
34
+ *
35
+ * // Check status later
36
+ * const task = runner.getTask(taskId);
37
+ * if (task?.status === 'completed') {
38
+ * console.log('Result:', task.result);
39
+ * }
40
+ *
41
+ * // Or wait for completion
42
+ * const completed = await runner.waitFor(taskId, 60000);
43
+ * ```
44
+ */
45
+ export declare class BackgroundTaskRunner extends EventEmitter {
46
+ private readonly tasks;
47
+ private readonly queue;
48
+ private runningCount;
49
+ private readonly config;
50
+ private readonly logger;
51
+ private isEnabled;
52
+ private isShuttingDown;
53
+ constructor(config: Partial<BackgroundTaskConfig>, logger: Logger);
54
+ /**
55
+ * Check if background tasks are enabled.
56
+ * Respects AGENT_FOUNDRY_DISABLE_BACKGROUND_TASKS env var.
57
+ */
58
+ isBackgroundEnabled(): boolean;
59
+ /**
60
+ * Enable or disable background task execution.
61
+ */
62
+ setEnabled(enabled: boolean): void;
63
+ /**
64
+ * Submit a task to run in the background.
65
+ * Returns immediately with task ID.
66
+ *
67
+ * @param task - Task definition (without id, status, createdAt)
68
+ * @returns Task ID for tracking
69
+ */
70
+ submit(task: Omit<BackgroundTask, 'id' | 'status' | 'createdAt'>): string;
71
+ /**
72
+ * Execute a function as a background task.
73
+ *
74
+ * @param type - Task type
75
+ * @param description - Task description
76
+ * @param fn - Async function to execute
77
+ * @param options - Additional options
78
+ * @returns Task ID for tracking
79
+ */
80
+ run<T>(type: BackgroundTaskType, description: string, fn: () => Promise<T>, options?: SubmitTaskOptions): Promise<string>;
81
+ /**
82
+ * Get task by ID.
83
+ */
84
+ getTask(taskId: string): BackgroundTask | undefined;
85
+ /**
86
+ * Get all tasks.
87
+ */
88
+ getAllTasks(): BackgroundTask[];
89
+ /**
90
+ * Get running tasks.
91
+ */
92
+ getRunningTasks(): BackgroundTask[];
93
+ /**
94
+ * Get pending tasks in queue.
95
+ */
96
+ getPendingTasks(): BackgroundTask[];
97
+ /**
98
+ * Get completed tasks.
99
+ */
100
+ getCompletedTasks(): BackgroundTask[];
101
+ /**
102
+ * Cancel a running or pending task.
103
+ *
104
+ * @param taskId - ID of task to cancel
105
+ * @returns true if task was cancelled, false if not found or already complete
106
+ */
107
+ cancel(taskId: string): boolean;
108
+ /**
109
+ * Wait for a task to complete.
110
+ *
111
+ * @param taskId - ID of task to wait for
112
+ * @param timeout - Maximum time to wait in ms (default: 60000)
113
+ * @returns The completed task
114
+ * @throws Error if task not found or timeout exceeded
115
+ */
116
+ waitFor(taskId: string, timeout?: number): Promise<BackgroundTask>;
117
+ /**
118
+ * Update task progress.
119
+ *
120
+ * @param taskId - ID of task to update
121
+ * @param progress - Progress percentage (0-100)
122
+ * @param message - Optional progress message
123
+ */
124
+ updateProgress(taskId: string, progress: number, message?: string): void;
125
+ /**
126
+ * Clean up completed/failed tasks older than specified age.
127
+ *
128
+ * @param maxAgeMs - Maximum age in ms (default: 1 hour)
129
+ * @returns Number of tasks cleaned up
130
+ */
131
+ cleanup(maxAgeMs?: number): number;
132
+ /**
133
+ * Shutdown the runner - cancel pending tasks and wait for running tasks.
134
+ *
135
+ * @param timeout - Maximum time to wait for running tasks in ms (default: 30000)
136
+ */
137
+ shutdown(timeout?: number): Promise<void>;
138
+ /**
139
+ * Get statistics about the task runner.
140
+ */
141
+ getStats(): {
142
+ pending: number;
143
+ running: number;
144
+ completed: number;
145
+ failed: number;
146
+ cancelled: number;
147
+ total: number;
148
+ queueLength: number;
149
+ maxConcurrent: number;
150
+ };
151
+ /**
152
+ * Serialize tasks for persistence.
153
+ * Only serializes metadata, not results or errors.
154
+ */
155
+ serializeTasks(): SerializedBackgroundTask[];
156
+ /**
157
+ * Process the task queue, starting tasks up to maxConcurrent.
158
+ */
159
+ private processQueue;
160
+ /**
161
+ * Execute a single task.
162
+ */
163
+ private executeTask;
164
+ /**
165
+ * Mark a task as completed.
166
+ */
167
+ private markCompleted;
168
+ /**
169
+ * Mark a task as failed.
170
+ */
171
+ private markFailed;
172
+ /**
173
+ * Send a notification if enabled.
174
+ */
175
+ private notify;
176
+ }
177
+ //# sourceMappingURL=task-runner.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"task-runner.d.ts","sourceRoot":"","sources":["../../src/background/task-runner.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAGtC,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,4BAA4B,CAAC;AACzD,OAAO,KAAK,EACV,cAAc,EACd,oBAAoB,EAEpB,kBAAkB,EAGlB,iBAAiB,EACjB,wBAAwB,EACzB,MAAM,YAAY,CAAC;AAwBpB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,qBAAa,oBAAqB,SAAQ,YAAY;IACpD,OAAO,CAAC,QAAQ,CAAC,KAAK,CAA0C;IAChE,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAwB;IAC9C,OAAO,CAAC,YAAY,CAAa;IACjC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAuB;IAC9C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAS;IAChC,OAAO,CAAC,SAAS,CAAiB;IAClC,OAAO,CAAC,cAAc,CAAkB;gBAE5B,MAAM,EAAE,OAAO,CAAC,oBAAoB,CAAC,EAAE,MAAM,EAAE,MAAM;IAejE;;;OAGG;IACH,mBAAmB,IAAI,OAAO;IAQ9B;;OAEG;IACH,UAAU,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI;IAKlC;;;;;;OAMG;IACH,MAAM,CACJ,IAAI,EAAE,IAAI,CAAC,cAAc,EAAE,IAAI,GAAG,QAAQ,GAAG,WAAW,CAAC,GACxD,MAAM;IAqCT;;;;;;;;OAQG;IACG,GAAG,CAAC,CAAC,EACT,IAAI,EAAE,kBAAkB,EACxB,WAAW,EAAE,MAAM,EACnB,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,EACpB,OAAO,CAAC,EAAE,iBAAiB,GAC1B,OAAO,CAAC,MAAM,CAAC;IA0BlB;;OAEG;IACH,OAAO,CAAC,MAAM,EAAE,MAAM,GAAG,cAAc,GAAG,SAAS;IAInD;;OAEG;IACH,WAAW,IAAI,cAAc,EAAE;IAI/B;;OAEG;IACH,eAAe,IAAI,cAAc,EAAE;IAInC;;OAEG;IACH,eAAe,IAAI,cAAc,EAAE;IAInC;;OAEG;IACH,iBAAiB,IAAI,cAAc,EAAE;IAMrC;;;;;OAKG;IACH,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO;IAsC/B;;;;;;;OAOG;IACG,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,MAAc,GAAG,OAAO,CAAC,cAAc,CAAC;IAoD/E;;;;;;OAMG;IACH,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI;IAoBxE;;;;;OAKG;IACH,OAAO,CAAC,QAAQ,GAAE,MAA+B,GAAG,MAAM;IAsB1D;;;;OAIG;IACG,QAAQ,CAAC,OAAO,GAAE,MAAc,GAAG,OAAO,CAAC,IAAI,CAAC;IA+BtD;;OAEG;IACH,QAAQ,IAAI;QACV,OAAO,EAAE,MAAM,CAAC;QAChB,OAAO,EAAE,MAAM,CAAC;QAChB,SAAS,EAAE,MAAM,CAAC;QAClB,MAAM,EAAE,MAAM,CAAC;QACf,SAAS,EAAE,MAAM,CAAC;QAClB,KAAK,EAAE,MAAM,CAAC;QACd,WAAW,EAAE,MAAM,CAAC;QACpB,aAAa,EAAE,MAAM,CAAC;KACvB;IAcD;;;OAGG;IACH,cAAc,IAAI,wBAAwB,EAAE;IAuB5C;;OAEG;IACH,OAAO,CAAC,YAAY;IAgBpB;;OAEG;YACW,WAAW;IAqEzB;;OAEG;IACH,OAAO,CAAC,aAAa;IA0BrB;;OAEG;IACH,OAAO,CAAC,UAAU;IA4BlB;;OAEG;IACH,OAAO,CAAC,MAAM;CAef"}