@teneo-protocol/sdk 1.0.0 → 2.0.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 (211) hide show
  1. package/.github/workflows/publish-npm.yml +8 -6
  2. package/CHANGELOG.md +265 -0
  3. package/README.md +406 -53
  4. package/dist/core/websocket-client.d.ts +13 -0
  5. package/dist/core/websocket-client.d.ts.map +1 -1
  6. package/dist/core/websocket-client.js +34 -3
  7. package/dist/core/websocket-client.js.map +1 -1
  8. package/dist/handlers/message-handlers/agent-room-operation-response-handler.d.ts +76 -0
  9. package/dist/handlers/message-handlers/agent-room-operation-response-handler.d.ts.map +1 -0
  10. package/dist/handlers/message-handlers/agent-room-operation-response-handler.js +70 -0
  11. package/dist/handlers/message-handlers/agent-room-operation-response-handler.js.map +1 -0
  12. package/dist/handlers/message-handlers/agent-selected-handler.d.ts +92 -38
  13. package/dist/handlers/message-handlers/agent-selected-handler.d.ts.map +1 -1
  14. package/dist/handlers/message-handlers/agent-status-update-handler.d.ts +904 -0
  15. package/dist/handlers/message-handlers/agent-status-update-handler.d.ts.map +1 -0
  16. package/dist/handlers/message-handlers/agent-status-update-handler.js +51 -0
  17. package/dist/handlers/message-handlers/agent-status-update-handler.js.map +1 -0
  18. package/dist/handlers/message-handlers/auth-error-handler.d.ts +45 -31
  19. package/dist/handlers/message-handlers/auth-error-handler.d.ts.map +1 -1
  20. package/dist/handlers/message-handlers/auth-message-handler.d.ts +6 -0
  21. package/dist/handlers/message-handlers/auth-message-handler.d.ts.map +1 -1
  22. package/dist/handlers/message-handlers/auth-message-handler.js +65 -5
  23. package/dist/handlers/message-handlers/auth-message-handler.js.map +1 -1
  24. package/dist/handlers/message-handlers/auth-required-handler.d.ts +49 -31
  25. package/dist/handlers/message-handlers/auth-required-handler.d.ts.map +1 -1
  26. package/dist/handlers/message-handlers/auth-success-handler.d.ts +6 -0
  27. package/dist/handlers/message-handlers/auth-success-handler.d.ts.map +1 -1
  28. package/dist/handlers/message-handlers/auth-success-handler.js +46 -4
  29. package/dist/handlers/message-handlers/auth-success-handler.js.map +1 -1
  30. package/dist/handlers/message-handlers/challenge-handler.d.ts +45 -31
  31. package/dist/handlers/message-handlers/challenge-handler.d.ts.map +1 -1
  32. package/dist/handlers/message-handlers/error-message-handler.d.ts +49 -31
  33. package/dist/handlers/message-handlers/error-message-handler.d.ts.map +1 -1
  34. package/dist/handlers/message-handlers/index.d.ts +5 -0
  35. package/dist/handlers/message-handlers/index.d.ts.map +1 -1
  36. package/dist/handlers/message-handlers/index.js +23 -1
  37. package/dist/handlers/message-handlers/index.js.map +1 -1
  38. package/dist/handlers/message-handlers/list-available-agents-handler.d.ts +877 -0
  39. package/dist/handlers/message-handlers/list-available-agents-handler.d.ts.map +1 -0
  40. package/dist/handlers/message-handlers/list-available-agents-handler.js +38 -0
  41. package/dist/handlers/message-handlers/list-available-agents-handler.js.map +1 -0
  42. package/dist/handlers/message-handlers/list-room-agents-handler.d.ts +886 -0
  43. package/dist/handlers/message-handlers/list-room-agents-handler.d.ts.map +1 -0
  44. package/dist/handlers/message-handlers/list-room-agents-handler.js +51 -0
  45. package/dist/handlers/message-handlers/list-room-agents-handler.js.map +1 -0
  46. package/dist/handlers/message-handlers/list-rooms-response-handler.d.ts +178 -89
  47. package/dist/handlers/message-handlers/list-rooms-response-handler.d.ts.map +1 -1
  48. package/dist/handlers/message-handlers/ping-pong-handler.d.ts +62 -58
  49. package/dist/handlers/message-handlers/ping-pong-handler.d.ts.map +1 -1
  50. package/dist/handlers/message-handlers/regular-message-handler.d.ts +31 -29
  51. package/dist/handlers/message-handlers/regular-message-handler.d.ts.map +1 -1
  52. package/dist/handlers/message-handlers/regular-message-handler.js +1 -0
  53. package/dist/handlers/message-handlers/regular-message-handler.js.map +1 -1
  54. package/dist/handlers/message-handlers/room-operation-response-handler.d.ts +328 -0
  55. package/dist/handlers/message-handlers/room-operation-response-handler.d.ts.map +1 -0
  56. package/dist/handlers/message-handlers/room-operation-response-handler.js +92 -0
  57. package/dist/handlers/message-handlers/room-operation-response-handler.js.map +1 -0
  58. package/dist/handlers/message-handlers/subscribe-response-handler.d.ts +53 -31
  59. package/dist/handlers/message-handlers/subscribe-response-handler.d.ts.map +1 -1
  60. package/dist/handlers/message-handlers/types.d.ts +2 -0
  61. package/dist/handlers/message-handlers/types.d.ts.map +1 -1
  62. package/dist/handlers/message-handlers/unsubscribe-response-handler.d.ts +53 -31
  63. package/dist/handlers/message-handlers/unsubscribe-response-handler.d.ts.map +1 -1
  64. package/dist/managers/agent-room-manager.d.ts +222 -0
  65. package/dist/managers/agent-room-manager.d.ts.map +1 -0
  66. package/dist/managers/agent-room-manager.js +508 -0
  67. package/dist/managers/agent-room-manager.js.map +1 -0
  68. package/dist/managers/index.d.ts +2 -0
  69. package/dist/managers/index.d.ts.map +1 -1
  70. package/dist/managers/index.js +5 -1
  71. package/dist/managers/index.js.map +1 -1
  72. package/dist/managers/message-router.d.ts +1 -1
  73. package/dist/managers/message-router.d.ts.map +1 -1
  74. package/dist/managers/message-router.js +41 -4
  75. package/dist/managers/message-router.js.map +1 -1
  76. package/dist/managers/room-management-manager.d.ts +213 -0
  77. package/dist/managers/room-management-manager.d.ts.map +1 -0
  78. package/dist/managers/room-management-manager.js +440 -0
  79. package/dist/managers/room-management-manager.js.map +1 -0
  80. package/dist/managers/room-manager.d.ts +4 -4
  81. package/dist/managers/room-manager.d.ts.map +1 -1
  82. package/dist/managers/room-manager.js +1 -1
  83. package/dist/managers/room-manager.js.map +1 -1
  84. package/dist/teneo-sdk.d.ts +362 -14
  85. package/dist/teneo-sdk.d.ts.map +1 -1
  86. package/dist/teneo-sdk.js +497 -7
  87. package/dist/teneo-sdk.js.map +1 -1
  88. package/dist/types/config.d.ts +63 -54
  89. package/dist/types/config.d.ts.map +1 -1
  90. package/dist/types/config.js +9 -5
  91. package/dist/types/config.js.map +1 -1
  92. package/dist/types/error-codes.d.ts +2 -0
  93. package/dist/types/error-codes.d.ts.map +1 -1
  94. package/dist/types/error-codes.js +3 -0
  95. package/dist/types/error-codes.js.map +1 -1
  96. package/dist/types/events.d.ts +132 -68
  97. package/dist/types/events.d.ts.map +1 -1
  98. package/dist/types/events.js.map +1 -1
  99. package/dist/types/index.d.ts +1 -1
  100. package/dist/types/index.d.ts.map +1 -1
  101. package/dist/types/index.js +27 -2
  102. package/dist/types/index.js.map +1 -1
  103. package/dist/types/messages.d.ts +11396 -2559
  104. package/dist/types/messages.d.ts.map +1 -1
  105. package/dist/types/messages.js +294 -27
  106. package/dist/types/messages.js.map +1 -1
  107. package/dist/types/validation.d.ts.map +1 -1
  108. package/dist/types/validation.js +1 -1
  109. package/dist/types/validation.js.map +1 -1
  110. package/dist/utils/bounded-queue.d.ts +1 -1
  111. package/dist/utils/bounded-queue.js +6 -6
  112. package/dist/utils/circuit-breaker.d.ts.map +1 -1
  113. package/dist/utils/circuit-breaker.js.map +1 -1
  114. package/dist/utils/event-waiter.d.ts.map +1 -1
  115. package/dist/utils/event-waiter.js +2 -1
  116. package/dist/utils/event-waiter.js.map +1 -1
  117. package/dist/utils/rate-limiter.d.ts.map +1 -1
  118. package/dist/utils/rate-limiter.js +4 -6
  119. package/dist/utils/rate-limiter.js.map +1 -1
  120. package/dist/utils/secure-private-key.d.ts.map +1 -1
  121. package/dist/utils/secure-private-key.js +9 -15
  122. package/dist/utils/secure-private-key.js.map +1 -1
  123. package/dist/utils/signature-verifier.d.ts +2 -2
  124. package/dist/utils/signature-verifier.d.ts.map +1 -1
  125. package/dist/utils/signature-verifier.js +5 -5
  126. package/dist/utils/signature-verifier.js.map +1 -1
  127. package/examples/.env.example +1 -1
  128. package/examples/agent-room-management-example.ts +334 -0
  129. package/examples/claude-agent-x-follower/.env.example +117 -0
  130. package/examples/claude-agent-x-follower/QUICKSTART.md +243 -0
  131. package/examples/claude-agent-x-follower/README.md +540 -0
  132. package/examples/claude-agent-x-follower/index.ts +248 -0
  133. package/examples/claude-agent-x-follower/package.json +37 -0
  134. package/examples/claude-agent-x-follower/tsconfig.json +20 -0
  135. package/examples/n8n-teneo/.env.example +127 -0
  136. package/examples/n8n-teneo/Dockerfile +42 -0
  137. package/examples/n8n-teneo/README.md +564 -0
  138. package/examples/n8n-teneo/docker-compose.yml +71 -0
  139. package/examples/n8n-teneo/index.ts +177 -0
  140. package/examples/n8n-teneo/package.json +22 -0
  141. package/examples/n8n-teneo/tsconfig.json +12 -0
  142. package/examples/n8n-teneo/workflows/x-timeline.json +66 -0
  143. package/examples/openai-teneo/.env.example +130 -0
  144. package/examples/openai-teneo/README.md +635 -0
  145. package/examples/openai-teneo/index.ts +280 -0
  146. package/examples/openai-teneo/package.json +24 -0
  147. package/examples/openai-teneo/tsconfig.json +16 -0
  148. package/examples/production-dashboard/.env.example +5 -3
  149. package/examples/production-dashboard/README.md +839 -0
  150. package/examples/production-dashboard/pnpm-lock.yaml +92 -0
  151. package/examples/production-dashboard/public/dashboard.html +1150 -504
  152. package/examples/production-dashboard/server.ts +428 -12
  153. package/examples/room-management-example.ts +285 -0
  154. package/examples/usage/.env.example +17 -0
  155. package/examples/usage/01-connect.ts +116 -0
  156. package/examples/usage/02-list-agents.ts +153 -0
  157. package/examples/usage/03-pick-agent.ts +201 -0
  158. package/examples/usage/04-find-by-capability.ts +237 -0
  159. package/examples/usage/05-webhook-example.ts +319 -0
  160. package/examples/usage/06-simple-api-server.ts +396 -0
  161. package/examples/usage/07-event-listener.ts +402 -0
  162. package/examples/usage/README.md +383 -0
  163. package/examples/usage/package.json +42 -0
  164. package/package.json +13 -3
  165. package/src/core/websocket-client.ts +43 -9
  166. package/src/formatters/response-formatter.test.ts +8 -2
  167. package/src/handlers/message-handlers/agent-room-operation-response-handler.ts +83 -0
  168. package/src/handlers/message-handlers/agent-status-update-handler.ts +58 -0
  169. package/src/handlers/message-handlers/auth-message-handler.ts +73 -5
  170. package/src/handlers/message-handlers/auth-success-handler.ts +58 -6
  171. package/src/handlers/message-handlers/index.ts +19 -0
  172. package/src/handlers/message-handlers/list-available-agents-handler.ts +41 -0
  173. package/src/handlers/message-handlers/list-room-agents-handler.ts +61 -0
  174. package/src/handlers/message-handlers/regular-message-handler.ts +1 -0
  175. package/src/handlers/message-handlers/room-operation-response-handler.ts +105 -0
  176. package/src/handlers/message-handlers/types.ts +6 -0
  177. package/src/handlers/webhook-handler.test.ts +13 -10
  178. package/src/managers/agent-room-manager.ts +609 -0
  179. package/src/managers/index.ts +2 -0
  180. package/src/managers/message-router.ts +48 -6
  181. package/src/managers/room-management-manager.ts +523 -0
  182. package/src/managers/room-manager.ts +12 -6
  183. package/src/teneo-sdk.ts +543 -10
  184. package/src/types/config.ts +13 -6
  185. package/src/types/error-codes.ts +4 -0
  186. package/src/types/events.ts +24 -0
  187. package/src/types/index.ts +55 -0
  188. package/src/types/messages.ts +374 -41
  189. package/src/types/validation.ts +4 -1
  190. package/src/utils/bounded-queue.ts +9 -9
  191. package/src/utils/circuit-breaker.ts +4 -1
  192. package/src/utils/deduplication-cache.test.ts +2 -6
  193. package/src/utils/event-waiter.test.ts +4 -1
  194. package/src/utils/event-waiter.ts +5 -7
  195. package/src/utils/rate-limiter.test.ts +5 -17
  196. package/src/utils/rate-limiter.ts +6 -9
  197. package/src/utils/secure-private-key.test.ts +66 -59
  198. package/src/utils/secure-private-key.ts +10 -16
  199. package/src/utils/signature-verifier.test.ts +75 -70
  200. package/src/utils/signature-verifier.ts +7 -8
  201. package/src/utils/ssrf-validator.test.ts +3 -3
  202. package/tests/integration/room-management.test.ts +514 -0
  203. package/tests/integration/websocket.test.ts +1 -1
  204. package/tests/unit/handlers/agent-room-operation-response-handler.test.ts +394 -0
  205. package/tests/unit/handlers/agent-status-update-handler.test.ts +407 -0
  206. package/tests/unit/handlers/auth-success-handler-rooms.test.ts +699 -0
  207. package/tests/unit/handlers/list-available-agents-handler.test.ts +256 -0
  208. package/tests/unit/handlers/list-room-agents-handler.test.ts +294 -0
  209. package/tests/unit/handlers/room-operation-response-handler.test.ts +527 -0
  210. package/tests/unit/managers/agent-room-manager.test.ts +534 -0
  211. package/tests/unit/managers/room-management-manager.test.ts +438 -0
