@cuylabs/agent-core 0.9.0 → 0.11.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 (116) 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-EKR6PKXU.js → chunk-6HZBHFOL.js} +3 -3
  7. package/dist/chunk-CJI7PVS2.js +58 -0
  8. package/dist/{chunk-WKHDSSXG.js → chunk-CMYN2RCB.js} +146 -46
  9. package/dist/chunk-FII65CN7.js +117 -0
  10. package/dist/{chunk-UHCJEM2E.js → chunk-ICZ66572.js} +13 -6
  11. package/dist/chunk-KYLPMBHD.js +316 -0
  12. package/dist/chunk-MXAP4UG6.js +2956 -0
  13. package/dist/{chunk-4QFNWPIF.js → chunk-N3VX7FEE.js} +35 -2
  14. package/dist/{chunk-MAZ5DY5B.js → chunk-NDZWXCBZ.js} +213 -78
  15. package/dist/{chunk-MHKK374K.js → chunk-Q742PSH3.js} +11 -27
  16. package/dist/{chunk-WGZAPU6N.js → chunk-QAL3OMI3.js} +15 -1
  17. package/dist/{chunk-UDCZ673N.js → chunk-RN6WZEUF.js} +27 -23
  18. package/dist/{chunk-ZXAKHMWH.js → chunk-ROTGCYDW.js} +22 -84
  19. package/dist/chunk-SPBFQXOT.js +0 -0
  20. package/dist/chunk-SSFBF3US.js +602 -0
  21. package/dist/chunk-SZ2XBPTW.js +8 -0
  22. package/dist/chunk-T4UIX5D7.js +115 -0
  23. package/dist/{chunk-IYWQOJMQ.js → chunk-TIHPYVAJ.js} +34 -34
  24. package/dist/{chunk-RKEW5WXI.js → chunk-TOTDGK3P.js} +1 -1
  25. package/dist/chunk-V4RFNEET.js +563 -0
  26. package/dist/chunk-VOUEJSW6.js +0 -0
  27. package/dist/{chunk-J4QDGZIA.js → chunk-WBPOZ7CL.js} +659 -275
  28. package/dist/chunk-X4VN4GIJ.js +185 -0
  29. package/dist/dispatch/index.d.ts +93 -0
  30. package/dist/dispatch/index.js +37 -0
  31. package/dist/events/index.d.ts +93 -0
  32. package/dist/events/index.js +6 -0
  33. package/dist/{runtime → execution}/index.d.ts +120 -35
  34. package/dist/{runtime → execution}/index.js +17 -11
  35. package/dist/index.d.ts +489 -115
  36. package/dist/index.js +1665 -462
  37. package/dist/inference/errors/index.js +1 -1
  38. package/dist/inference/index.d.ts +13 -21
  39. package/dist/inference/index.js +15 -12
  40. package/dist/instance-DzPiv6EK.d.ts +5723 -0
  41. package/dist/logger/index.d.ts +50 -0
  42. package/dist/logger/index.js +11 -0
  43. package/dist/mcp/index.d.ts +5 -9
  44. package/dist/mcp/index.js +2 -3
  45. package/dist/middleware/index.d.ts +10 -150
  46. package/dist/middleware/index.js +10 -2
  47. package/dist/model-messages-CJfwfzGe.d.ts +13 -0
  48. package/dist/models/index.d.ts +5 -2
  49. package/dist/models/index.js +2 -1
  50. package/dist/models/reasoning/index.js +2 -1
  51. package/dist/plugin/index.d.ts +55 -11
  52. package/dist/plugin/index.js +1 -1
  53. package/dist/profiles/index.d.ts +55 -0
  54. package/dist/{presets → profiles}/index.js +10 -10
  55. package/dist/prompt/index.d.ts +8 -13
  56. package/dist/safety/index.d.ts +109 -14
  57. package/dist/safety/index.js +59 -3
  58. package/dist/sandbox/index.d.ts +81 -0
  59. package/dist/sandbox/index.js +1 -0
  60. package/dist/skill/index.d.ts +10 -8
  61. package/dist/skill/index.js +2 -2
  62. package/dist/storage/index.d.ts +12 -4
  63. package/dist/storage/index.js +1 -1
  64. package/dist/subagents/index.d.ts +177 -0
  65. package/dist/subagents/index.js +78 -0
  66. package/dist/team/index.d.ts +544 -0
  67. package/dist/team/index.js +41 -0
  68. package/dist/tool/host/index.d.ts +41 -0
  69. package/dist/tool/host/index.js +10 -0
  70. package/dist/tool/index.d.ts +111 -21
  71. package/dist/tool/index.js +20 -13
  72. package/dist/{types-VQgymC1N.d.ts → types-Bj_J8u_W.d.ts} +44 -64
  73. package/dist/{types-CHiPh8U2.d.ts → types-C_LCeYNg.d.ts} +7 -7
  74. package/dist/types-RSCv7nQ4.d.ts +59 -0
  75. package/package.json +46 -47
  76. package/dist/builder-BgZ_j4Vs.d.ts +0 -35
  77. package/dist/chunk-5ARZJWD2.js +0 -259
  78. package/dist/chunk-DXFBQMXP.js +0 -53
  79. package/dist/chunk-H3FUYU52.js +0 -81
  80. package/dist/chunk-JLXG2SH7.js +0 -905
  81. package/dist/chunk-N7P4PN3O.js +0 -84
  82. package/dist/chunk-OFDKHNCX.js +0 -727
  83. package/dist/chunk-SDSBEQXG.js +0 -157
  84. package/dist/chunk-VEKUXUVF.js +0 -41
  85. package/dist/chunk-VNQBHPCT.js +0 -398
  86. package/dist/chunk-WWYYNWEW.js +0 -259
  87. package/dist/context/index.d.ts +0 -259
  88. package/dist/context/index.js +0 -26
  89. package/dist/events-CE72w8W4.d.ts +0 -149
  90. package/dist/host/index.d.ts +0 -45
  91. package/dist/host/index.js +0 -8
  92. package/dist/index-DQuTZ8xL.d.ts +0 -1335
  93. package/dist/messages-BYWGn8TY.d.ts +0 -110
  94. package/dist/presets/index.d.ts +0 -53
  95. package/dist/registry-DwYqsQkX.d.ts +0 -164
  96. package/dist/runner-CI-XeR16.d.ts +0 -91
  97. package/dist/scope/index.d.ts +0 -10
  98. package/dist/scope/index.js +0 -14
  99. package/dist/session-manager-KbYt2WUh.d.ts +0 -282
  100. package/dist/signal/index.d.ts +0 -28
  101. package/dist/signal/index.js +0 -6
  102. package/dist/sub-agent/index.d.ts +0 -24
  103. package/dist/sub-agent/index.js +0 -32
  104. package/dist/tool-CZWN3KbO.d.ts +0 -141
  105. package/dist/tool-DkhSCV2Y.d.ts +0 -145
  106. package/dist/tracker-DClqYqTj.d.ts +0 -96
  107. package/dist/tracking/index.d.ts +0 -111
  108. package/dist/tracking/index.js +0 -20
  109. package/dist/types-BfNpU8NS.d.ts +0 -270
  110. package/dist/types-BlOKk-Bb.d.ts +0 -330
  111. package/dist/types-BlZwmnuW.d.ts +0 -50
  112. package/dist/types-CQL-SvTn.d.ts +0 -29
  113. package/dist/types-CWm-7rvB.d.ts +0 -55
  114. package/dist/types-DTSkxakL.d.ts +0 -651
  115. package/dist/types-DmDwi2zI.d.ts +0 -339
  116. package/dist/types-YuWV4ag7.d.ts +0 -72
