@cuylabs/agent-core 0.8.0 → 0.10.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 (127) hide show
  1. package/README.md +33 -17
  2. package/dist/chunk-2O4MCSQS.js +780 -0
  3. package/dist/chunk-2TTOLHBT.js +198 -0
  4. package/dist/chunk-5FMSGQVX.js +281 -0
  5. package/dist/chunk-5NVVNXPQ.js +288 -0
  6. package/dist/{chunk-CAA7FHIH.js → chunk-6HZBHFOL.js} +3 -103
  7. package/dist/chunk-CJI7PVS2.js +58 -0
  8. package/dist/{chunk-N6HWIEEA.js → chunk-CMYN2RCB.js} +278 -61
  9. package/dist/chunk-FII65CN7.js +117 -0
  10. package/dist/{chunk-IVUJDISU.js → chunk-GFTW23FV.js} +5 -14
  11. package/dist/chunk-I6PKJ7XQ.js +292 -0
  12. package/dist/{chunk-BDBZ3SLK.js → chunk-ICZ66572.js} +48 -4
  13. package/dist/chunk-KYLPMBHD.js +316 -0
  14. package/dist/chunk-MXAP4UG6.js +2956 -0
  15. package/dist/{chunk-RZITT45F.js → chunk-N3VX7FEE.js} +39 -6
  16. package/dist/{chunk-YSLSEQ6B.js → chunk-NDZWXCBZ.js} +218 -95
  17. package/dist/{chunk-P6YF7USR.js → chunk-Q742PSH3.js} +23 -38
  18. package/dist/chunk-QAL3OMI3.js +943 -0
  19. package/dist/{chunk-RFEKJKTO.js → chunk-RN6WZEUF.js} +330 -280
  20. package/dist/{chunk-ZXAKHMWH.js → chunk-ROTGCYDW.js} +22 -84
  21. package/dist/chunk-SPBFQXOT.js +0 -0
  22. package/dist/{chunk-LRHOS4ZN.js → chunk-SPILYYDF.js} +3 -2
  23. package/dist/chunk-SSFBF3US.js +602 -0
  24. package/dist/chunk-SZ2XBPTW.js +8 -0
  25. package/dist/chunk-T4UIX5D7.js +115 -0
  26. package/dist/chunk-TIHPYVAJ.js +102 -0
  27. package/dist/{chunk-YUUJK53A.js → chunk-TOTDGK3P.js} +1 -1
  28. package/dist/chunk-V4RFNEET.js +563 -0
  29. package/dist/chunk-VOUEJSW6.js +0 -0
  30. package/dist/{chunk-4BDA7DQY.js → chunk-WBPOZ7CL.js} +673 -273
  31. package/dist/chunk-X4VN4GIJ.js +185 -0
  32. package/dist/dispatch/index.d.ts +93 -0
  33. package/dist/dispatch/index.js +37 -0
  34. package/dist/events/index.d.ts +93 -0
  35. package/dist/events/index.js +6 -0
  36. package/dist/{runtime → execution}/index.d.ts +120 -34
  37. package/dist/{runtime → execution}/index.js +18 -13
  38. package/dist/index-BCqEGzBj.d.ts +251 -0
  39. package/dist/index.d.ts +490 -122
  40. package/dist/index.js +2104 -615
  41. package/dist/{errors → inference/errors}/index.d.ts +2 -2
  42. package/dist/{errors → inference/errors}/index.js +1 -1
  43. package/dist/inference/index.d.ts +16 -23
  44. package/dist/inference/index.js +45 -16
  45. package/dist/instance-BqV2D5pc.d.ts +5723 -0
  46. package/dist/logger/index.d.ts +50 -0
  47. package/dist/logger/index.js +11 -0
  48. package/dist/mcp/index.d.ts +5 -9
  49. package/dist/mcp/index.js +2 -3
  50. package/dist/middleware/index.d.ts +10 -149
  51. package/dist/middleware/index.js +11 -3
  52. package/dist/model-messages-B4nK9D1-.d.ts +13 -0
  53. package/dist/models/index.d.ts +23 -18
  54. package/dist/models/index.js +48 -11
  55. package/dist/models/reasoning/index.d.ts +4 -0
  56. package/dist/{reasoning → models/reasoning}/index.js +3 -3
  57. package/dist/plugin/index.d.ts +458 -0
  58. package/dist/plugin/index.js +32 -0
  59. package/dist/profiles/index.d.ts +55 -0
  60. package/dist/profiles/index.js +30 -0
  61. package/dist/prompt/index.d.ts +8 -12
  62. package/dist/prompt/index.js +3 -2
  63. package/dist/safety/index.d.ts +109 -14
  64. package/dist/safety/index.js +59 -3
  65. package/dist/sandbox/index.d.ts +81 -0
  66. package/dist/sandbox/index.js +1 -0
  67. package/dist/skill/index.d.ts +10 -8
  68. package/dist/skill/index.js +3 -3
  69. package/dist/storage/index.d.ts +12 -4
  70. package/dist/storage/index.js +1 -1
  71. package/dist/subagents/index.d.ts +177 -0
  72. package/dist/subagents/index.js +78 -0
  73. package/dist/team/index.d.ts +544 -0
  74. package/dist/team/index.js +41 -0
  75. package/dist/tool/host/index.d.ts +41 -0
  76. package/dist/tool/host/index.js +10 -0
  77. package/dist/tool/index.d.ts +125 -21
  78. package/dist/tool/index.js +20 -13
  79. package/dist/{types-VQgymC1N.d.ts → types-Bj_J8u_W.d.ts} +44 -64
  80. package/dist/{types-CHiPh8U2.d.ts → types-C_LCeYNg.d.ts} +7 -7
  81. package/dist/types-RSCv7nQ4.d.ts +59 -0
  82. package/package.json +58 -53
  83. package/dist/builder-UpOWQMW3.d.ts +0 -34
  84. package/dist/chunk-7MUFEN4K.js +0 -559
  85. package/dist/chunk-7VKQ4WPB.js +0 -73
  86. package/dist/chunk-BFM2YHNM.js +0 -222
  87. package/dist/chunk-DWYX7ASF.js +0 -26
  88. package/dist/chunk-KUVSERLJ.js +0 -50
  89. package/dist/chunk-N7P4PN3O.js +0 -84
  90. package/dist/chunk-SDSBEQXG.js +0 -157
  91. package/dist/chunk-SQU2AJHO.js +0 -305
  92. package/dist/chunk-VBWWUHWI.js +0 -724
  93. package/dist/chunk-VEKUXUVF.js +0 -41
  94. package/dist/chunk-VNQBHPCT.js +0 -398
  95. package/dist/chunk-WWYYNWEW.js +0 -259
  96. package/dist/context/index.d.ts +0 -259
  97. package/dist/context/index.js +0 -26
  98. package/dist/events-CE72w8W4.d.ts +0 -149
  99. package/dist/host/index.d.ts +0 -45
  100. package/dist/host/index.js +0 -8
  101. package/dist/index-CWSchSql.d.ts +0 -1058
  102. package/dist/messages-BYWGn8TY.d.ts +0 -110
  103. package/dist/presets/index.d.ts +0 -53
  104. package/dist/presets/index.js +0 -28
  105. package/dist/reasoning/index.d.ts +0 -116
  106. package/dist/registry-DwYqsQkX.d.ts +0 -164
  107. package/dist/runner-e2YRcUoX.d.ts +0 -786
  108. package/dist/scope/index.d.ts +0 -10
  109. package/dist/scope/index.js +0 -14
  110. package/dist/session-manager-B_CWGTsl.d.ts +0 -274
  111. package/dist/signal/index.d.ts +0 -28
  112. package/dist/signal/index.js +0 -6
  113. package/dist/sub-agent/index.d.ts +0 -23
  114. package/dist/sub-agent/index.js +0 -15
  115. package/dist/tool-BHbyUAy3.d.ts +0 -150
  116. package/dist/tool-DLXAR9Ce.d.ts +0 -145
  117. package/dist/tracker-DClqYqTj.d.ts +0 -96
  118. package/dist/tracking/index.d.ts +0 -111
  119. package/dist/tracking/index.js +0 -20
  120. package/dist/types-BfNpU8NS.d.ts +0 -270
  121. package/dist/types-BnpEOYV-.d.ts +0 -50
  122. package/dist/types-CQL-SvTn.d.ts +0 -29
  123. package/dist/types-CWm-7rvB.d.ts +0 -55
  124. package/dist/types-KKDrdU9Y.d.ts +0 -325
  125. package/dist/types-QA4WhEfz.d.ts +0 -138
  126. package/dist/types-QKHHQLLq.d.ts +0 -336
  127. package/dist/types-YuWV4ag7.d.ts +0 -72
