@animus-labs/cortex 0.2.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 (293) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +73 -0
  3. package/dist/budget-guard.d.ts +75 -0
  4. package/dist/budget-guard.d.ts.map +1 -0
  5. package/dist/budget-guard.js +142 -0
  6. package/dist/budget-guard.js.map +1 -0
  7. package/dist/compaction/compaction.d.ts +99 -0
  8. package/dist/compaction/compaction.d.ts.map +1 -0
  9. package/dist/compaction/compaction.js +302 -0
  10. package/dist/compaction/compaction.js.map +1 -0
  11. package/dist/compaction/failsafe.d.ts +57 -0
  12. package/dist/compaction/failsafe.d.ts.map +1 -0
  13. package/dist/compaction/failsafe.js +135 -0
  14. package/dist/compaction/failsafe.js.map +1 -0
  15. package/dist/compaction/index.d.ts +381 -0
  16. package/dist/compaction/index.d.ts.map +1 -0
  17. package/dist/compaction/index.js +979 -0
  18. package/dist/compaction/index.js.map +1 -0
  19. package/dist/compaction/microcompaction.d.ts +219 -0
  20. package/dist/compaction/microcompaction.d.ts.map +1 -0
  21. package/dist/compaction/microcompaction.js +536 -0
  22. package/dist/compaction/microcompaction.js.map +1 -0
  23. package/dist/compaction/observational/buffering.d.ts +225 -0
  24. package/dist/compaction/observational/buffering.d.ts.map +1 -0
  25. package/dist/compaction/observational/buffering.js +354 -0
  26. package/dist/compaction/observational/buffering.js.map +1 -0
  27. package/dist/compaction/observational/constants.d.ts +70 -0
  28. package/dist/compaction/observational/constants.d.ts.map +1 -0
  29. package/dist/compaction/observational/constants.js +507 -0
  30. package/dist/compaction/observational/constants.js.map +1 -0
  31. package/dist/compaction/observational/index.d.ts +219 -0
  32. package/dist/compaction/observational/index.d.ts.map +1 -0
  33. package/dist/compaction/observational/index.js +641 -0
  34. package/dist/compaction/observational/index.js.map +1 -0
  35. package/dist/compaction/observational/observer.d.ts +97 -0
  36. package/dist/compaction/observational/observer.d.ts.map +1 -0
  37. package/dist/compaction/observational/observer.js +424 -0
  38. package/dist/compaction/observational/observer.js.map +1 -0
  39. package/dist/compaction/observational/recall-tool.d.ts +27 -0
  40. package/dist/compaction/observational/recall-tool.d.ts.map +1 -0
  41. package/dist/compaction/observational/recall-tool.js +93 -0
  42. package/dist/compaction/observational/recall-tool.js.map +1 -0
  43. package/dist/compaction/observational/reflector.d.ts +94 -0
  44. package/dist/compaction/observational/reflector.d.ts.map +1 -0
  45. package/dist/compaction/observational/reflector.js +167 -0
  46. package/dist/compaction/observational/reflector.js.map +1 -0
  47. package/dist/compaction/observational/types.d.ts +271 -0
  48. package/dist/compaction/observational/types.d.ts.map +1 -0
  49. package/dist/compaction/observational/types.js +15 -0
  50. package/dist/compaction/observational/types.js.map +1 -0
  51. package/dist/context-manager.d.ts +134 -0
  52. package/dist/context-manager.d.ts.map +1 -0
  53. package/dist/context-manager.js +170 -0
  54. package/dist/context-manager.js.map +1 -0
  55. package/dist/cortex-agent.d.ts +1020 -0
  56. package/dist/cortex-agent.d.ts.map +1 -0
  57. package/dist/cortex-agent.js +3589 -0
  58. package/dist/cortex-agent.js.map +1 -0
  59. package/dist/error-classifier.d.ts +48 -0
  60. package/dist/error-classifier.d.ts.map +1 -0
  61. package/dist/error-classifier.js +152 -0
  62. package/dist/error-classifier.js.map +1 -0
  63. package/dist/event-bridge.d.ts +166 -0
  64. package/dist/event-bridge.d.ts.map +1 -0
  65. package/dist/event-bridge.js +381 -0
  66. package/dist/event-bridge.js.map +1 -0
  67. package/dist/index.d.ts +55 -0
  68. package/dist/index.d.ts.map +1 -0
  69. package/dist/index.js +57 -0
  70. package/dist/index.js.map +1 -0
  71. package/dist/mcp-client.d.ts +119 -0
  72. package/dist/mcp-client.d.ts.map +1 -0
  73. package/dist/mcp-client.js +474 -0
  74. package/dist/mcp-client.js.map +1 -0
  75. package/dist/model-wrapper.d.ts +58 -0
  76. package/dist/model-wrapper.d.ts.map +1 -0
  77. package/dist/model-wrapper.js +86 -0
  78. package/dist/model-wrapper.js.map +1 -0
  79. package/dist/noop-logger.d.ts +4 -0
  80. package/dist/noop-logger.d.ts.map +1 -0
  81. package/dist/noop-logger.js +8 -0
  82. package/dist/noop-logger.js.map +1 -0
  83. package/dist/prompt-diagnostics.d.ts +47 -0
  84. package/dist/prompt-diagnostics.d.ts.map +1 -0
  85. package/dist/prompt-diagnostics.js +230 -0
  86. package/dist/prompt-diagnostics.js.map +1 -0
  87. package/dist/provider-manager.d.ts +224 -0
  88. package/dist/provider-manager.d.ts.map +1 -0
  89. package/dist/provider-manager.js +563 -0
  90. package/dist/provider-manager.js.map +1 -0
  91. package/dist/provider-registry.d.ts +115 -0
  92. package/dist/provider-registry.d.ts.map +1 -0
  93. package/dist/provider-registry.js +305 -0
  94. package/dist/provider-registry.js.map +1 -0
  95. package/dist/schema-converter.d.ts +20 -0
  96. package/dist/schema-converter.d.ts.map +1 -0
  97. package/dist/schema-converter.js +48 -0
  98. package/dist/schema-converter.js.map +1 -0
  99. package/dist/skill-preprocessor.d.ts +46 -0
  100. package/dist/skill-preprocessor.d.ts.map +1 -0
  101. package/dist/skill-preprocessor.js +237 -0
  102. package/dist/skill-preprocessor.js.map +1 -0
  103. package/dist/skill-registry.d.ts +107 -0
  104. package/dist/skill-registry.d.ts.map +1 -0
  105. package/dist/skill-registry.js +330 -0
  106. package/dist/skill-registry.js.map +1 -0
  107. package/dist/skill-tool.d.ts +54 -0
  108. package/dist/skill-tool.d.ts.map +1 -0
  109. package/dist/skill-tool.js +88 -0
  110. package/dist/skill-tool.js.map +1 -0
  111. package/dist/sub-agent-manager.d.ts +90 -0
  112. package/dist/sub-agent-manager.d.ts.map +1 -0
  113. package/dist/sub-agent-manager.js +192 -0
  114. package/dist/sub-agent-manager.js.map +1 -0
  115. package/dist/token-estimator.d.ts +23 -0
  116. package/dist/token-estimator.d.ts.map +1 -0
  117. package/dist/token-estimator.js +27 -0
  118. package/dist/token-estimator.js.map +1 -0
  119. package/dist/tool-contract.d.ts +68 -0
  120. package/dist/tool-contract.d.ts.map +1 -0
  121. package/dist/tool-contract.js +35 -0
  122. package/dist/tool-contract.js.map +1 -0
  123. package/dist/tool-result-persistence.d.ts +89 -0
  124. package/dist/tool-result-persistence.d.ts.map +1 -0
  125. package/dist/tool-result-persistence.js +152 -0
  126. package/dist/tool-result-persistence.js.map +1 -0
  127. package/dist/tools/bash/index.d.ts +71 -0
  128. package/dist/tools/bash/index.d.ts.map +1 -0
  129. package/dist/tools/bash/index.js +485 -0
  130. package/dist/tools/bash/index.js.map +1 -0
  131. package/dist/tools/bash/interactive.d.ts +47 -0
  132. package/dist/tools/bash/interactive.d.ts.map +1 -0
  133. package/dist/tools/bash/interactive.js +262 -0
  134. package/dist/tools/bash/interactive.js.map +1 -0
  135. package/dist/tools/bash/safety.d.ts +149 -0
  136. package/dist/tools/bash/safety.d.ts.map +1 -0
  137. package/dist/tools/bash/safety.js +1116 -0
  138. package/dist/tools/bash/safety.js.map +1 -0
  139. package/dist/tools/edit.d.ts +57 -0
  140. package/dist/tools/edit.d.ts.map +1 -0
  141. package/dist/tools/edit.js +310 -0
  142. package/dist/tools/edit.js.map +1 -0
  143. package/dist/tools/glob.d.ts +34 -0
  144. package/dist/tools/glob.d.ts.map +1 -0
  145. package/dist/tools/glob.js +268 -0
  146. package/dist/tools/glob.js.map +1 -0
  147. package/dist/tools/grep.d.ts +53 -0
  148. package/dist/tools/grep.d.ts.map +1 -0
  149. package/dist/tools/grep.js +673 -0
  150. package/dist/tools/grep.js.map +1 -0
  151. package/dist/tools/index.d.ts +62 -0
  152. package/dist/tools/index.d.ts.map +1 -0
  153. package/dist/tools/index.js +52 -0
  154. package/dist/tools/index.js.map +1 -0
  155. package/dist/tools/read.d.ts +43 -0
  156. package/dist/tools/read.d.ts.map +1 -0
  157. package/dist/tools/read.js +459 -0
  158. package/dist/tools/read.js.map +1 -0
  159. package/dist/tools/runtime.d.ts +62 -0
  160. package/dist/tools/runtime.d.ts.map +1 -0
  161. package/dist/tools/runtime.js +116 -0
  162. package/dist/tools/runtime.js.map +1 -0
  163. package/dist/tools/shared/cwd-tracker.d.ts +32 -0
  164. package/dist/tools/shared/cwd-tracker.d.ts.map +1 -0
  165. package/dist/tools/shared/cwd-tracker.js +44 -0
  166. package/dist/tools/shared/cwd-tracker.js.map +1 -0
  167. package/dist/tools/shared/edit-history.d.ts +55 -0
  168. package/dist/tools/shared/edit-history.d.ts.map +1 -0
  169. package/dist/tools/shared/edit-history.js +72 -0
  170. package/dist/tools/shared/edit-history.js.map +1 -0
  171. package/dist/tools/shared/edit-matcher.d.ts +83 -0
  172. package/dist/tools/shared/edit-matcher.d.ts.map +1 -0
  173. package/dist/tools/shared/edit-matcher.js +359 -0
  174. package/dist/tools/shared/edit-matcher.js.map +1 -0
  175. package/dist/tools/shared/file-mutation-lock.d.ts +22 -0
  176. package/dist/tools/shared/file-mutation-lock.d.ts.map +1 -0
  177. package/dist/tools/shared/file-mutation-lock.js +35 -0
  178. package/dist/tools/shared/file-mutation-lock.js.map +1 -0
  179. package/dist/tools/shared/gitignore.d.ts +17 -0
  180. package/dist/tools/shared/gitignore.d.ts.map +1 -0
  181. package/dist/tools/shared/gitignore.js +59 -0
  182. package/dist/tools/shared/gitignore.js.map +1 -0
  183. package/dist/tools/shared/pdf-extractor.d.ts +96 -0
  184. package/dist/tools/shared/pdf-extractor.d.ts.map +1 -0
  185. package/dist/tools/shared/pdf-extractor.js +196 -0
  186. package/dist/tools/shared/pdf-extractor.js.map +1 -0
  187. package/dist/tools/shared/read-registry.d.ts +66 -0
  188. package/dist/tools/shared/read-registry.d.ts.map +1 -0
  189. package/dist/tools/shared/read-registry.js +65 -0
  190. package/dist/tools/shared/read-registry.js.map +1 -0
  191. package/dist/tools/shared/safe-env.d.ts +18 -0
  192. package/dist/tools/shared/safe-env.d.ts.map +1 -0
  193. package/dist/tools/shared/safe-env.js +70 -0
  194. package/dist/tools/shared/safe-env.js.map +1 -0
  195. package/dist/tools/sub-agent.d.ts +91 -0
  196. package/dist/tools/sub-agent.d.ts.map +1 -0
  197. package/dist/tools/sub-agent.js +89 -0
  198. package/dist/tools/sub-agent.js.map +1 -0
  199. package/dist/tools/task-output.d.ts +38 -0
  200. package/dist/tools/task-output.d.ts.map +1 -0
  201. package/dist/tools/task-output.js +186 -0
  202. package/dist/tools/task-output.js.map +1 -0
  203. package/dist/tools/tool-search/index.d.ts +40 -0
  204. package/dist/tools/tool-search/index.d.ts.map +1 -0
  205. package/dist/tools/tool-search/index.js +110 -0
  206. package/dist/tools/tool-search/index.js.map +1 -0
  207. package/dist/tools/tool-search/registry.d.ts +82 -0
  208. package/dist/tools/tool-search/registry.d.ts.map +1 -0
  209. package/dist/tools/tool-search/registry.js +238 -0
  210. package/dist/tools/tool-search/registry.js.map +1 -0
  211. package/dist/tools/undo-edit.d.ts +51 -0
  212. package/dist/tools/undo-edit.d.ts.map +1 -0
  213. package/dist/tools/undo-edit.js +231 -0
  214. package/dist/tools/undo-edit.js.map +1 -0
  215. package/dist/tools/web-fetch/cache.d.ts +49 -0
  216. package/dist/tools/web-fetch/cache.d.ts.map +1 -0
  217. package/dist/tools/web-fetch/cache.js +89 -0
  218. package/dist/tools/web-fetch/cache.js.map +1 -0
  219. package/dist/tools/web-fetch/index.d.ts +53 -0
  220. package/dist/tools/web-fetch/index.d.ts.map +1 -0
  221. package/dist/tools/web-fetch/index.js +513 -0
  222. package/dist/tools/web-fetch/index.js.map +1 -0
  223. package/dist/tools/write.d.ts +59 -0
  224. package/dist/tools/write.d.ts.map +1 -0
  225. package/dist/tools/write.js +316 -0
  226. package/dist/tools/write.js.map +1 -0
  227. package/dist/types.d.ts +881 -0
  228. package/dist/types.d.ts.map +1 -0
  229. package/dist/types.js +16 -0
  230. package/dist/types.js.map +1 -0
  231. package/dist/working-tags.d.ts +44 -0
  232. package/dist/working-tags.d.ts.map +1 -0
  233. package/dist/working-tags.js +103 -0
  234. package/dist/working-tags.js.map +1 -0
  235. package/package.json +87 -0
  236. package/src/budget-guard.ts +170 -0
  237. package/src/compaction/compaction.ts +386 -0
  238. package/src/compaction/failsafe.ts +185 -0
  239. package/src/compaction/index.ts +1199 -0
  240. package/src/compaction/microcompaction.ts +709 -0
  241. package/src/compaction/observational/buffering.ts +430 -0
  242. package/src/compaction/observational/constants.ts +532 -0
  243. package/src/compaction/observational/index.ts +837 -0
  244. package/src/compaction/observational/observer.ts +510 -0
  245. package/src/compaction/observational/recall-tool.ts +130 -0
  246. package/src/compaction/observational/reflector.ts +221 -0
  247. package/src/compaction/observational/types.ts +343 -0
  248. package/src/context-manager.ts +237 -0
  249. package/src/cortex-agent.ts +4297 -0
  250. package/src/error-classifier.ts +199 -0
  251. package/src/event-bridge.ts +508 -0
  252. package/src/index.ts +292 -0
  253. package/src/mcp-client.ts +582 -0
  254. package/src/model-wrapper.ts +128 -0
  255. package/src/noop-logger.ts +9 -0
  256. package/src/prompt-diagnostics.ts +296 -0
  257. package/src/provider-manager.ts +823 -0
  258. package/src/provider-registry.ts +386 -0
  259. package/src/schema-converter.ts +51 -0
  260. package/src/skill-preprocessor.ts +314 -0
  261. package/src/skill-registry.ts +378 -0
  262. package/src/skill-tool.ts +130 -0
  263. package/src/sub-agent-manager.ts +236 -0
  264. package/src/token-estimator.ts +26 -0
  265. package/src/tool-contract.ts +113 -0
  266. package/src/tool-result-persistence.ts +197 -0
  267. package/src/tools/bash/index.ts +633 -0
  268. package/src/tools/bash/interactive.ts +302 -0
  269. package/src/tools/bash/safety.ts +1297 -0
  270. package/src/tools/edit.ts +422 -0
  271. package/src/tools/glob.ts +330 -0
  272. package/src/tools/grep.ts +819 -0
  273. package/src/tools/index.ts +110 -0
  274. package/src/tools/read.ts +580 -0
  275. package/src/tools/runtime.ts +173 -0
  276. package/src/tools/shared/cwd-tracker.ts +50 -0
  277. package/src/tools/shared/edit-history.ts +96 -0
  278. package/src/tools/shared/edit-matcher.ts +457 -0
  279. package/src/tools/shared/file-mutation-lock.ts +40 -0
  280. package/src/tools/shared/gitignore.ts +61 -0
  281. package/src/tools/shared/pdf-extractor.ts +290 -0
  282. package/src/tools/shared/read-registry.ts +93 -0
  283. package/src/tools/shared/safe-env.ts +82 -0
  284. package/src/tools/sub-agent.ts +171 -0
  285. package/src/tools/task-output.ts +236 -0
  286. package/src/tools/tool-search/index.ts +167 -0
  287. package/src/tools/tool-search/registry.ts +278 -0
  288. package/src/tools/undo-edit.ts +314 -0
  289. package/src/tools/web-fetch/cache.ts +112 -0
  290. package/src/tools/web-fetch/index.ts +604 -0
  291. package/src/tools/write.ts +385 -0
  292. package/src/types.ts +1057 -0
  293. package/src/working-tags.ts +118 -0
