@flink-app/flink 0.14.3 → 2.0.0-alpha.100

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 (280) hide show
  1. package/CHANGELOG.md +1051 -0
  2. package/SCHEMA_EXTRACTION_ANALYSIS.md +494 -0
  3. package/SIMPLE_AST_FEASIBILITY.md +570 -0
  4. package/bin/flink.ts +13 -2
  5. package/cli/build.ts +24 -44
  6. package/cli/clean.ts +13 -25
  7. package/cli/cli-utils.ts +190 -17
  8. package/cli/dev.ts +252 -0
  9. package/cli/loadEnvFiles.ts +116 -0
  10. package/cli/run.ts +45 -62
  11. package/dist/bin/flink.js +61 -2
  12. package/dist/cli/build.js +20 -25
  13. package/dist/cli/clean.js +12 -10
  14. package/dist/cli/cli-utils.d.ts +34 -3
  15. package/dist/cli/cli-utils.js +193 -12
  16. package/dist/cli/dev.d.ts +2 -0
  17. package/dist/cli/dev.js +279 -0
  18. package/dist/cli/loadEnvFiles.d.ts +30 -0
  19. package/dist/cli/loadEnvFiles.js +113 -0
  20. package/dist/cli/run.js +47 -46
  21. package/dist/src/DependencyTracker.d.ts +44 -0
  22. package/dist/src/DependencyTracker.js +239 -0
  23. package/dist/src/FlinkApp.d.ts +163 -10
  24. package/dist/src/FlinkApp.js +847 -184
  25. package/dist/src/FlinkContext.d.ts +41 -0
  26. package/dist/src/FlinkErrors.d.ts +19 -6
  27. package/dist/src/FlinkErrors.js +36 -42
  28. package/dist/src/FlinkHttpHandler.d.ts +219 -26
  29. package/dist/src/FlinkHttpHandler.js +37 -1
  30. package/dist/src/FlinkJob.d.ts +10 -0
  31. package/dist/src/FlinkLog.d.ts +82 -18
  32. package/dist/src/FlinkLog.js +165 -13
  33. package/dist/src/FlinkLogFactory.d.ts +288 -0
  34. package/dist/src/FlinkLogFactory.js +619 -0
  35. package/dist/src/FlinkRepo.d.ts +10 -2
  36. package/dist/src/FlinkRepo.js +11 -1
  37. package/dist/src/FlinkRequestContext.d.ts +63 -0
  38. package/dist/src/FlinkRequestContext.js +74 -0
  39. package/dist/src/FlinkResponse.d.ts +6 -0
  40. package/dist/src/FlinkService.d.ts +38 -0
  41. package/dist/src/FlinkService.js +46 -0
  42. package/dist/src/LeaderElection.d.ts +45 -0
  43. package/dist/src/LeaderElection.js +269 -0
  44. package/dist/src/SchemaCache.d.ts +84 -0
  45. package/dist/src/SchemaCache.js +289 -0
  46. package/dist/src/TypeScriptCompiler.d.ts +161 -51
  47. package/dist/src/TypeScriptCompiler.js +1253 -617
  48. package/dist/src/TypeScriptUtils.js +4 -0
  49. package/dist/src/ai/AgentRunner.d.ts +39 -0
  50. package/dist/src/ai/AgentRunner.js +760 -0
  51. package/dist/src/ai/ConversationAgent.d.ts +279 -0
  52. package/dist/src/ai/ConversationAgent.js +404 -0
  53. package/dist/src/ai/ConversationFlinkAgent.d.ts +278 -0
  54. package/dist/src/ai/ConversationFlinkAgent.js +404 -0
  55. package/dist/src/ai/FlinkAgent.d.ts +690 -0
  56. package/dist/src/ai/FlinkAgent.js +729 -0
  57. package/dist/src/ai/FlinkTool.d.ts +135 -0
  58. package/dist/src/ai/FlinkTool.js +2 -0
  59. package/dist/src/ai/InMemoryConversationAgent.d.ts +121 -0
  60. package/dist/src/ai/InMemoryConversationAgent.js +209 -0
  61. package/dist/src/ai/LLMAdapter.d.ts +148 -0
  62. package/dist/src/ai/LLMAdapter.js +2 -0
  63. package/dist/src/ai/PersistentFlinkAgent.d.ts +278 -0
  64. package/dist/src/ai/PersistentFlinkAgent.js +403 -0
  65. package/dist/src/ai/SubAgentExecutor.d.ts +38 -0
  66. package/dist/src/ai/SubAgentExecutor.js +223 -0
  67. package/dist/src/ai/ToolExecutor.d.ts +64 -0
  68. package/dist/src/ai/ToolExecutor.js +497 -0
  69. package/dist/src/ai/agentInstructions.d.ts +68 -0
  70. package/dist/src/ai/agentInstructions.js +286 -0
  71. package/dist/src/ai/index.d.ts +8 -0
  72. package/dist/src/ai/index.js +26 -0
  73. package/dist/src/ai/instructionFileLoader.d.ts +44 -0
  74. package/dist/src/ai/instructionFileLoader.js +179 -0
  75. package/dist/src/auth/FlinkAuthPlugin.d.ts +1 -1
  76. package/dist/src/handlers/StreamWriterFactory.d.ts +20 -0
  77. package/dist/src/handlers/StreamWriterFactory.js +83 -0
  78. package/dist/src/index.d.ts +14 -0
  79. package/dist/src/index.js +17 -0
  80. package/dist/src/loadPluginSchemas.d.ts +45 -0
  81. package/dist/src/loadPluginSchemas.js +143 -0
  82. package/dist/src/schema-extraction/ComplexTypeDetection.d.ts +40 -0
  83. package/dist/src/schema-extraction/ComplexTypeDetection.js +75 -0
  84. package/dist/src/schema-extraction/TypeScriptSourceParser.d.ts +321 -0
  85. package/dist/src/schema-extraction/TypeScriptSourceParser.js +925 -0
  86. package/dist/src/schema-extraction/TypeScriptSourceParser.spec.d.ts +1 -0
  87. package/dist/src/schema-extraction/TypeScriptSourceParser.spec.js +233 -0
  88. package/dist/src/schema-extraction/TypeScriptTokenizer.d.ts +57 -0
  89. package/dist/src/schema-extraction/TypeScriptTokenizer.js +177 -0
  90. package/dist/src/schema-extraction/index.d.ts +2 -0
  91. package/dist/src/schema-extraction/index.js +20 -0
  92. package/dist/src/schema-extraction/types.d.ts +31 -0
  93. package/dist/src/schema-extraction/types.js +2 -0
  94. package/dist/src/utils/loadFlinkConfig.d.ts +53 -0
  95. package/dist/src/utils/loadFlinkConfig.js +77 -0
  96. package/dist/src/utils.d.ts +30 -0
  97. package/dist/src/utils.js +52 -0
  98. package/dist/src/workers/SchemaGeneratorWorker.d.ts +1 -0
  99. package/dist/src/workers/SchemaGeneratorWorker.js +49 -0
  100. package/dist/src/workers/WorkerPool.d.ts +60 -0
  101. package/dist/src/workers/WorkerPool.js +306 -0
  102. package/examples/logging-hierarchical-example.ts +125 -0
  103. package/package.json +29 -4
  104. package/readme.md +499 -0
  105. package/spec/AgentDescendantDetection.spec.ts +335 -0
  106. package/spec/AgentDuplicateDetection.spec.ts +112 -0
  107. package/spec/AgentObserver.spec.ts +266 -0
  108. package/spec/AgentRunner.spec.ts +1062 -0
  109. package/spec/AsyncLocalStorageContext.spec.ts +223 -0
  110. package/spec/ConversationHooks.spec.ts +257 -0
  111. package/spec/FlinkAgent.spec.ts +681 -0
  112. package/spec/FlinkApp.htmlResponse.spec.ts +260 -0
  113. package/spec/FlinkApp.onError.invocation.spec.ts +151 -0
  114. package/spec/FlinkApp.onError.spec.ts +1 -2
  115. package/spec/FlinkApp.query.spec.ts +107 -0
  116. package/spec/FlinkApp.routeOrdering.spec.ts +61 -0
  117. package/spec/FlinkApp.undefinedResponse.spec.ts +123 -0
  118. package/spec/FlinkApp.validationMode.spec.ts +155 -0
  119. package/spec/FlinkJob.spec.ts +171 -0
  120. package/spec/FlinkLogFactory.spec.ts +337 -0
  121. package/spec/FlinkRepo.spec.ts +1 -1
  122. package/spec/LeaderElection.spec.ts +174 -0
  123. package/spec/StreamingIntegration.spec.ts +139 -0
  124. package/spec/ToolExecutor.spec.ts +465 -0
  125. package/spec/TypeScriptCompiler.spec.ts +1 -1
  126. package/spec/TypeScriptSourceParser.spec.ts +1215 -0
  127. package/spec/TypeScriptTokenizer.spec.ts +366 -0
  128. package/spec/ai/ContextCompaction.spec.ts +405 -0
  129. package/spec/ai/ConversationAgent.spec.ts +520 -0
  130. package/spec/ai/InMemoryConversationAgent.spec.ts +144 -0
  131. package/spec/ai/agentInstructions.spec.ts +358 -0
  132. package/spec/fixtures/agent-instructions/TestAgent.ts +24 -0
  133. package/spec/fixtures/agent-instructions/simple.md +3 -0
  134. package/spec/fixtures/agent-instructions/template.md +18 -0
  135. package/spec/fixtures/agent-instructions/yaml-format.yaml +9 -0
  136. package/spec/mock-project/dist/.tsbuildinfo +1 -0
  137. package/spec/mock-project/dist/spec/mock-project/src/handlers/GetCar.js +56 -0
  138. package/spec/mock-project/dist/spec/mock-project/src/handlers/GetCar2.js +58 -0
  139. package/spec/mock-project/dist/spec/mock-project/src/handlers/GetCarWithArraySchema.js +52 -0
  140. package/spec/mock-project/dist/spec/mock-project/src/handlers/GetCarWithArraySchema2.js +52 -0
  141. package/spec/mock-project/dist/spec/mock-project/src/handlers/GetCarWithArraySchema3.js +52 -0
  142. package/spec/mock-project/dist/spec/mock-project/src/handlers/GetCarWithLiteralSchema.js +54 -0
  143. package/spec/mock-project/dist/spec/mock-project/src/handlers/GetCarWithLiteralSchema2.js +54 -0
  144. package/spec/mock-project/dist/spec/mock-project/src/handlers/GetCarWithSchemaInFile.js +57 -0
  145. package/spec/mock-project/dist/spec/mock-project/src/handlers/GetCarWithSchemaInFile2.js +57 -0
  146. package/spec/mock-project/dist/spec/mock-project/src/handlers/ManuallyAddedHandler.js +53 -0
  147. package/spec/mock-project/dist/spec/mock-project/src/handlers/ManuallyAddedHandler2.js +55 -0
  148. package/spec/mock-project/dist/spec/mock-project/src/handlers/PatchCar.js +57 -0
  149. package/spec/mock-project/dist/spec/mock-project/src/handlers/PatchOnboardingSession.js +75 -0
  150. package/spec/mock-project/dist/spec/mock-project/src/handlers/PatchOrderWithComplexTypes.js +57 -0
  151. package/spec/mock-project/dist/spec/mock-project/src/handlers/PatchProductWithIntersection.js +58 -0
  152. package/spec/mock-project/dist/spec/mock-project/src/handlers/PatchUserWithUnion.js +58 -0
  153. package/spec/mock-project/dist/spec/mock-project/src/handlers/PostCar.js +54 -0
  154. package/spec/mock-project/dist/spec/mock-project/src/handlers/PostLogin.js +55 -0
  155. package/spec/mock-project/dist/spec/mock-project/src/handlers/PostLogout.js +54 -0
  156. package/spec/mock-project/dist/spec/mock-project/src/handlers/PutCar.js +54 -0
  157. package/spec/mock-project/dist/spec/mock-project/src/index.js +83 -0
  158. package/spec/mock-project/dist/spec/mock-project/src/repos/CarRepo.js +26 -0
  159. package/spec/mock-project/dist/spec/mock-project/src/schemas/Car.js +2 -0
  160. package/spec/mock-project/dist/spec/mock-project/src/schemas/DefaultExportSchema.js +2 -0
  161. package/spec/mock-project/dist/spec/mock-project/src/schemas/FileWithTwoSchemas.js +2 -0
  162. package/spec/mock-project/dist/src/FlinkApp.js +1000 -0
  163. package/spec/mock-project/dist/src/FlinkContext.js +2 -0
  164. package/spec/mock-project/dist/src/FlinkErrors.js +143 -0
  165. package/spec/mock-project/dist/src/FlinkHttpHandler.js +47 -0
  166. package/spec/mock-project/dist/src/FlinkJob.js +2 -0
  167. package/spec/mock-project/dist/src/FlinkLog.js +119 -0
  168. package/spec/mock-project/dist/src/FlinkLogFactory.js +617 -0
  169. package/spec/mock-project/dist/src/FlinkPlugin.js +2 -0
  170. package/spec/mock-project/dist/src/FlinkRepo.js +224 -0
  171. package/spec/mock-project/dist/src/FlinkRequestContext.js +74 -0
  172. package/spec/mock-project/dist/src/FlinkResponse.js +2 -0
  173. package/spec/mock-project/dist/src/ai/AgentExecutor.js +279 -0
  174. package/spec/mock-project/dist/src/ai/AgentRunner.js +632 -0
  175. package/spec/mock-project/dist/src/ai/ConversationAgent.js +402 -0
  176. package/spec/mock-project/dist/src/ai/ConversationFlinkAgent.js +422 -0
  177. package/spec/mock-project/dist/src/ai/FlinkAgent.js +699 -0
  178. package/spec/mock-project/dist/src/ai/FlinkTool.js +2 -0
  179. package/spec/mock-project/dist/src/ai/InMemoryConversationAgent.js +209 -0
  180. package/spec/mock-project/dist/src/ai/LLMAdapter.js +2 -0
  181. package/spec/mock-project/dist/src/ai/SubAgentExecutor.js +223 -0
  182. package/spec/mock-project/dist/src/ai/ToolExecutor.js +412 -0
  183. package/spec/mock-project/dist/src/ai/agentInstructions.js +246 -0
  184. package/spec/mock-project/dist/src/auth/FlinkAuthPlugin.js +2 -0
  185. package/spec/mock-project/dist/src/auth/FlinkAuthUser.js +2 -0
  186. package/spec/mock-project/dist/src/handlers/GetCar.js +26 -52
  187. package/spec/mock-project/dist/src/handlers/GetCar.js.map +1 -0
  188. package/spec/mock-project/dist/src/handlers/GetCar2.js +32 -54
  189. package/spec/mock-project/dist/src/handlers/GetCar2.js.map +1 -0
  190. package/spec/mock-project/dist/src/handlers/GetCarWithArraySchema.js +26 -48
  191. package/spec/mock-project/dist/src/handlers/GetCarWithArraySchema.js.map +1 -0
  192. package/spec/mock-project/dist/src/handlers/GetCarWithArraySchema2.js +28 -48
  193. package/spec/mock-project/dist/src/handlers/GetCarWithArraySchema2.js.map +1 -0
  194. package/spec/mock-project/dist/src/handlers/GetCarWithArraySchema3.js +29 -48
  195. package/spec/mock-project/dist/src/handlers/GetCarWithArraySchema3.js.map +1 -0
  196. package/spec/mock-project/dist/src/handlers/GetCarWithLiteralSchema.js +26 -50
  197. package/spec/mock-project/dist/src/handlers/GetCarWithLiteralSchema.js.map +1 -0
  198. package/spec/mock-project/dist/src/handlers/GetCarWithLiteralSchema2.js +28 -50
  199. package/spec/mock-project/dist/src/handlers/GetCarWithLiteralSchema2.js.map +1 -0
  200. package/spec/mock-project/dist/src/handlers/GetCarWithSchemaInFile.js +27 -53
  201. package/spec/mock-project/dist/src/handlers/GetCarWithSchemaInFile.js.map +1 -0
  202. package/spec/mock-project/dist/src/handlers/GetCarWithSchemaInFile2.js +29 -53
  203. package/spec/mock-project/dist/src/handlers/GetCarWithSchemaInFile2.js.map +1 -0
  204. package/spec/mock-project/dist/src/handlers/ManuallyAddedHandler.js +16 -49
  205. package/spec/mock-project/dist/src/handlers/ManuallyAddedHandler.js.map +1 -0
  206. package/spec/mock-project/dist/src/handlers/ManuallyAddedHandler2.js +25 -50
  207. package/spec/mock-project/dist/src/handlers/ManuallyAddedHandler2.js.map +1 -0
  208. package/spec/mock-project/dist/src/handlers/PatchCar.js +27 -53
  209. package/spec/mock-project/dist/src/handlers/PatchCar.js.map +1 -0
  210. package/spec/mock-project/dist/src/handlers/PatchOnboardingSession.js +44 -70
  211. package/spec/mock-project/dist/src/handlers/PatchOnboardingSession.js.map +1 -0
  212. package/spec/mock-project/dist/src/handlers/PatchOrderWithComplexTypes.js +27 -53
  213. package/spec/mock-project/dist/src/handlers/PatchOrderWithComplexTypes.js.map +1 -0
  214. package/spec/mock-project/dist/src/handlers/PatchProductWithIntersection.js +28 -54
  215. package/spec/mock-project/dist/src/handlers/PatchProductWithIntersection.js.map +1 -0
  216. package/spec/mock-project/dist/src/handlers/PatchUserWithUnion.js +28 -54
  217. package/spec/mock-project/dist/src/handlers/PatchUserWithUnion.js.map +1 -0
  218. package/spec/mock-project/dist/src/handlers/PostCar.js +24 -50
  219. package/spec/mock-project/dist/src/handlers/PostCar.js.map +1 -0
  220. package/spec/mock-project/dist/src/handlers/PostLogin.js +25 -51
  221. package/spec/mock-project/dist/src/handlers/PostLogin.js.map +1 -0
  222. package/spec/mock-project/dist/src/handlers/PostLogout.js +24 -50
  223. package/spec/mock-project/dist/src/handlers/PostLogout.js.map +1 -0
  224. package/spec/mock-project/dist/src/handlers/PutCar.js +24 -50
  225. package/spec/mock-project/dist/src/handlers/PutCar.js.map +1 -0
  226. package/spec/mock-project/dist/src/handlers/StreamWriterFactory.js +83 -0
  227. package/spec/mock-project/dist/src/index.js +52 -76
  228. package/spec/mock-project/dist/src/index.js.map +1 -0
  229. package/spec/mock-project/dist/src/mock-data-generator.js +9 -0
  230. package/spec/mock-project/dist/src/repos/CarRepo.js +12 -24
  231. package/spec/mock-project/dist/src/repos/CarRepo.js.map +1 -0
  232. package/spec/mock-project/dist/src/schemas/Car.js +3 -1
  233. package/spec/mock-project/dist/src/schemas/Car.js.map +1 -0
  234. package/spec/mock-project/dist/src/schemas/DefaultExportSchema.js +3 -1
  235. package/spec/mock-project/dist/src/schemas/DefaultExportSchema.js.map +1 -0
  236. package/spec/mock-project/dist/src/schemas/FileWithTwoSchemas.js +3 -1
  237. package/spec/mock-project/dist/src/schemas/FileWithTwoSchemas.js.map +1 -0
  238. package/spec/mock-project/dist/src/utils.js +290 -0
  239. package/spec/mock-project/tsconfig.json +6 -1
  240. package/spec/schema-generation-nested-objects.spec.ts +97 -0
  241. package/spec/testHelpers.ts +49 -0
  242. package/spec/utils.caseConversion.spec.ts +78 -0
  243. package/spec/utils.spec.ts +13 -13
  244. package/src/DependencyTracker.ts +166 -0
  245. package/src/FlinkApp.ts +919 -155
  246. package/src/FlinkContext.ts +43 -0
  247. package/src/FlinkErrors.ts +32 -12
  248. package/src/FlinkHttpHandler.ts +246 -28
  249. package/src/FlinkJob.ts +11 -0
  250. package/src/FlinkLog.ts +119 -12
  251. package/src/FlinkLogFactory.ts +699 -0
  252. package/src/FlinkRepo.ts +10 -3
  253. package/src/FlinkRequestContext.ts +95 -0
  254. package/src/FlinkResponse.ts +6 -0
  255. package/src/FlinkService.ts +49 -0
  256. package/src/LeaderElection.ts +203 -0
  257. package/src/SchemaCache.ts +232 -0
  258. package/src/TypeScriptCompiler.ts +1347 -610
  259. package/src/TypeScriptUtils.ts +5 -0
  260. package/src/ai/AgentRunner.ts +646 -0
  261. package/src/ai/ConversationAgent.ts +413 -0
  262. package/src/ai/FlinkAgent.ts +1069 -0
  263. package/src/ai/FlinkTool.ts +165 -0
  264. package/src/ai/InMemoryConversationAgent.ts +149 -0
  265. package/src/ai/LLMAdapter.ts +126 -0
  266. package/src/ai/ToolExecutor.ts +485 -0
  267. package/src/ai/agentInstructions.ts +245 -0
  268. package/src/ai/index.ts +8 -0
  269. package/src/ai/instructionFileLoader.ts +156 -0
  270. package/src/auth/FlinkAuthPlugin.ts +2 -1
  271. package/src/handlers/StreamWriterFactory.ts +84 -0
  272. package/src/index.ts +14 -0
  273. package/src/loadPluginSchemas.ts +141 -0
  274. package/src/schema-extraction/TypeScriptSourceParser.ts +1058 -0
  275. package/src/schema-extraction/TypeScriptTokenizer.ts +205 -0
  276. package/src/schema-extraction/index.ts +2 -0
  277. package/src/schema-extraction/types.ts +34 -0
  278. package/src/utils/loadFlinkConfig.ts +89 -0
  279. package/src/utils.ts +52 -0
  280. package/tsconfig.json +6 -1