@@ -0,0 +1,635 @@
1
+ # OpenAI Codex + Teneo Consumer SDK Integration
2
+
3
+ Minimal example showing how to integrate **OpenAI Codex SDK** with **Teneo Consumer SDK** for intelligent agent routing and task orchestration.
4
+
5
+ ## Overview
6
+
7
+ This example demonstrates a powerful integration pattern where:
8
+ 1. **OpenAI Codex** analyzes user queries using thread-based conversations
9
+ 2. **Codex selects** the most appropriate Teneo agent for the task
10
+ 3. **Teneo SDK** executes the command on the selected agent
11
+ 4. **Combined response** returned with agent selection reasoning
12
+
13
+ ## Features
14
+
15
+ ### Integration Features
16
+ - **Intelligent Agent Routing**: Codex analyzes queries and selects the best Teneo agent
17
+ - **Thread-Based Conversations**: Maintains conversation context across requests
18
+ - **Direct Codex Access**: Bypass Teneo and query Codex directly
19
+ - **Simple REST API**: Easy-to-use HTTP endpoints
20
+ - **Type-Safe**: Full TypeScript support with Zod validation
21
+
22
+ ### Modern SDK Features
23
+ - ✅ **Automatic Wallet Derivation**: No need to manually provide wallet address
24
+ - ✅ **Auto-Reconnection**: Exponential backoff with configurable retry attempts
25
+ - ✅ **Response Caching**: Better performance with configurable cache settings
26
+ - ✅ **Signature Verification**: Optional SEC-2 message signature verification
27
+ - ✅ **Flexible Configuration**: 15+ environment variables with sensible defaults
28
+ - ✅ **Type Safety**: Full TypeScript support with Zod validation
29
+
30
+ ## Prerequisites
31
+
32
+ 1. **Node.js** 18+ installed
33
+ 2. **OpenAI API Key** (get from https://platform.openai.com/api-keys)
34
+ 3. **Teneo Credentials** (WebSocket URL, Private Key)
35
+ 4. **Built Teneo SDK** (run `npm run build` in project root)
36
+ 5. **Active Teneo agents** running in your room
37
+
38
+ ## Installation
39
+
40
+ ```bash
41
+ # From project root
42
+ npm install
43
+
44
+ # Build the SDK
45
+ npm run build
46
+
47
+ # Navigate to example directory
48
+ cd examples/openai-teneo
49
+
50
+ # Install Codex SDK (if not already installed)
51
+ npm install @openai/codex-sdk
52
+ ```
53
+
54
+ ## Configuration
55
+
56
+ Create `.env` file from the template:
57
+
58
+ ```bash
59
+ cp examples/openai-teneo/.env.example examples/openai-teneo/.env
60
+ ```
61
+
62
+ ### Required Configuration
63
+
64
+ ```env
65
+ # OpenAI Configuration
66
+ OPENAI_API_KEY=sk-proj-your-openai-api-key-here
67
+
68
+ # Teneo Network Connection
69
+ WS_URL=wss://your-teneo-server.com/ws
70
+ PRIVATE_KEY=0x1234567890123456789012345678901234567890123456789012345678901234
71
+ WALLET_ADDRESS=0x1234567890123456789012345678901234567890 # Optional - auto-derived from private key
72
+
73
+ # Room Configuration
74
+ DEFAULT_ROOM=general # or KOL tracker for X-Agent features
75
+ ```
76
+
77
+ ### Optional Configuration
78
+
79
+ ```env
80
+ # Security Features
81
+ ENABLE_SIGNATURE_VERIFICATION=false # Enable SEC-2 message signature verification
82
+ TRUSTED_ADDRESSES=0xAddress1,0xAddress2 # Comma-separated list of trusted agent addresses
83
+
84
+ # Performance Tuning
85
+ ENABLE_CACHE=true # Enable agent caching
86
+ CACHE_TIMEOUT=300000 # Cache timeout (5 minutes)
87
+ MAX_CACHE_SIZE=100 # Maximum cache entries
88
+
89
+ # Connection Settings
90
+ ENABLE_RECONNECTION=true # Enable automatic reconnection
91
+ RECONNECT_DELAY=5000 # Reconnection delay (5 seconds)
92
+ MAX_RECONNECT_ATTEMPTS=10 # Maximum reconnection attempts
93
+
94
+ # Logging
95
+ LOG_LEVEL=info # debug | info | warn | error | silent
96
+
97
+ # Server
98
+ PORT=3000 # API server port
99
+ ```
100
+
101
+ ## Usage
102
+
103
+ ### Start the Server
104
+
105
+ ```bash
106
+ # From the example directory
107
+ npx tsx index.ts
108
+
109
+ # Or from project root
110
+ npx tsx examples/openai-teneo/index.ts
111
+ ```
112
+
113
+ The server will start on http://localhost:3000 (or the port specified in `.env`).
114
+
115
+ ## API Endpoints
116
+
117
+ ### GET /health
118
+
119
+ Health check endpoint showing connection status.
120
+
121
+ **Response:**
122
+ ```json
123
+ {
124
+ "status": "ok",
125
+ "teneo": {
126
+ "connected": true,
127
+ "authenticated": true
128
+ },
129
+ "codex": {
130
+ "initialized": true,
131
+ "apiKeyConfigured": true
132
+ }
133
+ }
134
+ ```
135
+
136
+ ### POST /query
137
+
138
+ **Smart Agent Routing** - Codex analyzes query and selects best Teneo agent.
139
+
140
+ **Request:**
141
+ ```json
142
+ {
143
+ "message": "timeline @elonmusk 3"
144
+ }
145
+ ```
146
+
147
+ **How it works:**
148
+ 1. Fetches available Teneo agents via `teneoSDK.getAgents()`
149
+ 2. Codex analyzes the query using thread-based conversation
150
+ 3. Codex selects the most appropriate agent for the task
151
+ 4. Query forwarded to selected agent via `teneoSDK.sendDirectCommand()`
152
+ 5. Response returned with agent selection + agent response
153
+
154
+ **Response:**
155
+ ```json
156
+ {
157
+ "success": true,
158
+ "data": {
159
+ "query": "timeline @elonmusk 3",
160
+ "selectedAgent": "X Platform Agent",
161
+ "selectedAgentId": "x-agent-001",
162
+ "response": "Here are the latest 3 tweets from @elonmusk...",
163
+ "codexSelection": "X Platform Agent",
164
+ "metadata": {
165
+ "agentName": "X Platform Agent",
166
+ "duration": 2619
167
+ }
168
+ }
169
+ }
170
+ ```
171
+
172
+ **Response Time:** Typically 2-3 seconds (Codex selection + Teneo execution)
173
+
174
+ ### POST /codex
175
+
176
+ **Direct Codex Query** - Bypass Teneo and query Codex directly with thread support.
177
+
178
+ **Request:**
179
+ ```json
180
+ {
181
+ "message": "Explain quantum computing in simple terms",
182
+ "threadId": "thread-abc123" // Optional - for conversation continuity
183
+ }
184
+ ```
185
+
186
+ **Response:**
187
+ ```json
188
+ {
189
+ "success": true,
190
+ "data": {
191
+ "response": "Quantum computing is a revolutionary approach to computation that leverages quantum mechanics...",
192
+ "threadId": "thread-abc123",
193
+ "usage": {
194
+ "promptTokens": 15,
195
+ "completionTokens": 180,
196
+ "totalTokens": 195
197
+ }
198
+ }
199
+ }
200
+ ```
201
+
202
+ **Thread Support:** Include `threadId` to maintain conversation context across requests.
203
+
204
+ ### List Teneo Agents
205
+ ```bash
206
+ GET /agents
207
+ ```
208
+
209
+ **Response:**
210
+ ```json
211
+ {
212
+ "success": true,
213
+ "agents": [
214
+ {
215
+ "id": "agent-001",
216
+ "name": "weather-agent",
217
+ "description": "Provides weather information",
218
+ "capabilities": ["weather", "forecast"]
219
+ }
220
+ ]
221
+ }
222
+ ```
223
+
224
+ ## Usage Examples
225
+
226
+ ### Using curl
227
+
228
+ ```bash
229
+ # Health check
230
+ curl http://localhost:3000/health
231
+
232
+ # Smart query (Codex + Teneo) - Get X timeline
233
+ curl -X POST http://localhost:3000/query \
234
+ -H "Content-Type: application/json" \
235
+ -d '{"message": "timeline @elonmusk 5"}'
236
+
237
+ # Direct Codex query with thread support
238
+ curl -X POST http://localhost:3000/codex \
239
+ -H "Content-Type: application/json" \
240
+ -d '{"message": "Explain quantum computing", "threadId": "my-conversation"}'
241
+
242
+ # List available Teneo agents
243
+ curl http://localhost:3000/agents
244
+ ```
245
+
246
+ ### Using JavaScript/TypeScript
247
+
248
+ ```typescript
249
+ import fetch from 'node-fetch';
250
+
251
+ // Example 1: Smart agent routing (Codex selects agent)
252
+ const queryResponse = await fetch('http://localhost:3000/query', {
253
+ method: 'POST',
254
+ headers: { 'Content-Type': 'application/json' },
255
+ body: JSON.stringify({
256
+ message: 'timeline @VitalikButerin 10'
257
+ })
258
+ });
259
+
260
+ const queryData = await queryResponse.json();
261
+ console.log('Selected Agent:', queryData.data.selectedAgent);
262
+ console.log('Response:', queryData.data.response);
263
+
264
+ // Example 2: Direct Codex query with thread continuity
265
+ const threadId = 'my-thread-123';
266
+
267
+ // First message in thread
268
+ const codexResponse1 = await fetch('http://localhost:3000/codex', {
269
+ method: 'POST',
270
+ headers: { 'Content-Type': 'application/json' },
271
+ body: JSON.stringify({
272
+ message: 'What is quantum computing?',
273
+ threadId
274
+ })
275
+ });
276
+
277
+ // Follow-up message in same thread
278
+ const codexResponse2 = await fetch('http://localhost:3000/codex', {
279
+ method: 'POST',
280
+ headers: { 'Content-Type': 'application/json' },
281
+ body: JSON.stringify({
282
+ message: 'How is it different from classical computing?',
283
+ threadId // Same thread ID maintains context
284
+ })
285
+ });
286
+
287
+ const data2 = await codexResponse2.json();
288
+ console.log('Codex Response:', data2.data.response);
289
+ ```
290
+
291
+ ## Architecture
292
+
293
+ ```
294
+ ┌─────────────────┐
295
+ │ HTTP Client │
296
+ │ (curl/fetch) │
297
+ └────────┬────────┘
298
+
299
+ │ POST /query
300
+
301
+ ┌─────────────────────────────────────┐
302
+ │ Express REST API Server │
303
+ │ ┌────────────────────────────────┐ │
304
+ │ │ Endpoint: /query │ │
305
+ │ └────────┬───────────────────────┘ │
306
+ │ │ │
307
+ │ ┌────────▼────────┐ ┌───────────┐ │
308
+ │ │ Codex SDK │ │ Teneo SDK │ │
309
+ │ │ (Thread API) │ │ (WebSocket│ │
310
+ │ └────────┬────────┘ └─────┬─────┘ │
311
+ └───────────┼───────────────────┼──────┘
312
+ │ │
313
+ ▼ ▼
314
+ ┌─────────────────┐ ┌─────────────────┐
315
+ │ OpenAI Codex │ │ Teneo Network │
316
+ │ (Agent Select) │ │ (X-Agent, etc) │
317
+ └─────────────────┘ └─────────────────┘
318
+
319
+ Flow:
320
+ 1. Client → POST /query {"message": "timeline @user"}
321
+ 2. Server → Get available agents from Teneo SDK
322
+ 3. Server → Ask Codex to select best agent
323
+ 4. Codex → Returns selected agent name
324
+ 5. Server → Execute command on selected agent via Teneo SDK
325
+ 6. Teneo → Agent processes and responds
326
+ 7. Server → Return combined response to client
327
+ ```
328
+
329
+ ## How It Works
330
+
331
+ ### Smart Agent Routing (/query endpoint)
332
+
333
+ 1. **Fetch Available Agents**
334
+ ```typescript
335
+ const agents = teneoSDK.getAgents();
336
+ ```
337
+
338
+ 2. **Ask Codex to Select Best Agent**
339
+ ```typescript
340
+ const thread = codex.startThread();
341
+ const codexResponse = await thread.run(`
342
+ You are an agent coordinator. Select the most appropriate agent.
343
+ Available agents: ${agentList}
344
+ User query: ${message}
345
+ Respond with ONLY the agent name.
346
+ `);
347
+ ```
348
+
349
+ 3. **Extract Agent Selection**
350
+ ```typescript
351
+ const selectedAgentName = codexResponse.finalResponse.trim();
352
+ const selectedAgent = agents.find(a => a.name === selectedAgentName);
353
+ ```
354
+
355
+ 4. **Execute Command on Selected Agent**
356
+ ```typescript
357
+ const teneoResponse = await teneoSDK.sendDirectCommand({
358
+ agent: selectedAgent.id,
359
+ command: message,
360
+ room: DEFAULT_ROOM
361
+ }, true); // waitForResponse = true
362
+ ```
363
+
364
+ 5. **Return Combined Response**
365
+ - Agent selection reasoning from Codex
366
+ - Actual response from Teneo agent
367
+ - Metadata (duration, timestamps, etc.)
368
+
369
+ ### Key Implementation Details
370
+
371
+ - **Codex Response Parsing**: Extracts `finalResponse` property from Codex SDK response object
372
+ - **Fallback Matching**: SDK uses room-based fallback when server doesn't echo `client_request_id`
373
+ - **Thread Support**: Codex maintains conversation context via thread IDs
374
+ - **Type Safety**: Full TypeScript with Zod validation throughout
375
+
376
+ ## Benefits
377
+
378
+ - **Intelligent Routing**: Codex's semantic understanding selects the optimal agent
379
+ - **Thread Continuity**: Maintain conversation context across multiple requests
380
+ - **Reliable Messaging**: SDK-level fallback matching handles various server implementations
381
+ - **Flexible**: Use Codex directly (/codex) or combined with Teneo (/query)
382
+ - **Fast**: Typical response time 2-3 seconds end-to-end
383
+ - **Simple**: Minimal code (~280 lines), easy to understand and extend
384
+ - **Type-Safe**: Full TypeScript support with runtime validation
385
+
386
+ ## SDK Configuration
387
+
388
+ This example uses the **modern SDKConfigBuilder pattern** for clean, type-safe Teneo SDK configuration.
389
+
390
+ ### Configuration Pattern
391
+
392
+ ```typescript
393
+ import { SDKConfigBuilder, TeneoSDK } from '../../dist/index.js';
394
+
395
+ const config = new SDKConfigBuilder()
396
+ .withWebSocketUrl(WS_URL)
397
+ .withAuthentication(PRIVATE_KEY, WALLET_ADDRESS) // Wallet auto-derived if not provided
398
+ .withRoom(DEFAULT_ROOM)
399
+ .withReconnection({ enabled: true, delay: 5000, maxAttempts: 10 })
400
+ .withResponseFormat({ format: 'both', includeMetadata: true })
401
+ .withLogging(LOG_LEVEL)
402
+ .withCache(true, 300000, 100)
403
+ .withSignatureVerification({
404
+ enabled: ENABLE_SIG_VERIFICATION,
405
+ trustedAddresses: TRUSTED_ADDRESSES,
406
+ requireFor: ['task_response', 'agent_selected'],
407
+ strictMode: false
408
+ })
409
+ .build();
410
+
411
+ const teneoSDK = new TeneoSDK(config);
412
+ ```
413
+
414
+ ### Key Features
415
+
416
+ - ✅ **Automatic Wallet Derivation**: Wallet address automatically derived from private key using viem
417
+ - ✅ **Auto-Reconnection**: Automatic reconnection with exponential backoff
418
+ - ✅ **Response Caching**: Agent response caching for better performance
419
+ - ✅ **Signature Verification**: Optional SEC-2 message signature verification
420
+ - ✅ **Flexible Configuration**: Environment-based with sensible defaults
421
+ - ✅ **Type Safety**: Full TypeScript support with Zod validation
422
+
423
+ ## Environment Variables
424
+
425
+ ### Required
426
+
427
+ | Variable | Description |
428
+ |----------|-------------|
429
+ | `OPENAI_API_KEY` | OpenAI API key (get from https://platform.openai.com/api-keys) |
430
+ | `WS_URL` | Teneo WebSocket URL |
431
+ | `PRIVATE_KEY` | Ethereum private key (with 0x prefix) |
432
+
433
+ ### Optional (with defaults)
434
+
435
+ | Variable | Default | Description |
436
+ |----------|---------|-------------|
437
+ | `OPENAI_MODEL` | `gpt-4-turbo-preview` | OpenAI model to use |
438
+ | `WALLET_ADDRESS` | *(auto-derived)* | Ethereum wallet (auto-derived from private key if not provided) |
439
+ | `DEFAULT_ROOM` | `general` | Default Teneo room |
440
+ | `ENABLE_SIGNATURE_VERIFICATION` | `false` | Enable SEC-2 signature verification |
441
+ | `TRUSTED_ADDRESSES` | *(empty)* | Comma-separated trusted agent addresses |
442
+ | `ENABLE_CACHE` | `true` | Enable agent caching |
443
+ | `CACHE_TIMEOUT` | `300000` | Cache timeout in ms (5 minutes) |
444
+ | `MAX_CACHE_SIZE` | `100` | Maximum cache entries |
445
+ | `ENABLE_RECONNECTION` | `true` | Enable automatic reconnection |
446
+ | `RECONNECT_DELAY` | `5000` | Reconnection delay in ms |
447
+ | `MAX_RECONNECT_ATTEMPTS` | `10` | Maximum reconnection attempts |
448
+ | `LOG_LEVEL` | `info` | Logging level: debug\|info\|warn\|error\|silent |
449
+ | `PORT` | `3000` | API server port |
450
+
451
+ See `.env.example` for complete documentation.
452
+
453
+ ## Troubleshooting
454
+
455
+ ### Teneo Connection Issues
456
+
457
+ **Problem:** Teneo SDK won't connect
458
+
459
+ **Solutions:**
460
+ - Verify `WS_URL` and `PRIVATE_KEY` in `.env`
461
+ - Ensure `PRIVATE_KEY` starts with `0x` prefix
462
+ - Check logs with `LOG_LEVEL=debug`
463
+ - Verify wallet has room access
464
+ - Test connection: `curl http://localhost:3000/health`
465
+
466
+ ### Wallet Not Whitelisted
467
+
468
+ **Problem:** "Access restricted: Your wallet is not whitelisted"
469
+
470
+ **Solutions:**
471
+ - Contact Teneo administrator to whitelist your wallet
472
+ - Verify you're using the correct room in `DEFAULT_ROOM`
473
+ - Check your `WALLET_ADDRESS` (or let it auto-derive from `PRIVATE_KEY`)
474
+ - List available rooms and confirm agent presence
475
+
476
+ ### Codex API Errors
477
+
478
+ **Problem:** Codex requests failing with 401 Unauthorized
479
+
480
+ **Solutions:**
481
+ - Verify `OPENAI_API_KEY` is correct in `.env`
482
+ - Ensure API key has sufficient credits at https://platform.openai.com/usage
483
+ - Check Codex SDK is initialized with explicit API key:
484
+ ```typescript
485
+ const codex = new Codex({
486
+ apiKey: OPENAI_API_KEY || process.env.OPENAI_API_KEY
487
+ });
488
+ ```
489
+ - Test Codex separately via `/codex` endpoint
490
+
491
+ ### Agent Selection Issues
492
+
493
+ **Problem:** Codex selects wrong agent or "[object Object]" error
494
+
495
+ **Solutions:**
496
+ - Check available agents: `curl http://localhost:3000/agents`
497
+ - Verify agents are online in your Teneo room
498
+ - Ensure proper Codex response parsing:
499
+ ```typescript
500
+ const selectedAgentName = (codexResponse as any).finalResponse
501
+ || (codexResponse as any).text
502
+ || String(codexResponse);
503
+ ```
504
+ - Test agent directly with known agent ID
505
+
506
+ ### Timeout Errors
507
+
508
+ **Problem:** Queries timeout before response arrives
509
+
510
+ **Solutions:**
511
+ - The SDK uses intelligent fallback matching for responses
512
+ - Check if agent is responding: `curl http://localhost:3000/agents`
513
+ - Increase timeout in request: `{"message": "...", "timeout": 60000}`
514
+ - Verify the agent is in the correct room (`DEFAULT_ROOM`)
515
+ - Check logs with `LOG_LEVEL=debug` to see fallback matching in action
516
+
517
+ **Note:** The SDK automatically handles servers that don't echo `client_request_id` by using room-based fallback matching within a 60-second window.
518
+
519
+ ### Message Format Errors
520
+
521
+ **Problem:** Server returns "Agents should use TypeTaskResponse instead of TypeMessage" (code: 400)
522
+
523
+ **Solutions:**
524
+ - Try `DEFAULT_ROOM=general` instead of specific agent rooms
525
+ - This is a server-side protocol error, not an SDK configuration issue
526
+ - Contact your Teneo administrator about room configuration
527
+ - The SDK handles both "message" and "task_response" types automatically
528
+
529
+ ## Error Handling
530
+
531
+ The API includes comprehensive error handling:
532
+
533
+ - **400 Bad Request**: Missing required parameters
534
+ - **500 Internal Server Error**: OpenAI or Teneo errors
535
+
536
+ All errors return consistent JSON format:
537
+ ```json
538
+ {
539
+ "success": false,
540
+ "error": "Error message here"
541
+ }
542
+ ```
543
+
544
+ ## Code Structure
545
+
546
+ ```
547
+ examples/openai-teneo/
548
+ ├── index.ts # Main server (~280 lines)
549
+ ├── package.json # Dependencies
550
+ ├── .env.example # Environment template
551
+ ├── .env # Your credentials (git-ignored)
552
+ └── README.md # This file
553
+ ```
554
+
555
+ ### Key Code Sections
556
+
557
+ **1. Codex SDK Initialization (lines 62-66)**
558
+ ```typescript
559
+ const codex = new Codex({
560
+ apiKey: OPENAI_API_KEY || process.env.OPENAI_API_KEY
561
+ });
562
+ ```
563
+
564
+ **2. Teneo SDK Configuration (lines 40-58)**
565
+ ```typescript
566
+ const config = new SDKConfigBuilder()
567
+ .withWebSocketUrl(WS_URL)
568
+ .withAuthentication(PRIVATE_KEY, WALLET_ADDRESS)
569
+ .withRoom(DEFAULT_ROOM)
570
+ .withReconnection({ enabled: true, delay: 5000, maxAttempts: 10 })
571
+ .withResponseFormat({ format: 'both', includeMetadata: true })
572
+ .withLogging(LOG_LEVEL)
573
+ .withCache(ENABLE_CACHE, CACHE_TIMEOUT, MAX_CACHE_SIZE)
574
+ .withSignatureVerification({
575
+ enabled: ENABLE_SIG_VERIFICATION,
576
+ trustedAddresses: TRUSTED_ADDRESSES,
577
+ requireFor: ['task_response', 'agent_selected'],
578
+ strictMode: false
579
+ })
580
+ .build();
581
+ ```
582
+
583
+ **3. Smart Agent Routing (lines 90-196)**
584
+ - Fetch available agents from Teneo
585
+ - Ask Codex to analyze and select best agent
586
+ - Parse Codex response (extract `finalResponse`)
587
+ - Execute command via `sendDirectCommand` with `waitForResponse: true`
588
+ - Return combined response
589
+
590
+ **4. Codex Response Parsing (lines 125-143)**
591
+ ```typescript
592
+ let selectedAgentName: string;
593
+ if (typeof codexResponse === 'string') {
594
+ selectedAgentName = codexResponse.trim();
595
+ } else if (codexResponse && typeof codexResponse === 'object') {
596
+ selectedAgentName = (codexResponse as any).finalResponse
597
+ || (codexResponse as any).text
598
+ || (codexResponse as any).content
599
+ || String(codexResponse);
600
+ // Handle nested objects
601
+ if (typeof selectedAgentName === 'object') {
602
+ selectedAgentName = JSON.stringify(selectedAgentName);
603
+ }
604
+ selectedAgentName = selectedAgentName.trim();
605
+ }
606
+ ```
607
+
608
+ ## Related Examples
609
+
610
+ - [Claude Agent + Teneo](../claude-agent-x-follower/) - Claude Agent SDK with custom tools
611
+ - [n8n + Teneo](../n8n-teneo/) - Visual workflow automation
612
+ - [Production Dashboard](../production-dashboard/) - Full-featured dashboard
613
+
614
+ ### Comparison
615
+
616
+ | Feature | OpenAI Codex | Claude Agent | n8n |
617
+ |---------|--------------|--------------|-----|
618
+ | **Interface** | REST API | CLI Tool | Visual Workflows |
619
+ | **AI Model** | OpenAI Codex | Claude 3.5 | N/A (HTTP only) |
620
+ | **Agent Selection** | ✅ Intelligent | ✅ Custom Tool | ❌ Manual |
621
+ | **Thread Support** | ✅ Yes | ✅ Conversation | ❌ No |
622
+ | **Use Case** | API Integration | Developer Tool | Automation |
623
+ | **Complexity** | ~280 lines | ~220 lines | ~180 lines |
624
+
625
+ **Note:** All examples now use the same **modern SDKConfigBuilder pattern** with:
626
+ - ✅ Automatic wallet derivation from private key
627
+ - ✅ Auto-reconnection with exponential backoff
628
+ - ✅ Agent response caching for performance
629
+ - ✅ Optional SEC-2 signature verification
630
+ - ✅ SDK-level fallback matching for reliable message correlation
631
+ - ✅ Comprehensive environment-based configuration
632
+
633
+ ## License
634
+
635
+ MIT