package/dist/index.d.ts CHANGED
@@ -1,81 +1,280 @@
1
- import { A as AgentConfig, a as Agent } from './index-CWSchSql.js';
2
- export { b as AgentProfile, C as CompactionConfig, D as DEFAULT_MAX_CONCURRENT, c as DEFAULT_MAX_SPAWN_DEPTH, d as DEFAULT_SESSION_TITLE_PREFIX, P as PRUNE_PROTECTED_TOOLS, S as SubAgentCompletedResult, e as SubAgentHandle, f as SubAgentStatus, g as SubAgentToolConfig, h as SubAgentTracker, i as SubAgentUsage, T as TracingConfig, j as createAgent, k as createSubAgentTools } from './index-CWSchSql.js';
3
- import { LanguageModel, Tool as Tool$1, TelemetrySettings, ModelMessage } from 'ai';
4
- import { M as Message, T as TokenUsage } from './messages-BYWGn8TY.js';
5
- export { A as AssistantMessage, a as MessageBase, b as MessageError, c as MessageRole, S as Session, d as SystemMessage, e as ToolMessage, U as UserMessage } from './messages-BYWGn8TY.js';
6
- import { T as Tool } from './tool-BHbyUAy3.js';
7
- export { C as CompatibleSchema, I as InferSchemaOutput, d as defineTool } from './tool-BHbyUAy3.js';
8
- import { T as ToolHost } from './types-CHiPh8U2.js';
9
- export { D as DirEntry, E as ExecOptions, a as ExecResult, F as FileStat } from './types-CHiPh8U2.js';
10
- import { M as MiddlewareRunner, d as StreamProvider, E as EnhancedTools } from './runner-e2YRcUoX.js';
11
- export { A as AgentMiddleware, f as AgentModelHooks, B as BlockedModelCall, g as EnvironmentInfo, I as InstructionFile, h as ModelCallContext, e as ModelCallInput, i as ModelCallOutput, c as ModelFamily, j as PluginCommand, k as PluginContext, l as PluginInit, a as PromptBuildContext, P as PromptConfig, b as PromptSection, S as StreamChunk, m as StreamProviderConfig, n as StreamProviderFactory, o as StreamProviderInput, p as StreamProviderResult, T as ToolCallDecision } from './runner-e2YRcUoX.js';
12
- import { g as InterventionController } from './types-KKDrdU9Y.js';
13
- export { A as AnyInferenceResult, a as AnyStreamResult, C as CustomStreamProvider, b as CustomStreamResult, D as DEFAULT_MAX_OUTPUT_TOKENS, h as DEFAULT_RETRY_CONFIG, c as InferenceCustomResult, d as InferenceStepInfo, I as InferenceStreamInput, e as InferenceStreamResult, L as LLMStreamInput, f as LLMStreamResult, O as OUTPUT_TOKEN_MAX, i as OnInterventionApplied, P as PendingIntervention, R as RetryConfig, j as RetryHandlerOptions, k as RetryState, S as StepInfo, T as ToolExecutionMode, l as calculateDelay, m as createRetryHandler, n as createRetryState, s as shouldRetry, o as sleep, w as withRetry } from './types-KKDrdU9Y.js';
1
+ import { H as HumanInputController, p as HumanInputConfig, T as Tool, M as Message, S as SessionManager, E as EffectiveAgentConfig, q as TurnChangeTracker, r as InterventionController, b as MiddlewareRunner, P as PromptBuilder, c as ToolExecutionMode, A as AgentEvent, t as StreamProvider, u as Scope, v as ScopeSnapshot, x as ScopeOptions, F as FileOperationMeta, y as AgentSignal, z as TypedHandler, U as Unsubscribe, W as WildcardHandler } from './instance-BqV2D5pc.js';
2
+ export { B as Agent, C as AgentConfig, G as AgentDefaults, J as AgentDefaultsContext, K as AgentDefaultsProvider, L as AgentMiddleware, N as AgentModelHooks, O as AgentStatus, Q as AgentTurnActiveToolCall, V as AgentTurnBoundaryKind, X as AgentTurnBoundaryMetadata, Y as AgentTurnBoundarySnapshot, Z as AgentTurnCommitApplier, _ as AgentTurnCommitBatch, $ as AgentTurnCommitOptions, a0 as AgentTurnEngine, a1 as AgentTurnEngineOptions, a2 as AgentTurnPhase, a3 as AgentTurnResolvedToolCall, a4 as AgentTurnState, a5 as AgentTurnStateAdvanceOptions, a6 as AgentTurnStepCommitSnapshot, a7 as AgentTurnStepCommitToolCall, a8 as AgentTurnStepCommitToolResult, a9 as AgentTurnStepRuntimeConfig, e as AnyInferenceResult, aa as AppliedProfile, ab as ApprovalAction, ac as ApprovalAgentMiddleware, ad as ApprovalCascadeMode, ae as ApprovalCascadePolicy, af as ApprovalConfig, ag as ApprovalCorrection, ah as ApprovalDecision, ai as ApprovalEvaluation, aj as ApprovalEvent, ak as ApprovalHandler, al as ApprovalMiddlewareConfig, am as ApprovalRememberScope, an as ApprovalRequest, ao as ApprovalResolution, ap as ApprovalRule, aq as ApprovalRuleContext, ar as AssistantMessage, as as BlockedModelCall, at as BranchEntry, au as ChatLifecycleContext, av as CommitOutputOptions, aw as CommitStepOptions, ax as CompactionConfig, ay as CompactionEntry, az as CompatibleSchema, aA as ConfigChangeEntry, aB as CoordinatorNotification, aC as CoordinatorNotificationKind, aD as CoordinatorRoundEvent, aE as CreateAgentTurnStateOptions, aF as CreateAgentTurnStepCommitBatchOptions, aG as CreateSessionOptions, aH as DEFAULT_AGENT_NAME, aI as DEFAULT_DISPATCH_TOOL_IDS, aJ as DEFAULT_LOCAL_DISPATCH_CONCURRENCY, aK as DEFAULT_LOCAL_DISPATCH_DEPTH, aL as DEFAULT_LOCAL_DISPATCH_TITLE_PREFIX, D as DEFAULT_MAX_OUTPUT_TOKENS, aM as DEFAULT_MAX_STEPS, D as DEFAULT_MAX_TOKENS, f as DEFAULT_RETRY_CONFIG, aN as DEFAULT_SYSTEM_PROMPT, aO as DISPATCH_STATES, aP as DispatchCheckOptions, aQ as DispatchListOptions, aR as DispatchRecord, aS as DispatchResult, aT as DispatchRole, aU as DispatchRuntime, aV as DispatchStartInput, aW as DispatchState, aX as DispatchTarget, aY as DispatchTargetInspection, aZ as DispatchTargetStartInput, a_ as DispatchTargetStartResult, a$ as DispatchTargetSummary, b0 as DispatchUsage, b1 as DoomLoopAction, b2 as DoomLoopHandler, b3 as DoomLoopRequest, b4 as EnhancedTools, b5 as EntryBase, b6 as EnvironmentInfo, b7 as ExternalTaskControl, b8 as FileEntry, b9 as GuidancePayload, ba as HumanInputEventContext, bb as HumanInputOption, bc as HumanInputRequest, bd as HumanInputRequestKind, be as HumanInputRequestListOptions, bf as HumanInputRequestRecord, bg as HumanInputRequestStatus, bh as HumanInputResponse, bi as HumanInputTimeoutError, bj as HumanInputToolArgs, bk as HumanInputUnavailableError, bl as IdleNotificationPayload, bm as InMemoryMailboxStore, bn as InMemoryTaskBoardStore, bo as InferSchemaOutput, g as InferenceCustomResult, h as InferenceStepInfo, I as InferenceStreamInput, i as InferenceStreamResult, bp as InputCheckResult, bq as InstructionFile, br as LocalDispatchRuntimeOptions, bs as Mailbox, bt as MailboxStore, bu as MailboxSubscriber, bv as MemberRegisteredEvent, bw as MemberRuntime, bx as MemberStats, by as MemberStatus, bz as MemberStatusChangedEvent, bA as MessageBase, bB as MessageEntry, bC as MessageError, bD as MessageInput, bE as MessageKind, bF as MessageListFilter, bG as MessagePayload, bH as MessageRole, bI as MessageSentEvent, bJ as MetadataEntry, d as ModelCallContext, bK as ModelCallInput, bL as ModelCallOutput, bM as ModelFamily, bN as NormalizedToolReplayPolicy, bO as NotificationPriority, bP as OnFollowUpQueued, bQ as OnInterventionApplied, bR as OtelMiddlewareConfig, bS as PRUNE_PROTECTED_TOOLS, bT as PendingIntervention, bU as PermissionForwardedEvent, bV as PermissionHandler, bW as PermissionRequestPayload, bX as PermissionResolvedEvent, bY as PermissionResponsePayload, bZ as PlanCreatedEvent, b_ as PlannedTask, b$ as PrepareModelStepOptions, c0 as PreparedAgentModelStep, c1 as PreparedExternalTask, c2 as Profile, c3 as PromptBuildContext, c4 as PromptConfig, c5 as PromptSection, c6 as QueueTaskInput, c7 as RemoteSkillEntry, c8 as RemoteSkillIndex, R as RetryConfig, j as RetryHandlerOptions, k as RetryState, c9 as RiskLevel, ca as RuleSource, cb as RunModelStepOptions, cc as RunToolBatchOptions, cd as RunToolBatchResult, ce as STORAGE_VERSION, cf as SerializedMessage, cg as Session, ch as SessionContext, ci as SessionEntry, cj as SessionHeader, ck as SessionInfo, cl as SessionStorage, cm as ShutdownRequestPayload, cn as ShutdownRequestedEvent, co as ShutdownResolvedEvent, cp as ShutdownResponsePayload, cq as SkillConfig, cr as SkillContent, cs as SkillDiscoveryError, ct as SkillDiscoveryResult, cu as SkillMetadata, cv as SkillRegistry, cw as SkillResource, cx as SkillResourceType, cy as SkillScope, cz as SkillSource, cA as SkillSourceType, cB as StepProcessingOptions, cC as StepProcessingOutput, cD as StepProcessingResult, cE as StreamChunk, cF as StreamInput, cG as StreamProviderConfig, cH as StreamProviderFactory, cI as StreamProviderInput, cJ as StreamProviderResult, cK as SynthesisCompleteEvent, cL as SynthesisResult, cM as SystemMessage, cN as TERMINAL_STATUSES, cO as TaskAbortedEvent, cP as TaskBoard, cQ as TaskBoardStore, cR as TaskCompletedEvent, cS as TaskCompletion, cT as TaskConflictError, cU as TaskCreateInput, cV as TaskCreatedEvent, cW as TaskDispatchMode, cX as TaskExecutor, cY as TaskExecutorInput, cZ as TaskFailedEvent, c_ as TaskListFilter, c$ as TaskResult, d0 as TaskStatus, d1 as TaskTransition, d2 as TaskTransitionEvent, d3 as TaskTransitionReason, d4 as TeamCoordinatorConfig, d5 as TeamEvent, d6 as TeamMember, d7 as TeamMessage, d8 as TeamNotificationEvent, d9 as TeamPlan, da as TeamSnapshot, db as TeamStartedEvent, dc as TeamStoppedEvent, dd as TeamTask, de as TelemetryConfig, df as TelemetryConfigResult, dg as TokenUsage, dh as ToolCallDecision, di as ToolCallOutput, dj as ToolCapabilities, dk as ToolContext, dl as ToolHostRequirements, dm as ToolMessage, dn as ToolMetadata, dp as ToolReplayMode, dq as ToolReplayPolicy, dr as ToolResult, ds as ToolSideEffectLevel, dt as TracingConfig, a as TurnTrackerContext, du as UndoResult, dv as UserMessage, dw as WorkerReportPayload, dx as accumulateUsage, dy as advanceAgentTurnState, dz as approvalMiddleware, dA as buildCoordinatorNotificationEvent, l as calculateDelay, dB as createAgent, dC as createAgentTurnEngine, dD as createAgentTurnState, dE as createApprovalHandler, dF as createHumanInputController, dG as createPromptBuilder, m as createRetryHandler, n as createRetryState, dH as createSkillRegistry, dI as createTurnTracker, dJ as emptySkillRegistry, dK as failAgentTurnState, dL as getRequiredToolHost, dM as isApprovalMiddleware, dN as isBlockedModelCall, dO as isHumanInputController, dP as requiresToolHost, dQ as resolveAgentDefaults, dR as resolveCapability, dS as sandboxDefaultsProvider, s as shouldRetry, w as withRetry } from './instance-BqV2D5pc.js';
3
+ import { LanguageModel, ModelMessage, Tool as Tool$1, TelemetrySettings } from 'ai';
4
+ import { T as ToolHost } from './types-C_LCeYNg.js';
5
+ export { D as DirEntry, E as ExecOptions, a as ExecResult, F as FileStat } from './types-C_LCeYNg.js';
6
+ import { L as Logger } from './types-RSCv7nQ4.js';
7
+ export { C as ConsoleLoggerOptions, F as FileLoggerOptions, a as LogLevel, b as LogMeta } from './types-RSCv7nQ4.js';
14
8
  import { R as ReasoningLevel } from './types-CQaXbRsS.js';
