@nuvin/nuvin-core 1.13.0 → 1.13.3

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.
package/dist/VERSION CHANGED
@@ -1,4 +1,4 @@
1
1
  {
2
- "version": "1.13.0",
3
- "commit": "76d9e11"
2
+ "version": "1.13.3",
3
+ "commit": "573ca7d"
4
4
  }
package/dist/index.d.ts CHANGED
@@ -32,6 +32,7 @@ type CompleteAgent = Required<Pick<AgentTemplate, 'id' | 'name' | 'description'
32
32
  type SpecialistAgentConfig = {
33
33
  agentId: string;
34
34
  agentName: string;
35
+ agentType?: string;
35
36
  taskDescription: string;
36
37
  systemPrompt: string;
37
38
  tools: string[];
@@ -48,6 +49,8 @@ type SpecialistAgentConfig = {
48
49
  conversationId?: string;
49
50
  messageId?: string;
50
51
  toolCallId?: string;
52
+ resumeSessionId?: string;
53
+ previousMessages?: Message[];
51
54
  };
52
55
  /**
53
56
  * Specialist Agent Result
@@ -65,6 +68,7 @@ type SpecialistAgentResult = {
65
68
  events?: AgentEvent[];
66
69
  errorMessage?: string;
67
70
  metrics?: MetricsSnapshot;
71
+ sessionId?: string;
68
72
  };
69
73
  };
70
74
  /**
@@ -73,6 +77,9 @@ type SpecialistAgentResult = {
73
77
  type AssignParams = {
74
78
  agent: string;
75
79
  task: string;
80
+ description?: string;
81
+ run_in_background?: boolean;
82
+ resume?: string;
76
83
  };
77
84
 
78
85
  interface AgentFilePersistenceOptions {
@@ -345,7 +352,7 @@ type DelegationMetadata = {
345
352
  agentId: string;
346
353
  agentName: string;
347
354
  delegationDepth: number;
348
- status: 'success' | 'error' | 'timeout';
355
+ status?: 'success' | 'error' | 'timeout';
349
356
  executionTimeMs: number;
350
357
  toolCallsExecuted: number;
351
358
  tokensUsed?: number;
@@ -355,6 +362,8 @@ type DelegationMetadata = {
355
362
  model?: string;
356
363
  conversationHistoryLength?: number;
357
364
  eventsEmitted?: number;
365
+ sessionId?: string;
366
+ runningInBackground?: boolean;
358
367
  };
359
368
 
360
369
  type BashToolMetadata = CommandMetadata & {
@@ -621,6 +630,7 @@ interface LLMPort {
621
630
  onReasoningChunk?: (delta: string) => void;
622
631
  onToolCallDelta?: (tc: ToolCall) => void;
623
632
  onStreamFinish?: (finishReason?: string, usage?: UsageData) => void;
633
+ onUsage?: (usage: UsageData) => void;
624
634
  }, signal?: AbortSignal): Promise<CompletionResult>;
625
635
  getModels?(signal?: AbortSignal): Promise<Array<{
626
636
  id: string;
@@ -809,7 +819,7 @@ interface AgentAwareToolPort {
809
819
  getAgentRegistry(): AgentRegistry | undefined;
810
820
  }
811
821
  interface OrchestratorAwareToolPort {
812
- setOrchestrator(config: AgentConfig, tools: ToolPort, llmFactory?: LLMFactory, configResolver?: () => Partial<AgentConfig>): void;
822
+ setOrchestrator(config: AgentConfig, tools: ToolPort, llmFactory?: LLMFactory, configResolver?: () => Partial<AgentConfig>, createMemoryForAgent?: (agentKey: string) => MemoryPort<Message>): void;
813
823
  }
814
824
  type MemorySnapshot<T = unknown> = Record<string, T[]>;
815
825
  interface MemoryPersistence<T = unknown> {
@@ -1170,7 +1180,7 @@ declare function buildInjectedSystem(p: InjectedSystemParams, { withSubAgent }?:
1170
1180
  * System prompt for the agent creation LLM
1171
1181
  * This prompt guides the LLM to generate specialist agent configurations
1172
1182
  */
1173
- declare const AGENT_CREATOR_SYSTEM_PROMPT = "You are an elite AI agent architect. Your job is to translate user requirements into a precise, reliable agent specification and final system prompt that downstream systems can use directly.\n\n### Context you may receive\n- Project materials (e.g., CLAUDE.md), coding standards, project structure, and custom requirements. Inherit these patterns explicitly in your design.\n\n### Your high-level objective\n- Produce a complete, self-sufficient agent spec that includes: a concise identifier, a clear \"when to use\" description with examples, and a robust system prompt that governs behavior.\n\n### Operating principles (follow in order)\n1) **Extract Core Intent**\n - Identify purpose, scope, users, inputs, outputs, success criteria, constraints, and any implicit needs.\n - If code-review is requested, default scope to *recently written or changed code* unless the user explicitly requests a full-repo review.\n2) **Design Expert Persona**\n - Define a domain-specific role (e.g., senior code reviewer, API docs writer), decision style, and domain heuristics.\n - Assume the role of a recognized domain expert with deep mastery of relevant concepts, methodologies, and best practices. Let this expertise guide your decision-making through nuanced understanding, authoritative judgment, and strategic thinking that anticipates challenges and recognizes proven patterns.\n - Communicate with professional confidence while acknowledging uncertainty when appropriate.\n1) **Decompose the Task**\n - Lay out a short pipeline (PLAN \u2192 EXECUTE \u2192 VERIFY \u2192 OUTPUT). Keep steps concrete and checklist-driven. (Structured, decomposed prompts improve reliability.)\n2) **Specify Inputs, Tools, and Boundaries**\n - Name required inputs; state assumptions if missing.\n - List allowed tools/APIs and how to invoke them; define fallback behavior if tools fail.\n - Include stop conditions and escalation rules (when to ask the user for clarification, when to return partial results).\n3) **Quality & Reliability**\n - Build in self-checks: requirement coverage, constraint adherence, formatting validation.\n - Where applicable, instruct the agent to generate and verify reasoning internally, then present only the final, concise result.\n - Encourage evidence/verification for factual claims when sources are available.\n4) **Output Contract**\n - Define exact output formats (schemas, sections, or bullet checklists) so downstream consumers are deterministic.\n\n### System-prompt structure you must generate (use this template)\n\n# Role\nYou are <expert-persona>. You optimize for correctness, clarity, and adherence to project standards.\n\n# Goals\n- <bullet list of concrete goals>\n\n# Inputs\n- <required inputs>\n- Assumptions if missing: <rules to infer or request>\n\n# Process\n- PLAN: <brief checklist>\n- EXECUTE: <methods, frameworks, heuristics>\n- VERIFY: <self-checks, requirement coverage, constraint audit>\n- OUTPUT: <exact sections / schema>\n\n# Policies & Boundaries\n- Follow project coding standards from CLAUDE.md if provided.\n- Review only recent changes unless told otherwise.\n- If information is insufficient, ask precisely targeted questions (max 3) before proceeding; otherwise proceed with clearly stated assumptions.\n- Stop and escalate if safety, legal, or data-governance risks are detected.\n\n# Quality Bar\n- Ensure: correctness > completeness > speed.\n- Run a final \"Spec QA\" checklist before responding:\n 1) All user requirements mapped to sections?\n 2) Output format matches the contract exactly?\n 3) Edge cases addressed?\n 4) Examples included when helpful?\n\"\"\"\n\n### What to return\n- A **JSON object** with exactly these fields:\n - 'id': short, kebab-case, descriptive (2\u20134 words), no generic terms like 'helper' or 'assistant'.\n - 'description': starts with \"Use this agent when...\" and includes at least two concrete examples showing tool invocation (not direct replies). Include proactive triggers if implied.\n - 'systemPrompt': the final second-person system prompt built from the template above.\n\n### Additional guidance\n- Prefer explicit instructions over prohibitions; say what to do. (Specific, structured prompts improve outcomes.)\n- Use few-shot examples when they clarify behavior.\n- Be concise but complete\u2014every line should add execution value.\n- If constraints conflict, state the trade-off and your resolution.\n- Only include optional advanced reasoning guidance when beneficial; keep the final user-visible output clean.\n\n\n### REQUIRED OUTPUT: You MUST return a JSON object with at least the 'systemPrompt' field.\n\n**OPTIONAL FIELDS**: You may also include any of these fields (they have defaults if omitted):\n- 'id': A kebab-case identifier (e.g., \"security-auditor\", \"data-analyzer\")\n- 'name': A human-readable name (e.g., \"Security Auditor\", \"Data Analyzer\")\n- 'description': A brief description of when to use this agent\n- 'tools': An array of tool names the agent should have access to\n- 'temperature': A number between 0 and 1 (default: 0.7)\n\nExample outputs:\n\n{\n \"id\": \"security-auditor\",\n \"name\": \"Security Auditor\",\n \"description\": \"Use this agent when you need to perform a security audit on a codebase or application. For example, you might invoke this agent when you want to check for vulnerabilities in a web application or when you need to ensure compliance with security best practices.\",\n \"systemPrompt\": \"\n You are a security auditing specialist. Your role is to analyze code for security vulnerabilities, including SQL injection, XSS, CSRF, authentication issues, and insecure dependencies.\n\n Approach:\n 1. Read and analyze the codebase systematically\n 2. Check for common vulnerability patterns\n 3. Review dependencies for known CVEs\n 4. Provide specific, actionable remediation steps\n\n Always prioritize critical security issues and explain the potential impact.\",\n \"tools\": [\"file_read\", \"web_search\", \"bash_tool\"],\n \"temperature\": 0.3\n}\n\n{\n \"systemPrompt\": \"You are a helpful specialist agent that assists with general programming tasks. You can read files, search for information, and provide clear explanations.\"\n}\n\nRemember: 'systemPrompt' is REQUIRED. All other fields are optional and will have defaults applied if omitted.\nIMPORTANT: Return ONLY the JSON object as your response. Do NOT include any additional text or explanation.\n";
1183
+ declare const AGENT_CREATOR_SYSTEM_PROMPT = "You are an elite AI agent architect. Your job is to translate user requirements into a precise, reliable agent specification and final system prompt that downstream systems can use directly.\n\n### Context you may receive\n- Project materials (e.g., CLAUDE.md), coding standards, project structure, and custom requirements. Inherit these patterns explicitly in your design.\n\n### Your high-level objective\n- Produce a complete, self-sufficient agent spec that includes: a concise identifier, a clear \"when to use\" description with examples, and a robust system prompt that governs behavior.\n\n### Operating principles (follow in order)\n1) **Extract Core Intent**\n - Identify purpose, scope, users, inputs, outputs, success criteria, constraints, and any implicit needs.\n - If code-review is requested, default scope to *recently written or changed code* unless the user explicitly requests a full-repo review.\n2) **Design Expert Persona**\n - Define a domain-specific role (e.g., senior code reviewer, API docs writer), decision style, and domain heuristics.\n - Assume the role of a recognized domain expert with deep mastery of relevant concepts, methodologies, and best practices.\n3) **Decompose the Task**\n - Lay out a short pipeline (PLAN \u2192 EXECUTE \u2192 VERIFY \u2192 OUTPUT). Keep steps concrete and checklist-driven.\n4) **Specify Inputs, Tools, and Boundaries**\n - Name required inputs; state assumptions if missing.\n - List allowed tools and how to invoke them; define fallback behavior if tools fail.\n - Include stop conditions and escalation rules (when to ask the user for clarification, when to return partial results).\n5) **Quality & Reliability**\n - Build in self-checks: requirement coverage, constraint adherence, formatting validation.\n - Where applicable, instruct the agent to generate and verify reasoning internally, then present only the final, concise result.\n6) **Output Contract**\n - Define exact output formats (schemas, sections, or bullet checklists) so downstream consumers are deterministic.\n\n### System-prompt structure you must generate\n\n# Role\nYou are <expert-persona>. You optimize for correctness, clarity, and adherence to project standards.\n\n# Goals\n- <bullet list of concrete goals>\n\n# Inputs\n- <required inputs>\n- Assumptions if missing: <rules to infer or request>\n\n# Process\n- PLAN: <brief checklist>\n- EXECUTE: <methods, frameworks, heuristics>\n- VERIFY: <self-checks, requirement coverage, constraint audit>\n- OUTPUT: <exact sections / schema>\n\n# Policies & Boundaries\n- Follow project coding standards from CLAUDE.md if provided.\n- Review only recent changes unless told otherwise.\n- If information is insufficient, ask precisely targeted questions (max 3) before proceeding; otherwise proceed with clearly stated assumptions.\n- Stop and escalate if safety, legal, or data-governance risks are detected.\n\n# Quality Bar\n- Ensure: correctness > completeness > speed.\n- Run a final \"Spec QA\" checklist before responding:\n 1) All user requirements mapped to sections?\n 2) Output format matches the contract exactly?\n 3) Edge cases addressed?\n 4) Examples included when helpful?\n\n### What to return\nReturn a **JSON object** with exactly these fields:\n- **systemPrompt** (REQUIRED): The final second-person system prompt built from the template above.\n- **id** (optional): A kebab-case identifier (e.g., \"security-auditor\", \"data-analyzer\"). If omitted, one will be auto-generated.\n- **name** (optional): A human-readable name (e.g., \"Security Auditor\", \"Data Analyzer\"). Defaults to \"Custom Agent\".\n- **description** (optional): Starts with \"Use this agent when...\" with 2+ concrete examples showing tool invocation. Defaults to generic description.\n- **tools** (optional): Array of tool names the agent should use. Defaults to [\"file_read\", \"web_search\"].\n- **temperature** (optional): Number between 0-1 for sampling. Lower values = more deterministic. Recommended: 0.3-0.5.\n- **model** (optional): Specific model to use (e.g., \"gpt-4\", \"claude-3-sonnet\"). If omitted, inherits from parent.\n- **provider** (optional): LLM provider (e.g., \"openrouter\", \"github\", \"anthropic\").\n- **topP** (optional): Top-p sampling parameter. Recommended: 1.\n- **maxTokens** (optional): Maximum tokens for response. Recommended: 64000 or omitted.\n- **timeoutMs** (optional): Timeout in milliseconds. Default: 300000 (5 minutes).\n\n### Examples\n\nExample 1:\n{\n \"id\": \"security-auditor\",\n \"name\": \"Security Auditor\",\n \"description\": \"Use this agent when you need to perform a security audit on a codebase or application. For example, you might invoke this agent when you want to check for vulnerabilities in a web application or when you need to ensure compliance with security best practices.\",\n \"systemPrompt\": \"You are a security auditing specialist. Your role is to analyze code for security vulnerabilities, including SQL injection, XSS, CSRF, authentication issues, and insecure dependencies. Approach: 1. file_read and analyze the codebase systematically. 2. Check for common vulnerability patterns. 3. Review dependencies for known CVEs. 4. Provide specific, actionable remediation steps. Always prioritize critical security issues and explain the potential impact.\",\n \"tools\": [\"file_read\", \"web_search\", \"bash_tool\", \"grep_tool\"],\n \"temperature\": 0.3\n}\n\nExample 2 (minimal):\n{\n \"systemPrompt\": \"You are a helpful specialist agent that assists with general programming tasks. You can read files, search for information, and provide clear explanations.\",\n \"tools\": [\"file_read\", \"web_search\"]\n}\n\n### Important guidelines\n- Use explicit instructions over prohibitions; say what to do.\n- Use few-shot examples when they clarify behavior.\n- Be concise but complete\u2014every line should add execution value.\n- If constraints conflict, state the trade-off and your resolution.\n- Include specific tool names from the available tools list.\n- Lower temperature (0.3) produces more consistent results.\n\n**Remember: Return ONLY the JSON object as your response. Do NOT include any additional text or explanation.**";
1174
1184
  /**
1175
1185
  * Generate a user prompt for agent creation
1176
1186
  */
@@ -1217,6 +1227,27 @@ declare class PersistedMemory<T = unknown> implements MemoryPort<T> {
1217
1227
  importSnapshot(snapshot: MemorySnapshot<T>): Promise<void>;
1218
1228
  }
1219
1229
 
1230
+ interface MultiFileMemoryPersistenceOptions {
1231
+ directory: string;
1232
+ /** Converts a memory key to a filename. Default: `history.${key}.json` */
1233
+ getFilename?: (key: string) => string;
1234
+ /** Extracts the key from a filename. Default: extracts from `history.{key}.json` */
1235
+ getKeyFromFilename?: (filename: string) => string | null;
1236
+ }
1237
+ /**
1238
+ * Multi-file persistence adapter that stores each memory key in its own file.
1239
+ * Files are named using the pattern: history.{key}.json
1240
+ * Only keys starting with 'agent:' are persisted to separate files.
1241
+ */
1242
+ declare class MultiFileMemoryPersistence<T = unknown> implements MemoryPersistence<T> {
1243
+ private options;
1244
+ private getFilename;
1245
+ private getKeyFromFilename;
1246
+ constructor(options: MultiFileMemoryPersistenceOptions);
1247
+ load(): Promise<MemorySnapshot<T>>;
1248
+ save(snapshot: MemorySnapshot<T>): Promise<void>;
1249
+ }
1250
+
1220
1251
  declare class MemoryPortMetadataAdapter<T> implements MetadataPort<T> {
1221
1252
  private memory;
1222
1253
  private prefix;
@@ -1397,19 +1428,6 @@ interface AgentCatalog {
1397
1428
  list(): AgentTemplate[];
1398
1429
  get(agentId: string): AgentTemplate | undefined;
1399
1430
  }
1400
- interface DelegationPolicyInput {
1401
- agent: AgentTemplate;
1402
- enabledAgents: Record<string, boolean>;
1403
- params: AssignParams;
1404
- context?: ToolExecutionContext;
1405
- }
1406
- interface PolicyDecision {
1407
- allowed: boolean;
1408
- reason?: string;
1409
- }
1410
- interface DelegationPolicy {
1411
- evaluate(input: DelegationPolicyInput): PolicyDecision;
1412
- }
1413
1431
  interface SpecialistAgentFactoryInput {
1414
1432
  template: AgentTemplate;
1415
1433
  params: AssignParams;
@@ -1417,7 +1435,7 @@ interface SpecialistAgentFactoryInput {
1417
1435
  currentDepth: number;
1418
1436
  }
1419
1437
  interface SpecialistAgentFactory {
1420
- create(input: SpecialistAgentFactoryInput): SpecialistAgentConfig;
1438
+ create(input: SpecialistAgentFactoryInput): SpecialistAgentConfig | Promise<SpecialistAgentConfig>;
1421
1439
  }
1422
1440
  interface AgentCommandRunner {
1423
1441
  run(config: SpecialistAgentConfig, context?: ToolExecutionContext): Promise<SpecialistAgentResult>;
@@ -1428,21 +1446,18 @@ interface DelegationResult {
1428
1446
  metadata?: Record<string, unknown>;
1429
1447
  error?: string;
1430
1448
  }
1431
- interface DelegationResultFormatter {
1432
- formatSuccess(agentId: string, result: SpecialistAgentResult): Pick<DelegationResult, 'summary' | 'metadata'>;
1433
- formatError(error: unknown): string;
1449
+ interface BackgroundDelegationResult {
1450
+ success: boolean;
1451
+ sessionId?: string;
1452
+ error?: string;
1434
1453
  }
1435
1454
  interface DelegationService {
1436
1455
  setEnabledAgents(enabledAgents: Record<string, boolean>): void;
1437
1456
  listEnabledAgents(): AgentTemplate[];
1438
1457
  delegate(params: AssignParams, context?: ToolExecutionContext): Promise<DelegationResult>;
1439
- }
1440
-
1441
- /**
1442
- * Default policy checks whether the agent is enabled (if explicitly configured).
1443
- */
1444
- declare class DefaultDelegationPolicy implements DelegationPolicy {
1445
- evaluate(input: DelegationPolicyInput): PolicyDecision;
1458
+ delegateBackground?(params: AssignParams, context?: ToolExecutionContext): Promise<BackgroundDelegationResult>;
1459
+ getBackgroundResult?(sessionId: string, blocking?: boolean): Promise<DelegationResult | null>;
1460
+ isBackgroundAgentRunning?(sessionId: string): boolean;
1446
1461
  }
1447
1462
 
1448
1463
  type SystemContext = {
@@ -1466,8 +1481,46 @@ declare class DefaultSpecialistAgentFactory implements SpecialistAgentFactory {
1466
1481
  systemContextProvider?: SystemContextProvider;
1467
1482
  agentListProvider?: AgentListProvider;
1468
1483
  idGenerator?: IdGenerator;
1484
+ createMemoryForAgent?: (agentKey: string) => MemoryPort<Message>;
1469
1485
  } | undefined);
1470
- create(input: SpecialistAgentFactoryInput): SpecialistAgentConfig;
1486
+ create(input: SpecialistAgentFactoryInput): Promise<SpecialistAgentConfig>;
1487
+ }
1488
+
1489
+ interface AgentSession {
1490
+ id: string;
1491
+ agentType: string;
1492
+ parentConversationId: string;
1493
+ state: 'pending' | 'running' | 'completed' | 'failed';
1494
+ taskDescription: string;
1495
+ startTime: number;
1496
+ endTime?: number;
1497
+ result?: string;
1498
+ error?: string;
1499
+ metrics?: {
1500
+ tokensUsed?: number;
1501
+ toolCallsExecuted?: number;
1502
+ executionTimeMs?: number;
1503
+ };
1504
+ }
1505
+ interface AgentStateManager {
1506
+ create(agentType: string, parentConvoId: string, taskDescription: string): string;
1507
+ get(sessionId: string): AgentSession | undefined;
1508
+ update(sessionId: string, updates: Partial<AgentSession>): void;
1509
+ getRunning(): AgentSession[];
1510
+ getByParent(parentConvoId: string): AgentSession[];
1511
+ getAllSessions(): AgentSession[];
1512
+ cleanup(maxAgeMs: number): number;
1513
+ }
1514
+ declare class DefaultAgentStateManager implements AgentStateManager {
1515
+ private sessions;
1516
+ private idGenerator;
1517
+ create(agentType: string, parentConvoId: string, taskDescription: string): string;
1518
+ get(sessionId: string): AgentSession | undefined;
1519
+ update(sessionId: string, updates: Partial<AgentSession>): void;
1520
+ getRunning(): AgentSession[];
1521
+ getByParent(parentConvoId: string): AgentSession[];
1522
+ getAllSessions(): AgentSession[];
1523
+ cleanup(maxAgeMs: number): number;
1471
1524
  }
1472
1525
 
1473
1526
  /**
@@ -1479,10 +1532,13 @@ declare class AgentManager {
1479
1532
  private llmFactory?;
1480
1533
  private eventCallback?;
1481
1534
  private configResolver?;
1535
+ private metricsPort?;
1482
1536
  private llmResolver;
1483
1537
  private activeAgents;
1484
1538
  private eventCollectors;
1485
- constructor(delegatingConfig: AgentConfig, delegatingTools: ToolPort, llmFactory?: LLMFactory | undefined, eventCallback?: ((event: AgentEvent) => void) | undefined, configResolver?: (() => Partial<AgentConfig>) | undefined);
1539
+ private stateManager;
1540
+ private createMemoryForAgent?;
1541
+ constructor(delegatingConfig: AgentConfig, delegatingTools: ToolPort, llmFactory?: LLMFactory | undefined, eventCallback?: ((event: AgentEvent) => void) | undefined, configResolver?: (() => Partial<AgentConfig>) | undefined, createMemoryForAgent?: (agentKey: string) => MemoryPort<Message>, metricsPort?: MetricsPort | undefined);
1486
1542
  /**
1487
1543
  * Create and execute a specialist agent for a specific task
1488
1544
  */
@@ -1507,6 +1563,10 @@ declare class AgentManager {
1507
1563
  * Cleanup all active agents (emergency stop)
1508
1564
  */
1509
1565
  cleanup(): void;
1566
+ /**
1567
+ * Get the state manager for querying sessions
1568
+ */
1569
+ getStateManager(): AgentStateManager;
1510
1570
  }
1511
1571
 
1512
1572
  declare class AgentManagerCommandRunner implements AgentCommandRunner {
@@ -1514,37 +1574,25 @@ declare class AgentManagerCommandRunner implements AgentCommandRunner {
1514
1574
  private readonly delegatingTools;
1515
1575
  private readonly llmFactory?;
1516
1576
  private readonly configResolver?;
1517
- constructor(delegatingConfig: AgentConfig, delegatingTools: ToolPort, llmFactory?: LLMFactory | undefined, configResolver?: (() => Partial<AgentConfig>) | undefined);
1577
+ private readonly createMemoryForAgent?;
1578
+ private readonly metricsPort?;
1579
+ constructor(delegatingConfig: AgentConfig, delegatingTools: ToolPort, llmFactory?: LLMFactory | undefined, configResolver?: (() => Partial<AgentConfig>) | undefined, createMemoryForAgent?: ((agentKey: string) => MemoryPort<Message>) | undefined, metricsPort?: MetricsPort | undefined);
1518
1580
  run(config: Parameters<AgentManager['executeTask']>[0], context?: ToolExecutionContext): Promise<SpecialistAgentResult>;
1519
1581
  }
1520
1582
 
1521
1583
  declare class DefaultDelegationService implements DelegationService {
1522
1584
  private readonly catalog;
1523
- private readonly policy;
1524
1585
  private readonly factory;
1525
1586
  private readonly runner;
1526
- private readonly formatter;
1527
1587
  private enabledAgents;
1528
- constructor(catalog: AgentCatalog, policy: DelegationPolicy, factory: SpecialistAgentFactory, runner: AgentCommandRunner, formatter: DelegationResultFormatter);
1588
+ private backgroundAgents;
1589
+ constructor(catalog: AgentCatalog, factory: SpecialistAgentFactory, runner: AgentCommandRunner);
1529
1590
  setEnabledAgents(enabledAgents: Record<string, boolean>): void;
1530
1591
  listEnabledAgents(): AgentTemplate[];
1531
1592
  delegate(params: AssignParams, context?: ToolExecutionContext): Promise<DelegationResult>;
1532
- }
1533
-
1534
- declare class DefaultDelegationResultFormatter implements DelegationResultFormatter {
1535
- formatSuccess(agentId: string, result: SpecialistAgentResult): {
1536
- summary: string;
1537
- metadata: {
1538
- agentId: string;
1539
- agentName: string;
1540
- status: "success" | "error" | "timeout";
1541
- executionTimeMs: number;
1542
- toolCallsExecuted: number;
1543
- tokensUsed: number | undefined;
1544
- metrics: MetricsSnapshot | undefined;
1545
- };
1546
- };
1547
- formatError(error: unknown): string;
1593
+ delegateBackground(params: AssignParams, context?: ToolExecutionContext): Promise<BackgroundDelegationResult>;
1594
+ getBackgroundResult(sessionId: string, blocking?: boolean): Promise<DelegationResult | null>;
1595
+ isBackgroundAgentRunning(sessionId: string): boolean;
1548
1596
  }
1549
1597
 
1550
1598
  interface DelegationServiceConfig {
@@ -1555,6 +1603,7 @@ interface DelegationServiceConfig {
1555
1603
  name: string;
1556
1604
  description: string;
1557
1605
  }>;
1606
+ createMemoryForAgent?: (agentKey: string) => MemoryPort<Message>;
1558
1607
  }
1559
1608
  declare class DelegationServiceFactory {
1560
1609
  create(config: DelegationServiceConfig): DelegationService;
@@ -1573,6 +1622,10 @@ declare class ToolRegistry implements ToolPort, AgentAwareToolPort, Orchestrator
1573
1622
  private delegationServiceFactory?;
1574
1623
  private assignTool?;
1575
1624
  private enabledAgentsConfig;
1625
+ private orchestratorConfig?;
1626
+ private orchestratorTools?;
1627
+ private orchestratorLLMFactory?;
1628
+ private orchestratorConfigResolver?;
1576
1629
  constructor(opts?: {
1577
1630
  todoMemory?: MemoryPort<TodoItem>;
1578
1631
  toolsMemory?: MemoryPort<string>;
@@ -1585,7 +1638,12 @@ declare class ToolRegistry implements ToolPort, AgentAwareToolPort, Orchestrator
1585
1638
  /**
1586
1639
  * Initialize AssignTool with orchestrator dependencies (lazy initialization)
1587
1640
  */
1588
- setOrchestrator(config: AgentConfig, tools: ToolPort, llmFactory?: LLMFactory, configResolver?: () => Partial<AgentConfig>): void;
1641
+ setOrchestrator(config: AgentConfig, tools: ToolPort, llmFactory?: LLMFactory, configResolver?: () => Partial<AgentConfig>, createMemoryForAgent?: (agentKey: string) => MemoryPort<Message>): void;
1642
+ /**
1643
+ * Update memory factory for sub-agent sessions.
1644
+ * Called when session is lazily initialized and memory needs to switch from in-memory to persisted.
1645
+ */
1646
+ setSharedMemory(createMemoryForAgent: (agentKey: string) => MemoryPort<Message>): void;
1589
1647
  /**
1590
1648
  * Get the agent registry
1591
1649
  */
@@ -2085,6 +2143,25 @@ type AssignErrorResult = ExecResultError & {
2085
2143
  };
2086
2144
  type AssignResult = AssignSuccessResult$1 | AssignErrorResult;
2087
2145
 
2146
+ interface TaskOutputParams {
2147
+ session_id: string;
2148
+ blocking?: boolean;
2149
+ timeout_ms?: number;
2150
+ }
2151
+ interface TaskOutputMetadata {
2152
+ sessionId: string;
2153
+ state: 'running' | 'completed' | 'failed' | 'not_found';
2154
+ metrics?: {
2155
+ tokensUsed?: number;
2156
+ toolCallsExecuted?: number;
2157
+ executionTimeMs?: number;
2158
+ };
2159
+ }
2160
+ type TaskOutputSuccessResult = ExecResultSuccess & {
2161
+ metadata: TaskOutputMetadata;
2162
+ };
2163
+ type TaskOutputResult = TaskOutputSuccessResult | ExecResultError;
2164
+
2088
2165
  declare function isSuccess(result: ExecResult): result is ExecResultSuccess;
2089
2166
  declare function isError(result: ExecResult): result is ExecResultError;
2090
2167
  declare function isTextResult(result: ExecResult): result is Extract<ExecResult, {
@@ -2320,6 +2397,7 @@ declare abstract class BaseLLM implements LLMPort {
2320
2397
  onReasoningChunk?: (delta: string) => void;
2321
2398
  onToolCallDelta?: (tc: ToolCall) => void;
2322
2399
  onStreamFinish?: (finishReason?: string, usage?: UsageData) => void;
2400
+ onUsage?: (usage: UsageData) => void;
2323
2401
  }, signal?: AbortSignal): Promise<CompletionResult>;
2324
2402
  }
2325
2403
 
@@ -2360,6 +2438,7 @@ declare class GithubLLM extends BaseLLM implements LLMPort {
2360
2438
  onChunk?: (delta: string, usage?: UsageData) => void;
2361
2439
  onToolCallDelta?: (tc: ToolCall) => void;
2362
2440
  onStreamFinish?: (finishReason?: string, usage?: UsageData) => void;
2441
+ onUsage?: (usage: UsageData) => void;
2363
2442
  }, signal?: AbortSignal): Promise<CompletionResult>;
2364
2443
  }
2365
2444
 
@@ -2401,6 +2480,7 @@ declare class AnthropicAISDKLLM {
2401
2480
  onChunk?: (delta: string, usage?: UsageData) => void;
2402
2481
  onToolCallDelta?: (tc: ToolCall) => void;
2403
2482
  onStreamFinish?: (finishReason?: string, usage?: UsageData) => void;
2483
+ onUsage?: (usage: UsageData) => void;
2404
2484
  }, signal?: AbortSignal): Promise<CompletionResult>;
2405
2485
  getModels(signal?: AbortSignal): Promise<ModelInfo[]>;
2406
2486
  }
@@ -2533,4 +2613,4 @@ declare function resolveBackspaces(s: string): string;
2533
2613
  declare function stripAnsiAndControls(s: string): string;
2534
2614
  declare function canonicalizeTerminalPaste(raw: string): string;
2535
2615
 
2536
- export { AGENT_CREATOR_SYSTEM_PROMPT, AbortError, type AgentAwareToolPort, type AgentCatalog, type AgentConfig, type AgentEvent, AgentEventTypes, AgentFilePersistence, AgentManager, AgentManagerCommandRunner, AgentOrchestrator, AgentRegistry, type AgentTemplate, AnthropicAISDKLLM, type AssignErrorResult, type AssignParams, type AssignResult, type AssignSuccessResult$1 as AssignSuccessResult, type AssignTaskArgs, type AssignTaskMetadata, type BaseLLMOptions, type BashErrorResult, type BashParams, type BashResult, type BashSuccessResult$1 as BashSuccessResult, BashTool, type BashToolArgs, type BashToolMetadata, CommandFilePersistence, type CommandMetadata, type CommandSource, type CompleteAgent, type CompleteCustomCommand, CompositeToolPort, type Conversation, ConversationContext, type ConversationMetadata, type ConversationSnapshot, ConversationStore, CoreMCPClient, type CustomCommandFrontmatter, type CustomCommandTemplate, DEFAULT_RETRY_CONFIG, DefaultDelegationPolicy, DefaultDelegationResultFormatter, DefaultDelegationService, DefaultSpecialistAgentFactory, type DelegationMetadata, type DelegationService, type DelegationServiceConfig, DelegationServiceFactory, type DirEntry, type ErrorMetadata, ErrorReason, type ExecResult, type ExecResultError, type ExecResultSuccess, type FileEditArgs, type FileEditMetadata, type FileEditResult, type FileEditSuccessResult$1 as FileEditSuccessResult, type FileMetadata, type FileNewArgs, type FileNewMetadata, type FileNewParams, type FileNewResult, type FileNewSuccessResult$1 as FileNewSuccessResult, type FileReadArgs, type FileReadErrorResult, type FileReadMetadata, type FileReadParams, type FileReadResult, type FileReadSuccessResult$1 as FileReadSuccessResult, type FolderTreeOptions, type FunctionTool, GithubLLM, type GlobArgs, type GlobParams, type GlobResult, type GlobSuccessResult$1 as GlobSuccessResult, type GlobToolMetadata, type GrepArgs, type GrepParams, type GrepResult, type GrepSuccessResult$1 as GrepSuccessResult, type GrepToolMetadata, InMemoryMemory, InMemoryMetadata, InMemoryMetricsPort, JsonFileMemoryPersistence, type LLMConfig, LLMError, type LLMFactory, type LLMOptions, type LLMPort, LLMResolver, type LineRangeMetadata, type LsArgs, type LsMetadata, type LsParams, type LsResult, type LsSuccessResult$1 as LsSuccessResult, type MCPConfig, type MCPServerConfig, MCPToolPort, type MemoryPort, MemoryPortMetadataAdapter, type Message, type MessageContent, type MessageContentPart, type MetadataPort, type MetricsChangeHandler, type MetricsPort, type MetricsSnapshot, type ModelInfo, type ModelLimits, NoopMetricsPort, NoopReminders, type OrchestratorAwareToolPort, type ParseResult, PersistedMemory, PersistingConsoleEventPort, type RetryConfig, RetryTransport, RuntimeEnv, type SendMessageOptions, SimpleContextBuilder, SimpleCost, SimpleId, type SpecialistAgentConfig, type SpecialistAgentResult, type SubAgentState, type SubAgentToolCall, SystemClock, type TodoWriteArgs, type TodoWriteMetadata, type TodoWriteResult, type TodoWriteSuccessResult$1 as TodoWriteSuccessResult, type ToolApprovalDecision, type ToolArguments, type ToolCall, type ToolCallConversionResult, type ToolCallValidation, type ToolErrorMetadata, type ToolExecutionContext, type ToolExecutionResult, type ToolMetadataMap, type ToolName, type ToolParameterMap, type ToolPort, ToolRegistry, type ToolValidator, type TypedToolInvocation, type UsageData, type UserAttachment, type UserMessagePayload, type ValidationError, type ValidationResult, type WebFetchArgs, type WebFetchMetadata, type WebFetchParams, type WebFetchResult, type WebFetchSuccessResult$1 as WebFetchSuccessResult, type WebSearchArgs, type WebSearchMetadata, type WebSearchParams, type WebSearchResult, type WebSearchSuccessResult$1 as WebSearchSuccessResult, type WebSearchToolResult, assignTaskSchema, bashToolSchema, buildAgentCreationPrompt, buildInjectedSystem, canonicalizeTerminalPaste, convertToolCall, convertToolCalls, convertToolCallsWithErrorHandling, createEmptySnapshot, createLLM, deduplicateModels, err, fileEditSchema, fileNewSchema, fileReadSchema, generateFolderTree, getAvailableProviders, getFallbackLimits, getProviderAuthMethods, getProviderDefaultModels, getProviderLabel, globToolSchema, grepToolSchema, isAssignResult, isAssignSuccess, isAssignTaskArgs, isBashResult, isBashSuccess, isBashToolArgs, isError, isFileEditArgs, isFileEditResult, isFileEditSuccess, isFileNewArgs, isFileNewResult, isFileNewSuccess, isFileReadArgs, isFileReadResult, isFileReadSuccess, isGlobArgs, isGlobResult, isGlobSuccess, isGrepArgs, isGrepResult, isGrepSuccess, isJsonResult, isLsArgs, isLsToolResult, isLsToolSuccess, isRetryableError, isRetryableStatusCode, isSuccess, isSuccessJson, isSuccessText, isTextResult, isTodoWriteArgs, isTodoWriteResult, isTodoWriteSuccess, isValidCommandId, isWebFetchArgs, isWebFetchResult, isWebFetchSuccess, isWebSearchArgs, isWebSearchResult, isWebSearchSuccess, lsToolSchema, normalizeModelInfo, normalizeModelLimits, normalizeNewlines, okJson, okText, parseJSON, parseSubAgentToolCallArguments, parseToolArguments, renderTemplate, resolveBackspaces, resolveCarriageReturns, sanitizeCommandId, stripAnsiAndControls, supportsGetModels, todoWriteSchema, toolSchemas, toolValidators, validateToolParams, webFetchSchema, webSearchSchema };
2616
+ export { AGENT_CREATOR_SYSTEM_PROMPT, AbortError, type AgentAwareToolPort, type AgentCatalog, type AgentConfig, type AgentEvent, AgentEventTypes, AgentFilePersistence, AgentManager, AgentManagerCommandRunner, AgentOrchestrator, AgentRegistry, type AgentSession, type AgentStateManager, type AgentTemplate, AnthropicAISDKLLM, type AssignErrorResult, type AssignParams, type AssignResult, type AssignSuccessResult$1 as AssignSuccessResult, type AssignTaskArgs, type AssignTaskMetadata, type BaseLLMOptions, type BashErrorResult, type BashParams, type BashResult, type BashSuccessResult$1 as BashSuccessResult, BashTool, type BashToolArgs, type BashToolMetadata, CommandFilePersistence, type CommandMetadata, type CommandSource, type CompleteAgent, type CompleteCustomCommand, CompositeToolPort, type Conversation, ConversationContext, type ConversationMetadata, type ConversationSnapshot, ConversationStore, CoreMCPClient, type CustomCommandFrontmatter, type CustomCommandTemplate, DEFAULT_RETRY_CONFIG, DefaultAgentStateManager, DefaultDelegationService, DefaultSpecialistAgentFactory, type DelegationMetadata, type DelegationService, type DelegationServiceConfig, DelegationServiceFactory, type DirEntry, type ErrorMetadata, ErrorReason, type ExecResult, type ExecResultError, type ExecResultSuccess, type FileEditArgs, type FileEditMetadata, type FileEditResult, type FileEditSuccessResult$1 as FileEditSuccessResult, type FileMetadata, type FileNewArgs, type FileNewMetadata, type FileNewParams, type FileNewResult, type FileNewSuccessResult$1 as FileNewSuccessResult, type FileReadArgs, type FileReadErrorResult, type FileReadMetadata, type FileReadParams, type FileReadResult, type FileReadSuccessResult$1 as FileReadSuccessResult, type FolderTreeOptions, type FunctionTool, GithubLLM, type GlobArgs, type GlobParams, type GlobResult, type GlobSuccessResult$1 as GlobSuccessResult, type GlobToolMetadata, type GrepArgs, type GrepParams, type GrepResult, type GrepSuccessResult$1 as GrepSuccessResult, type GrepToolMetadata, InMemoryMemory, InMemoryMetadata, InMemoryMetricsPort, JsonFileMemoryPersistence, type LLMConfig, LLMError, type LLMFactory, type LLMOptions, type LLMPort, LLMResolver, type LineRangeMetadata, type LsArgs, type LsMetadata, type LsParams, type LsResult, type LsSuccessResult$1 as LsSuccessResult, type MCPConfig, type MCPServerConfig, MCPToolPort, type MemoryPort, MemoryPortMetadataAdapter, type Message, type MessageContent, type MessageContentPart, type MetadataPort, type MetricsChangeHandler, type MetricsPort, type MetricsSnapshot, type ModelInfo, type ModelLimits, MultiFileMemoryPersistence, NoopMetricsPort, NoopReminders, type OrchestratorAwareToolPort, type ParseResult, PersistedMemory, PersistingConsoleEventPort, type RetryConfig, RetryTransport, RuntimeEnv, type SendMessageOptions, SimpleContextBuilder, SimpleCost, SimpleId, type SpecialistAgentConfig, type SpecialistAgentResult, type SubAgentState, type SubAgentToolCall, SystemClock, type TaskOutputMetadata, type TaskOutputParams, type TaskOutputResult, type TaskOutputSuccessResult, type TodoWriteArgs, type TodoWriteMetadata, type TodoWriteResult, type TodoWriteSuccessResult$1 as TodoWriteSuccessResult, type ToolApprovalDecision, type ToolArguments, type ToolCall, type ToolCallConversionResult, type ToolCallValidation, type ToolErrorMetadata, type ToolExecutionContext, type ToolExecutionResult, type ToolMetadataMap, type ToolName, type ToolParameterMap, type ToolPort, ToolRegistry, type ToolValidator, type TypedToolInvocation, type UsageData, type UserAttachment, type UserMessagePayload, type ValidationError, type ValidationResult, type WebFetchArgs, type WebFetchMetadata, type WebFetchParams, type WebFetchResult, type WebFetchSuccessResult$1 as WebFetchSuccessResult, type WebSearchArgs, type WebSearchMetadata, type WebSearchParams, type WebSearchResult, type WebSearchSuccessResult$1 as WebSearchSuccessResult, type WebSearchToolResult, assignTaskSchema, bashToolSchema, buildAgentCreationPrompt, buildInjectedSystem, canonicalizeTerminalPaste, convertToolCall, convertToolCalls, convertToolCallsWithErrorHandling, createEmptySnapshot, createLLM, deduplicateModels, err, fileEditSchema, fileNewSchema, fileReadSchema, generateFolderTree, getAvailableProviders, getFallbackLimits, getProviderAuthMethods, getProviderDefaultModels, getProviderLabel, globToolSchema, grepToolSchema, isAssignResult, isAssignSuccess, isAssignTaskArgs, isBashResult, isBashSuccess, isBashToolArgs, isError, isFileEditArgs, isFileEditResult, isFileEditSuccess, isFileNewArgs, isFileNewResult, isFileNewSuccess, isFileReadArgs, isFileReadResult, isFileReadSuccess, isGlobArgs, isGlobResult, isGlobSuccess, isGrepArgs, isGrepResult, isGrepSuccess, isJsonResult, isLsArgs, isLsToolResult, isLsToolSuccess, isRetryableError, isRetryableStatusCode, isSuccess, isSuccessJson, isSuccessText, isTextResult, isTodoWriteArgs, isTodoWriteResult, isTodoWriteSuccess, isValidCommandId, isWebFetchArgs, isWebFetchResult, isWebFetchSuccess, isWebSearchArgs, isWebSearchResult, isWebSearchSuccess, lsToolSchema, normalizeModelInfo, normalizeModelLimits, normalizeNewlines, okJson, okText, parseJSON, parseSubAgentToolCallArguments, parseToolArguments, renderTemplate, resolveBackspaces, resolveCarriageReturns, sanitizeCommandId, stripAnsiAndControls, supportsGetModels, todoWriteSchema, toolSchemas, toolValidators, validateToolParams, webFetchSchema, webSearchSchema };