@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,699 @@
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 __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
51
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
52
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
53
+ return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
54
+ function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
55
+ 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]); } }
56
+ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
57
+ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
58
+ function fulfill(value) { resume("next", value); }
59
+ function reject(value) { resume("throw", value); }
60
+ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
61
+ };
62
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
63
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
64
+ var m = o[Symbol.asyncIterator], i;
65
+ 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);
66
+ 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); }); }; }
67
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
68
+ };
69
+ Object.defineProperty(exports, "__esModule", { value: true });
70
+ exports.FlinkAgent = void 0;
71
+ var FlinkErrors_1 = require("../FlinkErrors");
72
+ var FlinkLogFactory_1 = require("../FlinkLogFactory");
73
+ var AgentRunner_1 = require("./AgentRunner");
74
+ var logger = FlinkLogFactory_1.FlinkLogFactory.createLogger("flink.ai.flink-agent");
75
+ /**
76
+ * Base class for Flink agents (similar to FlinkRepo pattern)
77
+ *
78
+ * Agents extend this class and define their configuration as properties.
79
+ * Auto-registered by scanning src/agents/ directory.
80
+ *
81
+ * Tool references are validated at startup to ensure all referenced tools exist.
82
+ *
83
+ * Agents define their own domain-specific entry points that call `this.execute()`.
84
+ * This provides better type safety and developer experience than a generic `run()` method.
85
+ *
86
+ * ## Lifecycle Hooks
87
+ *
88
+ * Agents support lifecycle hooks for advanced orchestration:
89
+ * - `beforeRun`: Load conversation history, prepare context
90
+ * - `onStep`: Save state after each LLM turn
91
+ * - `afterRun`: Persist final conversation state
92
+ *
93
+ * ## Context Compaction
94
+ *
95
+ * Long-running agents can accumulate large message histories. Use context compaction
96
+ * to automatically manage history size during execution:
97
+ *
98
+ * ```typescript
99
+ * export default class MyAgent extends FlinkAgent<AppCtx> {
100
+ * id = "my-agent";
101
+ * description = "Agent with automatic context management";
102
+ * instructions = "You are a helpful assistant...";
103
+ *
104
+ * // Compact when history exceeds 20 messages
105
+ * shouldCompact = (messages) => messages.length > 20;
106
+ *
107
+ * // Keep only last 10 messages
108
+ * compactHistory = (messages) => messages.slice(-10);
109
+ * }
110
+ * ```
111
+ *
112
+ * Compaction happens before each LLM call in the agentic loop, ensuring consistent
113
+ * token usage and preventing context window overflow.
114
+ *
115
+ * Example:
116
+ * ```typescript
117
+ * import { Tool as GetCarsTool } from "./tools/GetCarsTool";
118
+ * import * as UpdateCarTool from "./tools/UpdateCarTool";
119
+ *
120
+ * export default class CarAgent extends FlinkAgent<AppCtx> {
121
+ * id = "car-agent"; // Optional: defaults to kebab-case class name "car-agent"
122
+ * description = "Expert in car models";
123
+ * instructions = "You are a car expert...";
124
+ * tools = [
125
+ * "get-cars-tool", // String ID reference
126
+ * GetCarsTool, // Direct FlinkToolProps import
127
+ * UpdateCarTool, // Tool file reference
128
+ * ];
129
+ *
130
+ * // Domain-specific entry points with proper types
131
+ * async searchByBrand(brand: string) {
132
+ * const response = this.run({
133
+ * message: `Find all ${brand} cars`
134
+ * });
135
+ * return await response.result;
136
+ * }
137
+ *
138
+ * async compareModels(model1: string, model2: string) {
139
+ * const response = this.run({
140
+ * message: `Compare ${model1} and ${model2}`
141
+ * });
142
+ * return await response.result;
143
+ * }
144
+ *
145
+ * // Lifecycle hook: Load conversation history
146
+ * protected async beforeRun(input, context) {
147
+ * if (context.conversationId) {
148
+ * const conv = await this.ctx.repos.conversationRepo.getById(context.conversationId);
149
+ * input.history = conv.messages;
150
+ * }
151
+ * }
152
+ * }
153
+ * ```
154
+ */
155
+ var FlinkAgent = /** @class */ (function () {
156
+ function FlinkAgent() {
157
+ }
158
+ /**
159
+ * Internal initialization called by FlinkApp
160
+ * @internal
161
+ */
162
+ FlinkAgent.prototype.__init = function (llmAdapters, tools) {
163
+ this._llmAdapters = llmAdapters;
164
+ this._tools = tools;
165
+ };
166
+ /**
167
+ * Bind a user to this agent for permission checks
168
+ *
169
+ * This creates a new agent instance with the user bound, allowing clean API:
170
+ * ```typescript
171
+ * const result = await ctx.agents.carAgent
172
+ * .withUser(req.user)
173
+ * .searchByBrand("Volvo");
174
+ * ```
175
+ *
176
+ * The bound user is used for:
177
+ * - Agent-level permission checks
178
+ * - Tool filtering (only allowed tools shown to LLM)
179
+ * - Tool-level permission checks
180
+ */
181
+ FlinkAgent.prototype.withUser = function (user) {
182
+ var bound = Object.create(Object.getPrototypeOf(this));
183
+ Object.assign(bound, this);
184
+ bound._boundUser = user;
185
+ bound.runner = undefined; // Clear runner cache to use new user
186
+ // Explicitly ensure ctx and internal properties are copied (in case they're not enumerable)
187
+ if (this.ctx) {
188
+ bound.ctx = this.ctx;
189
+ }
190
+ if (this._llmAdapters) {
191
+ bound._llmAdapters = this._llmAdapters;
192
+ }
193
+ if (this._tools) {
194
+ bound._tools = this._tools;
195
+ }
196
+ if (this._boundUserPermissions !== undefined) {
197
+ bound._boundUserPermissions = this._boundUserPermissions;
198
+ }
199
+ return bound;
200
+ };
201
+ /**
202
+ * Bind resolved permissions to this agent for permission checks
203
+ *
204
+ * This creates a new agent instance with permissions bound, allowing clean API:
205
+ * ```typescript
206
+ * const result = await ctx.agents.carAgent
207
+ * .withUser(req.user)
208
+ * .withPermissions(req.userPermissions) // Resolved permissions from auth plugin
209
+ * .searchByBrand("Volvo");
210
+ * ```
211
+ *
212
+ * The bound permissions are used for:
213
+ * - Tool filtering (only allowed tools shown to LLM)
214
+ * - Tool-level permission checks
215
+ *
216
+ * Permissions are typically populated by auth plugins during authentication
217
+ * based on roles, dynamic roles, or custom permission resolution.
218
+ */
219
+ FlinkAgent.prototype.withPermissions = function (userPermissions) {
220
+ var bound = Object.create(Object.getPrototypeOf(this));
221
+ Object.assign(bound, this);
222
+ bound._boundUserPermissions = userPermissions;
223
+ bound.runner = undefined; // Clear runner cache to use new permissions
224
+ // Explicitly ensure ctx and internal properties are copied (in case they're not enumerable)
225
+ if (this.ctx) {
226
+ bound.ctx = this.ctx;
227
+ }
228
+ if (this._llmAdapters) {
229
+ bound._llmAdapters = this._llmAdapters;
230
+ }
231
+ if (this._tools) {
232
+ bound._tools = this._tools;
233
+ }
234
+ if (this._boundUser !== undefined) {
235
+ bound._boundUser = this._boundUser;
236
+ }
237
+ return bound;
238
+ };
239
+ /**
240
+ * Override the LLM adapter for this agent
241
+ *
242
+ * This creates a new agent instance with a different LLM adapter, allowing runtime selection:
243
+ * ```typescript
244
+ * const result = await ctx.agents.carAgent
245
+ * .withUser(req.user)
246
+ * .withLlm("fast") // Use fast LLM instead of default
247
+ * .searchByBrand("Volvo");
248
+ * ```
249
+ *
250
+ * The LLM adapter ID must be registered in FlinkApp's ai.llms configuration.
251
+ *
252
+ * @param adapterId - The ID of the LLM adapter to use (e.g., "default", "fake", "fast", "anthropic")
253
+ * @returns A new agent instance with the specified LLM adapter
254
+ */
255
+ FlinkAgent.prototype.withLlm = function (adapterId) {
256
+ var bound = Object.create(Object.getPrototypeOf(this));
257
+ Object.assign(bound, this);
258
+ // Override the model configuration with the new adapter ID
259
+ bound.model = __assign(__assign({}, (this.model || {})), { adapterId: adapterId });
260
+ bound.runner = undefined; // Clear runner cache to use new adapter
261
+ // Explicitly ensure ctx and internal properties are copied (in case they're not enumerable)
262
+ if (this.ctx) {
263
+ bound.ctx = this.ctx;
264
+ }
265
+ if (this._llmAdapters) {
266
+ bound._llmAdapters = this._llmAdapters;
267
+ }
268
+ if (this._tools) {
269
+ bound._tools = this._tools;
270
+ }
271
+ if (this._boundUser !== undefined) {
272
+ bound._boundUser = this._boundUser;
273
+ }
274
+ if (this._boundUserPermissions !== undefined) {
275
+ bound._boundUserPermissions = this._boundUserPermissions;
276
+ }
277
+ return bound;
278
+ };
279
+ /**
280
+ * Bind conversation context to this agent for passing to tools
281
+ *
282
+ * This creates a new agent instance with the conversation context bound, allowing clean API:
283
+ * ```typescript
284
+ * const result = await ctx.agents.carAgent
285
+ * .withUser(req.user)
286
+ * .withConversationContext({ sessionId: req.session.id, featureFlags: req.flags })
287
+ * .searchByBrand("Volvo");
288
+ * ```
289
+ *
290
+ * The bound conversation context is used for:
291
+ * - Passing request-scoped data to tools
292
+ * - Sharing state between agent and tools without polluting global context
293
+ * - Propagating to sub-agents automatically
294
+ */
295
+ FlinkAgent.prototype.withConversationContext = function (conversationContext) {
296
+ var bound = Object.create(Object.getPrototypeOf(this));
297
+ Object.assign(bound, this);
298
+ bound._boundConversationContext = conversationContext;
299
+ bound.runner = undefined; // Clear runner cache
300
+ // Copy non-enumerable properties
301
+ if (this.ctx) {
302
+ bound.ctx = this.ctx;
303
+ }
304
+ if (this._llmAdapters) {
305
+ bound._llmAdapters = this._llmAdapters;
306
+ }
307
+ if (this._tools) {
308
+ bound._tools = this._tools;
309
+ }
310
+ if (this._boundUser !== undefined) {
311
+ bound._boundUser = this._boundUser;
312
+ }
313
+ if (this._boundUserPermissions !== undefined) {
314
+ bound._boundUserPermissions = this._boundUserPermissions;
315
+ }
316
+ return bound;
317
+ };
318
+ /**
319
+ * Public execution method for external callers (handlers, sub-agents, etc.)
320
+ *
321
+ * Use this when calling an agent from outside the agent class.
322
+ * For internal use within agent subclasses, use `execute()` instead.
323
+ */
324
+ FlinkAgent.prototype.run = function (input) {
325
+ return this.execute(input);
326
+ };
327
+ /**
328
+ * Internal execution method - supports both awaiting and streaming
329
+ *
330
+ * Uses lazy generator pattern (similar to Vercel AI SDK) to allow
331
+ * multiple consumption without re-execution.
332
+ *
333
+ * Agents call this method from their run() implementation to execute the AI logic.
334
+ *
335
+ * Examples:
336
+ * const response = this.execute({ message: "Hello" });
337
+ * const result = await response.result; // Await final result
338
+ * for await (const text of response.textStream) { ... } // Stream text
339
+ * for await (const chunk of response.fullStream) { ... } // Stream all events
340
+ */
341
+ FlinkAgent.prototype.execute = function (input) {
342
+ var _this = this;
343
+ var _a, _b, _c;
344
+ // Use bound user if not explicitly provided in input
345
+ var user = (_a = input.user) !== null && _a !== void 0 ? _a : this._boundUser;
346
+ var userPermissions = (_b = input.userPermissions) !== null && _b !== void 0 ? _b : this._boundUserPermissions;
347
+ var conversationContext = (_c = input.conversationContext) !== null && _c !== void 0 ? _c : this._boundConversationContext;
348
+ var executeInput = __assign(__assign({}, input), { user: user, userPermissions: userPermissions, conversationContext: conversationContext });
349
+ // Permission check
350
+ if (this.permissions) {
351
+ this.checkPermissionsSync(user, userPermissions);
352
+ }
353
+ // Build execution context
354
+ var execContext = {
355
+ agentId: this.getAgentId(),
356
+ conversationId: executeInput.conversationId,
357
+ user: user,
358
+ metadata: executeInput.metadata,
359
+ conversationContext: executeInput.conversationContext,
360
+ };
361
+ var runner = this.getRunner();
362
+ logger.debug("Running agent ".concat(this.constructor.name));
363
+ // Lazy evaluation - generator only starts when first consumed
364
+ var baseGenerator = null;
365
+ var buffer = [];
366
+ var done = false;
367
+ var fetchPromise = null; // Prevent concurrent fetches
368
+ var beforeRunCalled = false;
369
+ var getBaseGenerator = function () { return __awaiter(_this, void 0, void 0, function () {
370
+ return __generator(this, function (_a) {
371
+ switch (_a.label) {
372
+ case 0:
373
+ if (!!baseGenerator) return [3 /*break*/, 3];
374
+ if (!(!beforeRunCalled && this.beforeRun)) return [3 /*break*/, 2];
375
+ beforeRunCalled = true;
376
+ return [4 /*yield*/, this.beforeRun(executeInput, execContext)];
377
+ case 1:
378
+ _a.sent();
379
+ _a.label = 2;
380
+ case 2:
381
+ baseGenerator = runner.streamGenerator(executeInput);
382
+ _a.label = 3;
383
+ case 3: return [2 /*return*/, baseGenerator];
384
+ }
385
+ });
386
+ }); };
387
+ // Fetch next chunk from base generator (only one consumer at a time)
388
+ var fetchNext = function () { return __awaiter(_this, void 0, void 0, function () {
389
+ var _this = this;
390
+ return __generator(this, function (_a) {
391
+ switch (_a.label) {
392
+ case 0:
393
+ if (!fetchPromise) return [3 /*break*/, 2];
394
+ // Another iterator is already fetching, wait for it
395
+ return [4 /*yield*/, fetchPromise];
396
+ case 1:
397
+ // Another iterator is already fetching, wait for it
398
+ _a.sent();
399
+ return [2 /*return*/];
400
+ case 2:
401
+ if (done) {
402
+ return [2 /*return*/];
403
+ }
404
+ fetchPromise = (function () { return __awaiter(_this, void 0, void 0, function () {
405
+ var gen, _a, value, isDone;
406
+ return __generator(this, function (_b) {
407
+ switch (_b.label) {
408
+ case 0: return [4 /*yield*/, getBaseGenerator()];
409
+ case 1:
410
+ gen = _b.sent();
411
+ return [4 /*yield*/, gen.next()];
412
+ case 2:
413
+ _a = _b.sent(), value = _a.value, isDone = _a.done;
414
+ if (isDone) {
415
+ done = true;
416
+ }
417
+ else {
418
+ buffer.push(value);
419
+ }
420
+ return [2 /*return*/];
421
+ }
422
+ });
423
+ }); })();
424
+ return [4 /*yield*/, fetchPromise];
425
+ case 3:
426
+ _a.sent();
427
+ fetchPromise = null;
428
+ return [2 /*return*/];
429
+ }
430
+ });
431
+ }); };
432
+ // Create independent iterators that share buffered chunks
433
+ var createIterator = function () {
434
+ var index = 0;
435
+ return (function () {
436
+ return __asyncGenerator(this, arguments, function () {
437
+ return __generator(this, function (_a) {
438
+ switch (_a.label) {
439
+ case 0:
440
+ if (!true) return [3 /*break*/, 9];
441
+ if (!(index < buffer.length)) return [3 /*break*/, 3];
442
+ return [4 /*yield*/, __await(buffer[index++])];
443
+ case 1: return [4 /*yield*/, _a.sent()];
444
+ case 2:
445
+ _a.sent();
446
+ return [3 /*break*/, 0];
447
+ case 3:
448
+ // If already done, exit
449
+ if (done) {
450
+ return [3 /*break*/, 9];
451
+ }
452
+ // Fetch next chunk (synchronized)
453
+ return [4 /*yield*/, __await(fetchNext())];
454
+ case 4:
455
+ // Fetch next chunk (synchronized)
456
+ _a.sent();
457
+ if (!(index < buffer.length)) return [3 /*break*/, 7];
458
+ return [4 /*yield*/, __await(buffer[index++])];
459
+ case 5: return [4 /*yield*/, _a.sent()];
460
+ case 6:
461
+ _a.sent();
462
+ return [3 /*break*/, 8];
463
+ case 7:
464
+ if (done) {
465
+ return [3 /*break*/, 9];
466
+ }
467
+ _a.label = 8;
468
+ case 8: return [3 /*break*/, 0];
469
+ case 9: return [2 /*return*/];
470
+ }
471
+ });
472
+ });
473
+ })();
474
+ };
475
+ return {
476
+ result: this.consumeAsResult(createIterator()),
477
+ textStream: this.consumeAsTextStream(createIterator()),
478
+ fullStream: createIterator(),
479
+ };
480
+ };
481
+ /**
482
+ * Consume stream as final result (for await pattern)
483
+ */
484
+ FlinkAgent.prototype.consumeAsResult = function (stream) {
485
+ return __awaiter(this, void 0, void 0, function () {
486
+ var result, chunk, e_1_1, err_1;
487
+ var _a, stream_1, stream_1_1;
488
+ var _b, e_1, _c, _d;
489
+ return __generator(this, function (_e) {
490
+ switch (_e.label) {
491
+ case 0:
492
+ _e.trys.push([0, 13, , 14]);
493
+ _e.label = 1;
494
+ case 1:
495
+ _e.trys.push([1, 6, 7, 12]);
496
+ _a = true, stream_1 = __asyncValues(stream);
497
+ _e.label = 2;
498
+ case 2: return [4 /*yield*/, stream_1.next()];
499
+ case 3:
500
+ if (!(stream_1_1 = _e.sent(), _b = stream_1_1.done, !_b)) return [3 /*break*/, 5];
501
+ _d = stream_1_1.value;
502
+ _a = false;
503
+ chunk = _d;
504
+ if (chunk.type === "complete") {
505
+ result = chunk.result;
506
+ return [3 /*break*/, 5]; // Exit early once we have the result
507
+ }
508
+ _e.label = 4;
509
+ case 4:
510
+ _a = true;
511
+ return [3 /*break*/, 2];
512
+ case 5: return [3 /*break*/, 12];
513
+ case 6:
514
+ e_1_1 = _e.sent();
515
+ e_1 = { error: e_1_1 };
516
+ return [3 /*break*/, 12];
517
+ case 7:
518
+ _e.trys.push([7, , 10, 11]);
519
+ if (!(!_a && !_b && (_c = stream_1.return))) return [3 /*break*/, 9];
520
+ return [4 /*yield*/, _c.call(stream_1)];
521
+ case 8:
522
+ _e.sent();
523
+ _e.label = 9;
524
+ case 9: return [3 /*break*/, 11];
525
+ case 10:
526
+ if (e_1) throw e_1.error;
527
+ return [7 /*endfinally*/];
528
+ case 11: return [7 /*endfinally*/];
529
+ case 12: return [3 /*break*/, 14];
530
+ case 13:
531
+ err_1 = _e.sent();
532
+ // If stream was already consumed or interrupted, that's okay
533
+ // as long as we got the result
534
+ if (!result) {
535
+ throw err_1;
536
+ }
537
+ return [3 /*break*/, 14];
538
+ case 14:
539
+ if (!result) {
540
+ throw new Error("Agent execution did not complete");
541
+ }
542
+ // Note: afterRun hook is called by AgentRunner now with full context
543
+ return [2 /*return*/, result];
544
+ }
545
+ });
546
+ });
547
+ };
548
+ /**
549
+ * Consume stream as text-only stream (for simple streaming UX)
550
+ */
551
+ FlinkAgent.prototype.consumeAsTextStream = function (stream) {
552
+ return __asyncGenerator(this, arguments, function consumeAsTextStream_1() {
553
+ var _a, stream_2, stream_2_1, chunk, e_2_1;
554
+ var _b, e_2, _c, _d;
555
+ return __generator(this, function (_e) {
556
+ switch (_e.label) {
557
+ case 0:
558
+ _e.trys.push([0, 7, 8, 13]);
559
+ _a = true, stream_2 = __asyncValues(stream);
560
+ _e.label = 1;
561
+ case 1: return [4 /*yield*/, __await(stream_2.next())];
562
+ case 2:
563
+ if (!(stream_2_1 = _e.sent(), _b = stream_2_1.done, !_b)) return [3 /*break*/, 6];
564
+ _d = stream_2_1.value;
565
+ _a = false;
566
+ chunk = _d;
567
+ if (!(chunk.type === "text_delta")) return [3 /*break*/, 5];
568
+ return [4 /*yield*/, __await(chunk.delta)];
569
+ case 3: return [4 /*yield*/, _e.sent()];
570
+ case 4:
571
+ _e.sent();
572
+ _e.label = 5;
573
+ case 5:
574
+ _a = true;
575
+ return [3 /*break*/, 1];
576
+ case 6: return [3 /*break*/, 13];
577
+ case 7:
578
+ e_2_1 = _e.sent();
579
+ e_2 = { error: e_2_1 };
580
+ return [3 /*break*/, 13];
581
+ case 8:
582
+ _e.trys.push([8, , 11, 12]);
583
+ if (!(!_a && !_b && (_c = stream_2.return))) return [3 /*break*/, 10];
584
+ return [4 /*yield*/, __await(_c.call(stream_2))];
585
+ case 9:
586
+ _e.sent();
587
+ _e.label = 10;
588
+ case 10: return [3 /*break*/, 12];
589
+ case 11:
590
+ if (e_2) throw e_2.error;
591
+ return [7 /*endfinally*/];
592
+ case 12: return [7 /*endfinally*/];
593
+ case 13: return [2 /*return*/];
594
+ }
595
+ });
596
+ });
597
+ };
598
+ FlinkAgent.prototype.getRunner = function () {
599
+ if (!this.runner) {
600
+ if (!this._llmAdapters) {
601
+ throw new Error("Agent not initialized - __init() must be called by FlinkApp");
602
+ }
603
+ // Get tools map and LLM adapters from internal properties
604
+ var toolsMap = this.resolveTools();
605
+ var llmAdapters = this._llmAdapters;
606
+ this.runner = new AgentRunner_1.AgentRunner(this.toAgentProps(), toolsMap, llmAdapters, this.getAgentId(), this.ctx // Pass ctx to runner so callbacks can access it
607
+ );
608
+ }
609
+ return this.runner;
610
+ };
611
+ /**
612
+ * Get agent id - uses explicit id property or falls back to kebab-case class name
613
+ *
614
+ * Examples:
615
+ * - CarAgent → car-agent
616
+ * - APIAgent → api-agent
617
+ * - HTMLParserAgent → html-parser-agent
618
+ */
619
+ FlinkAgent.prototype.getAgentId = function () {
620
+ return this.id;
621
+ };
622
+ FlinkAgent.prototype.toAgentProps = function () {
623
+ var _a, _b, _c, _d, _e;
624
+ return {
625
+ id: this.getAgentId(),
626
+ description: this.description,
627
+ instructions: this.instructions,
628
+ tools: this.tools,
629
+ model: this.model,
630
+ limits: this.limits,
631
+ permissions: this.permissions,
632
+ debug: this.debug,
633
+ // Pass context compaction callbacks
634
+ shouldCompact: (_a = this.shouldCompact) === null || _a === void 0 ? void 0 : _a.bind(this),
635
+ compactHistory: (_b = this.compactHistory) === null || _b === void 0 ? void 0 : _b.bind(this),
636
+ // Pass lifecycle hooks
637
+ beforeRun: (_c = this.beforeRun) === null || _c === void 0 ? void 0 : _c.bind(this),
638
+ onStep: (_d = this.onStep) === null || _d === void 0 ? void 0 : _d.bind(this),
639
+ afterRun: (_e = this.afterRun) === null || _e === void 0 ? void 0 : _e.bind(this),
640
+ };
641
+ };
642
+ FlinkAgent.prototype.resolveTools = function () {
643
+ var _this = this;
644
+ var toolsMap = new Map();
645
+ if (!this._tools) {
646
+ throw new Error("Agent not initialized - __init() must be called by FlinkApp");
647
+ }
648
+ var getTool = function (name) { return _this._tools[name]; };
649
+ // Resolve tool names/references to tool executors
650
+ if (this.tools) {
651
+ for (var _i = 0, _a = this.tools; _i < _a.length; _i++) {
652
+ var toolRef = _a[_i];
653
+ // Handle string IDs, tool file references, and tool props
654
+ var toolId = void 0;
655
+ if (typeof toolRef === "string") {
656
+ toolId = toolRef;
657
+ }
658
+ else if ("Tool" in toolRef) {
659
+ // FlinkToolFile - extract ID from Tool property
660
+ toolId = toolRef.Tool.id;
661
+ }
662
+ else {
663
+ // FlinkToolProps - extract ID directly
664
+ toolId = toolRef.id;
665
+ }
666
+ var tool = getTool(toolId);
667
+ if (!tool) {
668
+ throw new Error("Tool ".concat(toolId, " not found in context"));
669
+ }
670
+ toolsMap.set(toolId, tool);
671
+ }
672
+ }
673
+ return toolsMap;
674
+ };
675
+ FlinkAgent.prototype.checkPermissionsSync = function (user, userPermissions) {
676
+ var perms = this.permissions;
677
+ if (!perms)
678
+ return;
679
+ if (typeof perms === "function") {
680
+ var hasPermission = perms(user);
681
+ if (!hasPermission) {
682
+ throw (0, FlinkErrors_1.forbidden)("Permission denied for agent ".concat(this.getAgentId()));
683
+ }
684
+ return;
685
+ }
686
+ // Get effective permissions (prefer explicit userPermissions)
687
+ var effectivePerms = userPermissions || (user === null || user === void 0 ? void 0 : user.permissions) || [];
688
+ // If no user and no explicit permissions, deny access
689
+ if (!user && !userPermissions) {
690
+ throw (0, FlinkErrors_1.forbidden)("Permission denied for agent ".concat(this.getAgentId()));
691
+ }
692
+ var requiredPerms = Array.isArray(perms) ? perms : [perms];
693
+ if (!requiredPerms.every(function (p) { return effectivePerms.includes(p); })) {
694
+ throw (0, FlinkErrors_1.forbidden)("Permission denied for agent ".concat(this.getAgentId()));
695
+ }
696
+ };
697
+ return FlinkAgent;
698
+ }());
699
+ exports.FlinkAgent = FlinkAgent;