15
9
  export { E as EXTENDED_LEVELS, F as FIXED_LEVELS, a as ReasoningConfig, S as STANDARD_LEVELS, s as shouldIncludeReasoningSummary } from './types-CQaXbRsS.js';
16
- import { ContextManager } from './context/index.js';
17
- export { ContextLimits, DEFAULT_CONTEXT_LIMITS, PruneContextOptions, PruneResult, SummarizationOptions, estimateConversationTokens, estimateMessageTokens, estimateTokens, findCutPoint, generateSummary, isContextOverflowing, pruneContext, pruneToolResults, shouldPruneContext } from './context/index.js';
18
- import { T as TurnChangeTracker } from './tracker-DClqYqTj.js';
19
- export { F as FileBaseline, a as TurnFileChange, b as TurnSummary, c as TurnTrackerConfig, U as UndoResult, d as createTurnTracker } from './tracker-DClqYqTj.js';
20
- import { P as PromptBuilder } from './builder-UpOWQMW3.js';
21
- export { c as createPromptBuilder } from './builder-UpOWQMW3.js';
22
- import { S as SessionManager } from './session-manager-B_CWGTsl.js';
23
- export { B as BranchEntry, C as CompactionEntry, a as ConfigChangeEntry, b as CreateSessionOptions, E as EntryBase, F as FileEntry, M as MessageEntry, c as MetadataEntry, d as STORAGE_VERSION, e as SerializedMessage, f as SessionContext, g as SessionEntry, h as SessionHeader, i as SessionInfo, j as SessionStorage } from './session-manager-B_CWGTsl.js';
24
- import { A as AgentEvent } from './events-CE72w8W4.js';
25
- export { a as AgentStatus, b as AgentTurnBoundaryKind, c as ApprovalEvent, P as ProcessorResult, S as StepProcessingResult, d as StreamInput } from './events-CE72w8W4.js';
26
- export { A as AgentTurnActiveToolCall, a as AgentTurnBoundaryMetadata, b as AgentTurnBoundarySnapshot, c as AgentTurnCommitApplier, d as AgentTurnCommitBatch, e as AgentTurnCommitOptions, f as AgentTurnEngine, g as AgentTurnEngineOptions, h as AgentTurnPhase, i as AgentTurnResolvedToolCall, j as AgentTurnState, k as AgentTurnStateAdvanceOptions, l as AgentTurnStepCommitSnapshot, m as AgentTurnStepCommitToolCall, n as AgentTurnStepCommitToolResult, o as AgentTurnStepRuntimeConfig, C as CommitOutputOptions, p as CommitStepOptions, q as CreateAgentTurnStateOptions, r as CreateAgentTurnStepCommitBatchOptions, D as DoomLoopAction, s as DoomLoopHandler, t as DoomLoopRequest, P as PrepareModelStepOptions, u as PreparedAgentModelStep, v as ProcessorOptions, w as ProcessorOutput, R as RunModelStepOptions, x as RunToolBatchOptions, y as RunToolBatchResult, S as StepProcessingOptions, z as StepProcessingOutput, B as advanceAgentTurnState, E as createAgentTurnEngine, F as createAgentTurnState, G as failAgentTurnState } from './types-QKHHQLLq.js';
27
- export { ExecuteAgentToolCallOptions, ExecuteAgentToolCallResult, MAX_BYTES, MAX_LINES, TRUNCATE_DIR, TRUNCATE_GLOB, ToolRegistry, ToolSpec, TruncateResult, defaultRegistry, executeAgentToolCall, formatSize, normalizeToolReplayPolicy, truncateOutput } from './tool/index.js';
28
- export { AdapterSettings, CacheCapabilitySource, CapabilityCache, CapabilityOverrides, Directory, EngineSpec, ModelCapabilityResolver, Directory as ModelDirectory, Resolver as ModelResolver, ModelSpec, NetworkStatus, PatternCapabilitySource, RemoteCapabilityFetcher, RemoteCapabilitySource, ResolutionResult, Resolver, SyncResolver, applyCapabilityOverride, configureResolver, createResolver, extractModelId, extractProvider, findCapabilityOverride, getDefaultResolver, getModelId, getNetworkStatus, getProviderCompatibility, getProviderId, inferContextWindow, inferProvider, likelySupportsReasoning } from './models/index.js';
29
- export { C as CapabilitySource, D as DEFAULT_RESOLVER_OPTIONS, I as InputModality, M as ModelCapabilities, a as ModelEntry, O as OutputModality, P as ProviderCompatibility, R as ResolverOptions, S as SourcePriority, b as SourceResult } from './types-QA4WhEfz.js';
30
- export { H as HttpTransportConfig, M as MCPConfig, a as MCPManager, b as MCPPrompt, c as MCPResource, d as MCPServerConfig, e as MCPServerStatus, S as SseTransportConfig, f as StdioTransportConfig } from './types-VQgymC1N.js';
31
- export { createMCPManager, defineServer, httpServer, sseServer, stdioServer } from './mcp/index.js';
32
- export { AgentTaskChatAdapter, AgentTaskCheckpointReason, AgentTaskCheckpointStrategy, AgentTaskCheckpointStrategyInput, AgentTaskExecutionCheckpoint, AgentTaskExecutionContext, AgentTaskExecutionRun, AgentTaskExecutionSnapshot, AgentTaskObserver, AgentTaskPayload, AgentTaskResult, AgentTaskRunner, AgentTaskRunnerOptions, AgentWorkflowAssistantMessageSnapshot, AgentWorkflowCommitResult, AgentWorkflowMessageSnapshot, AgentWorkflowModelStepPlan, AgentWorkflowModelStepResult, AgentWorkflowOperationPlan, AgentWorkflowOutputCommitPlan, AgentWorkflowReplayDecision, AgentWorkflowStepCommitPlan, AgentWorkflowSystemMessageSnapshot, AgentWorkflowToolBatchResult, AgentWorkflowToolCallPlan, AgentWorkflowToolCallResult, AgentWorkflowToolCallSnapshot, AgentWorkflowToolMessageSnapshot, AgentWorkflowTurnPhase, AgentWorkflowTurnState, AgentWorkflowUserMessageSnapshot, ContextOverflowError, CreateAgentWorkflowTurnStateOptions, DoomLoopError, applyAgentWorkflowCommitResult, applyAgentWorkflowModelStepResult, applyAgentWorkflowToolBatchResult, applyAgentWorkflowToolCallResult, cloneAgentWorkflowTurnState, commitOutput, commitStep, convertAgentMessagesToModelMessages, createAgentTaskRunner, createAgentTurnStepCommitBatch, createAgentWorkflowTurnState, defaultAgentTaskCheckpointStrategy, failAgentWorkflowTurnState, planNextAgentWorkflowOperation, prepareModelStep, processStepStream, processStream, recordAgentWorkflowReplayDecision, restoreAgentWorkflowMessage, restoreAgentWorkflowMessages, runModelStep, runToolBatch, snapshotAgentWorkflowMessage, snapshotAgentWorkflowMessages } from './runtime/index.js';
33
- export { ApprovalMiddlewareConfig, CacheTTL, OtelMiddlewareConfig, PromptCacheConfig, TelemetryConfig, TelemetryConfigResult, approvalMiddleware, createTelemetryConfig, otelMiddleware, promptCacheMiddleware } from './middleware/index.js';
10
+ export { ExecuteAgentToolCallOptions, ExecuteAgentToolCallResult, MAX_BYTES, MAX_LINES, ToolRegistry, ToolSearchOptions, ToolSpec, TruncateResult, createToolSearchTool, defaultRegistry, executeAgentToolCall, normalizeToolReplayPolicy, truncateOutput } from './tool/index.js';
11
+ export { ToolHostProvider, ToolHostProviderSummary, ToolHostRegistry, defaultToolHostRegistry, localHost } from './tool/host/index.js';
12
+ export { AdapterSettings, CacheCapabilitySource, CapabilityCache, CapabilityOverrides, Directory, EngineSpec, ModelCapabilityResolver, ModelSpec, NetworkStatus, PatternCapabilitySource, RemoteCapabilityFetcher, RemoteCapabilitySource, ResolutionResult, Resolver, applyCapabilityOverride, configureResolver, createResolver, extractModelId, extractProvider, findCapabilityOverride, getDefaultResolver, getModelId, getNetworkStatus, getProviderCompatibility, getProviderId, inferContextWindow, inferProvider, likelySupportsReasoning } from './models/index.js';
13
+ export { C as CapabilitySource, D as DEFAULT_RESOLVER_OPTIONS, I as InputModality, M as ModelCapabilities, a as ModelEntry, O as OutputModality, P as ProviderCompatibility, R as ResolverOptions, S as SourcePriority, b as SourceResult, c as buildAnthropicOptions, d as buildBedrockOptions, e as buildGoogleOptions, f as buildGroqOptions, g as buildOpenAIOptions, h as buildOpenRouterOptions, i as buildReasoningOptions, j as buildReasoningOptionsSync, k as buildXAIOptions, l as getProviderOptionsKey, m as getReasoningConfig, n as getReasoningConfigSync, s as supportsReasoning, o as supportsReasoningSync } from './index-BCqEGzBj.js';
14
+ export { H as HttpTransportConfig, M as MCPConfig, a as MCPManager, b as MCPServerConfig, c as MCPServerStatus, R as RemoteTransportConfig, S as SseTransportConfig, d as StdioTransportConfig } from './types-Bj_J8u_W.js';
15
+ export { createMCPManager, httpServer, sseServer, stdioServer } from './mcp/index.js';
16
+ export { AgentTaskChatAdapter, AgentTaskCheckpointReason, AgentTaskCheckpointStrategy, AgentTaskCheckpointStrategyInput, AgentTaskExecutionCheckpoint, AgentTaskExecutionContext, AgentTaskExecutionRun, AgentTaskExecutionSnapshot, AgentTaskObserver, AgentTaskPayload, AgentTaskResult, AgentTaskResumeSnapshot, AgentTaskRunner, AgentTaskRunnerOptions, AgentWorkflowAssistantMessageSnapshot, AgentWorkflowCommitResult, AgentWorkflowInputCommitPlan, AgentWorkflowInterventionSnapshot, AgentWorkflowMessageSnapshot, AgentWorkflowModelStepPlan, AgentWorkflowModelStepResult, AgentWorkflowOperationPlan, AgentWorkflowOutputCommitPlan, AgentWorkflowReplayDecision, AgentWorkflowStepCommitPlan, AgentWorkflowSystemMessageSnapshot, AgentWorkflowToolBatchPlan, AgentWorkflowToolBatchResult, AgentWorkflowToolCallPlan, AgentWorkflowToolCallResult, AgentWorkflowToolCallSnapshot, AgentWorkflowToolMessageSnapshot, AgentWorkflowTurnPhase, AgentWorkflowTurnState, AgentWorkflowUserMessageSnapshot, ContextOverflowError, CreateAgentWorkflowTurnStateOptions, DoomLoopError, applyAgentWorkflowCommitResult, applyAgentWorkflowModelStepResult, applyAgentWorkflowToolBatchResult, applyAgentWorkflowToolCallResult, applyWorkflowInterventions, cloneAgentWorkflowTurnState, commitOutput, commitStep, createAgentTaskRunner, createAgentTurnStepCommitBatch, createAgentWorkflowTurnState, defaultAgentTaskCheckpointStrategy, drainWorkflowInterventions, failAgentWorkflowTurnState, planNextAgentWorkflowOperation, prepareModelStep, processStepStream, queueWorkflowFollowUps, recordAgentWorkflowReplayDecision, restoreAgentWorkflowMessage, restoreAgentWorkflowMessages, runModelStep, runToolBatch, snapshotAgentWorkflowMessage, snapshotAgentWorkflowMessages } from './execution/index.js';
17
+ export { c as convertAgentMessagesToModelMessages } from './model-messages-B4nK9D1-.js';
18
+ export { CacheTTL, PromptCacheConfig, createTelemetryConfig, otelMiddleware, promptCacheMiddleware } from './middleware/index.js';
34
19
  export { DEFAULT_INSTRUCTION_PATTERNS, DEFAULT_MAX_DEPTH, DEFAULT_MAX_FILE_SIZE, PRIORITY_BASE, PRIORITY_CUSTOM, PRIORITY_ENVIRONMENT, PRIORITY_INSTRUCTIONS, PRIORITY_OVERRIDE, PRIORITY_SKILLS, detectModelFamily, discoverInstructions, formatEnvironment, formatInstructions, gatherEnvironment, getAvailableFamilies, getTemplate, loadGlobalInstructions, summarizeEnvironment } from './prompt/index.js';