package/dist/index.d.ts CHANGED
@@ -1,83 +1,280 @@
1
- import { A as AgentConfig, a as Agent } from './index-DQuTZ8xL.js';
2
- export { b as AgentDiscoveryOptions, c as AgentDiscoveryResult, d as AgentProfile, e as AgentSource, C as CompactionConfig, D as DEFAULT_MAX_CONCURRENT, f as DEFAULT_MAX_SPAWN_DEPTH, g as DEFAULT_SESSION_TITLE_PREFIX, h as DiscoveredProfile, M as MarkdownAgentFrontmatter, i as MarkdownAgentProfile, P as PRUNE_PROTECTED_TOOLS, j as ParsedMarkdownAgent, k as ParsedToolSpec, l as ProfileResolvers, S as SubAgentCompletedResult, m as SubAgentHandle, n as SubAgentStatus, o as SubAgentToolConfig, p as SubAgentTracker, q as SubAgentUsage, T as ToolModifier, r as TracingConfig, s as createAgent, t as createSubAgentTools, u as discoverAgentProfiles, v as getProjectAgentsDir, w as getUserAgentsDir, x as isMarkdownProfile, y as parseAgentFrontmatter, z as parseMarkdownAgent, B as parseToolSpec, E as toAgentProfile } from './index-DQuTZ8xL.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-CZWN3KbO.js';
7
- export { C as CompatibleSchema, I as InferSchemaOutput, d as defineTool } from './tool-CZWN3KbO.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 } from './runner-CI-XeR16.js';
11
- import { n as InterventionController } from './types-BlOKk-Bb.js';
12
- export { A as AnyInferenceResult, a as AnyStreamResult, C as CustomStreamProvider, b as CustomStreamResult, D as DEFAULT_MAX_OUTPUT_TOKENS, c as DEFAULT_RETRY_CONFIG, d as InferenceCustomResult, e as InferenceStepInfo, I as InferenceStreamInput, f as InferenceStreamResult, L as LLMStreamInput, g as LLMStreamResult, O as OUTPUT_TOKEN_MAX, o as OnInterventionApplied, P as PendingIntervention, R as RetryConfig, h as RetryHandlerOptions, i as RetryState, S as StepInfo, T as ToolExecutionMode, j as calculateDelay, k as createRetryHandler, l as createRetryState, s as shouldRetry, m as sleep, w as withRetry } from './types-BlOKk-Bb.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-DzPiv6EK.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-DzPiv6EK.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';
13
8
  import { R as ReasoningLevel } from './types-CQaXbRsS.js';