@@ -0,0 +1,881 @@
1
+ /**
2
+ * Core types for the @animus-labs/cortex package.
3
+ *
4
+ * These types define the public API surface for CortexAgent configuration,
5
+ * context management, error classification, working tags, budget guards,
6
+ * compaction, events, and model tiers.
7
+ *
8
+ * References:
9
+ * - cortex-architecture.md
10
+ * - context-manager.md
11
+ * - model-tiers.md
12
+ * - error-recovery.md
13
+ * - working-tags.md
14
+ */
15
+ import type { CortexModel } from './model-wrapper.js';
16
+ import type { ObservationalMemoryConfig, ObservationEvent, ReflectionEvent } from './compaction/observational/types.js';
17
+ /**
18
+ * Pluggable logger interface for Cortex diagnostics.
19
+ *
20
+ * Cortex never decides where logs go. The consumer provides an implementation
21
+ * via CortexAgentConfig.logger. If omitted, all logging is silently discarded.
22
+ *
23
+ * All methods share the same signature for uniformity. The optional `data`
24
+ * parameter carries structured context (token counts, server names, error
25
+ * objects, etc.) that the consumer can serialize or inspect as needed.
26
+ *
27
+ * Compatible with `console` for quick development: `logger: console` works
28
+ * because console methods accept variadic args and ignore the extra object.
29
+ */
30
+ export interface CortexLogger {
31
+ debug(message: string, data?: Record<string, unknown>): void;
32
+ info(message: string, data?: Record<string, unknown>): void;
33
+ warn(message: string, data?: Record<string, unknown>): void;
34
+ error(message: string, data?: Record<string, unknown>): void;
35
+ }
36
+ /**
37
+ * Token usage and cost data from a single LLM call.
38
+ * Mirrors the pi-ai AssistantMessage.usage structure but is decoupled
39
+ * from pi-ai's types to avoid hard runtime dependencies.
40
+ */
41
+ export interface CortexUsage {
42
+ /** Input (prompt) tokens. */
43
+ input: number;
44
+ /** Output (completion) tokens. */
45
+ output: number;
46
+ /** Cache-read tokens (tokens served from cache). */
47
+ cacheRead: number;
48
+ /** Cache-write tokens (tokens written to cache). */
49
+ cacheWrite: number;
50
+ /** Total tokens (input + output). */
51
+ totalTokens: number;
52
+ /** Cost breakdown in USD. */
53
+ cost: {
54
+ input: number;
55
+ output: number;
56
+ cacheRead: number;
57
+ cacheWrite: number;
58
+ total: number;
59
+ };
60
+ /** Model identifier string (if available from the response). */
61
+ model?: string;
62
+ }
63
+ /**
64
+ * Accumulated usage data across the lifetime of a session.
65
+ *
66
+ * Unlike BudgetGuard (which resets per agentic loop for enforcement),
67
+ * SessionUsage accumulates across all loops for reporting and persistence.
68
+ * Cortex tracks this in memory; consumers persist and restore as needed.
69
+ */
70
+ export interface SessionUsage {
71
+ /** Total cost in USD across all turns. */
72
+ totalCost: number;
73
+ /** Total number of LLM turns across all loops. */
74
+ totalTurns: number;
75
+ /** Accumulated token counts across all turns. */
76
+ tokens: {
77
+ input: number;
78
+ output: number;
79
+ cacheRead: number;
80
+ cacheWrite: number;
81
+ };
82
+ }
83
+ /**
84
+ * The lifecycle state of a CortexAgent instance.
85
+ *
86
+ * CREATED -> ACTIVE -> DESTROYED
87
+ *
88
+ * abort() returns the agent to ACTIVE (still usable).
89
+ * destroy() transitions to DESTROYED (all resources released).
90
+ */
91
+ export type CortexLifecycleState = 'created' | 'active' | 'destroyed';
92
+ /**
93
+ * Consumer-facing thinking/effort level.
94
+ *
95
+ * "max" maps to pi-ai/pi-agent-core's "xhigh" internally.
96
+ * "off" disables extended thinking entirely.
97
+ */
98
+ export type ThinkingLevel = 'off' | 'minimal' | 'low' | 'medium' | 'high' | 'max';
99
+ /**
100
+ * Describes a model's thinking/reasoning capabilities.
101
+ * Returned by CortexAgent.getModelThinkingCapabilities().
102
+ */
103
+ export interface ModelThinkingCapabilities {
104
+ /** Whether the model supports extended thinking at all. */
105
+ supportsThinking: boolean;
106
+ /** Whether the model supports the "max" (xhigh) thinking level. */
107
+ supportsMax: boolean;
108
+ /** Exact thinking levels this model accepts, using Cortex's public names. */
109
+ supportedLevels: ThinkingLevel[];
110
+ }
111
+ export type CortexToolPermissionDecision = 'allow' | 'block' | 'ask';
112
+ export interface CortexToolPermissionResult {
113
+ decision: CortexToolPermissionDecision;
114
+ reason?: string;
115
+ }
116
+ /**
117
+ * Configuration for creating a CortexAgent instance.
118
+ *
119
+ * The `model` field uses CortexModel as the public boundary.
120
+ * Consumers obtain these handles from ProviderManager and pass them back to
121
+ * CortexAgent. Raw pi-ai model objects stay inside Cortex.
122
+ */
123
+ export interface CortexAgentConfig {
124
+ /** Primary model for the agentic loop, THOUGHT, REFLECT, and all consumer-facing work. */
125
+ model: CortexModel;
126
+ /**
127
+ * Initial application/base prompt.
128
+ * Cortex composes its operational sections around this prompt.
129
+ */
130
+ initialBasePrompt?: string;
131
+ /**
132
+ * Utility model for internal operations (WebFetch summarization, safety classifier).
133
+ * - `'default'`: Cortex selects from a built-in mapping based on the primary model's provider.
134
+ * - A CortexModel: explicit utility model (must be same provider as primary).
135
+ * - `undefined`: same as `'default'`.
136
+ */
137
+ utilityModel?: CortexModel | 'default';
138
+ /** Working directory for file operations (Bash, Read, Write, Edit, Glob, Grep). */
139
+ workingDirectory: string;
140
+ /**
141
+ * Callback to resolve API keys by provider name.
142
+ * Throws on failure (classified as authentication error).
143
+ * Returns the API key string on success. Must never return empty string.
144
+ */
145
+ getApiKey?: (provider: string) => Promise<string>;
146
+ /** Ordered list of context slot names. Order defines position in the message array. */
147
+ slots?: string[];
148
+ /** Working tags configuration. */
149
+ workingTags?: {
150
+ /** Whether to enable working tags. Default: true. */
151
+ enabled?: boolean;
152
+ };
153
+ /** Budget guard configuration. */
154
+ budgetGuard?: {
155
+ /** Maximum number of LLM turns before force-stopping the loop. Default: Infinity. */
156
+ maxTurns?: number;
157
+ /** Maximum cost in USD before force-stopping the loop. Default: Infinity. */
158
+ maxCost?: number;
159
+ };
160
+ /** Maximum number of concurrent sub-agents. */
161
+ maxConcurrentSubAgents?: number;
162
+ /**
163
+ * Tool execution strategy for assistant messages with multiple tool calls.
164
+ * Defaults to sequential for deterministic permission, logging, and UI order.
165
+ */
166
+ toolExecution?: 'sequential' | 'parallel';
167
+ /** WebFetch tool configuration. */
168
+ webFetch?: {
169
+ /** Maximum number of web fetches per agentic loop. */
170
+ maxPerLoop?: number;
171
+ };
172
+ /** Bash tool configuration. */
173
+ bash?: {
174
+ /** Token threshold at which Bash auto-yields control back to the agent. */
175
+ autoYieldThreshold?: number;
176
+ /** Path to the shell executable. */
177
+ shellPath?: string;
178
+ };
179
+ /**
180
+ * Disable specific built-in tools by name.
181
+ * Built-in tools (Read, Write, Edit, Glob, Grep, Bash, WebFetch, TaskOutput)
182
+ * are registered automatically. Use this to exclude tools the agent should not have.
183
+ * SubAgent and load_skill are controlled separately via enableSubAgentTool/enableLoadSkillTool.
184
+ */
185
+ disableTools?: string[];
186
+ /**
187
+ * Structured permission result for a tool call.
188
+ * - `allow`: proceed immediately
189
+ * - `block`: deny the call
190
+ * - `ask`: consumer requires approval before the call can proceed
191
+ */
192
+ resolvePermission?: (toolName: string, toolArgs: unknown) => Promise<boolean | CortexToolPermissionResult>;
193
+ /**
194
+ * Initial thinking/effort level for the agentic loop.
195
+ * Omit to use the pi-agent-core default (medium).
196
+ * "max" maps to pi-ai/pi-agent-core's "xhigh" internally.
197
+ * Consumers can use getModelThinkingCapabilities() and clampThinkingLevel()
198
+ * to avoid exposing unsupported levels.
199
+ */
200
+ thinkingLevel?: ThinkingLevel;
201
+ /**
202
+ * Limit the effective context window for compaction calculations.
203
+ * Clamped to min(limit, model.contextWindow) with a floor of MINIMUM_CONTEXT_WINDOW (16K).
204
+ * null or undefined = use the model's full context window.
205
+ */
206
+ contextWindowLimit?: number | null;
207
+ /** Compaction configuration. All layers are always active. */
208
+ compaction?: Partial<CortexCompactionConfig>;
209
+ /**
210
+ * Deferred tool loading. When enabled, tools marked for deferral are NOT
211
+ * included in the `tools` array sent on every API turn. Instead, their
212
+ * names appear in an internally-managed `_available_tools` slot, and the
213
+ * agent uses the auto-registered `ToolSearch` tool to load specific tools
214
+ * on demand.
215
+ *
216
+ * Useful when consumers connect MCP servers with many tools: schemas are
217
+ * only paid for once a tool is actually needed, instead of every turn.
218
+ */
219
+ deferredTools?: DeferredToolsConfig;
220
+ /**
221
+ * Persists oversized tool results to disk and returns the file path.
222
+ *
223
+ * When configured, large tool results (>25K tokens by default) are
224
+ * replaced in the conversation with a bookend preview (head + tail)
225
+ * plus a file reference, so the model can use the Read tool to access
226
+ * the full content on demand.
227
+ *
228
+ * Used by both the proactive tool execution interceptor and the
229
+ * reactive compaction paths (microcompaction trim, aggregate budget
230
+ * enforcement). Consumer owns the storage location and cleanup.
231
+ *
232
+ * If both this and `compaction.microcompaction.persistResult` are set,
233
+ * this top-level setting wins (and is propagated to microcompaction).
234
+ */
235
+ persistResult?: PersistResultFn;
236
+ /**
237
+ * Per-tool token threshold overrides for the result-persistence interceptor.
238
+ *
239
+ * Tools not listed here use the built-in defaults (Bash: 7,500 to keep
240
+ * verbose command output tight; everything else: 25,000).
241
+ *
242
+ * Useful for tuning specific MCP tools or custom tools whose output has
243
+ * unusual size characteristics (e.g., a tool that returns large JSON payloads
244
+ * where you want a smaller cap, or a research tool whose output you want to
245
+ * keep more of in context).
246
+ */
247
+ toolResultThresholds?: Record<string, number>;
248
+ /**
249
+ * Consumer-set environment variables that propagate to ALL subprocesses
250
+ * (Bash tool, MCP stdio servers), bypassing the security blocklist.
251
+ *
252
+ * Use case: macOS dock icon suppression requires DYLD_INSERT_LIBRARIES
253
+ * and ANIMUS_DOCK_SUPPRESS_ADDON to propagate to child processes, but
254
+ * the safe-env blocklist strips DYLD_ prefixed variables by default.
255
+ * envOverrides are merged ON TOP of the sanitized environment, restoring
256
+ * these specific variables.
257
+ */
258
+ envOverrides?: Record<string, string>;
259
+ /**
260
+ * Optional logger for Cortex internal diagnostics.
261
+ * If omitted, all internal logging is silently discarded (no-op).
262
+ * The library never decides where logs go; only the consumer does.
263
+ *
264
+ * Compatible with `console` for quick development: `{ logger: console }`.
265
+ */
266
+ logger?: CortexLogger;
267
+ /**
268
+ * Optional diagnostics for investigating prompt or provider stalls.
269
+ * All diagnostics are opt-in and should remain disabled in normal use.
270
+ */
271
+ diagnostics?: CortexDiagnosticsConfig;
272
+ }
273
+ /**
274
+ * Prompt watchdog diagnostics configuration.
275
+ *
276
+ * Emits bounded lifecycle and heartbeat logs around prompt() and abort().
277
+ * Intended for investigating freezes or hung provider calls.
278
+ */
279
+ export interface PromptWatchdogDiagnosticsConfig {
280
+ /** Whether prompt watchdog diagnostics are enabled. Default: false. */
281
+ enabled?: boolean;
282
+ /** Heartbeat interval while a prompt is in flight. Default: 1000ms. */
283
+ heartbeatIntervalMs?: number;
284
+ /** Warn if abort waits longer than this for idle. Default: 2000ms. */
285
+ abortWaitWarningMs?: number;
286
+ }
287
+ /**
288
+ * Optional diagnostics for Cortex internals.
289
+ *
290
+ * These are intentionally narrow and structured so consumers can opt into
291
+ * targeted investigations without turning normal debug logging into trace spam.
292
+ */
293
+ export interface CortexDiagnosticsConfig {
294
+ /** Prompt and abort watchdog logs for freeze investigation. */
295
+ promptWatchdog?: PromptWatchdogDiagnosticsConfig;
296
+ }
297
+ /**
298
+ * Configuration for deferred tool loading.
299
+ *
300
+ * Reference: docs/cortex/tools/tool-search.md (TBD)
301
+ */
302
+ export interface DeferredToolsConfig {
303
+ /**
304
+ * Master switch. When false (default), all tools are sent on every turn
305
+ * exactly as before. When true, tools marked for deferral are pulled out
306
+ * of the per-turn tools array and announced by name in the
307
+ * `_available_tools` slot instead.
308
+ */
309
+ enabled?: boolean;
310
+ /**
311
+ * When true (default), all MCP tools are deferred. When false, MCP tools
312
+ * are sent in full like built-ins. Has no effect when `enabled` is false.
313
+ */
314
+ deferMcp?: boolean;
315
+ /**
316
+ * Tool names that should never be deferred even if they match deferral
317
+ * criteria (overrides `shouldDefer` and `deferMcp` for the named tools).
318
+ * Use this to keep specific MCP tools always loaded.
319
+ */
320
+ alwaysLoad?: string[];
321
+ }
322
+ /**
323
+ * Configuration for the ContextManager.
324
+ *
325
+ * Slots define the ordered list of persistent content blocks at the start
326
+ * of the message array. Order determines position (first = most stable,
327
+ * best prefix cache hit rate).
328
+ */
329
+ export interface ContextManagerConfig {
330
+ /** Ordered list of slot names. */
331
+ slots: string[];
332
+ }
333
+ /**
334
+ * Error categories for classifying LLM and network errors.
335
+ * Checked in priority order (first match wins).
336
+ */
337
+ export type ErrorCategory = 'authentication' | 'rate_limit' | 'context_overflow' | 'server_error' | 'network' | 'cancelled' | 'unknown';
338
+ /**
339
+ * Error severity levels.
340
+ * - fatal: unrecoverable, stop processing (e.g., invalid API key)
341
+ * - retry: transient, can be retried (e.g., rate limit, server error, network)
342
+ * - recoverable: can be handled without retry (e.g., context overflow triggers compaction)
343
+ */
344
+ export type ErrorSeverity = 'fatal' | 'retry' | 'recoverable';
345
+ /**
346
+ * A classified error with category, severity, original message, and suggested action.
347
+ */
348
+ export interface ClassifiedError {
349
+ /** The error category determined by pattern matching. */
350
+ category: ErrorCategory;
351
+ /** The severity level for the category. */
352
+ severity: ErrorSeverity;
353
+ /** The original error message string. */
354
+ originalMessage: string;
355
+ /** Human-readable suggested action, or undefined if no action is needed. */
356
+ suggestedAction?: string;
357
+ }
358
+ /**
359
+ * Structured output from parsing working tags in agent text.
360
+ *
361
+ * Working tags separate internal reasoning (<working>...</working>) from
362
+ * user-facing communication. Both remain in conversation history; the
363
+ * difference is only in delivery.
364
+ */
365
+ export interface AgentTextOutput {
366
+ /** Text intended for the user (working tag content stripped, whitespace normalized). */
367
+ userFacing: string;
368
+ /** Content from inside <working> tags, concatenated. Null if no working tags present. */
369
+ working: string | null;
370
+ /** The original unparsed text exactly as the agent produced it. */
371
+ raw: string;
372
+ }
373
+ /**
374
+ * Structured tool result with content array and typed details.
375
+ */
376
+ export interface ToolContentDetails<T> {
377
+ content: Array<{
378
+ type: 'text';
379
+ text: string;
380
+ } | {
381
+ type: 'image';
382
+ data: string;
383
+ mimeType: string;
384
+ }>;
385
+ details: T;
386
+ }
387
+ /**
388
+ * Context passed to tool execute functions by the pi-agent-core adapter.
389
+ *
390
+ * Tools that want streaming support accept this as an optional second parameter.
391
+ * Tools that don't need it simply ignore it (backward compatible).
392
+ */
393
+ export interface ToolExecuteContext {
394
+ /** Unique identifier for this tool call. */
395
+ toolCallId: string;
396
+ /** Abort signal for cancellation. */
397
+ signal?: AbortSignal;
398
+ /**
399
+ * Callback for emitting incremental results during execution.
400
+ * Pi-agent-core emits these as tool_execution_update events.
401
+ * Useful for long-running tools (bash, sub-agents) that want to
402
+ * stream progress to the consumer's UI.
403
+ */
404
+ onUpdate?: (partialResult: ToolContentDetails<unknown>) => void;
405
+ }
406
+ /**
407
+ * Typed payload for tool_call_start events.
408
+ */
409
+ export interface ToolCallStartPayload {
410
+ toolCallId: string;
411
+ toolName: string;
412
+ args: Record<string, unknown>;
413
+ }
414
+ /**
415
+ * Typed payload for tool_call_update events.
416
+ */
417
+ export interface ToolCallUpdatePayload {
418
+ toolCallId: string;
419
+ toolName: string;
420
+ args: Record<string, unknown>;
421
+ partialResult: ToolContentDetails<unknown>;
422
+ }
423
+ /**
424
+ * Typed payload for tool_call_end events.
425
+ */
426
+ export interface ToolCallEndPayload {
427
+ toolCallId: string;
428
+ toolName: string;
429
+ result: ToolContentDetails<unknown>;
430
+ durationMs: number;
431
+ isError: boolean;
432
+ error?: string;
433
+ }
434
+ /**
435
+ * Budget guard configuration with explicit limits.
436
+ * Both default to Infinity (no enforcement).
437
+ */
438
+ export interface BudgetGuardConfig {
439
+ /** Maximum number of LLM turns. Default: Infinity. */
440
+ maxTurns: number;
441
+ /** Maximum cost in USD. Default: Infinity. */
442
+ maxCost: number;
443
+ }
444
+ /**
445
+ * Tool category for microcompaction retention decisions.
446
+ * - rereadable: agent can re-read the source (files, directories)
447
+ * - non-reproducible: output may change or cost to re-fetch (web, APIs)
448
+ * - ephemeral: stale quickly, trivially re-runnable (ls, git status)
449
+ * - computational: small results from computations, non-reproducible without re-running
450
+ */
451
+ export type ToolCategory = 'rereadable' | 'non-reproducible' | 'ephemeral' | 'computational';
452
+ /**
453
+ * Microcompaction configuration: progressive tool result trimming.
454
+ */
455
+ /**
456
+ * Callback invoked when microcompaction persists a cleared tool result to disk.
457
+ * The consumer implements the actual I/O and returns the file path.
458
+ *
459
+ * @param content - The full original tool result content
460
+ * @param metadata - Information about the result being persisted
461
+ * @returns The file path where the content was saved
462
+ */
463
+ export type PersistResultFn = (content: string, metadata: {
464
+ toolName: string;
465
+ category: ToolCategory;
466
+ /** Present when called from the proactive tool execution interceptor. */
467
+ toolCallId?: string;
468
+ /** Present when called from compaction (reactive paths). */
469
+ messageIndex?: number;
470
+ }) => Promise<string>;
471
+ export interface MicrocompactionConfig {
472
+ /** Maximum tokens for a single tool result at insertion time. Default: 50000. */
473
+ maxResultTokens: number;
474
+ /**
475
+ * Minimum context utilization ratio below which L1 never trims, even when
476
+ * the cache is cold. Prevents pointless work on nearly empty contexts.
477
+ * Default: 0.25 (25%).
478
+ */
479
+ trimFloorRatio: number;
480
+ /**
481
+ * Absolute floor for the hot zone size (in tokens). Tool results within the
482
+ * hot zone of the most recent message are never trimmed. The effective hot
483
+ * zone is `max(hotZoneMinTokens, contextWindow * hotZoneRatio)`.
484
+ * Default: 16000.
485
+ */
486
+ hotZoneMinTokens: number;
487
+ /**
488
+ * Hot zone as a fraction of the context window. Wins over the floor on
489
+ * very large windows. Default: 0.05 (5%).
490
+ */
491
+ hotZoneRatio: number;
492
+ /**
493
+ * Multiplier applied to the hot zone for non-reproducible tools. When
494
+ * undefined, resolves to 1.0 if a persistResult callback is configured
495
+ * (full content recoverable from disk) or 1.5 if not (some buffer since
496
+ * content is lost on trim).
497
+ */
498
+ extendedRetentionMultiplier?: number;
499
+ /** Bookend size at the hot zone boundary (chars per side). Default: 2000. */
500
+ bookendMaxChars: number;
501
+ /** Bookend size at the far end of the degradation span (chars per side). Default: 256. */
502
+ bookendMinChars: number;
503
+ /**
504
+ * The degradation span as a fraction of the context window. Bookend size
505
+ * interpolates linearly from bookendMaxChars to bookendMinChars across this
506
+ * span. Beyond the span, results become placeholder or clear based on tool
507
+ * category. Default: 0.40 (40%).
508
+ */
509
+ degradationSpanRatio: number;
510
+ /** Tool name to category mapping. Unregistered tools default to standard retention. */
511
+ toolCategories?: Record<string, ToolCategory>;
512
+ /**
513
+ * Callback to persist tool results to disk before destructive trim actions
514
+ * (bookend, placeholder, clear). When set, the in-context replacement
515
+ * includes a file path reference the agent can Read to recover full content.
516
+ * Only fires for non-reproducible and computational tools.
517
+ *
518
+ * Typically set at the top-level CortexAgentConfig.persistResult and
519
+ * propagated here automatically.
520
+ */
521
+ persistResult?: PersistResultFn;
522
+ /** Maximum aggregate tokens for all tool results in a single turn. Default: 150000. */
523
+ maxAggregateTurnTokens?: number;
524
+ }
525
+ /**
526
+ * Conversation summarization (Layer 2) configuration.
527
+ */
528
+ export interface CompactionConfig {
529
+ /** Context usage ratio that triggers summarization. Default: 0.70. */
530
+ threshold: number;
531
+ /** Number of recent turns preserved verbatim. Default: 6. */
532
+ preserveRecentTurns: number;
533
+ /** Custom summarization prompt. If provided, replaces the default prompt. */
534
+ customPrompt?: string;
535
+ /** Maximum Layer 2 retry attempts before falling through to Layer 3. Default: 3. */
536
+ maxRetries?: number;
537
+ /** Delay in ms between Layer 2 retry attempts. Default: 2000. */
538
+ retryDelayMs?: number;
539
+ }
540
+ /**
541
+ * Emergency truncation (Layer 3) configuration.
542
+ */
543
+ export interface FailsafeConfig {
544
+ /** Context usage ratio that triggers emergency truncation. Default: 0.90. */
545
+ threshold: number;
546
+ }
547
+ /**
548
+ * Adaptive threshold configuration for Layer 2 compaction.
549
+ *
550
+ * Adjusts the compaction trigger point based on how recently the user last
551
+ * interacted. When the user is idle (no messages for a while), the threshold
552
+ * is lowered so compaction fires earlier, reducing token costs during interval
553
+ * ticks where the agent is thinking to itself.
554
+ *
555
+ * Three windows:
556
+ * - Recent (< recentWindowMs): no threshold reduction
557
+ * - Moderate (recentWindowMs .. idleWindowMs): moderateReduction applied
558
+ * - Idle (> idleWindowMs): idleReduction applied
559
+ *
560
+ * The effective threshold is: config.compaction.threshold - reduction
561
+ */
562
+ export interface AdaptiveThresholdConfig {
563
+ /** Whether adaptive thresholds are enabled. Default: true. */
564
+ enabled: boolean;
565
+ /** Milliseconds within which interaction is considered "recent". Default: 300000 (5 min). */
566
+ recentWindowMs: number;
567
+ /** Milliseconds beyond which interaction is considered "idle". Default: 1800000 (30 min). */
568
+ idleWindowMs: number;
569
+ /** Threshold reduction when interaction is recent. Default: 0.0. */
570
+ recentReduction: number;
571
+ /** Threshold reduction when interaction is moderate. Default: 0.10. */
572
+ moderateReduction: number;
573
+ /** Threshold reduction when interaction is idle. Default: 0.20. */
574
+ idleReduction: number;
575
+ }
576
+ /**
577
+ * Full compaction configuration for CortexAgent.
578
+ *
579
+ * Supports two strategies:
580
+ * - `'observational'` (default): Observer/Reflector background compression
581
+ * replaces L1 threshold trimming and L2 summarization. L3 emergency
582
+ * truncation remains active as a safety valve.
583
+ * - `'classic'`: The existing L1 + L2 + L3 system operates unchanged.
584
+ *
585
+ * The failsafe (L3) is always active regardless of strategy.
586
+ */
587
+ export interface CortexCompactionConfig {
588
+ /**
589
+ * Compaction strategy selection.
590
+ * - `'observational'`: Background observer/reflector compression (default).
591
+ * - `'classic'`: Traditional L1 microcompaction + L2 summarization.
592
+ * @default 'observational'
593
+ */
594
+ strategy?: 'observational' | 'classic';
595
+ /** Microcompaction (L1) configuration. Used when strategy is 'classic'. */
596
+ microcompaction: MicrocompactionConfig;
597
+ /** Conversation summarization (L2) configuration. Used when strategy is 'classic'. */
598
+ compaction: CompactionConfig;
599
+ /** Emergency truncation (L3) configuration. Always active regardless of strategy. */
600
+ failsafe: FailsafeConfig;
601
+ /** Adaptive threshold configuration. Adjusts Layer 2 trigger based on interaction recency. Used when strategy is 'classic'. */
602
+ adaptive: AdaptiveThresholdConfig;
603
+ /**
604
+ * Observational memory configuration. Used when strategy is 'observational'
605
+ * (or omitted, since observational is the default).
606
+ */
607
+ observational?: Partial<ObservationalMemoryConfig>;
608
+ }
609
+ /**
610
+ * Information about the compaction target passed to onBeforeCompaction.
611
+ */
612
+ export interface CompactionTarget {
613
+ /** Number of turns that will be summarized. */
614
+ turnsToCompact: number;
615
+ /** Estimated tokens in the compaction target. */
616
+ estimatedTokens: number;
617
+ }
618
+ /**
619
+ * Result of a compaction operation.
620
+ */
621
+ export interface CompactionResult {
622
+ /** Total tokens before compaction. */
623
+ tokensBefore: number;
624
+ /** Total tokens after compaction. */
625
+ tokensAfter: number;
626
+ /** Number of conversation turns that were compacted (summarized/removed). */
627
+ turnsCompacted: number;
628
+ /** Number of conversation turns preserved after compaction. */
629
+ turnsPreserved: number;
630
+ /** Token count of the generated summary. */
631
+ summaryTokens: number;
632
+ /**
633
+ * ISO timestamp of the oldest preserved turn, or null if no timestamp
634
+ * could be determined. The consumer (backend) should use
635
+ * `oldestPreservedIndex` to map back to a database timestamp when
636
+ * this is null.
637
+ */
638
+ oldestPreservedTimestamp: string | null;
639
+ /**
640
+ * Index of the oldest preserved turn in the original (pre-compaction)
641
+ * conversation history. The consumer can map this index back to a
642
+ * database timestamp via messages.db. Always present and accurate.
643
+ */
644
+ oldestPreservedIndex: number;
645
+ /** The generated summary text. */
646
+ summary: string;
647
+ }
648
+ /**
649
+ * Info passed to onCompactionDegraded when Layer 2 failed and Layer 3 was used.
650
+ */
651
+ export interface CompactionDegradedInfo {
652
+ /** Number of consecutive Layer 2 failures (including this episode). */
653
+ layer2Failures: number;
654
+ /** Number of turns dropped by emergency truncation. */
655
+ turnsDropped: number;
656
+ }
657
+ /**
658
+ * Info passed to onCompactionExhausted when all compaction layers have failed.
659
+ */
660
+ export interface CompactionExhaustedInfo {
661
+ /** The error from the last Layer 2 attempt. */
662
+ error: Error;
663
+ /** Number of consecutive Layer 2 failures. */
664
+ layer2Failures: number;
665
+ }
666
+ /**
667
+ * Event handlers emitted by CortexAgent during the agentic loop lifecycle.
668
+ */
669
+ export interface CortexEvents {
670
+ /** Fired when the full agentic loop finishes (agent_end, not turn_end). */
671
+ onLoopComplete: () => void;
672
+ /** Fired before compaction starts. Awaited. Consumer should flush state. */
673
+ onBeforeCompaction: (target: CompactionTarget) => Promise<void>;
674
+ /** Fired after compaction completes. Consumer can re-seed messages, update state. */
675
+ onPostCompaction: (result: CompactionResult) => void;
676
+ /** Fired when context compaction fails. */
677
+ onCompactionError: (error: Error) => void;
678
+ /** Fired when Layer 2 compaction failed and Layer 3 (emergency truncation) was used as fallback. */
679
+ onCompactionDegraded: (info: CompactionDegradedInfo) => void;
680
+ /** Fired when all compaction layers have failed. Consumer should take recovery action. */
681
+ onCompactionExhausted: (info: CompactionExhaustedInfo) => void;
682
+ /** Fired when an error is classified during the agentic loop. */
683
+ onError: (error: ClassifiedError) => void;
684
+ /** Fired at the end of each turn with parsed working tag output. */
685
+ onTurnComplete: (output: AgentTextOutput) => void;
686
+ /** Fired when a sub-agent is spawned for delegated work. */
687
+ onSubAgentSpawned: (taskId: string, instructions: string, background: boolean) => void;
688
+ /** Fired when a sub-agent completes successfully. */
689
+ onSubAgentCompleted: (taskId: string, result: string, status: string, usage: unknown) => void;
690
+ /** Fired when a sub-agent fails. */
691
+ onSubAgentFailed: (taskId: string, error: string) => void;
692
+ /** Fired when observational memory activates (messages compressed and removed). Only fires when strategy is 'observational'. */
693
+ onObservation: (event: ObservationEvent) => void;
694
+ /** Fired when the reflector condenses observations. Only fires when strategy is 'observational'. */
695
+ onReflection: (event: ReflectionEvent) => void;
696
+ }
697
+ /**
698
+ * Transport configuration for connecting to an MCP server.
699
+ * Either stdio (spawn subprocess) or HTTP (connect to running server).
700
+ */
701
+ export type McpTransportConfig = McpStdioConfig | McpHttpConfig;
702
+ /**
703
+ * Stdio transport: spawn a subprocess and communicate via stdin/stdout.
704
+ */
705
+ export interface McpStdioConfig {
706
+ transport: 'stdio';
707
+ /** The executable to run (e.g., 'node', '/path/to/tsx'). */
708
+ command: string;
709
+ /** Command line arguments. */
710
+ args?: string[];
711
+ /** Environment variables for the subprocess. */
712
+ env?: Record<string, string>;
713
+ /** Working directory for the subprocess. */
714
+ cwd?: string;
715
+ }
716
+ /**
717
+ * HTTP transport: connect to an already-running MCP server via Streamable HTTP.
718
+ */
719
+ export interface McpHttpConfig {
720
+ transport: 'http';
721
+ /** The URL of the MCP server endpoint. */
722
+ url: string;
723
+ /** Optional HTTP headers (e.g., for authentication). */
724
+ headers?: Record<string, string>;
725
+ }
726
+ /**
727
+ * State of a single MCP server connection.
728
+ */
729
+ export interface McpConnectionState {
730
+ /** The server name used for namespacing tools. */
731
+ serverName: string;
732
+ /** Transport configuration used for this connection. */
733
+ config: McpTransportConfig;
734
+ /** Whether the connection is currently active. */
735
+ connected: boolean;
736
+ /** Number of reconnect attempts since last successful connection. */
737
+ reconnectAttempts: number;
738
+ /** Names of tools discovered from this server (namespaced). */
739
+ toolNames: string[];
740
+ }
741
+ /**
742
+ * Default utility model mapping per provider.
743
+ * Keys are provider names, values are model IDs.
744
+ */
745
+ export interface UtilityModelDefaults {
746
+ [provider: string]: string;
747
+ }
748
+ /**
749
+ * Configuration for registering a skill with the SkillRegistry.
750
+ * The consumer provides these at startup and dynamically as plugins install/uninstall.
751
+ */
752
+ export interface SkillConfig {
753
+ /** Absolute path to the SKILL.md file. */
754
+ path: string;
755
+ /** Where this skill came from. Used for display and debugging. */
756
+ source: string;
757
+ /**
758
+ * Per-skill variables for ${VAR} substitution in the SKILL.md body.
759
+ * Merged into the preprocessor variables when getSkillBody() runs.
760
+ * Useful for plugin skills that reference ${PLUGIN_ROOT}.
761
+ */
762
+ variables?: Record<string, string>;
763
+ }
764
+ /**
765
+ * Internal skill index entry built from parsing a SKILL.md file.
766
+ */
767
+ export interface SkillEntry {
768
+ /** Skill name from frontmatter (kebab-case). */
769
+ name: string;
770
+ /** Skill description from frontmatter (for agent activation). */
771
+ description: string;
772
+ /** Absolute path to the SKILL.md file. */
773
+ path: string;
774
+ /** Absolute path to the skill directory (parent of SKILL.md). */
775
+ dir: string;
776
+ /** Source identifier from SkillConfig. */
777
+ source: string;
778
+ /** Full parsed YAML frontmatter (preserved for forward compatibility). */
779
+ frontmatter: Record<string, unknown>;
780
+ /** Whether the agent can auto-load this skill. Derived from disable-model-invocation. */
781
+ modelInvocable: boolean;
782
+ /** Per-skill variables for ${VAR} substitution. */
783
+ variables?: Record<string, string>;
784
+ }
785
+ /**
786
+ * A loaded skill in the skill buffer (preprocessed body ready for injection).
787
+ */
788
+ export interface LoadedSkill {
789
+ /** The skill name. */
790
+ name: string;
791
+ /** The preprocessed SKILL.md body content. */
792
+ content: string;
793
+ }
794
+ /**
795
+ * Context object passed to skill preprocessor scripts (!{script: path}).
796
+ * Cortex owns the built-in fields; the consumer provides everything else.
797
+ */
798
+ export interface CortexScriptContext {
799
+ /** Absolute path to the skill's directory. */
800
+ skillDir: string;
801
+ /** Arguments passed to the skill (split by whitespace). */
802
+ args: string[];
803
+ /** Raw arguments string. */
804
+ rawArgs: string;
805
+ /** Additional key-value pairs from !{script: path, key: value} syntax. */
806
+ scriptArgs: Record<string, string>;
807
+ /** Consumer-provided context fields (Cortex does not inspect these). */
808
+ [key: string]: unknown;
809
+ }
810
+ /**
811
+ * Configuration for spawning a sub-agent via the SubAgent tool.
812
+ */
813
+ export interface SubAgentSpawnConfig {
814
+ /** What the sub-agent should do. Becomes the initial prompt. */
815
+ instructions: string;
816
+ /** Tool names to make available. Default: inherits parent's tools. */
817
+ tools?: string[];
818
+ /** Custom system prompt. Default: inherits parent's system prompt. */
819
+ systemPrompt?: string;
820
+ /** Maximum LLM turns. Default: inherits parent's budget guard config. */
821
+ maxTurns?: number;
822
+ /** Maximum cost in USD. Default: inherits parent's budget guard config. */
823
+ maxCost?: number;
824
+ /** Run asynchronously. Default: false (blocks until complete). */
825
+ background?: boolean;
826
+ }
827
+ /**
828
+ * Result returned by a completed sub-agent.
829
+ */
830
+ export interface SubAgentResult {
831
+ /** The sub-agent's final text output. */
832
+ output: string;
833
+ /** Completion status. */
834
+ status: 'completed' | 'failed' | 'timed_out' | 'cancelled';
835
+ /** Usage summary. */
836
+ usage: {
837
+ turns: number;
838
+ cost: number;
839
+ durationMs: number;
840
+ contextTokens: number;
841
+ };
842
+ /** Summary of tool calls made by the sub-agent (extracted from conversation history on completion). */
843
+ toolCalls?: Array<{
844
+ name: string;
845
+ durationMs: number;
846
+ error?: string;
847
+ }>;
848
+ }
849
+ /**
850
+ * Tracked sub-agent record managed by SubAgentManager.
851
+ */
852
+ export interface TrackedSubAgent {
853
+ /** Unique task identifier. */
854
+ taskId: string;
855
+ /** The sub-agent CortexAgent instance. */
856
+ agent: unknown;
857
+ /** The instructions the sub-agent was spawned with. */
858
+ instructions: string;
859
+ /** Whether this is a background sub-agent. */
860
+ background: boolean;
861
+ /** Spawn timestamp. */
862
+ spawnedAt: number;
863
+ /** Promise that resolves when the sub-agent completes. */
864
+ completion: Promise<SubAgentResult>;
865
+ /** Resolve function for the completion promise. */
866
+ resolve: (result: SubAgentResult) => void;
867
+ /** Number of tool calls executed so far. */
868
+ toolCount: number;
869
+ /** Name of the most recently started tool. */
870
+ lastToolName: string | null;
871
+ /** Summary/args of the most recently started tool. */
872
+ lastToolSummary: string | null;
873
+ /** Timestamp when the most recent tool started. */
874
+ lastToolStartedAt: number | null;
875
+ /** Set while the sub-agent is blocked awaiting a permission decision. */
876
+ pendingPermission: {
877
+ toolName: string;
878
+ args: unknown;
879
+ } | null;
880
+ }
881
+ //# sourceMappingURL=types.d.ts.map