@@ -0,0 +1,632 @@
1
+ "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
+ return new (P || (P = Promise))(function (resolve, reject) {
16
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
20
+ });
21
+ };
22
+ var __generator = (this && this.__generator) || function (thisArg, body) {
23
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
24
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
+ function verb(n) { return function (v) { return step([n, v]); }; }
26
+ function step(op) {
27
+ if (f) throw new TypeError("Generator is already executing.");
28
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
29
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
30
+ if (y = 0, t) op = [op[0] & 2, t.value];
31
+ switch (op[0]) {
32
+ case 0: case 1: t = op; break;
33
+ case 4: _.label++; return { value: op[1], done: false };
34
+ case 5: _.label++; y = op[1]; op = [0]; continue;
35
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
36
+ default:
37
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41
+ if (t[2]) _.ops.pop();
42
+ _.trys.pop(); continue;
43
+ }
44
+ op = body.call(thisArg, _);
45
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
+ }
48
+ };
49
+ var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
50
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
51
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
52
+ var m = o[Symbol.asyncIterator], i;
53
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
54
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
55
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
56
+ };
57
+ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
58
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
59
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
60
+ return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
61
+ function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
62
+ function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
63
+ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
64
+ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
65
+ function fulfill(value) { resume("next", value); }
66
+ function reject(value) { resume("throw", value); }
67
+ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
68
+ };
69
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
70
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
71
+ if (ar || !(i in from)) {
72
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
73
+ ar[i] = from[i];
74
+ }
75
+ }
76
+ return to.concat(ar || Array.prototype.slice.call(from));
77
+ };
78
+ Object.defineProperty(exports, "__esModule", { value: true });
79
+ exports.AgentRunner = void 0;
80
+ var FlinkLog_1 = require("../FlinkLog");
81
+ var AgentRunner = /** @class */ (function () {
82
+ function AgentRunner(agentProps, tools, llmAdapters, agentName, // Optional agent name for logging
83
+ ctx // FlinkContext for instruction callbacks (any for flexibility)
84
+ ) {
85
+ var _a, _b, _c, _d, _e;
86
+ this.agentProps = agentProps;
87
+ this.tools = tools;
88
+ this.agentName = agentName;
89
+ this.ctx = ctx;
90
+ // Get appropriate LLM adapter based on adapterId
91
+ var adapterId = ((_a = agentProps.model) === null || _a === void 0 ? void 0 : _a.adapterId) || "default";
92
+ var adapter = llmAdapters.get(adapterId);
93
+ if (!adapter) {
94
+ throw new Error("LLM adapter \"".concat(adapterId, "\" not configured - register it in FlinkOptions.ai.llms"));
95
+ }
96
+ this.llmAdapter = adapter;
97
+ this.maxTokens = ((_b = agentProps.model) === null || _b === void 0 ? void 0 : _b.maxTokens) || 4096;
98
+ this.temperature = ((_c = agentProps.model) === null || _c === void 0 ? void 0 : _c.temperature) || 0.7;
99
+ this.maxSteps = ((_d = agentProps.limits) === null || _d === void 0 ? void 0 : _d.maxSteps) || 10;
100
+ this.timeoutMs = ((_e = agentProps.limits) === null || _e === void 0 ? void 0 : _e.timeoutMs) || 60000;
101
+ }
102
+ AgentRunner.prototype.streamGenerator = function (input) {
103
+ return __asyncGenerator(this, arguments, function streamGenerator_1() {
104
+ var maxSteps, toolCalls, execContext, resolvedInstructions, _a, err_1, messages, step, finalMessage, stoppedEarly, totalInputTokens, totalOutputTokens, totalCachedInputTokens, totalCacheCreationInputTokens, finalProviderMetadata, availableTools, needsCompaction, beforeCount, originalMessages, compactedMessages, error_1, llmStream, textContent, toolCallsFromStream, usage, stopReason, providerMetadata, _b, llmStream_1, llmStream_1_1, chunk, _c, e_1_1, llmResponse, assistantContent, _i, _d, toolCall, stepContext, toolResults, _e, _f, toolCall, toolExecutor, toolOutput, toolError, toolResult, formattedResult, err_2, stepContext, result, finishContext;
105
+ var _g, e_1, _h, _j;
106
+ var _k, _l, _m;
107
+ return __generator(this, function (_o) {
108
+ switch (_o.label) {
109
+ case 0:
110
+ maxSteps = ((_k = input.options) === null || _k === void 0 ? void 0 : _k.maxSteps) || this.maxSteps;
111
+ toolCalls = [];
112
+ execContext = {
113
+ agentId: this.agentName || "unknown",
114
+ conversationId: input.conversationId,
115
+ user: input.user,
116
+ metadata: input.metadata,
117
+ conversationContext: input.conversationContext,
118
+ };
119
+ _o.label = 1;
120
+ case 1:
121
+ _o.trys.push([1, 5, , 6]);
122
+ if (!(typeof this.agentProps.instructions === "function")) return [3 /*break*/, 3];
123
+ return [4 /*yield*/, __await(this.agentProps.instructions(this.ctx, execContext))];
124
+ case 2:
125
+ _a = _o.sent();
126
+ return [3 /*break*/, 4];
127
+ case 3:
128
+ _a = this.agentProps.instructions;
129
+ _o.label = 4;
130
+ case 4:
131
+ resolvedInstructions = _a;
132
+ return [3 /*break*/, 6];
133
+ case 5:
134
+ err_1 = _o.sent();
135
+ throw new Error("Failed to resolve dynamic instructions for agent ".concat(this.agentName, ": ").concat(err_1.message));
136
+ case 6:
137
+ if (input.history && input.history.length > 0) {
138
+ // Start with history
139
+ messages = this.convertMessages(input.history);
140
+ }
141
+ else {
142
+ messages = [];
143
+ }
144
+ // Add new user message
145
+ if (typeof input.message === "string") {
146
+ messages.push({ role: "user", content: input.message });
147
+ }
148
+ else if (Array.isArray(input.message) && input.message.length > 0 && "type" in input.message[0]) {
149
+ // LLMContentBlock[] — multimodal content (e.g. text + images)
150
+ messages.push({ role: "user", content: input.message });
151
+ }
152
+ else {
153
+ messages.push.apply(messages, this.convertMessages(input.message));
154
+ }
155
+ step = 0;
156
+ finalMessage = "";
157
+ stoppedEarly = false;
158
+ totalInputTokens = 0;
159
+ totalOutputTokens = 0;
160
+ totalCachedInputTokens = 0;
161
+ totalCacheCreationInputTokens = 0;
162
+ finalProviderMetadata = {};
163
+ _o.label = 7;
164
+ case 7:
165
+ if (!(step < maxSteps)) return [3 /*break*/, 53];
166
+ step++;
167
+ return [4 /*yield*/, __await(this.filterToolsByPermissions(input.user, input.userPermissions, input.conversationContext))];
168
+ case 8:
169
+ availableTools = _o.sent();
170
+ if (!this.agentProps.shouldCompact) return [3 /*break*/, 16];
171
+ _o.label = 9;
172
+ case 9:
173
+ _o.trys.push([9, 15, , 16]);
174
+ return [4 /*yield*/, __await(this.agentProps.shouldCompact(messages, step))];
175
+ case 10:
176
+ needsCompaction = _o.sent();
177
+ if (!needsCompaction) return [3 /*break*/, 14];
178
+ beforeCount = messages.length;
179
+ originalMessages = messages;
180
+ compactedMessages = void 0;
181
+ if (!this.agentProps.compactHistory) return [3 /*break*/, 12];
182
+ return [4 /*yield*/, __await(this.agentProps.compactHistory(messages, step))];
183
+ case 11:
184
+ compactedMessages = _o.sent();
185
+ return [3 /*break*/, 13];
186
+ case 12:
187
+ // Default strategy: sliding window keeping last 10 messages
188
+ compactedMessages = messages.slice(-10);
189
+ _o.label = 13;
190
+ case 13:
191
+ // Validation: ensure compacted array is not empty
192
+ if (!compactedMessages || compactedMessages.length === 0) {
193
+ throw new Error("compactHistory must return at least one message");
194
+ }
195
+ // Apply compaction
196
+ messages = compactedMessages;
197
+ // Log compaction for debugging
198
+ FlinkLog_1.log.debug("[Agent:".concat(this.agentName, "] Step ").concat(step, ": Compacted ").concat(beforeCount, " messages \u2192 ").concat(messages.length));
199
+ // Debug logging: Show compacted messages if debug enabled
200
+ if (this.agentProps.debug) {
201
+ FlinkLog_1.log.debug("[Agent:".concat(this.agentName, "] Compacted messages:"), {
202
+ messageCount: messages.length,
203
+ messages: messages.map(function (m) { return ({
204
+ role: m.role,
205
+ contentPreview: typeof m.content === "string"
206
+ ? m.content.substring(0, 100) + (m.content.length > 100 ? "..." : "")
207
+ : "".concat(m.content.length, " blocks"),
208
+ }); }),
209
+ });
210
+ }
211
+ _o.label = 14;
212
+ case 14: return [3 /*break*/, 16];
213
+ case 15:
214
+ error_1 = _o.sent();
215
+ // Log error but don't fail execution - compaction is optional optimization
216
+ FlinkLog_1.log.error("[Agent:".concat(this.agentName, "] Context compaction failed:"), error_1.message);
217
+ return [3 /*break*/, 16];
218
+ case 16:
219
+ // Debug logging: Show what we're sending to the LLM
220
+ if (this.agentProps.debug) {
221
+ FlinkLog_1.log.debug("[Agent:".concat(this.agentName, "] Step ").concat(step, "/").concat(maxSteps, " - Calling LLM with:"), {
222
+ instructions: resolvedInstructions,
223
+ instructionsType: typeof this.agentProps.instructions === "function" ? "dynamic-callback" : "static",
224
+ messageCount: messages.length,
225
+ messages: messages.map(function (m) { return ({
226
+ role: m.role,
227
+ contentPreview: typeof m.content === "string"
228
+ ? m.content.substring(0, 100) + (m.content.length > 100 ? "..." : "")
229
+ : "".concat(m.content.length, " blocks"),
230
+ }); }),
231
+ toolCount: availableTools.length,
232
+ tools: availableTools.map(function (t) { return t.name; }),
233
+ maxTokens: this.maxTokens,
234
+ temperature: this.temperature,
235
+ });
236
+ }
237
+ llmStream = this.llmAdapter.stream({
238
+ instructions: resolvedInstructions,
239
+ messages: messages,
240
+ tools: availableTools,
241
+ maxTokens: this.maxTokens,
242
+ temperature: this.temperature,
243
+ providerMetadata: input.providerMetadata,
244
+ });
245
+ textContent = "";
246
+ toolCallsFromStream = [];
247
+ usage = { inputTokens: 0, outputTokens: 0 };
248
+ stopReason = "end_turn";
249
+ providerMetadata = {};
250
+ _o.label = 17;
251
+ case 17:
252
+ _o.trys.push([17, 29, 30, 35]);
253
+ _b = true, llmStream_1 = (e_1 = void 0, __asyncValues(llmStream));
254
+ _o.label = 18;
255
+ case 18: return [4 /*yield*/, __await(llmStream_1.next())];
256
+ case 19:
257
+ if (!(llmStream_1_1 = _o.sent(), _g = llmStream_1_1.done, !_g)) return [3 /*break*/, 28];
258
+ _j = llmStream_1_1.value;
259
+ _b = false;
260
+ chunk = _j;
261
+ _c = chunk.type;
262
+ switch (_c) {
263
+ case "text": return [3 /*break*/, 20];
264
+ case "tool_call": return [3 /*break*/, 23];
265
+ case "usage": return [3 /*break*/, 24];
266
+ case "metadata": return [3 /*break*/, 25];
267
+ case "done": return [3 /*break*/, 26];
268
+ }
269
+ return [3 /*break*/, 27];
270
+ case 20:
271
+ textContent += chunk.delta;
272
+ return [4 /*yield*/, __await({ type: "text_delta", delta: chunk.delta })];
273
+ case 21:
274
+ // Yield text_delta event in real-time
275
+ return [4 /*yield*/, _o.sent()];
276
+ case 22:
277
+ // Yield text_delta event in real-time
278
+ _o.sent();
279
+ return [3 /*break*/, 27];
280
+ case 23:
281
+ toolCallsFromStream.push(chunk.toolCall);
282
+ return [3 /*break*/, 27];
283
+ case 24:
284
+ usage = chunk.usage;
285
+ totalInputTokens += chunk.usage.inputTokens;
286
+ totalOutputTokens += chunk.usage.outputTokens;
287
+ totalCachedInputTokens += chunk.usage.cachedInputTokens || 0;
288
+ totalCacheCreationInputTokens += chunk.usage.cacheCreationInputTokens || 0;
289
+ return [3 /*break*/, 27];
290
+ case 25:
291
+ // Merge provider metadata (e.g., responseId for continuation)
292
+ providerMetadata = __assign(__assign({}, providerMetadata), chunk.metadata);
293
+ finalProviderMetadata = __assign(__assign({}, finalProviderMetadata), chunk.metadata);
294
+ return [3 /*break*/, 27];
295
+ case 26:
296
+ stopReason = chunk.stopReason;
297
+ return [3 /*break*/, 27];
298
+ case 27:
299
+ _b = true;
300
+ return [3 /*break*/, 18];
301
+ case 28: return [3 /*break*/, 35];
302
+ case 29:
303
+ e_1_1 = _o.sent();
304
+ e_1 = { error: e_1_1 };
305
+ return [3 /*break*/, 35];
306
+ case 30:
307
+ _o.trys.push([30, , 33, 34]);
308
+ if (!(!_b && !_g && (_h = llmStream_1.return))) return [3 /*break*/, 32];
309
+ return [4 /*yield*/, __await(_h.call(llmStream_1))];
310
+ case 31:
311
+ _o.sent();
312
+ _o.label = 32;
313
+ case 32: return [3 /*break*/, 34];
314
+ case 33:
315
+ if (e_1) throw e_1.error;
316
+ return [7 /*endfinally*/];
317
+ case 34: return [7 /*endfinally*/];
318
+ case 35:
319
+ llmResponse = {
320
+ textContent: textContent || undefined,
321
+ toolCalls: toolCallsFromStream,
322
+ usage: usage,
323
+ stopReason: stopReason,
324
+ };
325
+ // Debug logging: Show what the LLM responded with
326
+ if (this.agentProps.debug) {
327
+ FlinkLog_1.log.debug("[Agent:".concat(this.agentName, "] Step ").concat(step, " - LLM Response:"), {
328
+ textLength: ((_l = llmResponse.textContent) === null || _l === void 0 ? void 0 : _l.length) || 0,
329
+ textPreview: ((_m = llmResponse.textContent) === null || _m === void 0 ? void 0 : _m.substring(0, 200)) + (llmResponse.textContent && llmResponse.textContent.length > 200 ? "..." : ""),
330
+ toolCallsCount: llmResponse.toolCalls.length,
331
+ toolCalls: llmResponse.toolCalls.map(function (tc) { return ({
332
+ name: tc.name,
333
+ inputKeys: Object.keys(tc.input),
334
+ input: tc.input,
335
+ }); }),
336
+ stopReason: llmResponse.stopReason,
337
+ usage: llmResponse.usage,
338
+ });
339
+ }
340
+ // Extract text response
341
+ if (llmResponse.textContent) {
342
+ finalMessage = llmResponse.textContent;
343
+ }
344
+ assistantContent = [];
345
+ if (llmResponse.textContent) {
346
+ assistantContent.push({
347
+ type: "text",
348
+ text: llmResponse.textContent,
349
+ });
350
+ }
351
+ for (_i = 0, _d = llmResponse.toolCalls; _i < _d.length; _i++) {
352
+ toolCall = _d[_i];
353
+ assistantContent.push({
354
+ type: "tool_use",
355
+ id: toolCall.id,
356
+ name: toolCall.name,
357
+ input: toolCall.input,
358
+ });
359
+ }
360
+ messages.push({
361
+ role: "assistant",
362
+ content: assistantContent,
363
+ });
364
+ if (!(llmResponse.toolCalls.length === 0)) return [3 /*break*/, 38];
365
+ if (!this.agentProps.onStep) return [3 /*break*/, 37];
366
+ stepContext = __assign(__assign({}, execContext), { step: step, maxSteps: maxSteps, messages: __spreadArray([], messages, true) });
367
+ return [4 /*yield*/, __await(this.agentProps.onStep(stepContext))];
368
+ case 36:
369
+ _o.sent();
370
+ _o.label = 37;
371
+ case 37: return [3 /*break*/, 53]; // No more tool calls - done
372
+ case 38:
373
+ toolResults = [];
374
+ _e = 0, _f = llmResponse.toolCalls;
375
+ _o.label = 39;
376
+ case 39:
377
+ if (!(_e < _f.length)) return [3 /*break*/, 50];
378
+ toolCall = _f[_e];
379
+ toolExecutor = this.tools.get(toolCall.name);
380
+ toolOutput = void 0;
381
+ toolError = void 0;
382
+ // Debug logging: Tool execution start
383
+ if (this.agentProps.debug) {
384
+ FlinkLog_1.log.debug("[Agent:".concat(this.agentName, "] Executing tool '").concat(toolCall.name, "':"), {
385
+ input: toolCall.input,
386
+ inputSize: JSON.stringify(toolCall.input).length,
387
+ });
388
+ }
389
+ _o.label = 40;
390
+ case 40:
391
+ _o.trys.push([40, 46, , 49]);
392
+ if (!toolExecutor) {
393
+ throw new Error("Tool ".concat(toolCall.name, " not found"));
394
+ }
395
+ return [4 /*yield*/, __await({
396
+ type: "tool_call_start",
397
+ toolCall: {
398
+ id: toolCall.id,
399
+ name: toolCall.name,
400
+ input: toolCall.input,
401
+ },
402
+ })];
403
+ case 41:
404
+ // Yield tool_call_start event
405
+ return [4 /*yield*/, _o.sent()];
406
+ case 42:
407
+ // Yield tool_call_start event
408
+ _o.sent();
409
+ return [4 /*yield*/, __await(toolExecutor.execute(toolCall.input, {
410
+ user: input.user,
411
+ permissions: input.userPermissions,
412
+ conversationContext: input.conversationContext,
413
+ }))];
414
+ case 43:
415
+ toolResult = _o.sent();
416
+ formattedResult = toolExecutor.formatResultForAI(toolResult);
417
+ toolResults.push({
418
+ type: "tool_result",
419
+ tool_use_id: toolCall.id,
420
+ content: formattedResult,
421
+ is_error: !toolResult.success,
422
+ });
423
+ return [4 /*yield*/, __await({
424
+ type: "tool_call_result",
425
+ toolCall: {
426
+ id: toolCall.id,
427
+ name: toolCall.name,
428
+ input: toolCall.input,
429
+ },
430
+ output: toolResult.success ? toolResult.data : null,
431
+ error: toolResult.success ? undefined : toolResult.error,
432
+ })];
433
+ case 44:
434
+ // Yield tool_call_result event
435
+ return [4 /*yield*/, _o.sent()];
436
+ case 45:
437
+ // Yield tool_call_result event
438
+ _o.sent();
439
+ toolCalls.push({
440
+ name: toolCall.name,
441
+ input: toolCall.input,
442
+ output: toolResult.success ? toolResult.data : null,
443
+ error: toolResult.success ? undefined : toolResult.error,
444
+ });
445
+ // Debug logging: Tool execution result
446
+ if (this.agentProps.debug) {
447
+ FlinkLog_1.log.debug("[Agent:".concat(this.agentName, "] Tool '").concat(toolCall.name, "' ").concat(toolResult.success ? "succeeded" : "failed", ":"), {
448
+ success: toolResult.success,
449
+ outputSize: toolResult.success ? JSON.stringify(toolResult.data).length : 0,
450
+ outputPreview: toolResult.success
451
+ ? JSON.stringify(toolResult.data).substring(0, 200) + (JSON.stringify(toolResult.data).length > 200 ? "..." : "")
452
+ : toolResult.error,
453
+ code: toolResult.code,
454
+ });
455
+ }
456
+ if (!toolResult.success) {
457
+ FlinkLog_1.log.warn("Tool ".concat(toolCall.name, " returned error:"), toolResult.error);
458
+ }
459
+ return [3 /*break*/, 49];
460
+ case 46:
461
+ err_2 = _o.sent();
462
+ // Unexpected errors (not from tool itself)
463
+ toolError = err_2.message;
464
+ return [4 /*yield*/, __await({
465
+ type: "tool_call_result",
466
+ toolCall: {
467
+ id: toolCall.id,
468
+ name: toolCall.name,
469
+ input: toolCall.input,
470
+ },
471
+ output: null,
472
+ error: toolError,
473
+ })];
474
+ case 47:
475
+ // Yield tool_call_result with error
476
+ return [4 /*yield*/, _o.sent()];
477
+ case 48:
478
+ // Yield tool_call_result with error
479
+ _o.sent();
480
+ toolResults.push({
481
+ type: "tool_result",
482
+ tool_use_id: toolCall.id,
483
+ content: "Error: ".concat(err_2.message),
484
+ is_error: true,
485
+ });
486
+ toolCalls.push({
487
+ name: toolCall.name,
488
+ input: toolCall.input,
489
+ output: null,
490
+ error: toolError,
491
+ });
492
+ FlinkLog_1.log.error("Tool ".concat(toolCall.name, " execution failed:"), err_2.message);
493
+ return [3 /*break*/, 49];
494
+ case 49:
495
+ _e++;
496
+ return [3 /*break*/, 39];
497
+ case 50:
498
+ // Add tool results to conversation
499
+ messages.push({
500
+ role: "user",
501
+ content: toolResults,
502
+ });
503
+ if (!this.agentProps.onStep) return [3 /*break*/, 52];
504
+ stepContext = __assign(__assign({}, execContext), { step: step, maxSteps: maxSteps, messages: __spreadArray([], messages, true) });
505
+ return [4 /*yield*/, __await(this.agentProps.onStep(stepContext))];
506
+ case 51:
507
+ _o.sent();
508
+ _o.label = 52;
509
+ case 52: return [3 /*break*/, 7];
510
+ case 53:
511
+ if (step >= maxSteps && toolCalls.length > 0) {
512
+ stoppedEarly = true;
513
+ FlinkLog_1.log.warn("Agent ".concat(this.agentName || "unknown", " stopped early after ").concat(maxSteps, " steps"));
514
+ }
515
+ result = {
516
+ message: finalMessage,
517
+ toolCalls: toolCalls,
518
+ stepsUsed: step,
519
+ stoppedEarly: stoppedEarly,
520
+ usage: __assign(__assign({ inputTokens: totalInputTokens, outputTokens: totalOutputTokens }, (totalCachedInputTokens > 0 && { cachedInputTokens: totalCachedInputTokens })), (totalCacheCreationInputTokens > 0 && { cacheCreationInputTokens: totalCacheCreationInputTokens })),
521
+ providerMetadata: Object.keys(finalProviderMetadata).length > 0 ? finalProviderMetadata : undefined,
522
+ };
523
+ if (!this.agentProps.afterRun) return [3 /*break*/, 55];
524
+ finishContext = __assign(__assign({}, execContext), { messages: __spreadArray([], messages, true), result: result });
525
+ return [4 /*yield*/, __await(this.agentProps.afterRun(result, finishContext))];
526
+ case 54:
527
+ _o.sent();
528
+ _o.label = 55;
529
+ case 55: return [4 /*yield*/, __await({ type: "complete", result: result })];
530
+ case 56:
531
+ // Phase 1: Yield only complete event
532
+ // Phase 2: Will yield text_delta and tool events during loop
533
+ return [4 /*yield*/, _o.sent()];
534
+ case 57:
535
+ // Phase 1: Yield only complete event
536
+ // Phase 2: Will yield text_delta and tool events during loop
537
+ _o.sent();
538
+ return [4 /*yield*/, __await(result)];
539
+ case 58: return [2 /*return*/, _o.sent()];
540
+ }
541
+ });
542
+ });
543
+ };
544
+ /**
545
+ * Convert Message[] to LLM message format
546
+ * Supports multi-turn conversations with history
547
+ */
548
+ AgentRunner.prototype.convertMessages = function (messages) {
549
+ return messages.map(function (m) {
550
+ if (m.role === "user") {
551
+ return { role: "user", content: m.content };
552
+ }
553
+ else if (m.role === "assistant") {
554
+ // If assistant message has tool calls, convert to content blocks
555
+ if (m.toolCalls && m.toolCalls.length > 0) {
556
+ var contentBlocks = [];
557
+ // Add text content if present
558
+ if (m.content) {
559
+ contentBlocks.push({ type: "text", text: m.content });
560
+ }
561
+ // Add tool use blocks
562
+ for (var _i = 0, _a = m.toolCalls; _i < _a.length; _i++) {
563
+ var toolCall = _a[_i];
564
+ contentBlocks.push({
565
+ type: "tool_use",
566
+ id: toolCall.id,
567
+ name: toolCall.name,
568
+ input: toolCall.input,
569
+ });
570
+ }
571
+ return { role: "assistant", content: contentBlocks };
572
+ }
573
+ // Text-only assistant message
574
+ return { role: "assistant", content: m.content };
575
+ }
576
+ else {
577
+ // For tool messages, convert to user message with tool_result content block
578
+ return {
579
+ role: "user",
580
+ content: [
581
+ {
582
+ type: "tool_result",
583
+ tool_use_id: m.toolCallId,
584
+ content: m.result,
585
+ },
586
+ ],
587
+ };
588
+ }
589
+ });
590
+ };
591
+ AgentRunner.prototype.getToolSchemas = function () {
592
+ return Array.from(this.tools.values()).map(function (t) { return t.getToolSchema(); });
593
+ };
594
+ /**
595
+ * Filter tools based on user permissions
596
+ * Only returns schemas for tools the user has permission to use
597
+ *
598
+ * @param user - User object
599
+ * @param userPermissions - Optional resolved permissions from auth plugin (preferred)
600
+ * @param conversationContext - Optional conversation context
601
+ */
602
+ AgentRunner.prototype.filterToolsByPermissions = function (user, userPermissions, conversationContext) {
603
+ return __awaiter(this, void 0, void 0, function () {
604
+ var allowedTools, toolExecutors, _i, toolExecutors_1, tool, hasPermission;
605
+ return __generator(this, function (_a) {
606
+ switch (_a.label) {
607
+ case 0:
608
+ allowedTools = [];
609
+ toolExecutors = Array.from(this.tools.values());
610
+ _i = 0, toolExecutors_1 = toolExecutors;
611
+ _a.label = 1;
612
+ case 1:
613
+ if (!(_i < toolExecutors_1.length)) return [3 /*break*/, 4];
614
+ tool = toolExecutors_1[_i];
615
+ return [4 /*yield*/, tool.checkPermissions(user, undefined, userPermissions, conversationContext)];
616
+ case 2:
617
+ hasPermission = _a.sent();
618
+ if (hasPermission) {
619
+ allowedTools.push(tool.getToolSchema());
620
+ }
621
+ _a.label = 3;
622
+ case 3:
623
+ _i++;
624
+ return [3 /*break*/, 1];
625
+ case 4: return [2 /*return*/, allowedTools];
626
+ }
627
+ });
628
+ });
629
+ };
630
+ return AgentRunner;
631
+ }());
632
+ exports.AgentRunner = AgentRunner;