35
- export { R as RemoteSkillEntry, e as RemoteSkillIndex, d as SkillConfig, b as SkillContent, f as SkillDiscoveryError, S as SkillDiscoveryResult, a as SkillMetadata, c as SkillResource, g as SkillResourceType, h as SkillScope, i as SkillSource, j as SkillSourceType } from './types-BfNpU8NS.js';
36
- export { buildAnthropicOptions, buildBedrockOptions, buildGoogleOptions, buildGroqOptions, buildOpenAIOptions, buildOpenRouterOptions, buildReasoningOptions, buildReasoningOptionsSync, buildXAIOptions, getProviderOptionsKey, getReasoningConfig, getReasoningConfigSync, supportsReasoning, supportsReasoningSync } from './reasoning/index.js';
37
- export { A as AppliedPreset, P as Preset } from './types-BnpEOYV-.js';
38
- export { Presets, applyPreset, careful, code, createPreset, explore, filterTools, mergePresets, plan, quick, review, watch } from './presets/index.js';
39
- export { DockerHostOptions, dockerHost, localHost } from './host/index.js';
40
- export { a as Scope, b as ScopeAttributeValue, c as ScopeAttributes, d as ScopeKind, e as ScopeOptions, S as ScopeSnapshot } from './types-CQL-SvTn.js';
41
- export { createScope, currentScope, restoreScope, snapshotScope, withinScope } from './scope/index.js';
42
- export { Inference, LLM, buildToolSet, stream, streamOnce, streamStep } from './inference/index.js';
20
+ export { Profiles, applyProfile, careful, code, createProfile, explore, filterTools, mergeProfiles, plan, quick, review, watch } from './profiles/index.js';
21
+ export { SandboxPreview, SandboxProvider, SandboxSession, SandboxSessionMetadata, SandboxSnapshotResult } from './sandbox/index.js';
22
+ export { Inference, buildModelCallContext, buildToolSet, stream, streamOnce, streamStep } from './inference/index.js';
43
23
  export { FileStorage, FileStorageOptions, MemoryStorage, buildEntryPath, buildMessagesFromEntries, configureDefaultSessionManager, createMessageEntry, createMetadataEntry, deserializeMessage, extractSessionInfo, generateEntryId, getDataDir, getDefaultSessionManager, getGitRootHash, getLeafId, getProjectId, getProjectSessionsDir, getSessionsDir, parseJSONL, serializeMessage, toJSONL, toJSONLBatch } from './storage/index.js';
