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