14
9
  export { E as EXTENDED_LEVELS, F as FIXED_LEVELS, a as ReasoningConfig, S as STANDARD_LEVELS, s as shouldIncludeReasoningSummary } from './types-CQaXbRsS.js';
15
- import { ContextManager } from './context/index.js';
16
- export { ContextLimits, DEFAULT_CONTEXT_LIMITS, PruneContextOptions, PruneResult, SummarizationOptions, estimateConversationTokens, estimateMessageTokens, estimateTokens, findCutPoint, generateSummary, isContextOverflowing, pruneContext, pruneToolResults, shouldPruneContext } from './context/index.js';
17
- import { T as TurnChangeTracker } from './tracker-DClqYqTj.js';
18
- export { F as FileBaseline, a as TurnFileChange, b as TurnSummary, c as TurnTrackerConfig, U as UndoResult, d as createTurnTracker } from './tracker-DClqYqTj.js';
19
- import { P as PromptBuilder } from './builder-BgZ_j4Vs.js';
20
- export { c as createPromptBuilder } from './builder-BgZ_j4Vs.js';
21
- import { S as SessionManager } from './session-manager-KbYt2WUh.js';
22
- 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-KbYt2WUh.js';
23
- import { A as AgentEvent } from './events-CE72w8W4.js';
24
- export { a as AgentStatus, b as AgentTurnBoundaryKind, c as ApprovalEvent, P as ProcessorResult, S as StepProcessingResult, d as StreamInput } from './events-CE72w8W4.js';
25
- import { f as StreamProvider, E as EnhancedTools } from './types-DTSkxakL.js';
26
- export { A as AgentMiddleware, g as AgentModelHooks, B as BlockedModelCall, h as EnvironmentInfo, I as InstructionFile, a as ModelCallContext, M as ModelCallInput, b as ModelCallOutput, e as ModelFamily, P as PromptBuildContext, d as PromptConfig, c as PromptSection, S as StreamChunk, i as StreamProviderConfig, j as StreamProviderFactory, k as StreamProviderInput, l as StreamProviderResult, T as ToolCallDecision } from './types-DTSkxakL.js';
27
- 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-DmDwi2zI.js';
28
- export { ExecuteAgentToolCallOptions, ExecuteAgentToolCallResult, MAX_BYTES, MAX_LINES, TRUNCATE_DIR, TRUNCATE_GLOB, ToolRegistry, ToolSpec, TruncateResult, defaultRegistry, executeAgentToolCall, formatSize, normalizeToolReplayPolicy, truncateOutput } from './tool/index.js';
29
- export { AdapterSettings, CacheCapabilitySource, CapabilityCache, CapabilityOverrides, Directory, EngineSpec, ModelCapabilityResolver, Directory as ModelDirectory, Resolver as ModelResolver, 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';
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';
30
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';
31
- 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';
32
- export { createMCPManager, defineServer, httpServer, sseServer, stdioServer } from './mcp/index.js';
33
- 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';
34
- export { ApprovalMiddlewareConfig, CacheTTL, OtelMiddlewareConfig, PromptCacheConfig, TelemetryConfig, TelemetryConfigResult, approvalMiddleware, createTelemetryConfig, otelMiddleware, promptCacheMiddleware } from './middleware/index.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-CJfwfzGe.js';
18
+ export { CacheTTL, PromptCacheConfig, createTelemetryConfig, otelMiddleware, promptCacheMiddleware } from './middleware/index.js';
35
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';
36
- 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';
37
- export { A as AppliedPreset, P as Preset } from './types-BlZwmnuW.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
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 { DefinePluginInit, DiscoveredPlugin, LayeredSettings, NullSettings, PluginActivateContext, PluginCommand, PluginCompatibility, PluginContext, PluginContributions, PluginDefinition, PluginEventBus, PluginEventBusAPI, PluginEventHandler, PluginInit, PluginLifecycleHooks, PluginLoaderOptions, PluginManifest, PluginRegistry, PluginRegistryCompatibilityOptions, PluginRegistryOptions, PluginRegistryTimeoutOptions, PluginSessionContext, PluginSettingsDefinition, PluginSettingsProvider, PluginSettingsSchema, PluginUnsubscribe, StaticSettings, ValidatedSettings, definePlugin, discoverPlugins, getPluginLoader, isDefinedPlugin, loadPluginModule, resetFrameworkAliases, resetPluginLoader, resolveFrameworkAliases } from './plugin/index.js';
54
- export { F as FileOperationMeta, N as NormalizedToolReplayPolicy, T as ToolContext, a as ToolMetadata, e as ToolReplayMode, b as ToolReplayPolicy, c as ToolResult, f as ToolSideEffectLevel, d as TurnTrackerContext } from './tool-DkhSCV2Y.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';
55
34
  import 'zod';
56
35
  import '@ai-sdk/provider-utils';
57
36
  import 'jiti';
58
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;
71
+
59
72
  /**
60
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.
61
79
  */
62
80
  interface AgentState {
63
81
  model: LanguageModel;
64
- systemPrompt: string;
65
- cwd: string;
66
- isStreaming: boolean;
67
82
  /** Current reasoning level */
68
83
  reasoningLevel: ReasoningLevel;
69
- 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
+ };
70
258
  }