44
- export { ChangeSet, Checkpoint, CheckpointConfig, CheckpointManager, FileChange, TrackedToolMetadata, clearCheckpoints, createCheckpointManager, extractFilePathsFromArgs, shouldCaptureBaseline, withFileTracking } from './tracking/index.js';
45
- export { A as ApprovalAction, a as ApprovalConfig, b as ApprovalRequest, c as ApprovalRule, R as RiskLevel } from './types-CWm-7rvB.js';
46
- export { ApprovalDeniedError, ApprovalHandler, ApprovalTimeoutError, createApprovalHandler, getToolRisk } from './safety/index.js';
24
+ export { ApprovalDeniedError, ApprovalPolicyPresetName, ApprovalPolicyPresetOptions, ApprovalRuleCondition, ApprovalTimeoutError, RiskTierApprovalPolicyOptions, ThresholdApprovalRuleOptions, TrustedSessionApprovalPolicyOptions, allApprovalConditions, anyApprovalConditions, approvalRequestsOverlap, buildApprovalRuleContext, createApprovalCorrection, createApprovalPolicyPreset, createConditionalApprovalRule, createDangerouslyAllowAllApprovalPolicy, createHeadlessDenyApprovalPolicy, createInteractiveApprovalPolicy, createRememberedApprovalRules, createRiskTierApprovalPolicy, createThresholdApprovalRule, createTrustedSessionApprovalPolicy, describeApprovalOperation, extractApprovalPatterns, formatApprovalDeniedReason, getToolRisk, matchApprovalArgValue, matchApprovalNumericArg, matchApprovalPattern, matchApprovalRisks, matchApprovalSessions, matchApprovalStringPrefixes, normalizeApprovalCascadePolicy, normalizeRememberScopes, selectRememberScope, shouldCascadeApprovalDecision } from './safety/index.js';
47
25
  export { E as ErrorCategory, L as LLMError, a as LLMErrorOptions, R as ResponseHeaders } from './llm-error-D93FNNLY.js';
48
- export { getErrorCategory, getRetryDelay, isRetryable, isRetryableCategory, parseRetryDelay } from './errors/index.js';
26
+ export { getErrorCategory, getRetryDelay, isRetryable, isRetryableCategory, parseRetryDelay } from './inference/errors/index.js';
49
27
  export { DEFAULT_EXTERNAL_DIRS, DEFAULT_MAX_SCAN_DEPTH, DEFAULT_SKILL_MAX_SIZE, SKILL_FILENAME, createSkillResourceTool, createSkillTool, createSkillTools, discoverSkills, inferResourceType, loadResourceContent, loadSkillContent, loadSkillMetadata, parseFrontmatter } from './skill/index.js';
50
- export { S as SkillRegistry, c as createSkillRegistry, e as emptySkillRegistry } from './registry-DwYqsQkX.js';
51
- export { A as AgentSignal, E as EventOf, T as TypedHandler, U as Unsubscribe, W as WildcardHandler } from './types-YuWV4ag7.js';
52
- export { LocalSignal } from './signal/index.js';
53
- export { F as FileOperationMeta, N as NormalizedToolReplayPolicy, b as ToolContext, T as ToolMetadata, e as ToolReplayMode, a as ToolReplayPolicy, c as ToolResult, f as ToolSideEffectLevel, d as TurnTrackerContext } from './tool-DLXAR9Ce.js';
28
+ export { CompositeDispatchTaskExecutorOptions, DispatchExternalTaskControlOptions, DispatchTaskExecutorOptions, DispatchTaskExecutorRoute, RuntimeDispatchExecutorOptions, RuntimeDispatchTargetOptions, createCompositeDispatchTaskExecutor, createDispatchExternalTaskControl, createDispatchTaskExecutor, createDispatchTools, createLocalDispatchRuntime, createRuntimeDispatchExecutor, createRuntimeDispatchTargets, ensureNonEmpty, mergeInspection } from './dispatch/index.js';
29
+ export { DEFAULT_SUBAGENT_CONCURRENCY, DEFAULT_SUBAGENT_DEPTH, DEFAULT_SUBAGENT_SESSION_PREFIX, DiscoveredSubAgentRole, LOCAL_SUBAGENT_BACKEND, MarkdownSubAgentRole, MarkdownSubAgentRoleFrontmatter, ParsedMarkdownSubAgentRole, ParsedSubAgentToolSpec, SUBAGENT_TOOL_IDS, SubAgentCompletedResult, SubAgentConfig, SubAgentRole, SubAgentRoleDiscoveryOptions, SubAgentRoleDiscoveryResult, SubAgentRoleResolvers, SubAgentRoleSource, SubAgentToolModifier, SubAgentToolsOptions, clearInstalledSubAgents, configureSubAgents, createCloseAgentTool, createInvokeAgentTool, createSubAgentTools, createWaitAgentTool, discoverSubAgentRoles, formatAsyncSpawnedResult, formatCancelledAgentResult, formatCloseAlreadyResolvedResult, formatCloseMissingAgentResult, formatInvalidAgentTypeResult, formatMissingAgentsResult, formatSpawnBlockedResult, formatSyncSubAgentErrorResult, formatSyncSubAgentResult, formatWaitErrorResult, formatWaitResult, formatWaitTimeoutResult, getConfiguredSubAgents, getInstalledSubAgentBackend, getProjectSubAgentRolesDir, getUserSubAgentRolesDir, installLocalSubAgents, installSubAgentTools, isMarkdownSubAgentRole, parseMarkdownSubAgentRole, parseSubAgentRoleFrontmatter, parseSubAgentToolSpec, toSubAgentRole } from './subagents/index.js';
30
+ export { DefinePluginInit, DiscoveredPlugin, LayeredSettings, NullSettings, PluginActivateContext, PluginCapabilityTag, PluginCommand, PluginCommandMetadata, PluginCompatibility, PluginContext, PluginContributions, PluginDefinition, PluginEventBus, PluginEventBusAPI, PluginEventHandler, PluginInit, PluginLifecycleHooks, PluginLoaderOptions, PluginManifest, PluginRegistry, PluginRegistryCompatibilityOptions, PluginRegistryOptions, PluginRegistryTimeoutOptions, PluginSessionContext, PluginSettingsDefinition, PluginSettingsProvider, PluginSettingsSchema, PluginSurfaceContract, PluginUnsubscribe, StaticSettings, ValidatedSettings, definePlugin, discoverPlugins, getPluginLoader, isDefinedPlugin, loadPluginModule, resetFrameworkAliases, resetPluginLoader, resolveFrameworkAliases } from './plugin/index.js';
31
+ export { EventBus, EventBusMessage, EventBusOptions, EventBusSubscribeOptions, EventBusSubscription, createEventBus } from './events/index.js';
32
+ export { ApprovalForwarder, CoordinatorInboxItem, CoordinatorLoopOptions, CoordinatorLoopResult, CoordinatorRosterMember, CoordinatorRound, CoordinatorRoundTransition, CoordinatorRoundTransitionInput, CoordinatorRuntimeStatus, CoordinatorStatus, CoordinatorTaskNotificationLike, CoordinatorWorkerReportLike, TeamCoordinator, TeamPermissionPolicyConfig, TeamPermissionRule, WorkerReport, addTokenUsage, buildCoordinatorSystemPrompt, coordinatorToolDescriptions, createTeamCoordinator, evaluateCoordinatorRoundTransition, formatCoordinatorRoundMessage, formatCoordinatorTaskNotifications, formatCoordinatorWorkerReports, teamPermissionPolicy } from './team/index.js';
33
+ export { createConsoleLogger, createFileLogger, silentLogger } from './logger/index.js';
54
34
  import 'zod';
55
35
  import '@ai-sdk/provider-utils';
