@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,760 @@
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 uuid_1 = require("uuid");
81
+ var FlinkLogFactory_1 = require("../FlinkLogFactory");
82
+ var FlinkLog_1 = require("../FlinkLog");
83
+ var observerLog = FlinkLogFactory_1.FlinkLogFactory.createLogger("flink.ai.observer");
84
+ var AgentRunner = /** @class */ (function () {
85
+ function AgentRunner(agentProps, tools, llmAdapters, agentName, // Optional agent name for logging
86
+ ctx, // FlinkContext for instruction callbacks (any for flexibility)
87
+ observer) {
88
+ var _a, _b, _c, _d, _e;
89
+ this.agentProps = agentProps;
90
+ this.tools = tools;
91
+ this.agentName = agentName;
92
+ this.ctx = ctx;
93
+ this.observer = observer;
94
+ // Get appropriate LLM adapter based on adapterId
95
+ var adapterId = ((_a = agentProps.model) === null || _a === void 0 ? void 0 : _a.adapterId) || "default";
96
+ var adapter = llmAdapters.get(adapterId);
97
+ if (!adapter) {
98
+ throw new Error("LLM adapter \"".concat(adapterId, "\" not configured - register it in FlinkOptions.ai.llms"));
99
+ }
100
+ this.llmAdapter = adapter;
101
+ this.maxTokens = ((_b = agentProps.model) === null || _b === void 0 ? void 0 : _b.maxTokens) || 4096;
102
+ this.temperature = ((_c = agentProps.model) === null || _c === void 0 ? void 0 : _c.temperature) || 0.7;
103
+ this.maxSteps = ((_d = agentProps.limits) === null || _d === void 0 ? void 0 : _d.maxSteps) || 10;
104
+ this.timeoutMs = ((_e = agentProps.limits) === null || _e === void 0 ? void 0 : _e.timeoutMs) || 60000;
105
+ }
106
+ AgentRunner.prototype.streamGenerator = function (input) {
107
+ return __asyncGenerator(this, arguments, function streamGenerator_1() {
108
+ var maxSteps, toolCalls, runId, runStartedAt, agentId, modelInfo, declaredToolNames, execContext, resolvedInstructions, _a, err_1, messages, step, finalMessage, stoppedEarly, totalInputTokens, totalOutputTokens, totalCachedInputTokens, totalCacheCreationInputTokens, finalProviderMetadata, buildResult, _loop_1, this_1, state_1, result_1, finishContext, err_2;
109
+ var _this = this;
110
+ var _b, e_1, _c, _d;
111
+ var _e, _f, _g, _h;
112
+ return __generator(this, function (_j) {
113
+ switch (_j.label) {
114
+ case 0:
115
+ maxSteps = ((_e = input.options) === null || _e === void 0 ? void 0 : _e.maxSteps) || this.maxSteps;
116
+ toolCalls = [];
117
+ runId = (0, uuid_1.v4)();
118
+ runStartedAt = Date.now();
119
+ agentId = this.agentName || "unknown";
120
+ modelInfo = {
121
+ adapterId: (_f = this.agentProps.model) === null || _f === void 0 ? void 0 : _f.adapterId,
122
+ maxTokens: this.maxTokens,
123
+ temperature: this.temperature,
124
+ };
125
+ declaredToolNames = Array.from(this.tools.keys());
126
+ execContext = {
127
+ agentId: agentId,
128
+ conversationId: input.conversationId,
129
+ user: input.user,
130
+ metadata: input.metadata,
131
+ conversationContext: input.conversationContext,
132
+ };
133
+ _j.label = 1;
134
+ case 1:
135
+ _j.trys.push([1, 5, , 6]);
136
+ if (!(typeof this.agentProps.instructions === "function")) return [3 /*break*/, 3];
137
+ return [4 /*yield*/, __await(this.agentProps.instructions(this.ctx, execContext))];
138
+ case 2:
139
+ _a = _j.sent();
140
+ return [3 /*break*/, 4];
141
+ case 3:
142
+ _a = this.agentProps.instructions;
143
+ _j.label = 4;
144
+ case 4:
145
+ resolvedInstructions = _a;
146
+ return [3 /*break*/, 6];
147
+ case 5:
148
+ err_1 = _j.sent();
149
+ throw new Error("Failed to resolve instructions for agent ".concat(this.agentName, ": ").concat(err_1.message));
150
+ case 6:
151
+ if (input.history && input.history.length > 0) {
152
+ // Start with history
153
+ messages = this.convertMessages(input.history);
154
+ }
155
+ else {
156
+ messages = [];
157
+ }
158
+ // Add new user message
159
+ if (typeof input.message === "string") {
160
+ messages.push({ role: "user", content: input.message });
161
+ }
162
+ else if (Array.isArray(input.message) && input.message.length > 0 && "type" in input.message[0]) {
163
+ // LLMContentBlock[] — multimodal content (e.g. text + images)
164
+ messages.push({ role: "user", content: input.message });
165
+ }
166
+ else {
167
+ messages.push.apply(messages, this.convertMessages(input.message));
168
+ }
169
+ // Dispatch observer onRun (pre-loop, before compaction / tool filtering)
170
+ this.safeDispatch("onRun", function () {
171
+ var _a, _b;
172
+ return (_b = (_a = _this.observer) === null || _a === void 0 ? void 0 : _a.onRun) === null || _b === void 0 ? void 0 : _b.call(_a, {
173
+ runId: runId,
174
+ agentId: agentId,
175
+ instructions: resolvedInstructions,
176
+ input: input,
177
+ messages: __spreadArray([], messages, true),
178
+ tools: declaredToolNames,
179
+ model: modelInfo,
180
+ context: execContext,
181
+ });
182
+ });
183
+ step = 0;
184
+ finalMessage = "";
185
+ stoppedEarly = false;
186
+ totalInputTokens = 0;
187
+ totalOutputTokens = 0;
188
+ totalCachedInputTokens = 0;
189
+ totalCacheCreationInputTokens = 0;
190
+ finalProviderMetadata = {};
191
+ buildResult = function () { return ({
192
+ runId: runId,
193
+ message: finalMessage,
194
+ toolCalls: toolCalls,
195
+ stepsUsed: step,
196
+ stoppedEarly: stoppedEarly,
197
+ usage: __assign(__assign({ inputTokens: totalInputTokens, outputTokens: totalOutputTokens }, (totalCachedInputTokens > 0 && { cachedInputTokens: totalCachedInputTokens })), (totalCacheCreationInputTokens > 0 && { cacheCreationInputTokens: totalCacheCreationInputTokens })),
198
+ providerMetadata: Object.keys(finalProviderMetadata).length > 0 ? finalProviderMetadata : undefined,
199
+ }); };
200
+ _j.label = 7;
201
+ case 7:
202
+ _j.trys.push([7, 16, , 17]);
203
+ _loop_1 = function () {
204
+ var availableTools, needsCompaction, beforeCount, originalMessages, compactedMessages, error_1, toolCallsBeforeStep, llmStream, textContent, toolCallsFromStream, usage, stopReason, providerMetadata, _k, llmStream_1, llmStream_1_1, chunk, _l, e_1_1, llmResponse, assistantContent, _i, _m, toolCall, stepContext, toolResults, _o, _p, toolCall, toolExecutor, toolOutput, toolError, toolResult, formattedResult, err_3, stepContext;
205
+ return __generator(this, function (_q) {
206
+ switch (_q.label) {
207
+ case 0:
208
+ step++;
209
+ return [4 /*yield*/, __await(this_1.filterToolsByPermissions(input.user, input.userPermissions, input.conversationContext))];
210
+ case 1:
211
+ availableTools = _q.sent();
212
+ if (!this_1.agentProps.shouldCompact) return [3 /*break*/, 9];
213
+ _q.label = 2;
214
+ case 2:
215
+ _q.trys.push([2, 8, , 9]);
216
+ return [4 /*yield*/, __await(this_1.agentProps.shouldCompact(messages, step))];
217
+ case 3:
218
+ needsCompaction = _q.sent();
219
+ if (!needsCompaction) return [3 /*break*/, 7];
220
+ beforeCount = messages.length;
221
+ originalMessages = messages;
222
+ compactedMessages = void 0;
223
+ if (!this_1.agentProps.compactHistory) return [3 /*break*/, 5];
224
+ return [4 /*yield*/, __await(this_1.agentProps.compactHistory(messages, step))];
225
+ case 4:
226
+ compactedMessages = _q.sent();
227
+ return [3 /*break*/, 6];
228
+ case 5:
229
+ // Default strategy: sliding window keeping last 10 messages
230
+ compactedMessages = messages.slice(-10);
231
+ _q.label = 6;
232
+ case 6:
233
+ // Validation: ensure compacted array is not empty
234
+ if (!compactedMessages || compactedMessages.length === 0) {
235
+ throw new Error("compactHistory must return at least one message");
236
+ }
237
+ // Apply compaction
238
+ messages = compactedMessages;
239
+ // Log compaction for debugging
240
+ FlinkLog_1.log.debug("[Agent:".concat(this_1.agentName, "] Step ").concat(step, ": Compacted ").concat(beforeCount, " messages \u2192 ").concat(messages.length));
241
+ FlinkLog_1.log.debug("[Agent:".concat(this_1.agentName, "] Compacted messages:"), {
242
+ messageCount: messages.length,
243
+ messages: messages.map(function (m) { return ({
244
+ role: m.role,
245
+ contentPreview: typeof m.content === "string"
246
+ ? m.content.substring(0, 100) + (m.content.length > 100 ? "..." : "")
247
+ : "".concat(m.content.length, " blocks"),
248
+ }); }),
249
+ });
250
+ _q.label = 7;
251
+ case 7: return [3 /*break*/, 9];
252
+ case 8:
253
+ error_1 = _q.sent();
254
+ // Log error but don't fail execution - compaction is optional optimization
255
+ FlinkLog_1.log.error("[Agent:".concat(this_1.agentName, "] Context compaction failed:"), error_1.message);
256
+ return [3 /*break*/, 9];
257
+ case 9:
258
+ FlinkLog_1.log.debug("[Agent:".concat(this_1.agentName, "] Step ").concat(step, "/").concat(maxSteps, " - Calling LLM with:"), {
259
+ instructionsType: typeof this_1.agentProps.instructions === "function" ? "dynamic-callback" : "static",
260
+ messageCount: messages.length,
261
+ messages: messages.map(function (m) { return ({
262
+ role: m.role,
263
+ contentPreview: typeof m.content === "string"
264
+ ? m.content.substring(0, 100) + (m.content.length > 100 ? "..." : "")
265
+ : "".concat(m.content.length, " blocks"),
266
+ }); }),
267
+ toolCount: availableTools.length,
268
+ tools: availableTools.map(function (t) { return t.name; }),
269
+ maxTokens: this_1.maxTokens,
270
+ temperature: this_1.temperature,
271
+ });
272
+ // Dispatch observer onLlmCall — messages reflect post-compaction state;
273
+ // tools reflect per-step permission filtering
274
+ this_1.safeDispatch("onLlmCall", function () {
275
+ var _a, _b;
276
+ return (_b = (_a = _this.observer) === null || _a === void 0 ? void 0 : _a.onLlmCall) === null || _b === void 0 ? void 0 : _b.call(_a, {
277
+ runId: runId,
278
+ agentId: agentId,
279
+ step: step,
280
+ maxSteps: maxSteps,
281
+ instructions: resolvedInstructions,
282
+ messages: __spreadArray([], messages, true),
283
+ tools: availableTools.map(function (t) { return t.name; }),
284
+ model: modelInfo,
285
+ context: execContext,
286
+ });
287
+ });
288
+ toolCallsBeforeStep = toolCalls.length;
289
+ llmStream = this_1.llmAdapter.stream({
290
+ instructions: resolvedInstructions,
291
+ messages: messages,
292
+ tools: availableTools,
293
+ maxTokens: this_1.maxTokens,
294
+ temperature: this_1.temperature,
295
+ providerMetadata: input.providerMetadata,
296
+ });
297
+ textContent = "";
298
+ toolCallsFromStream = [];
299
+ usage = { inputTokens: 0, outputTokens: 0 };
300
+ stopReason = "end_turn";
301
+ providerMetadata = {};
302
+ _q.label = 10;
303
+ case 10:
304
+ _q.trys.push([10, 22, 23, 28]);
305
+ _k = true, llmStream_1 = (e_1 = void 0, __asyncValues(llmStream));
306
+ _q.label = 11;
307
+ case 11: return [4 /*yield*/, __await(llmStream_1.next())];
308
+ case 12:
309
+ if (!(llmStream_1_1 = _q.sent(), _b = llmStream_1_1.done, !_b)) return [3 /*break*/, 21];
310
+ _d = llmStream_1_1.value;
311
+ _k = false;
312
+ chunk = _d;
313
+ _l = chunk.type;
314
+ switch (_l) {
315
+ case "text": return [3 /*break*/, 13];
316
+ case "tool_call": return [3 /*break*/, 16];
317
+ case "usage": return [3 /*break*/, 17];
318
+ case "metadata": return [3 /*break*/, 18];
319
+ case "done": return [3 /*break*/, 19];
320
+ }
321
+ return [3 /*break*/, 20];
322
+ case 13:
323
+ textContent += chunk.delta;
324
+ return [4 /*yield*/, __await({ type: "text_delta", delta: chunk.delta })];
325
+ case 14:
326
+ // Yield text_delta event in real-time
327
+ return [4 /*yield*/, _q.sent()];
328
+ case 15:
329
+ // Yield text_delta event in real-time
330
+ _q.sent();
331
+ return [3 /*break*/, 20];
332
+ case 16:
333
+ toolCallsFromStream.push(chunk.toolCall);
334
+ return [3 /*break*/, 20];
335
+ case 17:
336
+ usage = chunk.usage;
337
+ totalInputTokens += chunk.usage.inputTokens;
338
+ totalOutputTokens += chunk.usage.outputTokens;
339
+ totalCachedInputTokens += chunk.usage.cachedInputTokens || 0;
340
+ totalCacheCreationInputTokens += chunk.usage.cacheCreationInputTokens || 0;
341
+ return [3 /*break*/, 20];
342
+ case 18:
343
+ // Merge provider metadata (e.g., responseId for continuation)
344
+ providerMetadata = __assign(__assign({}, providerMetadata), chunk.metadata);
345
+ finalProviderMetadata = __assign(__assign({}, finalProviderMetadata), chunk.metadata);
346
+ return [3 /*break*/, 20];
347
+ case 19:
348
+ stopReason = chunk.stopReason;
349
+ return [3 /*break*/, 20];
350
+ case 20:
351
+ _k = true;
352
+ return [3 /*break*/, 11];
353
+ case 21: return [3 /*break*/, 28];
354
+ case 22:
355
+ e_1_1 = _q.sent();
356
+ e_1 = { error: e_1_1 };
357
+ return [3 /*break*/, 28];
358
+ case 23:
359
+ _q.trys.push([23, , 26, 27]);
360
+ if (!(!_k && !_b && (_c = llmStream_1.return))) return [3 /*break*/, 25];
361
+ return [4 /*yield*/, __await(_c.call(llmStream_1))];
362
+ case 24:
363
+ _q.sent();
364
+ _q.label = 25;
365
+ case 25: return [3 /*break*/, 27];
366
+ case 26:
367
+ if (e_1) throw e_1.error;
368
+ return [7 /*endfinally*/];
369
+ case 27: return [7 /*endfinally*/];
370
+ case 28:
371
+ llmResponse = {
372
+ textContent: textContent || undefined,
373
+ toolCalls: toolCallsFromStream,
374
+ usage: usage,
375
+ stopReason: stopReason,
376
+ };
377
+ FlinkLog_1.log.debug("[Agent:".concat(this_1.agentName, "] Step ").concat(step, " - LLM Response:"), {
378
+ textLength: ((_g = llmResponse.textContent) === null || _g === void 0 ? void 0 : _g.length) || 0,
379
+ textPreview: ((_h = llmResponse.textContent) === null || _h === void 0 ? void 0 : _h.substring(0, 200)) + (llmResponse.textContent && llmResponse.textContent.length > 200 ? "..." : ""),
380
+ toolCallsCount: llmResponse.toolCalls.length,
381
+ toolCalls: llmResponse.toolCalls.map(function (tc) { return ({
382
+ name: tc.name,
383
+ inputKeys: Object.keys(tc.input),
384
+ input: tc.input,
385
+ }); }),
386
+ stopReason: llmResponse.stopReason,
387
+ usage: llmResponse.usage,
388
+ });
389
+ // Extract text response
390
+ if (llmResponse.textContent) {
391
+ finalMessage = llmResponse.textContent;
392
+ }
393
+ assistantContent = [];
394
+ if (llmResponse.textContent) {
395
+ assistantContent.push({
396
+ type: "text",
397
+ text: llmResponse.textContent,
398
+ });
399
+ }
400
+ for (_i = 0, _m = llmResponse.toolCalls; _i < _m.length; _i++) {
401
+ toolCall = _m[_i];
402
+ assistantContent.push({
403
+ type: "tool_use",
404
+ id: toolCall.id,
405
+ name: toolCall.name,
406
+ input: toolCall.input,
407
+ });
408
+ }
409
+ messages.push({
410
+ role: "assistant",
411
+ content: assistantContent,
412
+ });
413
+ if (!(llmResponse.toolCalls.length === 0)) return [3 /*break*/, 31];
414
+ if (!this_1.agentProps.onStep) return [3 /*break*/, 30];
415
+ stepContext = __assign(__assign({}, execContext), { step: step, maxSteps: maxSteps, messages: __spreadArray([], messages, true) });
416
+ return [4 /*yield*/, __await(this_1.agentProps.onStep(stepContext))];
417
+ case 29:
418
+ _q.sent();
419
+ _q.label = 30;
420
+ case 30:
421
+ // Dispatch observer onStep (no tool calls executed this step)
422
+ this_1.safeDispatch("onStep", function () {
423
+ var _a, _b;
424
+ return (_b = (_a = _this.observer) === null || _a === void 0 ? void 0 : _a.onStep) === null || _b === void 0 ? void 0 : _b.call(_a, {
425
+ runId: runId,
426
+ agentId: agentId,
427
+ step: step,
428
+ maxSteps: maxSteps,
429
+ messages: __spreadArray([], messages, true),
430
+ assistantText: llmResponse.textContent,
431
+ toolCalls: toolCalls.slice(toolCallsBeforeStep),
432
+ usage: usage,
433
+ context: execContext,
434
+ });
435
+ });
436
+ return [2 /*return*/, "break"];
437
+ case 31:
438
+ toolResults = [];
439
+ _o = 0, _p = llmResponse.toolCalls;
440
+ _q.label = 32;
441
+ case 32:
442
+ if (!(_o < _p.length)) return [3 /*break*/, 43];
443
+ toolCall = _p[_o];
444
+ toolExecutor = this_1.tools.get(toolCall.name);
445
+ toolOutput = void 0;
446
+ toolError = void 0;
447
+ FlinkLog_1.log.debug("[Agent:".concat(this_1.agentName, "] Executing tool '").concat(toolCall.name, "':"), {
448
+ input: toolCall.input,
449
+ inputSize: JSON.stringify(toolCall.input).length,
450
+ });
451
+ _q.label = 33;
452
+ case 33:
453
+ _q.trys.push([33, 39, , 42]);
454
+ if (!toolExecutor) {
455
+ throw new Error("Tool ".concat(toolCall.name, " not found"));
456
+ }
457
+ return [4 /*yield*/, __await({
458
+ type: "tool_call_start",
459
+ toolCall: {
460
+ id: toolCall.id,
461
+ name: toolCall.name,
462
+ input: toolCall.input,
463
+ },
464
+ })];
465
+ case 34:
466
+ // Yield tool_call_start event
467
+ return [4 /*yield*/, _q.sent()];
468
+ case 35:
469
+ // Yield tool_call_start event
470
+ _q.sent();
471
+ return [4 /*yield*/, __await(toolExecutor.execute(toolCall.input, {
472
+ user: input.user,
473
+ permissions: input.userPermissions,
474
+ conversationContext: input.conversationContext,
475
+ }))];
476
+ case 36:
477
+ toolResult = _q.sent();
478
+ formattedResult = toolExecutor.formatResultForAI(toolResult);
479
+ toolResults.push({
480
+ type: "tool_result",
481
+ tool_use_id: toolCall.id,
482
+ content: formattedResult,
483
+ is_error: !toolResult.success,
484
+ });
485
+ return [4 /*yield*/, __await({
486
+ type: "tool_call_result",
487
+ toolCall: {
488
+ id: toolCall.id,
489
+ name: toolCall.name,
490
+ input: toolCall.input,
491
+ },
492
+ output: toolResult.success ? toolResult.data : null,
493
+ error: toolResult.success ? undefined : toolResult.error,
494
+ })];
495
+ case 37:
496
+ // Yield tool_call_result event
497
+ return [4 /*yield*/, _q.sent()];
498
+ case 38:
499
+ // Yield tool_call_result event
500
+ _q.sent();
501
+ toolCalls.push({
502
+ name: toolCall.name,
503
+ input: toolCall.input,
504
+ output: toolResult.success ? toolResult.data : null,
505
+ error: toolResult.success ? undefined : toolResult.error,
506
+ });
507
+ FlinkLog_1.log.debug("[Agent:".concat(this_1.agentName, "] Tool '").concat(toolCall.name, "' ").concat(toolResult.success ? "succeeded" : "failed", ":"), {
508
+ success: toolResult.success,
509
+ outputSize: toolResult.success ? JSON.stringify(toolResult.data).length : 0,
510
+ outputPreview: toolResult.success
511
+ ? JSON.stringify(toolResult.data).substring(0, 200) + (JSON.stringify(toolResult.data).length > 200 ? "..." : "")
512
+ : toolResult.error,
513
+ code: toolResult.code,
514
+ });
515
+ if (!toolResult.success) {
516
+ FlinkLog_1.log.warn("Tool ".concat(toolCall.name, " returned error:"), toolResult.error);
517
+ }
518
+ return [3 /*break*/, 42];
519
+ case 39:
520
+ err_3 = _q.sent();
521
+ // Unexpected errors (not from tool itself)
522
+ toolError = err_3.message;
523
+ return [4 /*yield*/, __await({
524
+ type: "tool_call_result",
525
+ toolCall: {
526
+ id: toolCall.id,
527
+ name: toolCall.name,
528
+ input: toolCall.input,
529
+ },
530
+ output: null,
531
+ error: toolError,
532
+ })];
533
+ case 40:
534
+ // Yield tool_call_result with error
535
+ return [4 /*yield*/, _q.sent()];
536
+ case 41:
537
+ // Yield tool_call_result with error
538
+ _q.sent();
539
+ toolResults.push({
540
+ type: "tool_result",
541
+ tool_use_id: toolCall.id,
542
+ content: "Error: ".concat(err_3.message),
543
+ is_error: true,
544
+ });
545
+ toolCalls.push({
546
+ name: toolCall.name,
547
+ input: toolCall.input,
548
+ output: null,
549
+ error: toolError,
550
+ });
551
+ FlinkLog_1.log.error("Tool ".concat(toolCall.name, " execution failed:"), err_3.message);
552
+ return [3 /*break*/, 42];
553
+ case 42:
554
+ _o++;
555
+ return [3 /*break*/, 32];
556
+ case 43:
557
+ // Add tool results to conversation
558
+ messages.push({
559
+ role: "user",
560
+ content: toolResults,
561
+ });
562
+ if (!this_1.agentProps.onStep) return [3 /*break*/, 45];
563
+ stepContext = __assign(__assign({}, execContext), { step: step, maxSteps: maxSteps, messages: __spreadArray([], messages, true) });
564
+ return [4 /*yield*/, __await(this_1.agentProps.onStep(stepContext))];
565
+ case 44:
566
+ _q.sent();
567
+ _q.label = 45;
568
+ case 45:
569
+ // Dispatch observer onStep with per-step tool calls slice
570
+ this_1.safeDispatch("onStep", function () {
571
+ var _a, _b;
572
+ return (_b = (_a = _this.observer) === null || _a === void 0 ? void 0 : _a.onStep) === null || _b === void 0 ? void 0 : _b.call(_a, {
573
+ runId: runId,
574
+ agentId: agentId,
575
+ step: step,
576
+ maxSteps: maxSteps,
577
+ messages: __spreadArray([], messages, true),
578
+ assistantText: llmResponse.textContent,
579
+ toolCalls: toolCalls.slice(toolCallsBeforeStep),
580
+ usage: usage,
581
+ context: execContext,
582
+ });
583
+ });
584
+ return [2 /*return*/];
585
+ }
586
+ });
587
+ };
588
+ this_1 = this;
589
+ _j.label = 8;
590
+ case 8:
591
+ if (!(step < maxSteps)) return [3 /*break*/, 10];
592
+ return [5 /*yield**/, _loop_1()];
593
+ case 9:
594
+ state_1 = _j.sent();
595
+ if (state_1 === "break")
596
+ return [3 /*break*/, 10];
597
+ return [3 /*break*/, 8];
598
+ case 10:
599
+ if (step >= maxSteps && toolCalls.length > 0) {
600
+ stoppedEarly = true;
601
+ FlinkLog_1.log.warn("Agent ".concat(this.agentName || "unknown", " stopped early after ").concat(maxSteps, " steps"));
602
+ }
603
+ result_1 = buildResult();
604
+ if (!this.agentProps.afterRun) return [3 /*break*/, 12];
605
+ finishContext = __assign(__assign({}, execContext), { messages: __spreadArray([], messages, true), result: result_1 });
606
+ return [4 /*yield*/, __await(this.agentProps.afterRun(result_1, finishContext))];
607
+ case 11:
608
+ _j.sent();
609
+ _j.label = 12;
610
+ case 12:
611
+ // Dispatch observer onFinish (success path)
612
+ this.safeDispatch("onFinish", function () {
613
+ var _a, _b;
614
+ return (_b = (_a = _this.observer) === null || _a === void 0 ? void 0 : _a.onFinish) === null || _b === void 0 ? void 0 : _b.call(_a, {
615
+ runId: runId,
616
+ agentId: agentId,
617
+ result: result_1,
618
+ messages: __spreadArray([], messages, true),
619
+ durationMs: Date.now() - runStartedAt,
620
+ context: execContext,
621
+ });
622
+ });
623
+ return [4 /*yield*/, __await({ type: "complete", result: result_1 })];
624
+ case 13:
625
+ // Phase 1: Yield only complete event
626
+ // Phase 2: Will yield text_delta and tool events during loop
627
+ return [4 /*yield*/, _j.sent()];
628
+ case 14:
629
+ // Phase 1: Yield only complete event
630
+ // Phase 2: Will yield text_delta and tool events during loop
631
+ _j.sent();
632
+ return [4 /*yield*/, __await(result_1)];
633
+ case 15: return [2 /*return*/, _j.sent()];
634
+ case 16:
635
+ err_2 = _j.sent();
636
+ // Dispatch observer onFinish with error before rethrowing
637
+ this.safeDispatch("onFinish", function () {
638
+ var _a, _b;
639
+ return (_b = (_a = _this.observer) === null || _a === void 0 ? void 0 : _a.onFinish) === null || _b === void 0 ? void 0 : _b.call(_a, {
640
+ runId: runId,
641
+ agentId: agentId,
642
+ result: buildResult(),
643
+ messages: __spreadArray([], messages, true),
644
+ durationMs: Date.now() - runStartedAt,
645
+ error: (err_2 === null || err_2 === void 0 ? void 0 : err_2.message) || String(err_2),
646
+ context: execContext,
647
+ });
648
+ });
649
+ throw err_2;
650
+ case 17: return [2 /*return*/];
651
+ }
652
+ });
653
+ });
654
+ };
655
+ /**
656
+ * Fire-and-forget observer dispatch: catches synchronous throws and
657
+ * rejected promises so observer failures never break agent execution.
658
+ */
659
+ AgentRunner.prototype.safeDispatch = function (eventName, invoke) {
660
+ try {
661
+ var maybePromise = invoke();
662
+ if (maybePromise && typeof maybePromise.then === "function") {
663
+ maybePromise.catch(function (err) {
664
+ observerLog.warn("AgentObserver.".concat(eventName, " threw (async):"), (err === null || err === void 0 ? void 0 : err.message) || err);
665
+ });
666
+ }
667
+ }
668
+ catch (err) {
669
+ observerLog.warn("AgentObserver.".concat(eventName, " threw (sync):"), (err === null || err === void 0 ? void 0 : err.message) || err);
670
+ }
671
+ };
672
+ /**
673
+ * Convert Message[] to LLM message format
674
+ * Supports multi-turn conversations with history
675
+ */
676
+ AgentRunner.prototype.convertMessages = function (messages) {
677
+ return messages.map(function (m) {
678
+ if (m.role === "user") {
679
+ return { role: "user", content: m.content };
680
+ }
681
+ else if (m.role === "assistant") {
682
+ // If assistant message has tool calls, convert to content blocks
683
+ if (m.toolCalls && m.toolCalls.length > 0) {
684
+ var contentBlocks = [];
685
+ // Add text content if present
686
+ if (m.content) {
687
+ contentBlocks.push({ type: "text", text: m.content });
688
+ }
689
+ // Add tool use blocks
690
+ for (var _i = 0, _a = m.toolCalls; _i < _a.length; _i++) {
691
+ var toolCall = _a[_i];
692
+ contentBlocks.push({
693
+ type: "tool_use",
694
+ id: toolCall.id,
695
+ name: toolCall.name,
696
+ input: toolCall.input,
697
+ });
698
+ }
699
+ return { role: "assistant", content: contentBlocks };
700
+ }
701
+ // Text-only assistant message
702
+ return { role: "assistant", content: m.content };
703
+ }
704
+ else {
705
+ // For tool messages, convert to user message with tool_result content block
706
+ return {
707
+ role: "user",
708
+ content: [
709
+ {
710
+ type: "tool_result",
711
+ tool_use_id: m.toolCallId,
712
+ content: m.result,
713
+ },
714
+ ],
715
+ };
716
+ }
717
+ });
718
+ };
719
+ AgentRunner.prototype.getToolSchemas = function () {
720
+ return Array.from(this.tools.values()).map(function (t) { return t.getToolSchema(); });
721
+ };
722
+ /**
723
+ * Filter tools based on user permissions
724
+ * Only returns schemas for tools the user has permission to use
725
+ *
726
+ * @param user - User object
727
+ * @param userPermissions - Optional resolved permissions from auth plugin (preferred)
728
+ * @param conversationContext - Optional conversation context
729
+ */
730
+ AgentRunner.prototype.filterToolsByPermissions = function (user, userPermissions, conversationContext) {
731
+ return __awaiter(this, void 0, void 0, function () {
732
+ var allowedTools, toolExecutors, _i, toolExecutors_1, tool, hasPermission;
733
+ return __generator(this, function (_a) {
734
+ switch (_a.label) {
735
+ case 0:
736
+ allowedTools = [];
737
+ toolExecutors = Array.from(this.tools.values());
738
+ _i = 0, toolExecutors_1 = toolExecutors;
739
+ _a.label = 1;
740
+ case 1:
741
+ if (!(_i < toolExecutors_1.length)) return [3 /*break*/, 4];
742
+ tool = toolExecutors_1[_i];
743
+ return [4 /*yield*/, tool.checkPermissions(user, undefined, userPermissions, conversationContext)];
744
+ case 2:
745
+ hasPermission = _a.sent();
746
+ if (hasPermission) {
747
+ allowedTools.push(tool.getToolSchema());
748
+ }
749
+ _a.label = 3;
750
+ case 3:
751
+ _i++;
752
+ return [3 /*break*/, 1];
753
+ case 4: return [2 /*return*/, allowedTools];
754
+ }
755
+ });
756
+ });
757
+ };
758
+ return AgentRunner;
759
+ }());
760
+ exports.AgentRunner = AgentRunner;