71
259
 
72
260
  /** Everything the chat loop needs from the Agent instance. */
73
261
  interface ChatLoopDeps {
74
262
  sessionId: string;
263
+ turnId: string;
75
264
  message: string;
76
265
  abort: AbortSignal;
77
266
  systemOverride?: string;
78
267
  sessions: SessionManager;
79
- tools: Record<string, Tool.Info>;
80
- 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;
81
278
  turnTracker: TurnChangeTracker;
82
279
  interventionCtrl: InterventionController;
83
280
  middlewareRunner: MiddlewareRunner;
@@ -86,10 +283,19 @@ interface ChatLoopDeps {
86
283
  reasoningLevel: ReasoningLevel;
87
284
  promptBuilder?: PromptBuilder;
88
285
  host: ToolHost;
286
+ humanInputController?: HumanInputController;
89
287
  mcpTools: Record<string, Tool$1>;
90
288
  telemetrySettings?: TelemetrySettings;
91
289
  toModelMessages: (messages: Message[]) => ModelMessage[];
92
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;
93
299
  }
94
300
 
95
301
  /**
@@ -98,93 +304,261 @@ interface ChatLoopDeps {
98
304
  */
99
305
  declare function runChatLoop(deps: ChatLoopDeps): AsyncGenerator<AgentEvent>;
100
306
 
101
- /**
102
- * Concurrent sub-agent execution.
103
- */
307
+ declare function ensureSessionLoaded(options: {
308
+ sessionId: string;
309
+ sessions: SessionManager;
310
+ cwd: string;
311
+ }): Promise<void>;
104
312
 
105
313
  /**
106
- * 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.
107
330
  */
108
- interface SubAgentResult {
109
- /** Final response text */
110
- response: string;
111
- /** Sub-agent session ID */
112
- sessionId: string;
113
- /** Token usage */
114
- usage: TokenUsage;
115
- /** Tool calls made */
116
- toolCalls: Array<{
117
- name: string;
118
- result: unknown;
119
- }>;
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;
120
374
  }
121
375
  /**
122
- * Run multiple sub-agent tasks concurrently.
123
- *
124
- * Useful for parallelizing independent research or analysis tasks.
125
- * Results are returned in the same order as tasks.
376
+ * Create a stateless event handler for printing `AgentEvent`s to the
377
+ * terminal.
126
378
  *
127
- * Distinct sub-agent sessions can run in parallel safely. Turns targeting the
128
- * same session are serialized to preserve history order.
379
+ * @param options - Fine-tune which event categories are rendered.
380
+ * @returns A function that accepts one `AgentEvent` and writes to stdout/stderr.
129
381
  *
130
382
  * @example
131
- * ```typescript
132
- * const explorer = agent.fork({ name: "explore", ... });
383
+ * ```ts
384
+ * import { createAgent, createEventPrinter } from "@cuylabs/agent-core";
385
+ *
386
+ * const agent = createAgent({ model, systemPrompt: "Be concise." });
387
+ * const print = createEventPrinter();
133
388
  *
134
- * const results = await runConcurrent([
135
- * { agent: explorer, message: "Find all API endpoints" },
136
- * { agent: explorer, message: "Find all database queries" },
137
- * { agent: explorer, message: "Find all auth middleware" },
138
- * ], { maxConcurrency: 3 });
389
+ * for await (const event of agent.chat("demo", "Hello")) {
390
+ * print(event);
391
+ * }
392
+ * ```
393
+ *
394
+ * @example
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
+ * });
139
403
  * ```
140
404
  */
141
- declare function runConcurrent(tasks: Array<{
142
- agent: Agent;
143
- message: string;
144
- parentSessionId?: string;
145
- title?: string;
146
- }>, options?: {
147
- /** Maximum concurrent tasks (default: 5) */
148
- maxConcurrency?: number;
149
- /** Abort signal for all tasks */
150
- abort?: AbortSignal;
151
- }): Promise<SubAgentResult[]>;
405
+ declare function createEventPrinter(options?: EventPrinterOptions): (event: AgentEvent) => void;
152
406
 
153
407
  /**
154
- * Agent defaults constants used by the Agent constructor.
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.
155
412
  */
413
+ declare function autoDetectStreamProvider(model: LanguageModel, tools: unknown, explicitProvider: unknown): StreamProvider | undefined;
414
+
156
415
  /**
157
- * Generic fallback system prompt.
416
+ * Shared intervention/follow-up types for @cuylabs/agent-core.
158
417
  *
159
- * Only used when the consumer provides a flat `systemPrompt` string
160
- * without any value (i.e. the field exists but is empty/undefined).
161
- * When the prompt pipeline is active, this is never used.
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
162
422
  *
163
- * Domain-specific prompts (coding, browsing, etc.) belong in
164
- * consumer packages like agent-code, not here.
423
+ * The `InterventionController` remains the in-process implementation;
424
+ * these types are the protocol-level representation for cross-process
425
+ * and durable scenarios.
165
426
  */
166
- 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.";
167
- /** Default max steps */
168
- declare const DEFAULT_MAX_STEPS = 50;
169
- /** Default max output tokens */
170
- declare const DEFAULT_MAX_TOKENS = 32000;
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.
450
+ */
451
+ interface SteeringResponse {
452
+ /** The steering request ID */
453
+ id: string;
454
+ /** Whether the message was accepted */
455
+ accepted: boolean;
456
+ }
457
+ /**
458
+ * A deferred follow-up request surfaced to runtime consumers.
459
+ *
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.
477
+ *
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.
481
+ */
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>;
171
533
 
172
534
  /**
173
- * Check if a model requires a custom stream provider.
535
+ * Extract file paths from tool arguments based on metadata.
174
536
  */
175
- declare function needsCustomStreamProvider(model: LanguageModel, customPatterns?: string[]): boolean;
537
+ declare function extractFilePathsFromArgs(args: Record<string, unknown>, meta: FileOperationMeta): string[];
176
538
  /**
177
- * Check if tools array has stream provider factory attached.
539
+ * Check whether a tool operation should trigger baseline capture.
178
540
  */
179
- declare function hasStreamProviderFactory(tools: unknown): tools is EnhancedTools & {
180
- __streamProviderFactory: NonNullable<EnhancedTools["__streamProviderFactory"]>;
181
- };
541
+ declare function shouldCaptureBaseline(meta: FileOperationMeta): boolean;
542
+
182
543
  /**
183
- * Auto-detect and configure stream provider from model and tools.
544
+ * LocalSignal in-process event dispatch.
184
545
  *
185
- * Returns the configured stream provider, or undefined if standard
186
- * 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.
187
551
  */
188
- declare function autoDetectStreamProvider(model: LanguageModel, tools: unknown, explicitProvider: unknown): StreamProvider | undefined;
189
552
 
190
- 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 };