36
+ import 'jiti';
37
+
38
+ /**
39
+ * Promise-based sleep utility.
40
+ *
41
+ * @param ms - Duration to wait in milliseconds.
42
+ */
43
+ declare function sleep(ms: number): Promise<void>;
44
+
45
+ /**
46
+ * Backward-compatible alias for the controller-backed human input primitive.
47
+ *
48
+ * Prefer `createHumanInputController(...)` in new code.
49
+ */
50
+ type HumanInputHandler = HumanInputController;
51
+ /**
52
+ * Backward-compatible alias for `createHumanInputController(...)`.
53
+ *
54
+ * Prefer `createHumanInputController(...)` in new code.
55
+ */
56
+ declare function createHumanInputHandler(config?: HumanInputConfig): HumanInputHandler;
57
+
58
+ interface CreateHumanInputToolOptions extends HumanInputConfig {
59
+ controller?: HumanInputController;
60
+ name?: string;
61
+ description?: string;
62
+ }
63
+ declare function createHumanInputTool(options?: CreateHumanInputToolOptions): Tool.AnyInfo;
64
+ declare function createHumanInputToolWithController(controller?: HumanInputController, options?: Pick<CreateHumanInputToolOptions, "name" | "description">): Tool.AnyInfo;
65
+ /**
66
+ * Backward-compatible alias for `createHumanInputToolWithController(...)`.
67
+ *
68
+ * Prefer the controller name in new code.
69
+ */
70
+ declare const createHumanInputToolWithHandler: typeof createHumanInputToolWithController;
56
71
 
57
72
  /**
58
73
  * Mutable runtime state held by an `Agent` instance.
74
+ *
75
+ * Only fields that are actually read at runtime belong here.
76
+ * Configuration-level values (systemPrompt, cwd) live on
77
+ * `EffectiveAgentConfig`; computed values (isStreaming) are
78
+ * derived from instance counters.
59
79
  */
60
80
  interface AgentState {
61
81
  model: LanguageModel;
62
- systemPrompt: string;
63
- cwd: string;
64
- isStreaming: boolean;
65
82
  /** Current reasoning level */
66
83
  reasoningLevel: ReasoningLevel;
67
- error?: Error;
84
+ }
85
+
86
+ /**
87
+ * Token Estimation Utilities
88
+ *
89
+ * Provides lightweight heuristic-based token counting for messages
90
+ * and conversations. Uses the chars/4 approximation — simple but
91
+ * effective for context-window planning decisions.
92
+ *
93
+ * These are *estimates*, not exact counts. For billing or hard limits,
94
+ * use the provider's native tokeniser instead.
95
+ */
96
+
97
+ /**
98
+ * Estimate token count for a plain string.
99
+ *
100
+ * Uses the widely-accepted `chars / 4` heuristic.
101
+ *
102
+ * @param text - Text to estimate
103
+ * @returns Estimated token count (always ≥ 1 for non-empty input)
104
+ */
105
+ declare function estimateTokens(text: string): number;
106
+ /**
107
+ * Estimate token count for a single message.
108
+ *
109
+ * Handles:
110
+ * - Plain string content
111
+ * - Multi-part / multimodal arrays (text parts + images)
112
+ *
113
+ * @param message - A `Message` (internal) or `ModelMessage` (AI SDK)
114
+ * @returns Estimated token count
115
+ */
116
+ declare function estimateMessageTokens(message: Message | ModelMessage): number;
117
+ /**
118
+ * Estimate total tokens for an entire conversation.
119
+ *
120
+ * Adds a small per-message overhead (≈ 4 tokens) for message
121
+ * framing (`role`, delimiters, etc.).
122
+ *
123
+ * @param messages - Array of messages to estimate
124
+ * @returns Estimated total token count
125
+ */
126
+ declare function estimateConversationTokens(messages: (Message | ModelMessage)[]): number;
127
+
128
+ /**
129
+ * Context Overflow Detection & Pruning
130
+ *
131
+ * Detects when a conversation is approaching the model's context-window
132
+ * limit and prunes old / redundant content to stay within bounds.
133
+ *
134
+ * Two pruning strategies are available:
135
+ * 1. **Tool-result pruning** — replaces large, stale tool outputs with
136
+ * compact placeholders (lightweight, no model call).
137
+ * 2. **Conversation cutting** — identifies a safe cut-point and removes
138
+ * older messages entirely (optionally summarised by the manager).
139
+ */
140
+
141
+ /**
142
+ * Context limits configuration.
143
+ *
144
+ * All values are in *estimated* tokens (see {@link estimateTokens}).
145
+ */
146
+ interface ContextLimits {
147
+ /** Maximum context window size in tokens */
148
+ contextWindow: number;
149
+ /** Reserve tokens for output generation */
150
+ reserveTokens: number;
151
+ /** Protect this many recent tokens from pruning */
152
+ protectedTokens: number;
153
+ /** Minimum tokens to trigger pruning (avoid pruning tiny contexts) */
154
+ pruneMinimum: number;
155
+ }
156
+ /**
157
+ * Default context limits.
158
+ * Based on typical 128 k context-window models.
159
+ */
160
+ declare const DEFAULT_CONTEXT_LIMITS: ContextLimits;
161
+ /**
162
+ * Compute the usable token budget: the context window minus reserved output tokens.
163
+ *
164
+ * This is the single formula for the "safe input threshold" used by
165
+ * overflow detection, auto-compaction event emission, and step-processing limits.
166
+ */
167
+ declare function getUsableTokenLimit(limits: Pick<ContextLimits, "contextWindow" | "reserveTokens">): number;
168
+ /**
169
+ * Result of a pruning operation.
170
+ */
171
+ interface PruneResult {
172
+ /** Messages after pruning (may include a summary message) */
173
+ messages: Message[];
174
+ /** Number of messages removed */
175
+ removedCount: number;
176
+ /** Estimated tokens removed */
177
+ tokensRemoved: number;
178
+ /** Whether summarisation was used */
179
+ summarized: boolean;
180
+ /** The summary content, if generated */
181
+ summary?: string;
182
+ }
183
+ /**
184
+ * Find a safe index at which the conversation can be "cut".
185
+ *
186
+ * Rules:
187
+ * - Never cut in the middle of a tool-call sequence
188
+ * - Prefer cutting after assistant / user messages
189
+ * - Keep at least {@link protectedTokens} tokens at the end
190
+ *
191
+ * @param messages - Full message array
192
+ * @param protectedTokens - Tokens to preserve at the end
193
+ * @returns Cut index (exclusive — remove messages *before* this index).
194
+ * Returns `0` when no safe cut-point exists.
195
+ */
196
+ declare function findCutPoint(messages: Message[], protectedTokens?: number): number;
197
+
198
+ /**
199
+ * Context Manager
200
+ *
201
+ * Stateful wrapper around the context-management primitives.
202
+ * Tracks per-session context limits and provides a single entry
203
+ * point for token estimation, overflow detection, and pruning.
204
+ */
205
+
206
+ /**
207
+ * Per-session context manager.
208
+ *
209
+ * Holds the active context-window limits and provides convenience
210
+ * methods for checking, reporting, and pruning context.
211
+ *
212
+ * @example
213
+ * ```typescript
214
+ * const ctx = new ContextManager({ limits: { contextWindow: 200_000 } });
215
+ *
216
+ * if (ctx.shouldPrune(messages)) {
217
+ * const result = await ctx.prune(messages);
218
+ * console.log(`Removed ${result.removedCount} messages`);
219
+ * }
220
+ * ```
221
+ */
222
+ declare class ContextManager {
223
+ private limits;
224
+ private model?;
225
+ private summaryPrompt?;
226
+ constructor(options?: {
227
+ limits?: Partial<ContextLimits>;
228
+ model?: LanguageModel;
229
+ summaryPrompt?: string;
230
+ });
231
+ /** Get a copy of the current context limits. */
232
+ getLimits(): ContextLimits;
233
+ /** Update context limits (e.g. when switching models). */
234
+ setLimits(limits: Partial<ContextLimits>): void;
235
+ /** Set the model used for summarisation. */
236
+ setModel(model: LanguageModel): void;
237
+ /** Estimate total tokens for a message array. */
238
+ estimateTokens(messages: (Message | ModelMessage)[]): number;
239
+ /** Check whether the context is overflowing. */
240
+ isOverflowing(messages: (Message | ModelMessage)[]): boolean;
241
+ /** Check whether pruning should be triggered. */
242
+ shouldPrune(messages: (Message | ModelMessage)[]): boolean;
243
+ /** Prune context to fit within limits. */
244
+ prune(messages: Message[]): Promise<PruneResult>;
245
+ /**
246
+ * Get a snapshot of token statistics.
247
+ *
248
+ * Useful for dashboards, logging, or deciding whether to prune.
249
+ */
250
+ getStats(messages: (Message | ModelMessage)[]): {
251
+ tokens: number;
252
+ limit: number;
253
+ available: number;
254
+ utilizationPercent: number;
255
+ isOverflowing: boolean;
256
+ shouldPrune: boolean;
257
+ };
68
258
  }
69
259
 
70
260
  /** Everything the chat loop needs from the Agent instance. */
