@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,381 @@
1
+ /**
2
+ * Event bridge: maps pi-agent-core events to normalized consumer events.
3
+ *
4
+ * Pi-agent-core emits 10 events across 4 scopes (agent, turn, message, tool).
5
+ * The event bridge normalizes these into a consumer-facing event stream for
6
+ * logging, monitoring, and lifecycle hooks.
7
+ *
8
+ * Key mappings:
9
+ * agent_start -> loop_start
10
+ * agent_end -> loop_end (onLoopComplete fires here)
11
+ * turn_start -> turn_start
12
+ * turn_end -> turn_end + AgentTextOutput (parse working tags)
13
+ * message_start -> response_start
14
+ * message_update -> response_chunk
15
+ * message_end -> response_end
16
+ * tool_execution_start -> tool_call_start
17
+ * tool_execution_update -> tool_call_update
18
+ * tool_execution_end -> tool_call_end
19
+ *
20
+ * Child event forwarding:
21
+ * forwardFrom(childBridge, childTaskId) subscribes to a child agent's
22
+ * event bridge and re-emits events on this bridge with childTaskId set.
23
+ * Consumers use event.childTaskId to distinguish parent vs child events.
24
+ *
25
+ * Reference: cortex-architecture.md (Event Bridge section)
26
+ */
27
+ import { NOOP_LOGGER } from './noop-logger.js';
28
+ import { parseWorkingTags } from './working-tags.js';
29
+ // ---------------------------------------------------------------------------
30
+ // Event type mapping
31
+ // ---------------------------------------------------------------------------
32
+ const PI_TO_CORTEX_MAP = {
33
+ agent_start: 'loop_start',
34
+ agent_end: 'loop_end',
35
+ turn_start: 'turn_start',
36
+ turn_end: 'turn_end',
37
+ message_start: 'response_start',
38
+ message_update: 'response_chunk',
39
+ message_end: 'response_end',
40
+ tool_execution_start: 'tool_call_start',
41
+ tool_execution_update: 'tool_call_update',
42
+ tool_execution_end: 'tool_call_end',
43
+ };
44
+ // ---------------------------------------------------------------------------
45
+ // EventBridge
46
+ // ---------------------------------------------------------------------------
47
+ export class EventBridge {
48
+ listeners = new Map();
49
+ allListeners = new Set();
50
+ unsubscribeFromPi = null;
51
+ workingTagsEnabled;
52
+ logger;
53
+ /**
54
+ * Create an EventBridge.
55
+ *
56
+ * @param workingTagsEnabled - Whether to parse working tags on turn_end
57
+ * @param logger - Optional logger for diagnostics (defaults to silent no-op)
58
+ */
59
+ constructor(workingTagsEnabled = true, logger) {
60
+ this.workingTagsEnabled = workingTagsEnabled;
61
+ this.logger = logger ?? NOOP_LOGGER;
62
+ }
63
+ /**
64
+ * Wire the bridge to a pi-agent-core Agent's event stream.
65
+ * Stores the unsubscribe function for cleanup.
66
+ *
67
+ * @param source - The pi-agent-core Agent (or any PiEventSource)
68
+ */
69
+ wire(source) {
70
+ // Clean up previous wiring if any
71
+ this.unwire();
72
+ this.unsubscribeFromPi = source.subscribe((piEvent) => {
73
+ this.handlePiEvent(piEvent);
74
+ });
75
+ }
76
+ /**
77
+ * Disconnect from the pi-agent-core event stream.
78
+ */
79
+ unwire() {
80
+ if (this.unsubscribeFromPi) {
81
+ this.unsubscribeFromPi();
82
+ this.unsubscribeFromPi = null;
83
+ }
84
+ }
85
+ /**
86
+ * Register a listener for a specific event type.
87
+ *
88
+ * @param type - The event type to listen for
89
+ * @param listener - The callback function
90
+ * @returns An unsubscribe function
91
+ */
92
+ on(type, listener) {
93
+ let typeListeners = this.listeners.get(type);
94
+ if (!typeListeners) {
95
+ typeListeners = new Set();
96
+ this.listeners.set(type, typeListeners);
97
+ }
98
+ typeListeners.add(listener);
99
+ return () => {
100
+ typeListeners.delete(listener);
101
+ };
102
+ }
103
+ /**
104
+ * Register a listener for all event types.
105
+ *
106
+ * @param listener - The callback function
107
+ * @returns An unsubscribe function
108
+ */
109
+ onAll(listener) {
110
+ this.allListeners.add(listener);
111
+ return () => {
112
+ this.allListeners.delete(listener);
113
+ };
114
+ }
115
+ /**
116
+ * Forward all events from a child agent's event bridge onto this bridge.
117
+ *
118
+ * Each forwarded event gets `childTaskId` set so consumers can distinguish
119
+ * parent events from child events. Returns an unsubscribe function that
120
+ * stops forwarding (call when the child agent completes or is destroyed).
121
+ *
122
+ * @param childBridge - The child agent's EventBridge
123
+ * @param childTaskId - The sub-agent task ID to tag forwarded events with
124
+ * @returns An unsubscribe function
125
+ */
126
+ forwardFrom(childBridge, childTaskId) {
127
+ return childBridge.onAll((event) => {
128
+ this.emit({
129
+ ...event,
130
+ childTaskId,
131
+ });
132
+ });
133
+ }
134
+ /**
135
+ * Update whether working tags parsing is enabled.
136
+ */
137
+ setWorkingTagsEnabled(enabled) {
138
+ this.workingTagsEnabled = enabled;
139
+ }
140
+ /**
141
+ * Clean up all listeners and disconnect from the pi-agent-core event stream.
142
+ */
143
+ destroy() {
144
+ this.unwire();
145
+ this.listeners.clear();
146
+ this.allListeners.clear();
147
+ }
148
+ /**
149
+ * Handle a pi-agent-core event by mapping and emitting to consumers.
150
+ */
151
+ handlePiEvent(piEvent) {
152
+ const cortexType = PI_TO_CORTEX_MAP[piEvent.type];
153
+ if (!cortexType) {
154
+ return;
155
+ }
156
+ const cortexEvent = {
157
+ type: cortexType,
158
+ data: piEvent,
159
+ };
160
+ // Populate typed payload for tool events
161
+ const payload = this.extractToolPayload(cortexType, piEvent);
162
+ if (payload) {
163
+ cortexEvent.payload = payload;
164
+ }
165
+ // For turn_end, extract typed usage and parse working tags
166
+ if (cortexType === 'turn_end') {
167
+ const usage = this.extractUsage(piEvent);
168
+ if (usage) {
169
+ cortexEvent.usage = usage;
170
+ }
171
+ if (this.workingTagsEnabled) {
172
+ const text = this.extractTurnText(piEvent);
173
+ if (text) {
174
+ cortexEvent.textOutput = parseWorkingTags(text);
175
+ }
176
+ }
177
+ }
178
+ this.emit(cortexEvent);
179
+ }
180
+ /**
181
+ * Extract a typed payload from a pi-agent-core tool event.
182
+ * Returns undefined for non-tool events.
183
+ */
184
+ extractToolPayload(cortexType, piEvent) {
185
+ if (cortexType === 'tool_call_start') {
186
+ return {
187
+ toolCallId: String(piEvent['toolCallId'] ?? piEvent['id'] ?? ''),
188
+ toolName: String(piEvent['toolName'] ?? piEvent['name'] ?? 'unknown'),
189
+ args: (piEvent['args'] ?? piEvent['input'] ?? {}),
190
+ };
191
+ }
192
+ if (cortexType === 'tool_call_update') {
193
+ const partialResult = piEvent['partialResult'];
194
+ return {
195
+ toolCallId: String(piEvent['toolCallId'] ?? piEvent['id'] ?? ''),
196
+ toolName: String(piEvent['toolName'] ?? piEvent['name'] ?? 'unknown'),
197
+ args: (piEvent['args'] ?? piEvent['input'] ?? {}),
198
+ partialResult: partialResult ?? { content: [], details: {} },
199
+ };
200
+ }
201
+ if (cortexType === 'tool_call_end') {
202
+ const result = piEvent['result'];
203
+ const isError = Boolean(piEvent['isError']);
204
+ const explicitError = piEvent['error'];
205
+ const payload = {
206
+ toolCallId: String(piEvent['toolCallId'] ?? piEvent['id'] ?? ''),
207
+ toolName: String(piEvent['toolName'] ?? piEvent['name'] ?? 'unknown'),
208
+ result: result ?? { content: [], details: {} },
209
+ durationMs: Number(piEvent['durationMs'] ?? piEvent['duration'] ?? 0),
210
+ isError,
211
+ };
212
+ if (isError) {
213
+ // Extract error text from multiple possible sources:
214
+ // 1. Explicit error string field
215
+ // 2. Error object with message
216
+ // 3. Result content text (pi-agent-core puts error details here)
217
+ // 4. Fallback
218
+ let errorText;
219
+ if (typeof explicitError === 'string') {
220
+ errorText = explicitError;
221
+ }
222
+ else if (explicitError instanceof Error) {
223
+ errorText = explicitError.message;
224
+ }
225
+ else if (typeof explicitError === 'object' && explicitError !== null && 'message' in explicitError) {
226
+ errorText = String(explicitError['message']);
227
+ }
228
+ // If no explicit error, extract from result content
229
+ if (!errorText && result?.content) {
230
+ const textParts = result.content
231
+ .filter((c) => c.type === 'text')
232
+ .map(c => c.text);
233
+ if (textParts.length > 0) {
234
+ errorText = textParts.join('\n');
235
+ }
236
+ }
237
+ payload.error = errorText ?? 'unknown error';
238
+ }
239
+ return payload;
240
+ }
241
+ return undefined;
242
+ }
243
+ /**
244
+ * Extract the text content from a turn_end event.
245
+ * Pi-agent-core's turn_end event carries the assistant message for that turn.
246
+ */
247
+ extractTurnText(piEvent) {
248
+ // The turn_end event from pi-agent-core carries the assistant message.
249
+ // The structure varies, so we try multiple access patterns.
250
+ // Pattern 1: Direct text property
251
+ if (typeof piEvent['text'] === 'string') {
252
+ return piEvent['text'];
253
+ }
254
+ // Pattern 2: message.content as string
255
+ const message = piEvent['message'];
256
+ if (message && typeof message['content'] === 'string') {
257
+ return message['content'];
258
+ }
259
+ // Pattern 3: message.content as array with text parts
260
+ if (message && Array.isArray(message['content'])) {
261
+ const textParts = message['content']
262
+ .filter((part) => part.type === 'text' && typeof part.text === 'string')
263
+ .map((part) => part.text);
264
+ if (textParts.length > 0) {
265
+ return textParts.join('');
266
+ }
267
+ }
268
+ // Pattern 4: result.content
269
+ const result = piEvent['result'];
270
+ if (result && typeof result['content'] === 'string') {
271
+ return result['content'];
272
+ }
273
+ // Pattern 5: content on the content parts of the result
274
+ if (result && Array.isArray(result['content'])) {
275
+ const textParts = result['content']
276
+ .filter((part) => part.type === 'text' && typeof part.text === 'string')
277
+ .map((part) => part.text);
278
+ if (textParts.length > 0) {
279
+ return textParts.join('');
280
+ }
281
+ }
282
+ return null;
283
+ }
284
+ /**
285
+ * Extract typed CortexUsage from a turn_end event.
286
+ *
287
+ * Pi-ai's AssistantMessage carries usage at message.usage with a nested
288
+ * cost object. This method navigates the opaque event data once so all
289
+ * subscribers receive clean, typed usage without duplicating extraction.
290
+ */
291
+ extractUsage(piEvent) {
292
+ // Pattern 1: message.usage (pi-ai AssistantMessage, the primary path)
293
+ const message = piEvent['message'];
294
+ if (message) {
295
+ const usage = this.buildUsageFromObject(message['usage']);
296
+ if (usage) {
297
+ if (typeof message['model'] === 'string') {
298
+ usage.model = message['model'];
299
+ }
300
+ return usage;
301
+ }
302
+ }
303
+ // Pattern 2: Direct usage property on the event
304
+ const directUsage = this.buildUsageFromObject(piEvent['usage']);
305
+ if (directUsage)
306
+ return directUsage;
307
+ // Pattern 3: result.usage
308
+ const result = piEvent['result'];
309
+ if (result) {
310
+ const resultUsage = this.buildUsageFromObject(result['usage']);
311
+ if (resultUsage)
312
+ return resultUsage;
313
+ }
314
+ return null;
315
+ }
316
+ /**
317
+ * Build a CortexUsage from a raw usage-shaped object.
318
+ * Returns null if the object is not a valid usage structure.
319
+ */
320
+ buildUsageFromObject(raw) {
321
+ if (!raw || typeof raw !== 'object')
322
+ return null;
323
+ const u = raw;
324
+ const input = typeof u['input'] === 'number' ? u['input'] : 0;
325
+ const output = typeof u['output'] === 'number' ? u['output'] : 0;
326
+ const cacheRead = typeof u['cacheRead'] === 'number' ? u['cacheRead'] : 0;
327
+ const cacheWrite = typeof u['cacheWrite'] === 'number' ? u['cacheWrite'] : 0;
328
+ const totalTokens = typeof u['totalTokens'] === 'number' ? u['totalTokens'] : input + output;
329
+ // At least one non-zero field to consider this a valid usage object
330
+ if (input === 0 && output === 0 && cacheRead === 0 && totalTokens === 0)
331
+ return null;
332
+ let cost = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 };
333
+ const costObj = u['cost'];
334
+ if (costObj && typeof costObj === 'object') {
335
+ const c = costObj;
336
+ cost = {
337
+ input: typeof c['input'] === 'number' ? c['input'] : 0,
338
+ output: typeof c['output'] === 'number' ? c['output'] : 0,
339
+ cacheRead: typeof c['cacheRead'] === 'number' ? c['cacheRead'] : 0,
340
+ cacheWrite: typeof c['cacheWrite'] === 'number' ? c['cacheWrite'] : 0,
341
+ total: typeof c['total'] === 'number' ? c['total'] : 0,
342
+ };
343
+ }
344
+ return { input, output, cacheRead, cacheWrite, totalTokens, cost };
345
+ }
346
+ /**
347
+ * Emit a normalized event to all matching listeners.
348
+ * Each listener is wrapped in try/catch so a throwing listener
349
+ * does not prevent subsequent listeners from receiving the event.
350
+ */
351
+ emit(event) {
352
+ // Notify type-specific listeners
353
+ const typeListeners = this.listeners.get(event.type);
354
+ if (typeListeners) {
355
+ for (const listener of typeListeners) {
356
+ try {
357
+ listener(event);
358
+ }
359
+ catch (err) {
360
+ this.logger.error('[EventBridge] listener threw', {
361
+ eventType: event.type,
362
+ error: err instanceof Error ? err.message : String(err),
363
+ });
364
+ }
365
+ }
366
+ }
367
+ // Notify catch-all listeners
368
+ for (const listener of this.allListeners) {
369
+ try {
370
+ listener(event);
371
+ }
372
+ catch (err) {
373
+ this.logger.error('[EventBridge] catch-all listener threw', {
374
+ eventType: event.type,
375
+ error: err instanceof Error ? err.message : String(err),
376
+ });
377
+ }
378
+ }
379
+ }
380
+ }
381
+ //# sourceMappingURL=event-bridge.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event-bridge.js","sourceRoot":"","sources":["../src/event-bridge.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAWH,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAiFrD,8EAA8E;AAC9E,qBAAqB;AACrB,8EAA8E;AAE9E,MAAM,gBAAgB,GAAkD;IACtE,WAAW,EAAE,YAAY;IACzB,SAAS,EAAE,UAAU;IACrB,UAAU,EAAE,YAAY;IACxB,QAAQ,EAAE,UAAU;IACpB,aAAa,EAAE,gBAAgB;IAC/B,cAAc,EAAE,gBAAgB;IAChC,WAAW,EAAE,cAAc;IAC3B,oBAAoB,EAAE,iBAAiB;IACvC,qBAAqB,EAAE,kBAAkB;IACzC,kBAAkB,EAAE,eAAe;CACpC,CAAC;AAEF,8EAA8E;AAC9E,cAAc;AACd,8EAA8E;AAE9E,MAAM,OAAO,WAAW;IACL,SAAS,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Y,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC;iBACxD,CAAC,CAAC;YACL,CAAC;QACH,CAAC;IACH,CAAC;CACF"}
@@ -0,0 +1,55 @@
1
+ /**
2
+ * @animus-labs/cortex
3
+ *
4
+ * Production-grade agent wrapper for pi-agent-core.
5
+ * Provides context management, MCP tool support, tool permissions,
6
+ * budget guards, compaction, skill system, and event logging.
7
+ *
8
+ * Phase 1A exports: types and pure utility modules.
9
+ * Phase 1B exports: CortexAgent, ContextManager, EventBridge, BudgetGuard.
10
+ * Phase 1C exports: Built-in tools (Read, Write, Edit, Glob, Grep, Bash, TaskOutput, WebFetch).
11
+ * Phase 1D exports: ProviderManager, model wrapper, provider registry.
12
+ */
13
+ export type { CortexLogger, CortexUsage, SessionUsage, CortexLifecycleState, CortexToolPermissionDecision, CortexToolPermissionResult, CortexAgentConfig, CortexDiagnosticsConfig, ContextManagerConfig, ErrorCategory, ErrorSeverity, ClassifiedError, AgentTextOutput, ToolContentDetails, BudgetGuardConfig, ToolCategory, MicrocompactionConfig, CompactionConfig, FailsafeConfig, AdaptiveThresholdConfig, CortexCompactionConfig, CompactionTarget, CompactionResult, CompactionDegradedInfo, CompactionExhaustedInfo, PersistResultFn, CortexEvents, UtilityModelDefaults, McpTransportConfig, McpStdioConfig, McpHttpConfig, McpConnectionState, SkillConfig, SkillEntry, LoadedSkill, CortexScriptContext, SubAgentSpawnConfig, SubAgentResult, TrackedSubAgent, ThinkingLevel, ModelThinkingCapabilities, ToolExecuteContext, ToolCallStartPayload, ToolCallUpdatePayload, ToolCallEndPayload, PromptWatchdogDiagnosticsConfig, } from './types.js';
14
+ export { NOOP_LOGGER } from './noop-logger.js';
15
+ export { zodToTypebox } from './schema-converter.js';
16
+ export { estimateTokens } from './token-estimator.js';
17
+ export { stripWorkingTags, extractWorkingContent, parseWorkingTags, } from './working-tags.js';
18
+ export { classifyError } from './error-classifier.js';
19
+ export type { ClassifyErrorOptions } from './error-classifier.js';
20
+ export { ContextManager } from './context-manager.js';
21
+ export type { AgentMessage, AgentStateAccessor, AgentContext, } from './context-manager.js';
22
+ export { EventBridge } from './event-bridge.js';
23
+ export type { CortexEventType, CortexEvent, CortexEventListener, PiEventType, PiEvent, PiEventSource, } from './event-bridge.js';
24
+ export { BudgetGuard } from './budget-guard.js';
25
+ export { CortexAgent, MINIMUM_CONTEXT_WINDOW, TOOL_RESULT_WORKING_TAGS_REMINDER } from './cortex-agent.js';
26
+ export type { PiAgent, PiModel } from './cortex-agent.js';
27
+ export { fromPiAgentTool, assertValidCortexTool } from './tool-contract.js';
28
+ export type { CortexTool, PiAgentTool } from './tool-contract.js';
29
+ export { McpClientManager } from './mcp-client.js';
30
+ export type { AgentTool } from './mcp-client.js';
31
+ export { ReadRegistry, CwdTracker, CortexToolRuntime, BackgroundTaskStore, WebFetchRuntimeState, globalBackgroundTaskStore, attachRuntimeAwareTool, getRuntimeAwareToolMetadata, cloneRuntimeAwareTool, createReadTool, createWriteTool, createEditTool, createGlobTool, createGrepTool, createBashTool, createTaskOutputTool, createWebFetchTool, WebFetchCache, getBackgroundTask, getAllBackgroundTasks, buildSafeEnv, isCriticalPath, classifyCommand, checkObfuscation, stripInvisibleChars, checkScriptPreflight, checkAutoModeClassifier, runSafetyChecks, validateWritePaths, extractWritePaths, TOOL_NAMES, } from './tools/index.js';
32
+ export type { ReadDetails, ReadParamsType, ReadToolConfig, WriteDetails, WriteParamsType, WriteToolConfig, DiffHunk, EditDetails, EditParamsType, EditToolConfig, GlobDetails, GlobParamsType, GlobToolConfig, GrepDetails, GrepParamsType, GrepToolConfig, BashDetails, BashStreamUpdate, BashParamsType, BashToolConfig, BackgroundTask, TaskOutputDetails, TaskOutputParamsType, TaskOutputToolConfig, WebFetchDetails, WebFetchParamsType, WebFetchToolConfig, CacheEntry, CommandClassification, SafetyCheckResult, BuiltInToolName, SubAgentToolConfig, SubAgentDetails, SubAgentParamsType, } from './tools/index.js';
33
+ export { SkillRegistry, parseFrontmatter } from './skill-registry.js';
34
+ export { preprocessSkillBody, substituteVariables, executeShellCommand, executeScript } from './skill-preprocessor.js';
35
+ export { createLoadSkillTool, buildLoadSkillDescription, LOAD_SKILL_TOOL_NAME } from './skill-tool.js';
36
+ export type { LoadSkillToolConfig, LoadSkillParamsType } from './skill-tool.js';
37
+ export { LoadSkillParams } from './skill-tool.js';
38
+ export { SubAgentManager } from './sub-agent-manager.js';
39
+ export type { SubAgentManagerConfig, SubAgentLifecycleHooks } from './sub-agent-manager.js';
40
+ export { DeferredToolRegistry } from './tools/tool-search/registry.js';
41
+ export type { ToolSearchResult } from './tools/tool-search/registry.js';
42
+ export { createToolSearchTool, TOOL_SEARCH_TOOL_NAME, ToolSearchParams, } from './tools/tool-search/index.js';
43
+ export type { ToolSearchToolConfig, ToolSearchDetails, ToolSearchParamsType, } from './tools/tool-search/index.js';
44
+ export type { DeferredToolsConfig } from './types.js';
45
+ export { CompactionManager, buildCompactionConfig, DEFAULT_COMPACTION_CONFIG, ADAPTIVE_DEFAULTS, computeAdaptiveThreshold, MicrocompactionEngine, capToolResult, runCompaction, shouldCompact, partitionHistory, buildSummaryMessage, emergencyTruncate, shouldTruncate, isContextOverflow, } from './compaction/index.js';
46
+ export { applyResultPersistence, processToolResult, resolveThreshold, MAX_RESULT_TOKENS, BOOKEND_CHARS, SKIP_RESULT_PERSISTENCE, DEFAULT_TOOL_THRESHOLDS, } from './tool-result-persistence.js';
47
+ export type { ApplyPersistenceOptions, ProcessResultOptions, } from './tool-result-persistence.js';
48
+ export type { TrimAction, TrimState, CompleteFn, FailsafeTruncationResult, ObservationalMemoryConfig, ObservationalMemoryState, ObservationEvent, ReflectionEvent, RecallConfig, RecallResult, } from './compaction/index.js';
49
+ export { wrapModel, unwrapModel, isCortexModel } from './model-wrapper.js';
50
+ export type { CortexModel } from './model-wrapper.js';
51
+ export { PROVIDER_REGISTRY, OAUTH_PROVIDER_IDS, UTILITY_MODEL_DEFAULTS, PRIMARY_MODEL_DEFAULTS, PROVIDER_CACHE_CONFIG, resolveCacheRetention, } from './provider-registry.js';
52
+ export type { AuthMethod, ProviderInfo, ModelInfo, ProviderCacheConfig, CacheRetention, } from './provider-registry.js';
53
+ export { ProviderManager } from './provider-manager.js';
54
+ export type { IProviderManager, OAuthCallbacks, OAuthMeta, OAuthResult, OAuthRefreshResult, CustomModelConfig, ApiKeyValidationStatus, ApiKeyValidationResult, } from './provider-manager.js';
55
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAGH,YAAY,EACV,YAAY,EACZ,WAAW,EACX,YAAY,EACZ,oBAAoB,EACpB,4BAA4B,EAC5B,0BAA0B,EAC1B,iBAAiB,EACjB,uBAAuB,EACvB,oBAAoB,EACpB,aAAa,EACb,aAAa,EACb,eAAe,EACf,eAAe,EACf,kBAAkB,EAClB,iBAAiB,EACjB,YAAY,EACZ,qBAAqB,EACrB,gBAAgB,EAChB,cAAc,EACd,uBAAuB,EACvB,sBAAsB,EACtB,gBAAgB,EAChB,gBAAgB,EAChB,sBAAsB,EACtB,uBAAuB,EACvB,eAAe,EACf,YAAY,EACZ,oBAAoB,EACpB,kBAAkB,EAClB,cAAc,EACd,aAAa,EACb,kBAAkB,EAClB,WAAW,EACX,UAAU,EACV,WAAW,EACX,mBAAmB,EACnB,mBAAmB,EACnB,cAAc,EACd,eAAe,EACf,aAAa,EACb,yBAAyB,EACzB,kBAAkB,EAClB,oBAAoB,EACpB,qBAAqB,EACrB,kBAAkB,EAClB,+BAA+B,GAChC,MAAM,YAAY,CAAC;AAGpB,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAG/C,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAGrD,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAGtD,OA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uB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,57 @@
1
+ /**
2
+ * @animus-labs/cortex
3
+ *
4
+ * Production-grade agent wrapper for pi-agent-core.
5
+ * Provides context management, MCP tool support, tool permissions,
6
+ * budget guards, compaction, skill system, and event logging.
7
+ *
8
+ * Phase 1A exports: types and pure utility modules.
9
+ * Phase 1B exports: CortexAgent, ContextManager, EventBridge, BudgetGuard.
10
+ * Phase 1C exports: Built-in tools (Read, Write, Edit, Glob, Grep, Bash, TaskOutput, WebFetch).
11
+ * Phase 1D exports: ProviderManager, model wrapper, provider registry.
12
+ */
13
+ // Logger
14
+ export { NOOP_LOGGER } from './noop-logger.js';
15
+ // Schema Converter
16
+ export { zodToTypebox } from './schema-converter.js';
17
+ // Token Estimator
18
+ export { estimateTokens } from './token-estimator.js';
19
+ // Working Tags Parser
20
+ export { stripWorkingTags, extractWorkingContent, parseWorkingTags, } from './working-tags.js';
21
+ // Error Classifier
22
+ export { classifyError } from './error-classifier.js';
23
+ // Context Manager (Phase 1B)
24
+ export { ContextManager } from './context-manager.js';
25
+ // Event Bridge (Phase 1B)
26
+ export { EventBridge } from './event-bridge.js';
27
+ // Budget Guard (Phase 1B)
28
+ export { BudgetGuard } from './budget-guard.js';
29
+ // CortexAgent (Phase 1B)
30
+ export { CortexAgent, MINIMUM_CONTEXT_WINDOW, TOOL_RESULT_WORKING_TAGS_REMINDER } from './cortex-agent.js';
31
+ // Tool Contracts
32
+ export { fromPiAgentTool, assertValidCortexTool } from './tool-contract.js';
33
+ // MCP Client Manager (Phase 3)
34
+ export { McpClientManager } from './mcp-client.js';
35
+ // Built-in Tools (Phase 1C)
36
+ export { ReadRegistry, CwdTracker, CortexToolRuntime, BackgroundTaskStore, WebFetchRuntimeState, globalBackgroundTaskStore, attachRuntimeAwareTool, getRuntimeAwareToolMetadata, cloneRuntimeAwareTool, createReadTool, createWriteTool, createEditTool, createGlobTool, createGrepTool, createBashTool, createTaskOutputTool, createWebFetchTool, WebFetchCache, getBackgroundTask, getAllBackgroundTasks, buildSafeEnv, isCriticalPath, classifyCommand, checkObfuscation, stripInvisibleChars, checkScriptPreflight, checkAutoModeClassifier, runSafetyChecks, validateWritePaths, extractWritePaths, TOOL_NAMES, } from './tools/index.js';
37
+ // Skill System (Phase 4)
38
+ export { SkillRegistry, parseFrontmatter } from './skill-registry.js';
39
+ export { preprocessSkillBody, substituteVariables, executeShellCommand, executeScript } from './skill-preprocessor.js';
40
+ export { createLoadSkillTool, buildLoadSkillDescription, LOAD_SKILL_TOOL_NAME } from './skill-tool.js';
41
+ export { LoadSkillParams } from './skill-tool.js';
42
+ // Sub-Agent Manager (Phase 4)
43
+ export { SubAgentManager } from './sub-agent-manager.js';
44
+ // Deferred Tool Loading / ToolSearch
45
+ export { DeferredToolRegistry } from './tools/tool-search/registry.js';
46
+ export { createToolSearchTool, TOOL_SEARCH_TOOL_NAME, ToolSearchParams, } from './tools/tool-search/index.js';
47
+ // Compaction (Phase 5)
48
+ export { CompactionManager, buildCompactionConfig, DEFAULT_COMPACTION_CONFIG, ADAPTIVE_DEFAULTS, computeAdaptiveThreshold, MicrocompactionEngine, capToolResult, runCompaction, shouldCompact, partitionHistory, buildSummaryMessage, emergencyTruncate, shouldTruncate, isContextOverflow, } from './compaction/index.js';
49
+ // Tool Result Persistence (proactive interceptor at the tool execution boundary)
50
+ export { applyResultPersistence, processToolResult, resolveThreshold, MAX_RESULT_TOKENS, BOOKEND_CHARS, SKIP_RESULT_PERSISTENCE, DEFAULT_TOOL_THRESHOLDS, } from './tool-result-persistence.js';
51
+ // Model Wrapper (Phase 1D)
52
+ export { wrapModel, unwrapModel, isCortexModel } from './model-wrapper.js';
53
+ // Provider Registry (Phase 1D)
54
+ export { PROVIDER_REGISTRY, OAUTH_PROVIDER_IDS, UTILITY_MODEL_DEFAULTS, PRIMARY_MODEL_DEFAULTS, PROVIDER_CACHE_CONFIG, resolveCacheRetention, } from './provider-registry.js';
55
+ // Provider Manager (Phase 1D)
56
+ export { ProviderManager } from './provider-manager.js';
57
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAoDH,SAAS;AACT,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAE/C,mBAAmB;AACnB,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAErD,kBAAkB;AAClB,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAEtD,sBAAsB;AACtB,OAAO,EACL,gBAAgB,EAChB,qBAAqB,EACrB,gBAAgB,GACjB,MAAM,mBAAmB,CAAC;AAE3B,mBAAmB;AACnB,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAGtD,6BAA6B;AAC7B,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAOtD,0BAA0B;AAC1B,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAUhD,0BAA0B;AAC1B,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEhD,yBAAyB;AACzB,OAAO,EAAE,WAAW,EAAE,sBAAsB,EAAE,iCAAiC,EAAE,MAAM,mBAAmB,CAAC;AAG3G,iBAAiB;AACjB,OAAO,EAAE,eAAe,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAG5E,+BAA+B;AAC/B,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAGnD,4BAA4B;AAC5B,OAAO,EACL,YAAY,EACZ,UAAU,EACV,iBAAiB,EACjB,mBAAmB,EACnB,oBAAoB,EACpB,yBAAyB,EACzB,sBAAsB,EACtB,2BAA2B,EAC3B,qBAAqB,EACrB,cAAc,EACd,eAAe,EACf,cAAc,EACd,cAAc,EACd,cAAc,EACd,cAAc,EACd,oBAAoB,EACpB,kBAAkB,EAClB,aAAa,EACb,iBAAiB,EACjB,qB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kBAAkB,EAClB,sBAAsB,EACtB,sBAAsB,EACtB,qBAAqB,EACrB,qBAAqB,GACtB,MAAM,wBAAwB,CAAC;AAShC,8BAA8B;AAC9B,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC"}
@@ -0,0 +1,119 @@
1
+ /**
2
+ * McpClientManager: connects to MCP servers and wraps discovered tools
3
+ * as AgentTool objects for registration with pi-agent-core.
4
+ *
5
+ * Handles two transport types:
6
+ * - Stdio: spawns a subprocess, communicates via stdin/stdout
7
+ * - HTTP: connects to an already-running Streamable HTTP server
8
+ *
9
+ * Tool discovery via tools/list, tool execution via tools/call.
10
+ * Connections are persistent (kept alive between ticks) with health monitoring.
11
+ * Reconnect on subprocess crash (3 attempts before deregistering).
12
+ *
13
+ * References:
14
+ * - docs/cortex/mcp-integration.md
15
+ * - docs/cortex/plans/phase-3-plugin-tools.md
16
+ */
17
+ import type { McpTransportConfig, McpConnectionState, CortexLogger } from './types.js';
18
+ import type { CortexTool } from './tool-contract.js';
19
+ /**
20
+ * Backward-compatible export name for Cortex's canonical tool contract.
21
+ */
22
+ export type AgentTool = CortexTool;
23
+ export declare class McpClientManager {
24
+ private connections;
25
+ /**
26
+ * Callback invoked whenever the aggregate tool set changes.
27
+ * CortexAgent uses this to resync live tools after connect/disconnect/reconnect.
28
+ */
29
+ onToolsChanged?: () => void;
30
+ /**
31
+ * Callback invoked when a subprocess is spawned (for PID tracking).
32
+ * The consumer (CortexAgent) uses this to track PIDs for exit cleanup.
33
+ */
34
+ onSubprocessSpawned?: (pid: number) => void;
35
+ /**
36
+ * Callback invoked when a subprocess exits (for PID tracking).
37
+ */
38
+ onSubprocessExited?: (pid: number) => void;
39
+ /**
40
+ * Consumer-set environment variable overrides that bypass the security blocklist.
41
+ * Merged ON TOP of the sanitized environment for all stdio subprocesses.
42
+ * Used for macOS dock icon suppression vars (DYLD_INSERT_LIBRARIES, etc.).
43
+ */
44
+ envOverrides?: Record<string, string>;
45
+ /** Logger for MCP diagnostics. Set by CortexAgent after construction. */
46
+ logger: CortexLogger;
47
+ /**
48
+ * Connect to an MCP server and discover its tools.
49
+ *
50
+ * Spawns a subprocess (stdio) or connects to a URL (http), performs
51
+ * the MCP handshake, calls tools/list, and wraps each discovered
52
+ * tool as an AgentTool with namespaced name.
53
+ *
54
+ * @param serverName - Unique name for this server (used for tool namespacing)
55
+ * @param config - Transport configuration
56
+ * @throws Error if connection or tool discovery fails
57
+ */
58
+ connect(serverName: string, config: McpTransportConfig): Promise<void>;
59
+ /**
60
+ * Disconnect from a specific MCP server.
61
+ * Closes the transport and removes all tools from that server.
62
+ *
63
+ * @param serverName - The server name to disconnect
64
+ */
65
+ disconnect(serverName: string): Promise<void>;
66
+ /**
67
+ * Close all MCP connections.
68
+ * Kills all stdio subprocesses and closes HTTP connections.
69
+ */
70
+ closeAll(): Promise<void>;
71
+ /**
72
+ * Get all AgentTool objects from all connected MCP servers.
73
+ * Returns tools namespaced as serverName__toolName.
74
+ */
75
+ getTools(): AgentTool[];
76
+ /**
77
+ * Get tool names from a specific server.
78
+ */
79
+ getServerToolNames(serverName: string): string[];
80
+ /**
81
+ * Get the connection state for all servers.
82
+ */
83
+ getConnectionStates(): McpConnectionState[];
84
+ /**
85
+ * Check if a specific server is connected.
86
+ */
87
+ isConnected(serverName: string): boolean;
88
+ /**
89
+ * Get the number of active connections.
90
+ */
91
+ get connectionCount(): number;
92
+ private createTransport;
93
+ private createStdioTransport;
94
+ private createHttpTransport;
95
+ /**
96
+ * Discover tools from a connected MCP server and wrap them as AgentTools.
97
+ */
98
+ private discoverTools;
99
+ /**
100
+ * Wrap a single MCP tool definition as an AgentTool.
101
+ *
102
+ * Key details:
103
+ * - Name is prefixed with serverName__ for namespacing
104
+ * - JSON Schema from MCP is wrapped via Type.Unsafe() for TypeBox
105
+ * - execute() calls tools/call on the MCP connection using the original name
106
+ * - Errors are caught and returned as error results (not thrown)
107
+ */
108
+ private wrapMcpTool;
109
+ /**
110
+ * Handle unexpected disconnection from an MCP server.
111
+ * Attempts reconnection up to MAX_RECONNECT_ATTEMPTS times.
112
+ */
113
+ private handleDisconnect;
114
+ /**
115
+ * Attempt to reconnect to an MCP server.
116
+ */
117
+ private attemptReconnect;
118
+ }
119
+ //# sourceMappingURL=mcp-client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcp-client.d.ts","sourceRoot":"","sources":["../src/mcp-client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAOH,OAAO,KAAK,EAAE,kBAAkB,EAAE,kBAAkB,EAAiC,YAAY,EAAE,MAAM,YAAY,CAAC;AACtH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAQrD;;GAEG;AACH,MAAM,MAAM,SAAS,GAAG,UAAU,CAAC;AA4BnC,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,WAAW,CAAoC;IAEvD;;;OAGG;IACH,cAAc,CAAC,EAAE,MAAM,IAAI,CAAC;IAE5B;;;OAGG;IACH,mBAAmB,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,CAAC;IAE5C;;OAEG;IACH,kBAAkB,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,CAAC;IAE3C;;;;OAIG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAEtC,yEAAyE;IACzE,MAAM,EAAE,YAAY,CAAe;IAEnC;;;;;;;;;;OAUG;IACG,OAAO,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,kBAAkB,GAAG,OAAO,CAAC,IAAI,CAAC;IAqE5E;;;;;OAKG;IACG,UAAU,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAqBnD;;;OAGG;IACG,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;IAc/B;;;OAGG;IACH,QAAQ,IAAI,SAAS,EAAE;IAUvB;;OAEG;IACH,kBAAkB,CA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