71
261
  interface ChatLoopDeps {
72
262
  sessionId: string;
263
+ turnId: string;
73
264
  message: string;
74
265
  abort: AbortSignal;
75
266
  systemOverride?: string;
76
267
  sessions: SessionManager;
77
- tools: Record<string, Tool.Info>;
78
- config: Required<Pick<AgentConfig, "model" | "systemPrompt" | "cwd" | "maxOutputTokens" | "maxSteps">> & AgentConfig;
268
+ /**
269
+ * Live reference to the agent's tools Map.
270
+ *
271
+ * The loop rebuilds a `Record<string, Tool.Info>` from this Map at
272
+ * the start of each model step so that mid-turn additions (e.g.
273
+ * tools loaded by `tool_search` via `agent.addTool()`) are visible
274
+ * to the next step without restarting the turn.
275
+ */
276
+ tools: Map<string, Tool.AnyInfo>;
277
+ config: EffectiveAgentConfig;
79
278
  turnTracker: TurnChangeTracker;
80
279
  interventionCtrl: InterventionController;
81
280
  middlewareRunner: MiddlewareRunner;
@@ -84,10 +283,19 @@ interface ChatLoopDeps {
84
283
  reasoningLevel: ReasoningLevel;
85
284
  promptBuilder?: PromptBuilder;
86
285
  host: ToolHost;
286
+ humanInputController?: HumanInputController;
87
287
  mcpTools: Record<string, Tool$1>;
88
288
  telemetrySettings?: TelemetrySettings;
89
289
  toModelMessages: (messages: Message[]) => ModelMessage[];
90
290
  setIsStreaming: (value: boolean) => void;
291
+ /**
292
+ * Tool execution mode for this chat loop.
293
+ * - `"auto"` — tools auto-execute via AI SDK (default)
294
+ * - `"plan"` — tools are planned, then dispatched via `runToolBatch()`
295
+ */
296
+ toolExecutionMode?: ToolExecutionMode;
297
+ /** Logger for diagnostic output. */
298
+ logger?: Logger;
91
299
  }
92
300
 
93
301
  /**
@@ -96,101 +304,261 @@ interface ChatLoopDeps {
96
304
  */
97
305
  declare function runChatLoop(deps: ChatLoopDeps): AsyncGenerator<AgentEvent>;
98
306
 
99
- /**
100
- * Concurrent sub-agent execution.
101
- */
307
+ declare function ensureSessionLoaded(options: {
308
+ sessionId: string;
309
+ sessions: SessionManager;
310
+ cwd: string;
311
+ }): Promise<void>;
102
312
 
103
313
  /**
104
- * Sub-agent run result
314
+ * CLI-friendly event printer for `agent.chat()` streams.
315
+ *
316
+ * Provides a zero-config function that handles the full `AgentEvent`
317
+ * union, writing text deltas to stdout, tool calls with emoji prefixes,
318
+ * and lifecycle events to stderr. Covers the same ground as the
319
+ * 80-line `handleEvent()` in example 03–streaming but as a reusable
320
+ * one-liner:
321
+ *
322
+ * ```ts
323
+ * const print = createEventPrinter();
324
+ * for await (const event of agent.chat("demo", "Hello")) {
325
+ * print(event);
326
+ * }
327
+ * ```
328
+ *
329
+ * All options are optional — sensible defaults work out of the box.
105
330
  */
106
- interface SubAgentResult {
107
- /** Final response text */
108
- response: string;
109
- /** Sub-agent session ID */
110
- sessionId: string;
111
- /** Token usage */
112
- usage: TokenUsage;
113
- /** Tool calls made */
114
- toolCalls: Array<{
115
- name: string;
116
- result: unknown;
117
- }>;
331
+
332
+ /** Controls which event categories the printer renders. */
333
+ interface EventPrinterOptions {
334
+ /**
335
+ * Show tool start/result/error events.
336
+ * @default true
337
+ */
338
+ tools?: boolean;
339
+ /**
340
+ * Show reasoning tokens (thinking models like o3, o4-mini).
341
+ * @default true
342
+ */
343
+ reasoning?: boolean;
344
+ /**
345
+ * Show step/lifecycle banners.
346
+ * @default false
347
+ */
348
+ steps?: boolean;
349
+ /**
350
+ * Show approval, intervention, and safety events.
351
+ * @default true
352
+ */
353
+ safety?: boolean;
354
+ /**
355
+ * Show the completion summary line.
356
+ * @default true
357
+ */
358
+ completion?: boolean;
359
+ /**
360
+ * Show team coordination events (team-*).
361
+ * @default false
362
+ */
363
+ team?: boolean;
364
+ /**
365
+ * Writable stream for text output.
366
+ * @default process.stdout
367
+ */
368
+ stdout?: NodeJS.WritableStream;
369
+ /**
370
+ * Writable stream for diagnostic/lifecycle output.
371
+ * @default process.stderr
372
+ */
373
+ stderr?: NodeJS.WritableStream;
118
374
  }
119
375
  /**
120
- * Run multiple sub-agent tasks concurrently.
376
+ * Create a stateless event handler for printing `AgentEvent`s to the
377
+ * terminal.
121
378
  *
122
- * Useful for parallelizing independent research or analysis tasks.
123
- * Results are returned in the same order as tasks.
379
+ * @param options - Fine-tune which event categories are rendered.
380
+ * @returns A function that accepts one `AgentEvent` and writes to stdout/stderr.
124
381
  *
125
- * **IMPORTANT: Concurrency Considerations**
126
- *
127
- * When multiple tasks use the same `Agent` instance, they share the same
128
- * `SessionManager`. To avoid state conflicts:
382
+ * @example
383
+ * ```ts
384
+ * import { createAgent, createEventPrinter } from "@cuylabs/agent-core";
129
385
  *
130
- * 1. Use distinct `parentSessionId` values for each task
131
- * 2. Or create separate `Agent` instances via `agent.fork()` for each task
132
- * 3. Or ensure tasks use unique session IDs (auto-generated if not specified)
386
+ * const agent = createAgent({ model, systemPrompt: "Be concise." });
387
+ * const print = createEventPrinter();
133
388
  *
134
- * Tasks modifying the same session concurrently may cause race conditions.
389
+ * for await (const event of agent.chat("demo", "Hello")) {
390
+ * print(event);
391
+ * }
392
+ * ```
135
393
  *
136
394
  * @example
137
- * ```typescript
138
- * const explorer = agent.fork({ name: "explore", ... });
139
- *
140
- * const results = await runConcurrent([
141
- * { agent: explorer, message: "Find all API endpoints" },
142
- * { agent: explorer, message: "Find all database queries" },
143
- * { agent: explorer, message: "Find all auth middleware" },
144
- * ], { maxConcurrency: 3 });
395
+ * ```ts
396
+ * // Quiet mode text only, no tool or lifecycle output
397
+ * const print = createEventPrinter({
398
+ * tools: false,
399
+ * reasoning: false,
400
+ * steps: false,
401
+ * completion: false,
402
+ * });
145
403
  * ```
146
404
  */
147
- declare function runConcurrent(tasks: Array<{
148
- agent: Agent;
149
- message: string;
150
- parentSessionId?: string;
151
- title?: string;
152
- }>, options?: {
153
- /** Maximum concurrent tasks (default: 5) */
154
- maxConcurrency?: number;
155
- /** Abort signal for all tasks */
156
- abort?: AbortSignal;
157
- }): Promise<SubAgentResult[]>;
405
+ declare function createEventPrinter(options?: EventPrinterOptions): (event: AgentEvent) => void;
406
+
407
+ /**
408
+ * Auto-detect and configure stream provider from model and tools.
409
+ *
410
+ * Returns the configured stream provider, or undefined if standard
411
+ * AI SDK streaming should be used.
412
+ */
413
+ declare function autoDetectStreamProvider(model: LanguageModel, tools: unknown, explicitProvider: unknown): StreamProvider | undefined;
158
414
 
159
415
  /**
160
- * Agent defaults constants used by the Agent constructor.
416
+ * Shared intervention/follow-up types for @cuylabs/agent-core.
417
+ *
418
+ * These types give runtimes (agent-server, agent-runtime-dapr) a common
419
+ * vocabulary for user-directed turn control:
420
+ * - immediate mid-turn steering
421
+ * - deferred follow-ups queued for the next turn
422
+ *
423
+ * The `InterventionController` remains the in-process implementation;
424
+ * these types are the protocol-level representation for cross-process
425
+ * and durable scenarios.
426
+ */
427
+ /**
428
+ * A steering request surfaced to runtime consumers.
429
+ *
430
+ * Created when a client calls `steerTurn()` (agent-server) or
431
+ * `POST /agents/:id/steer` (agent-runtime-dapr). Runtimes publish
432
+ * an `intervention-applied` event so UIs can show the injection.
433
+ */
434
+ interface SteeringRequest {
435
+ /** Unique identifier (maps to `PendingIntervention.id` in direct mode) */
436
+ id: string;
437
+ /** Session the steering targets */
438
+ sessionId: string;
439
+ /** The user message to inject */
440
+ message: string;
441
+ /** When the steering was requested */
442
+ timestamp: number;
443
+ }
444
+ /**
445
+ * Acknowledgement returned after a steering message is accepted.
446
+ *
447
+ * In direct mode, the message is already queued in the
448
+ * `InterventionController`. In durable mode, it is persisted in
449
+ * state and will be picked up at the next workflow activity boundary.
161
450
  */
451
+ interface SteeringResponse {
452
+ /** The steering request ID */
453
+ id: string;
454
+ /** Whether the message was accepted */
455
+ accepted: boolean;
456
+ }
162
457
  /**
163
- * Generic fallback system prompt.
458
+ * A deferred follow-up request surfaced to runtime consumers.
164
459
  *
165
- * Only used when the consumer provides a flat `systemPrompt` string
166
- * without any value (i.e. the field exists but is empty/undefined).
167
- * When the prompt pipeline is active, this is never used.
460
+ * Created when a client calls `followUpTurn()` (agent-server) or
461
+ * `POST /agents/:id/follow-up` (agent-runtime-dapr). Runtimes publish
462
+ * a `follow-up-queued` event so UIs can show that the message will be
463
+ * available after the current turn completes.
464
+ */
465
+ interface FollowUpRequest {
466
+ /** Unique identifier (maps to `PendingIntervention.id` in direct mode) */
467
+ id: string;
468
+ /** Session the follow-up targets */
469
+ sessionId: string;
470
+ /** The user message to queue for the next turn */
471
+ message: string;
472
+ /** When the follow-up was requested */
473
+ timestamp: number;
474
+ }
475
+ /**
476
+ * Acknowledgement returned after a follow-up message is accepted.
168
477
  *
169
- * Domain-specific prompts (coding, browsing, etc.) belong in
170
- * consumer packages like agent-code, not here.
478
+ * In direct mode, the message is queued in the `InterventionController`.
479
+ * In durable mode, it is persisted in the runtime's durable follow-up store
480
+ * and becomes seedable on the next turn for the same session.
171
481
  */
172
- declare const DEFAULT_SYSTEM_PROMPT = "You are a capable AI assistant with access to tools.\n\nThink step by step about what you need to do.\nUse the available tools to accomplish tasks.\nVerify your results after each action.\n\nIf a tool fails, try an alternative approach \u2014 do not give up after a single error.\nKeep working until the task is fully resolved or you have exhausted all options.";
173
- /** Default max steps */
174
- declare const DEFAULT_MAX_STEPS = 50;
175
- /** Default max output tokens */
176
- declare const DEFAULT_MAX_TOKENS = 32000;
482
+ interface FollowUpResponse {
483
+ /** The follow-up request ID */
484
+ id: string;
485
+ /** Whether the message was accepted */
486
+ accepted: boolean;
487
+ }
488
+
489
+ type FollowUpMode = "suggest" | "confirm" | "auto-run";
490
+ type FollowUpStatus = "queued" | "accepted" | "discarded" | "applied";
491
+ type FollowUpDecisionAction = "accept" | "discard";
492
+ interface FollowUpPolicy {
493
+ /**
494
+ * `suggest`:
495
+ * queue the follow-up and expose it for the host/UI to surface.
496
+ * `confirm`:
497
+ * queue it, but require an explicit accept/discard decision before seeding.
498
+ * `auto-run`:
499
+ * automatically seed the next turn with queued follow-ups for the session.
500
+ */
501
+ mode?: FollowUpMode;
502
+ }
503
+ interface QueuedFollowUpRecord {
504
+ id: string;
505
+ sessionId: string;
506
+ message: string;
507
+ createdAt: string;
508
+ updatedAt: string;
509
+ mode: FollowUpMode;
510
+ status: FollowUpStatus;
511
+ sourceTurnId?: string;
512
+ workflowInstanceId?: string;
513
+ decidedAt?: string;
514
+ appliedAt?: string;
515
+ seededTurnId?: string;
516
+ }
517
+ declare function normalizeFollowUpMode(mode?: FollowUpMode): FollowUpMode;
518
+ declare function createQueuedFollowUpRecord(request: FollowUpRequest, options?: {
519
+ mode?: FollowUpMode;
520
+ sourceTurnId?: string;
521
+ workflowInstanceId?: string;
522
+ createdAt?: string;
523
+ updatedAt?: string;
524
+ }): QueuedFollowUpRecord;
525
+ declare function resolveQueuedFollowUp(record: QueuedFollowUpRecord, action: FollowUpDecisionAction, updatedAt: string): QueuedFollowUpRecord;
526
+ declare function markQueuedFollowUpApplied(record: QueuedFollowUpRecord, updatedAt: string, seededTurnId?: string): QueuedFollowUpRecord;
527
+ declare function canSeedQueuedFollowUp(record: QueuedFollowUpRecord): boolean;
528
+
529
+ declare function currentScope(): Scope | undefined;
530
+ declare function snapshotScope(scope?: Scope | undefined): ScopeSnapshot | undefined;
531
+ declare function withinScope<T>(options: ScopeOptions, fn: () => T | Promise<T>): Promise<T>;
532
+ declare function restoreScope<T>(snapshot: ScopeSnapshot | undefined, fn: () => T | Promise<T>): Promise<T>;
177
533
 
178
534
  /**
179
- * Check if a model requires a custom stream provider.
535
+ * Extract file paths from tool arguments based on metadata.
180
536
  */
181
- declare function needsCustomStreamProvider(model: LanguageModel, customPatterns?: string[]): boolean;
537
+ declare function extractFilePathsFromArgs(args: Record<string, unknown>, meta: FileOperationMeta): string[];
182
538
  /**
183
- * Check if tools array has stream provider factory attached.
539
+ * Check whether a tool operation should trigger baseline capture.
184
540
  */
185
- declare function hasStreamProviderFactory(tools: unknown): tools is EnhancedTools & {
186
- __streamProviderFactory: NonNullable<EnhancedTools["__streamProviderFactory"]>;
187
- };
541
+ declare function shouldCaptureBaseline(meta: FileOperationMeta): boolean;
542
+
188
543
  /**
189
- * Auto-detect and configure stream provider from model and tools.
544
+ * LocalSignal in-process event dispatch.
190
545
  *
191
- * Returns the configured stream provider, or undefined if standard
192
- * AI SDK streaming should be used.
546
+ * Dispatches events synchronously via direct function calls.
547
+ * Zero dependencies, zero serialization, zero network.
548
+ *
549
+ * Handler errors are caught silently — a broken listener must never
550
+ * interrupt the agent's streaming pipeline.
193
551
  */
194
- declare function autoDetectStreamProvider(model: LanguageModel, tools: unknown, explicitProvider: unknown): StreamProvider | undefined;
195
552
 
196
- export { Agent, AgentConfig, AgentEvent, type AgentState, type ChatLoopDeps, ContextManager, DEFAULT_MAX_STEPS, DEFAULT_MAX_TOKENS, DEFAULT_SYSTEM_PROMPT, EnhancedTools, InterventionController, Message, MiddlewareRunner, PromptBuilder, ReasoningLevel, SessionManager, StreamProvider, type SubAgentResult, TokenUsage, Tool, ToolHost, TurnChangeTracker, autoDetectStreamProvider, hasStreamProviderFactory, needsCustomStreamProvider, runChatLoop, runConcurrent };
553
+ declare class LocalSignal implements AgentSignal {
554
+ /** type → Set<handler> for typed subscriptions */
555
+ private readonly typed;
556
+ /** handlers that receive every event */
557
+ private readonly wildcard;
558
+ on<T extends AgentEvent["type"]>(type: T, handler: TypedHandler<T>): Unsubscribe;
559
+ onAny(handler: WildcardHandler): Unsubscribe;
560
+ emit(event: AgentEvent): void;
561
+ clear(): void;
562
+ }
563
+
564
+ export { AgentEvent, AgentSignal, type AgentState, type ChatLoopDeps, type ContextLimits, ContextManager, type CreateHumanInputToolOptions, DEFAULT_CONTEXT_LIMITS, EffectiveAgentConfig, type EventPrinterOptions, FileOperationMeta, type FollowUpDecisionAction, type FollowUpMode, type FollowUpPolicy, type FollowUpRequest, type FollowUpResponse, type FollowUpStatus, HumanInputConfig, HumanInputController, type HumanInputHandler, InterventionController, LocalSignal, Logger, Message, MiddlewareRunner, PromptBuilder, type QueuedFollowUpRecord, ReasoningLevel, ScopeSnapshot, SessionManager, type SteeringRequest, type SteeringResponse, StreamProvider, Tool, ToolExecutionMode, ToolHost, TurnChangeTracker, autoDetectStreamProvider, canSeedQueuedFollowUp, createEventPrinter, createHumanInputHandler, createHumanInputTool, createHumanInputToolWithController, createHumanInputToolWithHandler, createQueuedFollowUpRecord, currentScope, ensureSessionLoaded, estimateConversationTokens, estimateMessageTokens, estimateTokens, extractFilePathsFromArgs, findCutPoint, getUsableTokenLimit, markQueuedFollowUpApplied, normalizeFollowUpMode, resolveQueuedFollowUp, restoreScope, runChatLoop, shouldCaptureBaseline, sleep, snapshotScope, withinScope };