freelang-editor 11.7.4

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 (1473) hide show
  1. package/.config/jest.config.js +47 -0
  2. package/.config/jest.fast.config.js +9 -0
  3. package/.config/openapi.yaml +457 -0
  4. package/.config/tsconfig.json +30 -0
  5. package/.github/CODE_OF_CONDUCT.md +176 -0
  6. package/.github/CONTRIBUTING.md +296 -0
  7. package/.github/DISCUSSIONS.md +179 -0
  8. package/.github/ISSUE_TEMPLATE/bug-report.md +44 -0
  9. package/.github/ISSUE_TEMPLATE/feature-request.md +39 -0
  10. package/.github/pull_request_template.md +87 -0
  11. package/.github/workflows/phase-3c-l2-proof.yml +101 -0
  12. package/.github/workflows/phase-c-full-slack.yml +409 -0
  13. package/.github/workflows/phase-c-full.yml +241 -0
  14. package/.github/workflows/phase-c-scan.yml +64 -0
  15. package/.gitmodules +3 -0
  16. package/.tmp.js +3 -0
  17. package/CHANGELOG.md +1182 -0
  18. package/CLAUDE.md +633 -0
  19. package/Dockerfile +3 -0
  20. package/LICENSE +21 -0
  21. package/MISTAKES-COVERAGE.json +115 -0
  22. package/Makefile +95 -0
  23. package/PHASE-F-ROADMAP.md +554 -0
  24. package/README.md +459 -0
  25. package/SELF_HOSTING_CHECKLIST.md +155 -0
  26. package/benchmark-freelang.fl +47 -0
  27. package/benchmark-results.json +37 -0
  28. package/benchmark-simple.fl +38 -0
  29. package/bin/freelang-migrate +310 -0
  30. package/bin/freelang-smart +258 -0
  31. package/bootstrap.js +1134 -0
  32. package/docker-compose.yml +3 -0
  33. package/docs/AI_FRIENDLINESS.md +181 -0
  34. package/docs/AI_LEARNING_PATH.md +542 -0
  35. package/docs/AI_MAINTENANCE.md +153 -0
  36. package/docs/AI_QUICKSTART.md +380 -0
  37. package/docs/AI_REFERENCE.md +559 -0
  38. package/docs/AI_RELIABILITY_GUIDE.md +597 -0
  39. package/docs/AKL_ARCHITECTURE.md +228 -0
  40. package/docs/AKL_P0_KIMDB.md +215 -0
  41. package/docs/API.md +380 -0
  42. package/docs/ARCHITECTURE.md +208 -0
  43. package/docs/CHANGELOG.md +1014 -0
  44. package/docs/CLAUDE.md +991 -0
  45. package/docs/CLAUDE_AI.md +210 -0
  46. package/docs/CODEGEN_IMPROVEMENTS.md +158 -0
  47. package/docs/CODE_OF_CONDUCT.md +337 -0
  48. package/docs/CONTRIBUTING.md +437 -0
  49. package/docs/CRON_AUTOMATION.md +97 -0
  50. package/docs/DEPLOYMENT.md +357 -0
  51. package/docs/DETERMINISM_GUIDE.md +174 -0
  52. package/docs/HUMAN_GUIDE.md +599 -0
  53. package/docs/INDEX.md +199 -0
  54. package/docs/INLINE_TEST_GUIDE.md +231 -0
  55. package/docs/LANGUAGE-FAULTS.md +583 -0
  56. package/docs/LANGUAGE_IMPROVEMENT_REQUESTS.md +187 -0
  57. package/docs/LEARNING.md +257 -0
  58. package/docs/MISTAKES-100.md +52 -0
  59. package/docs/MISTAKES.md +131 -0
  60. package/docs/NAMING_CONVENTIONS.md +158 -0
  61. package/docs/NIGHTLY-MONITORING.md +222 -0
  62. package/docs/OFFICIAL_LANGUAGE.md +249 -0
  63. package/docs/ONBOARDING_1HOUR.md +210 -0
  64. package/docs/PERFORMANCE.md +329 -0
  65. package/docs/PHASE-3C-L2-PROOF-PLAN.md +282 -0
  66. package/docs/PHASE-3C-L2-RESULTS.md +183 -0
  67. package/docs/PHASE-3D-AI-LIBRARY.md +170 -0
  68. package/docs/PHASE-3E-VM-OPTIMIZATION.md +192 -0
  69. package/docs/PHASE-C-CI.md +242 -0
  70. package/docs/PHASE-C-PR-CHECKLIST.md +267 -0
  71. package/docs/PHASE-C-ROADMAP.md +141 -0
  72. package/docs/PHASE-C-SCAN.md +205 -0
  73. package/docs/PHASE-G-ROADMAP.md +228 -0
  74. package/docs/PHASE-X-V11.5-ROADMAP.md +267 -0
  75. package/docs/PHASE4_IMPLEMENTATION_PLAN.md +290 -0
  76. package/docs/PHASE5-COMPLETION.md +186 -0
  77. package/docs/PHASE5-SUMMARY.md +82 -0
  78. package/docs/PLUGIN_GUIDE.md +241 -0
  79. package/docs/PROJECT_OVERVIEW_KO.md +66 -0
  80. package/docs/QUICKSTART.md +160 -0
  81. package/docs/README.md +192 -0
  82. package/docs/RESERVED.md +125 -0
  83. package/docs/ROADMAP.md +191 -0
  84. package/docs/SECURITY.md +518 -0
  85. package/docs/SETUP.md +127 -0
  86. package/docs/SLACK-SETUP.md +190 -0
  87. package/docs/STATE_OF_V11.md +74 -0
  88. package/docs/STDLIB_NAMING_AUDIT.md +154 -0
  89. package/docs/STDLIB_REFERENCE.md +2722 -0
  90. package/docs/STYLE_GUIDE.md +559 -0
  91. package/docs/TASK5-MAP-DESTRUCTURE-DESIGN.md +136 -0
  92. package/docs/TOOLS.md +357 -0
  93. package/docs/TYPE_SYSTEM_GUIDE.md +201 -0
  94. package/docs/UI-PATTERN.md +265 -0
  95. package/docs/V11.5-RULES.md +416 -0
  96. package/docs/V11.6-HARNESS-RULES.md +222 -0
  97. package/docs/V11.6-MULTI-AGENT-PLAN.md +265 -0
  98. package/docs/V11.6-STABILIZATION-PLAN.md +290 -0
  99. package/docs/Y4-2B_DRY_RUN.md +142 -0
  100. package/docs/_classifications.json +882 -0
  101. package/docs/api/stdlib.md +134 -0
  102. package/docs/blog/2026-04-17-v11-ai-first-evolution.md +223 -0
  103. package/docs/blog/2026-04-20-self-hosting-fixedpoint.md +269 -0
  104. package/docs/blog/2026-05-04-mistakes-are-language-faults.md +267 -0
  105. package/docs/blog/2026-05-04-mistakes-coverage-honest.md +170 -0
  106. package/docs/blog/2026-05-04-phase-g-followup-smart-wrapper.md +188 -0
  107. package/docs/blog/2026-05-04-phase-g-mistakes-100.md +269 -0
  108. package/docs/blog/2026-05-04-phase-x-v11.5-launch.md +224 -0
  109. package/docs/blog/2026-05-04-v11.5.0-real-language-change.md +252 -0
  110. package/docs/blog-demo/README.md +44 -0
  111. package/docs/examples/index.md +78 -0
  112. package/docs/examples/todo-app.md +99 -0
  113. package/docs/guide/ai-blocks.md +335 -0
  114. package/docs/guide/basics.md +235 -0
  115. package/docs/guide/frameworks.md +319 -0
  116. package/docs/homepage/README.md +164 -0
  117. package/docs/index.md +183 -0
  118. package/docs/v12-DESIGN.md +214 -0
  119. package/examples/README.md +26 -0
  120. package/examples/browser-test.html +149 -0
  121. package/examples/csv-tool/analyze.fl +222 -0
  122. package/examples/csv-tool/employees.csv +16 -0
  123. package/examples/csv-tool/products.csv +21 -0
  124. package/examples/factorial.fl +9 -0
  125. package/examples/fib30.fl +4 -0
  126. package/examples/hello.fl +2 -0
  127. package/examples/hello.fl.js +3 -0
  128. package/examples/learning-session/01-grade-stats.fl +49 -0
  129. package/examples/learning-session/02-class-stats.fl +52 -0
  130. package/examples/learning-session/03-cart.fl +61 -0
  131. package/examples/learning-session/04-word-freq.fl +57 -0
  132. package/examples/learning-session/05-todo.fl +69 -0
  133. package/examples/learning-session/06-library.fl +76 -0
  134. package/examples/learning-session/07-currency.fl +99 -0
  135. package/examples/learning-session/08-csv-grades.fl +104 -0
  136. package/examples/learning-session/09-calc-repl.fl +92 -0
  137. package/examples/learning-session/10-contacts.fl +109 -0
  138. package/examples/learning-session/11-markdown.fl +107 -0
  139. package/examples/learning-session/12-calendar.fl +87 -0
  140. package/examples/learning-session/13-statistics.fl +123 -0
  141. package/examples/learning-session/14-primes.fl +107 -0
  142. package/examples/learning-session/15-statistics.fl +123 -0
  143. package/examples/learning-session/16-calendar.fl +87 -0
  144. package/examples/learning-session/17-markdown.fl +107 -0
  145. package/examples/learning-session/18-contacts.fl +109 -0
  146. package/examples/learning-session/19-json-serializer.fl +86 -0
  147. package/examples/learning-session/20-template.fl +201 -0
  148. package/examples/learning-session/21-calc-parser.fl +148 -0
  149. package/examples/learning-session/22-table.fl +96 -0
  150. package/examples/patterns/01-map-filter-reduce.fl +50 -0
  151. package/examples/patterns/02-error-handling.fl +51 -0
  152. package/examples/patterns/03-type-validation.fl +57 -0
  153. package/examples/patterns/04-state-management.fl +44 -0
  154. package/examples/patterns/05-api-integration.fl +95 -0
  155. package/examples/patterns/06-database-operations.fl +113 -0
  156. package/examples/patterns/07-string-processing.fl +86 -0
  157. package/examples/patterns/08-data-transformation.fl +92 -0
  158. package/examples/patterns/09-decision-logic.fl +122 -0
  159. package/examples/patterns/10-agent-orchestration.fl +184 -0
  160. package/examples/patterns/README.md +344 -0
  161. package/examples/simple-server.fl +29 -0
  162. package/examples/tables-app.fl +219 -0
  163. package/examples/test-libs.fl +272 -0
  164. package/jest.config.js +4 -0
  165. package/lib/datetime.fl +123 -0
  166. package/lib/http-client.fl +129 -0
  167. package/lib/pipeline.fl +150 -0
  168. package/lib/query.fl +160 -0
  169. package/lib/result.fl +124 -0
  170. package/lib/template.fl +161 -0
  171. package/lib/validate.fl +136 -0
  172. package/package.json +58 -0
  173. package/scripts/ai-eval.js +318 -0
  174. package/scripts/ai-self-verify.js +200 -0
  175. package/scripts/ai-validate.js +302 -0
  176. package/scripts/bench.sh +71 -0
  177. package/scripts/benchmark.js +258 -0
  178. package/scripts/benchmark.sh +99 -0
  179. package/scripts/build-binary.sh +68 -0
  180. package/scripts/build-runtime.sh +46 -0
  181. package/scripts/build-stage1-final.sh +58 -0
  182. package/scripts/build-stage1.sh +119 -0
  183. package/scripts/build-standalone.sh +17 -0
  184. package/scripts/build.js +130 -0
  185. package/scripts/check-let-regressions.js +95 -0
  186. package/scripts/check-parens.py +117 -0
  187. package/scripts/check-ports.sh +49 -0
  188. package/scripts/check-syntax.js +30 -0
  189. package/scripts/cli-extras.js +135 -0
  190. package/scripts/cron-daily-verify.sh +101 -0
  191. package/scripts/deploy.sh +91 -0
  192. package/scripts/dev.sh +37 -0
  193. package/scripts/extract-fl-examples.js +29 -0
  194. package/scripts/extract-runtime-helpers.js +122 -0
  195. package/scripts/fl-compile.sh +14 -0
  196. package/scripts/fl-fixpoint.sh +28 -0
  197. package/scripts/fl-repl.sh +21 -0
  198. package/scripts/fl-run.sh +41 -0
  199. package/scripts/fl-serve.sh +25 -0
  200. package/scripts/fuzz-compiler.js +92 -0
  201. package/scripts/gen-ai-prompt.js +340 -0
  202. package/scripts/gen-fixtures.js +166 -0
  203. package/scripts/gen-mistakes-split.js +199 -0
  204. package/scripts/gen-stdlib-docs.js +69 -0
  205. package/scripts/lint-stdlib-aliases.js +166 -0
  206. package/scripts/measure-baseline.sh +43 -0
  207. package/scripts/property-test.js +885 -0
  208. package/scripts/push-to-gogs.sh +60 -0
  209. package/scripts/regression-scan.js +132 -0
  210. package/scripts/run-jest-shard.sh +85 -0
  211. package/scripts/safe-push.sh +37 -0
  212. package/scripts/scan-fl-tokens.js +170 -0
  213. package/scripts/scan-for-fl-tokens.sh +17 -0
  214. package/scripts/self-diff.sh +95 -0
  215. package/scripts/snapshot-v0.sh +35 -0
  216. package/scripts/test-l2-fixpoint.sh +54 -0
  217. package/scripts/verify-all.sh +130 -0
  218. package/scripts/verify-build-deterministic.sh +110 -0
  219. package/scripts/verify-c7-bootstrap.sh +150 -0
  220. package/scripts/verify-c8-fixed-point-simple.sh +121 -0
  221. package/scripts/verify-c8-fixed-point.sh +133 -0
  222. package/scripts/verify-c9-fuzzing.sh +214 -0
  223. package/scripts/verify-fixed-point-deep.sh +133 -0
  224. package/scripts/verify-fixed-point.sh +65 -0
  225. package/scripts/verify-l2-proof.sh +153 -0
  226. package/scripts/verify-l3-proof.sh +40 -0
  227. package/scripts/verify-mistakes-coverage.js +120 -0
  228. package/scripts/verify-self-host.sh +509 -0
  229. package/self/CHANGELOG.md +964 -0
  230. package/self/COMPILER_REDESIGN_FAILURES.md +59 -0
  231. package/self/INTEGRATION-CHECKLIST.md +113 -0
  232. package/self/README.md +34 -0
  233. package/self/all.fl +1353 -0
  234. package/self/ast.fl +219 -0
  235. package/self/ast.self.js +47 -0
  236. package/self/bench/_bi_json-parse.js +46 -0
  237. package/self/bench/_bi_json-str.js +60 -0
  238. package/self/bench/_bi_list-distinct.js +37 -0
  239. package/self/bench/_bi_list-filter-even.js +56 -0
  240. package/self/bench/_bi_list-first.js +29 -0
  241. package/self/bench/_bi_list-last.js +28 -0
  242. package/self/bench/_bi_list-map-inc.js +41 -0
  243. package/self/bench/_bi_list-range.js +22 -0
  244. package/self/bench/_bi_list-reduce-sum.js +50 -0
  245. package/self/bench/_bi_list-reverse.js +28 -0
  246. package/self/bench/_bi_list-sort.js +35 -0
  247. package/self/bench/_bi_list-take.js +36 -0
  248. package/self/bench/_bi_m-abs.js +24 -0
  249. package/self/bench/_bi_m-floor.js +22 -0
  250. package/self/bench/_bi_m-max.js +26 -0
  251. package/self/bench/_bi_m-min.js +26 -0
  252. package/self/bench/_bi_m-mod.js +21 -0
  253. package/self/bench/_bi_map-has.js +50 -0
  254. package/self/bench/_bi_map-keys.js +50 -0
  255. package/self/bench/_bi_map-values.js +52 -0
  256. package/self/bench/_bi_str-concat.js +36 -0
  257. package/self/bench/_bi_str-contains.js +43 -0
  258. package/self/bench/_bi_str-ends.js +45 -0
  259. package/self/bench/_bi_str-index.js +34 -0
  260. package/self/bench/_bi_str-lower.js +23 -0
  261. package/self/bench/_bi_str-repeat.js +26 -0
  262. package/self/bench/_bi_str-split.js +41 -0
  263. package/self/bench/_bi_str-starts.js +47 -0
  264. package/self/bench/_bi_str-trim.js +26 -0
  265. package/self/bench/_bi_str-upper.js +23 -0
  266. package/self/bench/_bi_t-list.js +24 -0
  267. package/self/bench/_bi_t-null.js +23 -0
  268. package/self/bench/_bi_t-number.js +23 -0
  269. package/self/bench/_bi_t-string.js +25 -0
  270. package/self/bench/_bi_t-typeof.js +25 -0
  271. package/self/bench/_c_parse_probe.fl +426 -0
  272. package/self/bench/_c_parse_probe.js +67 -0
  273. package/self/bench/_codegen_nodrv.fl +751 -0
  274. package/self/bench/_combined2.fl +423 -0
  275. package/self/bench/_combined_arr.fl +422 -0
  276. package/self/bench/_combined_astprobe.fl +429 -0
  277. package/self/bench/_combined_astprobe.js +69 -0
  278. package/self/bench/_combined_cg.fl +424 -0
  279. package/self/bench/_combined_cg.js +64 -0
  280. package/self/bench/_combined_lex.fl +421 -0
  281. package/self/bench/_combined_trace.fl +435 -0
  282. package/self/bench/_combined_trace.js +75 -0
  283. package/self/bench/_ext_abs-neg.js +2 -0
  284. package/self/bench/_ext_and.js +2 -0
  285. package/self/bench/_ext_cond-1.js +2 -0
  286. package/self/bench/_ext_cond-2.js +2 -0
  287. package/self/bench/_ext_do-seq.js +2 -0
  288. package/self/bench/_ext_fact20.js +3 -0
  289. package/self/bench/_ext_fib25.js +3 -0
  290. package/self/bench/_ext_length.js +2 -0
  291. package/self/bench/_ext_let-1d.js +18 -0
  292. package/self/bench/_ext_let-2d.js +2 -0
  293. package/self/bench/_ext_list-sum.js +3 -0
  294. package/self/bench/_ext_math.js +2 -0
  295. package/self/bench/_ext_or.js +2 -0
  296. package/self/bench/_ext_str.js +2 -0
  297. package/self/bench/_fact15.js +2 -0
  298. package/self/bench/_fb_fact15.js +2 -0
  299. package/self/bench/_fb_func-fact.js +2 -0
  300. package/self/bench/_fb_func-multi.js +2 -0
  301. package/self/bench/_fb_func-mutual.js +3 -0
  302. package/self/bench/_fb_func-simple.js +21 -0
  303. package/self/bench/_fib.js +2 -0
  304. package/self/bench/_fn_async-await-seq.js +40 -0
  305. package/self/bench/_fn_async-await.js +3 -0
  306. package/self/bench/_fn_async-print.js +26 -0
  307. package/self/bench/_fn_async-result.js +1 -0
  308. package/self/bench/_fn_call-form.js +24 -0
  309. package/self/bench/_fn_compose.js +37 -0
  310. package/self/bench/_fn_pipe.js +34 -0
  311. package/self/bench/_fn_thread-first-sexpr.js +31 -0
  312. package/self/bench/_fn_thread-first.js +25 -0
  313. package/self/bench/_fn_thread-last.js +31 -0
  314. package/self/bench/_generated.js +35 -0
  315. package/self/bench/_mt_match-default.js +51 -0
  316. package/self/bench/_mt_match-num.js +58 -0
  317. package/self/bench/_mt_match-str.js +56 -0
  318. package/self/bench/_mt_match-var.js +32 -0
  319. package/self/bench/_mt_match-wild.js +36 -0
  320. package/self/bench/_mt_struct-make.js +81 -0
  321. package/self/bench/_mt_struct-tag.js +81 -0
  322. package/self/bench/_probe.fl +1 -0
  323. package/self/bench/_probe2.fl +1 -0
  324. package/self/bench/_probe3.fl +3 -0
  325. package/self/bench/_probe_apply.fl +1 -0
  326. package/self/bench/_probe_args.fl +7 -0
  327. package/self/bench/_probe_arr.fl +7 -0
  328. package/self/bench/_probe_arr2.fl +5 -0
  329. package/self/bench/_probe_block.fl +7 -0
  330. package/self/bench/_probe_call.fl +1 -0
  331. package/self/bench/_probe_cg.fl +27 -0
  332. package/self/bench/_probe_compose.fl +13 -0
  333. package/self/bench/_probe_define.fl +1 -0
  334. package/self/bench/_probe_keys.fl +5 -0
  335. package/self/bench/_probe_length.fl +5 -0
  336. package/self/bench/_probe_lexparse.fl +4 -0
  337. package/self/bench/_probe_loop.fl +12 -0
  338. package/self/bench/_probe_map.fl +8 -0
  339. package/self/bench/_probe_map2.fl +8 -0
  340. package/self/bench/_probe_map3.fl +5 -0
  341. package/self/bench/_probe_mapkeys.fl +5 -0
  342. package/self/bench/_probe_mapv12.fl +1 -0
  343. package/self/bench/_probe_mapv12.js +2 -0
  344. package/self/bench/_probe_match.fl +1 -0
  345. package/self/bench/_probe_match2.fl +1 -0
  346. package/self/bench/_probe_neg.fl +7 -0
  347. package/self/bench/_probe_neg2.fl +3 -0
  348. package/self/bench/_probe_protocol.fl +7 -0
  349. package/self/bench/_probe_self_parse.fl +6 -0
  350. package/self/bench/_probe_struct.fl +1 -0
  351. package/self/bench/_probe_true.fl +3 -0
  352. package/self/bench/_probe_true2.fl +6 -0
  353. package/self/bench/_probe_v12_cg.fl +7 -0
  354. package/self/bench/_probe_v12_extract.fl +8 -0
  355. package/self/bench/_probe_v12_extract.js +7 -0
  356. package/self/bench/_probe_v12_internal.fl +21 -0
  357. package/self/bench/_probe_v12_map_ast.fl +12 -0
  358. package/self/bench/_rs_combo.js +3 -0
  359. package/self/bench/_rs_gcd.js +36 -0
  360. package/self/bench/_rs_grade.js +2 -0
  361. package/self/bench/_rs_mutual-fib.js +2 -0
  362. package/self/bench/_rs_range-sum.js +2 -0
  363. package/self/bench/_rs_sum-10k.js +2 -0
  364. package/self/bench/_rs_sum-5k.js +2 -0
  365. package/self/bench/_sf_loop-fact-10.js +73 -0
  366. package/self/bench/_sf_loop-sum-10k.js +87 -0
  367. package/self/bench/_sf_set-x.js +40 -0
  368. package/self/bench/_sf_throw-catch.js +1 -0
  369. package/self/bench/_sf_while-5.js +62 -0
  370. package/self/bench/_v12_combined.fl +1184 -0
  371. package/self/bench/_v12_extract_test.fl +14 -0
  372. package/self/bench/_v12_extract_test.js +7 -0
  373. package/self/bench/_v12_inspect.js +26 -0
  374. package/self/bench/_v12_inspect_mod.js +137 -0
  375. package/self/bench/_v12_makevartest.fl +8 -0
  376. package/self/bench/_v12_makevartest.js +6 -0
  377. package/self/bench/_v12_parse_probe.fl +9 -0
  378. package/self/bench/_v12_parse_trace.fl +18 -0
  379. package/self/bench/_v12_simple_fn.fl +2 -0
  380. package/self/bench/_v12_simple_fn.js +3 -0
  381. package/self/bench/_v12_trace.fl +2 -0
  382. package/self/bench/_v12_trace.js +3 -0
  383. package/self/bench/collection.js +13 -0
  384. package/self/bench/fib30.fl +4 -0
  385. package/self/bench/final-test.fl +12 -0
  386. package/self/bench/final-test.js +2 -0
  387. package/self/bench/fp1-v12.js +4 -0
  388. package/self/bench/fp1.fl +3 -0
  389. package/self/bench/fp1.fp.js +4 -0
  390. package/self/bench/fp2-v12.js +4 -0
  391. package/self/bench/fp2.fl +3 -0
  392. package/self/bench/fp2.fp.js +4 -0
  393. package/self/bench/fp3-v12.js +8 -0
  394. package/self/bench/fp3.fl +11 -0
  395. package/self/bench/fp3.fp.js +8 -0
  396. package/self/bench/fp4-v12.js +6 -0
  397. package/self/bench/fp4.fl +9 -0
  398. package/self/bench/fp4.fp.js +6 -0
  399. package/self/bench/hello-sample.fl +3 -0
  400. package/self/bench/hello-sample.js +4 -0
  401. package/self/bench/hello.fl +1 -0
  402. package/self/bench/json.js +9 -0
  403. package/self/bench/json1mb.fl +3 -0
  404. package/self/bench/math.js +8 -0
  405. package/self/bench/realworld.fl +17 -0
  406. package/self/bench/realworld.js +8 -0
  407. package/self/bench/regex.js +10 -0
  408. package/self/bench/sample.json +1 -0
  409. package/self/bench/string.js +7 -0
  410. package/self/bench/test-ffi.fl +3 -0
  411. package/self/bench/test-ffi.js +2 -0
  412. package/self/bench/test-hof-advanced.fl +7 -0
  413. package/self/bench/test-hof-advanced.js +2 -0
  414. package/self/bench/test-hof.fl +5 -0
  415. package/self/bench/test-hof.js +2 -0
  416. package/self/bench/test-output.txt +1 -0
  417. package/self/bench/test-phase15-integration.fl +16 -0
  418. package/self/bench/test-phase15-integration.js +3 -0
  419. package/self/bench/test-phase19-complete.fl +24 -0
  420. package/self/bench/test-phase19-complete.js +2 -0
  421. package/self/bench/test-stdlib-codegen.fl +9 -0
  422. package/self/bench/test-stdlib-codegen.js +2 -0
  423. package/self/bench/test-time.fl +8 -0
  424. package/self/bench/test-time.js +2 -0
  425. package/self/bench/time.js +9 -0
  426. package/self/bench/tiny-v12.js +2 -0
  427. package/self/bench/tiny.fl +1 -0
  428. package/self/builtins/core.fl +150 -0
  429. package/self/char-class.fl +45 -0
  430. package/self/codegen-core.fl +733 -0
  431. package/self/codegen-final.fl +135 -0
  432. package/self/codegen.fl +379 -0
  433. package/self/codegen.fl.bak +856 -0
  434. package/self/codegen.self.js +75 -0
  435. package/self/examples/agent-loop.fl +32 -0
  436. package/self/examples/ci-cd-example.fl +114 -0
  437. package/self/examples/cloud-real.fl +134 -0
  438. package/self/examples/docker-example.fl +67 -0
  439. package/self/examples/fullstack-app.fl +330 -0
  440. package/self/examples/k8s-example.fl +91 -0
  441. package/self/examples/microservices.fl +448 -0
  442. package/self/examples/rest-api.fl +253 -0
  443. package/self/examples/style-example.fl +133 -0
  444. package/self/examples/workflow-orchestration.fl +44 -0
  445. package/self/fixtures/eval/add.fl +1 -0
  446. package/self/fixtures/eval/and-sc.fl +1 -0
  447. package/self/fixtures/eval/bool-false.fl +1 -0
  448. package/self/fixtures/eval/bool-true.fl +1 -0
  449. package/self/fixtures/eval/closure.fl +1 -0
  450. package/self/fixtures/eval/cmp-eq.fl +1 -0
  451. package/self/fixtures/eval/cmp-lt.fl +1 -0
  452. package/self/fixtures/eval/cond-first.fl +1 -0
  453. package/self/fixtures/eval/define-fn3.fl +1 -0
  454. package/self/fixtures/eval/define-var.fl +1 -0
  455. package/self/fixtures/eval/defn-bare.fl +1 -0
  456. package/self/fixtures/eval/defn-call.fl +1 -0
  457. package/self/fixtures/eval/div.fl +1 -0
  458. package/self/fixtures/eval/filter-hof.fl +1 -0
  459. package/self/fixtures/eval/floor.fl +1 -0
  460. package/self/fixtures/eval/fn-apply.fl +1 -0
  461. package/self/fixtures/eval/get-idx.fl +1 -0
  462. package/self/fixtures/eval/get-key.fl +1 -0
  463. package/self/fixtures/eval/higher-order.fl +1 -0
  464. package/self/fixtures/eval/let-bare.fl +1 -0
  465. package/self/fixtures/eval/let-flat.fl +1 -0
  466. package/self/fixtures/eval/let-use.fl +1 -0
  467. package/self/fixtures/eval/list-first.fl +1 -0
  468. package/self/fixtures/eval/list-last.fl +1 -0
  469. package/self/fixtures/eval/list-len.fl +1 -0
  470. package/self/fixtures/eval/map-hof.fl +1 -0
  471. package/self/fixtures/eval/mod.fl +1 -0
  472. package/self/fixtures/eval/mul-nested.fl +1 -0
  473. package/self/fixtures/eval/not.fl +1 -0
  474. package/self/fixtures/eval/null-p.fl +1 -0
  475. package/self/fixtures/eval/or-sc.fl +1 -0
  476. package/self/fixtures/eval/pow.fl +1 -0
  477. package/self/fixtures/eval/recursion.fl +1 -0
  478. package/self/fixtures/eval/reduce-hof.fl +1 -0
  479. package/self/fixtures/eval/replace.fl +1 -0
  480. package/self/fixtures/eval/sqrt.fl +1 -0
  481. package/self/fixtures/eval/str-concat.fl +1 -0
  482. package/self/fixtures/eval/str-num.fl +1 -0
  483. package/self/fixtures/eval/sub.fl +1 -0
  484. package/self/fixtures/eval/substring.fl +1 -0
  485. package/self/fixtures/lex/array.fl +1 -0
  486. package/self/fixtures/lex/at-atom.fl +1 -0
  487. package/self/fixtures/lex/block.fl +1 -0
  488. package/self/fixtures/lex/comment.fl +2 -0
  489. package/self/fixtures/lex/deep-array.fl +1 -0
  490. package/self/fixtures/lex/deep-map.fl +1 -0
  491. package/self/fixtures/lex/deep-nest.fl +1 -0
  492. package/self/fixtures/lex/dollar-dot.fl +1 -0
  493. package/self/fixtures/lex/empty-list.fl +1 -0
  494. package/self/fixtures/lex/empty-str.fl +1 -0
  495. package/self/fixtures/lex/empty.fl +1 -0
  496. package/self/fixtures/lex/float.fl +1 -0
  497. package/self/fixtures/lex/hex.fl +1 -0
  498. package/self/fixtures/lex/kebab-sym.fl +1 -0
  499. package/self/fixtures/lex/keyword.fl +1 -0
  500. package/self/fixtures/lex/leading-zero.fl +1 -0
  501. package/self/fixtures/lex/long-num.fl +1 -0
  502. package/self/fixtures/lex/many-args.fl +1 -0
  503. package/self/fixtures/lex/map.fl +1 -0
  504. package/self/fixtures/lex/mixed.fl +1 -0
  505. package/self/fixtures/lex/neg-float.fl +1 -0
  506. package/self/fixtures/lex/negative.fl +1 -0
  507. package/self/fixtures/lex/nested.fl +1 -0
  508. package/self/fixtures/lex/null.fl +1 -0
  509. package/self/fixtures/lex/pipe-op.fl +1 -0
  510. package/self/fixtures/lex/route-like.fl +1 -0
  511. package/self/fixtures/lex/scientific.fl +1 -0
  512. package/self/fixtures/lex/single-num.fl +1 -0
  513. package/self/fixtures/lex/small-sexpr.fl +1 -0
  514. package/self/fixtures/lex/spaces.fl +1 -0
  515. package/self/fixtures/lex/str-quote.fl +1 -0
  516. package/self/fixtures/lex/str-tab.fl +1 -0
  517. package/self/fixtures/lex/string-esc.fl +1 -0
  518. package/self/fixtures/lex/string.fl +1 -0
  519. package/self/fixtures/lex/symbol.fl +1 -0
  520. package/self/fixtures/lex/tabs-nl.fl +3 -0
  521. package/self/fixtures/lex/true-false.fl +1 -0
  522. package/self/fixtures/lex/unicode.fl +1 -0
  523. package/self/fixtures/lex/variable.fl +1 -0
  524. package/self/fixtures/lex/zero.fl +1 -0
  525. package/self/fixtures/parse/and-or.fl +1 -0
  526. package/self/fixtures/parse/array-lit.fl +1 -0
  527. package/self/fixtures/parse/block-func.fl +1 -0
  528. package/self/fixtures/parse/compose.fl +1 -0
  529. package/self/fixtures/parse/cond.fl +1 -0
  530. package/self/fixtures/parse/define-fn.fl +1 -0
  531. package/self/fixtures/parse/define-val.fl +1 -0
  532. package/self/fixtures/parse/defn.fl +1 -0
  533. package/self/fixtures/parse/do-begin.fl +1 -0
  534. package/self/fixtures/parse/dotted.fl +1 -0
  535. package/self/fixtures/parse/empty-fn.fl +1 -0
  536. package/self/fixtures/parse/empty-list.fl +1 -0
  537. package/self/fixtures/parse/fn.fl +1 -0
  538. package/self/fixtures/parse/if-else.fl +1 -0
  539. package/self/fixtures/parse/if-only.fl +1 -0
  540. package/self/fixtures/parse/keyword-arg.fl +1 -0
  541. package/self/fixtures/parse/kw.fl +1 -0
  542. package/self/fixtures/parse/let-1d.fl +1 -0
  543. package/self/fixtures/parse/let-2d.fl +1 -0
  544. package/self/fixtures/parse/let-bare.fl +1 -0
  545. package/self/fixtures/parse/literal-num.fl +1 -0
  546. package/self/fixtures/parse/literal-str.fl +1 -0
  547. package/self/fixtures/parse/loop-recur.fl +1 -0
  548. package/self/fixtures/parse/map-lit.fl +1 -0
  549. package/self/fixtures/parse/match-simple.fl +1 -0
  550. package/self/fixtures/parse/multi-body.fl +1 -0
  551. package/self/fixtures/parse/nested-arr.fl +1 -0
  552. package/self/fixtures/parse/nested-block.fl +1 -0
  553. package/self/fixtures/parse/nested-map.fl +1 -0
  554. package/self/fixtures/parse/nested.fl +1 -0
  555. package/self/fixtures/parse/pipe.fl +1 -0
  556. package/self/fixtures/parse/quote.fl +1 -0
  557. package/self/fixtures/parse/set-bang.fl +1 -0
  558. package/self/fixtures/parse/sexpr.fl +1 -0
  559. package/self/fixtures/parse/str-interp.fl +1 -0
  560. package/self/fixtures/parse/sym.fl +1 -0
  561. package/self/fixtures/parse/thread-first.fl +1 -0
  562. package/self/fixtures/parse/thread-last.fl +1 -0
  563. package/self/fixtures/parse/try-catch.fl +1 -0
  564. package/self/fixtures/parse/var.fl +1 -0
  565. package/self/full-compiler-fixed.fl +1308 -0
  566. package/self/full-compiler-v1-bloated.fl +1298 -0
  567. package/self/full-compiler.fl +1301 -0
  568. package/self/interpreter.fl +351 -0
  569. package/self/lexer.fl +200 -0
  570. package/self/lexer.self.js +30 -0
  571. package/self/main.fl +22 -0
  572. package/self/parser.fl +241 -0
  573. package/self/parser.self.js +33 -0
  574. package/self/runtime/http-server.js +642 -0
  575. package/self/runtime/interpreter.js +30787 -0
  576. package/self/runtime/repl.js +186 -0
  577. package/self/runtime-helpers.ts +282 -0
  578. package/self/scope.fl +80 -0
  579. package/self/scope.self.js +1 -0
  580. package/self/self/bench/_bi_list-distinct.js +2 -0
  581. package/self/self/bench/_bi_list-filter-even.js +2 -0
  582. package/self/self/bench/_bi_list-first.js +2 -0
  583. package/self/self/bench/_bi_list-last.js +2 -0
  584. package/self/self/bench/_bi_list-map-inc.js +2 -0
  585. package/self/self/bench/_bi_list-range.js +2 -0
  586. package/self/self/bench/_bi_list-reduce-sum.js +2 -0
  587. package/self/self/bench/_bi_list-reverse.js +2 -0
  588. package/self/self/bench/_bi_list-sort.js +2 -0
  589. package/self/self/bench/_bi_list-take.js +2 -0
  590. package/self/self/bench/_bi_map-has.js +2 -0
  591. package/self/self/bench/_bi_map-keys.js +2 -0
  592. package/self/self/bench/_bi_map-values.js +2 -0
  593. package/self/self/bench/_bi_str-concat.js +2 -0
  594. package/self/self/bench/_bi_str-contains.js +2 -0
  595. package/self/self/bench/_bi_str-ends.js +2 -0
  596. package/self/self/bench/_bi_str-index.js +2 -0
  597. package/self/self/bench/_bi_str-lower.js +2 -0
  598. package/self/self/bench/_bi_str-repeat.js +2 -0
  599. package/self/self/bench/_bi_str-split.js +2 -0
  600. package/self/self/bench/_bi_str-starts.js +2 -0
  601. package/self/self/bench/_bi_str-trim.js +2 -0
  602. package/self/self/bench/_bi_str-upper.js +2 -0
  603. package/self/self/bench/_ext_abs-neg.js +2 -0
  604. package/self/self/bench/_ext_and.js +2 -0
  605. package/self/self/bench/_ext_cond-1.js +2 -0
  606. package/self/self/bench/_ext_cond-2.js +2 -0
  607. package/self/self/bench/_ext_do-seq.js +2 -0
  608. package/self/self/bench/_ext_fact20.js +3 -0
  609. package/self/self/bench/_ext_fib25.js +3 -0
  610. package/self/self/bench/_ext_length.js +2 -0
  611. package/self/self/bench/_ext_let-1d.js +2 -0
  612. package/self/self/bench/_ext_let-2d.js +2 -0
  613. package/self/self/bench/_ext_list-sum.js +3 -0
  614. package/self/self/bench/_ext_math.js +2 -0
  615. package/self/self/bench/_ext_or.js +2 -0
  616. package/self/self/bench/_ext_str.js +2 -0
  617. package/self/self/bench/_fact15.js +2 -0
  618. package/self/self/bench/_fb_fact15.js +2 -0
  619. package/self/self/bench/_fb_func-fact.js +2 -0
  620. package/self/self/bench/_fb_func-multi.js +2 -0
  621. package/self/self/bench/_fb_func-mutual.js +3 -0
  622. package/self/self/bench/_fb_func-simple.js +2 -0
  623. package/self/self/bench/_fib.js +2 -0
  624. package/self/self/bench/_fn_async-await-seq.js +2 -0
  625. package/self/self/bench/_fn_async-print.js +2 -0
  626. package/self/self/bench/_fn_call-form.js +2 -0
  627. package/self/self/bench/_fn_compose.js +2 -0
  628. package/self/self/bench/_fn_pipe.js +2 -0
  629. package/self/self/bench/_fn_thread-first-sexpr.js +2 -0
  630. package/self/self/bench/_fn_thread-first.js +2 -0
  631. package/self/self/bench/_fn_thread-last.js +2 -0
  632. package/self/self/bench/_generated.js +2 -0
  633. package/self/self/bench/_mt_match-default.js +2 -0
  634. package/self/self/bench/_mt_match-num.js +2 -0
  635. package/self/self/bench/_mt_match-str.js +2 -0
  636. package/self/self/bench/_mt_match-var.js +2 -0
  637. package/self/self/bench/_mt_match-wild.js +2 -0
  638. package/self/self/bench/_mt_struct-make.js +4 -0
  639. package/self/self/bench/_mt_struct-tag.js +4 -0
  640. package/self/self/bench/_rs_combo.js +3 -0
  641. package/self/self/bench/_rs_gcd.js +2 -0
  642. package/self/self/bench/_rs_grade.js +2 -0
  643. package/self/self/bench/_rs_mutual-fib.js +2 -0
  644. package/self/self/bench/_rs_range-sum.js +2 -0
  645. package/self/self/bench/_rs_sum-5k.js +2 -0
  646. package/self/self/bench/_sf_loop-fact-10.js +1 -0
  647. package/self/self/bench/_sf_loop-sum-10k.js +1 -0
  648. package/self/self/bench/_sf_set-x.js +3 -0
  649. package/self/self/bench/_sf_throw-catch.js +1 -0
  650. package/self/self/bench/_sf_while-5.js +3 -0
  651. package/self/stdlib/ai.fl +73 -0
  652. package/self/stdlib/assert.fl +30 -0
  653. package/self/stdlib/async.fl +48 -0
  654. package/self/stdlib/base64.fl +22 -0
  655. package/self/stdlib/binary.fl +30 -0
  656. package/self/stdlib/build.fl +69 -0
  657. package/self/stdlib/collection.fl +37 -0
  658. package/self/stdlib/color.fl +35 -0
  659. package/self/stdlib/crypto-hash.fl +29 -0
  660. package/self/stdlib/crypto.fl +56 -0
  661. package/self/stdlib/data.fl +69 -0
  662. package/self/stdlib/db.fl +53 -0
  663. package/self/stdlib/encoding.fl +49 -0
  664. package/self/stdlib/error.fl +36 -0
  665. package/self/stdlib/feed.fl +86 -0
  666. package/self/stdlib/file.fl +53 -0
  667. package/self/stdlib/format.fl +34 -0
  668. package/self/stdlib/graph.fl +72 -0
  669. package/self/stdlib/hash.fl +32 -0
  670. package/self/stdlib/heap.fl +76 -0
  671. package/self/stdlib/http.fl +47 -0
  672. package/self/stdlib/image.fl +45 -0
  673. package/self/stdlib/json.fl +11 -0
  674. package/self/stdlib/list-extra.fl +32 -0
  675. package/self/stdlib/markdown.fl +59 -0
  676. package/self/stdlib/math-extra.fl +34 -0
  677. package/self/stdlib/math.fl +13 -0
  678. package/self/stdlib/metadata.fl +66 -0
  679. package/self/stdlib/mongodb/bson.fl +21 -0
  680. package/self/stdlib/mongodb/schema.fl +95 -0
  681. package/self/stdlib/mongodb/wire.fl +54 -0
  682. package/self/stdlib/mongodb.fl +172 -0
  683. package/self/stdlib/path.fl +72 -0
  684. package/self/stdlib/plot.fl +56 -0
  685. package/self/stdlib/process.fl +50 -0
  686. package/self/stdlib/queue.fl +65 -0
  687. package/self/stdlib/regex.fl +11 -0
  688. package/self/stdlib/resource.fl +61 -0
  689. package/self/stdlib/search.fl +54 -0
  690. package/self/stdlib/set-extra.fl +35 -0
  691. package/self/stdlib/sort.fl +61 -0
  692. package/self/stdlib/stack.fl +54 -0
  693. package/self/stdlib/stats.fl +110 -0
  694. package/self/stdlib/stream.fl +56 -0
  695. package/self/stdlib/string-extended.fl +25 -0
  696. package/self/stdlib/string-extra.fl +40 -0
  697. package/self/stdlib/string.fl +21 -0
  698. package/self/stdlib/test-helpers.fl +51 -0
  699. package/self/stdlib/test-runner.fl +76 -0
  700. package/self/stdlib/time-extra.fl +27 -0
  701. package/self/stdlib/time.fl +31 -0
  702. package/self/stdlib/tree.fl +57 -0
  703. package/self/stdlib/types.fl +85 -0
  704. package/self/stdlib/url.fl +33 -0
  705. package/self/stdlib/uuid.fl +28 -0
  706. package/self/stdlib/validation.fl +42 -0
  707. package/self/stdlib/vector-math.fl +52 -0
  708. package/self/stdlib/ws.fl +52 -0
  709. package/self/tests/mongodb-phase3.fl +75 -0
  710. package/self/tests/mongodb-wire-phase2.fl +45 -0
  711. package/self/tests/test-ast.fl +36 -0
  712. package/self/tests/test-builtins.fl +340 -0
  713. package/self/tests/test-char-class.fl +29 -0
  714. package/self/tests/test-codegen-builtins.fl +240 -0
  715. package/self/tests/test-codegen-ext.fl +380 -0
  716. package/self/tests/test-codegen-ffi.fl +295 -0
  717. package/self/tests/test-codegen-fn.fl +177 -0
  718. package/self/tests/test-codegen-match.fl +161 -0
  719. package/self/tests/test-codegen-run.fl +252 -0
  720. package/self/tests/test-codegen-sf.fl +262 -0
  721. package/self/tests/test-codegen.fl +260 -0
  722. package/self/tests/test-core-fl.fl +63 -0
  723. package/self/tests/test-forward-decl.fl +5 -0
  724. package/self/tests/test-func-block.fl +4 -0
  725. package/self/tests/test-interp-user-fn.fl +296 -0
  726. package/self/tests/test-interp.fl +225 -0
  727. package/self/tests/test-lexer.fl +162 -0
  728. package/self/tests/test-list-debug.fl +21 -0
  729. package/self/tests/test-mutual-rec.fl +6 -0
  730. package/self/tests/test-parser-debug.fl +35 -0
  731. package/self/tests/test-parser-full-debug.fl +66 -0
  732. package/self/tests/test-parser-lex-debug.fl +107 -0
  733. package/self/tests/test-parser-lex-only.fl +40 -0
  734. package/self/tests/test-parser-simple-debug.fl +35 -0
  735. package/self/tests/test-parser.fl +262 -0
  736. package/self/tests/test-real-stdlib.fl +377 -0
  737. package/self/tests/test-scope.fl +74 -0
  738. package/self/tests/test-selfcompile.fl +325 -0
  739. package/self/tests/test-stdlib.fl +44 -0
  740. package/self/tests/test-tco.fl +16 -0
  741. package/self/tests/test-token.fl +4 -0
  742. package/self/token.fl +38 -0
  743. package/self/token.self.js +8 -0
  744. package/self/v12-driver.fl +16 -0
  745. package/self/verify.fl +39 -0
  746. package/self-evolve/1-observe-ast.fl +28 -0
  747. package/self-evolve/2-inspect-block.fl +35 -0
  748. package/self-evolve/3-full-ast-json.fl +10 -0
  749. package/self-evolve/4-trace-block-fields.fl +23 -0
  750. package/self-evolve/5-analyze-do-ast.fl +29 -0
  751. package/self-evolve/6-test-do-elim-simple.fl +14 -0
  752. package/self-evolve/debug-evaluate.fl +24 -0
  753. package/self-evolve/debug-gen1-const-fold.fl +57 -0
  754. package/self-evolve/debug-map.fl +15 -0
  755. package/self-evolve/debug-optimize-simple.fl +95 -0
  756. package/self-evolve/debug-recursive-map.fl +23 -0
  757. package/self-evolve/logs/gen-0.fl +1658 -0
  758. package/self-evolve/logs/gen-1.fl +1658 -0
  759. package/self-evolve/logs/gen-2.fl +1658 -0
  760. package/self-evolve/logs/speed-gen-0.fl +1423 -0
  761. package/self-evolve/run-semantic-test.js +130 -0
  762. package/self-evolve/test-basic.fl +19 -0
  763. package/self-evolve/test-fold-direct.fl +60 -0
  764. package/self-evolve/test-gen1-simple.fl +67 -0
  765. package/self-evolve/test-optimize-debug.fl +63 -0
  766. package/self-evolve/tmp-test.fl +1 -0
  767. package/self-evolve/v11-analyzer.fl +40 -0
  768. package/self-evolve/v11-benchmark.fl +45 -0
  769. package/self-evolve/v11-evolution-real.fl +45 -0
  770. package/self-evolve/v11-evolution.fl +32 -0
  771. package/self-evolve/v11-gen1-validate.fl +157 -0
  772. package/self-evolve/v11-optimizer-constant-fold.fl +124 -0
  773. package/self-evolve/v11-optimizer-dead-expr.fl +111 -0
  774. package/self-evolve/v11-optimizer-gen1-complete.fl +180 -0
  775. package/self-evolve/v11-optimizer-gen1.fl +68 -0
  776. package/self-evolve/v11-optimizer.fl +56 -0
  777. package/self-evolve/v11-semantic-test.fl +54 -0
  778. package/self-evolve/v11-speed-benchmark.fl +106 -0
  779. package/self-evolve/v11-speed-optimizer.fl +79 -0
  780. package/src/AGENT-DSL.md +527 -0
  781. package/src/CLI-DEPLOYMENT.md +204 -0
  782. package/src/CLI.md +361 -0
  783. package/src/EXPRESS-ADVANCED.md +294 -0
  784. package/src/EXPRESS-AUTH.md +365 -0
  785. package/src/EXPRESS-CACHE.md +409 -0
  786. package/src/EXPRESS-COMPLETE.md +569 -0
  787. package/src/EXPRESS-README.md +121 -0
  788. package/src/EXPRESS-TEST.md +492 -0
  789. package/src/EXPRESS-WEBSOCKET.md +391 -0
  790. package/src/LOGGING-GUIDE.md +354 -0
  791. package/src/STORAGE-GUIDE.md +416 -0
  792. package/src/__tests__/advanced.test.ts +573 -0
  793. package/src/__tests__/ai-library.test.ts +210 -0
  794. package/src/__tests__/build-determinism.test.ts +33 -0
  795. package/src/__tests__/builtins-advanced.test.ts +150 -0
  796. package/src/__tests__/builtins-sanity.test.ts +180 -0
  797. package/src/__tests__/codegen.let.test.ts +81 -0
  798. package/src/__tests__/core.test.ts +188 -0
  799. package/src/__tests__/coverage-boost.test.ts +626 -0
  800. package/src/__tests__/cron-scheduler.test.ts +269 -0
  801. package/src/__tests__/enterprise-blocks.test.ts +63 -0
  802. package/src/__tests__/errors.test.ts +313 -0
  803. package/src/__tests__/integration.test.ts +219 -0
  804. package/src/__tests__/interpreter.test.ts +170 -0
  805. package/src/__tests__/l2-proof.test.ts +78 -0
  806. package/src/__tests__/lexer-parser.test.ts +366 -0
  807. package/src/__tests__/lexer.test.ts +106 -0
  808. package/src/__tests__/mariadb-prepared-statement.test.ts +206 -0
  809. package/src/__tests__/migrate.test.ts +403 -0
  810. package/src/__tests__/mongodb-integration.test.ts.skip +207 -0
  811. package/src/__tests__/mongodb-phase4.test.ts +132 -0
  812. package/src/__tests__/p1-1-parallel-tasks.test.ts +179 -0
  813. package/src/__tests__/p1-2-compensation.test.ts +242 -0
  814. package/src/__tests__/p1-3-distributed.test.ts +160 -0
  815. package/src/__tests__/p1-4-observability.test.ts +161 -0
  816. package/src/__tests__/parser.test.ts +142 -0
  817. package/src/__tests__/phase151-self-evolve.test.ts +161 -0
  818. package/src/__tests__/rate-limiter.test.ts +274 -0
  819. package/src/__tests__/self-hosting.test.ts +174 -0
  820. package/src/__tests__/semantic-preservation.test.ts +207 -0
  821. package/src/__tests__/setup.ts +34 -0
  822. package/src/__tests__/special-forms-advanced.test.ts +106 -0
  823. package/src/__tests__/stdlib-crypto-rsa.test.ts +122 -0
  824. package/src/__tests__/stdlib-f4.test.ts +159 -0
  825. package/src/__tests__/stdlib-helpers.test.ts +128 -0
  826. package/src/__tests__/stdlib-modules.test.ts +161 -0
  827. package/src/__tests__/stdlib-mongodb.test.ts +331 -0
  828. package/src/__tests__/stdlib-new.test.ts +269 -0
  829. package/src/__tests__/stdlib-perf.test.ts +125 -0
  830. package/src/__tests__/stdlib-phase-b.test.ts +249 -0
  831. package/src/__tests__/stdlib.test.ts +163 -0
  832. package/src/__tests__/v12-alpha.test.ts +205 -0
  833. package/src/__tests__/vm-optin.test.ts +141 -0
  834. package/src/__tests__/web-integration.test.ts +1452 -0
  835. package/src/__tests__/weblibs.test.ts +210 -0
  836. package/src/_aliases.json +1123 -0
  837. package/src/_mongodb_helper.js +272 -0
  838. package/src/_stdlib-signatures.json +1 -0
  839. package/src/agent-chain.ts +71 -0
  840. package/src/agent-dsl.fl +168 -0
  841. package/src/agent-example-error-handling.fl +51 -0
  842. package/src/agent-example-sequential.fl +66 -0
  843. package/src/agent-example-state-tracking.fl +70 -0
  844. package/src/agent.ts +393 -0
  845. package/src/align.ts +349 -0
  846. package/src/analogy.ts +78 -0
  847. package/src/ast-helpers.ts +199 -0
  848. package/src/ast.ts +817 -0
  849. package/src/async-runtime.ts +263 -0
  850. package/src/belief.ts +86 -0
  851. package/src/benchmark-self.ts +275 -0
  852. package/src/benchmarks/bench-interpreter.ts +73 -0
  853. package/src/benchmarks/bench-runner.ts +85 -0
  854. package/src/benchmarks/bench-vm.ts +128 -0
  855. package/src/browser-debug-panel.ts +220 -0
  856. package/src/browser-entry.ts +79 -0
  857. package/src/browser-stubs/child-process-stubs.ts +6 -0
  858. package/src/browser-stubs/crypto-stubs.ts +15 -0
  859. package/src/browser-stubs/misc-stubs.ts +4 -0
  860. package/src/browser-stubs/node-stubs.ts +17 -0
  861. package/src/browser-stubs/path-stubs.ts +6 -0
  862. package/src/bytecode.ts +41 -0
  863. package/src/causal.ts +258 -0
  864. package/src/chain-agents.ts +86 -0
  865. package/src/checkpoint.ts +106 -0
  866. package/src/ci-runner.ts +279 -0
  867. package/src/cli.ts +2136 -0
  868. package/src/codegen-js.ts +847 -0
  869. package/src/cognitive.ts +95 -0
  870. package/src/compete.ts +60 -0
  871. package/src/compiler.ts +267 -0
  872. package/src/compose-reason.ts +118 -0
  873. package/src/consensus.ts +109 -0
  874. package/src/context-window.ts +139 -0
  875. package/src/cot.ts +241 -0
  876. package/src/counterfactual.ts +268 -0
  877. package/src/critique.ts +77 -0
  878. package/src/crossover.ts +218 -0
  879. package/src/curiosity.ts +305 -0
  880. package/src/debate.ts +64 -0
  881. package/src/debug-api.ts +92 -0
  882. package/src/debugger.ts +185 -0
  883. package/src/delegate.ts +78 -0
  884. package/src/doc-extractor.ts +255 -0
  885. package/src/doc-renderer.ts +131 -0
  886. package/src/echo-server-demo.fl +17 -0
  887. package/src/error-formatter.ts +369 -0
  888. package/src/error-system.ts +88 -0
  889. package/src/errors.ts +281 -0
  890. package/src/ethics-check.ts +408 -0
  891. package/src/eval-ai-blocks.ts +182 -0
  892. package/src/eval-ai-handlers.ts +132 -0
  893. package/src/eval-builtins-ai.ts +1659 -0
  894. package/src/eval-builtins.ts +5956 -0
  895. package/src/eval-call-function.ts +665 -0
  896. package/src/eval-infra-blocks.ts +450 -0
  897. package/src/eval-module-system.ts +286 -0
  898. package/src/eval-pattern-match.ts +289 -0
  899. package/src/eval-phase150.ts +87 -0
  900. package/src/eval-reasoning-sequence.ts +218 -0
  901. package/src/eval-special-forms.ts +2154 -0
  902. package/src/eval-style-blocks.ts +193 -0
  903. package/src/eval-type-classes.ts +148 -0
  904. package/src/evolve.ts +276 -0
  905. package/src/explain.ts +345 -0
  906. package/src/express-advanced.fl +78 -0
  907. package/src/express-auth.fl +118 -0
  908. package/src/express-cache.fl +118 -0
  909. package/src/express-chat.fl +81 -0
  910. package/src/express-example.fl +67 -0
  911. package/src/express-test.fl +331 -0
  912. package/src/express.fl +92 -0
  913. package/src/fitness.ts +238 -0
  914. package/src/fl-app-demo.fl +19 -0
  915. package/src/fl-files/fl-fmt.fl +29 -0
  916. package/src/fl-files/fl-lint.fl +61 -0
  917. package/src/fl-files/fl-test.fl +52 -0
  918. package/src/fl-http-demo.fl +19 -0
  919. package/src/fl-list-utils.fl +108 -0
  920. package/src/fl-math-lib.fl +14 -0
  921. package/src/fl-sdk.ts +154 -0
  922. package/src/fl-server-demo.fl +74 -0
  923. package/src/fl-str-utils.fl +29 -0
  924. package/src/fl-tutor.ts +126 -0
  925. package/src/formatter.ts +581 -0
  926. package/src/freelang-codegen.fl +904 -0
  927. package/src/freelang-interpreter.fl +483 -0
  928. package/src/freelang-lexer.fl +337 -0
  929. package/src/freelang-parser.fl +349 -0
  930. package/src/freelang-stdlib.fl +246 -0
  931. package/src/freelang-typechecker.fl +422 -0
  932. package/src/freelang-v9-complete.ts +474 -0
  933. package/src/generation.ts +201 -0
  934. package/src/gpt-mini-p3.fl +316 -0
  935. package/src/hot-reload.ts +235 -0
  936. package/src/http-server-runner.ts +89 -0
  937. package/src/hypothesis.ts +62 -0
  938. package/src/immutable.ts +140 -0
  939. package/src/interpreter-context.ts +87 -0
  940. package/src/interpreter-scope.ts +140 -0
  941. package/src/interpreter.ts +2351 -0
  942. package/src/lazy-seq.ts +134 -0
  943. package/src/learned-facts-store.ts +306 -0
  944. package/src/lexer.ts +359 -0
  945. package/src/lint-rules.ts +584 -0
  946. package/src/linter.ts +237 -0
  947. package/src/logger.ts +128 -0
  948. package/src/logging-deterministic.fl +138 -0
  949. package/src/lsp-server.ts +379 -0
  950. package/src/macro-expander.ts +195 -0
  951. package/src/maybe-chain.ts +108 -0
  952. package/src/maybe-type.ts +163 -0
  953. package/src/memory-system.ts +142 -0
  954. package/src/meta-reason.ts +93 -0
  955. package/src/multi-agent-hub.ts +247 -0
  956. package/src/multi-agent.ts +101 -0
  957. package/src/mutate.ts +226 -0
  958. package/src/negotiate.ts +55 -0
  959. package/src/optimizer.ts +277 -0
  960. package/src/orchestrate.ts +154 -0
  961. package/src/package-manager.ts +375 -0
  962. package/src/parser.ts +2722 -0
  963. package/src/peer-review.ts +53 -0
  964. package/src/predict.ts +365 -0
  965. package/src/profiler.ts +150 -0
  966. package/src/prompt-compiler.ts +123 -0
  967. package/src/protocol.ts +114 -0
  968. package/src/prune.ts +195 -0
  969. package/src/quality-loop.ts +105 -0
  970. package/src/rag.ts +81 -0
  971. package/src/reasoning-debugger.ts +122 -0
  972. package/src/refactor-self.ts +362 -0
  973. package/src/reflect.ts +186 -0
  974. package/src/repl.ts +323 -0
  975. package/src/result-type.ts +126 -0
  976. package/src/return-signal.ts +10 -0
  977. package/src/runtime-entry.ts +8 -0
  978. package/src/runtime-helpers.ts +234 -0
  979. package/src/self-evolution-hub.ts +431 -0
  980. package/src/self-improve.ts +107 -0
  981. package/src/source-map.ts +114 -0
  982. package/src/stdlib-agent.js +164 -0
  983. package/src/stdlib-agent.ts +225 -0
  984. package/src/stdlib-ai-native.ts +176 -0
  985. package/src/stdlib-ai-workflow.ts +308 -0
  986. package/src/stdlib-ai.ts +180 -0
  987. package/src/stdlib-async.ts +179 -0
  988. package/src/stdlib-audit.ts +94 -0
  989. package/src/stdlib-auth.ts +196 -0
  990. package/src/stdlib-bits.ts +86 -0
  991. package/src/stdlib-blog.ts +127 -0
  992. package/src/stdlib-browser.ts +239 -0
  993. package/src/stdlib-cache.ts +147 -0
  994. package/src/stdlib-capture-error.ts +183 -0
  995. package/src/stdlib-channel.ts +96 -0
  996. package/src/stdlib-checkpoint.js +109 -0
  997. package/src/stdlib-checkpoint.ts +97 -0
  998. package/src/stdlib-cloud.ts +317 -0
  999. package/src/stdlib-collection.ts +227 -0
  1000. package/src/stdlib-compile.ts +111 -0
  1001. package/src/stdlib-cron.ts +219 -0
  1002. package/src/stdlib-crypto-rsa.ts +82 -0
  1003. package/src/stdlib-crypto.js +203 -0
  1004. package/src/stdlib-crypto.ts +208 -0
  1005. package/src/stdlib-data.ts +614 -0
  1006. package/src/stdlib-db-query.ts +198 -0
  1007. package/src/stdlib-db.ts +185 -0
  1008. package/src/stdlib-distributed.ts +292 -0
  1009. package/src/stdlib-error.ts +90 -0
  1010. package/src/stdlib-fd.ts +130 -0
  1011. package/src/stdlib-feed.ts +171 -0
  1012. package/src/stdlib-file.ts +182 -0
  1013. package/src/stdlib-helpers.ts +273 -0
  1014. package/src/stdlib-http-macro.ts +178 -0
  1015. package/src/stdlib-http-server.ts +1229 -0
  1016. package/src/stdlib-http.ts +405 -0
  1017. package/src/stdlib-image.ts +92 -0
  1018. package/src/stdlib-kebab-aliases.ts +131 -0
  1019. package/src/stdlib-lazy-registry.ts +106 -0
  1020. package/src/stdlib-loader.ts +810 -0
  1021. package/src/stdlib-mail.ts +251 -0
  1022. package/src/stdlib-mariadb.ts +467 -0
  1023. package/src/stdlib-markdown.ts +227 -0
  1024. package/src/stdlib-matrix.ts +170 -0
  1025. package/src/stdlib-middleware.ts +221 -0
  1026. package/src/stdlib-module.ts +178 -0
  1027. package/src/stdlib-mongodb.ts +174 -0
  1028. package/src/stdlib-oci.ts +321 -0
  1029. package/src/stdlib-optional.ts +56 -0
  1030. package/src/stdlib-orm.ts +241 -0
  1031. package/src/stdlib-perf.ts +140 -0
  1032. package/src/stdlib-pg.ts +181 -0
  1033. package/src/stdlib-plot.ts +196 -0
  1034. package/src/stdlib-process.ts +120 -0
  1035. package/src/stdlib-property.ts +157 -0
  1036. package/src/stdlib-pubsub.ts +93 -0
  1037. package/src/stdlib-queue-helpers.ts +92 -0
  1038. package/src/stdlib-registry.ts +78 -0
  1039. package/src/stdlib-resource.ts +553 -0
  1040. package/src/stdlib-rest-crud.ts +146 -0
  1041. package/src/stdlib-service.ts +206 -0
  1042. package/src/stdlib-shell.ts +76 -0
  1043. package/src/stdlib-stats.ts +172 -0
  1044. package/src/stdlib-table.ts +200 -0
  1045. package/src/stdlib-test-enhanced.ts +76 -0
  1046. package/src/stdlib-test.ts +153 -0
  1047. package/src/stdlib-time.js +217 -0
  1048. package/src/stdlib-time.ts +282 -0
  1049. package/src/stdlib-timer.ts +134 -0
  1050. package/src/stdlib-totp.ts +110 -0
  1051. package/src/stdlib-type-predicates.ts +136 -0
  1052. package/src/stdlib-types.ts +107 -0
  1053. package/src/stdlib-validation.ts +248 -0
  1054. package/src/stdlib-verify.ts +181 -0
  1055. package/src/stdlib-webauthn.ts +192 -0
  1056. package/src/stdlib-workflow.js +715 -0
  1057. package/src/stdlib-workflow.ts +950 -0
  1058. package/src/stdlib-ws.ts +333 -0
  1059. package/src/stdlib-wsc.test.ts +122 -0
  1060. package/src/stdlib-wsc.ts +243 -0
  1061. package/src/storage-unified.fl +279 -0
  1062. package/src/streaming.ts +101 -0
  1063. package/src/struct-system.ts +104 -0
  1064. package/src/style-registry.ts +54 -0
  1065. package/src/swarm.ts +89 -0
  1066. package/src/tco.ts +31 -0
  1067. package/src/test-advanced-patterns.ts +211 -0
  1068. package/src/test-ast-debug.ts +20 -0
  1069. package/src/test-ast-helpers.ts +208 -0
  1070. package/src/test-async.ts +406 -0
  1071. package/src/test-bootstrap-self-compile.ts +449 -0
  1072. package/src/test-bootstrap-verification.ts +336 -0
  1073. package/src/test-composition.ts +206 -0
  1074. package/src/test-errors-phase6.ts +166 -0
  1075. package/src/test-extended-monads.ts +313 -0
  1076. package/src/test-field-parsing.ts +135 -0
  1077. package/src/test-first-class-functions.ts +257 -0
  1078. package/src/test-freelang-interpreter.ts +320 -0
  1079. package/src/test-freelang-lexer.ts +306 -0
  1080. package/src/test-freelang-parser.ts +268 -0
  1081. package/src/test-fullstack-core.ts +258 -0
  1082. package/src/test-fullstack-phase7-12.ts +305 -0
  1083. package/src/test-fullstack-practical.ts +338 -0
  1084. package/src/test-integration-stdlib.ts +195 -0
  1085. package/src/test-interpreter-phase6.ts +305 -0
  1086. package/src/test-lexer-comparison.ts +108 -0
  1087. package/src/test-lexer-phase6.ts +271 -0
  1088. package/src/test-modules.ts +325 -0
  1089. package/src/test-monad-laws.ts +383 -0
  1090. package/src/test-monads.ts +197 -0
  1091. package/src/test-p0-checkpoint.ts +304 -0
  1092. package/src/test-p0-conditional.ts +284 -0
  1093. package/src/test-p0-error-handling.ts +231 -0
  1094. package/src/test-p0-error-messages.ts +220 -0
  1095. package/src/test-p1-1-parallel-tasks.js +214 -0
  1096. package/src/test-parser-phase6.ts +222 -0
  1097. package/src/test-performance.ts +206 -0
  1098. package/src/test-phase10-data.ts +259 -0
  1099. package/src/test-phase10-file.ts +216 -0
  1100. package/src/test-phase100-stdlib-ai.ts +343 -0
  1101. package/src/test-phase101-memory.ts +309 -0
  1102. package/src/test-phase102-rag.ts +296 -0
  1103. package/src/test-phase103-multi-agent.ts +418 -0
  1104. package/src/test-phase104-try-reason.ts +459 -0
  1105. package/src/test-phase105-streaming.ts +287 -0
  1106. package/src/test-phase106-quality.ts +397 -0
  1107. package/src/test-phase107-tutor.ts +305 -0
  1108. package/src/test-phase108-debugger.ts +316 -0
  1109. package/src/test-phase109-prompt-compiler.ts +333 -0
  1110. package/src/test-phase11-12-complete.ts +275 -0
  1111. package/src/test-phase11-error.ts +192 -0
  1112. package/src/test-phase110-sdk.ts +320 -0
  1113. package/src/test-phase111-hypothesis.ts +380 -0
  1114. package/src/test-phase112-maybe-chain.ts +313 -0
  1115. package/src/test-phase113-debate.ts +364 -0
  1116. package/src/test-phase114-checkpoint.ts +348 -0
  1117. package/src/test-phase115-meta-reason.ts +277 -0
  1118. package/src/test-phase116-belief.ts +275 -0
  1119. package/src/test-phase117-analogy.ts +325 -0
  1120. package/src/test-phase118-critique.ts +308 -0
  1121. package/src/test-phase119-compose.ts +434 -0
  1122. package/src/test-phase12-http-shell.ts +120 -0
  1123. package/src/test-phase120-cognitive.ts +297 -0
  1124. package/src/test-phase121-consensus.ts +404 -0
  1125. package/src/test-phase122-delegate.ts +411 -0
  1126. package/src/test-phase123-vote.ts +339 -0
  1127. package/src/test-phase124-negotiate.ts +403 -0
  1128. package/src/test-phase125-swarm.ts +321 -0
  1129. package/src/test-phase126-orchestrate.ts +343 -0
  1130. package/src/test-phase127-peer-review.ts +279 -0
  1131. package/src/test-phase128-chain-agents.ts +456 -0
  1132. package/src/test-phase129-compete.ts +256 -0
  1133. package/src/test-phase13-data.ts +223 -0
  1134. package/src/test-phase130-hub.ts +390 -0
  1135. package/src/test-phase131-evolve.ts +536 -0
  1136. package/src/test-phase132-mutate.ts +268 -0
  1137. package/src/test-phase133-crossover.ts +289 -0
  1138. package/src/test-phase134-fitness.ts +306 -0
  1139. package/src/test-phase135-generation.ts +328 -0
  1140. package/src/test-phase136-prune.ts +228 -0
  1141. package/src/test-phase137-refactor-self.ts +354 -0
  1142. package/src/test-phase138-benchmark-self.ts +325 -0
  1143. package/src/test-phase139-version-self.ts +278 -0
  1144. package/src/test-phase14-collection.ts +254 -0
  1145. package/src/test-phase140-self-evolution.ts +410 -0
  1146. package/src/test-phase141-world-model.ts +387 -0
  1147. package/src/test-phase142-causal.ts +384 -0
  1148. package/src/test-phase143-counterfactual.ts +280 -0
  1149. package/src/test-phase144-predict.ts +312 -0
  1150. package/src/test-phase145-explain.ts +287 -0
  1151. package/src/test-phase146-align.ts +439 -0
  1152. package/src/test-phase147-ethics-check.ts +399 -0
  1153. package/src/test-phase148-curiosity.ts +247 -0
  1154. package/src/test-phase149-wisdom.ts +758 -0
  1155. package/src/test-phase15-agent.ts +320 -0
  1156. package/src/test-phase150-complete.ts +481 -0
  1157. package/src/test-phase16-time.ts +292 -0
  1158. package/src/test-phase17-crypto.ts +312 -0
  1159. package/src/test-phase18-integration.ts +429 -0
  1160. package/src/test-phase19-resource.ts +214 -0
  1161. package/src/test-phase20-server-db.ts +160 -0
  1162. package/src/test-phase21-ws-auth-cache-pubsub.ts +212 -0
  1163. package/src/test-phase22-process.ts +166 -0
  1164. package/src/test-phase23-selfhosting.ts +383 -0
  1165. package/src/test-phase24-codegen.ts +236 -0
  1166. package/src/test-phase25-bootstrap.ts +227 -0
  1167. package/src/test-phase26-map-filter-reduce.ts +282 -0
  1168. package/src/test-phase27-stdlib-codegen.ts +325 -0
  1169. package/src/test-phase28-loop-recur.ts +182 -0
  1170. package/src/test-phase29-import.ts +165 -0
  1171. package/src/test-phase3-web-server.ts +234 -0
  1172. package/src/test-phase30-selfcompile.ts +254 -0
  1173. package/src/test-phase31-gen2-lexer.ts +251 -0
  1174. package/src/test-phase33-gen3-bootstrap.ts +323 -0
  1175. package/src/test-phase34-parser-tco.ts +268 -0
  1176. package/src/test-phase35-error-messages.ts +280 -0
  1177. package/src/test-phase36-sourcemap.ts +240 -0
  1178. package/src/test-phase37-variadic.ts +228 -0
  1179. package/src/test-phase38-destructuring.ts +261 -0
  1180. package/src/test-phase39-do-block.ts +288 -0
  1181. package/src/test-phase40-const-fold.ts +249 -0
  1182. package/src/test-phase41-repl.ts +312 -0
  1183. package/src/test-phase42-watch.ts +314 -0
  1184. package/src/test-phase43-format.ts +377 -0
  1185. package/src/test-phase44-check.ts +505 -0
  1186. package/src/test-phase45-interpreter.ts +367 -0
  1187. package/src/test-phase46-match.ts +390 -0
  1188. package/src/test-phase47-file-io.ts +338 -0
  1189. package/src/test-phase48-types.ts +308 -0
  1190. package/src/test-phase49-stdlib.ts +365 -0
  1191. package/src/test-phase5-week1.ts +160 -0
  1192. package/src/test-phase50-fl-server.ts +159 -0
  1193. package/src/test-phase51-transformer.ts +152 -0
  1194. package/src/test-phase52-import.ts +161 -0
  1195. package/src/test-phase53-training.ts +122 -0
  1196. package/src/test-phase54-fl-utils.ts +122 -0
  1197. package/src/test-phase55-http-client.ts +182 -0
  1198. package/src/test-phase56-lexical-scope.ts +230 -0
  1199. package/src/test-phase58-module-refactor.ts +298 -0
  1200. package/src/test-phase59-errors.ts +226 -0
  1201. package/src/test-phase6-compile.ts +227 -0
  1202. package/src/test-phase60-types.ts +457 -0
  1203. package/src/test-phase61-tco.ts +209 -0
  1204. package/src/test-phase63-macros.ts +191 -0
  1205. package/src/test-phase64-protocols.ts +451 -0
  1206. package/src/test-phase65-patterns.ts +301 -0
  1207. package/src/test-phase66-structs.ts +215 -0
  1208. package/src/test-phase67-concurrency.ts +348 -0
  1209. package/src/test-phase68-pipeline.ts +209 -0
  1210. package/src/test-phase69-lazy.ts +237 -0
  1211. package/src/test-phase7-registry.ts +236 -0
  1212. package/src/test-phase70-immutable.ts +488 -0
  1213. package/src/test-phase71-ai-native.ts +252 -0
  1214. package/src/test-phase72-integration.ts +533 -0
  1215. package/src/test-phase73-formatter.ts +361 -0
  1216. package/src/test-phase74-linter.ts +565 -0
  1217. package/src/test-phase75-repl.ts +227 -0
  1218. package/src/test-phase76-testrunner.ts +439 -0
  1219. package/src/test-phase77-doc.ts +416 -0
  1220. package/src/test-phase78-debugger.ts +370 -0
  1221. package/src/test-phase79-watch.ts +224 -0
  1222. package/src/test-phase8-oci.ts +264 -0
  1223. package/src/test-phase80-ci.ts +282 -0
  1224. package/src/test-phase81-pkg.ts +383 -0
  1225. package/src/test-phase82-profiler.ts +336 -0
  1226. package/src/test-phase83-vm.ts +318 -0
  1227. package/src/test-phase84-optimizer.ts +424 -0
  1228. package/src/test-phase85-codegen.ts +380 -0
  1229. package/src/test-phase86-lsp.ts +533 -0
  1230. package/src/test-phase87-packages.ts +277 -0
  1231. package/src/test-phase88-selfhost.ts +412 -0
  1232. package/src/test-phase89-bench.ts +361 -0
  1233. package/src/test-phase9-flnext-v2.ts +372 -0
  1234. package/src/test-phase9-learn.ts +241 -0
  1235. package/src/test-phase9-reasoning.ts +312 -0
  1236. package/src/test-phase9-search.ts +212 -0
  1237. package/src/test-phase90-release.ts +365 -0
  1238. package/src/test-phase91-maybe.ts +257 -0
  1239. package/src/test-phase92-cot.ts +438 -0
  1240. package/src/test-phase93-tot.ts +462 -0
  1241. package/src/test-phase94-reflect.ts +498 -0
  1242. package/src/test-phase95-context.ts +268 -0
  1243. package/src/test-phase96-errors.ts +296 -0
  1244. package/src/test-phase97-tools.ts +344 -0
  1245. package/src/test-phase98-agent.ts +370 -0
  1246. package/src/test-phase99-self-improve.ts +394 -0
  1247. package/src/test-phase9a-websearch.ts +283 -0
  1248. package/src/test-phase9ab-integration.ts +140 -0
  1249. package/src/test-phase9b-persistence.ts +448 -0
  1250. package/src/test-phase9c-conditional.ts +251 -0
  1251. package/src/test-phase9c-extension.ts +270 -0
  1252. package/src/test-phase9c-feedback.ts +263 -0
  1253. package/src/test-phase9c-loop.ts +239 -0
  1254. package/src/test-selfhosting-sh1.ts +41 -0
  1255. package/src/test-selfhosting-sh2.ts +84 -0
  1256. package/src/test-selfhosting-sh3.ts +61 -0
  1257. package/src/test-selfhosting-sh4.ts +65 -0
  1258. package/src/test-type-classes-dispatch.ts +202 -0
  1259. package/src/test-type-classes.ts +320 -0
  1260. package/src/test-type-inference.ts +464 -0
  1261. package/src/test-typeclass-parsing-final.ts +218 -0
  1262. package/src/test-typeclass-parsing.ts +264 -0
  1263. package/src/todo-server-30116.ts +53 -0
  1264. package/src/token.ts +130 -0
  1265. package/src/tool-registry.ts +195 -0
  1266. package/src/tot.ts +258 -0
  1267. package/src/try-reason.ts +109 -0
  1268. package/src/type-check-static.ts +417 -0
  1269. package/src/type-checker.ts +245 -0
  1270. package/src/type-inference.ts +271 -0
  1271. package/src/type-system.ts +169 -0
  1272. package/src/version-self.ts +219 -0
  1273. package/src/vm-eligible.ts +106 -0
  1274. package/src/vm.ts +219 -0
  1275. package/src/vote.ts +127 -0
  1276. package/src/vpm/checksum-test.fl +193 -0
  1277. package/src/vpm/checksum.fl +219 -0
  1278. package/src/vpm/error-test.fl +211 -0
  1279. package/src/vpm/error.fl +218 -0
  1280. package/src/vpm/lock-file.fl +380 -0
  1281. package/src/vpm/logging-test.fl +194 -0
  1282. package/src/vpm/logging.fl +294 -0
  1283. package/src/vpm/resolver-test.fl +117 -0
  1284. package/src/vpm/resolver.fl +618 -0
  1285. package/src/vpm/semver-test.fl +180 -0
  1286. package/src/vpm/semver.fl +143 -0
  1287. package/src/vpm-cli.ts +1955 -0
  1288. package/src/web/app-router.ts +286 -0
  1289. package/src/web/fl-executor.ts +655 -0
  1290. package/src/web/image-optimizer.ts +206 -0
  1291. package/src/web/index.ts +14 -0
  1292. package/src/web/page-renderer.ts +287 -0
  1293. package/src/web/server.ts +553 -0
  1294. package/src/web-search-adapter.ts +348 -0
  1295. package/src/wisdom.ts +441 -0
  1296. package/src/world-model.ts +348 -0
  1297. package/stdlib/cache.fl +42 -0
  1298. package/stdlib/csv.fl +38 -0
  1299. package/stdlib/date-ext.fl +68 -0
  1300. package/stdlib/log.fl +44 -0
  1301. package/stdlib/math-ext.fl +57 -0
  1302. package/stdlib/number-ext.fl +47 -0
  1303. package/stdlib/queue.fl +57 -0
  1304. package/stdlib/string-ext.fl +45 -0
  1305. package/stdlib/validate.fl +123 -0
  1306. package/stdlib/web/components.fl +125 -0
  1307. package/stdlib/web/csrf.fl +61 -0
  1308. package/stdlib/web/format.fl +75 -0
  1309. package/stdlib/web/forms.fl +94 -0
  1310. package/stdlib/web/image.fl +77 -0
  1311. package/stdlib/web/metadata.fl +85 -0
  1312. package/stdlib/web/pagination.fl +62 -0
  1313. package/stdlib/web/state.fl +167 -0
  1314. package/stdlib/web/styles.fl +68 -0
  1315. package/stdlib/web/toast.fl +62 -0
  1316. package/stdlib/web/v9-stdlib-dom.fl +92 -0
  1317. package/stdlib/web/v9-stdlib-fetch.fl +90 -0
  1318. package/stdlib/web/v9-stdlib-storage.fl +70 -0
  1319. package/stdlib/web/v9-stdlib-ui.fl +115 -0
  1320. package/stdlib/web/ws-client.fl +125 -0
  1321. package/tests/.v11-backup/test-migrate-sample.fl +22 -0
  1322. package/tests/PHASE-C-VERIFICATION-REPORT.md +125 -0
  1323. package/tests/benchmark-v11.1.js +103 -0
  1324. package/tests/evidence/01-about.html +1 -0
  1325. package/tests/evidence/02-post-hello.html +1 -0
  1326. package/tests/evidence/02-post-world.html +1 -0
  1327. package/tests/evidence/03-home.html +1 -0
  1328. package/tests/evidence/04-dist/404.html +1 -0
  1329. package/tests/evidence/04-dist/about/index.html +1 -0
  1330. package/tests/evidence/04-dist/index.html +1 -0
  1331. package/tests/evidence/04-dist/post/hello/index.html +1 -0
  1332. package/tests/evidence/04-dist/post/world/index.html +1 -0
  1333. package/tests/evidence/05-dist/404.html +1 -0
  1334. package/tests/evidence/05-dist/about/index.html +1 -0
  1335. package/tests/evidence/05-dist/index.html +1 -0
  1336. package/tests/evidence/05-dist/post/hello/index.html +1 -0
  1337. package/tests/evidence/05-dist/post/world/index.html +1 -0
  1338. package/tests/evidence/06-dist/404.html +1 -0
  1339. package/tests/evidence/06-dist/about/index.html +1 -0
  1340. package/tests/evidence/06-dist/index.html +1 -0
  1341. package/tests/evidence/06-dist/post/hello/index.html +1 -0
  1342. package/tests/evidence/06-dist/post/world/index.html +1 -0
  1343. package/tests/evidence/07-markdown.html +1 -0
  1344. package/tests/evidence/08-rss.xml +25 -0
  1345. package/tests/evidence/09-robots.txt +4 -0
  1346. package/tests/evidence/09-sitemap.xml +12 -0
  1347. package/tests/evidence/10-jsonld.html +1 -0
  1348. package/tests/evidence/_results.txt +11 -0
  1349. package/tests/evidence/about.html +1 -0
  1350. package/tests/evidence/home.html +1 -0
  1351. package/tests/evidence/missing.html +42 -0
  1352. package/tests/evidence/post-hello.html +1 -0
  1353. package/tests/evidence/post-world.html +1 -0
  1354. package/tests/fixtures/basic-app/about/page.fl +1 -0
  1355. package/tests/fixtures/basic-app/api/echo/route.fl +5 -0
  1356. package/tests/fixtures/basic-app/layout.fl +1 -0
  1357. package/tests/fixtures/basic-app/not-found.fl +1 -0
  1358. package/tests/fixtures/basic-app/page.fl +1 -0
  1359. package/tests/fixtures/basic-app/post/[slug]/generate-static-params.fl +1 -0
  1360. package/tests/fixtures/basic-app/post/[slug]/page.fl +1 -0
  1361. package/tests/fixtures/stdlib-probes/blog.fl +6 -0
  1362. package/tests/fixtures/stdlib-probes/jsonld.fl +1 -0
  1363. package/tests/fixtures/stdlib-probes/map-probe.fl +3 -0
  1364. package/tests/fixtures/stdlib-probes/map-shape.fl +2 -0
  1365. package/tests/fixtures/stdlib-probes/md.fl +1 -0
  1366. package/tests/fixtures/stdlib-probes/robots.fl +1 -0
  1367. package/tests/fixtures/stdlib-probes/rss.fl +4 -0
  1368. package/tests/fixtures/stdlib-probes/sitemap.fl +1 -0
  1369. package/tests/l2/case-01-arithmetic.fl +6 -0
  1370. package/tests/l2/case-02-comparisons.fl +15 -0
  1371. package/tests/l2/case-03-logic.fl +15 -0
  1372. package/tests/l2/case-04-control-flow.fl +15 -0
  1373. package/tests/l2/case-05-functions.fl +13 -0
  1374. package/tests/l2/case-06-collections.fl +14 -0
  1375. package/tests/l2/case-07-pattern-matching.fl +14 -0
  1376. package/tests/l2/case-08-recursion.fl +19 -0
  1377. package/tests/l2/case-09-strings.fl +13 -0
  1378. package/tests/l2/case-10-loops.fl +17 -0
  1379. package/tests/l2/case-11-higher-order.fl +13 -0
  1380. package/tests/l2/case-12-edge-cases.fl +14 -0
  1381. package/tests/l2/case-13-ai-vector.fl +22 -0
  1382. package/tests/l2/case-14-ai-cosine.fl +25 -0
  1383. package/tests/l2/case-15-ai-template.fl +22 -0
  1384. package/tests/l2/case-16-ai-ranking.fl +20 -0
  1385. package/tests/l2/case-17-stdlib-extended.fl +32 -0
  1386. package/tests/l2-proof/01-arithmetic.bootstrap.js +141 -0
  1387. package/tests/l2-proof/01-arithmetic.fl +15 -0
  1388. package/tests/l2-proof/01-arithmetic.stage1.js +141 -0
  1389. package/tests/l2-proof/02-comparisons.bootstrap.js +141 -0
  1390. package/tests/l2-proof/02-comparisons.fl +17 -0
  1391. package/tests/l2-proof/03-logic.bootstrap.js +141 -0
  1392. package/tests/l2-proof/03-logic.fl +15 -0
  1393. package/tests/l2-proof/04-control-flow.bootstrap.js +146 -0
  1394. package/tests/l2-proof/04-control-flow.fl +24 -0
  1395. package/tests/l2-proof/05-functions.bootstrap.js +143 -0
  1396. package/tests/l2-proof/05-functions.fl +16 -0
  1397. package/tests/l2-proof/06-collections.bootstrap.js +146 -0
  1398. package/tests/l2-proof/06-collections.fl +27 -0
  1399. package/tests/l2-proof/07-pattern-matching.bootstrap.js +142 -0
  1400. package/tests/l2-proof/07-pattern-matching.fl +23 -0
  1401. package/tests/l2-proof/08-async-errors.bootstrap.js +142 -0
  1402. package/tests/l2-proof/08-async-errors.fl +17 -0
  1403. package/tests/l2-proof/09-strings.bootstrap.js +141 -0
  1404. package/tests/l2-proof/09-strings.fl +13 -0
  1405. package/tests/l2-proof/10-type-checks.bootstrap.js +141 -0
  1406. package/tests/l2-proof/10-type-checks.fl +17 -0
  1407. package/tests/l2-proof/11-recursion.bootstrap.js +143 -0
  1408. package/tests/l2-proof/11-recursion.fl +21 -0
  1409. package/tests/l2-proof/12-edge-cases.bootstrap.js +141 -0
  1410. package/tests/l2-proof/12-edge-cases.fl +17 -0
  1411. package/tests/parity/01-app-router-static.sh +18 -0
  1412. package/tests/parity/02-app-router-dynamic.sh +18 -0
  1413. package/tests/parity/03-layout-children.sh +17 -0
  1414. package/tests/parity/04-not-found.sh +22 -0
  1415. package/tests/parity/05-ssg.sh +21 -0
  1416. package/tests/parity/06-parallel-render.sh +21 -0
  1417. package/tests/parity/07-markdown.sh +16 -0
  1418. package/tests/parity/08-rss-atom.sh +18 -0
  1419. package/tests/parity/09-sitemap-robots.sh +23 -0
  1420. package/tests/parity/10-jsonld.sh +16 -0
  1421. package/tests/parity/11-blog-helpers.sh +28 -0
  1422. package/tests/parity/12-api-routes.sh +25 -0
  1423. package/tests/parity/_lib.sh +53 -0
  1424. package/tests/parity/run-all.sh +89 -0
  1425. package/tests/parity/score.sh +20 -0
  1426. package/tests/phase-c-fuzzing.fl +89 -0
  1427. package/tests/phase-c-property-testing.fl +137 -0
  1428. package/tests/phase-c-sha-verification.fl +117 -0
  1429. package/tests/phase-c-validation.fl +194 -0
  1430. package/tests/property-testing.sh +47 -0
  1431. package/tests/regen/let-in-expr-01.fl +5 -0
  1432. package/tests/regen/let-in-expr-02.fl +6 -0
  1433. package/tests/regen/let-in-expr-03.fl +4 -0
  1434. package/tests/regen/let-in-expr-04.fl +6 -0
  1435. package/tests/regen/let-in-expr-05.fl +5 -0
  1436. package/tests/test-ai-library.fl +36 -0
  1437. package/tests/test-andor.fl +2 -0
  1438. package/tests/test-bootstrap-match.fl +5 -0
  1439. package/tests/test-cg-final.fl +5 -0
  1440. package/tests/test-cli.fl +19 -0
  1441. package/tests/test-codegen.fl +4 -0
  1442. package/tests/test-cond-flat.fl +1 -0
  1443. package/tests/test-fl-exec-op.fl +1 -0
  1444. package/tests/test-fp.fl +10 -0
  1445. package/tests/test-funcs.fl +11 -0
  1446. package/tests/test-fuzz-crash.fl +3 -0
  1447. package/tests/test-http-get.fl +3 -0
  1448. package/tests/test-json-load.fl +32 -0
  1449. package/tests/test-let-flat.fl +2 -0
  1450. package/tests/test-let-order.fl +3 -0
  1451. package/tests/test-let-simple.fl +3 -0
  1452. package/tests/test-let-syntax.fl +2 -0
  1453. package/tests/test-let.fl +3 -0
  1454. package/tests/test-lex-debug.fl +75 -0
  1455. package/tests/test-loop-bug.fl +5 -0
  1456. package/tests/test-map-entries.fl +1 -0
  1457. package/tests/test-map-pattern.fl +3 -0
  1458. package/tests/test-match-syntax.fl +5 -0
  1459. package/tests/test-migrate-sample.fl +22 -0
  1460. package/tests/test-neg.fl +1 -0
  1461. package/tests/test-nested-let.fl +4 -0
  1462. package/tests/test-node-to-pattern.fl +8 -0
  1463. package/tests/test-quant-lib.fl +114 -0
  1464. package/tests/test-reduce.fl +10 -0
  1465. package/tests/test-server.fl +3 -0
  1466. package/tests/test-simple-map.fl +4 -0
  1467. package/tests/test-simple-match.fl +3 -0
  1468. package/tests/test-simple.fl +1 -0
  1469. package/tests/test-try-bootstrap.fl +7 -0
  1470. package/tests/test-try-catch.fl +3 -0
  1471. package/tests/test-watchdog-lib.fl +69 -0
  1472. package/tests/test-which-lex.fl +4 -0
  1473. package/tsconfig.json +39 -0
package/bootstrap.js ADDED
@@ -0,0 +1,1134 @@
1
+ #!/usr/bin/env node
2
+ var Cp=Object.create;var Gr=Object.defineProperty;var Np=Object.getOwnPropertyDescriptor;var Op=Object.getOwnPropertyNames;var Fp=Object.getPrototypeOf,Pp=Object.prototype.hasOwnProperty;var gt=(r,t)=>()=>(r&&(t=r(r=0)),t);var jp=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),on=(r,t)=>{for(var e in t)Gr(r,e,{get:t[e],enumerable:!0})},co=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Op(t))!Pp.call(r,s)&&s!==e&&Gr(r,s,{get:()=>t[s],enumerable:!(n=Np(t,s))||n.enumerable});return r};var z=(r,t,e)=>(e=r!=null?Cp(Fp(r)):{},co(t||!r||!r.__esModule?Gr(e,"default",{value:r,enumerable:!0}):e,r)),_e=r=>co(Gr({},"__esModule",{value:!0}),r);var da=gt(()=>{});var cn={};on(cn,{lex:()=>W});function Bp(r){return Lp.get(r)??null}function W(r){let t=[],e=0,n=1,s=1;for(;e<r.length;){let a=r[e];if(/\s/.test(a)){a===`
3
+ `?(n++,s=1):s++,e++;continue}if(a===";"){for(;e<r.length&&r[e]!==`
4
+ `;)e++;continue}if(a==='"'&&r[e+1]==='"'&&r[e+2]==='"'){let i=s;e+=3,s+=3;let o="";for(;e<r.length;){if(r[e]==='"'&&r[e+1]==='"'&&r[e+2]==='"'){e+=3,s+=3;break}r[e]===`
5
+ `?(n++,s=1):s++,o+=r[e],e++}t.push({type:"String",value:o,line:n,col:i});continue}if(a==='"'){let i=e,o=s;e++,s++;let u="";for(;e<r.length&&r[e]!=='"';)if(r[e]==="\\"&&e+1<r.length){e++,s++;let f=r[e];switch(f){case"n":u+=`
6
+ `;break;case"t":u+=" ";break;case"r":u+="\r";break;case"\\":u+="\\";break;case'"':u+='"';break;default:u+=f}e++,s++}else r[e]===`
7
+ `?(n++,s=1):s++,u+=r[e],e++;if(e>=r.length)throw new Error(`Unterminated string at line ${n}, col ${o}`);e++,s++,t.push({type:"String",value:u,line:n,col:o});continue}if(a==="["){t.push({type:"LBracket",value:"[",line:n,col:s}),e++,s++;continue}if(a==="]"){t.push({type:"RBracket",value:"]",line:n,col:s}),e++,s++;continue}if(a==="("){t.push({type:"LParen",value:"(",line:n,col:s}),e++,s++;continue}if(a===")"){t.push({type:"RParen",value:")",line:n,col:s}),e++,s++;continue}if(a==="{"){t.push({type:"LBrace",value:"{",line:n,col:s}),e++,s++;continue}if(a==="}"){t.push({type:"RBrace",value:"}",line:n,col:s}),e++,s++;continue}if(a==="|"){let i=s;e+1<r.length&&r[e+1]===">"?(t.push({type:"Symbol",value:"|>",line:n,col:i}),e+=2,s+=2):(t.push({type:"Symbol",value:"|",line:n,col:i}),e++,s++);continue}if(a===":"){let i=s;t.push({type:"Colon",value:":",line:n,col:i}),e++,s++;continue}if(a==="^"){let i=s;e++,s++;let o="";for(;e<r.length&&/[a-zA-Z0-9_\-?]/.test(r[e]);)o+=r[e],e++,s++;t.push({type:"Symbol",value:"^"+o,line:n,col:i});continue}if(a==="@"){let i=s;e++,s++;let o="";for(;e<r.length&&/[a-zA-Z0-9_\-?!]/.test(r[e]);)o+=r[e],e++,s++;if(o.length===0)throw new Error(`Expected atom name after @ at line ${n}, col ${i}`);t.push({type:"LParen",value:"(",line:n,col:i}),t.push({type:"Symbol",value:"deref",line:n,col:i}),t.push({type:"Symbol",value:o,line:n,col:i}),t.push({type:"RParen",value:")",line:n,col:i});continue}if(a==="$"){let i=e,o=s;e++,s++;let u="";for(;e<r.length&&/[a-zA-Z0-9_\-?]/.test(r[e]);)u+=r[e],e++,s++;if(u.length===0)throw new Error(`Expected variable name after $ at line ${n}, col ${o}`);t.push({type:"Variable",value:u,line:n,col:o});continue}if(/\d/.test(a)||a==="-"&&e+1<r.length&&/\d/.test(r[e+1])){let i=e,o=s;for(a==="-"&&(e++,s++);e<r.length&&/[\d.]/.test(r[e]);)e++,s++;let u=r.slice(i,e);t.push({type:"Number",value:u,line:n,col:o});continue}if(/[a-zA-Z_<>=!+\-*&/%?]/.test(a)){let i=e,o=s;for(;e<r.length&&/[a-zA-Z0-9_<>=!+\-*/?&.%]/.test(r[e]);)e++,s++;let u=r.slice(i,e),l=Bp(u)??"Symbol";t.push({type:l,value:u,line:n,col:o});continue}throw new Error(`Unexpected character '${a}' at line ${n}, col ${s}`)}return t.push({type:"EOF",value:"",line:n,col:s}),t}var Lp,be=gt(()=>{da();Lp=new Map([["MODULE","Module"],["TYPECLASS","TypeClass"],["INSTANCE","Instance"],["open","Open"],["search","Search"],["fetch","Fetch"],["learn","Learn"],["recall","Recall"],["remember","Remember"],["forget","Forget"],["observe","Observe"],["analyze","Analyze"],["decide","Decide"],["act","Act"],["verify","Verify"],["if","If"],["when","When"],["then","Then"],["else","Else"],["repeat","Repeat"],["until","Until"],["while","While"],["PAGE","Page"],["API","Api"],["ROUTE","Route"],["COMPONENT","Component"],["FORM","Form"],["STATE","State"],["COMPUTED","Computed"],["WATCH","Watch"],["METHOD","Method"],["RENDER","Render"],["HANDLER","Handler"],["VALIDATION","Validation"],["LAYOUT","Layout"],["MIDDLEWARE","Middleware"],["SUSPENSE","Suspense"],["SLOT","Slot"],["METADATA","Metadata"],["SERVICE","Service"],["CONTROLLER","Controller"],["GUARD","Guard"],["PIPE","Pipe"],["MODEL","Model"],["QUERY","Query"],["MIGRATION","Migration"],["REPOSITORY","Repository"],["DATABASE","Database"],["CACHE","Cache"],["CACHED","Cached"],["KAFKA","Kafka"],["PRODUCER","Producer"],["CONSUMER","Consumer"],["QUEUE","Queue"],["RABBITMQ","RabbitMQ"],["JWT","JWT"],["OAUTH","OAuth"],["DOCKERFILE","Dockerfile"],["DOCKER-COMPOSE","DockerCompose"],["K8S-DEPLOYMENT","K8sDeployment"],["K8S-SERVICE","K8sService"],["K8S-INGRESS","K8sIngress"],["AWS","AWS"],["AWS-S3","AwsS3"],["AWS-LAMBDA","AwsLambda"],["AWS-RDS","AwsRds"],["AWS-SQS","AwsSqs"],["GCP","GCP"],["GCP-CLOUD-RUN","GcpCloudRun"],["GCP-BIGQUERY","GcpBigquery"],["AZURE","Azure"],["AZURE-FUNCTION","AzureFunction"],["AZURE-COSMOS","AzureCosmos"]])});function He(r,t,e){return{kind:"literal",type:r,value:t,line:e}}function lo(r,t){return{kind:"template-string",value:r,line:t}}function uo(r,t){return{kind:"variable",name:r,line:t}}function ln(r,t,e){return{kind:"sexpr",op:r,args:t,line:e}}function po(r){return{kind:"keyword",name:r}}function ht(r,t,e,n){return{kind:"block",type:r,name:t,fields:e,line:n}}function Jn(r,t,e,n){return{kind:"type",name:r,generic:t,union:e,optional:n}}function ga(r,t){return{kind:"literal-pattern",type:r,value:t}}function Xn(r){return{kind:"variable-pattern",name:r}}function fo(){return{kind:"wildcard-pattern"}}function mo(r,t){return{kind:"list-pattern",elements:r,restElement:t}}function ha(r,t){return{kind:"struct-pattern",fields:r,asBinding:t}}function go(r,t){return{kind:"range-pattern",min:r,max:t}}function ho(r){return{kind:"or-pattern",alternatives:r}}function yo(r,t,e){return{pattern:r,guard:e,body:t}}function bo(r,t,e){return{kind:"pattern-match",value:r,cases:t,defaultCase:e}}function ko(r,t,e,n){return{kind:"import",moduleName:r,source:t,selective:e,alias:n}}function vo(r,t){return{kind:"open",moduleName:r,source:t}}function wo(r,t,e){return{kind:"try-block",body:r,catchClauses:t,finallyBlock:e}}function _o(r,t,e){return{kind:"catch-clause",pattern:t,variable:e,handler:r}}function So(r){return{kind:"throw",argument:r}}function xo(r,t,e,n,s,a){return{kind:"page",name:r,title:t,route:e,component:n,metadata:s,line:a}}function Ao(r,t,e,n,s,a,i){return{kind:"route",name:r,path:t,method:e,handler:n,middleware:s,validation:a,line:i}}function $o(r,t,e,n,s,a,i,o){return{kind:"component",name:r,render:t,state:e,computed:n,watch:s,methods:a,slots:i,line:o}}function Eo(r,t,e,n,s,a){return{kind:"form",name:r,fields:t,validation:e,submit:n,handlers:s,line:a}}function Lt(r){return r&&r.kind==="block"}function Mo(r){return r&&r.kind==="literal"}function ya(r){return Lt(r)&&r.type==="FUNC"}function Ro(r){return r&&r.kind==="variable"}function To(r){return r&&r.kind==="module"}function Co(r){return r&&r.kind==="import"}function No(r){return r&&r.kind==="open"}function Oo(r){return r&&r.kind==="search-block"}function Fo(r){return r&&r.kind==="learn-block"}function Po(r){return r&&r.kind==="reasoning-block"}function jo(r){return r&&r.kind==="reasoning-sequence"}function Yn(r){return Dp.includes(r.type)}var Dp,un=gt(()=>{Dp=["FUNC","SERVER","ROUTE","INTENT","MIDDLEWARE","WEBSOCKET","ERROR-HANDLER","TYPECLASS","INSTANCE","MODULE"]});var fn={};on(fn,{Parser:()=>Kr,ParserError:()=>pn,parse:()=>H});function H(r){return new Kr(r).parse()}var pn,qp,Kr,ke=gt(()=>{da();un();pn=class extends Error{constructor(e,n,s,a,i,o="parse"){let u=i?`[${i}]`:"",f=`[${n}:${s}]`,l=a?`
8
+ \uD78C\uD2B8: ${a}`:"";super(`${u} ${f} ${e}${l}`);this.line=n;this.col=s;this.hint=a;this.code=i;this.stage=o}toJSON(){return{code:this.code||"E_PARSE_SYNTAX_ERROR",stage:this.stage,message:this.message,file:void 0,line:this.line,column:this.col,symbol:void 0,cause:void 0,hint:this.hint}}},qp={"Expected RParen, got Symbol":"\uAD04\uD638\uAC00 \uB2EB\uD788\uC9C0 \uC54A\uC558\uAC70\uB098 \uC640\uC77C\uB4DC\uCE74\uB4DC \uD328\uD134\uC5D0 \uAD04\uD638\uAC00 \uD544\uC694\uD569\uB2C8\uB2E4: _ expr \u2192 (_ expr)","Expected RParen, got EOF":"\uAD04\uD638\uAC00 \uB2EB\uD788\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4. \uC5EC\uB294 ( \uC640 \uB2EB\uB294 ) \uC218\uB97C \uD655\uC778\uD558\uC138\uC694.","Expected operator":"S-expression\uC758 \uCCAB \uC694\uC18C\uB294 \uD568\uC218\uBA85\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4: (\uD568\uC218\uBA85 \uC778\uC790...)","Expected ':' keyword in map literal":"\uB9F5 \uB9AC\uD130\uB7F4\uC758 \uD0A4\uB294 :\uC73C\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4: {:key value}","Unexpected token: Colon":"\uCF5C\uB860 \uD0A4\uC6CC\uB4DC (:key)\uB294 \uB9F5 \uB9AC\uD130\uB7F4 \uB610\uB294 \uBE14\uB85D \uD544\uB4DC\uC5D0\uC11C\uB9CC \uC0AC\uC6A9\uD560 \uC218 \uC788\uC2B5\uB2C8\uB2E4.","Expected block type":"\uBE14\uB85D\uC740 [FUNC name :params [...] :body ...] \uD615\uC2DD\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4.","Unterminated string":'\uBB38\uC790\uC5F4\uC774 \uB2EB\uD788\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4. \uB2EB\uB294 " \uB97C \uCD94\uAC00\uD558\uC138\uC694.'},Kr=class{constructor(t){this.pos=0;this.parenStack=[];this.tokens=t}parse(){let t=[];for(;!this.isAtEnd()&&!this.check("EOF");)if(this.check("LBracket")){let e=this.pos+1,n=["FUNC","INTENT","PROMPT","PIPE","AGENT","LOAD","RULE","MODULE","TYPECLASS","INSTANCE","SERVER","ROUTE","MIDDLEWARE","WEBSOCKET","ERROR-HANDLER","PAGE","COMPONENT","FORM","SERVICE","CONTROLLER","GUARD","MODEL","QUERY","MIGRATION","REPOSITORY","DATABASE","CACHE","CACHED","KAFKA","PRODUCER","CONSUMER","QUEUE","RABBITMQ","JWT","OAUTH","DOCKERFILE","DOCKER-COMPOSE","K8S-DEPLOYMENT","K8S-SERVICE","K8S-INGRESS","AWS","AWS-S3","AWS-LAMBDA","AWS-RDS","AWS-SQS","GCP","GCP-CLOUD-RUN","GCP-BIGQUERY","AZURE","AZURE-FUNCTION","AZURE-COSMOS"];if(e<this.tokens.length){let s=this.tokens[e],a=s.type==="Module"||s.type==="TypeClass"||s.type==="Instance"||s.type==="Page"||s.type==="Api"||s.type==="Component"||s.type==="Form"||s.type==="Route"||s.type==="Service"||s.type==="Controller"||s.type==="Guard"||s.type==="Model"||s.type==="Query"||s.type==="Migration"||s.type==="Repository"||s.type==="Database"||s.type==="Cached"||s.type==="Kafka"||s.type==="JWT"||s.type==="OAuth"||s.type==="Dockerfile"||s.type==="K8sDeployment"||s.type==="AWS"||s.type==="GCP"||s.type==="Azure",i=s.type==="Symbol"&&n.includes(s.value),o=e+1<this.tokens.length&&(this.tokens[e+1].type==="Keyword"||this.tokens[e+1].type==="Colon");a||i||o?t.push(this.parseBlock()):t.push(this.parseArray())}else t.push(this.parseBlock())}else if(this.check("LParen"))t.push(this.parseSExpr());else throw this.error(`Expected block or S-expression, got ${this.peek().type}`,this.peek());return t}parseBlock(){let e=this.expect("LBracket").line,n=this.advance(),s;if(n.type==="Symbol")s=n.value,s==="FUNC"&&!process.env.FL_NO_DEPRECATION_WARN&&process.stderr.write(`\x1B[33m[deprecated]\x1B[0m [FUNC ...] \uBB38\uBC95\uC740 deprecated\uC785\uB2C8\uB2E4. (defn ...) \uC744 \uC0AC\uC6A9\uD558\uC138\uC694. (line ${n.line})
9
+ `);else if(n.type==="Module")s="MODULE";else if(n.type==="TypeClass")s="TYPECLASS";else if(n.type==="Instance")s="INSTANCE";else if(n.type==="Page")s="PAGE";else if(n.type==="Api")s="API";else if(n.type==="Route")s="ROUTE";else if(n.type==="Component")s="COMPONENT";else if(n.type==="Form")s="FORM";else if(n.type==="Service")s="SERVICE";else if(n.type==="Controller")s="CONTROLLER";else if(n.type==="Guard")s="GUARD";else if(n.type==="Model")s="MODEL";else throw this.error(`Expected block type (symbol or keyword), got ${n.type}`,n);let a;if(s==="FUNC"&&(this.check("Colon")||this.check("Keyword")))a=`__anon_func_${this.pos}`;else{let c=this.advance();if(c.type!=="Symbol")throw this.error(`Expected block name (symbol), got ${c.type}`,c);a=c.value}let i=new Map,o=new Map,u;for(;!this.check("RBracket")&&!this.isAtEnd();){let c,p=this.peek();if(this.check("Colon")){if(this.advance(),!this.check("Symbol"))throw this.error(`Expected symbol after ':', got ${this.peek().type}`,this.peek());c=this.advance().value}else if(this.check("Keyword"))c=this.advance().value,c.startsWith(":")&&(c=c.substring(1));else throw this.error(`Expected keyword field (starting with :), got ${this.peek().type}`,this.peek());let m=[];for(!this.check("Keyword")&&!this.check("Colon")&&!this.check("RBracket")&&m.push(this.parseValue());!this.check("Keyword")&&!this.check("Colon")&&!this.check("RBracket")&&!this.isAtEnd();)m.push(this.parseValue());if(m.length===0)throw this.error(`Expected at least one value for keyword ${c}`,p);if(m.length===1?i.set(c,m[0]):i.set(c,m),c==="return"&&m.length===1){let d=m[0];if(d.kind==="literal"&&d.type==="symbol"){let g=d.value;o.set("return",Jn(g))}}if(c==="generics"&&m.length===1){let d=m[0];if(d.kind==="block"&&d.type==="Array"){let g=d.fields?.get("items");if(Array.isArray(g)){let h=[];for(let y of g)y.kind==="literal"&&y.type==="symbol"&&h.push(y.value);h.length>0&&(u=h)}}}if(c==="params"&&m.length===1){let d=m[0];if(!(d.kind==="literal"&&d.type==="symbol")){if(d.kind==="block"&&d.type==="Array"){let g=d.fields?.get("items");if(Array.isArray(g)){let h=[];for(let y of g)if(y.kind==="block"&&y.type==="Array"){let k=y.fields?.get("items");if(Array.isArray(k)&&k.length===2){let v=k[1];if(v.kind==="literal"&&v.type==="symbol"){let $=v.value;h.push(Jn($))}}}h.length>0&&o.set("params",h)}}}}}if(this.expect("RBracket"),s==="MODULE"){let c=ht(s,a,i,e);return this.convertBlockToModuleBlock(c)}if(s==="TYPECLASS"){let c=ht(s,a,i,e);return this.convertBlockToTypeClass(c)}if(s==="INSTANCE"){let c=ht(s,a,i,e);return this.convertBlockToInstance(c)}if(["PAGE","ROUTE","COMPONENT","FORM","SERVICE","CONTROLLER","GUARD","MODEL","QUERY","MIGRATION","REPOSITORY","DATABASE","CACHE","CACHED","KAFKA","PRODUCER","CONSUMER","QUEUE","RABBITMQ","JWT","OAUTH","DOCKERFILE","DOCKER-COMPOSE","K8S-DEPLOYMENT","K8S-SERVICE","K8S-INGRESS","AWS","AWS-S3","AWS-LAMBDA","AWS-RDS","AWS-SQS","GCP","GCP-CLOUD-RUN","GCP-BIGQUERY","AZURE","AZURE-FUNCTION","AZURE-COSMOS"].includes(s))return ht(s,a,i,e);let l=ht(s,a,i,e);return(s==="FUNC"||o.size>0)&&(l.typeAnnotations=o),u&&u.length>0&&(l.generics=u),l}convertBlockToModuleBlock(t){let e=[],n=[],s=t.fields?.get("exports");if(s)if(s.kind==="block"&&s.type==="Array"){let i=s.fields?.get("items");Array.isArray(i)&&i.forEach(o=>{o.kind==="literal"&&o.type==="symbol"&&e.push(o.value)})}else s.kind==="literal"&&s.type==="symbol"&&e.push(s.value);let a=t.fields?.get("body");if(a)if(a.kind==="block"&&a.type==="Array"){let i=a.fields?.get("items");Array.isArray(i)&&n.push(...i)}else Array.isArray(a)?n.push(...a):n.push(a);return{kind:"module",name:t.name,exports:e,body:n,path:void 0}}convertBlockToTypeClass(t){let e=new Map,n=[],s=t.fields?.get("typeParams");if(s)if(s.kind==="block"&&s.type==="Array"){let i=s.fields?.get("items");Array.isArray(i)&&i.forEach(o=>{o.kind==="literal"&&o.type==="symbol"&&n.push(o.value)})}else s.kind==="literal"&&s.type==="symbol"?n.push(s.value):Array.isArray(s)&&s.forEach(i=>{i.kind==="literal"&&i.type==="symbol"&&n.push(i.value)});let a=t.fields?.get("methods");if(a&&a.kind==="block"&&a.type==="Array"){let i=a.fields?.get("items");Array.isArray(i)&&i.forEach(o=>{if(o.kind==="block"&&o.type==="Array"){let u=o.fields?.get("items");if(Array.isArray(u)&&u.length===2){let f=u[0],l=u[1];if(f.kind==="literal"&&f.type==="symbol"){let c=f.value;e.set(c,{name:c,type:l})}}}})}return{kind:"type-class",name:t.name,typeParams:n,methods:e}}convertBlockToInstance(t){let e="",n=t.name,s=new Map,a=t.fields?.get("typeclass");return a&&a.kind==="literal"&&a.type==="symbol"&&(e=a.value),t.fields?.forEach((i,o)=>{o!=="typeclass"&&s.set(o,i)}),{kind:"type-class-instance",className:e,concreteType:n,implementations:s}}parseValue(){if(this.check("LParen"))return this.parseSExpr();if(this.check("Number")){let t=this.advance();return He("number",parseFloat(t.value))}if(this.check("String")){let t=this.advance();return t.value.includes("${")?lo(t.value):He("string",t.value)}if(this.check("Variable")){let t=this.advance();return uo(t.value,t.line)}if(this.check("Keyword")){let t=this.advance();return po(t.value)}if(this.check("Else")||this.check("Then")||this.check("When")||this.check("Repeat")||this.check("Until")||this.check("While")){let t=this.advance();return He("symbol",t.value)}if(this.check("Colon")){this.advance();let t=this.tokens[this.pos];if(t){if(t.type==="Variable"&&t.value)return this.advance(),He("string","$"+t.value);if(t.value&&/^[a-zA-Z_][a-zA-Z0-9_\-]*$/.test(t.value))return He("string",this.advance().value)}return He("string",":")}if(this.check("LBrace"))return this.parseMap();if(this.check("LBracket")){let t=this.pos+1,e=["FUNC","INTENT","PROMPT","PIPE","AGENT","LOAD","RULE","MODULE","TYPECLASS","INSTANCE","SERVER","ROUTE","MIDDLEWARE","WEBSOCKET","ERROR-HANDLER","PAGE","COMPONENT","FORM","SERVICE","CONTROLLER","GUARD"];if(t<this.tokens.length&&this.tokens[t].type==="Symbol"){let n=this.tokens[t].value,s=e.includes(n),a=t+1,i=a<this.tokens.length&&(this.tokens[a].type==="Keyword"||this.tokens[a].type==="Colon");return s||i?this.parseBlock():this.parseArray()}else if(t<this.tokens.length&&this.tokens[t].type==="Module"){let n=this.parseBlock();if(n.kind==="module")return n;throw this.error("Expected ModuleBlock from parseBlock with MODULE token",this.peek())}else return t<this.tokens.length&&(this.tokens[t].type==="TypeClass"||this.tokens[t].type==="Instance")?this.parseBlock():t<this.tokens.length&&(this.tokens[t].type==="Page"||this.tokens[t].type==="Api"||this.tokens[t].type==="Component"||this.tokens[t].type==="Form"||this.tokens[t].type==="Route")?this.parseBlock():t<this.tokens.length&&(this.tokens[t].type==="Service"||this.tokens[t].type==="Controller"||this.tokens[t].type==="Guard"||this.tokens[t].type==="Model"||this.tokens[t].type==="Query"||this.tokens[t].type==="Migration"||this.tokens[t].type==="Repository"||this.tokens[t].type==="Database"||this.tokens[t].type==="Cached"||this.tokens[t].type==="Kafka"||this.tokens[t].type==="Producer"||this.tokens[t].type==="Consumer"||this.tokens[t].type==="Queue"||this.tokens[t].type==="RabbitMQ"||this.tokens[t].type==="JWT"||this.tokens[t].type==="OAuth"||this.tokens[t].type==="Dockerfile"||this.tokens[t].type==="DockerCompose"||this.tokens[t].type==="K8sDeployment"||this.tokens[t].type==="K8sService"||this.tokens[t].type==="K8sIngress"||this.tokens[t].type==="AWS"||this.tokens[t].type==="GCP"||this.tokens[t].type==="Azure")?this.parseBlock():this.parseArray()}if(this.check("Symbol")){let t=this.advance();return t.value==="true"?He("boolean",!0):t.value==="false"?He("boolean",!1):He("symbol",t.value)}throw this.error(`Unexpected token: ${this.peek().type}`,this.peek())}parseArray(){this.expect("LBracket");let t=[];for(;!this.check("RBracket")&&!this.isAtEnd();)t.push(this.parseValue());this.expect("RBracket");let e=new Map;return e.set("items",t),ht("Array","$array",e)}parseMap(){this.expect("LBrace");let t=new Map;for(;!this.check("RBrace")&&!this.isAtEnd();){let e;if(this.check("Colon")){this.advance();let s=this.peek();if(s.type==="RBrace"||this.isAtEnd())throw this.error("Expected key after ':' in map literal",s);s.type==="Variable"?(this.advance(),e="$"+s.value):e=this.advance().value}else if(this.check("String"))e=this.advance().value;else throw this.error('Map key must be :keyword or "string"',this.peek());let n=this.parseValue();t.set(e,n)}return this.expect("RBrace"),ht("Map","$map",t)}isArrayLiteralStart(){if(!this.check("LBracket"))return!1;let t=this.pos+1;if(t>=this.tokens.length)return!1;let e=this.tokens[t];if(e.type==="Symbol"){let n=e.value;return!(n.length<=2&&n===n.toUpperCase()&&/^[A-Z]/.test(n))}return e.type==="Variable"||e.type==="Number"||e.type==="String"||e.type==="RBracket"||e.type==="LBracket"||e.type==="LParen"}parseSExpr(){this.expect("LParen");let t,e=this.advance();if(e.type==="Open")t="open";else if(e.type==="Search")t="search";else if(e.type==="Fetch")t="fetch";else if(e.type==="Learn")t="learn";else if(e.type==="Recall")t="recall";else if(e.type==="Remember")t="remember";else if(e.type==="Forget")t="forget";else if(e.type==="Observe")t="observe";else if(e.type==="Analyze")t="analyze";else if(e.type==="Decide")t="decide";else if(e.type==="Act")t="act";else if(e.type==="Verify")t="verify";else if(e.type==="If")t="if";else if(e.type==="When")t="when";else if(e.type==="Then")t="then";else if(e.type==="Else")t="else";else if(e.type==="Repeat")t="repeat";else if(e.type==="Until")t="until";else if(e.type==="While")t="while";else if(e.type==="LParen"){this.pos--;let a=[];for(;!this.check("RParen")&&!this.isAtEnd();)a.push(this.parseValue());return this.expect("RParen"),a.length===1?a[0]:{kind:"sexpr",op:"do",args:a}}else if(e.type==="Variable")t=e.value.startsWith("$")?e.value:"$"+e.value;else{if(e.type!=="Symbol")throw this.error(`Expected operator (symbol or keyword) in S-expression, got ${e.type}`,e);t=e.value}if(t==="import"){let a=this.parseImportExpression();return this.expect("RParen"),a}if(t==="open"){let a=this.parseOpenExpression();return this.expect("RParen"),a}if(t==="search"){let a=this.parseSearchExpression();return this.expect("RParen"),a}if(t==="fetch"){let a=this.parseFetchExpression();return this.expect("RParen"),a}if(t==="learn"){let a=this.parseLearnExpression();return this.expect("RParen"),a}if(t==="recall"){let a=this.parseRecallExpression();return this.expect("RParen"),a}if(t==="observe"||e.type==="Observe"){let a=this.parseReasoningExpression("observe");return this.expect("RParen"),a}if(t==="analyze"||e.type==="Analyze"){let a=this.parseReasoningExpression("analyze");return this.expect("RParen"),a}if(t==="decide"||e.type==="Decide"){let a=this.parseReasoningExpression("decide");return this.expect("RParen"),a}if(t==="act"||e.type==="Act"){let a=this.parseReasoningExpression("act");return this.expect("RParen"),a}if(t==="verify"||e.type==="Verify"){let a=this.parseReasoningExpression("verify");return this.expect("RParen"),a}if(t==="reasoning-sequence"){let a=this.parseReasoningSequenceExpression();return this.expect("RParen"),a}if(t==="try"){let a=this.parseTryExpression();return this.expect("RParen"),a}if(t==="throw"){let a=this.parseThrowExpression();return this.expect("RParen"),a}if(t==="match"){let a=this.parsePatternMatch();return this.expect("RParen"),a}if(!new Set(["fn","let","if","cond","match","do","try","catch","let*","letrec","define","async","await","loop","recur","import","export"]).has(t)&&this.check("LBracket")&&!this.isArrayLiteralStart()){this.advance();let a=[];for(;!this.check("RBracket")&&!this.isAtEnd();){let i=this.advance();i.type==="Symbol"&&a.push(i.value),this.check("Symbol")&&this.peek().value===","&&this.advance()}this.expect("RBracket"),a.length>0&&(t=`${t}[${a.join(", ")}]`)}let s=[];for(;!this.check("RParen")&&!this.isAtEnd();)s.push(this.parseValue());return this.expect("RParen"),ln(t,s,e.line)}parseTypeAnnotation(){let t=this.advance();if(t.type!=="Symbol")throw this.error(`Expected type annotation (symbol), got ${t.type}`,t);let e=t.value,n,s=!1;if(this.check("Symbol")&&this.peek().value==="?"&&(this.advance(),s=!0),e.includes("<")&&e.includes(">")){let a=e.match(/<(.+)>/);if(a){let i=a[1];n=Jn(i),e=e.substring(0,e.indexOf("<"))}}return Jn(e,n,void 0,s)}parsePattern(){let t=this.parseAtomicPattern();if(this.check("Symbol")&&this.peek().value==="|"){let e=[t];for(;this.check("Symbol")&&this.peek().value==="|";)this.advance(),e.push(this.parseAtomicPattern());return ho(e)}return t}parseAtomicPattern(){if(this.check("Symbol")&&this.peek().value==="_")return this.advance(),fo();if(this.check("Variable")){let t=this.advance();return Xn(t.value)}if(this.check("Symbol")&&!["&","|"].includes(this.peek().value)){let t=this.advance();return Xn(t.value)}if(this.check("Number")){let t=this.advance();return ga("number",parseFloat(t.value))}if(this.check("String")){let t=this.advance();return ga("string",t.value)}if(this.check("LParen")){if(this.advance(),this.check("Symbol")&&this.peek().value==="range"){this.advance();let e=this.advance(),n=this.advance();return this.expect("RParen"),go(parseFloat(e.value),parseFloat(n.value))}let t=this.parsePattern();return this.expect("RParen"),t}if(this.check("LBracket")){this.advance();let t=[],e;for(;!this.check("RBracket")&&!this.isAtEnd();){if(this.check("Symbol")&&this.peek().value==="&"){this.advance(),this.check("Symbol")&&(e=this.advance().value);break}t.push(this.parsePattern())}return this.expect("RBracket"),mo(t,e)}if(this.check("LBrace")){this.advance();let t=new Map,e;for(;!this.check("RBrace")&&!this.isAtEnd();){let n;if(this.check("Colon")){if(this.advance(),!this.check("Symbol"))break;n=this.advance().value}else if(this.check("Keyword")){let a=this.advance();n=a.value.startsWith(":")?a.value.slice(1):a.value}else break;if(n==="as"){this.check("Variable")&&(e=this.advance().value);continue}let s=this.parsePattern();t.set(n,s)}if(this.expect("RBrace"),!e&&this.check("Colon")){let n=this.pos;this.advance(),this.check("Symbol")&&this.peek().value==="as"?(this.advance(),this.check("Variable")&&(e=this.advance().value)):this.pos=n}return ha(t,e)}if(this.check("Keyword")){let t=new Map,e;for(;this.check("Keyword")&&!this.isAtEnd();){let n=this.advance(),s=n.value.startsWith(":")?n.value.slice(1):n.value;if(s==="as"){this.check("Variable")&&(e=this.advance().value);break}let a=this.parsePattern();t.set(s,a)}return ha(t,e)}throw this.error(`Expected pattern, got ${this.peek().type}`,this.peek())}parsePatternMatch(){let t=this.parseValue(),e=[],n;for(;this.check("LParen")&&!this.isAtEnd();){if(this.advance(),this.check("Symbol")&&this.peek().value==="default"){this.advance(),n=this.parseValue(),this.expect("RParen");break}let s=this.parsePattern(),a;if(this.check("LParen")&&(this.peekNext()?.value==="if"||this.peekNext()?.value==="when")){let o=this.pos;this.advance();let u=this.advance().value,f=this.parseValue();this.check("RParen")?(this.advance(),a=f):u==="when"?this.pos=o:this.pos=o}let i=this.parseValue();e.push(yo(s,i,a)),this.expect("RParen")}return bo(t,e,n)}peek(){return this.pos>=this.tokens.length?this.tokens[this.tokens.length-1]:this.tokens[this.pos]}peekNext(){return this.pos+1>=this.tokens.length?null:this.tokens[this.pos+1]}advance(){return this.pos<this.tokens.length&&this.pos++,this.tokens[this.pos-1]}check(t){return this.isAtEnd()?!1:this.peek().type===t}expect(t){if(this.check(t)){let s=this.advance();return t==="LParen"||t==="LBracket"||t==="LBrace"?this.parenStack.push({type:t,line:s.line,col:s.col}):(t==="RParen"||t==="RBracket"||t==="RBrace")&&this.parenStack.pop(),s}let e=this.peek(),n="";if((t==="RParen"||t==="RBracket"||t==="RBrace")&&this.parenStack.length>0){let s=this.parenStack[this.parenStack.length-1],a=s.type==="LParen"?"(":s.type==="LBracket"?"[":"{",i=t==="RParen"?")":t==="RBracket"?"]":"}";n=` (\uAC00\uC7A5 \uCD5C\uADFC opening '${a}' at line ${s.line}:${s.col} \u2014 '${i}' \uB204\uB77D \uB610\uB294 \uC911\uCCA9 \uC624\uB958)`}throw this.error(`Expected ${t}, got ${e.type}${n}`,e)}isAtEnd(){return this.pos>=this.tokens.length}error(t,e){let n=Object.entries(qp).find(([a])=>t.includes(a))?.[1];if(this.parenStack.length>0&&(e.type==="EOF"||t.includes("Expected R")||t.includes("Unexpected"))){let a=this.parenStack.map((l,c)=>{let p=l.type==="LParen"?"(":l.type==="LBracket"?"[":"{";return` [${c+1}] '${p}' at line ${l.line}:${l.col}`}).join(`
10
+ `),i=this.parenStack.map(l=>l.type==="LParen"?")":l.type==="LBracket"?"]":"}").reverse().join(""),o=this.parenStack[this.parenStack.length-1],u=o.type==="LParen"?")":o.type==="LBracket"?"]":"}",f=`\uBBF8\uB2EB\uD798 \uAD04\uD638 \uC2A4\uD0DD (\uAE4A\uC774: ${this.parenStack.length}):
11
+ ${a}
12
+
13
+ \uD544\uC694\uD55C \uB2EB\uD798 \uAD04\uD638 \uC2DC\uD000\uC2A4: ${i}
14
+
15
+ \uB2E4\uC74C \uD1A0\uD070\uC744 \uC608\uC0C1: '${u}'`;n=n?`${n}
16
+
17
+ ${f}`:f}let s="E_PARSE_SYNTAX_ERROR";return t.includes("Expected")||t.includes("Unexpected")?s="E_PARSE_UNEXPECTED_TOKEN":t.includes("Unterminated")?s="E_PARSE_UNCLOSED_PAREN":t.includes("Expected block")&&(s="E_PARSE_SYNTAX_ERROR"),new pn(t,e.line,e.col,n,s,"parse")}synchronize(){for(this.advance();!this.isAtEnd();){if(this.check("LBracket"))return;this.advance()}}parseImportExpression(){let t=this.parseQualifiedIdentifier(),e,n,s;for(;!this.check("RParen")&&!this.isAtEnd();)if(this.check("Colon")){if(this.advance(),!this.check("Symbol"))throw this.error(`Expected symbol after ':', got ${this.peek().type}`,this.peek());let a=this.advance().value;switch(a){case"from":if(!this.check("String"))throw this.error(`Expected string after :from, got ${this.peek().type}`,this.peek());e=this.advance().value;break;case"only":if(!this.check("LBracket"))throw this.error(`Expected [ after :only, got ${this.peek().type}`,this.peek());n=this.parseSelectiveImport();break;case"as":if(!this.check("Symbol"))throw this.error(`Expected symbol after :as, got ${this.peek().type}`,this.peek());s=this.advance().value;break;default:throw this.error(`Unknown import clause: ${a}`,this.peek())}}else throw this.error(`Expected ':' in import expression, got ${this.peek().type}`,this.peek());return ko(t,e,n,s)}parseOpenExpression(){let t=this.parseQualifiedIdentifier(),e;for(;!this.check("RParen")&&!this.isAtEnd();)if(this.check("Colon")){if(this.advance(),!this.check("Symbol"))throw this.error(`Expected symbol after ':', got ${this.peek().type}`,this.peek());let n=this.advance().value;if(n==="from"){if(!this.check("String"))throw this.error(`Expected string after :from, got ${this.peek().type}`,this.peek());e=this.advance().value}else throw this.error(`Unknown open clause: ${n}`,this.peek())}else throw this.error(`Expected ':' in open expression, got ${this.peek().type}`,this.peek());return vo(t,e)}parseSearchExpression(){let t="",e=this.parseValue();if(e.kind==="literal"&&e.type==="string")t=e.value;else throw this.error("Expected string query in search expression",this.peek());let n="web",s=!1,a=10,i;for(;!this.check("RParen")&&!this.isAtEnd();)if(this.check("Colon")){if(this.advance(),!this.check("Symbol"))throw this.error(`Expected symbol after ':', got ${this.peek().type}`,this.peek());let o=this.advance().value;switch(o){case"source":if(!this.check("String"))throw this.error("Expected string after :source",this.peek());let u=this.advance().value;if(u==="web"||u==="api"||u==="kb")n=u;else throw this.error(`Invalid source: ${u}`,this.peek());break;case"cache":let f=this.parseValue();f.kind==="literal"&&(s=f.value==="true"||f.value===!0);break;case"limit":let l=this.parseValue();l.kind==="literal"&&l.type==="number"&&(a=l.value);break;case"name":if(!this.check("Symbol"))throw this.error("Expected symbol after :name",this.peek());i=this.advance().value;break;default:throw this.error(`Unknown search clause: ${o}`,this.peek())}}else throw this.error(`Expected ':' in search expression, got ${this.peek().type}`,this.peek());return{kind:"search-block",query:t,source:n,cache:s,limit:a,name:i}}parseFetchExpression(){let t="",e=this.parseValue();if(e.kind==="literal"&&e.type==="string")t=e.value;else throw this.error("Expected string URL in fetch expression",this.peek());let n=!1;for(;!this.check("RParen")&&!this.isAtEnd();)if(this.check("Colon")){if(this.advance(),!this.check("Symbol"))throw this.error(`Expected symbol after ':', got ${this.peek().type}`,this.peek());let s=this.advance().value;if(s==="cache"){let a=this.parseValue();a.kind==="literal"&&(n=a.value==="true"||a.value===!0)}else throw this.error(`Unknown fetch clause: ${s}`,this.peek())}else throw this.error(`Expected ':' in fetch expression, got ${this.peek().type}`,this.peek());return{kind:"search-block",query:t,source:"api",cache:n}}parseLearnExpression(){let t="",e=this.parseValue();if(e.kind==="literal"&&(e.type==="string"||e.type==="symbol"))t=e.value;else if(e.kind==="variable")t=e.name;else throw this.error("Expected symbol/string key in learn expression",this.peek());let n=null;!this.check("Colon")&&!this.check("RParen")&&!this.isAtEnd()&&(n=this.parseValue());let s="search",a,i;for(;!this.check("RParen")&&!this.isAtEnd();)if(this.check("Colon")){if(this.advance(),!this.check("Symbol"))throw this.error(`Expected symbol after ':', got ${this.peek().type}`,this.peek());let o=this.advance().value;switch(o){case"source":let u=this.parseValue();if(u.kind==="literal"&&u.type==="string"){let c=u.value;(c==="search"||c==="feedback"||c==="analysis")&&(s=c)}break;case"confidence":let f=this.parseValue();f.kind==="literal"&&f.type==="number"&&(a=f.value);break;case"timestamp":let l=this.parseValue();l.kind==="literal"&&l.type==="string"&&(i=l.value);break;default:throw this.error(`Unknown learn clause: ${o}`,this.peek())}}else throw this.error(`Expected ':' in learn expression, got ${this.peek().type}`,this.peek());return{kind:"learn-block",key:t,data:n,source:s,confidence:a,timestamp:i}}parseRecallExpression(){let t="",e=this.parseValue();if(e.kind==="literal"&&(e.type==="string"||e.type==="symbol"))t=e.value;else if(e.kind==="variable")t=e.name;else throw this.error("Expected symbol/string key in recall expression",this.peek());return{kind:"learn-block",key:t,data:null,source:"search"}}parseReasoningExpression(t){let e=new Map,n={startTime:new Date().toISOString()},s,a,i,o,u;switch(t){case"observe":{if(!this.check("RParen")&&!this.check("Colon")){let f=this.parseValue();s=[f],e.set("observation",f)}for(;!this.check("RParen")&&!this.isAtEnd();)if(this.check("Colon")){this.advance();let f=this.advance().value,l=this.parseValue();f==="confidence"?l.kind==="literal"&&l.type==="number"&&e.set(f,l.value):e.set(f,l)}else throw this.error(`Expected ':' in observe expression, got ${this.peek().type}`,this.peek());break}case"analyze":{let f=new Map;for(;!this.check("RParen")&&!this.isAtEnd();)if(this.check("Colon")){this.advance();let l=this.advance().value;if(l==="selected"){let c=this.parseValue();e.set("selected",c)}else{let c=this.parseValue();f.set(l,c)}}else throw this.error(`Expected ':' in analyze expression, got ${this.peek().type}`,this.peek());e.set("angles",f),a=Array.from(f.values());break}case"decide":{for(;!this.check("RParen")&&!this.isAtEnd();)if(this.check("Colon")){this.advance();let f=this.advance().value,l=this.parseValue();e.set(f,l)}else throw this.error(`Expected ':' in decide expression, got ${this.peek().type}`,this.peek());i=[e.get("choice")];break}case"act":{for(;!this.check("RParen")&&!this.isAtEnd();)if(this.check("Colon")){this.advance();let f=this.advance().value,l=this.parseValue();e.set(f,l)}else throw this.error(`Expected ':' in act expression, got ${this.peek().type}`,this.peek());o=[e.get("action")];break}case"verify":{for(;!this.check("RParen")&&!this.isAtEnd();)if(this.check("Colon")){this.advance();let f=this.advance().value,l=this.parseValue();f==="confidence"?l.kind==="literal"&&l.type==="number"&&(n.confidence=l.value):e.set(f,l)}else throw this.error(`Expected ':' in verify expression, got ${this.peek().type}`,this.peek());u=[e.get("result")];break}}return n.endTime=new Date().toISOString(),{kind:"reasoning-block",stage:t,data:e,observations:s,analysis:a,decisions:i,actions:o,verifications:u,metadata:n}}parseReasoningSequenceExpression(){let t=[],e=new Date().toISOString(),n;for(;!this.check("RParen")&&!this.isAtEnd();)if(this.check("Colon")){if(this.advance(),!this.check("Symbol"))throw this.error(`Expected symbol after ':', got ${this.peek().type}`,this.peek());let a=this.advance().value;if(a==="feedback")for(n={enabled:!1,fromStage:"verify",toStage:"analyze",maxIterations:3,confidenceDamping:.1};!this.check("RParen")&&!this.isAtEnd()&&this.check("Colon");){this.advance();let i=this.advance().value;switch(i){case"enabled":let o=this.parseValue();n.enabled=o.kind==="literal"&&o.value===!0;break;case"from":let u=this.parseValue();u.kind==="literal"&&u.type==="string"&&(n.fromStage=u.value);break;case"to":let f=this.parseValue();f.kind==="literal"&&f.type==="string"&&(n.toStage=f.value);break;case"max-iterations":let l=this.parseValue();l.kind==="literal"&&l.type==="number"&&(n.maxIterations=l.value);break;case"damping":let c=this.parseValue();c.kind==="literal"&&c.type==="number"&&(n.confidenceDamping=c.value);break;case"condition":n.condition=this.parseValue();break;default:throw this.error(`Unknown feedback option: ${i}`,this.peek())}}else throw this.error(`Unknown option: ${a}`,this.peek())}else if(this.check("LParen")){if(this.pos+1<this.tokens.length){let f=this.tokens[this.pos+1];if(f.type==="If"){let l=this.parseConditionalReasoningBlock();t.push(l);continue}if(f.type==="When"){let l=this.parseWhenReasoningBlock();t.push(l);continue}if(f.type==="Repeat"||f.type==="While"){let l=this.parseLoopReasoningBlock();t.push(l);continue}if(f.type==="Search"){let l=this.parseSearchReasoningBlock();t.push(l);continue}if(f.type==="Learn"){let l=this.parseLearnReasoningBlock();t.push(l);continue}}this.advance();let a=this.peek();if(!(a.type==="Observe"||a.type==="Analyze"||a.type==="Decide"||a.type==="Act"||a.type==="Verify"||a.type==="Symbol"&&(a.value==="observe"||a.value==="analyze"||a.value==="decide"||a.value==="act"||a.value==="verify")))throw this.error(`Expected reasoning stage (observe/analyze/decide/act/verify), got ${a.value}`,a);let o=a.type==="Observe"?"observe":a.type==="Analyze"?"analyze":a.type==="Decide"?"decide":a.type==="Act"?"act":a.type==="Verify"?"verify":a.value;this.advance();let u=this.parseReasoningExpressionInternal(o);t.push(u),this.expect("RParen")}else if(this.check("If")){let a=this.parseConditionalReasoningBlock();t.push(a)}else if(this.check("When")){let a=this.parseWhenReasoningBlock();t.push(a)}else if(this.check("Repeat")||this.check("While")){let a=this.parseLoopReasoningBlock();t.push(a)}else throw this.error(`Expected '(' before reasoning block, 'if', 'when', 'repeat', 'while', or ':feedback', got ${this.peek().type}`,this.peek());let s=new Date().toISOString();return{kind:"reasoning-sequence",stages:t,metadata:{startTime:e,endTime:s,executionPath:t.map(a=>"stage"in a?a.stage:a.kind==="search-block"?"search":a.kind==="learn-block"?"learn":"unknown")},feedbackLoop:n?.enabled?n:void 0}}parseTryExpression(){let t=[];for(;this.check("LParen")||!this.check("RParen");){if(this.check("LParen")&&this.pos+1<this.tokens.length){let a=this.tokens[this.pos+1];if(a.type==="Symbol"&&(a.value==="catch"||a.value==="finally"))break}if(this.isAtEnd()||this.check("RParen"))break;t.push(this.parseValue())}let e=t.length===1?t[0]:ln("do",t),n=[],s;for(;this.check("LParen")&&!this.isAtEnd();){let a=this.peek();if(this.pos+1<this.tokens.length){let i=this.tokens[this.pos+1];if(i.type==="Symbol"&&i.value==="catch"){this.advance(),this.advance();let o,u;if(this.check("LBracket")){if(this.advance(),this.check("Symbol")){let c=this.advance().value;u=c,o=Xn(c)}this.expect("RBracket")}else if(this.check("Symbol")||this.check("Variable")){let c=this.advance();u=c.value,o=Xn(c.value)}let f=[];for(;!this.check("RParen")&&!this.isAtEnd();)f.push(this.parseValue());let l=f.length===1?f[0]:ln("do",f);n.push(_o(l,o,u)),this.expect("RParen")}else if(i.type==="Symbol"&&i.value==="finally"){this.advance(),this.advance();let o=[];for(;!this.check("RParen")&&!this.isAtEnd();)o.push(this.parseValue());s=o.length===1?o[0]:ln("do",o),this.expect("RParen");break}else break}else break}return wo(e,n.length>0?n:void 0,s)}parseThrowExpression(){let t=this.parseValue();return So(t)}parseLoopExpression(){let t=this.peek().line||0;this.expect("LBracket");let e=this.parseValue(),n=this.parseValue(),s=this.parseValue();this.expect("RBracket");let a=[];for(;!this.check("RParen")&&!this.isAtEnd();)a.push(this.parseValue());let i=a.length===1?a[0]:ln("do",a);return{kind:"loop",init:e,condition:n,update:s,body:i,line:t}}parseReasoningExpressionInternal(t){let e=new Map,n=[],s=[],a=[],i=[],o=[],u={startTime:new Date().toISOString()};switch(t){case"observe":{if(!this.check("RParen")){let f=this.parseValue();f.kind==="literal"&&f.type==="string"&&(e.set("observation",f.value),n.push(f.value))}for(;!this.check("RParen")&&!this.isAtEnd();)if(this.check("Colon")){if(this.advance(),!this.check("Symbol"))throw this.error(`Expected symbol after ':', got ${this.peek().type}`,this.peek());let f=this.advance().value,l=this.parseValue();f==="confidence"?l.kind==="literal"&&l.type==="number"&&(u.confidence=l.value):e.set(f,l)}else throw this.error(`Expected ':' in observe expression, got ${this.peek().type}`,this.peek());break}case"analyze":{for(;!this.check("RParen")&&!this.isAtEnd();)if(this.check("Colon")){this.advance();let f=this.advance().value,l=this.parseValue();e.set(f,l),f==="selected"&&s.push(l)}else throw this.error(`Expected ':' in analyze expression, got ${this.peek().type}`,this.peek());break}case"decide":{for(;!this.check("RParen")&&!this.isAtEnd();)if(this.check("Colon")){this.advance();let f=this.advance().value,l=this.parseValue();e.set(f,l)}else throw this.error(`Expected ':' in decide expression, got ${this.peek().type}`,this.peek());a=[e.get("choice")];break}case"act":{for(;!this.check("RParen")&&!this.isAtEnd();)if(this.check("Colon")){this.advance();let f=this.advance().value,l=this.parseValue();e.set(f,l)}else throw this.error(`Expected ':' in act expression, got ${this.peek().type}`,this.peek());i=[e.get("action")];break}case"verify":{for(;!this.check("RParen")&&!this.isAtEnd();)if(this.check("Colon")){this.advance();let f=this.advance().value,l=this.parseValue();f==="confidence"?l.kind==="literal"&&l.type==="number"&&(u.confidence=l.value):e.set(f,l)}else throw this.error(`Expected ':' in verify expression, got ${this.peek().type}`,this.peek());o=[e.get("result")];break}}return u.endTime=new Date().toISOString(),{kind:"reasoning-block",stage:t,data:e,observations:n,analysis:s,decisions:a,actions:i,verifications:o,metadata:u}}parseQualifiedIdentifier(){if(!this.check("Symbol"))throw this.error(`Expected symbol, got ${this.peek().type}`,this.peek());let t=[];t.push(this.advance().value);let e=new Set(["from","as","only","to","body","params","exports"]);for(;this.check("Colon");){let n=this.pos+1;if(n>=this.tokens.length)break;let s=this.tokens[n];if(s.type==="Symbol"&&e.has(s.value))break;if(this.advance(),!this.check("Symbol"))throw this.error(`Expected symbol after ':', got ${this.peek().type}`,this.peek());t.push(this.advance().value)}return t.join(":")}parseSelectiveImport(){this.expect("LBracket");let t=[];for(;!this.check("RBracket")&&!this.isAtEnd();){if(!this.check("Symbol"))throw this.error(`Expected symbol in import list, got ${this.peek().type}`,this.peek());t.push(this.advance().value)}return this.expect("RBracket"),t}parseConditionalReasoningBlock(){this.expect("LParen"),this.expect("If");let t=this.parseValue();if(!this.check("LParen"))throw this.error(`Expected '(' for then block, got ${this.peek().type}`,this.peek());this.advance();let e=this.peek(),n=this.getReasoningStageName(e);if(!n)throw this.error(`Expected reasoning stage in then block, got ${e.value}`,e);this.advance();let s=this.parseReasoningExpressionInternal(n);this.expect("RParen");let a;if(this.check("LParen")){let i=this.pos+1;if(i<this.tokens.length){let o=this.tokens[i],u=this.getReasoningStageName(o);u&&(this.advance(),this.advance(),a=this.parseReasoningExpressionInternal(u),this.expect("RParen"))}}return this.expect("RParen"),{...s,conditional:{condition:t,thenBlock:s,elseBlock:a}}}parseWhenReasoningBlock(){this.expect("LParen"),this.expect("When");let t=this.parseValue();if(!this.check("LParen"))throw this.error(`Expected '(' for when block, got ${this.peek().type}`,this.peek());this.advance();let e=this.peek(),n=this.getReasoningStageName(e);if(!n)throw this.error(`Expected reasoning stage in when block, got ${e.value}`,e);this.advance();let s=this.parseReasoningExpressionInternal(n);return this.expect("RParen"),this.expect("RParen"),{...s,whenGuard:t}}parseSearchReasoningBlock(){this.expect("LParen"),this.expect("Search");let t=this.parseSearchExpression();return this.expect("RParen"),t}parseLearnReasoningBlock(){this.expect("LParen"),this.expect("Learn");let t=this.parseLearnExpression();return this.expect("RParen"),t}parseLoopReasoningBlock(){this.expect("LParen");let t=this.peek(),e=t.type==="Repeat",n=t.type==="While";if(!e&&!n)throw this.error(`Expected 'repeat' or 'while' in loop, got ${t.type}`,t);this.advance();let s;e?(this.expect("Until"),s="repeat-until"):s="repeat-while";let a=this.parseValue();if(!this.check("LParen"))throw this.error(`Expected '(' for loop block, got ${this.peek().type}`,this.peek());this.advance();let i=this.peek(),o=this.getReasoningStageName(i);if(!o)throw this.error(`Expected reasoning stage in loop block, got ${i.value}`,i);this.advance();let u=this.parseReasoningExpressionInternal(o);return this.expect("RParen"),this.expect("RParen"),{...u,loopControl:{type:s,condition:a}}}parsePage(t,e,n){let s=this.extractStringField(e,"path"),a=this.extractStringField(e,"title"),i=this.extractStringField(e,"render"),o=this.extractSymbolField(e,"component"),u=this.extractMapField(e,"metadata"),f=xo(t,a,s,o,u,n);return i&&(f.fields=f.fields||new Map,f.fields.set("render",{kind:"literal",type:"string",value:i})),f}parseRoute(t,e,n){let s=this.extractStringField(e,"path"),a=this.extractStringField(e,"method"),i=this.extractSymbolField(e,"handler"),o=this.extractSymbolArrayField(e,"middleware"),u=this.extractSymbolField(e,"validation");return Ao(t,s,a,i,o,u,n)}parseComponent(t,e,n){let s=this.extractSymbolField(e,"render"),a=this.extractSymbolField(e,"state"),i=this.extractSymbolArrayField(e,"computed"),o=this.extractWatchField(e,"watch"),u=this.extractMethodsField(e,"methods"),f=this.extractSymbolArrayField(e,"slots");return $o(t,s,a,i,o,u,f,n)}parseForm(t,e,n){let s=this.extractMapField(e,"fields"),a=this.extractSymbolField(e,"validation"),i=this.extractSymbolField(e,"submit"),o=this.extractHandlersField(e,"handlers");return Eo(t,s,a,i,o,n)}extractStringField(t,e){let n=t.get(e);if(n){if(Array.isArray(n)){let s=n[0];if(s.kind==="literal"&&s.type==="string")return s.value}else if(n.kind==="literal"&&n.type==="string")return n.value}}extractSymbolField(t,e){let n=t.get(e);if(n){if(Array.isArray(n)){let s=n[0];if(s.kind==="literal"&&s.type==="symbol")return s.value}else if(n.kind==="literal"&&n.type==="symbol")return n.value}}extractSymbolArrayField(t,e){let n=t.get(e);if(!n)return;let s=[],a=[];if(Array.isArray(n))a=n;else if(n.kind==="block"&&n.type==="Array"){let i=n.fields?.get("items");Array.isArray(i)&&(a=i)}for(let i of a)i.kind==="literal"&&i.type==="symbol"&&s.push(i.value);return s.length>0?s:void 0}extractMapField(t,e){let n=t.get(e);if(!n)return;let s=new Map;if(n.kind==="block"&&n.type==="Map"){let a=n.fields;if(a)for(let[i,o]of a)s.set(i,o)}return s.size>0?s:void 0}extractWatchField(t,e){let n=t.get(e);if(!n)return;let s=new Map;if(n.kind==="block"&&n.type==="Map"){let a=n.fields;if(a)for(let[i,o]of a)o.kind==="literal"&&o.type==="symbol"&&s.set(i,o.value)}return s.size>0?s:void 0}extractMethodsField(t,e){let n=t.get(e);if(!n)return;let s=new Map;if(n.kind==="block"&&n.type==="Map"){let a=n.fields;if(a)for(let[i,o]of a)o.kind==="literal"&&o.type==="symbol"&&s.set(i,o.value)}return s.size>0?s:void 0}extractHandlersField(t,e){let n=t.get(e);if(!n)return;let s=new Map;if(n.kind==="block"&&n.type==="Map"){let a=n.fields;if(a)for(let[i,o]of a)o.kind==="literal"&&o.type==="symbol"&&s.set(i,o.value)}return s.size>0?s:void 0}getReasoningStageName(t){if(t.type==="Observe")return"observe";if(t.type==="Analyze")return"analyze";if(t.type==="Decide")return"decide";if(t.type==="Act")return"act";if(t.type==="Verify")return"verify";if(t.type==="Symbol"){if(t.value==="observe")return"observe";if(t.value==="analyze")return"analyze";if(t.value==="decide")return"decide";if(t.value==="act")return"act";if(t.value==="verify")return"verify"}return null}}});var xa={};on(xa,{ErrorCodes:()=>de,FLRuntimeError:()=>ue,FunctionNotFoundError:()=>Bt,FunctionRegistrationError:()=>wa,InvalidModuleStructureError:()=>va,ModuleError:()=>yt,ModuleNotFoundError:()=>mn,RECOVERY_HINTS:()=>Sa,SelectiveImportError:()=>ka,UnresolvedSymbolError:()=>_a,VariableNotFoundError:()=>Dt});function zp(r,t,e){if(!Vp.has(r))try{let n=JSON.stringify({name:r,file:t,line:e,ts:Date.now()})+`
18
+ `;(0,Bo.appendFileSync)(Up,n)}catch{}}var Bo,Up,Vp,yt,mn,ka,va,wa,Bt,de,Sa,ue,Dt,_a,nt=gt(()=>{Bo=require("fs"),Up=process.env.FL_ERROR_LOG??"/tmp/fl-unknown-functions.jsonl",Vp=new Set(["+","-","*","/","%","=","!=","<",">","<=",">=","and","or","not","str","inc","dec","mod"]);yt=class r extends Error{constructor(e,n,s,a,i,o){super(e);this.moduleName=n;this.file=s;this.line=a;this.col=i;this.hint=o;this.name="ModuleError",Object.setPrototypeOf(this,r.prototype)}},mn=class r extends yt{constructor(t,e,n,s,a,i){let o=e?` (from ${e})`:"";super(`Module not found: ${t}${o}`,t,n,s,a,i),this.name="ModuleNotFoundError",Object.setPrototypeOf(this,r.prototype)}},ka=class r extends yt{constructor(t,e,n,s,a,i){super(`Function "${e}" not exported from module "${t}"`,t,n,s,a,i),this.name="SelectiveImportError",Object.setPrototypeOf(this,r.prototype)}},va=class r extends yt{constructor(t,e){super(`Invalid module structure in "${t}": ${e}`,t),this.name="InvalidModuleStructureError",Object.setPrototypeOf(this,r.prototype)}},wa=class r extends yt{constructor(t,e,n,s,a,i,o){super(`Failed to register function "${e}" in module "${t}": ${n}`,t,s,a,i,o),this.name="FunctionRegistrationError",Object.setPrototypeOf(this,r.prototype)}},Bt=class r extends Error{constructor(e,n,s,a,i){let o=i?` ${i}`:"";super(`Function not found: ${e}${o}`);this.functionName=e;this.file=n;this.line=s;this.col=a;this.hint=i;this.name="FunctionNotFoundError",Object.setPrototypeOf(this,r.prototype),zp(e,n,s)}},de={TYPE_NIL:"E_TYPE_NIL",TYPE_MISMATCH:"E_TYPE_MISMATCH",ARG_COUNT:"E_ARG_COUNT",STACK_OVERFLOW:"E_STACK_OVERFLOW",FN_NOT_FOUND:"E_FN_NOT_FOUND",DIV_BY_ZERO:"E_DIV_BY_ZERO",INDEX_OUT_OF_BOUNDS:"E_INDEX_OOB",INVALID_FORM:"E_INVALID_FORM",RUNTIME:"E_RUNTIME",PURE_VIOLATION:"E_PURE_VIOLATION",UNDEFINED_VAR:"E_UNDEFINED_VAR",UNRESOLVED_SYMBOL:"E_UNRESOLVED_SYMBOL"},Sa={E_TYPE_NIL:"\uAC12\uC774 nil\uC778\uC9C0 (nil? x) \uB610\uB294 (get-or x :key default) \uB85C \uBA3C\uC800 \uD655\uC778\uD558\uC138\uC694.",E_TYPE_MISMATCH:"\uAE30\uB300 \uD0C0\uC785\uACFC \uB2E4\uB985\uB2C8\uB2E4. (string? x) (number? x) \uB4F1\uC73C\uB85C \uC0AC\uC804 \uAC80\uC99D\uD558\uAC70\uB098 \uBCC0\uD658 \uD568\uC218\uB97C \uC0AC\uC6A9\uD558\uC138\uC694.",E_ARG_COUNT:"\uC778\uC790 \uAC2F\uC218\uAC00 \uB9DE\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4. \uD568\uC218 \uC2DC\uADF8\uB2C8\uCC98\uB97C \uB2E4\uC2DC \uD655\uC778\uD558\uC138\uC694.",E_STACK_OVERFLOW:"\uC7AC\uADC0 \uAE4A\uC774 \uCD08\uACFC. \uC885\uB8CC \uC870\uAC74\uC774 \uC788\uB294\uC9C0, \uB610\uB294 loop/recur \uB610\uB294 reduce\uB85C \uBCC0\uD658 \uAC00\uB2A5\uD55C\uC9C0 \uD655\uC778\uD558\uC138\uC694.",E_FN_NOT_FOUND:"\uD568\uC218\uAC00 \uB4F1\uB85D\uB418\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4. \uBAA8\uB4C8 import \uB610\uB294 \uC624\uD0C0\uB97C \uD655\uC778\uD558\uC138\uC694.",E_DIV_BY_ZERO:"0\uC73C\uB85C \uB098\uB20C \uC218 \uC5C6\uC2B5\uB2C8\uB2E4. \uBD84\uBAA8 \uAC80\uC99D (= denom 0) \uD6C4 \uBD84\uAE30\uD558\uC138\uC694.",E_INDEX_OOB:"\uC778\uB371\uC2A4\uAC00 \uBC94\uC704\uB97C \uBC97\uC5B4\uB0AC\uC2B5\uB2C8\uB2E4. (length coll) \uC73C\uB85C \uAE38\uC774\uB97C \uBA3C\uC800 \uD655\uC778\uD558\uC138\uC694.",E_INVALID_FORM:"\uC798\uBABB\uB41C special form \uAD6C\uC870\uC785\uB2C8\uB2E4. \uBB38\uBC95 \uAC00\uC774\uB4DC\uB97C \uD655\uC778\uD558\uC138\uC694.",E_RUNTIME:"\uB7F0\uD0C0\uC784 \uC624\uB958. \uC785\uB825 \uB370\uC774\uD130\uC640 \uD750\uB984\uC744 \uC810\uAC80\uD558\uC138\uC694.",E_PURE_VIOLATION:"^pure/:effects [] \uD568\uC218\uC5D0\uC11C side effect\uAC00 \uBC1C\uACAC\uB418\uC5C8\uC2B5\uB2C8\uB2E4. :effects \uC120\uC5B8\uC744 \uCD94\uAC00\uD558\uAC70\uB098 effect \uD638\uCD9C\uC744 \uC81C\uAC70\uD558\uC138\uC694.",E_UNDEFINED_VAR:"\uBCC0\uC218\uAC00 \uC815\uC758\uB418\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4. (define name value) \uB610\uB294 (let [[name value]] ...) \uB85C \uBA3C\uC800 \uC815\uC758\uD558\uC138\uC694.",E_UNRESOLVED_SYMBOL:"\uC2EC\uBCFC\uC744 \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4. \uD568\uC218\uBA85 \uC624\uD0C0, \uBAA8\uB4C8 import, \uB610\uB294 \uBCC0\uC218 \uC815\uC758\uB97C \uD655\uC778\uD558\uC138\uC694."},ue=class r extends yt{constructor(e,n,s={},a,i,o,u){super(`[${e}] ${n}`,"runtime",a,i,o,u??Sa[e]);this.code=e;this.context=s;this.name="FLRuntimeError",Object.setPrototypeOf(this,r.prototype)}},Dt=class r extends ue{constructor(t,e,n,s,a,i){typeof n=="string"?n=[n]:Array.isArray(n)||(n=[]);let o=[`\uBCC0\uC218 '$${t}'\uC774(\uAC00) \uC815\uC758\uB418\uC9C0 \uC54A\uC558\uC2B5\uB2C8\uB2E4.`,e&&e.length>0?`\uC2A4\uCF54\uD504 \uB0B4 \uBCC0\uC218: ${e.slice(0,5).join(", ")}${e.length>5?" ...":""}`:null,n&&n.length>0?`\uC720\uC0AC \uC774\uB984: ${n.slice(0,3).join(", ")}`:null].filter(Boolean).join(" | ");super(de.UNDEFINED_VAR,o,{varName:t,scope:e,suggestions:n},s,a,i),this.name="VariableNotFoundError",Object.setPrototypeOf(this,r.prototype)}},_a=class r extends ue{constructor(t,e,n,s,a,i){let o=[`\uC2EC\uBCFC '${t}'\uC744(\uB97C) \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4.`,n&&n.length>0?`\uC720\uC0AC \uC774\uB984: ${n.slice(0,3).join(", ")}`:null].filter(Boolean).join(" | ");super(de.UNRESOLVED_SYMBOL,o,{symbol:t,suggestions:n},s,a,i),this.name="UnresolvedSymbolError",Object.setPrototypeOf(this,r.prototype)}}});var ri=jp((mw,If)=>{If.exports=[{module:"agent",name:"agent_create",params:"name",returns:"AgentState"},{module:"agent",name:"agent_set",params:"agent key value",returns:"AgentState (immutable update)"},{module:"agent",name:"agent_get",params:"agent key",returns:"any"},{module:"agent",name:"agent_update",params:"agent updates",returns:"AgentState (merge multiple keys)"},{module:"agent",name:"agent_steps",params:"agent",returns:"number"},{module:"agent",name:"agent_status",params:"agent",returns:"string"},{module:"agent",name:"agent_done",params:"agent",returns:"boolean"},{module:"agent",name:"agent_add_tool",params:"agent toolName fn",returns:"AgentState"},{module:"agent",name:"agent_call_tool",params:"agent toolName ...args",returns:"any"},{module:"agent",name:"agent_tools",params:"agent",returns:"[string] (list registered tool names)"},{module:"agent",name:"agent_push_history",params:"agent entry",returns:"AgentState"},{module:"agent",name:"agent_history",params:"agent",returns:"[AgentHistoryEntry]"},{module:"agent",name:"agent_history_last",params:"agent n",returns:"[AgentHistoryEntry] (last n entries)"},{module:"agent",name:"agent_history_type",params:"agent type",returns:"[AgentHistoryEntry] (filter by type)"},{module:"agent",name:"plan_create",params:"steps",returns:"Plan"},{module:"agent",name:"plan_next",params:"plan",returns:"string | null (current step or null if done)"},{module:"agent",name:"plan_advance",params:"plan result",returns:"Plan (mark current step done, move to next)"},{module:"agent",name:"plan_done",params:"plan",returns:"boolean"},{module:"agent",name:"plan_progress",params:"plan",returns:"number (0.0 - 1.0)"},{module:"agent",name:"plan_results",params:"plan",returns:"{step: result}"},{module:"agent",name:"observe",params:"key value context",returns:"context (accumulate observations)"},{module:"agent",name:"summarize",params:"context",returns:"string (human/AI readable summary of context)"},{module:"agent",name:"context_create",params:"",returns:"{} (empty context)"},{module:"agent",name:"context_merge",params:"ctx1 ctx2",returns:"context"},{module:"ai-workflow",name:"ai-stream",params:"prompt onChunk [model]",returns:"null (\uCF5C\uBC31\uC73C\uB85C \uCCAD\uD06C \uC804\uB2EC)"},{module:"ai-workflow",name:"ollama",params:"prompt [model]",returns:"string (\uB85C\uCEEC LLM \uC9C1\uC811 \uD638\uCD9C)"},{module:"ai-workflow",name:"ollama-models",params:"",returns:"[string] (\uC124\uCE58\uB41C \uBAA8\uB378 \uBAA9\uB85D)"},{module:"ai-workflow",name:"ai-render",params:"template vars",returns:"string"},{module:"bits",name:"bit_and",params:"a b",returns:"number (bitwise AND: a & b)"},{module:"bits",name:"bit_or",params:"a b",returns:"number (bitwise OR: a | b)"},{module:"bits",name:"bit_xor",params:"a b",returns:"number (bitwise XOR: a ^ b)"},{module:"bits",name:"bit_not",params:"a",returns:"number (bitwise NOT: ~a)"},{module:"bits",name:"bit_shl",params:"a n",returns:"number (shift left: a << n)"},{module:"bits",name:"bit_shr",params:"a n",returns:"number (unsigned right shift: a >>> n)"},{module:"bits",name:"bit_sar",params:"a n",returns:"number (arithmetic right shift: a >> n)"},{module:"bits",name:"bit_popcount",params:"a",returns:"number (count set bits)"},{module:"bits",name:"bit_test",params:"a n",returns:"boolean (test bit at position n)"},{module:"bits",name:"bit_set",params:"a n",returns:"number (set bit at position n)"},{module:"bits",name:"bit_clear",params:"a n",returns:"number (clear bit at position n)"},{module:"bits",name:"bit_rotate_left",params:"a n",returns:"number (rotate left: (a << n) | (a >>> (32-n)))"},{module:"bits",name:"bit_rotate_right",params:"a n",returns:"number (rotate right: (a >>> n) | (a << (32-n)))"},{module:"browser",name:"dom_select",params:"selector",returns:"Element | null"},{module:"browser",name:"dom_select_all",params:"selector",returns:"[Element]"},{module:"browser",name:"dom_by_id",params:"id",returns:"Element | null"},{module:"browser",name:"dom_text",params:"el",returns:"string"},{module:"browser",name:"dom_html",params:"el",returns:"string"},{module:"browser",name:"dom_attr",params:"el attr",returns:"string"},{module:"browser",name:"dom_val",params:"el",returns:"string (input value)"},{module:"browser",name:"dom_set_text",params:"el text",returns:"null"},{module:"browser",name:"dom_set_html",params:"el html",returns:"null"},{module:"browser",name:"dom_set_attr",params:"el attr value",returns:"null"},{module:"browser",name:"dom_set_val",params:"el value",returns:"null (input)"},{module:"browser",name:"dom_set_style",params:"el prop value",returns:"null"},{module:"browser",name:"dom_add_class",params:"el cls",returns:"null"},{module:"browser",name:"dom_remove_class",params:"el cls",returns:"null"},{module:"browser",name:"dom_toggle_class",params:"el cls",returns:"boolean"},{module:"browser",name:"dom_has_class",params:"el cls",returns:"boolean"},{module:"browser",name:"dom_create",params:"tag",returns:"Element"},{module:"browser",name:"dom_append",params:"parent child",returns:"null"},{module:"browser",name:"dom_prepend",params:"parent child",returns:"null"},{module:"browser",name:"dom_remove",params:"el",returns:"null"},{module:"browser",name:"dom_show",params:"el",returns:"null"},{module:"browser",name:"dom_hide",params:"el",returns:"null"},{module:"browser",name:"dom_toggle",params:"el",returns:"null"},{module:"browser",name:"event_on",params:"el event handlerName",returns:"null (FL \uD568\uC218\uBA85\uC73C\uB85C \uB4F1\uB85D)"},{module:"browser",name:"event_off",params:"el event handlerName",returns:"null"},{module:"browser",name:"event_target",params:"e",returns:"Element"},{module:"browser",name:"event_val",params:"e",returns:"string (input \uC774\uBCA4\uD2B8\uC5D0\uC11C \uAC12 \uCD94\uCD9C)"},{module:"browser",name:"event_prevent",params:"e",returns:"null"},{module:"browser",name:"event_stop",params:"e",returns:"null"},{module:"browser",name:"fetch_get",params:"url",returns:"{ok, status, data} (\uB3D9\uAE30 \uBD88\uAC00 \u2192 Promise \uBC18\uD658)"},{module:"browser",name:"fetch_post",params:"url body",returns:"{ok, status, data}"},{module:"browser",name:"fetch_put",params:"url body",returns:"{ok, status, data}"},{module:"browser",name:"fetch_delete",params:"url",returns:"{ok, status, data}"},{module:"browser",name:"storage_set",params:"key value",returns:"null"},{module:"browser",name:"storage_get",params:"key",returns:"string | null"},{module:"browser",name:"storage_remove",params:"key",returns:"null"},{module:"browser",name:"storage_clear",params:"",returns:"null"},{module:"browser",name:"browser_url",params:"",returns:"string"},{module:"browser",name:"browser_path",params:"",returns:"string"},{module:"browser",name:"browser_go",params:"url",returns:"null"},{module:"browser",name:"browser_push",params:"url",returns:"null (history API)"},{module:"browser",name:"browser_reload",params:"",returns:"null"},{module:"browser",name:"browser_alert",params:"msg",returns:"null"},{module:"browser",name:"browser_confirm",params:"msg",returns:"boolean"},{module:"browser",name:"browser_title",params:"",returns:"string"},{module:"browser",name:"browser_set_title",params:"title",returns:"null"},{module:"browser",name:"wcrypto_random_hex",params:"n",returns:"string (n \uBC14\uC774\uD2B8 hex)"},{module:"browser",name:"wcrypto_sha256",params:"str",returns:"Promise<string>"},{module:"browser",name:"browser_timeout",params:"ms handlerName",returns:"id"},{module:"browser",name:"browser_interval",params:"ms handlerName",returns:"id"},{module:"browser",name:"browser_clear_timer",params:"id",returns:"null"},{module:"capture-error",name:"capture_error_args",params:"fn args context?",returns:"{ok, result, error?}"},{module:"capture-error",name:"error_log",params:"",returns:"[{message, name, stack, timestamp, context?}, ...]"},{module:"capture-error",name:"error_log_clear",params:"",returns:"count cleared"},{module:"capture-error",name:"error_log_last",params:"n?",returns:"last n errors (default 10)"},{module:"capture-error",name:"error_count",params:"",returns:"number of captured errors"},{module:"capture-error",name:"make_error",params:"message name? code?",returns:"plain object"},{module:"capture-error",name:"error_message",params:"err",returns:"string"},{module:"capture-error",name:"error_stack",params:"err",returns:"[string]"},{module:"capture-error",name:"retry",params:"fn attempts delay_ms?",returns:"{ok, result, attempts_used, error?}"},{module:"collection",name:"arr_flatten",params:"arr",returns:"[any] (flatten one level deep)"},{module:"collection",name:"arr_flatten_deep",params:"arr",returns:"[any] (flatten all levels)"},{module:"collection",name:"arr_zip",params:"arr1 arr2",returns:"[[a,b]] (zip two arrays into pairs)"},{module:"collection",name:"arr_unique",params:"arr",returns:"[any] (deduplicate, preserves order)"},{module:"collection",name:"arr_chunk",params:"arr size",returns:"[[any]] (split into chunks of size)"},{module:"collection",name:"arr_take",params:"arr n",returns:"[any] (first n elements)"},{module:"collection",name:"arr_drop",params:"arr n",returns:"[any] (all but first n elements)"},{module:"collection",name:"arr_sum",params:"arr",returns:"number"},{module:"collection",name:"arr_avg",params:"arr",returns:"number"},{module:"collection",name:"arr_min",params:"arr",returns:"number"},{module:"collection",name:"arr_max",params:"arr",returns:"number"},{module:"collection",name:"arr_group_by",params:"arr key",returns:"{key: [items]} (group objects by a key)"},{module:"collection",name:"arr_sort_by",params:"arr key",returns:"[any] (sort objects by a key, ascending)"},{module:"collection",name:"arr_sort_by_desc",params:"arr key",returns:"[any] (descending)"},{module:"collection",name:"frequencies",params:"arr",returns:"{value: count} (count occurrences of each value)"},{module:"collection",name:"arr_count_by",params:"arr key",returns:"{key: count} (count by key value)"},{module:"collection",name:"arr_pluck",params:"arr key",returns:"[any] (extract field from each object)"},{module:"collection",name:"arr_index_by",params:"arr key",returns:"{key: item} (index objects by unique key)"},{module:"collection",name:"retry",params:"n fn",returns:"any (call fn(), retry up to n times on error)"},{module:"collection",name:"retry_silent",params:"n fn",returns:"any|null (retry n times, return null on final failure)"},{module:"collection",name:"memoize",params:"fn",returns:"fn (return memoized version of fn, keyed by JSON args)"},{module:"collection",name:"once",params:"fn",returns:"fn (return version of fn that only executes once)"},{module:"collection",name:"tap",params:"value fn",returns:"value (call fn(value) for side effects, return value unchanged)"},{module:"collection",name:"range",params:"start end",returns:"[number] (inclusive start, exclusive end)"},{module:"collection",name:"range_step",params:"start end step",returns:"[number]"},{module:"collection",name:"repeat",params:"n value",returns:"[value] (array of n copies of value)"},{module:"collection",name:"arr_includes",params:"arr item",returns:"boolean (deep equality check)"},{module:"collection",name:"arr_index_of",params:"arr item",returns:"number (-1 if not found)"},{module:"collection",name:"arr_remove",params:"arr item",returns:"[any] (remove first occurrence)"},{module:"crypto-rsa",name:"crypto_rsa_generate",params:"bits",returns:"map (publicKey/privateKey PEM)"},{module:"crypto-rsa",name:"crypto_rsa_sign",params:"private_pem data",returns:"string (base64url \uC11C\uBA85)"},{module:"crypto-rsa",name:"crypto_rsa_verify",params:"public_pem data signature_b64url",returns:"boolean"},{module:"crypto-rsa",name:"pkce_s256",params:"verifier",returns:"string (PKCE S256 challenge: base64url(SHA256(verifier_bytes)))"},{module:"crypto-rsa",name:"crypto_rsa_public_to_jwk",params:"public_pem kid",returns:"map (kty/n/e/kid/alg/use)"},{module:"crypto",name:"sha256",params:"str",returns:"string (hex digest)"},{module:"crypto",name:"sha256_short",params:"str",returns:"string (first 8 chars, useful as short ID)"},{module:"crypto",name:"md5",params:"str",returns:"string (hex digest, for checksums only)"},{module:"crypto",name:"sha1",params:"str",returns:"string"},{module:"crypto",name:"hmac_sha256",params:"key msg",returns:"string (hex digest)"},{module:"crypto",name:"hash_eq",params:"hash1 hash2",returns:"boolean (timing-safe compare)"},{module:"crypto",name:"base64_encode",params:"str",returns:"string"},{module:"crypto",name:"base64_decode",params:"str",returns:"string"},{module:"crypto",name:"base64url_encode",params:"str",returns:"string (URL-safe, no padding)"},{module:"crypto",name:"base64url_decode",params:"str",returns:"string (URL-safe Base64 \u2192 UTF-8)"},{module:"crypto",name:"hex_encode",params:"str",returns:"string"},{module:"crypto",name:"hex_decode",params:"hex",returns:"string"},{module:"crypto",name:"random_bytes",params:"n",returns:"string (hex, n bytes of randomness)"},{module:"crypto",name:"random_int",params:"min max",returns:"number (inclusive)"},{module:"crypto",name:"random_float",params:"",returns:"number (0.0 - 1.0)"},{module:"crypto",name:"uuid_v4",params:"",returns:"string (random UUID)"},{module:"crypto",name:"uuid_short",params:"",returns:"string (8-char short ID from random bytes)"},{module:"crypto",name:"uuid_from_str",params:"str",returns:"string (deterministic ID from string content)"},{module:"crypto",name:"is_uuid",params:"str",returns:"boolean"},{module:"crypto",name:"regex_match",params:"str pattern",returns:"boolean"},{module:"crypto",name:"regex_match_i",params:"str pattern",returns:"boolean (case insensitive)"},{module:"crypto",name:"regex_find",params:"str pattern",returns:"string|null (first match)"},{module:"crypto",name:"regex_find_all",params:"str pattern",returns:"[string] (all non-overlapping matches)"},{module:"crypto",name:"regex_replace",params:"str pattern replacement",returns:"string"},{module:"crypto",name:"regex_replace_first",params:"str pattern replacement",returns:"string (only first match)"},{module:"crypto",name:"regex_extract",params:"str pattern",returns:"[string] (capture groups of first match)"},{module:"crypto",name:"regex_extract_all",params:"str pattern",returns:"[[string]] (all matches with groups)"},{module:"crypto",name:"regex_split",params:"str pattern",returns:"[string]"},{module:"crypto",name:"regex_count",params:"str pattern",returns:"number (count of matches)"},{module:"crypto",name:"extract_json",params:"str",returns:"any|null (extract first JSON object/array from text)"},{module:"crypto",name:"extract_code",params:"str lang",returns:"string|null (extract code block from markdown)"},{module:"crypto",name:"extract_emails",params:"str",returns:"[string]"},{module:"crypto",name:"extract_urls",params:"str",returns:"[string]"},{module:"crypto",name:"extract_numbers",params:"str",returns:"[number]"},{module:"crypto",name:"is_email",params:"str",returns:"boolean"},{module:"crypto",name:"is_url",params:"str",returns:"boolean"},{module:"data",name:"json_get",params:"obj path",returns:'any (dot-path access: "user.name" or "items.0")'},{module:"data",name:"json_set",params:"obj path value",returns:"object (immutable update, returns new obj)"},{module:"data",name:"json_merge",params:"obj1 obj2",returns:"object (shallow merge, obj2 wins on conflict)"},{module:"data",name:"json_deep_merge",params:"obj1 obj2",returns:"object (deep recursive merge)"},{module:"data",name:"json_keys",params:"obj",returns:"[string] (get keys of object)"},{module:"data",name:"json_vals",params:"obj",returns:"[any] (get values of object)"},{module:"data",name:"map-entries",params:"m",returns:"[[k,v],...] (introspection primitive \u2014 JS Map/plain object \uBAA8\uB450 \uC5F4\uAC70)"},{module:"data",name:"map_entries",params:"m",returns:"[[k,v],...] (alias for map-entries)"},{module:"data",name:"json_parse",params:"str",returns:"object (parse JSON string to object)"},{module:"data",name:"json_str",params:"obj",returns:"string (serialize to JSON string, handles Maps)"},{module:"data",name:"json_stringify",params:"obj",returns:"string (alias for json_str)"},{module:"data",name:"json_pretty",params:"obj",returns:"string (pretty-print JSON, handles Maps)"},{module:"data",name:"json_has",params:"obj key",returns:"boolean (check if key exists)"},{module:"data",name:"json_del",params:"obj key",returns:"object (delete key, returns new obj)"},{module:"data",name:"csv_parse",params:"str",returns:"[[string]] (parse CSV string to rows)"},{module:"data",name:"csv_write",params:"rows",returns:"string (serialize rows to CSV string)"},{module:"data",name:"csv_header",params:"rows",returns:"[string] (get first row as header)"},{module:"data",name:"csv_to_objects",params:"rows",returns:"[{header: value}] (rows to named objects)"},{module:"data",name:"csv-parse",params:"text [delimiter]",returns:"[[string]] (quoted fields \uC644\uC804 \uC9C0\uC6D0)"},{module:"data",name:"csv-parse-map",params:"text [delimiter]",returns:"[{header: val}] (\uD5E4\uB354 \uD3EC\uD568 \uD30C\uC2F1)"},{module:"data",name:"csv-stringify",params:"rows [delimiter]",returns:"string"},{module:"data",name:"str_template",params:"template vars",returns:"string ({key} \u2192 value substitution)"},{module:"data",name:"str_lines",params:"str",returns:"[string] (split into lines)"},{module:"data",name:"str_join_lines",params:"lines",returns:"string"},{module:"data",name:"str_trim",params:"str",returns:"string"},{module:"data",name:"str_words",params:"str",returns:"[string] (split by whitespace)"},{module:"data",name:"str_count",params:"str sub",returns:"number (count occurrences of sub in str)"},{module:"data",name:"number_format",params:"num decimals",returns:'string (1234567 0 -> "1,234,567")'},{module:"data",name:"to_fixed",params:"num decimals",returns:'string (3.14159 2 -> "3.14")'},{module:"data",name:"format_currency",params:"num code",returns:'string (1234567 "KRW" -> "\u20A91,234,567")'},{module:"data",name:"empty?",params:"x",returns:"boolean (\uBC30\uC5F4/\uBB38\uC790\uC5F4/\uAC1D\uCCB4/nil \uBAA8\uB450 \uC9C0\uC6D0)"},{module:"data",name:"array-empty?",params:"x",returns:"boolean (\uBC30\uC5F4\uB9CC \uD655\uC778)"},{module:"data",name:"str_replace_in",params:"s old new",returns:"string (replaceAll, \uC778\uC790 \uC21C\uC11C: s \uBA3C\uC800)"},{module:"db",name:"db_get",params:"collection id",returns:"data or null"},{module:"db",name:"db_all",params:"collection",returns:"array"},{module:"db",name:"db_put",params:"collection id data",returns:"saved data"},{module:"db",name:"db_delete",params:"collection id",returns:"boolean"},{module:"db",name:"db_project",params:"name",returns:"project data or null (kimdb shorthand)"},{module:"db",name:"db_projects",params:"",returns:"project list"},{module:"db",name:"db_insert",params:"dbPath table data",returns:"true"},{module:"db",name:"db_update",params:"dbPath table data where",returns:"true"},{module:"db",name:"db_delete_row",params:"dbPath table where",returns:"true"},{module:"db",name:"db_count",params:"dbPath table",returns:"number"},{module:"db",name:"db_tables",params:"dbPath",returns:"string[]"},{module:"db",name:"db_create",params:"dbPath sql",returns:"true (CREATE TABLE ...)"},{module:"db",name:"db_close",params:"dbPath",returns:"true"},{module:"distributed",name:"distributed_execute",params:"dtask",returns:"DistributedResult"},{module:"distributed",name:"distributed_task_create",params:"items worker_count",returns:"DistributedTask"},{module:"distributed",name:"distributed_task_set_fn",params:"dtask fn",returns:"DistributedTask (set task function)"},{module:"error",name:"error_message",params:"err",returns:"string (get error message)"},{module:"error",name:"error_type",params:"err",returns:"string (get error type/name)"},{module:"error",name:"is_error",params:"value",returns:"boolean (check if value is an error)"},{module:"error",name:"create_error",params:"message",returns:"error (create an error object)"},{module:"error",name:"create_typed_error",params:"type message",returns:"error (create a typed error)"},{module:"error",name:"error_stack",params:"err",returns:"string (get error stack trace)"},{module:"error",name:"with_fallback",params:"try_fn fallback_fn",returns:"any (execute try_fn, fallback on error)"},{module:"fd",name:"fd_open",params:"path mode",returns:"number (fd, mode: r/w/a)"},{module:"fd",name:"fd_write",params:"fd data",returns:"boolean (write data to file descriptor)"},{module:"fd",name:"fd_fsync",params:"fd",returns:"boolean (flush file descriptor to disk)"},{module:"fd",name:"fd_close",params:"fd",returns:"boolean (close file descriptor)"},{module:"fd",name:"fd_read",params:"fd bytes",returns:"string (read bytes from file descriptor)"},{module:"fd",name:"fd_seek",params:"fd offset whence",returns:"number (whence: 0/1/2)"},{module:"fd",name:"fd_flush",params:"",returns:"boolean (flush all open fds)"},{module:"feed",name:"rss_feed",params:"meta items",returns:"<?xml ... <rss>...</rss>"},{module:"feed",name:"atom_feed",params:"meta items",returns:"<?xml ... <feed>...</feed>"},{module:"feed",name:"sitemap_xml",params:"baseUrl routes",returns:"<?xml ... <urlset>..."},{module:"feed",name:"robots_txt",params:"options",returns:'"User-agent: * ..."'},{module:"feed",name:"jsonld_article",params:"article",returns:'<script type="application/ld+json">...</script>'},{module:"feed",name:"jsonld_breadcrumb",params:"items",returns:"schema.org BreadcrumbList"},{module:"feed",name:"jsonld_organization",params:"org",returns:"schema.org Organization"},{module:"file",name:"file_read",params:"filePath",returns:"string (read file content)"},{module:"file",name:"file_write",params:"filePath content",returns:"boolean (write content to file)"},{module:"file",name:"file_exists",params:"filePath",returns:"boolean (check if file exists)"},{module:"file",name:"file_delete",params:"filePath",returns:"boolean (delete file)"},{module:"file",name:"file_append",params:"filePath content",returns:"boolean (append content to file)"},{module:"file",name:"file_copy",params:"src dest",returns:"boolean (copy file)"},{module:"file",name:"dir_create",params:"dirPath",returns:"boolean (create directory)"},{module:"file",name:"dir_list",params:"dirPath",returns:"[string] (list directory contents)"},{module:"file",name:"dir_delete",params:"dirPath",returns:"boolean (delete directory - must be empty)"},{module:"file",name:"file_size",params:"filePath",returns:"number (get file size in bytes)"},{module:"file",name:"file_is_file",params:"filePath",returns:"boolean (check if path is a file)"},{module:"file",name:"file_is_dir",params:"filePath",returns:"boolean (check if path is a directory)"},{module:"file",name:"file_mtime",params:"filePath",returns:"number (get modification time as timestamp)"},{module:"file",name:"file_ctime",params:"filePath",returns:"number (get creation time as timestamp)"},{module:"file",name:"file_read_or",params:"filePath defaultVal",returns:"string | any (\uD30C\uC77C \uC5C6\uAC70\uB098 \uC624\uB958 \uC2DC \uAE30\uBCF8\uAC12 \uBC18\uD658)"},{module:"http-macro",name:"http_get_json",params:"url headers?",returns:"{ok, status, body}"},{module:"http-macro",name:"http_post_json",params:"url body headers?",returns:"{ok, status, body}"},{module:"http-macro",name:"http_ok?",params:"result",returns:"boolean"},{module:"http-macro",name:"http_body",params:"result",returns:"parsed body or null"},{module:"http-macro",name:"http_status",params:"result",returns:"number"},{module:"http-server",name:"server_get",params:"path handlerName",returns:"null"},{module:"http-server",name:"server_post",params:"path handlerName",returns:"null"},{module:"http-server",name:"server_put",params:"path handlerName",returns:"null"},{module:"http-server",name:"server_patch",params:"path handlerName",returns:"null"},{module:"http-server",name:"server_delete",params:"path handlerName",returns:"null"},{module:"http-server",name:"server_static",params:"dir [urlPrefix]",returns:'null \uC815\uC801 \uD30C\uC77C \uC11C\uBE59 (server-static "public" "/")'},{module:"http-server",name:"server_stop",params:"",returns:"null"},{module:"http-server",name:"server_text",params:"text",returns:"response object"},{module:"http-server",name:"server_status",params:"code body",returns:"response object"},{module:"http-server",name:"server_html_cookie",params:"cookie html",returns:"response (Set-Cookie \uD5E4\uB354 \uD3EC\uD568 HTML \uC751\uB2F5)"},{module:"http-server",name:"server_set_cookie",params:"name value opts",returns:"cookie string (HttpOnly+Secure+SameSite \uC790\uB3D9)"},{module:"http-server",name:"server_redirect",params:"url",returns:"response (302 \uB9AC\uB2E4\uC774\uB809\uD2B8)"},{module:"http-server",name:"server_redirect_cookie",params:"url cookie",returns:"response (302 \uB9AC\uB2E4\uC774\uB809\uD2B8 + Set-Cookie)"},{module:"http-server",name:"server_header",params:"response key value",returns:"response (\uD5E4\uB354 \uCD94\uAC00)"},{module:"http-server",name:"server_options",params:"response",returns:"204 No Content (CORS preflight \uC751\uB2F5)"},{module:"http-server",name:"server_req_cookie",params:"req name",returns:"string | null (\uCFE0\uD0A4 \uAC12 \uC77D\uAE30)"},{module:"http-server",name:"server_wait_respond",params:"promise",returns:"response object (\uBE44\uB3D9\uAE30 \uC751\uB2F5 \uB300\uAE30)"},{module:"http-server",name:"server_req_query",params:"req [key]",returns:"object or string"},{module:"http-server",name:"server_req_files",params:"req",returns:"array of multipart files"},{module:"http-server",name:"server_req_fields",params:"req",returns:"map of multipart text fields"},{module:"http-server",name:"server_req_header",params:"req name",returns:"string"},{module:"http-server",name:"server_req_headers",params:"req",returns:"object (\uC804\uCCB4 \uD5E4\uB354 \uB9F5)"},{module:"http-server",name:"server_req_param",params:"req name",returns:"string"},{module:"http-server",name:"server_req_params",params:"req",returns:"object (all URL params as an object)"},{module:"http-server",name:"server_req_method",params:"req",returns:"string"},{module:"http-server",name:"server_req_path",params:"req",returns:"string"},{module:"http-server",name:"server_req_id",params:"",returns:"string | null (\uD604\uC7AC \uC694\uCCAD ID)"},{module:"http-server",name:"server_hold_response",params:"reqId",returns:"null (\uC751\uB2F5 \uBCF4\uB958)"},{module:"http-server",name:"server_send_held",params:"reqId status body",returns:"boolean (\uBCF4\uB958\uB41C \uC751\uB2F5 \uC804\uC1A1)"},{module:"http-server",name:"server_on_upgrade",params:"fnName",returns:"null (WS upgrade \uD578\uB4E4\uB7EC \uB4F1\uB85D)"},{module:"http-server",name:"server_on_ws_message",params:"fnName",returns:"null (\uD074\uB77C\uC774\uC5B8\uD2B8 WS \uBA54\uC2DC\uC9C0 \uD578\uB4E4\uB7EC)"},{module:"http-server",name:"server_on_ws_close",params:"fnName",returns:"null (\uD074\uB77C\uC774\uC5B8\uD2B8 WS \uC885\uB8CC \uD578\uB4E4\uB7EC)"},{module:"http-server",name:"ws_send_to_client",params:"sessionId data [isBinary]",returns:"boolean"},{module:"http-server",name:"ws_close_client",params:"sessionId [code]",returns:"null"},{module:"http-server",name:"server_req_session_id",params:"req",returns:"string | null"},{module:"http",name:"http_get",params:"url",returns:'{:status 200 :body "..."}'},{module:"http",name:"http_post",params:"url body",returns:'{:status 200 :body "..."}'},{module:"http",name:"http_post_form",params:"url body",returns:'{:status 200 :body "..."}'},{module:"http",name:"http_get_bearer",params:"url token",returns:'{:status 200 :body "..."}'},{module:"http",name:"http_put",params:"url body",returns:'{:status 200 :body "..."}'},{module:"http",name:"http_patch",params:"url body",returns:'{:status 200 :body "..."}'},{module:"http",name:"http_delete",params:"url",returns:'{:status 200 :body "..."}'},{module:"http",name:"http_head",params:"url",returns:'{:status 200 :body ""}'},{module:"http",name:"http_get_key",params:"url api-key",returns:'{:status 200 :body "..."}'},{module:"http",name:"http_post_key",params:"url body api-key",returns:'{:status 200 :body "..."}'},{module:"http",name:"http_status",params:"url",returns:"number (\uC0C1\uD0DC\uCF54\uB4DC\uB9CC)"},{module:"http",name:"http_json",params:"url",returns:"{:status 200 :data {...} :error nil}"},{module:"http",name:"http_header",params:"url header",returns:"string (\uD2B9\uC815 \uD5E4\uB354\uB9CC)"},{module:"http",name:"http_with_timeout",params:"url timeout",returns:'{:status 200 :body "..."}'},{module:"http",name:"http_post_json",params:"url data",returns:"{:status 200 :data {...}}"},{module:"http",name:"http_put_json",params:"url data",returns:"{:status 200 :data {...}}"},{module:"http",name:"http_request",params:"method url headers body",returns:'{:status 200 :body "..."}'},{module:"http",name:"http_req_status",params:"method url headers body",returns:"number"},{module:"http",name:"http_get_json",params:"url headers",returns:"{:status 200 :data {...}}"},{module:"http",name:"http_get_json_bearer",params:"url token",returns:"{:status 200 :data {...}}"},{module:"http",name:"http_post_bearer",params:"url body token",returns:'{:status 200 :body "..."}'},{module:"http",name:"http_retry_post",params:"url body token retries",returns:'{:status 200 :body "..."}'},{module:"http",name:"is_http_success",params:"status",returns:"boolean"},{module:"http",name:"is_http_redirect",params:"status",returns:"boolean"},{module:"http",name:"is_http_error",params:"status",returns:"boolean"},{module:"http",name:"http-post-data",params:"url data",returns:"parsed JSON data | nil (#12 \uD574\uACB0)"},{module:"mail",name:"mail_outbox_write",params:"dir to subject body",returns:"string (\uD30C\uC77C \uACBD\uB85C)"},{module:"mail",name:"mail_outbox_list",params:"dir",returns:"array (JSON \uBC30\uC5F4, \uD050\uB41C \uBA54\uC2DC\uC9C0)"},{module:"mail",name:"mail_outbox_count",params:"dir",returns:"number"},{module:"markdown",name:"markdown_to_html",params:"md",returns:"html string"},{module:"markdown",name:"markdown_frontmatter",params:"md",returns:'{ fm: {...}, body: "..." }'},{module:"markdown",name:"markdown_render_full",params:"md",returns:"{ fm, html }"},{module:"matrix",name:"matrix_mul",params:"A B",returns:"[[number]] (matrix multiplication)"},{module:"matrix",name:"matrix_transpose",params:"A",returns:"[[number]] (transpose matrix)"},{module:"matrix",name:"vector_dot",params:"u v",returns:"number (dot product)"},{module:"matrix",name:"vector_add",params:"u v",returns:"[number] (vector addition)"},{module:"matrix",name:"vector_sub",params:"u v",returns:"[number] (vector subtraction)"},{module:"matrix",name:"vector_scale",params:"v s",returns:"[number] (scalar multiplication)"},{module:"matrix",name:"vector_norm",params:"v",returns:"number (Euclidean norm / L2 norm)"},{module:"matrix",name:"matrix_zeros",params:"rows cols",returns:"[[number]] (create zero matrix)"},{module:"matrix",name:"vector_zeros",params:"n",returns:"[number] (create zero vector)"},{module:"optional",name:"require_optional",params:"modName",returns:"true/false (\uC124\uCE58 \uC5EC\uBD80)"},{module:"optional",name:"optional_call",params:"modName fnPath args",returns:"result or throws"},{module:"optional",name:"optional_has?",params:"modName",returns:"boolean"},{module:"optional",name:"optional_version",params:"modName",returns:"string or nil"},{module:"perf",name:"profile_fn",params:"fn count",returns:"PerfResult"},{module:"perf",name:"trace_expr",params:"fn label",returns:"TraceResult"},{module:"perf",name:"perf_stats",params:"",returns:"PerfStats"},{module:"perf",name:"now_ms",params:"",returns:"number"},{module:"perf",name:"elapsed_ms",params:"start",returns:"number"},{module:"perf",name:"bench",params:"fn iterations",returns:"{ms, ops_per_sec}"},{module:"perf",name:"time_fn",params:"fn args...",returns:"{result, ms}"},{module:"process",name:"shell_exec_stdout",params:"cmd cwd?",returns:"string | null (stdout\uB9CC \uBC18\uD658, \uC2E4\uD328 \uC2DC null)"},{module:"queue-helpers",name:"queue_db_init",params:"db_path",returns:"bool (WAL \uBAA8\uB4DC + busy_timeout \uD65C\uC131\uD654)"},{module:"resource",name:"res_cpu_load",params:"",returns:"[1m, 5m, 15m]"},{module:"resource",name:"res_cpu_count",params:"",returns:"number"},{module:"resource",name:"res_cpu_model",params:"",returns:"string"},{module:"resource",name:"res_cpu_pct",params:"",returns:"number (1-min loadavg based, avoids busy wait)"},{module:"resource",name:"res_mem",params:"",returns:"{total_mb, used_mb, free_mb, buffers_mb, cached_mb, available_mb}"},{module:"resource",name:"res_mem_pct",params:"",returns:"number (used %)"},{module:"resource",name:"res_disk",params:"",returns:"DiskInfo[]"},{module:"resource",name:"res_disk_usage",params:"path",returns:"{total_gb, used_gb, avail_gb, use_pct}"},{module:"resource",name:"res_procs",params:"",returns:"ProcessInfo[] (top 20 by CPU)"},{module:"resource",name:"res_find_proc",params:"name",returns:"ProcessInfo[] (search by name substring)"},{module:"resource",name:"res_proc_exists",params:"name",returns:"boolean"},{module:"resource",name:"res_proc_pid",params:"name",returns:"number | null"},{module:"resource",name:"res_proc_count",params:"name",returns:"number (how many instances running)"},{module:"resource",name:"res_ports",params:"",returns:"PortInfo[] (all listening ports)"},{module:"resource",name:"res_port_used",params:"port",returns:"boolean"},{module:"resource",name:"res_port_info",params:"port",returns:"PortInfo | null"},{module:"resource",name:"res_find_free_port",params:"start end",returns:"number | null (first free port in range)"},{module:"resource",name:"res_net",params:"",returns:"NetInterface[]"},{module:"resource",name:"res_hostname",params:"",returns:"string"},{module:"resource",name:"res_uptime_s",params:"",returns:"number (system uptime in seconds)"},{module:"resource",name:"res_pm2_list",params:"",returns:"ServiceInfo[]"},{module:"resource",name:"res_pm2_find",params:"name",returns:"ServiceInfo | null"},{module:"resource",name:"res_systemd_status",params:"name",returns:"ServiceInfo"},{module:"resource",name:"res_kimdb_project",params:"name",returns:"Record | null (query local kimdb)"},{module:"resource",name:"res_kimdb_projects",params:"",returns:"Record[] (all projects)"},{module:"resource",name:"res_kimdb_health",params:"",returns:"boolean"},{module:"resource",name:"res_snapshot",params:"",returns:"ResourceSnapshot (complete server state, ~1s)"},{module:"resource",name:"res_snapshot_report",params:"snapshot",returns:"string (human/AI readable)"},{module:"resource",name:"res_health_check",params:"",returns:"{ok, warnings, errors}"},{module:"rest-crud",name:"route_info",params:"basePath",returns:"{base, param_name, supported_ops: [...]}"},{module:"rest-crud",name:"path_param",params:"req paramName",returns:"string or nil"},{module:"rest-crud",name:"rest_response",params:"status body",returns:"Map"},{module:"rest-crud",name:"rest_ok",params:"body",returns:"Map (200)"},{module:"rest-crud",name:"rest_created",params:"body",returns:"Map (201)"},{module:"rest-crud",name:"rest_not_found",params:"msg",returns:"Map (404)"},{module:"rest-crud",name:"rest_error",params:"status msg",returns:"Map"},{module:"shell",name:"shell",params:"cmd",returns:"string (run command, return stdout)"},{module:"shell",name:"shell_status",params:"cmd",returns:"number (run command, return exit code)"},{module:"shell",name:"shell_ok",params:"cmd",returns:"boolean (returns true if exit code is 0)"},{module:"shell",name:"shell_pipe",params:"cmd1 cmd2",returns:"string (pipe output of cmd1 into cmd2)"},{module:"shell",name:"shell_capture",params:"cmd",returns:"{stdout, stderr, code} (capture all output)"},{module:"shell",name:"shell_exists",params:"program",returns:"boolean (check if a program is in PATH)"},{module:"shell",name:"shell_env",params:"varname",returns:"string | null (\uD658\uACBD\uBCC0\uC218 \uC5C6\uC73C\uBA74 null)"},{module:"shell",name:"shell_cwd",params:"",returns:"string (current working directory)"},{module:"time",name:"now",params:"",returns:"number (current timestamp ms)"},{module:"time",name:"now_ms",params:"",returns:"number (ms since epoch, always returns number)"},{module:"time",name:"now_iso",params:"",returns:"string (ISO 8601)"},{module:"time",name:"now_unix",params:"",returns:"number (seconds since epoch)"},{module:"time",name:"time_diff",params:"t1 t2",returns:"number (ms, positive if t2 > t1)"},{module:"time",name:"time_since",params:"ts",returns:"number (ms elapsed since ts)"},{module:"time",name:"time_ago",params:"ts",returns:'string (human-readable: "3s ago", "2m ago", "1h ago")'},{module:"time",name:"date_parts",params:"ts",returns:"{year,month,day,hour,min,sec,ms,weekday}"},{module:"time",name:"date_add",params:"ts unit n",returns:'number (unit: "ms"|"s"|"m"|"h"|"d"|"days"|"hours"|"minutes"|"months"|"years"|"weeks"|"seconds")'},{module:"time",name:"date_parse",params:"str",returns:'number ("2026-04-23" | "2026-04-23T12:00:00Z" -> timestamp ms)'},{module:"time",name:"sleep_ms",params:"ms",returns:"void (synchronous spin-wait, short durations only)"},{module:"time",name:"timer_start",params:"label",returns:"Timer"},{module:"time",name:"timer_lap",params:"timer label",returns:"Timer (record a lap time)"},{module:"time",name:"timer_elapsed",params:"timer",returns:"number (ms since start)"},{module:"time",name:"timer_stop",params:"timer",returns:"{label, total_ms, laps}"},{module:"time",name:"log_create",params:"name level",returns:"Logger (level = minimum level to record)"},{module:"time",name:"log_entry",params:"logger level msg data?",returns:"Logger"},{module:"time",name:"log_info",params:"logger msg",returns:"Logger"},{module:"time",name:"log_warn",params:"logger msg",returns:"Logger"},{module:"time",name:"log_error",params:"logger msg",returns:"Logger"},{module:"time",name:"log_debug",params:"logger msg",returns:"Logger"},{module:"time",name:"log_filter",params:"logger level",returns:"[LogEntry] (entries at or above level)"},{module:"time",name:"log_count",params:"logger level",returns:"number"},{module:"time",name:"log_last",params:"logger n",returns:"[LogEntry]"},{module:"time",name:"log_dump",params:"logger",returns:"void (print all entries to stdout)"},{module:"time",name:"metrics_create",params:"name",returns:"Metrics"},{module:"time",name:"metrics_record",params:"metrics key value",returns:"Metrics"},{module:"time",name:"metrics_inc",params:"metrics key",returns:"Metrics (increment counter by 1)"},{module:"time",name:"metrics_inc_by",params:"metrics key n",returns:"Metrics"},{module:"time",name:"metrics_count",params:"metrics key",returns:"number"},{module:"time",name:"metrics_avg",params:"metrics key",returns:"number"},{module:"time",name:"metrics_min",params:"metrics key",returns:"number"},{module:"time",name:"metrics_max",params:"metrics key",returns:"number"},{module:"time",name:"metrics_p95",params:"metrics key",returns:"number (95th percentile)"},{module:"time",name:"metrics_summary",params:"metrics",returns:"{key: {count, avg, min, max}}"},{module:"timer",name:"set_interval",params:"fn ms",returns:"number (fn: function name string, ms: interval)"},{module:"timer",name:"clear_interval",params:"timerId",returns:"boolean (stop periodic timer)"},{module:"timer",name:"set_timeout",params:"fn ms",returns:"number (fn: function name string, ms: delay)"},{module:"timer",name:"clear_timeout",params:"timerId",returns:"boolean (cancel one-time timer)"},{module:"timer",name:"timer_count",params:"",returns:"number (returns count of active timers)"},{module:"timer",name:"timer_clear_all",params:"",returns:"boolean (clear all active timers)"},{module:"totp",name:"totp_secret_generate",params:"bytes",returns:"string (base32, default 20 bytes = 160 bits = 32 chars)"},{module:"totp",name:"totp_now",params:"secret_b32",returns:"string (\uD604\uC7AC \uC2DC\uAC01\uC758 6\uC790\uB9AC \uCF54\uB4DC, \uB514\uBC84\uADF8\xB7\uB4F1\uB85D\uC6A9)"},{module:"totp",name:"totp_uri",params:"label issuer secret_b32",returns:"string (otpauth://totp/... QR \uCF54\uB4DC \uD45C\uC900)"},{module:"verify",name:"check_parens",params:"code",returns:"VerifyResult"},{module:"verify",name:"verify_code",params:"code",returns:"{valid, error_count, first_error}"},{module:"verify",name:"fix_parens",params:"code",returns:"\uC790\uB3D9 \uC218\uC815\uB41C \uCF54\uB4DC (or original if already valid)"},{module:"verify",name:"count_parens",params:"code",returns:"{open, close, balanced}"},{module:"webauthn",name:"webauthn_challenge",params:"bytes",returns:"base64url string (32 bytes)"},{module:"workflow",name:"workflow_create",params:"name steps",returns:"Workflow object"},{module:"workflow",name:"workflow_step",params:"name fn options",returns:"WorkflowStep (helper for defining steps)"},{module:"workflow",name:"step-with-error",params:"step handler-fn",returns:"WorkflowStep (add error handler)"},{module:"workflow",name:"step-with-fallback",params:"step value-or-fn",returns:"WorkflowStep (add fallback)"},{module:"workflow",name:"step-with-timeout",params:"step ms",returns:"WorkflowStep (add timeout)"},{module:"workflow",name:"step-when",params:"step condition-fn",returns:"WorkflowStep (add conditional)"},{module:"workflow",name:"workflow_ok",params:"result",returns:"boolean"},{module:"workflow",name:"workflow_get",params:"result key",returns:"any (get value from result context)"},{module:"workflow",name:"workflow_summary",params:"result",returns:"string (human/AI readable summary)"},{module:"workflow",name:"task_create",params:"goal",returns:"Task"},{module:"workflow",name:"task_add_subtask",params:"task name",returns:"task"},{module:"workflow",name:"task_complete_subtask",params:"task name result",returns:"task"},{module:"workflow",name:"task_finish",params:"task result",returns:"task"},{module:"workflow",name:"task_progress",params:"task",returns:"number (0.0-1.0)"},{module:"workflow",name:"report_create",params:"title",returns:"Report"},{module:"workflow",name:"report_add",params:"report section_name data",returns:"Report"},{module:"workflow",name:"report_render",params:"report",returns:"string (formatted text report)"}]});var Ki={};on(Ki,{DebugSession:()=>Wn,getGlobalDebugSession:()=>Wi,handleBreak:()=>Gi,setGlobalDebugSession:()=>Hi});function Wi(){return na||(na=new Wn),na}function Hi(r){na=r}function Gi(r,t,e){r.enabled&&r.onBreak(t,e)}var Wn,na,Br=gt(()=>{Wn=class r{constructor(){this.breakpoints=new Set;this.stepMode=!1;this.enabled=!1;this.onBreakCallback=null;this.sourceMap=null;this.breakLog=[];this.watchList=new Set;this.callStack=[]}static _key(t,e){return`${t}:${e}`}addBreakpoint(t,e){this.breakpoints.add(r._key(t,e))}removeBreakpoint(t,e){this.breakpoints.delete(r._key(t,e))}isBreakpoint(t,e){return this.breakpoints.has(r._key(t,e))}onBreak(t,e){if(!this.enabled)return;let n={loc:t,env:{...e}};this.breakLog.push(n);let s=`${t.file}:${t.line}:${t.col}`;if(console.log(`[BREAK] ${s}`),this.callStack.length>0&&console.log(` stack: [${this.callStack.join(" > ")}]`),this.watchList.size>0){let i=this.getWatchValues(e);if(Object.keys(i).length>0){console.log(" \u{1F441} watch:");for(let[u,f]of Object.entries(i)){let l=typeof f=="object"?JSON.stringify(f):String(f);console.log(` ${u} = ${l.slice(0,80)}`)}}}let a=Object.entries(e).slice(0,10);if(a.length>0){console.log(" env:");for(let[i,o]of a){let u=typeof o=="object"?JSON.stringify(o):String(o);console.log(` ${i} = ${u.slice(0,80)}`)}}this.onBreakCallback&&this.onBreakCallback(n)}clearBreakpoints(){this.breakpoints.clear()}breakpointCount(){return this.breakpoints.size}addWatch(t){this.watchList.add(t)}removeWatch(t){this.watchList.delete(t)}getWatchValues(t){let e={};for(let n of this.watchList)n in t?e[n]=t[n]:e[n]=void 0;return e}pushCall(t){this.callStack.push(t)}popCall(){this.callStack.length>0&&this.callStack.pop()}getStack(){return[...this.callStack]}},na=null});var bp={};on(bp,{ALL_RULES:()=>yp,arityCheck:()=>mp,deadCode:()=>hp,emptyBody:()=>dp,getRuleByName:()=>ab,shadowedVars:()=>fp,undefinedVars:()=>up,unreachableMatch:()=>gp,unusedBindings:()=>pp});function lp(r){let t=r.fields.get("params");if(!t)return[];let e=Array.isArray(t)?t:[t];if(e.length===1&&e[0].kind==="block"&&e[0].type==="Array"){let n=e[0].fields?.get("items");if(!Array.isArray(n))return[];let s=[];for(let a of n)if(a.kind==="variable")s.push(a.name);else if(a.kind==="block"&&a.type==="Array"){let i=a.fields?.get("items");i&&i[0]?.kind==="variable"&&s.push(i[0].name)}return s}return e.filter(n=>n.kind==="variable").map(n=>n.name)}function to(r){let t=r.fields.get("body");return t?Array.isArray(t)?t:[t]:[]}function sb(r){let t=[];return ee(r,e=>{if(e.kind==="sexpr"&&(e.op==="let"||e.op==="let*"||e.op==="letrec")&&e.args.length>=1){let n=e.args[0];if(n.kind==="block"&&n.type==="Array"){let s=n.fields.get("items");if(Array.isArray(s))for(let a of s)if(a.kind==="block"&&a.type==="Array"){let i=a.fields.get("items");Array.isArray(i)&&i[0]?.kind==="variable"&&t.push({name:i[0].name})}else a.kind==="variable"&&t.push({name:a.name})}}}),t}function ab(r){return yp.find(t=>t.name===r)}var up,pp,fp,mp,dp,gp,hp,yp,kp=gt(()=>{no();up={name:"undefined-vars",check(r,t){let e=[],n=new Set(t.variables);for(let s of t.functions)n.add("$"+s),n.add(s);for(let s of r)if(s.kind==="block"&&s.type==="FUNC"){let a=new Set(n);for(let o of lp(s))a.add(o);let i=to(s);for(let o of sb(i))a.add(o.name);ee(i,o=>{o.kind==="sexpr"&&o.op==="define"&&o.args[0]?.kind==="variable"&&a.add(o.args[0].name)}),ee(i,o=>{if(o.kind==="variable"){let u=o.name,f=u.startsWith("$")?u.slice(1):u;!a.has(u)&&!a.has(f)&&!a.has("$"+f)&&e.push({rule:"undefined-vars",severity:"warn",message:`\uBBF8\uC815\uC758 \uBCC0\uC218 \uCC38\uC870: ${u} (FUNC ${s.name} \uB0B4)`,line:s.line})}})}else s.kind==="sexpr"&&ee([s],a=>{if(a.kind==="variable"){let i=a.name,o=i.startsWith("$")?i.slice(1):i;!n.has(i)&&!n.has(o)&&!n.has("$"+o)&&!t.functions.has(o)&&e.push({rule:"undefined-vars",severity:"warn",message:`\uBBF8\uC815\uC758 \uBCC0\uC218 \uCC38\uC870: ${i}`})}});return e}},pp={name:"unused-bindings",check(r,t){let e=[];for(let n of r){if(n.kind!=="block"||n.type!=="FUNC")continue;let s=to(n),a=[];ee(s,u=>{if(u.kind==="sexpr"&&(u.op==="let"||u.op==="let*")&&u.args.length>=1){let f=u.args[0];if(f.kind==="block"&&f.type==="Array"){let l=f.fields.get("items");if(Array.isArray(l)){for(let c of l)if(c.kind==="block"&&c.type==="Array"){let p=c.fields.get("items");Array.isArray(p)&&p[0]?.kind==="variable"&&a.push({name:p[0].name})}}}}});let i=[];ee(s,u=>{u.kind==="sexpr"&&u.op==="define"&&u.args[0]?.kind==="variable"&&i.push({name:u.args[0].name})});let o=new Set;ee(s,u=>{u.kind==="variable"&&(o.add(u.name),o.add(u.name.replace(/^\$/,"")))});for(let u of a){let f=u.name.replace(/^\$/,""),l=0;ee(s,c=>{c.kind==="variable"&&c.name.replace(/^\$/,"")===f&&l++}),l<2&&e.push({rule:"unused-bindings",severity:"warn",message:`\uBBF8\uC0AC\uC6A9 let \uBC14\uC778\uB529: ${u.name} (FUNC ${n.name} \uB0B4)`})}for(let u of i){let f=u.name.replace(/^\$/,""),l=0;ee(s,c=>{c.kind==="variable"&&c.name.replace(/^\$/,"")===f&&l++}),l<2&&e.push({rule:"unused-bindings",severity:"warn",message:`\uBBF8\uC0AC\uC6A9 define \uBC14\uC778\uB529: ${u.name} (FUNC ${n.name} \uB0B4)`})}}return e}},fp={name:"shadowed-vars",check(r,t){let e=[];for(let n of r){if(n.kind!=="block"||n.type!=="FUNC")continue;let s=new Set(lp(n).map(i=>i.replace(/^\$/,""))),a=to(n);ee(a,i=>{if(i.kind==="sexpr"&&(i.op==="let"||i.op==="let*")&&i.args.length>=1){let o=i.args[0];if(o.kind==="block"&&o.type==="Array"){let u=o.fields.get("items");if(Array.isArray(u)){for(let f of u)if(f.kind==="block"&&f.type==="Array"){let l=f.fields.get("items");if(Array.isArray(l)&&l[0]?.kind==="variable"){let c=l[0].name.replace(/^\$/,"");s.has(c)&&e.push({rule:"shadowed-vars",severity:"warn",message:`\uBCC0\uC218 \uC100\uB3C4\uC789: $${c}\uB294 \uD30C\uB77C\uBBF8\uD130\uB97C \uB36E\uC5B4\uC501\uB2C8\uB2E4 (FUNC ${n.name})`})}}}}}});for(let i of s)(t.variables.has("$"+i)||t.variables.has(i))&&e.push({rule:"shadowed-vars",severity:"info",message:`\uD30C\uB77C\uBBF8\uD130 $${i}\uC774 \uC804\uC5ED \uBCC0\uC218\uB97C \uC100\uB3C4\uC789\uD569\uB2C8\uB2E4 (FUNC ${n.name})`})}return e}},mp={name:"arity-check",check(r,t){let e=[],n=new Set(["print","println","list","array","concat","str","+","-","*","/","and","or","do","begin","cond","if","let","let*","define","match","fn","map","filter","each","reduce","range"]);function s(a){if(a.kind!=="sexpr")return;let i=a.op;if(n.has(i))return;let o=t.funcArity.get(i);if(o===void 0)return;let u=a.args.length;u!==o&&e.push({rule:"arity-check",severity:"warn",message:`\uD568\uC218 ${i}: ${o}\uAC1C \uC778\uC790 \uD544\uC694, ${u}\uAC1C \uC804\uB2EC\uB428`,line:a.line});for(let f of a.args)f.kind==="sexpr"&&s(f)}return ee(r,a=>{a.kind==="sexpr"&&s(a)}),e}},dp={name:"empty-body",check(r,t){let e=[];for(let n of r){if(n.kind!=="block"||n.type!=="FUNC")continue;let s=n.fields.get("body"),a=!1;if(!s)a=!0;else if(Array.isArray(s)&&s.length===0)a=!0;else if(!Array.isArray(s)&&s.kind==="block"&&s.type==="Array"){let i=s.fields?.get("items");(!i||Array.isArray(i)&&i.length===0)&&(a=!0)}a&&e.push({rule:"empty-body",severity:"warn",message:`\uBE48 \uD568\uC218 \uBC14\uB514: FUNC ${n.name}`,line:n.line})}return e}},gp={name:"unreachable-match",check(r,t){let e=[];return ee(r,n=>{if(n.kind==="sexpr"&&n.op==="cond"){let s=!1;for(let a=0;a<n.args.length;a++){let i=n.args[a];if(s){e.push({rule:"unreachable-match",severity:"warn",message:`\uB3C4\uB2EC \uBD88\uAC00 cond \uCF00\uC774\uC2A4: else \uC774\uD6C4 \uCF00\uC774\uC2A4 \uBC1C\uACAC (\uC778\uB371\uC2A4 ${a})`,line:n.line});break}if(i.kind==="block"&&i.type==="Array"){let o=i.fields.get("items");if(Array.isArray(o)&&o.length>=1){let u=o[0];(u.kind==="literal"&&u.value===!0||u.kind==="literal"&&u.type==="symbol"&&u.value==="else"||u.kind==="sexpr"&&u.op==="else")&&(s=!0)}}else i.kind==="sexpr"&&i.op==="else"&&(s=!0)}}if(n.kind==="pattern-match"){let s=!1;for(let a=0;a<n.cases.length;a++){let i=n.cases[a];if(s){e.push({rule:"unreachable-match",severity:"warn",message:`\uB3C4\uB2EC \uBD88\uAC00 match \uCF00\uC774\uC2A4: wildcard \uC774\uD6C4 \uCF00\uC774\uC2A4 (\uC778\uB371\uC2A4 ${a})`});break}i.pattern.kind==="wildcard-pattern"&&(s=!0)}}}),e}},hp={name:"dead-code",check(r,t){let e=[];function n(s){return s.kind==="literal"||s.kind==="variable"||s.kind==="keyword"?!0:s.kind==="sexpr"&&new Set(["+","-","*","/","%","<",">","<=",">=","=","!=","and","or","not","str","num","bool","list","array","get","length","count","first","rest","keys","values","concat","append","reverse"]).has(s.op)?s.args.every(i=>n(i)):!1}return ee(r,s=>{if(s.kind==="sexpr"&&s.op==="do"){let a=s.args;for(let i=0;i<a.length-1;i++)n(a[i])&&e.push({rule:"dead-code",severity:"warn",message:`Dead code: do \uBE14\uB85D\uC5D0\uC11C \uACB0\uACFC\uAC00 \uC0AC\uC6A9\uB418\uC9C0 \uC54A\uB294 \uC21C\uC218 \uD45C\uD604\uC2DD (\uC778\uB371\uC2A4 ${i})`,line:s.line})}}),e}},yp=[up,pp,fp,mp,dp,gp,hp]});function ee(r,t,e){for(let n of r)if(t(n,e),n.kind==="block")for(let[,s]of n.fields){let a=Array.isArray(s)?s:[s];ee(a,t,n)}else if(n.kind==="sexpr")t(n,e),ee(n.args,t,n);else if(n.kind==="pattern-match"){ee([n.value],t,n);for(let s of n.cases)ee([s.body],t,n),s.guard&&ee([s.guard],t,n);n.defaultCase&&ee([n.defaultCase],t,n)}else if(n.kind==="try-block"){if(ee([n.body],t,n),n.catchClauses)for(let s of n.catchClauses)ee([s.handler],t,n);n.finallyBlock&&ee([n.finallyBlock],t,n)}else n.kind==="await"?ee([n.argument],t,n):n.kind==="throw"?ee([n.argument],t,n):n.kind==="async-function"&&ee([n.body],t,n)}function ib(r,t){let e=new Set,n=new Set,s=new Map,a=["print","println","+","-","*","/","%","<",">","<=",">=","=","!=","and","or","not","if","cond","let","define","do","begin","list","array","map","get","set","push","pop","length","count","filter","reduce","each","range","concat","str","num","bool","first","rest","cons","nil?","empty?","null?","type-of","string-length","substring","string-split","string-join","string-contains","keys","values","entries","merge","json-parse","json-stringify","throw","try","catch","await","async","match","fn","let*","append","reverse","sort","zip","flat-map","max","min","abs","floor","ceil","round","sqrt","pow","now","date-format","sleep","http-get","http-post","defstruct","defprotocol","impl","->","push!","map-get","map-set","defmacro","when","unless","iterate","take","filter-lazy","parallel","channel","send!","receive!","assoc","dissoc","update"];for(let o of a)e.add(o);let i={not:1,"nil?":1,"empty?":1,"null?":1,"type-of":1,length:1,count:1,first:1,rest:1,reverse:1,keys:1,values:1,"json-parse":1,"json-stringify":1,str:1,num:1,bool:1,abs:1,floor:1,ceil:1,round:1,sqrt:1,print:1,println:1,"+":2,"-":2,"*":2,"/":2,"%":2,"<":2,">":2,"<=":2,">=":2,"=":2,"!=":2,and:2,or:2,get:2,push:2,cons:2,concat:2,pow:2,merge:2,zip:2,append:2,assoc:3,dissoc:2,filter:2,each:2,map:2,sort:2,"flat-map":2,reduce:3,range:2,substring:3};for(let[o,u]of Object.entries(i))s.set(o,u);for(let o of r)if(o.kind==="block"&&o.type==="FUNC"){e.add(o.name);let u=o.fields.get("params");if(u){let f=Array.isArray(u)?u:[u];if(f.length===1&&f[0].kind==="block"&&f[0].type==="Array"){let l=f[0].fields?.get("items");Array.isArray(l)?s.set(o.name,l.length):s.set(o.name,0)}else{let l=f.filter(c=>c.kind==="variable");s.set(o.name,l.length)}}else s.set(o.name,0)}for(let o of r)if(o.kind==="sexpr"&&o.op==="define"&&o.args.length>=1){let u=o.args[0];u.kind==="variable"&&n.add(u.name)}return{source:t,functions:e,variables:n,funcArity:s}}function vp(){let{ALL_RULES:r}=(kp(),_e(bp)),t=new ro;for(let e of r)t.addRule(e);return t}var ro,no=gt(()=>{be();ke();ro=class{constructor(){this.rules=[]}addRule(t){return this.rules.push(t),this}lint(t){let e,n;try{e=W(t),n=H(e)}catch(i){return[{rule:"parse-error",severity:"error",message:`Parse error: ${i.message}`}]}let s=ib(n,t),a=[];for(let i of this.rules)try{let o=i.check(n,s);a.push(...o)}catch{}return a}lintFiltered(t,e){return this.lint(t).filter(n=>n.severity===e)}}});var j=z(require("fs")),D=z(require("path")),$p=z(require("readline"));be();ke();var ia=z(require("fs")),np=z(require("path"));be();ke();un();var Io=new Map([["+",{params:[{kind:"type",name:"int"},{kind:"type",name:"int"}],returnType:{kind:"type",name:"int"}}],["-",{params:[{kind:"type",name:"int"},{kind:"type",name:"int"}],returnType:{kind:"type",name:"int"}}],["*",{params:[{kind:"type",name:"int"},{kind:"type",name:"int"}],returnType:{kind:"type",name:"int"}}],["/",{params:[{kind:"type",name:"int"},{kind:"type",name:"int"}],returnType:{kind:"type",name:"int"}}],["=",{params:[{kind:"type",name:"any"},{kind:"type",name:"any"}],returnType:{kind:"type",name:"bool"}}],["<",{params:[{kind:"type",name:"int"},{kind:"type",name:"int"}],returnType:{kind:"type",name:"bool"}}],[">",{params:[{kind:"type",name:"int"},{kind:"type",name:"int"}],returnType:{kind:"type",name:"bool"}}],["concat",{params:[{kind:"type",name:"string"},{kind:"type",name:"string"}],returnType:{kind:"type",name:"string"}}],["upper",{params:[{kind:"type",name:"string"}],returnType:{kind:"type",name:"string"}}],["lower",{params:[{kind:"type",name:"string"}],returnType:{kind:"type",name:"string"}}],["list",{params:[{kind:"type",name:"any"}],returnType:{kind:"type",name:"array<any>"}}]]),ba=class{constructor(){this.functionTypes=new Map;this.variableTypes=new Map}registerFunction(t,e,n){this.functionTypes.set(t,{params:e,returnType:n})}registerVariable(t,e){this.variableTypes.set(t,e)}checkFunctionCall(t,e){let n=Io.get(t);if(n)return e.length!==n.params.length?{valid:!1,message:`Function '${t}' expects ${n.params.length} arguments, got ${e.length}`}:{valid:!0,message:"OK",inferredType:n.returnType};let s=this.functionTypes.get(t);if(s){if(e.length!==s.params.length)return{valid:!1,message:`Function '${t}' expects ${s.params.length} arguments, got ${e.length}`};for(let a=0;a<e.length;a++)if(!this.isCompatible(e[a],s.params[a]))return{valid:!1,message:`Argument ${a+1} to '${t}': expected ${s.params[a].name}, got ${e[a].name}`};return{valid:!0,message:"OK",inferredType:s.returnType}}return{valid:!1,message:`Unknown function: ${t}`}}checkAssignment(t,e,n){return n&&!this.isCompatible(e,n)?{valid:!1,message:`Variable '${t}' declared as ${n.name}, but assigned ${e.name}`}:{valid:!0,message:"OK"}}inferType(t){let e=t,n=t,s=t;if(e.kind==="literal")switch(e.type){case"number":return{kind:"type",name:"int"};case"string":return{kind:"type",name:"string"};case"boolean":return{kind:"type",name:"bool"};default:return{kind:"type",name:"any"}}if(n.kind==="variable")return this.variableTypes.get(n.name)||{kind:"type",name:"any"};if(s.kind==="sexpr"){let a=Io.get(s.op)||this.functionTypes.get(s.op);if(a)return a.returnType}return{kind:"type",name:"any"}}registerGenericFunction(t,e,n,s){this.functionTypes.set(t,{params:n,returnType:s,generics:e,isGeneric:e.length>0})}instantiateGenericFunction(t,e){let n=this.functionTypes.get(t);if(!n||!n.isGeneric)return{valid:!1,message:`Function '${t}' is not generic`};if(!n.generics||e.length!==n.generics.length)return{valid:!1,message:`Function '${t}' expects ${n.generics?.length||0} type arguments, got ${e.length}`};let s=new Map;for(let o=0;o<n.generics.length;o++)s.set(n.generics[o],e[o]);let a=n.params.map(o=>this.substituteType(o,s));return{valid:!0,message:"OK",inferredType:this.substituteType(n.returnType,s)}}substituteType(t,e){return t.isTypeVariable&&e.has(t.name)?e.get(t.name)||t:t.generic?{...t,generic:this.substituteType(t.generic,e)}:t.union?{...t,union:t.union.map(n=>this.substituteType(n,e))}:t}isCompatible(t,e){return t.name===e.name||e.name==="any"||t.name==="any"||t.name==="int"&&e.name==="string"||t.name==="string"&&e.name==="int"}};function Lo(){return new ba}function Do(r){return r==null?"null":typeof r=="boolean"?"bool":typeof r=="number"?Number.isInteger(r)?"int":"float":typeof r=="string"?"string":Array.isArray(r)?"array":typeof r=="function"?"fn":typeof r=="object"?"map":"any"}function qo(r,t){return t==="any"||r==="any"||r===t||t==="number"&&(r==="int"||r==="float")||t==="float"&&r==="int"}function Uo(r){switch(r){case"int":return"int";case"float":return"float";case"number":return"number";case"string":return"string";case"bool":return"bool";case"boolean":return"bool";case"array":case"array<any>":return"array";case"map":return"map";case"fn":case"function":return"fn";case"null":return"null";default:return"any"}}var Jr=class{constructor(t=!1){this.funcTypes=new Map;this.strict=t}get isStrict(){return this.strict}registerFunc(t,e,n){this.funcTypes.set(t,{params:e.map(Uo),ret:Uo(n)})}checkCall(t,e){if(!this.strict)return;let n=this.funcTypes.get(t);if(!n)return;let s=Math.min(n.params.length,e.length);for(let a=0;a<s;a++){let i=n.params[a];if(i==="any")continue;let o=Do(e[a]);if(!qo(o,i)){let{FLRuntimeError:u,ErrorCodes:f}=(nt(),_e(xa));throw new u(f.TYPE_MISMATCH,`'${t}': arg ${a+1} expected ${i}, got ${o}`,{fn:t,arg:a,expected:i,got:o,value:e[a]})}}}checkReturn(t,e){if(!this.strict)return;let n=this.funcTypes.get(t);if(!n||n.ret==="any")return;let s=Do(e);if(!qo(s,n.ret)){let{FLRuntimeError:a,ErrorCodes:i}=(nt(),_e(xa));throw new a(i.TYPE_MISMATCH,`'${t}' return: expected ${n.ret}, got ${s}`,{fn:t,expected:n.ret,got:s,value:e})}}getSignature(t){return this.funcTypes.get(t)}registeredFuncs(){return Array.from(this.funcTypes.keys())}};nt();nt();function Wp(r,t){let e=r.length,n=t.length,s=Array.from({length:e+1},(a,i)=>Array.from({length:n+1},(o,u)=>i===0?u:u===0?i:0));for(let a=1;a<=e;a++)for(let i=1;i<=n;i++)r[a-1]===t[i-1]?s[a][i]=s[a-1][i-1]:s[a][i]=1+Math.min(s[a-1][i],s[a][i-1],s[a-1][i-1]);return s[e][n]}var Xr={env:{correct:"shell_env",usage:'(shell_env "KEY")'},get_env:{correct:"shell_env",usage:'(shell_env "KEY")'},"get-env":{correct:"shell_env",usage:'(shell_env "KEY")'},get_env_or:{correct:"shell_env",usage:'(or (shell_env "KEY") "default")'},obj_merge:{correct:"assoc",usage:'(assoc map "key" value)'},"obj-merge":{correct:"assoc",usage:'(assoc map "key" value)'},merge:{correct:"assoc",usage:'(assoc map "key" value)'},obj_omit:{correct:"dissoc",usage:'(dissoc map "key")'},"obj-omit":{correct:"dissoc",usage:'(dissoc map "key")'},obj_pick:{correct:"get",usage:'(get map "key")'},dict:{correct:"map-set",usage:'(map-set {} "key" value)'},str_length:{correct:"length",usage:'(length "hello")'},string_length:{correct:"length",usage:'(length "hello")'},str_concat:{correct:"str",usage:'(str "a" "b" "c")'},str_to_int:{correct:"str_to_num",usage:'(str_to_num "42")'},parse_int:{correct:"str_to_num",usage:'(str_to_num "42")'},int_to_str:{correct:"num_to_str",usage:"(num_to_str 42)"},to_string:{correct:"str",usage:"(str value)"},to_str:{correct:"str",usage:"(str value)"},is_null:{correct:"nil?",usage:"(nil? value)"},is_nil:{correct:"nil?",usage:"(nil? value)"},"null?":{correct:"nil?",usage:"(nil? value)"},is_array:{correct:"array?",usage:"(array? value)"},is_string:{correct:"string?",usage:"(string? value)"},is_number:{correct:"number?",usage:"(number? value)"},push:{correct:"append",usage:"(append arr item)"},list_append:{correct:"append",usage:"(append arr item)"},array_push:{correct:"append",usage:"(append arr item)"},array_length:{correct:"length",usage:"(length arr)"},first:{correct:"get",usage:"(get arr 0)"},head:{correct:"get",usage:"(get arr 0)"},console_log:{correct:"println",usage:"(println value)"},"console.log":{correct:"println",usage:"(println value)"},print:{correct:"println",usage:"(println value)"},log:{correct:"println",usage:"(println value)"},mariadb_all:{correct:"mariadb_query",usage:'(mariadb_query db "SELECT ..." [params])'},db_query:{correct:"mariadb_query",usage:'(mariadb_query db "SELECT ..." [params])'},"mariadb-query":{correct:"mariadb_query",usage:`\uBA3C\uC800 DB \uB9F5 \uC815\uC758: (define DB {:host "localhost" :user "u" :password "p" :database "d"})
19
+ \uADF8 \uD6C4: (mariadb_query DB "SELECT ..." [params])`},"mariadb-exec":{correct:"mariadb_exec",usage:'(mariadb_exec DB "INSERT INTO ..." [params])'},"mariadb-one":{correct:"mariadb_one",usage:'(mariadb_one DB "SELECT ... LIMIT 1" [params]) ;; \u2192 \uB2E8\uC77C row \uBC18\uD658'},"db-query":{correct:"mariadb_query",usage:'(mariadb_query DB "SELECT ..." [params])'},"db-exec":{correct:"mariadb_exec",usage:'(mariadb_exec DB "INSERT ..." [params])'},http_post:{correct:"http_get",usage:'(http_get url {:method "POST" :body data})'},fetch:{correct:"http_get",usage:"(http_get url)"},server_listen:{correct:"server_start",usage:"(server_start 40000)"},listen:{correct:"server_start",usage:"(server_start 40000)"},raise:{correct:"error",usage:'(error "\uBA54\uC2DC\uC9C0")'},panic:{correct:"error",usage:'(error "\uBA54\uC2DC\uC9C0")'},"str-to-int":{correct:"str-to-num",usage:'(str-to-num "42")'},str_to_int:{correct:"str-to-num",usage:'(str-to-num "42")'},"parse-int":{correct:"str-to-num",usage:'(str-to-num "42")'},parseInt:{correct:"str-to-num",usage:'(str-to-num "42")'},json_keys:{correct:"keys",usage:"(keys map)"},"json-keys":{correct:"keys",usage:"(keys map)"},"map-keys":{correct:"keys",usage:"(keys map)"},"object-keys":{correct:"keys",usage:"(keys map)"},"http-simple-get":{correct:"http-get-data",usage:"(http-get-data url)"},"http-fetch":{correct:"http-get-data",usage:"(http-get-data url)"},"obj-merge":{correct:"merge",usage:"(merge map1 map2)"},obj_merge:{correct:"merge",usage:"(merge map1 map2)"},size:{correct:"length",usage:"(length arr)"},split:{correct:"str-split",usage:'(str-split "a,b" ",")'},str_split:{correct:"str-split",usage:'(str-split "a,b" ",")'},"JSON.parse":{correct:"json-parse",usage:'(json-parse "{}")'},parseJSON:{correct:"json-parse",usage:'(json-parse "{}")'},parse_json:{correct:"json-parse",usage:'(json-parse "{}")'},"JSON.stringify":{correct:"json-stringify",usage:"(json-stringify {})"},toJSON:{correct:"json-stringify",usage:"(json-stringify {})"},stringify:{correct:"json-stringify",usage:"(json-stringify {})"},"num-to-str":{correct:"num_to_str",usage:"(num_to_str 42)"},numToStr:{correct:"num_to_str",usage:"(num_to_str 42)"},number_to_str:{correct:"num_to_str",usage:"(num_to_str 42)"},trim:{correct:"str-trim",usage:'(str-trim " hello ")'},str_trim:{correct:"str-trim",usage:'(str-trim " hello ")'},"starts-with?":{correct:"str-starts-with",usage:'(str-starts-with "hello" "he")'},startsWith:{correct:"str-starts-with",usage:'(str-starts-with "hello" "he")'},includes:{correct:"str-contains",usage:'(str-contains "hello" "ell")'},str_includes:{correct:"str-contains",usage:'(str-contains "hello" "ell")'},"to-upper":{correct:"str-to-upper",usage:'(str-to-upper "hello")'},toUpperCase:{correct:"str-to-upper",usage:'(str-to-upper "hello")'},to_upper:{correct:"str-to-upper",usage:'(str-to-upper "hello")'},toString:{correct:"str",usage:"(str value)"},"Date.now":{correct:"now-ms",usage:"(now-ms)"},"Date.now()":{correct:"now-ms",usage:"(now-ms)"},now_ms:{correct:"now-ms",usage:"(now-ms)"},currentTimeMs:{correct:"now-ms",usage:"(now-ms)"},"num-round":{correct:"round",usage:"(round 3.7) ;; \u2192 4 | \uC18C\uC218\uC810 \uC774\uD558 \uC81C\uAC70\uB294 (int 3.7) \u2192 3"},num_round:{correct:"round",usage:"(round 3.7)"},"Math.round":{correct:"round",usage:"(round 3.7)"},"Math.floor":{correct:"floor",usage:"(floor 3.7) ;; \u2192 3"},"Math.ceil":{correct:"ceil",usage:"(ceil 3.2) ;; \u2192 4"},"Math.abs":{correct:"abs",usage:"(abs -5) ;; \u2192 5"},"Math.max":{correct:"max",usage:"(max 3 7) ;; \u2192 7"},"Math.min":{correct:"min",usage:"(min 3 7) ;; \u2192 3"},"Math.pow":{correct:"pow",usage:"(pow 2 10) ;; \u2192 1024"},"Math.sqrt":{correct:"sqrt",usage:"(sqrt 16) ;; \u2192 4"},truncate:{correct:"int",usage:"(int 3.9) ;; \u2192 3 (\uC18C\uC218\uC810 \uBC84\uB9BC)"},trunc:{correct:"int",usage:"(int 3.9) ;; \u2192 3"},"num-abs":{correct:"abs",usage:"(abs -5)"},"num-floor":{correct:"floor",usage:"(floor 3.7)"},"num-ceil":{correct:"ceil",usage:"(ceil 3.2)"},"regex-test":{correct:"re-test",usage:'(re-test "^hello" "hello world") ;; \u2192 true'},regex_test:{correct:"re-test",usage:'(re-test "\uD328\uD134" \uBB38\uC790\uC5F4)'},"regexp-test":{correct:"re-test",usage:'(re-test "\uD328\uD134" \uBB38\uC790\uC5F4)'},"re-match":{correct:"re-test",usage:'(re-test "\uD328\uD134" \uBB38\uC790\uC5F4) ;; boolean \uBC18\uD658'},req_param:{correct:"server_req_param",usage:'(server_req_param req "id")'},"req-param":{correct:"server_req_param",usage:'(server_req_param req "id")'},req_query:{correct:"server_req_query",usage:'(server_req_query req "key")'},"req-query":{correct:"server_req_query",usage:'(server_req_query req "key")'},req_body:{correct:"server_req_body",usage:"(server_req_body req)"},"req-body":{correct:"server_req_body",usage:"(server_req_body req)"},mariadb_connect:{correct:"mariadb_connect",usage:'(mariadb_connect {:host "h" :user "u" :password "p" :database "d"}) \uB610\uB294 (mariadb_connect "host" "user" "pass" "db")'},"http-post-json":{correct:"http_post",usage:"(http_post url (json-stringify body))"},"req-params":{correct:"server_req_param",usage:'(server_req_param req "id") \u2014 URL :id \uD30C\uB77C\uBBF8\uD130 \uC811\uADFC'},"req-param":{correct:"server_req_param",usage:'(server_req_param req "id")'},params:{correct:"server_req_param",usage:'(server_req_param req "id") \u2014 URL :id \uD30C\uB77C\uBBF8\uD130. (get (get req "params") "id") \uB300\uC2E0 \uC0AC\uC6A9'},req_body_raw:{correct:"server_req_body",usage:"(server_req_body req) \u2014 body \uBB38\uC790\uC5F4 \uBC18\uD658. JSON\uC774\uBA74 (json-parse (server_req_body req)) \uC0AC\uC6A9"},body_parse:{correct:"get",usage:'(get req "body") \u2014 Content-Type: application/json \uC694\uCCAD\uC740 \uC790\uB3D9 \uD30C\uC2F1. \uADF8 \uC678\uB294 (json-parse (server_req_body req)) \uD544\uC694'},"app-get":{correct:"server-get",usage:'(load "src/express.fl") \uC5C6\uC774 server-get \uC0AC\uC6A9. express.fl \uB85C\uB4DC \uD6C4\uC5D0\uB294 app-* \uACC4\uC5F4\uB9CC \uC0AC\uC6A9\uD558\uC138\uC694.'},"app-post":{correct:"server-post",usage:'(load "src/express.fl") \uC5C6\uC774 server-post \uC0AC\uC6A9. \uD63C\uC6A9 \uAE08\uC9C0: \uD55C \uD504\uB85C\uC81D\uD2B8\uC5D0\uC11C server_* / app-* \uC911 \uD558\uB098\uB9CC \uC120\uD0DD.'},"app-listen":{correct:"server-start",usage:'(load "src/express.fl") \uC5C6\uC774 app-listen \uC0AC\uC6A9. express.fl \uB85C\uB4DC \uD6C4\uC5D0\uB9CC app-listen \uC0AC\uC6A9 \uAC00\uB2A5.'},"res-json":{correct:"server-json",usage:'(load "src/express.fl") \uC5C6\uC774 res-json \uC0AC\uC6A9. express.fl \uB85C\uB4DC \uD6C4\uC5D0\uB9CC res-* \uACC4\uC5F4 \uC0AC\uC6A9 \uAC00\uB2A5.'},"res-status":{correct:"server-status",usage:'(load "src/express.fl") \uC5C6\uC774 res-status \uC0AC\uC6A9. \uD63C\uC6A9 \uAE08\uC9C0.'},ws_handler:{correct:"ws-handler",usage:"(ws-handler (fn [conn msg] ...)) \u2014 conn: \uC5F0\uACB0 \uAC1D\uCCB4, msg: \uC218\uC2E0 \uBA54\uC2DC\uC9C0"},"on-close":{correct:"ws-on-close",usage:"(ws-on-close conn (fn [] ...)) \u2014 \uC5F0\uACB0 \uC885\uB8CC \uD578\uB4E4\uB7EC"},server_listen:{correct:"server_start",usage:"(server_start port) \u2014 \uC774\uD6C4 \uCF54\uB4DC\uB294 \uC2E4\uD589\uB418\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4. \uCD08\uAE30\uD654\uB294 server_start \uD638\uCD9C \uC804\uC5D0 \uC644\uB8CC\uD558\uC138\uC694."},"server-listen":{correct:"server_start",usage:"(server_start port)"}};function dn(r,t){let e=null,n=1/0,s=r.length>4?3:2;for(let a of t){let i=Wp(r.toLowerCase(),a.toLowerCase());i<=s&&i<n&&(n=i,e=a)}return e}var Aa=class{constructor(t){this.logLevelOrder={debug:0,info:1,warn:2,error:3};let e=process.env.LOG_LEVEL;this.currentLogLevel=t||e||"info",process.env.DEBUG_LOGGER&&console.log(`[Logger] Initialized with log level: ${this.currentLogLevel}`)}debug(t,e){this.log("debug",t,e)}info(t,e){this.log("info",t,e)}warn(t,e){this.log("warn",t,e)}error(t,e){this.log("error",t,e)}setLogLevel(t){this.currentLogLevel=t}log(t,e,n){if(this.logLevelOrder[t]<this.logLevelOrder[this.currentLogLevel])return;let i=`${`[${new Date().toISOString()}] [${t.toUpperCase()}]`} ${e}`;switch(t){case"debug":console.log(i,n||"");break;case"info":console.log(i,n||"");break;case"warn":console.warn(i,n||"");break;case"error":console.error(i,n||"");break}}};var Hp=new Aa;function Vo(){return Hp}var Yr=class{constructor(){this.stack=[new Map];this.meta=new Map}get(t){for(let e=this.stack.length-1;e>=0;e--)if(this.stack[e].has(t))return this.stack[e].get(t)}has(t){for(let e=this.stack.length-1;e>=0;e--)if(this.stack[e].has(t))return!0;return!1}set(t,e,n){if(this.stack[this.stack.length-1].set(t,e),n){let s=this.stack.length-1;this.meta.set(`${s}:${t}`,{scope:"local",...n})}}setGlobal(t,e,n){this.stack[0].set(t,e),n&&this.meta.set(`0:${t}`,{scope:"global",...n})}getMeta(t){for(let e=this.stack.length-1;e>=0;e--)if(this.stack[e].has(t))return this.meta.get(`${e}:${t}`)}getCurrentScopeVars(){return this.stack.length===0?[]:Array.from(this.stack[this.stack.length-1].keys())}getAllVars(){let t=new Set;for(let e of this.stack)for(let n of e.keys())t.add(n);return Array.from(t)}mutate(t,e){for(let n=this.stack.length-1;n>=0;n--)if(this.stack[n].has(t))return this.stack[n].set(t,e),!0;return!1}push(){this.stack.push(new Map)}pop(){this.stack.length>1&&this.stack.pop()}snapshot(){let t=new Map;for(let e of this.stack)for(let[n,s]of e)t.set(n,s);return t}fromSnapshot(t){this.stack=[new Map(t)],this.meta=new Map}saveStack(){return this.stack.map(t=>new Map(t))}restoreStack(t){this.stack=t}delete(t){for(let e=this.stack.length-1;e>=0;e--)if(this.stack[e].has(t)){this.stack[e].delete(t);return}}};var Qr=class{constructor(t,e="mock"){this.cacheTtlMs=24*60*60*1e3;this.cache=new Map,this.apiKey=t,this.apiProvider=e}searchSync(t,e={}){let{limit:n=10,cache:s=!0}=e;if(s){let i=this.getCachedResult(t);if(i)return i.map(o=>({...o,source:"cache"}))}let a=this.searchMock(t,n);return s&&this.cacheResult(t,a),a}async search(t,e={}){let{limit:n=10,cache:s=!0,timeout:a=5e3}=e;if(s){let o=this.getCachedResult(t);if(o)return o.map(u=>({...u,source:"cache"}))}let i;try{switch(this.apiProvider){case"brave":i=await this.searchBrave(t,n,a);break;case"serper":i=await this.searchSerper(t,n,a);break;case"mock":default:i=this.searchMock(t,n)}}catch(o){console.warn(`Search API failed: ${o.message}, using mock results`),i=this.searchMock(t,n)}return s&&this.cacheResult(t,i),i}async searchBrave(t,e,n){if(!this.apiKey)throw new Error("Brave Search requires API key (BRAVE_SEARCH_KEY)");let s=new AbortController,a=setTimeout(()=>s.abort(),n);try{let i=await fetch("https://api.search.brave.com/res/v1/web/search",{method:"GET",headers:{Accept:"application/json","X-Subscription-Token":this.apiKey},signal:s.signal});if(!i.ok)throw new Error(`Brave API error: ${i.status}`);return((await i.json()).web||[]).slice(0,e).map(f=>({title:f.title,url:f.url,snippet:f.description,source:"api",relevance:.9,timestamp:new Date().toISOString()}))}finally{clearTimeout(a)}}async searchSerper(t,e,n){if(!this.apiKey)throw new Error("Serper requires API key (SERPER_API_KEY)");let s=new AbortController,a=setTimeout(()=>s.abort(),n);try{let i=await fetch("https://google.serper.dev/search",{method:"POST",headers:{"X-API-KEY":this.apiKey,"Content-Type":"application/json"},body:JSON.stringify({q:t,num:Math.min(e,10)}),signal:s.signal});if(!i.ok)throw new Error(`Serper API error: ${i.status}`);return((await i.json()).organic||[]).slice(0,e).map(f=>({title:f.title,url:f.link,snippet:f.snippet,source:"api",relevance:.85,timestamp:new Date().toISOString()}))}finally{clearTimeout(a)}}searchMock(t,e){let n={"ai trends 2026":[{title:"2026 AI Trends: Multimodal Systems Dominate",url:"https://example.com/ai-trends-2026",snippet:"Multimodal AI systems combining text, image, and audio are becoming the standard...",source:"api",relevance:.95},{title:"AI Safety & Alignment: Key Focus Areas",url:"https://example.com/ai-safety-2026",snippet:"As AI systems become more capable, safety and alignment research intensifies...",source:"api",relevance:.88},{title:"Enterprise AI Adoption Accelerates",url:"https://example.com/enterprise-ai-2026",snippet:"Companies are deploying AI for productivity gains across departments...",source:"api",relevance:.82}],"typescript performance":[{title:"TypeScript Performance Optimization Guide",url:"https://example.com/ts-perf",snippet:"Learn how to optimize TypeScript compilation and runtime performance...",source:"api",relevance:.92},{title:"Build Tools: esbuild vs tsc vs swc",url:"https://example.com/build-tools-comparison",snippet:"Comparing modern TypeScript build tools and their performance characteristics...",source:"api",relevance:.87}]},s=t.toLowerCase();return(n[s]||[{title:`Results for: ${t}`,url:`https://example.com/search?q=${encodeURIComponent(t)}`,snippet:`Mock search results for query: "${t}"`,source:"api",relevance:.75}]).slice(0,e)}getCachedResult(t){let e=this.cache.get(t);return e?Date.now()>e.expiresAt?(this.cache.delete(t),null):e.results:null}cacheResult(t,e){let n=Date.now();this.cache.set(t,{results:e,timestamp:n,expiresAt:n+this.cacheTtlMs})}clearCache(t){t?this.cache.delete(t):this.cache.clear()}getCacheStats(){let t=Array.from(this.cache.keys()),e;for(let[n,s]of this.cache.entries())(!e||s.timestamp<e.timestamp)&&(e={query:n,timestamp:s.timestamp});return{size:this.cache.size,queries:t,oldestEntry:e}}};var Le=z(require("fs")),zo=z(require("path")),Zr=class{constructor(t="./data/learned-facts.json",e=30){this.defaultTtlDays=30;this.autoSaveInterval=5e3;this.isDirty=!1;this.filePath=t,this.facts=new Map,this.defaultTtlDays=e;let n=zo.dirname(this.filePath);Le.existsSync(n)||Le.mkdirSync(n,{recursive:!0}),this.loadFromFile(),this.startAutoSave()}save(t,e,n){let{confidence:s,source:a,ttlDays:i=this.defaultTtlDays}=n;if(s<0||s>1)throw new Error(`Invalid confidence: ${s}. Must be between 0 and 1.`);let o=Date.now(),u={key:t,data:e,confidence:s,source:a,timestamp:o,expiresAt:o+i*24*60*60*1e3,accessCount:0,lastAccessed:o};this.facts.set(t,u),this.isDirty=!0}load(t){let e=this.facts.get(t);return e?Date.now()>e.expiresAt?(this.facts.delete(t),this.isDirty=!0,null):(e.accessCount++,e.lastAccessed=Date.now(),this.isDirty=!0,e):null}loadAll(){let t=[],e=Date.now(),n=!1;for(let[s,a]of this.facts.entries())e>a.expiresAt?(this.facts.delete(s),n=!0):t.push(a);return n&&(this.isDirty=!0),t}delete(t){this.facts.has(t)&&(this.facts.delete(t),this.isDirty=!0)}findByConfidence(t){return this.loadAll().filter(e=>e.confidence>=t)}findBySource(t){return this.loadAll().filter(e=>e.source===t)}cleanup(){let t=Date.now(),e=0;for(let[n,s]of this.facts.entries())t>s.expiresAt&&(this.facts.delete(n),e++);return e>0&&(this.isDirty=!0),e}getStats(){let t=this.loadAll(),e=Date.now(),n=0,s=0,a=null,i={};for(let[,o]of this.facts.entries())e>o.expiresAt&&n++,i[o.source]=(i[o.source]||0)+1;return t.length>0&&(s=t.reduce((o,u)=>o+u.confidence,0)/t.length,a=Math.min(...t.map(o=>o.expiresAt))),{totalFacts:t.length,expiredCount:n,averageConfidence:s,oldestExpiry:a,sourceDistribution:i}}flush(){this.isDirty&&(this.saveToFile(),this.isDirty=!1)}destroy(){this.autoSaveTimer&&(clearInterval(this.autoSaveTimer),this.autoSaveTimer=void 0),this.flush()}loadFromFile(){try{if(!Le.existsSync(this.filePath))return;let t=Le.readFileSync(this.filePath,"utf-8"),e=JSON.parse(t);if(!e.facts||!Array.isArray(e.facts)){console.warn("Invalid learned facts file format, starting with empty store");return}for(let n of e.facts)this.facts.set(n.key,n);this.cleanup()}catch(t){console.error(`Failed to load learned facts: ${t.message}`)}}saveToFile(){try{let t={version:"1.0",lastUpdated:new Date().toISOString(),facts:Array.from(this.facts.values())},e=this.filePath+".tmp";Le.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),Le.renameSync(e,this.filePath)}catch(t){console.error(`Failed to save learned facts: ${t.message}`)}}startAutoSave(){this.autoSaveTimer=setInterval(()=>{this.isDirty&&this.flush()},this.autoSaveInterval),this.autoSaveTimer&&typeof this.autoSaveTimer.unref=="function"&&this.autoSaveTimer.unref()}};var ae=class r{constructor(t){this.state="pending";this.value=void 0;this.error=null;this.resolvers=[];this.rejecters=[];try{t(this.resolve.bind(this),this.reject.bind(this))}catch(e){this.reject(e)}}getState(){return this.state}getValue(){if(this.state==="resolved")return this.value;throw new Error("Cannot get value from non-resolved Promise")}getError(){return this.state==="rejected"?this.error:null}resolve(t){if(this.state==="pending"){this.state="resolved",this.value=t;for(let e of this.resolvers)try{e(t)}catch{}this.resolvers=[]}}reject(t){if(this.state==="pending"){this.state="rejected",this.error=t;for(let e of this.rejecters)try{e(t)}catch{}this.rejecters=[]}}then(t){return new r((e,n)=>{if(this.state==="resolved")try{let s=t(this.value);e(s)}catch(s){n(s)}else this.state==="rejected"?n(this.error):this.resolvers.push(s=>{try{let a=t(s);e(a)}catch(a){n(a)}})})}catch(t){return new r((e,n)=>{if(this.state==="rejected")try{let s=t(this.error);e(s)}catch(s){n(s)}else this.state==="resolved"?e(this.value):this.rejecters.push(s=>{try{let a=t(s);e(a)}catch(a){n(a)}})})}finally(t){return new r((e,n)=>{let s=()=>{try{t()}catch(a){n(a);return}this.state==="resolved"?e(this.value):this.state==="rejected"&&n(this.error)};this.state!=="pending"?s():(this.resolvers.push(()=>s()),this.rejecters.push(()=>s()))})}static all(t){return new r((e,n)=>{if(t.length===0){e([]);return}let s=[],a=0;for(let i=0;i<t.length;i++){let o=t[i];if(o.state==="resolved")s[i]=o.value,a++;else if(o.state==="rejected"){n(o.error);return}else o.then(u=>{s[i]=u,a++,a===t.length&&e(s)}).catch(u=>n(u))}a===t.length&&e(s)})}static race(t){return new r((e,n)=>{for(let s of t)if(s.state==="resolved"){e(s.value);return}else if(s.state==="rejected"){n(s.error);return}else s.then(a=>e(a)).catch(a=>n(a))})}};function Wo(r){return new ae(t=>{t(r)})}function $a(r){return new ae((t,e)=>{e(r)})}nt();var Ho=Symbol("LAZY_SEQ");function gn(r,t){return{[Ho]:!0,head:r,tail:t}}function Re(r){return r!=null&&typeof r=="object"&&r[Ho]===!0}function bt(r){return r._headEvaluated||(r._headCache=r.head(),r._headEvaluated=!0),r._headCache}function rt(r){return r._tailEvaluated||(r._tailCache=r.tail(),r._tailEvaluated=!0),r._tailCache??null}function es(r,t){if(Array.isArray(t))return t.slice(0,r);let e=[],n=t;for(;n&&e.length<r;)e.push(bt(n)),n=rt(n);return e}function Go(r,t){let e=t,n=r;for(;n>0&&e;)e=rt(e),n--;return e}function Ea(r,t){return t!==void 0&&r>=t?null:gn(()=>r,()=>Ea(r+1,t))}var Gp=0;function Kp(){return`ctx-${Date.now()}-${++Gp}`}var ts=class{constructor(t=4096,e="priority"){this.window={maxTokens:t,entries:[],usedTokens:0,strategy:e}}estimateTokens(t){try{let e=typeof t=="string"?t:JSON.stringify(t);return Math.max(1,Math.ceil(e.length/4))}catch{return 1}}hasRoom(t){return this.window.usedTokens+t<=this.window.maxTokens}add(t,e){let n=e?.tokens??this.estimateTokens(t),s=e?.priority??.5,a=e?.tags??[],i=Kp(),o={id:i,content:t,tokens:n,priority:s,timestamp:Date.now(),tags:a};return this.window.entries.push(o),this.window.usedTokens+=n,this.window.usedTokens>this.window.maxTokens&&this.trim(),i}get(t){return this.window.entries.find(e=>e.id===t)}remove(t){let e=this.window.entries.findIndex(n=>n.id===t);e!==-1&&(this.window.usedTokens-=this.window.entries[e].tokens,this.window.entries.splice(e,1),this.window.usedTokens<0&&(this.window.usedTokens=0))}trim(){let t=[];if(this.window.usedTokens<=this.window.maxTokens)return t;let e=[...this.window.entries].sort((n,s)=>n.priority!==s.priority?n.priority-s.priority:n.timestamp-s.timestamp);for(let n of e){if(this.window.usedTokens<=this.window.maxTokens)break;let s=this.window.entries.findIndex(a=>a.id===n.id);s!==-1&&(this.window.usedTokens-=this.window.entries[s].tokens,t.push(this.window.entries[s]),this.window.entries.splice(s,1))}return this.window.usedTokens<0&&(this.window.usedTokens=0),t}compress(t){return t(this.window.entries)}getAll(t){return t?this.window.entries.filter(e=>e.tags.includes(t)):[...this.window.entries]}stats(){let t=this.window.usedTokens,e=this.window.maxTokens,n=e>0?Math.round(t/e*100):0;return{used:t,max:e,percent:n,count:this.window.entries.length}}};function qt(r){return{_tag:"Ok",value:r}}function hn(r,t,e){return{_tag:"Err",code:r,message:t,category:e?.category??"runtime-error",context:e?.context,hint:e?.hint,recoverable:e?.recoverable??!1}}function Ut(r){return r._tag==="Ok"}function yn(r){return r._tag==="Err"}function Ko(r){if(Ut(r))return r.value;throw new Error(`[FreeLang Result] unwrap failed: [${r.code}] ${r.message}`)}function Jo(r,t){return Ut(r)?r.value:t}function Xo(r,t){return Ut(r)?qt(t(r.value)):r}function Yo(r,t){return yn(r)?t(r):r}function Qo(r,t){return Ut(r)?t(r.value):r}function Zo(r,t){return Ut(r)?r.value:t(r)}function ns(r,t="UNKNOWN"){if(typeof r=="string")return hn(t,r);if(r instanceof Error){let e=r.message.toLowerCase(),n="runtime-error";return e.includes("not found")||e.includes("undefined")||e.includes("cannot find")?n="not-found":e.includes("type")||e.includes("is not a")?n="type-error":e.includes("arity")||e.includes("argument")?n="arity-error":e.includes("timeout")?n="timeout":(e.includes("enoent")||e.includes("eacces")||e.includes("file"))&&(n="io-error"),hn(t,r.message,{category:n,recoverable:!1})}return hn(t,String(r))}var Ma=class{constructor(){this.strategies=[]}addStrategy(t){return this.strategies.push(t),this}handle(t){for(let e of this.strategies)if(e.condition(t))try{return qt(e.recover(t))}catch{}return t}classify(t){return ns(t)}explain(t){let s=`[${{"type-error":"\uD0C0\uC785 \uC624\uB958","runtime-error":"\uB7F0\uD0C0\uC784 \uC624\uB958","not-found":"\uCC3E\uC744 \uC218 \uC5C6\uC74C","arity-error":"\uC778\uC790 \uC218 \uC624\uB958","io-error":"\uC785\uCD9C\uB825 \uC624\uB958","ai-error":"AI \uBE14\uB85D \uC624\uB958","user-error":"\uC0AC\uC6A9\uC790 \uC815\uC758 \uC624\uB958",timeout:"\uD0C0\uC784\uC544\uC6C3"}[t.category]??"\uC54C \uC218 \uC5C6\uB294 \uC624\uB958"}] ${t.message}`;return t.hint&&(s+=`
20
+ \uD78C\uD2B8: ${t.hint}`),t.recoverable&&(s+=`
21
+ \uBCF5\uAD6C \uAC00\uB2A5: \uC790\uB3D9 \uBCF5\uAD6C\uB97C \uC2DC\uB3C4\uD560 \uC218 \uC788\uC2B5\uB2C8\uB2E4.`),s}canRecover(t){return t.recoverable?!0:this.strategies.some(e=>e.condition(t))}},bn=new Ma;bn.addStrategy({name:"division-by-zero",condition:r=>r.message.toLowerCase().includes("division by zero")||r.message.toLowerCase().includes("divide by zero")||r.category==="runtime-error"&&r.code==="DIV_ZERO",recover:()=>0});bn.addStrategy({name:"not-found-null",condition:r=>r.category==="not-found"&&r.recoverable===!0,recover:()=>null});var Ra=class{constructor(){this.tools=new Map}register(t){return this.tools.set(t.name,t),this}get(t){return this.tools.get(t)}listAll(){return Array.from(this.tools.values())}async execute(t,e){let n=Date.now(),s=this.tools.get(t);if(!s)return{tool:t,input:e,output:null,durationMs:Date.now()-n,success:!1,error:`Tool not found: ${t}`};let a=s.timeout??5e3;try{let i=Promise.resolve(s.execute(e)),o=new Promise((f,l)=>setTimeout(()=>l(new Error(`Tool timeout: ${t} (${a}ms)`)),a)),u=await Promise.race([i,o]);return{tool:t,input:e,output:u,durationMs:Date.now()-n,success:!0}}catch(i){return{tool:t,input:e,output:null,durationMs:Date.now()-n,success:!1,error:String(i?.message??i)}}}executeSync(t,e){let n=Date.now(),s=this.tools.get(t);if(!s)return{tool:t,input:e,output:null,durationMs:Date.now()-n,success:!1,error:`Tool not found: ${t}`};try{let a=s.execute(e);return{tool:t,input:e,output:a,durationMs:Date.now()-n,success:!0}}catch(a){return{tool:t,input:e,output:null,durationMs:Date.now()-n,success:!1,error:String(a?.message??a)}}}};function Xp(r){let t=r.replace(/[^0-9+\-*/.() ]/g,"");return Function(`"use strict"; return (${t})`)()}var Te=new Ra;Te.register({name:"math",description:'\uC218\uD559 \uD45C\uD604\uC2DD\uC744 \uACC4\uC0B0\uD569\uB2C8\uB2E4. \uC608: {expr: "2 + 3 * 4"}',inputSchema:{expr:"string"},outputSchema:"number",execute:({expr:r})=>Xp(String(r))});Te.register({name:"str-upper",description:"\uBB38\uC790\uC5F4\uC744 \uB300\uBB38\uC790\uB85C \uBCC0\uD658\uD569\uB2C8\uB2E4.",inputSchema:{s:"string"},outputSchema:"string",execute:({s:r})=>String(r).toUpperCase()});Te.register({name:"str-lower",description:"\uBB38\uC790\uC5F4\uC744 \uC18C\uBB38\uC790\uB85C \uBCC0\uD658\uD569\uB2C8\uB2E4.",inputSchema:{s:"string"},outputSchema:"string",execute:({s:r})=>String(r).toLowerCase()});Te.register({name:"str-len",description:"\uBB38\uC790\uC5F4 \uAE38\uC774\uB97C \uBC18\uD658\uD569\uB2C8\uB2E4.",inputSchema:{s:"string"},outputSchema:"number",execute:({s:r})=>String(r).length});Te.register({name:"json-parse",description:"JSON \uBB38\uC790\uC5F4\uC744 \uAC1D\uCCB4\uB85C \uD30C\uC2F1\uD569\uB2C8\uB2E4.",inputSchema:{s:"string"},outputSchema:"any",execute:({s:r})=>JSON.parse(String(r))});Te.register({name:"json-stringify",description:"\uAC12\uC744 JSON \uBB38\uC790\uC5F4\uB85C \uBCC0\uD658\uD569\uB2C8\uB2E4.",inputSchema:{v:"any"},outputSchema:"string",execute:({v:r})=>JSON.stringify(r)});Te.register({name:"type-of",description:"\uAC12\uC758 \uD0C0\uC785\uC744 \uBC18\uD658\uD569\uB2C8\uB2E4.",inputSchema:{v:"any"},outputSchema:"string",execute:({v:r})=>typeof r});var Ta=class{constructor(){this.longTerm=new Map;this.shortTerm=new Map;this.episodes=[];this.working=null}remember(t,e,n={}){let s={key:t,value:e,scope:n.scope??"long-term",ttl:n.ttl??"forever",createdAt:Date.now(),accessCount:0,tags:n.tags??[]};s.scope==="short-term"?this.shortTerm.set(t,s):this.longTerm.set(t,s)}recall(t,e=null){let n=this.longTerm.get(t)??this.shortTerm.get(t);return n?n.ttl!=="forever"&&Date.now()-n.createdAt>n.ttl?(this.longTerm.delete(t),this.shortTerm.delete(t),e):(n.accessCount++,n.value):e}forget(t){return this.longTerm.delete(t)||this.shortTerm.delete(t)}recordEpisode(t,e,n={},s){let a={id:t,what:e,when:Date.now(),context:n,outcome:s};return this.episodes.push(a),a}searchEpisodes(t){return this.episodes.filter(e=>e.what.includes(t)||e.id.includes(t))}setWorking(t){this.working=t}getWorking(){return this.working}clearWorking(){this.working=null}searchByTag(t){return[...this.longTerm.values(),...this.shortTerm.values()].filter(e=>e.tags.includes(t))}keys(t){return t==="short-term"?[...this.shortTerm.keys()]:t==="long-term"?[...this.longTerm.keys()]:[...this.longTerm.keys(),...this.shortTerm.keys()]}purgeExpired(){let t=0,e=Date.now();for(let[n,s]of this.shortTerm)s.ttl!=="forever"&&e-s.createdAt>s.ttl&&(this.shortTerm.delete(n),t++);for(let[n,s]of this.longTerm)s.ttl!=="forever"&&e-s.createdAt>s.ttl&&(this.longTerm.delete(n),t++);return t}stats(){return{longTerm:this.longTerm.size,shortTerm:this.shortTerm.size,episodes:this.episodes.length}}clear(){this.longTerm.clear(),this.shortTerm.clear(),this.episodes=[],this.working=null}},xe=new Ta;function ec(r){return r.toLowerCase().replace(/[^a-z0-9가-힣\s]/g,"").split(/\s+/).filter(Boolean)}function Yp(r,t){let e=new Set(t),n=r.filter(s=>e.has(s)).length;return n===0?0:n/(Math.sqrt(r.length)*Math.sqrt(t.length))}var Ca=class{constructor(){this.docs=[]}add(t){this.docs.push(t)}addMany(t){t.forEach(e=>this.add(e))}retrieve(t,e=3){let n=ec(t);return this.docs.map(s=>({...s,score:Yp(n,ec(s.content))})).filter(s=>(s.score??0)>0).sort((s,a)=>(a.score??0)-(s.score??0)).slice(0,e)}query(t,e={}){let n=this.retrieve(t,e.topK??3),s=e.augment?e.augment(t,n):`Query: ${t}
22
+
23
+ Context:
24
+ ${n.map(a=>a.content).join(`
25
+ ---
26
+ `)}`;return{query:t,retrieved:n,augmented:s}}remove(t){let e=this.docs.findIndex(n=>n.id===t);return e===-1?!1:(this.docs.splice(e,1),!0)}size(){return this.docs.length}all(){return[...this.docs]}clear(){this.docs=[]}},kn=new Ca;var Na=class{constructor(){this.agents=new Map;this.log=[];this.msgCounter=0}spawn(t,e){let n={id:t,handler:e,inbox:[],running:!0};return this.agents.set(t,n),n}send(t,e,n){let s={from:t,to:e,content:n,timestamp:Date.now(),id:`msg-${++this.msgCounter}`},a=this.agents.get(e);return a&&a.inbox.push(s),this.log.push(s),s}broadcast(t,e){return[...this.agents.keys()].filter(n=>n!==t).map(n=>this.send(t,n,e))}recv(t){let e=this.agents.get(t);return!e||e.inbox.length===0?null:e.inbox.shift()}process(t){let e=this.agents.get(t);if(!e)return[];let n=[];for(;e.inbox.length>0;){let s=e.inbox.shift();n.push(e.handler(s,this))}return n}stop(t){let e=this.agents.get(t);e&&(e.running=!1)}history(){return[...this.log]}list(){return[...this.agents.keys()]}inboxSize(t){return this.agents.get(t)?.inbox.length??0}size(){return this.agents.size}get(t){return this.agents.get(t)}},st=new Na;var Oa=class{constructor(){this.history=[]}async run(t){let e=[];for(let n=0;n<t.attempts.length;n++){let{strategy:s,fn:a,validate:i}=t.attempts[n];try{let o=await Promise.resolve(a());if(i?i(o):!0)return this.history.push({success:!0,value:o,attempt:n+1,strategy:s}),t.onSuccess?.(o,s,n+1),o;{let f="validation failed";e.push(`[${s}] ${f}`),this.history.push({success:!1,error:f,attempt:n+1,strategy:s})}}catch(o){let u=o instanceof Error?o.message:String(o);e.push(`[${s}] ${u}`),this.history.push({success:!1,error:u,attempt:n+1,strategy:s})}}if(t.onAllFail)return t.onAllFail(e);throw new Error(`All attempts failed:
27
+ ${e.join(`
28
+ `)}`)}getHistory(){return[...this.history]}lastSuccess(){let t=this.history.filter(e=>e.success);return t.length>0?t[t.length-1]:null}reset(){this.history=[]}};async function tc(r){if(r.length===0)throw new Error(`All attempts failed:
29
+ (no attempts provided)`);return new Oa().run({attempts:r.map(([e,n])=>({strategy:e,fn:n}))})}async function nc(r,t){try{return await Promise.resolve(r())}catch{return t}}var rc=require("events"),Fa=class extends rc.EventEmitter{constructor(){super(...arguments);this.chunks=[];this.chunkIndex=0;this._done=!1;this._collected=""}write(e){if(this._done)return;let n={index:this.chunkIndex++,content:e,done:!1,timestamp:Date.now()};this.chunks.push(n),this._collected+=e,this.emit("chunk",n)}end(){if(this._done)return;this._done=!0;let e={index:this.chunkIndex++,content:"",done:!0,timestamp:Date.now()};this.chunks.push(e),this.emit("chunk",e),this.emit("end",this._collected)}collect(){return this._done?Promise.resolve(this._collected):new Promise(e=>{this.once("end",e)})}isDone(){return this._done}getChunks(){return[...this.chunks]}collected(){return this._collected}chunkCount(){return this.chunks.filter(e=>!e.done).length}};function sc(r,t,e=0){let n=t.split(" ");return new Promise(s=>{let a=0;function i(){if(a>=n.length){r.end(),s();return}r.write(a===0?n[a]:" "+n[a]),a++,e>0?setTimeout(i,e):i()}i()})}var Pa=new Map,Qp=0;function ac(){let r=`stream-${++Qp}`,t=new Fa;return Pa.set(r,t),{id:r,stream:t}}function kt(r){return Pa.get(r)??null}function ic(r){return Pa.delete(r)}function rs(r,t,e=.7){let n=0,s=0,a={},i=[];for(let u of t){let f=Math.max(0,Math.min(1,u.evaluate(r)));a[u.name]=f,s+=f*u.weight,n+=u.weight,f<e&&i.push(`${u.name}: ${(f*100).toFixed(0)}% (\uAE30\uC900 \uBBF8\uB2EC)`)}let o=n>0?s/n:0;return{score:o,passed:o>=e,breakdown:a,feedback:i}}var ss=[{name:"length",weight:.3,evaluate:r=>{let t=String(r);return t.length<10?.3:t.length<50?.7:1}},{name:"non-empty",weight:.4,evaluate:r=>r!=null&&r!==""?1:0},{name:"no-error",weight:.3,evaluate:r=>r instanceof Error||typeof r=="object"&&r?._tag==="Err"?0:1}];var Zp=[{concept:"define",code:"(define x 42)",description:"\uBCC0\uC218 \uC815\uC758",difficulty:"beginner",tags:["basic","variable"]},{concept:"lambda",code:"(lambda [$x $y] (+ $x $y))",description:"\uC775\uBA85 \uD568\uC218",difficulty:"beginner",tags:["function","basic"]},{concept:"if",code:'(if (> $x 0) "positive" "non-positive")',description:"\uC870\uAC74 \uBD84\uAE30",difficulty:"beginner",tags:["control","basic"]},{concept:"let",code:"(let [$a 1 $b 2] (+ $a $b))",description:"\uC9C0\uC5ED \uBCC0\uC218",difficulty:"beginner",tags:["variable","scope"]},{concept:"defn",code:"(defn add [$a $b] (+ $a $b))",description:"\uD568\uC218 \uC815\uC758",difficulty:"beginner",tags:["function"]},{concept:"pipe",code:"(-> $data parse-json filter-errors extract-values)",description:"\uD30C\uC774\uD504\uB77C\uC778",difficulty:"intermediate",tags:["pipeline","functional"]},{concept:"maybe",code:'(maybe 0.85 "Paris")',description:"\uBD88\uD655\uC2E4\uC131 \uD0C0\uC785",difficulty:"intermediate",tags:["ai","uncertainty"]},{concept:"result",code:`(ok 42)
30
+ (err "NOT_FOUND" "\uC5C6\uC74C")`,description:"Result \uD0C0\uC785",difficulty:"intermediate",tags:["error","result"]},{concept:"fl-try",code:`(fl-try (call-api $url)
31
+ :on-not-found (fn [$e] "fallback")
32
+ :default (fn [$e] (log $e)))`,description:"AI \uC5D0\uB7EC \uCC98\uB9AC",difficulty:"intermediate",tags:["error","ai"]},{concept:"parallel",code:"(parallel [(task-a) (task-b) (task-c)])",description:"\uBCD1\uB82C \uC2E4\uD589",difficulty:"intermediate",tags:["concurrency"]},{concept:"COT",code:'[COT :step "\uBD84\uC11D" (analyze $data) :step "\uCD94\uB860" (reason $prev) :conclude summarize]',description:"Chain-of-Thought",difficulty:"advanced",tags:["ai","reasoning"]},{concept:"TOT",code:'[TOT :branch "\uAC00\uC124A" $val1 :branch "\uAC00\uC124B" $val2 :eval score-fn :select best]',description:"Tree-of-Thought",difficulty:"advanced",tags:["ai","search"]},{concept:"REFLECT",code:"[REFLECT :output $result :criteria [accuracy completeness] :threshold 0.8]",description:"\uC790\uAE30 \uD3C9\uAC00",difficulty:"advanced",tags:["ai","reflect"]},{concept:"AGENT",code:'[AGENT :goal "\uB370\uC774\uD130 \uBD84\uC11D" :max-steps 5 :step (fn [$s] (analyze $s))]',description:"\uC5D0\uC774\uC804\uD2B8 \uB8E8\uD504",difficulty:"advanced",tags:["ai","agent"]},{concept:"SELF-IMPROVE",code:"(self-improve :target $code :evaluate score-fn :improve enhance-fn :iterations 3)",description:"\uC790\uAE30 \uAC1C\uC120",difficulty:"advanced",tags:["ai","improve"]}],ja=class{constructor(t=Zp){this.examples=t.map(e=>({...e,tags:[...e.tags]}))}findByConcept(t){return this.examples.filter(e=>e.concept.toLowerCase().includes(t.toLowerCase()))}findByTag(t){return this.examples.filter(e=>e.tags.includes(t))}findByDifficulty(t){return this.examples.filter(e=>e.difficulty===t)}lesson(t){let e=this.findByConcept(t),n=e.length>0?`${t}\uC740 FreeLang\uC758 \uD575\uC2EC \uAC1C\uB150\uC785\uB2C8\uB2E4.
33
+ ${e.map(a=>a.description).join(". ")}.`:`${t} \uAC1C\uB150\uC744 \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4.`,s=e.length>0?`; \uC5F0\uC2B5: ${e[0].description}
34
+ ; \uC544\uB798\uB97C \uC644\uC131\uD558\uC138\uC694:
35
+ ${e[0].code.replace(/\$\w+/g,"???")}`:`; ${t} \uC608\uC81C\uB97C \uC791\uC131\uD574\uBCF4\uC138\uC694`;return{concept:t,examples:e,explanation:n,exercise:s}}random(){return this.examples[Math.floor(Math.random()*this.examples.length)]}concepts(){return[...new Set(this.examples.map(t=>t.concept))]}addExample(t){this.examples.push(t)}size(){return this.examples.length}lessonMarkdown(t){let e=this.lesson(t),n=[`# FreeLang \uB808\uC2A8: ${e.concept}`,"","## \uC124\uBA85",e.explanation,""];if(e.examples.length>0){n.push("## \uC608\uC81C");for(let s of e.examples)n.push(`### ${s.concept} (${s.difficulty})`),n.push(`${s.description}`),n.push("```"),n.push(s.code),n.push("```"),n.push("")}return n.push("## \uC5F0\uC2B5 \uBB38\uC81C"),n.push("```"),n.push(e.exercise),n.push("```"),n.join(`
36
+ `)}},Qn=new ja;var Ia=class{constructor(t){this.stack=[];this.nodeCounter=0;this.root=this.makeNode("thought",t),this.current=this.root}makeNode(t,e,n){return{id:`node-${++this.nodeCounter}`,type:t,label:e,value:n,children:[],depth:this.stack.length,timestamp:Date.now()}}add(t,e,n){let s=this.makeNode(t,e,n);return this.current.children.push(s),s}enter(t,e,n){let s=this.makeNode(t,e,n);return this.current.children.push(s),this.stack.push(this.current),this.current=s,s}exit(t){this.stack.length>0&&(t!==void 0&&(this.current.value=t),this.current.duration=Date.now()-this.current.timestamp,this.current=this.stack.pop())}toMarkdown(){let t=["## Reasoning Trace",""];function e(n,s){let a=" ".repeat(s),i={thought:"\u{1F4AD}",action:"\u26A1",observation:"\u{1F441}",decision:"\u{1F3AF}",error:"\u274C",result:"\u2705"}[n.type],o=n.duration?` (${n.duration}ms)`:"",u=n.value!==void 0?` \u2192 \`${JSON.stringify(n.value)}\``:"";t.push(`${a}${i} **${n.label}**${u}${o}`),n.children.forEach(f=>e(f,s+1))}return e(this.root,0),t.join(`
37
+ `)}toTree(){let t=[];function e(n,s,a){let i=a?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",o=n.value!==void 0?`: ${JSON.stringify(n.value)}`:"";t.push(`${s}${i}[${n.type}] ${n.label}${o}`);let u=s+(a?" ":"\u2502 ");n.children.forEach((f,l)=>e(f,u,l===n.children.length-1))}return t.push(`[root] ${this.root.label}`),this.root.children.forEach((n,s)=>e(n,"",s===this.root.children.length-1)),t.join(`
38
+ `)}getRoot(){return this.root}getCurrent(){return this.current}depth(){return this.stack.length}nodeCount(){return this.nodeCounter}},oc=new Map,ef=0;function cc(r){let t=`trace-${++ef}`,e=new Ia(r);return oc.set(t,e),{id:t,trace:e}}function Vt(r){return oc.get(r)??null}var tf={COT:r=>({name:"chain-of-thought",priority:1,content:`Think step by step:
39
+ ${(r.steps??[]).map((t,e)=>`${e+1}. ${t}`).join(`
40
+ `)}
41
+ Then provide your conclusion.`}),TOT:r=>({name:"tree-of-thought",priority:1,content:`Explore multiple approaches:
42
+ ${(r.branches??[]).map(t=>`- ${t}`).join(`
43
+ `)}
44
+ Evaluate each and select the best.`}),REFLECT:r=>({name:"self-reflection",priority:.5,content:`After responding, reflect on:
45
+ ${(r.criteria??["accuracy","completeness"]).map(t=>`- ${t}`).join(`
46
+ `)}
47
+ Score each criterion (0-10) and revise if below ${(r.threshold??.7)*10}.`}),AGENT:r=>({name:"agent-loop",priority:1,content:`Goal: ${r.goal??"Complete the task"}
48
+ Max steps: ${r.maxSteps??5}
49
+ For each step: observe \u2192 think \u2192 act \u2192 verify.`}),CONTEXT:r=>({name:"context",priority:1,content:`Context window: ${r.maxTokens??4096} tokens. Strategy: ${r.strategy??"sliding"}.`}),"SELF-IMPROVE":r=>({name:"self-improvement",priority:.5,content:`Iterations: ${r.iterations??3}. After each response, evaluate and improve until satisfied.`})},La=class{constructor(t="claude"){this.target=t}compileBlock(t,e={}){let n=tf[t];return n?n(e):null}compile(t,e){let n=[...t].sort((i,o)=>o.priority-i.priority),s=[];this.target==="claude"?(s.push("Human: "+e),s.push(`
50
+ [Instructions]`),n.forEach(i=>{i.content&&s.push(i.content)}),s.push(`
51
+ Assistant:`)):this.target==="gpt"?(s.push("[System]"),n.forEach(i=>{i.content&&s.push(i.content)}),s.push(`
52
+ [User]: `+e)):(n.forEach(i=>{i.content&&s.push(i.content)}),s.push(`
53
+ `+e));let a=s.join(`
54
+ `);return{prompt:a,target:this.target,tokens:Math.ceil(a.length/4),sections:n.map(i=>i.name)}}compileFromCode(t,e){let n=[],s=/\[(COT|TOT|REFLECT|AGENT|CONTEXT|SELF-IMPROVE)[^\]]*\]/g,a;for(;(a=s.exec(t))!==null;){let i=a[1],o=this.compileBlock(i,{});o&&n.push(o)}return n.length===0&&n.push({name:"default",content:"",priority:.5}),this.compile(n,e)}setTarget(t){this.target=t}getTarget(){return this.target}},Zn=new La("claude");var Ba=class{constructor(){this.lines=[]}define(t,e){return this.lines.push(`(define ${t} ${e})`),this}defn(t,e,n){return this.lines.push(`(defn ${t} [${e.map(s=>"$"+s).join(" ")}] ${n})`),this}call(t,...e){return this.lines.push(`(${t} ${e.join(" ")})`),this}cot(t,e){let n=e.map(s=>`:step "${s}" nil`).join(" ");return this.lines.push(`[COT :goal "${t}" ${n} :conclude identity]`),this}agent(t,e=5){return this.lines.push(`[AGENT :goal "${t}" :max-steps ${e} :step (fn [$s] $s)]`),this}maybe(t,e){return this.lines.push(`(maybe ${t} ${e})`),this}result(t,e,n){return t==="ok"?this.lines.push(`(ok ${e})`):this.lines.push(`(err "${n??"ERROR"}" ${e})`),this}pipe(...t){return this.lines.push(`(-> $data ${t.join(" ")})`),this}comment(t){return this.lines.push(`; ${t}`),this}build(){return this.lines.join(`
55
+ `)}reset(){return this.lines=[],this}lineCount(){return this.lines.length}},Da=class{constructor(){this.version="9.0.0";this.features=["maybe","cot","tot","reflect","context","result","fl-try","use-tool","agent","self-improve","memory","rag","multi-agent","try-reason","streaming","quality-loop","tutor","debugger","prompt-compiler"]}builder(){return new Ba}block(t,e,n){return{type:t,code:e,description:n}}supports(t){return this.features.includes(t)}validate(t){let e=[],n=0;for(let s of t)if(s==="("||s==="[")n++;else if((s===")"||s==="]")&&(n--,n<0)){e.push("Unexpected closing bracket");break}return n>0&&e.push(`Unclosed brackets: ${n}`),{valid:e.length===0,errors:e}}snippet(t){return{maybe:'(maybe 0.8 "result")',ok:"(ok 42)",err:'(err "NOT_FOUND" "Item not found")',cot:'[COT :step "analyze" nil :conclude identity]',agent:'[AGENT :goal "task" :max-steps 5 :step (fn [$s] $s)]',reflect:"[REFLECT :output $result :criteria [accuracy] :threshold 0.8]",pipe:"(-> $data parse transform output)",memory:'(mem-remember "key" "value")',rag:'(rag-add "doc1" "content")'}[t]??`; ${t} snippet not found`}getConfig(){return{version:this.version,features:[...this.features]}}},vn=new Da;var er=class{test(t){let{claim:e,test:n,evaluate:s,maxAttempts:a=3,threshold:i=.7,conclude:o=m=>m>=i?"accepted":m<=1-i?"rejected":"inconclusive"}=t,u=[],f=0,l=0;for(let m=0;m<a;m++){l++;let d=n(m);if(u.push(d),f=s(u),f>=i||f<=1-i)break}let c=o(f),p=`${l}\uD68C \uD14C\uC2A4\uD2B8, \uC2E0\uB8B0\uB3C4 ${(f*100).toFixed(0)}% \u2192 ${c}`;return{claim:e,verdict:c,confidence:f,evidence:u,reasoning:p,iterations:l}}compete(t){return t.map(n=>this.test(n)).reduce((n,s)=>s.confidence>n.confidence?s:n)}},as=new er;function tr(r,t,e){if(r<0||r>1)throw new RangeError(`confidence\uB294 0.0~1.0 \uC0AC\uC774\uC5EC\uC57C \uD569\uB2C8\uB2E4: ${r}`);return e!==void 0?{_tag:"Maybe",value:t,confidence:r,reason:e}:{_tag:"Maybe",value:t,confidence:r}}function wn(r){return r!==void 0?{_tag:"None",reason:r}:{_tag:"None"}}function at(r){return r!==null&&typeof r=="object"&&r._tag==="Maybe"}function Se(r){return r!==null&&typeof r=="object"&&r._tag==="None"}function nf(r,t=.5){return Se(r)?null:r.confidence>=t?r.value:null}function rf(r){return r.length===0?wn("\uD6C4\uBCF4 \uC5C6\uC74C"):r.reduce((t,e)=>e.confidence>t.confidence?e:t)}function sf(r,t,e){return Se(r)||r.confidence<t?null:e(r.value)}function af(r,t,e){if(Se(r)||Se(t))return wn("\uD558\uB098 \uC774\uC0C1\uC774 None");let n=r.confidence*t.confidence,s=e(r.value,t.value),a=[r.reason,t.reason].filter(Boolean).join(" + ")||void 0;return a!==void 0?tr(n,s,a):tr(n,s)}function lc(r,t){function e(n,s){if(typeof n=="function")return n(...s);if(n&&n.kind==="function-value"&&r)return r(n,s);if(typeof n=="string"&&t)return t(n,s);throw new Error("fn is not a function")}return{maybe:(n,s,a)=>tr(n,s,a),"uncertain-none":n=>wn(n),"is-maybe?":n=>at(n),"is-none?":n=>Se(n),confident:(n,s=.5)=>nf(n,s),"most-likely":n=>{if(!Array.isArray(n))return wn("\uC785\uB825\uC774 \uBC30\uC5F4\uC774 \uC544\uB2D8");let s=n.filter(at);return rf(s)},"when-confident":(n,s,a)=>sf(n,s,i=>e(a,[i])),combine:(n,s,a)=>af(n,s,(i,o)=>e(a,[i,o])),"maybe-confidence":n=>at(n)?n.confidence:null,"maybe-value":n=>at(n)?n.value:null,"maybe-reason":n=>at(n)&&n.reason!==void 0?n.reason:null}}function of(r){return Math.max(0,Math.min(1,r))}function is(r,t){return tr(of(r),t)}function vt(r){return wn(r)}function uc(r,t){return Se(r)?vt("none \uC785\uB825"):is(r.confidence,t(r.value))}function pc(r,t){if(Se(r))return vt("none \uC785\uB825");let e=t(r.value);return Se(e)?vt("fn\uC774 none \uBC18\uD658"):is(r.confidence*e.confidence,e.value)}function fc(r,t){if(r.some(a=>Se(a)))return vt("\uD558\uB098 \uC774\uC0C1\uC774 none");let e=r,n=e.reduce((a,i)=>a*i.confidence,1),s=e.map(a=>a.value);return is(n,t(...s))}function mc(r,t){return Se(r)?vt("none \uC785\uB825"):t(r.value)?r:vt("\uC870\uAC74 \uBD88\uB9CC\uC871")}function dc(r,t,e){return Se(r)||Se(t)?vt("\uD558\uB098 \uC774\uC0C1\uC774 none"):is(r.confidence*t.confidence,e(r.value,t.value))}function gc(r){let t=r.filter(e=>at(e));return t.length===0?vt("\uD6C4\uBCF4 \uC5C6\uC74C"):t.reduce((e,n)=>n.confidence>e.confidence?n:e)}var nr=class{debate(t){let{proposition:e,pro:n,con:s,rounds:a=3}=t,i=t.judge??((d,g)=>d>g?"pro":g>d?"con":"tie"),o=[],u=[],f=[];for(let d=1;d<=a;d++){let g=n(d,f);u.push(g);let h=s(d,u);f.push(h),o.push({round:d,proArgument:g,conArgument:h})}let l=u.reduce((d,g)=>d+g.strength,0)/u.length,c=f.reduce((d,g)=>d+g.strength,0)/f.length,p=i(l,c),m=p==="tie"?`"${e}" \u2014 \uD33D\uD33D\uD55C \uB17C\uC7C1 (pro: ${l.toFixed(2)}, con: ${c.toFixed(2)})`:`"${e}" \u2014 ${p==="pro"?"\uCC44\uD0DD":"\uAE30\uAC01"} (\uC2B9\uC790: ${p})`;return{proposition:e,winner:p,proScore:l,conScore:c,rounds:o,conclusion:m}}},os=new nr;var rr=class{constructor(){this.checkpoints=new Map;this.depth=0}save(t,e){let n=typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e)),s={name:t,state:n,timestamp:Date.now(),depth:this.depth};this.checkpoints.has(t)||this.checkpoints.set(t,[]),this.checkpoints.get(t).push(s)}restore(t){let e=this.checkpoints.get(t);return!e||e.length===0?null:e[e.length-1].state}restoreAt(t,e){let n=this.checkpoints.get(t);return!n||e<0||e>=n.length?null:n[e].state}getEntries(t){return this.checkpoints.get(t)??[]}branch(t,e,n){this.save(t,e),this.depth++;try{let s=n(e);return this.depth--,{success:!0,result:s,restored:e}}catch{return this.depth--,{success:!1,restored:this.restore(t)}}}drop(t){return this.checkpoints.delete(t)}list(){return[...this.checkpoints.keys()]}versions(t){return this.checkpoints.get(t)?.length??0}getDepth(){return this.depth}clear(){this.checkpoints.clear(),this.depth=0}},zt=new rr;var cf=["COT","TOT","HYPOTHESIS","DEBATE","REFLECT","DIRECT"];function lf(r,t){let e=r.toLowerCase(),n=.5,s="";switch(t){case"COT":n=e.includes("step")||e.includes("\uB2E8\uACC4")||e.includes("\uC21C\uC11C")||e.includes("how")?.9:.5,s="\uC21C\uCC28\uC801 \uB2E8\uACC4 \uCD94\uB860";break;case"TOT":n=e.includes("option")||e.includes("\uBC29\uBC95")||e.includes("compare")||e.includes("which")?.9:.4,s="\uBD84\uAE30 \uD0D0\uC0C9 \uD544\uC694";break;case"HYPOTHESIS":n=e.includes("verify")||e.includes("\uB9DE")||e.includes("correct")||e.includes("true")?.85:.4,s="\uAC00\uC124 \uAC80\uC99D \uD544\uC694";break;case"DEBATE":n=e.includes("should")||e.includes("better")||e.includes("vs")||e.includes("\uACB0\uC815")?.85:.35,s="\uCC2C\uBC18 \uAD6C\uC870 \uBD84\uC11D";break;case"REFLECT":n=e.includes("quality")||e.includes("improve")||e.includes("review")||e.includes("\uD3C9\uAC00")?.8:.4,s="\uC790\uAE30 \uD3C9\uAC00 \uD544\uC694";break;case"DIRECT":n=e.length<30?.8:.3,s="\uB2E8\uC21C \uC9C1\uC811 \uC751\uB2F5";break}return n=Math.max(0,Math.min(1,n)),{strategy:t,score:n,reason:s}}var sr=class{constructor(t=[...cf]){this.strategies=t}analyze(t){let e=this.strategies.map(a=>lf(t,a));e.sort((a,i)=>i.score-a.score);let n=e[0].strategy,s=`"${t.slice(0,50)}" \u2192 ${n} \uC120\uD0DD (\uC810\uC218: ${e[0].score.toFixed(2)}, \uC774\uC720: ${e[0].reason})`;return{problem:t,selected:n,scores:e,rationale:s}}addStrategy(t){this.strategies.includes(t)||this.strategies.push(t)}getStrategies(){return[...this.strategies]}},cs=new sr;var ar=class{constructor(){this.beliefs=new Map}set(t,e){let n=Math.max(0,Math.min(1,e)),s=this.beliefs.get(t);if(s){let a=n-s.confidence;s.confidence=n,s.history.push({event:"set",delta:a,timestamp:Date.now()})}else this.beliefs.set(t,{claim:t,confidence:n,history:[{event:"initialized",delta:0,timestamp:Date.now()}],createdAt:Date.now()})}get(t){return this.beliefs.get(t)?.confidence??null}update(t,e,n="evidence"){let s=this.beliefs.get(t);if(!s)return 0;let a=s.confidence,i=e>.5?e:1-e,u=(e>.5?1:-1)*i*(1-Math.abs(a-.5))*.3,f=Math.max(.01,Math.min(.99,a+u));return s.history.push({event:n,delta:f-a,timestamp:Date.now()}),s.confidence=f,f}negate(t){return this.update(t,.1,"negation")}list(){return[...this.beliefs.values()]}strongest(){let t=this.list();return t.length===0?null:t.reduce((e,n)=>n.confidence>e.confidence?n:e)}certain(t=.8){return this.list().filter(e=>e.confidence>=t)}forget(t){return this.beliefs.delete(t)}size(){return this.beliefs.size}},Ge=new ar;function uf(r,t){let e=new Set(r.toLowerCase().split(/\s+/)),n=new Set(t.toLowerCase().split(/\s+/)),s=[...e].filter(a=>n.has(a)).length;return s===0?0:s/Math.sqrt(e.size*n.size)}var ir=class{constructor(){this.patterns=[];this.counter=0}store(t,e,n=[]){let s={id:`pattern-${++this.counter}`,description:t,solution:e,tags:n,useCount:0};return this.patterns.push(s),s}find(t,e=3){return this.patterns.map(n=>({...n,similarity:uf(t,n.description)+n.tags.filter(s=>t.toLowerCase().includes(s)).length*.1})).filter(n=>(n.similarity??0)>0).sort((n,s)=>(s.similarity??0)-(n.similarity??0)).slice(0,e)}best(t){let e=this.find(t,1);if(e.length===0)return null;let n=this.patterns.find(s=>s.id===e[0].id);return n&&n.useCount++,e[0]}byTag(t){return this.patterns.filter(e=>e.tags.includes(t))}popular(t=3){return[...this.patterns].sort((e,n)=>n.useCount-e.useCount).slice(0,t)}size(){return this.patterns.length}all(){return[...this.patterns]}},wt=new ir;function pf(r){return{critical:1,major:.7,minor:.3,suggestion:.1}[r]}var or=class{run(t,e){let{finders:n,riskThreshold:s=.5}=e,a=n.flatMap(p=>{try{return p(t)}catch{return[]}}),i=a.length===0?0:a.reduce((p,m)=>p+pf(m.severity),0)/(a.length*1),o=Math.min(1,i),u=o<s&&!a.some(p=>p.severity==="critical"),f=a.filter(p=>p.severity==="critical").length,l=a.filter(p=>p.severity==="major").length,c=a.length===0?"\uBE44\uD310\uD560 \uC810 \uC5C6\uC74C \u2014 \uD1B5\uACFC":`${a.length}\uAC1C \uBB38\uC81C \uBC1C\uACAC (critical: ${f}, major: ${l}), \uC704\uD5D8\uB3C4: ${(o*100).toFixed(0)}%`;return{output:t,points:a,overallRisk:o,approved:u,summary:c}}},Wt=[r=>r==null||r===""?[{type:"missing",description:"\uCD9C\uB825\uC774 \uBE44\uC5B4\uC788\uC74C",severity:"critical"}]:[],r=>typeof r=="string"&&r.length>0&&r.length<5?[{type:"weakness",description:"\uCD9C\uB825\uC774 \uB108\uBB34 \uC9E7\uC74C",severity:"minor",suggestion:"\uB354 \uAD6C\uCCB4\uC801\uC73C\uB85C \uC11C\uC220"}]:[],r=>r instanceof Error||typeof r=="object"&&r!==null&&r?._tag==="Err"?[{type:"weakness",description:"\uC5D0\uB7EC \uAC12\uC774 \uCD9C\uB825\uB428",severity:"major"}]:[]],cr=new or;var lr=class{compose(t,e){let n=Date.now(),s={step:0,history:[],store:new Map},a=e,i=!0;for(let o of t){if(o.condition&&!o.condition(a,s)){s.history.push({name:`${o.name}(skipped)`,input:a,output:a,duration:0}),s.step++;continue}let u=Date.now();try{let f=o.fn(a,s);s.history.push({name:o.name,input:a,output:f,duration:Date.now()-u}),a=f}catch(f){if(o.onError){let l=o.onError(f,a);s.history.push({name:`${o.name}(error\u2192fallback)`,input:a,output:l,duration:Date.now()-u}),a=l}else{i=!1,s.history.push({name:`${o.name}(failed)`,input:a,output:null,duration:Date.now()-u});break}}s.step++}return{output:a,steps:s.step,history:s.history,success:i,duration:Date.now()-n}}pipeline(){return new qa(this)}},qa=class{constructor(t){this.steps=[];this.composer=t}step(t,e,n={}){return this.steps.push({name:t,fn:e,...n}),this}run(t){return this.composer.compose(this.steps,t)}stepCount(){return this.steps.length}},ls=new lr;var Ua=class{constructor(){this.meta=new sr,this.beliefs=new ar,this.analogies=new ir,this.hypothesis=new er,this.critique=new or,this.composer=new lr,this.debater=new nr,this.checkpoints=new rr}solve(t,e){let s=this.meta.analyze(t).selected;this.checkpoints.save("pre-solve",{problem:t,strategy:s});let a=this.analogies.best(t),i=e(s,t),o=this.critique.run(i,{finders:Wt});this.beliefs.set(`solved:${t.slice(0,20)}`,o.approved?.8:.4);let u={problem:t,strategy:s,beliefs:new Map([["solved",o.approved?.8:.4]]),analogies:a?[a.description]:[],output:i,critique:{approved:o.approved,risk:o.overallRisk},iterations:1};return{strategy:s,output:i,approved:o.approved,risk:o.overallRisk,state:u}}stats(){return{beliefs:this.beliefs.size(),analogies:this.analogies.size(),checkpoints:this.checkpoints.list().length}}},_n=new Ua;var ur=class{majority(t){if(!t||t.length===0)throw new Error("votes\uAC00 \uBE44\uC5B4\uC788\uC74C");let e=new Map;for(let o of t){let u=JSON.stringify(o.answer),f=e.get(u)??{answer:o.answer,count:0,totalConf:0};f.count++,f.totalConf+=o.confidence,e.set(u,f)}let s=[...e.values()].sort((o,u)=>u.count-o.count)[0],a=s.count/t.length,i=JSON.stringify(s.answer);return{answer:s.answer,strategy:"majority",agreement:a,votes:t,dissent:t.filter(o=>JSON.stringify(o.answer)!==i)}}weighted(t){if(!t||t.length===0)throw new Error("votes\uAC00 \uBE44\uC5B4\uC788\uC74C");let e=t.reduce((u,f)=>u+f.confidence,0),n=t.reduce((u,f)=>u+f.answer*f.confidence,0)/e,s=t.map(u=>u.answer),a=Math.max(...s)-Math.min(...s),i=t.reduce((u,f)=>u+Math.abs(f.answer-n)*f.confidence,0)/e,o=Math.max(0,1-i/(a+1));return{answer:n,strategy:"weighted",agreement:o,votes:t,dissent:[]}}threshold(t,e=.7){if(!t||t.length===0)return null;let n=new Map;for(let s of t){let a=JSON.stringify(s.answer);n.has(a)||n.set(a,[]),n.get(a).push(s)}for(let[s,a]of n){let i=a.reduce((o,u)=>o+u.confidence,0)/a.length;if(i>=e)return{answer:a[0].answer,strategy:"threshold",agreement:i,votes:t,dissent:t.filter(o=>JSON.stringify(o.answer)!==s)}}return null}unanimous(t){if(!t||t.length===0)return null;let e=JSON.stringify(t[0].answer);return t.every(n=>JSON.stringify(n.answer)===e)?{answer:t[0].answer,strategy:"unanimous",agreement:1,votes:t,dissent:[]}:null}agreement(t){return!t||t.length===0?0:this.majority(t).agreement}},Sn=new ur;var xn=class{constructor(){this.agents=new Map}register(t){this.agents.set(t.id,t)}findCapable(t){return[...this.agents.values()].filter(e=>e.capabilities.includes(t))}delegate(t){let e=t.requiredCapability?this.findCapable(t.requiredCapability):[...this.agents.values()];if(e.length===0)return{taskId:t.id,agentId:"none",output:null,success:!1,duration:0};let n=e[0],s=Date.now();try{let a=n.execute(t);return{taskId:t.id,agentId:n.id,output:a,success:!0,duration:Date.now()-s}}catch{return{taskId:t.id,agentId:n.id,output:null,success:!1,duration:Date.now()-s}}}delegateAll(t){let e=Date.now(),n=t.map(s=>this.delegate(s));return{results:n,successful:n.filter(s=>s.success).length,failed:n.filter(s=>!s.success).length,totalDuration:Date.now()-e}}list(){return[...this.agents.keys()]}size(){return this.agents.size}},An=new xn;var pr=class{negotiate(t,e=5){let n=[],s={};t.forEach(a=>{s[a.agentId]=a.offer});for(let a=1;a<=e;a++){let i=Object.values(s),o=Math.max(...i)-Math.min(...i);n.push({round:a,offers:{...s},gap:o});let u=i.reduce((l,c)=>l+c,0)/i.length;if(t.every(l=>u>=l.minAccept&&u<=l.maxOffer)||o<.01)return{agreed:!0,value:u,rounds:n,breakdown:`${a}\uB77C\uC6B4\uB4DC\uC5D0 \uD569\uC758 (\uAC12: ${u.toFixed(3)})`};t.forEach(l=>{let c=s[l.agentId],p=(u-c)*l.flexibility*.5;s[l.agentId]=Math.max(l.minAccept,Math.min(l.maxOffer,c+p))})}return{agreed:!1,rounds:n,breakdown:`${e}\uB77C\uC6B4\uB4DC \uD6C4 \uD611\uC0C1 \uACB0\uB82C`}}},fr=new pr;var mr=class{plurality(t,e){let n={};e.forEach(a=>n[a]=0),t.forEach(a=>{a.choices[0]&&(n[a.choices[0]]=(n[a.choices[0]]??0)+1)});let s=[...e].sort((a,i)=>n[i]-n[a]);return{winner:s[0],method:"plurality",tally:n,totalVoters:t.length,margin:n[s[0]]-(n[s[1]]??0)}}approval(t,e){let n={};e.forEach(a=>n[a]=0),t.forEach(a=>a.choices.forEach(i=>{n.hasOwnProperty(i)&&(n[i]=(n[i]??0)+1)}));let s=[...e].sort((a,i)=>n[i]-n[a]);return{winner:s[0],method:"approval",tally:n,totalVoters:t.length,margin:n[s[0]]-(n[s[1]]??0)}}ranked(t,e){let n=[...e],s=t.map(i=>({...i,choices:[...i.choices]}));for(;n.length>1;){let i={};n.forEach(f=>i[f]=0),s.forEach(f=>{let l=f.choices.find(c=>n.includes(c));l&&(i[l]=(i[l]??0)+1)});let o=Object.values(i).reduce((f,l)=>f+l,0),u=[...n].sort((f,l)=>i[l]-i[f]);if(i[u[0]]>o/2){let f={};return e.forEach(l=>f[l]=0),n.forEach(l=>f[l]=i[l]),{winner:u[0],method:"ranked",tally:f,totalVoters:t.length,margin:i[u[0]]-(i[u[1]]??0)}}n=n.filter(f=>f!==u[u.length-1])}let a={};return e.forEach(i=>a[i]=0),n[0]&&(a[n[0]]=t.length),{winner:n[0]??e[0],method:"ranked",tally:a,totalVoters:t.length,margin:0}}score(t,e){let n={};e.forEach(a=>n[a]=0),t.forEach(a=>{a.scores&&e.forEach(i=>{n[i]+=a.scores[i]??0})});let s=[...e].sort((a,i)=>n[i]-n[a]);return{winner:s[0],method:"score",tally:n,totalVoters:t.length,margin:n[s[0]]-(n[s[1]]??0)}}tally(t,e){let n={};return e.forEach(s=>n[s]=0),t.forEach(s=>{s.choices[0]&&(n[s.choices[0]]=(n[s.choices[0]]??0)+1)}),n}},$n=new mr;var dr=class{optimize(t){let{objective:e,particles:n=10,iterations:s=50,bounds:a=[0,1],tolerance:i=.001}=t,[o,u]=a,f=u-o,l=Array.from({length:n},(g,h)=>{let y=o+Math.random()*f,k=e(y);return{id:`p${h}`,position:y,velocity:(Math.random()-.5)*f*.1,bestPosition:y,bestScore:k}}),c=l.reduce((g,h)=>h.bestScore>g.bestScore?h:g),p=-1/0,m=0,d=!1;for(m=0;m<s;m++){for(let g of l){g.velocity=.7*g.velocity+1.5*Math.random()*(g.bestPosition-g.position)+1.5*Math.random()*(c.bestPosition-g.position),g.position=Math.max(o,Math.min(u,g.position+g.velocity));let v=e(g.position);v>g.bestScore&&(g.bestScore=v,g.bestPosition=g.position),v>c.bestScore&&(c=g)}if(Math.abs(c.bestScore-p)<i){d=!0;break}p=c.bestScore}return{bestPosition:c.bestPosition,bestScore:c.bestScore,iterations:m+1,particles:l,converged:d}}},gr=new dr;var En=class{constructor(){this.reviewers=new Map}addReviewer(t){this.reviewers.set(t.id,t)}review(t,e,n,s=.7){let i=(n?n.map(c=>this.reviewers.get(c)).filter(Boolean):[...this.reviewers.values()]).map(c=>c.review(e)),o=i.length>0?i.reduce((c,p)=>c+p.score,0)/i.length:0,u=o>=s,f=i.filter(c=>c.score<s),l=u?`\uC2B9\uC778 (\uD3C9\uADE0 \uC810\uC218: ${o.toFixed(2)})`:`\uBC18\uB824 \u2014 ${f.length}\uAC1C \uBB38\uC81C: ${f.map(c=>c.aspect).join(", ")}`;return{targetId:t,output:e,comments:i,averageScore:o,approved:u,summary:l}}list(){return[...this.reviewers.keys()]}size(){return this.reviewers.size}},Ht=new En;var Mn=class{constructor(){this.competitors=new Map}register(t){this.competitors.set(t.id,t)}run(t,e){let n=[];for(let i of this.competitors.values())try{let o=i.solve(t);n.push({agentId:i.id,output:o,score:e(o)})}catch{n.push({agentId:i.id,output:null,score:-1/0})}n.sort((i,o)=>o.score-i.score);let s=n.map((i,o)=>({...i,rank:o+1})),a=s.length>=2?s[0].score-s[1].score:s[0]?.score??0;return{winner:s[0],allResults:s,margin:a}}tournament(t,e){return this.run(t,e)}list(){return[...this.competitors.keys()]}size(){return this.competitors.size}},Gt=new Mn;var Ke=class r{constructor(){this.agents=[]}add(t){return this.agents.push(t),this}run(t){let e=[],n=t,s=!0;for(let a of this.agents){let i=Date.now();try{let o=a.transform(n),u=a.validate?a.validate(o):!0;e.push({agentId:a.id,input:n,output:o,duration:Date.now()-i,skipped:!u}),u&&(n=o)}catch{e.push({agentId:a.id,input:n,output:null,duration:Date.now()-i,skipped:!0}),s=!1;break}}return{finalOutput:n,links:e,success:s,stepsCompleted:e.filter(a=>!a.skipped).length}}static from(t){let e=new r;return t.forEach(n=>e.add(n)),e}length(){return this.agents.length}},ff=new Ke;var Rn=class{constructor(){this.agents=new Map}register(t){this.agents.set(t.id,t)}list(){return[...this.agents.keys()]}topSort(t){let e=[],n=new Set,s=new Map(t.map(i=>[i.id,i])),a=i=>{if(n.has(i))return;n.add(i);let o=s.get(i);if(o?.dependsOn)for(let u of o.dependsOn)a(u);e.push(i)};for(let i of t)a(i.id);return e}run(t){let e=Date.now(),n={},s=this.topSort(t),a=new Map(t.map(i=>[i.id,i]));if(t.length===0)return{outputs:n,order:[],duration:Date.now()-e,success:!0};try{for(let i of s){let o=a.get(i);if(!o)continue;let u=this.agents.get(i)??this.agents.values().next().value;if(!u)continue;let f=(o.dependsOn??[]).map(c=>n[c]),l=f.length>0?{...o.input,deps:f}:o.input;n[i]=u.run(l)}return{outputs:n,order:s,duration:Date.now()-e,success:!0}}catch{return{outputs:n,order:s,duration:Date.now()-e,success:!1}}}getOrder(t){return this.topSort(t)}},us=new Rn;var Va=class{constructor(){this.consensus=new ur,this.delegation=new xn,this.voting=new mr,this.negotiator=new pr,this.swarm=new dr,this.orchestrator=new Rn,this.peerReview=new En,this.chain=new Ke,this.competition=new Mn}route(t,e,n=[]){let s=Date.now();switch(t){case"consensus":{let a=Array.isArray(n)?n.map((o,u)=>({agentId:o.id??`agent-${u}`,answer:typeof o.solve=="function"?o.solve(e):o.answer??e,confidence:o.confidence??.8})):[{agentId:"default",answer:e,confidence:1}],i=this.consensus.majority(a.length>0?a:[{agentId:"solo",answer:e,confidence:1}]);return{taskType:t,result:i.answer,system:"ConsensusEngine",timestamp:s}}case"delegate":{if(n.length===0)return{taskType:t,result:e,system:"DelegationManager",timestamp:s};let a=new xn;n.forEach(u=>{u.id&&u.execute?a.register(u):a.register({id:u.id??"default",capabilities:u.capabilities??["general"],execute:typeof u.solve=="function"?u.solve:()=>e})});let i=typeof e=="object"&&e.id?e:{id:"task-0",description:String(e),input:e},o=a.delegate(i);return{taskType:t,result:o.output,system:"DelegationManager",timestamp:s}}case"vote":{if(!Array.isArray(e?.ballots)||!Array.isArray(e?.candidates))return{taskType:t,result:e,system:"VotingSystem",timestamp:s};let a=this.voting.plurality(e.ballots,e.candidates);return{taskType:t,result:a.winner,system:"VotingSystem",timestamp:s}}case"negotiate":{if(!Array.isArray(e))return{taskType:t,result:null,system:"Negotiator",timestamp:s};let a=this.negotiator.negotiate(e);return{taskType:t,result:a.agreed?a.value:null,system:"Negotiator",timestamp:s}}case"swarm":{let a=typeof e=="function"?e:o=>-Math.abs(o-(e??0)),i=this.swarm.optimize({objective:a});return{taskType:t,result:i.bestPosition,system:"Swarm",timestamp:s}}case"orchestrate":{let a=new Rn;n.forEach(u=>{u.id&&u.run?a.register(u):u.id&&a.register({id:u.id,run:typeof u.solve=="function"?u.solve:f=>f})});let i=Array.isArray(e)?e:[{id:"task",input:e}],o=a.run(i);return{taskType:t,result:o.outputs,system:"Orchestrator",timestamp:s}}case"peer-review":{let a=new En;n.forEach((o,u)=>{a.addReviewer({id:o.id??`reviewer-${u}`,review:f=>({reviewerId:o.id??`reviewer-${u}`,aspect:"quality",score:typeof o.score=="function"?o.score(f):o.score??.8,comment:o.comment??"OK"})})}),a.size()===0&&a.addReviewer({id:"default-reviewer",review:o=>({reviewerId:"default-reviewer",aspect:"quality",score:.8,comment:"OK"})});let i=a.review("target",e);return{taskType:t,result:i.approved,system:"PeerReviewSystem",timestamp:s}}case"chain":{let a=new Ke;if(n.forEach((o,u)=>{a.add({id:o.id??`chain-${u}`,transform:typeof o.transform=="function"?o.transform:typeof o.process=="function"?o.process:typeof o.solve=="function"?o.solve:f=>f})}),a.length()===0)return{taskType:t,result:e,system:"AgentChain",timestamp:s};let i=a.run(e);return{taskType:t,result:i.finalOutput,system:"AgentChain",timestamp:s}}case"compete":{if(n.length===0)return{taskType:t,result:e,system:"Competition",timestamp:s};let a=new Mn;n.forEach((f,l)=>{a.register({id:f.id??`competitor-${l}`,solve:typeof f.solve=="function"?f.solve:()=>e})});let i=typeof e?.evaluate=="function"?e.evaluate:f=>typeof f=="number"?f:1,o=e?.task??e,u=a.run(o,i);return{taskType:t,result:u.winner.output,system:"Competition",timestamp:s}}default:return{taskType:t,result:e,system:"passthrough",timestamp:s}}}stats(){return{systems:9,ready:9,phases:9,tier:8}}systems(){return["ConsensusEngine","DelegationManager","VotingSystem","Negotiator","Swarm","Orchestrator","PeerReviewSystem","AgentChain","Competition"]}taskTypes(){return["consensus","delegate","vote","negotiate","swarm","orchestrate","peer-review","chain","compete"]}},hr=new Va;var za=require("crypto"),Je=class{constructor(t){this.population=[];this.currentGeneration=0;this.history=[];this.config={populationSize:t.populationSize??20,maxGenerations:t.maxGenerations??50,mutationRate:t.mutationRate??.1,eliteRatio:t.eliteRatio??.1,fitnessGoal:t.fitnessGoal,fitnessFunc:t.fitnessFunc,mutateFunc:t.mutateFunc,crossoverFunc:t.crossoverFunc,initFunc:t.initFunc}}initialize(){this.population=[],this.currentGeneration=0,this.history=[];for(let t=0;t<this.config.populationSize;t++){let e=this.config.initFunc(),n=this.config.fitnessFunc(e);this.population.push({genome:e,fitness:n,generation:0,id:(0,za.randomUUID)()})}}select(){let t=Math.max(2,Math.floor(this.population.length*.2)),e=[];for(let n=0;n<t;n++){let s=Math.floor(Math.random()*this.population.length);e.push(this.population[s])}return e.reduce((n,s)=>s.fitness>n.fitness?s:n)}step(){if(this.population.length===0)throw new Error("Population not initialized. Call initialize() first.");this.population.sort((i,o)=>o.fitness-i.fitness);let t=Math.max(1,Math.floor(this.config.populationSize*this.config.eliteRatio)),n=[...this.population.slice(0,t).map(i=>({...i}))];for(;n.length<this.config.populationSize;){let i=this.select(),o=this.select(),u=this.config.crossoverFunc(i.genome,o.genome);u=this.config.mutateFunc(u,this.config.mutationRate);let f=this.config.fitnessFunc(u);n.push({genome:u,fitness:f,generation:this.currentGeneration+1,id:(0,za.randomUUID)()})}this.population=n,this.currentGeneration++;let s=this.population[0]?.fitness??0,a=this.population.reduce((i,o)=>i+o.fitness,0)/this.population.length;return this.history.push({gen:this.currentGeneration,bestFitness:s,avgFitness:a}),{bestFitness:s,avgFitness:a}}run(){this.population.length===0&&this.initialize();let t=!1;for(let n=0;n<this.config.maxGenerations;n++){this.step();let s=this.getBest();if(s&&this.config.fitnessGoal!==void 0&&s.fitness>=this.config.fitnessGoal){t=!0;break}}return{best:this.getBest(),population:[...this.population],generations:this.currentGeneration,converged:t,history:[...this.history]}}getBest(){return this.population.length===0?null:this.population.reduce((t,e)=>e.fitness>t.fitness?e:t)}getPopulation(){return[...this.population]}getHistory(){return[...this.history]}};function hc(r,t=20,e=50){let n={populationSize:t,maxGenerations:e,mutationRate:.2,eliteRatio:.1,fitnessGoal:0,fitnessFunc:a=>-(a.reduce((o,u,f)=>{let l=u-(r[f]??0);return o+l*l},0)/a.length),mutateFunc:(a,i)=>a.map(o=>Math.random()<i?o+(Math.random()-.5)*2:o),crossoverFunc:(a,i)=>{let o=Math.floor(Math.random()*Math.min(a.length,i.length));return[...a.slice(0,o),...i.slice(o)]},initFunc:()=>r.map(()=>(Math.random()-.5)*20)};return new Je(n).run()}function yc(r,t=30,e=100){let n="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 !.,",s={populationSize:t,maxGenerations:e,mutationRate:.05,eliteRatio:.1,fitnessGoal:0,fitnessFunc:i=>{let o=0;for(let u=0;u<Math.max(i.length,r.length);u++){let f=i.charCodeAt(u)||0,l=r.charCodeAt(u)||0;o-=Math.abs(f-l)}return o},mutateFunc:(i,o)=>{let u=i;for(let f=0;f<u.length;f++)if(Math.random()<o){let l=n[Math.floor(Math.random()*n.length)];u=u.slice(0,f)+l+u.slice(f+1)}return u},crossoverFunc:(i,o)=>{let u=Math.max(i.length,o.length),f=Math.floor(Math.random()*u);return i.slice(0,f)+o.slice(f)},initFunc:()=>Array.from({length:r.length},()=>n[Math.floor(Math.random()*n.length)]).join("")};return new Je(s).run()}var mf={rate:.1,strength:.1,type:"random"},Tn="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",Be=class{constructor(t){this.config={...mf,...t}}getConfig(){return{...this.config}}mutateNumbers(t){let e=[...t],n=[...t],s=0,a=this.config.type;if(a==="swap")return this.swapMutation(t);if(a==="flip")return this.flipMutation(t);for(let i=0;i<n.length;i++)if(Math.random()<this.config.rate){if(a==="gaussian"){let o=Math.random(),u=Math.random(),f=Math.sqrt(-2*Math.log(o))*Math.cos(2*Math.PI*u);n[i]=n[i]+f*this.config.strength*(Math.abs(n[i])||1)}else{let o=(Math.random()*2-1)*this.config.strength*(Math.abs(n[i])||1);n[i]=n[i]+o}s++}return{original:e,mutated:n,mutations:s,mutationType:a}}mutateString(t){let e=t,n=this.config.type,s=t,a=0;if(n==="insert"){let i=t.split(""),o=[];for(let u=0;u<i.length;u++)if(o.push(i[u]),Math.random()<this.config.rate){let f=Tn[Math.floor(Math.random()*Tn.length)];o.push(f),a++}s=o.join("")}else if(n==="delete"){let i=t.split(""),o=[];for(let u of i)Math.random()<this.config.rate?a++:o.push(u);s=o.join("")}else if(n==="swap"){let i=t.split("");for(let o=0;o<i.length-1;o++)if(Math.random()<this.config.rate){let u=i[o];i[o]=i[o+1],i[o+1]=u,a++,o++}s=i.join("")}else{let i=t.split("");for(let o=0;o<i.length;o++)Math.random()<this.config.rate&&(i[o]=Tn[Math.floor(Math.random()*Tn.length)],a++);s=i.join("")}return{original:e,mutated:s,mutations:a,mutationType:n}}mutateObject(t){let e=JSON.parse(JSON.stringify(t)),n=JSON.parse(JSON.stringify(t)),s=0,a=this.config.type;for(let i of Object.keys(n))if(Math.random()<this.config.rate){let o=n[i];if(typeof o=="number"){let u=(Math.random()*2-1)*this.config.strength*(Math.abs(o)||1);n[i]=o+u,s++}else if(typeof o=="string"){if(o.length>0){let u=Math.floor(Math.random()*o.length),f=Tn[Math.floor(Math.random()*Tn.length)];n[i]=o.slice(0,u)+f+o.slice(u+1),s++}}else typeof o=="boolean"&&(n[i]=!o,s++)}return{original:e,mutated:n,mutations:s,mutationType:a}}swapMutation(t){let e=[...t],n=[...t],s=0;for(let a=0;a<n.length-1;a++)if(Math.random()<this.config.rate){let i=Math.floor(Math.random()*(n.length-a-1))+a+1,o=n[a];n[a]=n[i],n[i]=o,s++}return{original:e,mutated:n,mutations:s,mutationType:"swap"}}flipMutation(t){let e=[...t],n=[...t],s=0;for(let a=0;a<n.length;a++)Math.random()<this.config.rate&&(n[a]=n[a]===0?1:0,s++);return{original:e,mutated:n,mutations:s,mutationType:"flip"}}select(t,e){return[...t].sort((s,a)=>a.fitness-s.fitness).slice(0,e).map(s=>s.value)}},bc=new Be;var yr=class{constructor(t){this.config={type:t?.type??"single-point",rate:t?.rate??.7,blendAlpha:t?.blendAlpha??.5}}singlePoint(t,e){let n=Math.min(t.length,e.length),s=n<=1?0:Math.floor(Math.random()*(n-1))+1,a=[...t.slice(0,s),...e.slice(s)],i=[...e.slice(0,s),...t.slice(s)];for(;a.length<t.length;)a.push(t[a.length]);for(;i.length<e.length;)i.push(e[i.length]);return{parent1:[...t],parent2:[...e],child1:a.slice(0,t.length),child2:i.slice(0,e.length),crossoverPoint:s,type:"single-point"}}twoPoint(t,e){let n=Math.min(t.length,e.length),s=n<=2?0:Math.floor(Math.random()*(n-1)),a=n<=2?n:Math.floor(Math.random()*(n-s-1))+s+1;s>=a&&(a=Math.min(s+1,n));let i=[...t.slice(0,s),...e.slice(s,a),...t.slice(a)],o=[...e.slice(0,s),...t.slice(s,a),...e.slice(a)];return{parent1:[...t],parent2:[...e],child1:i.slice(0,t.length),child2:o.slice(0,e.length),crossoverPoints:[s,a],type:"two-point"}}uniform(t,e){let n=Math.max(t.length,e.length),s=[],a=[];for(let i=0;i<n;i++){let o=i<t.length?t[i]:e[i],u=i<e.length?e[i]:t[i];Math.random()<.5?(s.push(o),a.push(u)):(s.push(u),a.push(o))}return{parent1:[...t],parent2:[...e],child1:s.slice(0,t.length),child2:a.slice(0,e.length),type:"uniform"}}arithmetic(t,e,n){let s=n??this.config.blendAlpha??.5,a=t.map((o,u)=>s*o+(1-s)*(e[u]??0)),i=t.map((o,u)=>(1-s)*o+s*(e[u]??0));return{parent1:[...t],parent2:[...e],child1:a,child2:i,type:"arithmetic"}}crossoverStrings(t,e){let n=t.split(""),s=e.split(""),a=this.singlePoint(n,s);return{parent1:t,parent2:e,child1:a.child1.join(""),child2:a.child2.join(""),crossoverPoint:a.crossoverPoint,type:"single-point"}}crossoverObjects(t,e){let n=Array.from(new Set([...Object.keys(t),...Object.keys(e)])),s={},a={};for(let i of n)Math.random()<.5?(s[i]=i in t?t[i]:e[i],a[i]=i in e?e[i]:t[i]):(s[i]=i in e?e[i]:t[i],a[i]=i in t?t[i]:e[i]);return{parent1:{...t},parent2:{...e},child1:s,child2:a,type:"uniform"}}cross(t,e){if(Array.isArray(t)&&Array.isArray(e))return t.every(a=>typeof a=="number")?this.arithmetic(t,e):this.singlePoint(t,e);if(typeof t=="string"&&typeof e=="string")return this.crossoverStrings(t,e);if(typeof t=="object"&&t!==null&&typeof e=="object"&&e!==null)return this.crossoverObjects(t,e);if(typeof t=="number"&&typeof e=="number"){let n=this.config.blendAlpha??.5;return{parent1:t,parent2:e,child1:n*t+(1-n)*e,child2:(1-n)*t+n*e,type:"arithmetic"}}return{parent1:t,parent2:e,child1:t,child2:e,type:this.config.type}}},_t=new yr;function df(r,t){let e=r.length,n=t.length,s=Array.from({length:e+1},(a,i)=>Array.from({length:n+1},(o,u)=>i===0?u:u===0?i:0));for(let a=1;a<=e;a++)for(let i=1;i<=n;i++)r[a-1]===t[i-1]?s[a][i]=s[a-1][i-1]:s[a][i]=1+Math.min(s[a-1][i-1],s[a-1][i],s[a][i-1]);return s[e][n]}var br=class{constructor(t={}){this.config={normalize:t.normalize!==!1,maximize:t.maximize!==!1,weights:t.weights??{}}}proximity(t,e,n){let s=Math.abs(t-e),a=n!==void 0?n:Math.abs(e)||1,i,o;return a===0?(i=s===0?1:0,o=i):(i=Math.max(0,1-s/a),o=(this.config.normalize!==!1,i)),this.config.maximize===!1&&(o=1-o),{score:o,rawScore:i,details:{diff:s,tolerance:a,proximity:i}}}stringSimilarity(t,e){if(t.length===0&&e.length===0)return{score:1,rawScore:1,details:{distance:0,maxLen:0}};let n=Math.max(t.length,e.length),s=df(t,e),a=n===0?1:1-s/n;return{score:this.config.maximize===!1?1-a:a,rawScore:a,details:{distance:s,maxLen:n,similarity:a}}}arrayMatch(t,e){if(e.length===0&&t.length===0)return{score:1,rawScore:1,details:{matched:0,total:0}};let n=Math.max(t.length,e.length),s=0,a=Math.min(t.length,e.length);for(let u=0;u<a;u++)JSON.stringify(t[u])===JSON.stringify(e[u])&&s++;let i=n===0?1:s/n;return{score:this.config.maximize===!1?1-i:i,rawScore:i,details:{matched:s,total:n,arrLen:t.length,targetLen:e.length}}}multiObjective(t,e,n){let s=Object.keys(e);if(s.length===0)return{score:1,rawScore:1,details:{}};let a=n??this.config.weights??{},i={},o=0,u=0;for(let c of s){let p=t[c]??0,m=e[c]??0,d=a[c]??1,g=Math.max(Math.abs(m),Math.abs(p),1),h=Math.max(0,1-Math.abs(p-m)/g);i[c]=h,o+=h*d,u+=d}let f=u>0?o/u:0;return{score:this.config.maximize===!1?1-f:f,rawScore:f,details:i}}constraintSatisfaction(t,e){if(e.length===0)return{score:1,rawScore:1,details:{satisfied:0,total:0}};let n=0,s={};for(let o=0;o<e.length;o++){let u=e[o](t)?1:0;s[`constraint_${o}`]=u,n+=u}let a=n/e.length;return{score:this.config.maximize===!1?1-a:a,rawScore:a,details:{...s,satisfied:n,total:e.length}}}rank(t,e){let n=t.map((s,a)=>({item:s,score:e(s),idx:a}));return n.sort((s,a)=>a.score-s.score),n.map((s,a)=>({...s.item,rank:a+1,score:s.score}))}paretoFront(t,e){if(t.length===0)return[];let n=new Set;for(let s=0;s<t.length;s++)if(!n.has(s))for(let a=0;a<t.length;a++){if(s===a||n.has(a))continue;let i=e.map(l=>l(t[s])),o=e.map(l=>l(t[a])),u=i.every((l,c)=>l>=o[c]),f=i.some((l,c)=>l>o[c]);u&&f&&n.add(a)}return t.filter((s,a)=>!n.has(a))}},St=new br;var xt=class{constructor(t){this.statsHistory=[];this.stagnationCount=0;this.currentStats=null;this.config={maxGenerations:t.maxGenerations,targetFitness:t.targetFitness,stagnationLimit:t.stagnationLimit??10,logInterval:t.logInterval??10,onGeneration:t.onGeneration}}run(t,e,n){this.statsHistory=[],this.stagnationCount=0,this.currentStats=null;let s=[...t],a=s.map(e),i=s[0],o=a[0]??-1/0;for(let p=0;p<s.length;p++)a[p]>o&&(o=a[p],i=s[p]);let u=o,f=-1/0,l="max-generations";for(let p=0;p<this.config.maxGenerations;p++){let m=this._computeStats(p,a,f);this.statsHistory.push(m),this.currentStats=m;for(let g=0;g<s.length;g++)a[g]>o&&(o=a[g],i=s[g]);if(this.config.onGeneration&&this.config.onGeneration(m),this.config.targetFitness!==void 0&&o>=this.config.targetFitness){l="target-reached";break}m.improved?this.stagnationCount=0:this.stagnationCount++;let d=this.config.stagnationLimit??10;if(this.stagnationCount>=d){l="stagnation";break}f=m.best,p<this.config.maxGenerations-1&&(s=n(s,a),a=s.map(e))}let c=u===0?o-u:Math.abs((o-u)/Math.abs(u===0?1:u));return{best:i,bestFitness:o,totalGenerations:this.statsHistory.length,history:[...this.statsHistory],terminationReason:l,improvementRatio:c}}getCurrentStats(){return this.currentStats}getHistory(){return[...this.statsHistory]}calculateDiversity(t){if(t.length<=1)return 0;let e=Math.min(...t),s=Math.max(...t)-e;if(s===0)return 0;let a=t.reduce((f,l)=>f+l,0)/t.length,i=t.reduce((f,l)=>f+(l-a)**2,0)/t.length,o=Math.sqrt(i);return Math.min(1,o/(s+1e-9))}hasConverged(){if(this.statsHistory.length<5)return!1;let t=this.statsHistory.slice(-5),e=t[0].best;return t.every(n=>Math.abs(n.best-e)<1e-9)}_computeStats(t,e,n){if(e.length===0)return{generation:t,best:0,worst:0,average:0,diversity:0,elites:0,improved:!1};let s=Math.max(...e),a=Math.min(...e),i=e.reduce((l,c)=>l+c,0)/e.length,o=this.calculateDiversity(e),u=Math.max(1,Math.floor(e.length*.1)),f=t===0?!0:s>n;return{generation:t,best:s,worst:a,average:i,diversity:o,elites:u,improved:f}}};function Wa(r){return r.length===0?0:r.reduce((t,e)=>t+e,0)/r.length}function Kt(r,t,e,n,s){let a=e?r.map(e).filter(u=>u!==null):[],i=e?t.map(e).filter(u=>u!==null):[],o=r.length+t.length;return{kept:r,removed:t,keptRatio:o===0?1:r.length/o,strategy:n,stats:{originalCount:s,keptCount:r.length,removedCount:t.length,avgFitnessKept:Wa(a),avgFitnessRemoved:Wa(i)}}}var Pe=class{constructor(t){this.config=t??{}}pruneByThreshold(t,e,n){let s=[...t],a=[],i=[];for(let o of s)e(o)>=n?a.push(o):i.push(o);return Kt(a,i,e,"threshold",s.length)}pruneToTopK(t,e,n){let s=[...t],a=[...s].sort((l,c)=>e(c)-e(l)),i=Math.min(n,s.length),o=a.slice(0,i),u=new Set(o),f=s.filter(l=>!u.has(l));return Kt(o,f,e,"top-k",s.length)}pruneToTopPercent(t,e,n){let s=[...t],a=Math.max(1,Math.ceil(s.length*n));return this.pruneToTopK(s,e,a)}pruneForDiversity(t,e,n,s){let a=[...t];if(a.length===0)return Kt([],[],e,"diversity",0);let i=[...a].sort((l,c)=>e(c)-e(l)),o=[];for(let l of i)o.some(p=>n(l,p)>1-s)||o.push(l);let u=new Set(o),f=a.filter(l=>!u.has(l));return Kt(o,f,e,"diversity",a.length)}dedup(t,e){let n=[...t],s=new Set,a=[],i=[];for(let o of n){let u=e?e(o):JSON.stringify(o);s.has(u)?i.push(o):(s.add(u),a.push(o))}return Kt(a,i,()=>0,"threshold",n.length)}pruneWeak(t,e){let n=[...t];if(n.length===0)return Kt([],[],e,"threshold",0);let s=n.map(e),a=Wa(s),i=[],o=[];for(let u=0;u<n.length;u++)s[u]>=a?i.push(n[u]):o.push(n[u]);return Kt(i,o,e,"threshold",n.length)}prune(t,e){switch(this.config.strategy??"top-k"){case"threshold":return this.pruneByThreshold(t,e,this.config.threshold??.5);case"top-k":return this.pruneToTopK(t,e,this.config.k??10);case"top-percent":return this.pruneToTopPercent(t,e,this.config.percent??.5);case"diversity":return this.pruneForDiversity(t,e,(s,a)=>s===a?1:0,this.config.minDiversity??.2);default:return this.pruneWeak(t,e)}}},rv=new Pe;function kc(r,t,e){return[...r].sort((s,a)=>t(a)-t(s)).slice(0,Math.min(e,r.length))}var it=class{constructor(t="default"){this.pendingFns=[];this.suite={name:t,results:[],startTime:new Date,summary:{total:0,fastest:null,slowest:null,avgOpsPerSec:0}}}percentile(t,e){if(t.length===0)return 0;let n=[...t].sort((a,i)=>a-i),s=Math.ceil(e/100*n.length)-1;return n[Math.max(0,Math.min(s,n.length-1))]}measure(t,e,n=100){let s=[],a=0,i=0,o=Math.min(10,Math.floor(n/10));for(let k=0;k<o;k++)e();typeof process<"u"&&process.memoryUsage&&(a=process.memoryUsage().heapUsed);for(let k=0;k<n;k++){let v=performance.now();e();let $=performance.now();s.push($-v)}typeof process<"u"&&process.memoryUsage&&(i=process.memoryUsage().heapUsed);let u=s.reduce((k,v)=>k+v,0),f=u/n,l=Math.min(...s),c=Math.max(...s),p=this.percentile(s,50),m=this.percentile(s,95),d=this.percentile(s,99),g=f>0?Math.round(1e3/f):1/0,h=i>a?i-a:0;return{name:t,runs:n,totalMs:u,avgMs:f,minMs:l,maxMs:c,p50:p,p95:m,p99:d,opsPerSec:g,memoryUsed:h}}async measureAsync(t,e,n=100){let s=[],a=Math.min(5,Math.floor(n/10));for(let d=0;d<a;d++)await e();for(let d=0;d<n;d++){let g=performance.now();await e();let h=performance.now();s.push(h-g)}let i=s.reduce((d,g)=>d+g,0),o=i/n,u=Math.min(...s),f=Math.max(...s),l=this.percentile(s,50),c=this.percentile(s,95),p=this.percentile(s,99),m=o>0?Math.round(1e3/o):1/0;return{name:t,runs:n,totalMs:i,avgMs:o,minMs:u,maxMs:f,p50:l,p95:c,p99:p,opsPerSec:m}}compare(t,e,n,s,a=100){let i=this.measure(t,e,a),o=this.measure(n,s,a),u=i.avgMs>0?i.avgMs/o.avgMs:1,f,c=Math.abs(u-1)>=.05;return c?u>1?f="target":f="baseline":f="tie",{baseline:i,target:o,speedup:u,winner:f,significant:c}}add(t,e){return this.pendingFns.push({name:t,fn:e}),this}run(t=100){this.suite.startTime=new Date,this.suite.results=[];for(let{name:e,fn:n}of this.pendingFns){let s=this.measure(e,n,t);this.suite.results.push(s)}if(this.suite.endTime=new Date,this.suite.results.length>0){let e=[...this.suite.results].sort((i,o)=>i.avgMs-o.avgMs),n=e[0],s=e[e.length-1],a=Math.round(this.suite.results.reduce((i,o)=>i+o.opsPerSec,0)/this.suite.results.length);this.suite.summary={total:this.suite.results.length,fastest:n,slowest:s,avgOpsPerSec:a}}return this.suite}report(t){let e=[`\u250C\u2500 Benchmark: ${t.name}`,`\u2502 Runs: ${t.runs}`,`\u2502 Total: ${t.totalMs.toFixed(3)}ms`,`\u2502 Avg: ${t.avgMs.toFixed(4)}ms`,`\u2502 Min: ${t.minMs.toFixed(4)}ms`,`\u2502 Max: ${t.maxMs.toFixed(4)}ms`,`\u2502 P50: ${t.p50.toFixed(4)}ms`,`\u2502 P95: ${t.p95.toFixed(4)}ms`,`\u2502 P99: ${t.p99.toFixed(4)}ms`,`\u2502 Ops/sec: ${t.opsPerSec.toLocaleString()}`];return t.memoryUsed!==void 0&&t.memoryUsed>0&&e.push(`\u2502 Memory: ${(t.memoryUsed/1024).toFixed(2)}KB`),e.push("\u2514\u2500"),e.join(`
56
+ `)}histogram(t){let n=t.maxMs-t.minMs,s=n/10||.001,a=new Array(10).fill(0),i=20,o=[`Histogram: ${t.name}`];for(let u=0;u<10;u++){let f=t.minMs+u*s,l=f+s,c=(f+l)/2,p=Math.abs(c-t.avgMs)/(n||1),m=Math.max(0,Math.round(i*(1-p*2))),d="\u2588".repeat(m);o.push(` ${f.toFixed(3)}-${l.toFixed(3)}ms | ${d} (${m})`)}return o.join(`
57
+ `)}},ps=new it("global");var wc=require("crypto");function vc(r,t){let e=JSON.stringify(r,null,2),n=JSON.stringify(t,null,2);if(e===n)return"(no changes)";let s=e.split(`
58
+ `),a=n.split(`
59
+ `),i=a.filter(u=>!s.includes(u)).length,o=s.filter(u=>!a.includes(u)).length;return`+${i} lines, -${o} lines`}function gf(r){let t=r.split(".").map(Number);return[t[0]??0,t[1]??0,t[2]??0]}var kr=class{constructor(t=100){this.maxHistory=t,this.history={snapshots:[],current:"",total:0,branches:new Map}}snapshot(t,e,n=[],s){let a=(0,wc.randomUUID)(),i=this.history.current||void 0,o=i?this.get(i):null,u=o?this.bumpVersion(o.version,"patch"):"1.0.0",f=o?vc(o.data,t):void 0,l={id:a,version:u,timestamp:new Date,data:t,metadata:{description:e,tags:n,performance:s},parentId:i,diff:f};if(this.history.snapshots.push(l),this.history.current=a,this.history.total++,this.history.snapshots.length>this.maxHistory){let c=new Set(this.history.branches.values());c.add(this.history.current);let p=this.history.snapshots.find(m=>!c.has(m.id)&&m.id!==this.history.current);if(p){let m=this.history.snapshots.indexOf(p);this.history.snapshots.splice(m,1)}}return l}rollback(t){let e=this.latest(),n=this.get(t);return!e||!n?{previous:e,restored:e,success:!1,reason:`Snapshot ${t} not found`}:(this.history.current=t,{previous:e,restored:n,success:!0})}rollbackPrev(){let t=this.latest();return!t||!t.parentId?{previous:t,restored:t,success:!1,reason:"No previous version"}:this.rollback(t.parentId)}diff(t,e){let n=this.get(t),s=this.get(e);return!n||!s?"(one or both snapshots not found)":vc(n.data,s.data)}get(t){return this.history.snapshots.find(e=>e.id===t)??null}latest(){return this.history.current?this.get(this.history.current):null}getHistory(){return[...this.history.snapshots]}findByTag(t){return this.history.snapshots.filter(e=>e.metadata.tags.includes(t))}branch(t,e){let n=e??this.history.current;if(!n)throw new Error("No snapshot to branch from");return this.history.branches.set(t,n),n}checkout(t){let e=this.history.branches.get(t);return e?(this.history.current=e,this.get(e)):null}nextVersion(t){let e=this.latest(),n=e?e.version:"1.0.0";return this.bumpVersion(n,t)}bumpVersion(t,e){let[n,s,a]=gf(t);switch(e){case"major":return`${n+1}.0.0`;case"minor":return`${n}.${s+1}.0`;case"patch":return`${n}.${s}.${a+1}`}}bestPerforming(){let t=this.history.snapshots.filter(e=>e.metadata.performance!==void 0);return t.length===0?null:t.reduce((e,n)=>n.metadata.performance>e.metadata.performance?n:e)}},De=new kr(100);var hf=[/\b([a-z])\b/g,/\b(tmp|temp|foo|bar|baz|x|y|z|xx|yy)\b/g,/\b(val|var|obj|arr|str|num|fn|cb)\b/g],yf=new Set(["i","j","k","n","m","e","a","b","c"]),vr=class{findDuplicates(t){let e=[],n=t.split(`
60
+ `).filter(i=>i.trim().length>3),s=2,a=new Map;for(let i=0;i<=n.length-s;i++){let o=n.slice(i,i+s).join(`
61
+ `).trim();if(!(o.length<10))if(!a.has(o))a.set(o,[i]);else{let u=a.get(o);u.push(i),a.set(o,u)}}for(let[i,o]of a.entries())if(o.length>=2){let u=i.length>100?"high":i.length>40?"medium":"low";e.push({pattern:"extract-duplicate",location:`lines ${o.map(f=>f+1).join(", ")}`,original:i,suggested:`function extractedBlock() {
62
+ ${i.split(`
63
+ `).join(`
64
+ `)}
65
+ }`,reason:`\uB3D9\uC77C \uCF54\uB4DC\uAC00 ${o.length}\uACF3\uC5D0\uC11C \uBC18\uBCF5\uB428 \u2014 \uD568\uC218\uB85C \uCD94\uCD9C\uD558\uBA74 \uC720\uC9C0\uBCF4\uC218\uC131 \uD5A5\uC0C1`,impact:u})}return e}analyzeComplexity(t){let e=t.split(`
66
+ `),n=e.filter(f=>f.trim().length>0).length,s=0,a=0;for(let f of e){let l=(f.match(/[\(\[\{]/g)||[]).length,c=(f.match(/[\)\]\}]/g)||[]).length;a+=l-c,a>s&&(s=a),a<0&&(a=0)}let i=[/\bif\b/g,/\belse\b/g,/\bcond\b/g,/\bwhen\b/g,/\bcase\b/g,/\bswitch\b/g,/\?\s/g,/\band\b/g,/\bor\b/g],o=0;for(let f of i){let l=t.match(f);l&&(o+=l.length)}let u=Math.round(n*.5+s*10+o*3);return{lines:n,depth:s,conditions:o,score:u}}suggest(t){let e=[];e.push(...this.findDuplicates(t));let n=this.analyzeComplexity(t);n.depth>5&&e.push({pattern:"flatten-nesting",location:"high nesting area",original:`(depth=${n.depth} nesting detected)`,suggested:"; \uC911\uCCA9\uB41C \uC870\uAC74\uBB38\uC744 early-return \uB610\uB294 guard clause\uB85C \uBD84\uB9AC",reason:`\uC911\uCCA9 \uAE4A\uC774 ${n.depth} \u2014 5 \uC774\uD558 \uAD8C\uC7A5`,impact:"high"}),n.conditions>10&&e.push({pattern:"simplify-condition",location:"multiple condition branches",original:`(${n.conditions} conditions found)`,suggested:"; \uC870\uAC74\uC744 named predicate \uD568\uC218\uB85C \uCD94\uCD9C\uD558\uC5EC \uB2E8\uC21C\uD654",reason:`\uC870\uAC74\uBB38 ${n.conditions}\uAC1C \u2014 \uACFC\uB3C4\uD55C \uBD84\uAE30\uB85C \uAC00\uB3C5\uC131 \uC800\uD558`,impact:n.conditions>20?"high":"medium"});let s=t.split(`
67
+ `).filter(u=>u.trim().length>0);s.length>30&&e.push({pattern:"split-long-function",location:"function body",original:`(${s.length} lines in function)`,suggested:"; \uD568\uC218\uB97C \uB17C\uB9AC\uC801 \uB2E8\uC704\uB85C \uBD84\uB9AC: \uAC80\uC99D / \uBCC0\uD658 / \uCD9C\uB825",reason:`\uD568\uC218 \uAE38\uC774 ${s.length}\uC904 \u2014 30\uC904 \uC774\uD558 \uAD8C\uC7A5`,impact:s.length>60?"high":"medium"});let a=this.analyzeNaming(t);for(let u of a.issues)e.push({pattern:"rename-unclear",location:`variable: ${u.name}`,original:u.name,suggested:u.suggestion,reason:u.reason,impact:"low"});let i=/\(let \$(\w+) ([^\n]+)\)\s*\n[^\n]*\$\1[^\n]*\n(?![^\n]*\$\1)/g,o;for(;(o=i.exec(t))!==null;){let u=o[1],f=o[2].trim();f.length<30&&e.push({pattern:"inline-single-use",location:`variable $${u}`,original:`(let $${u} ${f})`,suggested:`; $${u} \uC778\uB77C\uC778 \u2014 \uBCC0\uC218 \uC120\uC5B8 \uC81C\uAC70`,reason:`$${u}\uC740 \uD55C \uBC88\uB9CC \uC0AC\uC6A9\uB428 \u2014 \uC778\uB77C\uC778\uC73C\uB85C \uB2E8\uC21C\uD654`,impact:"low"})}return e}apply(t,e){let n=t,s=[];for(let a of e)if(a.impact==="high"&&a.pattern==="rename-unclear"&&a.original&&a.suggested&&!a.suggested.startsWith(";")){let i=n;n=n.replace(new RegExp(`\\b${a.original}\\b`,"g"),a.suggested),n!==i&&s.push(a)}return{code:n,applied:s}}qualityScore(t){let e=this.analyzeComplexity(t),n=this.analyzeNaming(t),s=this.findDuplicates(t),a=Math.min(e.score/100,1),i=n.score,o=Math.min(s.length*.1,.5),u=(1-a)*.5+i*.3+(1-o)*.2;return Math.max(0,Math.min(1,Math.round(u*100)/100))}analyzeNaming(t){let e=[],n=new Set;for(let a of hf){let i=new RegExp(a.source,"g"),o;for(;(o=i.exec(t))!==null;){let u=o[1]||o[0];if(yf.has(u)||n.has(u))continue;n.add(u);let f=u,l="";/^[a-z]$/.test(u)?(f=`${u}Value`,l="\uB2E8\uC77C \uBB38\uC790 \uBCC0\uC218 \u2014 \uC758\uBBF8\uB97C \uB2F4\uC740 \uC774\uB984 \uC0AC\uC6A9 \uAD8C\uC7A5"):["tmp","temp"].includes(u)?(f="temporaryResult",l=`'${u}'\uC740 \uBAA9\uC801\uC774 \uBD88\uBA85\uD655\uD55C \uC784\uC2DC \uBCC0\uC218\uBA85`):["foo","bar","baz"].includes(u)?(f="meaningfulName",l=`'${u}'\uC740 placeholder\uBA85 \u2014 \uC2E4\uC81C \uC758\uBBF8\uB97C \uB2F4\uC740 \uC774\uB984 \uC0AC\uC6A9`):["val","var","obj","arr","str","num","fn","cb"].includes(u)?(f=u+"Result",l="\uD0C0\uC785\uC744 \uC774\uB984\uC73C\uB85C \uC4F0\uB294 \uAC83\uC740 \uBD88\uBA85\uD655 \u2014 \uC5ED\uD560/\uBAA9\uC801\uC744 \uB2F4\uC740 \uC774\uB984 \uAD8C\uC7A5"):["x","y","z","xx","yy"].includes(u)&&(f=`${u}Coordinate`,l="\uC218\uD559\uC801 \uC88C\uD45C\uAC00 \uC544\uB2CC \uACBD\uC6B0 \uC758\uBBF8\uC788\uB294 \uC774\uB984 \uAD8C\uC7A5"),f!==u&&e.push({name:u,suggestion:f,reason:l})}}let s=e.length===0?1:Math.max(0,1-e.length*.1);return{issues:e,score:Math.round(s*100)/100}}refactor(t,e=!0){let n=this.qualityScore(t),s=this.suggest(t),a=0,i=0,o=t;if(e){let l=this.apply(t,s);o=l.code,a=l.applied.length,i=s.length-a}else i=s.length;let u=e?this.qualityScore(o):n,f=n>0?Math.round((u-n)/n*100*100)/100:0;return{suggestions:s,applied:a,skipped:i,score:{before:n,after:u,improvement:f}}}},At=new vr;var _c=require("crypto"),fs={target:null,populationSize:20,generations:30,mutationRate:.1,eliteRatio:.1,pruneThreshold:.2,enableVersioning:!1,enableBenchmark:!1,enableRefactor:!1},Ha=class{constructor(){this._cycleCount=0;this._totalGenerations=0;this._refactorSuggestions=0;this._versionCount=0;this._fitnessHistory=[];this.fitnessEval=new br({normalize:!0,maximize:!0}),this.pruner=new Pe,this.refactorer=new vr,this.benchmark=new it("self-evolution-hub"),this.versioning=new kr(200)}runCycle(t,e,n,s,a){let i={...fs,...a},o=Date.now();if(!t||t.length===0)return this._emptyResult(i);let u=[...t],f=-1/0,l=u[0],c=0,p=0,m=[],d=0,g=new Be({rate:i.mutationRate}),h=new yr,y=new xt({maxGenerations:i.generations});for(let O=0;O<i.generations;O++){d++;let C=u.map(S=>({item:S,fitness:e(S)}));C.sort((S,R)=>R.fitness-S.fitness);let P=C[0].fitness;m.push(P),P>f&&(f=P,l=C[0].item,c++);let _=Math.floor(u.length*i.pruneThreshold);if(_>0){p+=_;let S=C.slice(0,u.length-_).map(R=>R.item);u.length=0,u.push(...S)}for(;u.length<i.populationSize;){let S=u[Math.floor(Math.random()*u.length)],R=u[Math.floor(Math.random()*u.length)],E=s(S,R),T=n(E);u.push(T)}}this._cycleCount++,this._totalGenerations+=d,this._fitnessHistory.push(...m);let k;i.enableBenchmark&&(k=Date.now()-o);let v;if(i.enableVersioning)try{v=this.versioning.snapshot(l,`evolution-cycle-${this._cycleCount}`,["auto-evolved"],f).id,this._versionCount++}catch{v=(0,_c.randomUUID)(),this._versionCount++}let $=0;if(i.enableRefactor)try{$=this.refactorer.suggest(String(l)).length,this._refactorSuggestions+=$}catch{$=0}let M=this._buildReport({bestFitness:f,generations:d,improvements:c,prunedCount:p,benchmarkMs:k,versionId:v,refactorCount:$});return{best:l,bestFitness:f,generations:d,improvements:c,prunedCount:p,benchmarkMs:k,versionId:v,report:M}}evolveNumbers(t,e){let n={...fs,target:t,...e},s=n.populationSize,a=t.length,i=Array.from({length:s},()=>Array.from({length:a},()=>Math.random()*10)),o=l=>{let c=l;return Array.isArray(c)?1/(1+t.reduce((m,d,g)=>m+Math.abs(d-(c[g]??0)),0)):0},u=l=>{let c=[...l],p=Math.floor(Math.random()*c.length);return c[p]+=(Math.random()-.5)*n.mutationRate*2,c},f=(l,c)=>{let p=l,m=c,d=Math.floor(Math.random()*p.length);return[...p.slice(0,d),...m.slice(d)]};return this.runCycle(i,o,u,f,n)}evolveString(t,e){let n={...fs,target:t,...e},s="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ",a=t.length,i=n.populationSize,o=Array.from({length:i},()=>Array.from({length:a},()=>s[Math.floor(Math.random()*s.length)]).join("")),u=c=>{let p=String(c);if(p.length!==t.length)return 0;let m=0;for(let d=0;d<t.length;d++)p[d]===t[d]&&m++;return m/t.length},f=c=>{let p=String(c).split("");for(let m=0;m<p.length;m++)Math.random()<n.mutationRate&&(p[m]=s[Math.floor(Math.random()*s.length)]);return p.join("")},l=(c,p)=>{let m=String(c),d=String(p),g=Math.floor(Math.random()*m.length);return m.slice(0,g)+d.slice(g)};return this.runCycle(o,u,f,l,n)}generateReport(t){let e=t.length,n=t.reduce((l,c)=>l+c.generations,0),s=t.map(l=>l.bestFitness),a=this._refactorSuggestions,i=this._versionCount,o=s.length>0?s.reduce((l,c)=>l+c,0)/s.length:0,u=s.length>0?Math.max(...s):0,f=[`[SelfEvolutionHub] ${e}\uAC1C \uC0AC\uC774\uD074, ${n}\uC138\uB300 \uC2E4\uD589`,`\uCD5C\uACE0 \uC801\uD569\uB3C4: ${u.toFixed(4)}, \uD3C9\uADE0: ${o.toFixed(4)}`,`\uB9AC\uD329\uD1A0\uB9C1 \uC81C\uC548: ${a}\uAC1C, \uBC84\uC804: ${i}\uAC1C`].join(" | ");return{timestamp:new Date,cycles:e,totalGenerations:n,fitnessProgress:s,refactorSuggestions:a,versions:i,summary:f}}selfImprove(t){let e={...fs,...t},n=[{...e},{...e,mutationRate:Math.min(.5,e.mutationRate*1.5)},{...e,mutationRate:Math.max(.01,e.mutationRate*.7)},{...e,populationSize:Math.min(100,e.populationSize*2)},{...e,eliteRatio:Math.min(.5,e.eliteRatio*1.5)},{...e,pruneThreshold:Math.max(.05,e.pruneThreshold*.8)}],s=e,a=0,i=0,o=[1,2,3,4,5];n.forEach((f,l)=>{let c=this.evolveNumbers(o,{...f,generations:10});l===0?(a=c.bestFitness,i=a,s=f):c.bestFitness>i&&(i=c.bestFitness,s=f)});let u=a>0?(i-a)/a:0;return{optimized:s,improvement:Math.max(0,u)}}_emptyResult(t){return{best:null,bestFitness:0,generations:0,improvements:0,prunedCount:0,report:"[SelfEvolutionHub] \uBE48 population \u2014 \uC9C4\uD654 \uC5C6\uC74C"}}_buildReport(t){let e=[`[SelfEvolutionHub] \uCD5C\uACE0 \uC801\uD569\uB3C4=${t.bestFitness.toFixed(4)}`,`\uC138\uB300=${t.generations}`,`\uAC1C\uC120=${t.improvements}`,`\uAC00\uC9C0\uCE58\uAE30=${t.prunedCount}`];return t.benchmarkMs!==void 0&&e.push(`\uC2E4\uD589\uC2DC\uAC04=${t.benchmarkMs}ms`),t.versionId&&e.push(`\uBC84\uC804ID=${t.versionId.slice(0,8)}...`),t.refactorCount!==void 0&&t.refactorCount>0&&e.push(`\uB9AC\uD329\uD1A0\uB9C1\uC81C\uC548=${t.refactorCount}\uAC1C`),e.join(", ")}get cycleCount(){return this._cycleCount}get totalGenerations(){return this._totalGenerations}get refactorSuggestions(){return this._refactorSuggestions}get versionCount(){return this._versionCount}get fitnessHistory(){return[...this._fitnessHistory]}},Jt=new Ha;var Ga=class{constructor(){this.nodes=new Map,this.edges=[]}addNode(t){this.nodes.set(t.id,t)}addEdge(t){this.edges.push(t)}getDirectCauses(t){return this.edges.filter(e=>e.to===t)}getDirectEffects(t){return this.edges.filter(e=>e.from===t)}findCausalChains(t,e,n=new Set){if(t===e)return[{path:[t],totalStrength:1,explanation:`${this.nodes.get(t)?.name??t}`,confidence:1}];if(n.has(t))return[];n.add(t);let s=[],a=this.getDirectEffects(t);for(let i of a){let o=this.findCausalChains(i.to,e,new Set(n));for(let u of o){let f=this.nodes.get(t)?.name??t,l=this.nodes.get(i.to)?.name??i.to,c=i.mechanism?` (${i.mechanism})`:"";s.push({path:[t,...u.path],totalStrength:i.strength*u.totalStrength,explanation:`${f} \u2192 ${l}${c}; ${u.explanation}`,confidence:i.confidence*u.confidence})}}return s}explain(t){let n=this.nodes.get(t)?.name??t,s=[];for(let[m]of this.nodes){if(m===t)continue;let d=this.findCausalChains(m,t);for(let g of d)g.path.length>=2&&s.push({cause:m,chain:g})}let a=new Map;for(let m of s){let d=a.get(m.cause);(!d||Math.abs(m.chain.totalStrength)>Math.abs(d.chain.totalStrength))&&a.set(m.cause,m)}let i=Array.from(a.values()),o=i.reduce((m,d)=>m+Math.abs(d.chain.totalStrength),0)||1,u=i.map(m=>({cause:m.cause,chain:m.chain,contribution:Math.abs(m.chain.totalStrength)/o}));u.sort((m,d)=>d.contribution-m.contribution);let f=u[0]?.cause??t,l=this.nodes.get(f)?.name??f,c=u.length>0?u.reduce((m,d)=>m+d.chain.confidence,0)/u.length:0,p=u.length>0?`${n}\uC758 \uC8FC\uC694 \uC6D0\uC778\uC740 "${l}"\uC774\uB2E4. `+u.slice(0,3).map(m=>`${this.nodes.get(m.cause)?.name??m.cause} (\uAE30\uC5EC\uB3C4: ${(m.contribution*100).toFixed(1)}%)`).join(", ")+".":`${n}\uC758 \uC6D0\uC778\uC744 \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4.`;return{effect:t,causes:u,primaryCause:f,explanation:p,confidence:c}}findRootCauses(t,e=new Set){if(e.has(t))return[];e.add(t);let n=this.getDirectCauses(t);if(n.length===0)return[t];let s=[];for(let a of n){let i=this.findRootCauses(a.from,new Set(e));for(let o of i)s.includes(o)||s.push(o)}return s}simulate(t){let e={...t},n=Object.keys(t),s=new Set(n);for(;n.length>0;){let a=n.shift(),i=e[a]??this.nodes.get(a)?.value??0,o=this.getDirectEffects(a);for(let u of o)if(!s.has(u.to)){let f=this.nodes.get(u.to)?.value??0,l=i*u.strength*u.confidence;e[u.to]=(e[u.to]??f)+l,n.push(u.to),s.add(u.to)}}return e}summarize(t){let e=this.nodes.get(t);if(!e)return`\uB178\uB4DC "${t}"\uB97C \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4.`;let n=this.getDirectCauses(t),s=this.getDirectEffects(t),a=this.findRootCauses(t),i=n.length>0?n.map(f=>`${this.nodes.get(f.from)?.name??f.from}(\uAC15\uB3C4:${f.strength})`).join(", "):"\uC5C6\uC74C",o=s.length>0?s.map(f=>`${this.nodes.get(f.to)?.name??f.to}(\uAC15\uB3C4:${f.strength})`).join(", "):"\uC5C6\uC74C",u=a.filter(f=>f!==t).length>0?a.filter(f=>f!==t).map(f=>this.nodes.get(f)?.name??f).join(", "):"\uC5C6\uC74C (\uB8E8\uD2B8 \uC6D0\uC778)";return`[${e.name}] \uC9C1\uC811\uC6D0\uC778: ${i} | \uC9C1\uC811\uACB0\uACFC: ${o} | \uB8E8\uD2B8\uC6D0\uC778: ${u}`}detectCycle(t,e){let n=new Set,s=[e];for(;s.length>0;){let a=s.shift();if(a===t)return!0;if(n.has(a))continue;n.add(a);let i=this.getDirectEffects(a);for(let o of i)s.push(o.to)}return!1}},oe=new Ga;function ms(r,t){let e=oe.findCausalChains(t,r);return e.length===0?null:e.sort((n,s)=>Math.abs(s.totalStrength)-Math.abs(n.totalStrength))[0]}var Ka=class{constructor(){this.goals=new Map,this.values=new Map}addGoal(t){t.priority<1&&(t={...t,priority:1}),t.priority>10&&(t={...t,priority:10}),this.goals.set(t.id,t)}addValue(t){t.weight<0&&(t={...t,weight:0}),t.weight>1&&(t={...t,weight:1}),this.values.set(t.id,t)}score(t){let e={},n={},s=[];for(let[g,h]of this.goals){let y=t.expectedOutcomes[g]??0,k=Math.max(0,Math.min(1,(y+1)/2));e[g]=k,k>=.7?s.push(`\uBAA9\uD45C "${h.description}" \uB2EC\uC131\uC5D0 \uAE30\uC5EC (${(k*100).toFixed(0)}%)`):k<.3&&s.push(`\uBAA9\uD45C "${h.description}" \uB2EC\uC131\uC5D0 \uBD80\uC815\uC801 \uC601\uD5A5 (${(k*100).toFixed(0)}%)`)}for(let[g,h]of this.values){let y=1;for(let k of t.risks){let v=k.toLowerCase(),$=h.name.toLowerCase(),M=h.description.toLowerCase();(v.includes($)||v.includes(M.split(" ")[0]))&&(y-=.3),(v.includes("harm")||v.includes("\uC704\uD5D8")||v.includes("\uAC70\uC9D3")||v.includes("\uC18D\uC784"))&&(y-=.2*h.weight)}n[g]=Math.max(0,Math.min(1,y))}let a=this._detectActionConflicts(t,e),i=0,o=0;for(let[g,h]of this.goals){let y=h.priority/10;i+=(e[g]??0)*y,o+=y}let u=o>0?i/o:.5,f=0,l=0;for(let[g,h]of this.values)f+=(n[g]??1)*h.weight,l+=h.weight;let c=l>0?f/l:1,p=0;for(let g of a)g.severity==="high"?p+=.3:g.severity==="medium"?p+=.15:p+=.05;let m=Math.max(0,Math.min(1,u*.6+c*.4-p)),d;return m>=.65&&p<.3?d="proceed":m>=.35&&p<.6?d="caution":(d="reject",s.push("\uC885\uD569 \uC815\uB82C\uB3C4\uAC00 \uB108\uBB34 \uB0AE\uAC70\uB098 \uC2EC\uAC01\uD55C \uCDA9\uB3CC\uC774 \uC788\uC74C")),a.length>0&&s.push(`${a.length}\uAC1C\uC758 \uBAA9\uD45C \uCDA9\uB3CC \uAC10\uC9C0\uB428`),{action:t,goalAlignment:e,valueAlignment:n,overallScore:m,conflicts:a,recommendation:d,reasons:s}}_detectActionConflicts(t,e){let n=[],s=Array.from(this.goals.keys());for(let a=0;a<s.length;a++)for(let i=a+1;i<s.length;i++){let o=s[a],u=s[i],f=e[o]??.5,l=e[u]??.5,c=Math.abs(f-l);c>.6?n.push({goal1:o,goal2:u,severity:"high"}):c>.4?n.push({goal1:o,goal2:u,severity:"medium"}):c>.25&&n.push({goal1:o,goal2:u,severity:"low"})}return n}selectBestAligned(t){if(t.length===0)throw new Error("\uD589\uB3D9 \uBAA9\uB85D\uC774 \uBE44\uC5B4\uC788\uC74C");if(t.length===1)return t[0];let e=t[0],n=this.score(t[0]).overallScore;for(let s=1;s<t.length;s++){let a=this.score(t[s]).overallScore;a>n&&(n=a,e=t[s])}return e}detectConflicts(){let t=[],e=Array.from(this.goals.values());for(let n=0;n<e.length;n++)for(let s=n+1;s<e.length;s++){let a=e[n],i=e[s],o=Math.abs(a.priority-i.priority);o>=5&&t.push({goal1:a.id,goal2:i.id,description:`\uC6B0\uC120\uC21C\uC704 \uCC28\uC774 ${o}: "${a.description}" vs "${i.description}"`}),a.measurable!==i.measurable&&o>=3&&t.push({goal1:a.id,goal2:i.id,description:`\uCE21\uC815 \uAC00\uB2A5\uC131 \uBD88\uC77C\uCE58: "${a.description}" (${a.measurable?"\uCE21\uC815\uAC00\uB2A5":"\uCD94\uC0C1\uC801"}) vs "${i.description}" (${i.measurable?"\uCE21\uC815\uAC00\uB2A5":"\uCD94\uC0C1\uC801"})`})}return t}evaluatePlan(t){if(t.length===0)return{overallAlignment:0,weakLinks:[],summary:"\uACC4\uD68D\uC774 \uBE44\uC5B4\uC788\uC74C"};let e=t.map(f=>({action:f,result:this.score(f)})),n=e.reduce((f,l)=>f+l.result.overallScore,0)/e.length,s=e.filter(f=>f.result.overallScore<.4||f.result.recommendation==="reject").map(f=>f.action),a=e.filter(f=>f.result.recommendation==="reject").length,i=e.filter(f=>f.result.recommendation==="caution").length,o=e.filter(f=>f.result.recommendation==="proceed").length,u=[`\uACC4\uD68D ${t.length}\uAC1C \uD589\uB3D9 \uD3C9\uAC00:`,` - \uC9C4\uD589 \uAD8C\uACE0: ${o}\uAC1C`,` - \uC8FC\uC758 \uD544\uC694: ${i}\uAC1C`,` - \uAC70\uBD80 \uAD8C\uACE0: ${a}\uAC1C`,` - \uC804\uCCB4 \uC815\uB82C\uB3C4: ${(n*100).toFixed(1)}%`,s.length>0?` - \uCDE8\uC57D \uACE0\uB9AC ${s.length}\uAC1C \uBC1C\uACAC`:" - \uCDE8\uC57D \uACE0\uB9AC \uC5C6\uC74C"].join(`
68
+ `);return{overallAlignment:n,weakLinks:s,summary:u}}suggestImprovements(t){let e=this.score(t),n=[];for(let[s,a]of Object.entries(e.goalAlignment))if(a<.5){let i=this.goals.get(s);i&&n.push(`\uBAA9\uD45C "${i.description}" \uAE30\uC5EC\uB3C4 \uD5A5\uC0C1 \uD544\uC694 (\uD604\uC7AC ${(a*100).toFixed(0)}%): expectedOutcomes["${s}"]\uB97C \uB192\uC774\uC138\uC694`)}for(let[s,a]of Object.entries(e.valueAlignment))if(a<.7){let i=this.values.get(s);i&&n.push(`\uAC00\uCE58 "${i.name}" \uC704\uBC18 \uC704\uD5D8 \uC788\uC74C (\uC815\uB82C\uB3C4 ${(a*100).toFixed(0)}%): \uAD00\uB828 \uB9AC\uC2A4\uD06C \uC694\uC778\uC744 \uC81C\uAC70\uD558\uC138\uC694`)}for(let s of e.conflicts){let a=this.goals.get(s.goal1),i=this.goals.get(s.goal2);a&&i&&n.push(`\uCDA9\uB3CC(${s.severity}): "${a.description}"\uC640 "${i.description}" \uC0AC\uC774\uC758 \uC808\uCDA9\uC548 \uACE0\uB824`)}return t.risks.length>2&&n.push(`\uB9AC\uC2A4\uD06C\uAC00 ${t.risks.length}\uAC1C\uB85C \uB9CE\uC2B5\uB2C8\uB2E4. \uB9AC\uC2A4\uD06C \uC644\uD654 \uC804\uB7B5\uC744 \uC218\uB9BD\uD558\uC138\uC694`),n.length===0&&n.push("\uD604\uC7AC \uC815\uB82C\uB3C4\uAC00 \uC591\uD638\uD569\uB2C8\uB2E4. \uC720\uC9C0\uD558\uC138\uC694."),n}prioritizeGoals(){return Array.from(this.goals.values()).sort((t,e)=>e.priority-t.priority)}getGoals(){return new Map(this.goals)}getValues(){return new Map(this.values)}},ot=new Ka;var bf={id:"do-no-harm",name:"\uD574\uC545 \uAE08\uC9C0",description:"\uD589\uB3D9\uC774\uB098 \uCD9C\uB825\uC774 \uC778\uAC04\uC774\uB098 \uC0DD\uBA85\uCCB4\uC5D0 \uD574\uB97C \uB07C\uCCD0\uC11C\uB294 \uC548 \uB41C\uB2E4",framework:"deontological",check:(r,t)=>{let e=["kill","murder","harm","hurt","injure","damage","destroy","\uC8FD","\uC0B4\uC778","\uD574\uCE58","\uD3ED\uB825","\uD3ED\uBC1C","\uD3ED\uD0C4","\uB3C5","\uC790\uC0B4","weapon","bomb","poison","explosive","attack","violence","illegal","steal","theft","fraud","abuse"],n=r.toLowerCase(),s=e.some(a=>n.includes(a));return{passed:!s,reason:s?`\uD574\uC545\uC744 \uCD08\uB798\uD560 \uC218 \uC788\uB294 \uB0B4\uC6A9\uC774 \uAC10\uC9C0\uB418\uC5C8\uC2B5\uB2C8\uB2E4: "${r.substring(0,50)}"`:"\uD574\uC545 \uAE08\uC9C0 \uC6D0\uCE59\uC744 \uC900\uC218\uD569\uB2C8\uB2E4"}}},kf={id:"fairness",name:"\uACF5\uC815\uC131",description:"\uBAA8\uB4E0 \uAC1C\uC778\uACFC \uC9D1\uB2E8\uC744 \uACF5\uC815\uD558\uAC8C \uB300\uC6B0\uD574\uC57C \uD55C\uB2E4",framework:"fairness",check:(r,t)=>{let e=["racist","sexist","discriminat","prejudice","bias against","\uCC28\uBCC4","\uD3B8\uACAC","\uD610\uC624","\uC778\uC885\uCC28\uBCC4","\uC131\uCC28\uBCC4","\uC7A5\uC560\uC778 \uCC28\uBCC4","inferior","superior race","stereotype"],n=r.toLowerCase(),s=e.some(a=>n.includes(a));return{passed:!s,reason:s?"\uCC28\uBCC4 \uB610\uB294 \uD3B8\uACAC\uC774 \uAC10\uC9C0\uB418\uC5C8\uC2B5\uB2C8\uB2E4":"\uACF5\uC815\uC131 \uC6D0\uCE59\uC744 \uC900\uC218\uD569\uB2C8\uB2E4"}}},vf={id:"transparency",name:"\uD22C\uBA85\uC131",description:"AI \uC2DC\uC2A4\uD15C\uC758 \uC758\uC0AC\uACB0\uC815 \uACFC\uC815\uC740 \uD22C\uBA85\uD558\uACE0 \uC124\uBA85 \uAC00\uB2A5\uD574\uC57C \uD55C\uB2E4",framework:"virtue",check:(r,t)=>{let e=["deceive","lie","hide","conceal","manipulate","trick","mislead","\uC18D\uC774","\uAC70\uC9D3","\uC228\uAE30","\uC870\uC791","\uAE30\uB9CC","\uC0AC\uAE30"],n=r.toLowerCase(),s=e.some(i=>n.includes(i)),a=t.hiding===!0||t.deceptive===!0;return{passed:!s&&!a,reason:s||a?"\uD22C\uBA85\uC131\uC744 \uD574\uCE58\uB294 \uB0B4\uC6A9\uC774 \uAC10\uC9C0\uB418\uC5C8\uC2B5\uB2C8\uB2E4":"\uD22C\uBA85\uC131 \uC6D0\uCE59\uC744 \uC900\uC218\uD569\uB2C8\uB2E4"}}},wf={id:"privacy",name:"\uAC1C\uC778\uC815\uBCF4 \uBCF4\uD638",description:"\uAC1C\uC778\uC758 \uD504\uB77C\uC774\uBC84\uC2DC\uC640 \uB370\uC774\uD130 \uBCF4\uD638 \uAD8C\uB9AC\uB97C \uC874\uC911\uD574\uC57C \uD55C\uB2E4",framework:"care",check:(r,t)=>{let e=["personal data","private information","ssn","social security","credit card","password","expose private","\uC8FC\uBBFC\uBC88\uD638","\uAC1C\uC778\uC815\uBCF4 \uC720\uCD9C","\uBE44\uBC00\uBC88\uD638 \uB178\uCD9C","\uC0AC\uC0DD\uD65C \uCE68\uD574","doxx","doxing","stalk"],n=r.toLowerCase(),s=e.some(i=>n.includes(i)),a=t.privacy_violation===!0;return{passed:!s&&!a,reason:s||a?"\uAC1C\uC778\uC815\uBCF4 \uBCF4\uD638 \uC704\uBC18\uC774 \uAC10\uC9C0\uB418\uC5C8\uC2B5\uB2C8\uB2E4":"\uAC1C\uC778\uC815\uBCF4 \uBCF4\uD638 \uC6D0\uCE59\uC744 \uC900\uC218\uD569\uB2C8\uB2E4"}}},_f={id:"autonomy",name:"\uC790\uC728\uC131 \uC874\uC911",description:"\uC778\uAC04\uC758 \uC790\uC728\uC801 \uC758\uC0AC\uACB0\uC815 \uB2A5\uB825\uC744 \uC874\uC911\uD558\uACE0 \uCD5C\uB300 \uC774\uC775\uC744 \uCD94\uAD6C\uD55C\uB2E4",framework:"utilitarian",check:(r,t)=>{let e=["force","coerce","compel","override human","bypass consent","\uAC15\uC81C","\uB3D9\uC758 \uC5C6\uC774","\uD5C8\uB77D \uC5C6\uC774","\uC790\uC728\uC131 \uCE68\uD574","\uC778\uAC04 \uBB34\uC2DC","manipulate user","control human","override decision"],n=r.toLowerCase(),s=e.some(i=>n.includes(i)),a=t.autonomy_violation===!0;return{passed:!s&&!a,reason:s||a?"\uC778\uAC04\uC758 \uC790\uC728\uC131\uC744 \uCE68\uD574\uD558\uB294 \uB0B4\uC6A9\uC774 \uAC10\uC9C0\uB418\uC5C8\uC2B5\uB2C8\uB2E4":"\uC790\uC728\uC131 \uC874\uC911 \uC6D0\uCE59\uC744 \uC900\uC218\uD569\uB2C8\uB2E4"}}},Sf=[bf,kf,vf,wf,_f],Ja=class{constructor(){this.principles=[...Sf]}addPrinciple(t){this.principles.push(t)}check(t,e={}){let n=[],s={utilitarian:{passed:!0,score:1,violations:0},deontological:{passed:!0,score:1,violations:0},virtue:{passed:!0,score:1,violations:0},care:{passed:!0,score:1,violations:0},fairness:{passed:!0,score:1,violations:0}};for(let d of this.principles){let g=d.check(t,e);if(!g.passed){let h=this._determineSeverity(t,d,e),y={principle:d.name,severity:h,description:g.reason,suggestion:this._generateSuggestion(d,t),framework:d.framework};n.push(y),s[d.framework].passed=!1,s[d.framework].violations+=1}}let a={utilitarian:0,deontological:0,virtue:0,care:0,fairness:0};for(let d of this.principles)a[d.framework]=(a[d.framework]||0)+1;for(let d of Object.keys(s)){let g=a[d]||1,h=s[d].violations;s[d].score=Math.max(0,1-h/g)}let i=0;for(let d of n)i+=this._severityPenalty(d.severity);let o=Math.max(0,1-i/Math.max(this.principles.length,1)),u=n.length===0,f=n.some(d=>d.severity==="critical"),l=n.some(d=>d.severity==="high"),c=f||l,p={utilitarian:{passed:s.utilitarian.passed,score:s.utilitarian.score},deontological:{passed:s.deontological.passed,score:s.deontological.score},virtue:{passed:s.virtue.passed,score:s.virtue.score},care:{passed:s.care.passed,score:s.care.score},fairness:{passed:s.fairness.passed,score:s.fairness.score}},m=this._generateRecommendation(u,n,o);return{subject:t,passed:u,violations:n,score:o,frameworks:p,recommendation:m,requiresHumanReview:c}}checkByFramework(t,e,n={}){let s=this.principles.filter(u=>u.framework===e),a=[];for(let u of s){let f=u.check(t,n);if(!f.passed){let l=this._determineSeverity(t,u,n);a.push({principle:u.name,severity:l,description:f.reason,suggestion:this._generateSuggestion(u,t),framework:u.framework})}}let i=s.length||1,o=Math.max(0,1-a.reduce((u,f)=>u+this._severityPenalty(f.severity),0)/i);return{passed:a.length===0,score:o,violations:a}}isEthical(t,e={}){for(let n of this.principles)if(!n.check(t,e).passed)return!1;return!0}suggestEthicalAlternative(t,e){if(e.length===0)return`"${t.substring(0,50)}"\uC740(\uB294) \uC774\uBBF8 \uC724\uB9AC\uC801\uC785\uB2C8\uB2E4. \uBCC0\uACBD\uC774 \uD544\uC694\uD558\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.`;let n=[],s=new Set(e.map(i=>i.framework));for(let i of e)n.push(`\u2022 [${i.framework}] ${i.suggestion}`);let a=[];return s.has("deontological")&&a.push("\uC758\uBB34\uB860\uC801 \uAD00\uC810: \uC808\uB300\uC801 \uD574\uC545\uC744 \uC81C\uAC70\uD558\uC2ED\uC2DC\uC624"),s.has("utilitarian")&&a.push("\uACF5\uB9AC\uC8FC\uC758\uC801 \uAD00\uC810: \uCD5C\uB300 \uB2E4\uC218\uC758 \uCD5C\uB300 \uC774\uC775\uC744 \uCD94\uAD6C\uD558\uC2ED\uC2DC\uC624"),s.has("virtue")&&a.push("\uB355 \uC724\uB9AC \uAD00\uC810: \uD22C\uBA85\uD558\uACE0 \uC815\uC9C1\uD55C \uBC29\uC2DD\uC744 \uD0DD\uD558\uC2ED\uC2DC\uC624"),s.has("care")&&a.push("\uB3CC\uBD04 \uC724\uB9AC \uAD00\uC810: \uCDE8\uC57D\uD55C \uAC1C\uC778\uC758 \uAD8C\uB9AC\uB97C \uBCF4\uD638\uD558\uC2ED\uC2DC\uC624"),s.has("fairness")&&a.push("\uACF5\uC815\uC131 \uAD00\uC810: \uBAA8\uB4E0 \uC9D1\uB2E8\uC744 \uB3D9\uB4F1\uD558\uAC8C \uB300\uC6B0\uD558\uC2ED\uC2DC\uC624"),[`\uC724\uB9AC\uC801 \uB300\uC548 \uC81C\uC548 (${e.length}\uAC1C \uC704\uBC18):`,...n,"","\uD504\uB808\uC784\uC6CC\uD06C\uBCC4 \uAD8C\uACE0\uC0AC\uD56D:",...a,"","\uAD8C\uC7A5: \uC704 \uC0AC\uD56D\uB4E4\uC744 \uBC18\uC601\uD558\uC5EC \uB0B4\uC6A9\uC744 \uC218\uC815\uD558\uAC70\uB098 \uC804\uBB38\uAC00\uC758 \uAC80\uD1A0\uB97C \uBC1B\uC73C\uC2ED\uC2DC\uC624."].join(`
69
+ `)}riskLevel(t){return t.violations.length===0?"none":t.violations.some(a=>a.severity==="critical")?"critical":t.violations.some(a=>a.severity==="high")?"high":t.violations.some(a=>a.severity==="medium")?"medium":"low"}_determineSeverity(t,e,n){let s=t.toLowerCase();if(["kill","murder","bomb","explosive","\uC0B4\uC778","\uD3ED\uD0C4","\uC790\uC0B4"].some(f=>s.includes(f)))return"critical";if(["doxx","doxing","stalk","racist","sexist","\uC8FC\uBBFC\uBC88\uD638","\uC0AC\uAE30"].some(f=>s.includes(f)))return"high";let o=n.severity;return o==="critical"?"critical":o==="high"?"high":o==="medium"||["harm","hurt","damage","\uD574\uCE58","\uC190\uD574","manipulate"].some(f=>s.includes(f))?"medium":"low"}_generateSuggestion(t,e){return{"do-no-harm":"\uD574\uC545\uC744 \uCD08\uB798\uD558\uC9C0 \uC54A\uB294 \uBC29\uD5A5\uC73C\uB85C \uB0B4\uC6A9\uC744 \uC218\uC815\uD558\uAC70\uB098, \uC720\uD574\uD55C \uC694\uC18C\uB97C \uC81C\uAC70\uD558\uC2ED\uC2DC\uC624",fairness:"\uBAA8\uB4E0 \uC9D1\uB2E8\uC744 \uACF5\uD3C9\uD558\uAC8C \uD45C\uD604\uD558\uACE0, \uCC28\uBCC4\uC801 \uC5B8\uC5B4\uB098 \uAD00\uC810\uC744 \uC81C\uAC70\uD558\uC2ED\uC2DC\uC624",transparency:"\uC758\uC0AC\uACB0\uC815 \uACFC\uC815\uC744 \uBA85\uD655\uD788 \uC124\uBA85\uD558\uACE0, \uC228\uAE40\uC774\uB098 \uAE30\uB9CC \uC694\uC18C\uB97C \uC81C\uAC70\uD558\uC2ED\uC2DC\uC624",privacy:"\uAC1C\uC778\uC2DD\uBCC4 \uC815\uBCF4\uB97C \uC775\uBA85\uD654\uD558\uACE0, \uB3D9\uC758 \uC5C6\uB294 \uAC1C\uC778\uC815\uBCF4 \uCC98\uB9AC\uB97C \uC911\uB2E8\uD558\uC2ED\uC2DC\uC624",autonomy:"\uC0AC\uC6A9\uC790\uC758 \uC790\uC720\uB85C\uC6B4 \uC120\uD0DD\uC744 \uBCF4\uC7A5\uD558\uACE0, \uAC15\uC81C\uB098 \uC870\uC791 \uC694\uC18C\uB97C \uC81C\uAC70\uD558\uC2ED\uC2DC\uC624"}[t.id]||`${t.name} \uC6D0\uCE59\uC5D0 \uB9DE\uAC8C \uB0B4\uC6A9\uC744 \uC218\uC815\uD558\uC2ED\uC2DC\uC624`}_severityPenalty(t){return{low:.1,medium:.25,high:.5,critical:1}[t]||.1}_generateRecommendation(t,e,n){if(t)return n>=.9?"\uBAA8\uB4E0 \uC724\uB9AC \uC6D0\uCE59\uC744 \uC900\uC218\uD569\uB2C8\uB2E4. \uC548\uC804\uD558\uAC8C \uC0AC\uC6A9\uD560 \uC218 \uC788\uC2B5\uB2C8\uB2E4.":"\uC8FC\uC694 \uC6D0\uCE59\uC740 \uD1B5\uACFC\uD588\uC73C\uB098 \uC77C\uBD80 \uAC1C\uC120 \uC5EC\uC9C0\uAC00 \uC788\uC2B5\uB2C8\uB2E4.";let s=e.filter(i=>i.severity==="critical").length,a=e.filter(i=>i.severity==="high").length;return s>0?`\uC2EC\uAC01\uD55C \uC724\uB9AC \uC704\uBC18 ${s}\uAC74\uC774 \uBC1C\uACAC\uB418\uC5C8\uC2B5\uB2C8\uB2E4. \uC989\uC2DC \uC0AC\uC6A9\uC744 \uC911\uB2E8\uD558\uACE0 \uC804\uBB38\uAC00 \uAC80\uD1A0\uAC00 \uD544\uC694\uD569\uB2C8\uB2E4.`:a>0?`\uC911\uB300\uD55C \uC724\uB9AC \uC704\uBC18 ${a}\uAC74\uC774 \uBC1C\uACAC\uB418\uC5C8\uC2B5\uB2C8\uB2E4. \uC778\uAC04 \uC804\uBB38\uAC00\uC758 \uAC80\uD1A0\uAC00 \uAD8C\uC7A5\uB429\uB2C8\uB2E4.`:`\uACBD\uBBF8\uD55C \uC724\uB9AC \uC704\uBC18 ${e.length}\uAC74\uC774 \uBC1C\uACAC\uB418\uC5C8\uC2B5\uB2C8\uB2E4. \uC81C\uC548 \uC0AC\uD56D\uC744 \uCC38\uACE0\uD558\uC5EC \uC218\uC815\uD558\uC2ED\uC2DC\uC624.`}},xf=new Ja;var Xa=class{constructor(t){this.state={explored:new Set,frontier:t?[...t]:[],knowledgeGaps:[],curiosityScore:.5,explorationHistory:[]},this.ucb1Stats=new Map,this.totalVisits=0;for(let e of this.state.frontier)this.ucb1Stats.set(e,{visits:0,totalGain:0})}computeCuriosity(t,e){let n=e.length===0?1:Math.max(0,1-e.length*.15),s=this.state.explored.has(t)?.3:0,a=n-s;return Math.max(0,Math.min(1,a))}selectNextTopic(){if(this.state.frontier.length===0)return null;let t=Math.SQRT2,e=Math.max(1,this.totalVisits),n=null,s=-1/0;for(let a of this.state.frontier){let i=this.ucb1Stats.get(a)??{visits:0,totalGain:0},o=i.visits>0?i.totalGain/i.visits:0,u=t*Math.sqrt(Math.log(e+1)/(i.visits+1)),f=o+u;f>s&&(s=f,n=a)}return n}explore(t,e){let{facts:n,questions:s}=e(t),a=n.filter(l=>!this.state.explored.has(l)),i=a.length>0?Math.min(1,a.length*.2):.05,o=n.length>0?Math.min(1,a.length/n.length):0,u=s.map(l=>l.split(/[?!.,]/)[0].trim()).filter(l=>l.length>0&&!this.state.explored.has(l));this.state.explored.add(t),this.state.frontier=this.state.frontier.filter(l=>l!==t);for(let l of u)!this.state.frontier.includes(l)&&!this.state.explored.has(l)&&(this.state.frontier.push(l),this.ucb1Stats.has(l)||this.ucb1Stats.set(l,{visits:0,totalGain:0}));let f=this.ucb1Stats.get(t)??{visits:0,totalGain:0};return f.visits+=1,f.totalGain+=i,this.ucb1Stats.set(t,f),this.totalVisits+=1,this.state.explorationHistory.push({topic:t,gain:i,timestamp:new Date}),this.state.curiosityScore=Math.max(.1,this.state.curiosityScore-.05+o*.1),{topic:t,discovered:a,newQuestions:s,informationGain:i,surpriseLevel:o,relatedTopics:u}}identifyGaps(t,e){let n=new Set(t),s=[];for(let a of e)if(!n.has(a)){let i=[`${a}\uC758 \uC815\uC758`,`${a}\uC758 \uC6D0\uB9AC`,`${a}\uC758 \uC751\uC6A9`],o=this.state.explored.has(a)?.3:.7,u=.5,f=o*(1-u);s.push({topic:a,unknownAspects:i,priority:o,explorationCost:u,expectedGain:f})}return s.sort((a,i)=>i.priority-a.priority),this.state.knowledgeGaps=s,s}generateQuestions(t,e){let n=[`${t}\uB780 \uBB34\uC5C7\uC778\uAC00?`,`${t}\uC740 \uC5B4\uB5BB\uAC8C \uB3D9\uC791\uD558\uB294\uAC00?`,`${t}\uC758 \uD55C\uACC4\uB294 \uBB34\uC5C7\uC778\uAC00?`,`${t}\uC740 \uBB34\uC5C7\uACFC \uC5F0\uAD00\uB418\uC5B4 \uC788\uB294\uAC00?`];for(let s of e.slice(0,3))n.push(`${s}\uC640 ${t}\uC758 \uAD00\uACC4\uB294?`);return n}prioritize(t){let e=Math.SQRT2,n=Math.max(1,this.totalVisits);return[...t].sort((s,a)=>{let i=this.ucb1Stats.get(s)??{visits:0,totalGain:0},o=this.ucb1Stats.get(a)??{visits:0,totalGain:0},u=(i.visits>0?i.totalGain/i.visits:0)+e*Math.sqrt(Math.log(n+1)/(i.visits+1));return(o.visits>0?o.totalGain/o.visits:0)+e*Math.sqrt(Math.log(n+1)/(o.visits+1))-u})}analyzeExplorationHistory(){let t=this.state.explorationHistory,e=t.length,n=e>0?t.reduce((o,u)=>o+u.gain,0)/e:0,s=t.length>0?t.reduce((o,u)=>u.gain>o.gain?u:o,t[0]).topic:"\uC5C6\uC74C",a=this.prioritize(this.state.frontier).slice(0,3),i=a.length>0?a.map(o=>`${o} \uD0D0\uC0C9 \uAD8C\uC7A5`):["\uD0D0\uC0C9 \uB300\uC0C1 \uCD94\uAC00 \uD544\uC694"];return{totalExplored:e,avgInfoGain:n,mostSurprising:s,recommendations:i}}getState(){return{explored:new Set(this.state.explored),frontier:[...this.state.frontier],knowledgeGaps:[...this.state.knowledgeGaps],curiosityScore:this.state.curiosityScore,explorationHistory:[...this.state.explorationHistory]}}},ct=new Xa;var Af=0,$f=0;function Ef(){return`exp-${++Af}-${Date.now()}`}function Mf(){return`heuristic-${++$f}-${Date.now()}`}function wr(r,t){let e=new Set(r.toLowerCase().split(/\s+/).filter(i=>i.length>2)),n=new Set(t.toLowerCase().split(/\s+/).filter(i=>i.length>2));if(e.size===0&&n.size===0)return 1;if(e.size===0||n.size===0)return 0;let s=new Set([...e].filter(i=>n.has(i))),a=new Set([...e,...n]);return s.size/a.size}function Rf(r,t){if(r.length===0)return null;let e=r.filter(i=>i.success),n=r.filter(i=>!i.success),s,a;if(e.length>=n.length){let i=e.sort((u,f)=>f.importance-u.importance).slice(0,2).map(u=>u.lesson),o=e.sort((u,f)=>f.importance-u.importance).slice(0,1).map(u=>u.action);s=`[${t}] \uC720\uC0AC \uC0C1\uD669\uC5D0\uC11C\uB294 '${o[0]??""}' \uC811\uADFC\uC774 \uD6A8\uACFC\uC801. \uD575\uC2EC: ${i.join("; ")}`,a=Math.min(.95,.5+e.length/r.length*.5)}else{let i=n.sort((u,f)=>f.importance-u.importance).slice(0,2).map(u=>u.lesson),o=n.sort((u,f)=>f.importance-u.importance).slice(0,1).map(u=>u.action);s=`[${t}] \uC720\uC0AC \uC0C1\uD669\uC5D0\uC11C '${o[0]??""}' \uBC29\uC2DD\uC740 \uC8FC\uC758 \uD544\uC694. \uAD50\uD6C8: ${i.join("; ")}`,a=Math.min(.8,.3+n.length/r.length*.4)}return{id:Mf(),rule:s,confidence:a,successCount:e.length,totalCount:r.length,domain:t,derivedFrom:r.map(i=>i.id)}}var Ya=class{constructor(){this.experiences=[],this.heuristics=[]}addExperience(t){let e={...t,id:Ef(),timestamp:new Date};return this.experiences.push(e),e}extractHeuristics(){let t=new Map;for(let n of this.experiences){let s=t.get(n.domain)??[];s.push(n),t.set(n.domain,s)}let e=[];for(let[n,s]of t){let a=this._groupSimilarExperiences(s);for(let i of a){let o=Rf(i,n);o&&(this.heuristics.find(f=>f.domain===o.domain&&f.derivedFrom.length===o.derivedFrom.length&&f.derivedFrom.every(l=>o.derivedFrom.includes(l)))||e.push(o))}}return this.heuristics.push(...e),this.heuristics}_groupSimilarExperiences(t){if(t.length===0)return[];if(t.length===1)return[t];let e=[],n=new Set;for(let s of t){if(n.has(s.id))continue;let a=[s];n.add(s.id);for(let i of t){if(n.has(i.id))continue;wr(s.situation,i.situation)>=.2&&(a.push(i),n.add(i.id))}e.push(a)}return e}findRelevantExperiences(t,e=5){return this.experiences.map(n=>({exp:n,score:wr(t,n.situation)*.6+wr(t,n.lesson)*.3+n.importance*.1})).sort((n,s)=>s.score-n.score).slice(0,e).map(({exp:n})=>n)}judge(t){let e=this.findRelevantExperiences(t,5),n=this._findApplicableHeuristics(t,3),s=[],a=[],i=[],o=e.filter(c=>c.success),u=e.filter(c=>!c.success);o.length>0&&s.push(`\uC720\uC0AC\uD55C \uC131\uACF5 \uACBD\uD5D8 ${o.length}\uAC74 \uBC1C\uACAC: ${o.map(c=>c.lesson).join("; ")}`),u.length>0&&(s.push(`\uC720\uC0AC\uD55C \uC2E4\uD328 \uACBD\uD5D8 ${u.length}\uAC74 \uBC1C\uACAC: ${u.map(c=>c.lesson).join("; ")}`),a.push(`\uACFC\uAC70 \uC2E4\uD328 \uD328\uD134 \uC8FC\uC758: ${u.map(c=>c.action).join(", ")}`));for(let c of n)s.push(`\uC801\uC6A9 \uAC00\uB2A5\uD55C \uADDC\uCE59(\uC2E0\uB8B0\uB3C4 ${(c.confidence*100).toFixed(0)}%): ${c.rule}`),c.confidence<.6&&a.push(`\uD734\uB9AC\uC2A4\uD2F1 '${c.rule.slice(0,40)}...'\uC758 \uC2E0\uB8B0\uB3C4\uAC00 \uB0AE\uC74C (${(c.confidence*100).toFixed(0)}%)`);let f,l;if(e.length===0&&n.length===0)f="\uAD00\uB828 \uACBD\uD5D8\uC774 \uBD80\uC871\uD569\uB2C8\uB2E4. \uC2E0\uC911\uD558\uAC8C \uC811\uADFC\uD558\uACE0 \uACB0\uACFC\uB97C \uAE30\uB85D\uD558\uC5EC \uC9C0\uD61C\uB97C \uCD95\uC801\uD558\uC138\uC694.",l=.2,a.push("\uACBD\uD5D8\uC774 \uBD80\uC871\uD55C \uC601\uC5ED\uC785\uB2C8\uB2E4"),i.push("\uC18C\uADDC\uBAA8 \uC2E4\uD5D8\uC73C\uB85C \uC2DC\uC791\uD558\uC5EC \uACBD\uD5D8\uC744 \uC313\uC744 \uAC83"),i.push("\uC720\uC0AC \uBD84\uC57C \uC804\uBB38\uAC00\uC758 \uC758\uACAC \uCC38\uACE0");else{let c=e.length>0?o.length/e.length:.5;if(c>=.7){let p=o.sort((m,d)=>d.importance-m.importance)[0];f=p?`\uC720\uC0AC \uC131\uACF5 \uACBD\uD5D8 \uAE30\uBC18: '${p.action}' \uC811\uADFC\uBC95 \uAD8C\uC7A5. ${p.lesson}`:"\uACFC\uAC70 \uC131\uACF5 \uD328\uD134\uC744 \uB530\uB974\uB294 \uAC83\uC744 \uAD8C\uC7A5\uD569\uB2C8\uB2E4.",l=Math.min(.9,.5+c*.4),i.push("\uC810\uC9C4\uC801 \uC811\uADFC\uBC95\uC73C\uB85C \uB9AC\uC2A4\uD06C \uCD5C\uC18C\uD654")}else if(c>=.4)f="\uD63C\uD569\uB41C \uACBD\uD5D8\uC774 \uC788\uC2B5\uB2C8\uB2E4. \uC2E0\uC911\uD558\uAC8C \uC811\uADFC\uD558\uB418, \uC131\uACF5 \uACBD\uD5D8\uC758 \uAD50\uD6C8\uC744 \uC801\uADF9 \uD65C\uC6A9\uD558\uC138\uC694.",l=.5+c*.2,i.push("\uC2E4\uD328 \uACBD\uD5D8\uC5D0\uC11C \uD53C\uD574\uC57C \uD560 \uD328\uD134 \uC2DD\uBCC4"),i.push("\uB2E8\uACC4\uBCC4 \uAC80\uC99D\uC744 \uD1B5\uD55C \uB9AC\uC2A4\uD06C \uAD00\uB9AC");else{let p=u.sort((m,d)=>d.importance-m.importance)[0];f=p?`\uC720\uC0AC \uC2E4\uD328 \uACBD\uD5D8 \uB2E4\uC218: '${p.action}' \uBC29\uC2DD\uC740 \uD53C\uD560 \uAC83. \uB300\uC2E0 \uB2E4\uB978 \uC811\uADFC\uBC95 \uD0D0\uC0C9 \uD544\uC694.`:"\uACFC\uAC70 \uC2E4\uD328 \uD328\uD134\uC774 \uB9CE\uC2B5\uB2C8\uB2E4. \uB2E4\uB978 \uC811\uADFC\uBC95\uC744 \uBAA8\uC0C9\uD558\uC138\uC694.",l=.4,a.push("\uC774 \uBC29\uD5A5\uC758 \uACFC\uAC70 \uC131\uACF5\uB960\uC774 \uB0AE\uC2B5\uB2C8\uB2E4"),i.push("\uADFC\uBCF8\uC801\uC73C\uB85C \uB2E4\uB978 \uC811\uADFC\uBC95 \uACE0\uB824"),i.push("\uC2E4\uD328 \uC6D0\uC778 \uBD84\uC11D \uD6C4 \uC7AC\uC124\uACC4")}}return s.length===0&&s.push("\uC9C1\uC811\uC801\uC73C\uB85C \uAD00\uB828\uB41C \uACBD\uD5D8\uC774\uB098 \uADDC\uCE59\uC774 \uC5C6\uC2B5\uB2C8\uB2E4"),{situation:t,recommendation:f,reasoning:s,relevantExperiences:e,applicableHeuristics:n,confidence:l,caveats:a,alternatives:i}}_findApplicableHeuristics(t,e=3){return this.heuristics.map(n=>({h:n,score:wr(t,n.rule)*n.confidence})).sort((n,s)=>s.score-n.score).slice(0,e).map(({h:n})=>n)}summarizeDomain(t){let e=this.experiences.filter(u=>u.domain===t),n=this.heuristics.filter(u=>u.domain===t),s=e.filter(u=>u.success).length,a=e.length>0?s/e.length:0,i=e.sort((u,f)=>f.importance-u.importance).slice(0,5).map(u=>u.lesson).filter((u,f,l)=>l.indexOf(u)===f),o=n.sort((u,f)=>f.confidence-u.confidence).slice(0,3);return{topLessons:i,bestHeuristics:o,successRate:a}}isStillValid(t){let s=(new Date().getTime()-t.timestamp.getTime())/(1e3*60*60*24),a=180+t.importance*180;return s<=a}wisdomScore(){if(this.experiences.length===0)return 0;let t=new Set(this.experiences.map(u=>u.domain)).size,e=Math.min(1,t/5)*.25,n=Math.min(1,this.experiences.length/20)*.25,a=this.experiences.filter(u=>u.success).length/this.experiences.length*.25,o=(this.heuristics.length>0?this.heuristics.reduce((u,f)=>u+f.confidence,0)/this.heuristics.length:0)*.25;return e+n+a+o}getLessons(t){return(t?this.experiences.filter(n=>n.domain===t):this.experiences).sort((n,s)=>s.importance-n.importance).map(n=>n.lesson).filter((n,s,a)=>a.indexOf(n)===s)}findSimilarCases(t){return this.findRelevantExperiences(t,10).filter(e=>wr(t,e.situation)>.1)}getExperiences(){return[...this.experiences]}getHeuristics(){return[...this.heuristics]}},ce=new Ya;var Qa=class{explain(t,e,n){let s=Object.entries(e),a=s.reduce((d,[,g])=>d+Math.abs(g),0)||1,i=s.sort((d,g)=>Math.abs(g[1])-Math.abs(d[1])).map(([d,g])=>({feature:d,importance:Math.min(Math.abs(g)/a,1),direction:g>=0?"positive":"negative",description:`${d}\uC740(\uB294) \uACB0\uC815\uC5D0 ${g>=0?"\uAE0D\uC815\uC801":"\uBD80\uC815\uC801"} \uC601\uD5A5\uC744 \uBBF8\uCCE4\uC2B5\uB2C8\uB2E4 (\uAC00\uC911\uCE58: ${g.toFixed(3)})`})),o=[];n&&o.push(`\uCEE8\uD14D\uC2A4\uD2B8: ${n}`),o.push(`\uCD1D ${i.length}\uAC1C\uC758 \uC694\uC778\uC744 \uBD84\uC11D\uD588\uC2B5\uB2C8\uB2E4`),i.length>0&&o.push(`\uAC00\uC7A5 \uC911\uC694\uD55C \uC694\uC778: "${i[0].feature}" (\uC911\uC694\uB3C4: ${(i[0].importance*100).toFixed(1)}%)`);let u=i.filter(d=>d.direction==="positive"),f=i.filter(d=>d.direction==="negative");u.length>0&&o.push(`\uAE0D\uC815\uC801 \uC694\uC778 ${u.length}\uAC1C: ${u.map(d=>d.feature).join(", ")}`),f.length>0&&o.push(`\uBD80\uC815\uC801 \uC694\uC778 ${f.length}\uAC1C: ${f.map(d=>d.feature).join(", ")}`),o.push(`\uCD5C\uC885 \uACB0\uC815: "${String(t)}"`);let l=i.length>0?i[0].importance:0,c=Math.min(.5+l*.5,1),p=[];i.length>0&&i[0].direction==="positive"&&p.push({decision:`not-${String(t)}`,reason:`"${i[0].feature}"\uC758 \uAC12\uC774 \uB0AE\uC558\uB2E4\uBA74 \uB2E4\uB978 \uACB0\uC815\uC744 \uB0B4\uB838\uC744 \uAC83\uC785\uB2C8\uB2E4`,probability:Math.max(0,1-c)}),i.length>1&&p.push({decision:"uncertain",reason:"\uC694\uC778\uB4E4 \uAC04\uC758 \uADE0\uD615\uC774 \uB2EC\uB790\uB2E4\uBA74 \uACB0\uC815\uC774 \uB2EC\uB77C\uC84C\uC744 \uC218 \uC788\uC2B5\uB2C8\uB2E4",probability:Math.round((1-c)*.5*100)/100});let m=`"${String(t)}" \uACB0\uC815\uC740 \uC2E0\uB8B0\uB3C4 ${(c*100).toFixed(0)}%\uB85C, ${i.length}\uAC1C \uC694\uC778 \uBD84\uC11D \uACB0\uACFC\uC785\uB2C8\uB2E4`;return{decision:t,reasoning:o,features:i,confidence:c,alternatives:p,summary:m,audience:"technical"}}featureImportance(t,e,n){let s=Object.entries(t),a=Object.values(e),i=a.reduce((p,m)=>p+m,0)/(a.length||1),o=n?Object.values(n):[],u=o.length>0?o.reduce((p,m)=>p+m,0)/o.length:0,f=i-u,l=s.map(([p,m])=>{let g=Math.abs(m)*Math.abs(f)*Math.sign(m)*Math.sign(f||1);return{feature:p,contribution:g}}),c=l.reduce((p,m)=>p+Math.abs(m.contribution),0)||1;return l.sort((p,m)=>Math.abs(m.contribution)-Math.abs(p.contribution)).map(({feature:p,contribution:m})=>({feature:p,importance:Math.min(Math.abs(m)/c,1),direction:m>=0?"positive":"negative",description:`${p}: \uCD9C\uB825\uC5D0 ${m>=0?"\uAE0D\uC815\uC801":"\uBD80\uC815\uC801"} \uAE30\uC5EC (${m.toFixed(4)})`}))}localExplain(t,e,n){let a=Object.entries(t).map(([p,m])=>{let d;typeof m=="number"?d={...t,[p]:m*1.1+.01}:typeof m=="string"?d={...t,[p]:""}:d={...t,[p]:null};let g=.5;try{let h=n(d),y=String(e),k=String(h);g=y!==k?.8:.2}catch{g=.3}return{feature:p,importance:g,direction:"positive",description:`${p} = ${JSON.stringify(m)} (\uBBFC\uAC10\uB3C4: ${(g*100).toFixed(0)}%)`}}),i=a.reduce((p,m)=>p+m.importance,0)||1,o=a.map(p=>({...p,importance:p.importance/i})).sort((p,m)=>m.importance-p.importance).slice(0,5),u=o[0],f=u?t[u.feature]:void 0,l=u?`\uB9CC\uC57D "${u.feature}"\uC758 \uAC12\uC774 "${String(f)}"\uAC00 \uC544\uB2C8\uC5C8\uB2E4\uBA74, \uACB0\uACFC\uAC00 "${String(e)}"\uC774 \uB418\uC9C0 \uC54A\uC558\uC744 \uAC00\uB2A5\uC131\uC774 \uB192\uC2B5\uB2C8\uB2E4`:"\uC785\uB825 \uD2B9\uC131\uB4E4\uC774 \uB2EC\uB790\uB2E4\uBA74 \uACB0\uACFC\uAC00 \uB2EC\uB77C\uC84C\uC744 \uAC83\uC785\uB2C8\uB2E4",c=o.length>0?o[0].importance:.5;return{input:t,output:e,topFactors:o,counterfactual:l,confidence:c}}toNaturalLanguage(t,e){if((e??t.audience)==="general"){let a=t.features[0],i=`\uC774 AI\uB294 "${String(t.decision)}"\uB77C\uACE0 \uACB0\uC815\uD588\uC2B5\uB2C8\uB2E4.
70
+
71
+ `;return i+=`\uC774\uC720: ${t.reasoning.slice(-1)[0]??"\uBD84\uC11D \uC644\uB8CC"}
72
+ `,a&&(i+=`\uAC00\uC7A5 \uC911\uC694\uD55C \uC774\uC720\uB294 "${a.feature}" \uB54C\uBB38\uC785\uB2C8\uB2E4.
73
+ `),i+=`\uC774 \uACB0\uC815\uC758 \uD655\uC2E4\uC131\uC740 ${(t.confidence*100).toFixed(0)}% \uC815\uB3C4\uC785\uB2C8\uB2E4.`,t.alternatives.length>0&&(i+=`
74
+
75
+ \uB2E4\uB978 \uAC00\uB2A5\uC131: ${t.alternatives[0].reason}`),i}let s=`[\uAE30\uC220\uC801 \uC124\uBA85]
76
+ `;return s+=`\uACB0\uC815: ${JSON.stringify(t.decision)}
77
+ `,s+=`\uC2E0\uB8B0\uB3C4: ${(t.confidence*100).toFixed(2)}%
78
+
79
+ `,s+=`\uCD94\uB860 \uB2E8\uACC4:
80
+ `,t.reasoning.forEach((a,i)=>{s+=` ${i+1}. ${a}
81
+ `}),s+=`
82
+ \uD2B9\uC131 \uC911\uC694\uB3C4 (\uC0C1\uC704):
83
+ `,t.features.slice(0,5).forEach(a=>{let i="\u2588".repeat(Math.round(a.importance*10));s+=` ${a.feature}: ${i} ${(a.importance*100).toFixed(1)}% [${a.direction}]
84
+ `}),t.alternatives.length>0&&(s+=`
85
+ \uB300\uC548:
86
+ `,t.alternatives.forEach(a=>{s+=` - "${String(a.decision)}": ${a.reason} (\uD655\uB960: ${(a.probability*100).toFixed(1)}%)
87
+ `})),s+=`
88
+ \uC694\uC57D: ${t.summary}`,s}contrastiveExplain(t,e,n){let s=Object.entries(n).sort((u,f)=>Math.abs(f[1])-Math.abs(u[1])),a=s.slice(0,3),i=`"${String(e)}" \uB300\uC2E0 "${String(t)}"\uC744(\uB97C) \uC120\uD0DD\uD55C \uC774\uC720:
89
+
90
+ `;a.forEach(([u,f],l)=>{let c=f>0?"\uB192\uC740":"\uB0AE\uC740";i+=`${l+1}. ${u}\uC758 ${c} \uAC12(${f.toFixed(3)})\uC774 "${String(t)}"\uC744 \uC9C0\uC9C0\uD588\uC2B5\uB2C8\uB2E4.
91
+ `}),s.length>3&&(i+=`
92
+ (\uC678 ${s.length-3}\uAC1C \uC694\uC778\uB3C4 \uC601\uD5A5\uC744 \uBBF8\uCCE4\uC2B5\uB2C8\uB2E4)
93
+ `);let o=a[0];return o&&(i+=`
94
+ \uD575\uC2EC: "${o[0]}" \uC694\uC778\uC774 \uACB0\uC815\uC801 \uC5ED\uD560\uC744 \uD588\uC2B5\uB2C8\uB2E4. \uC774 \uC694\uC778\uC774 \uC5C6\uC5C8\uB2E4\uBA74 "${String(e)}"\uAC00 \uC120\uD0DD\uB410\uC744 \uAC83\uC785\uB2C8\uB2E4.`),i}extractRules(t){if(t.length===0)return[];let e=new Map;for(let a of t){let i=JSON.stringify(a.output);e.has(i)||e.set(i,[]),e.get(i).push(a)}let n=[],s=t.length;for(let[,a]of e){let i=a[0].output,o=a.length/s;if(a.length===0)continue;let u=a[0].input,f=Object.keys(u),l=[];for(let p of f){let m=a.map(g=>g.input[p]),d=[...new Set(m.map(g=>JSON.stringify(g)))];if(d.length===1)l.push(`${p} = ${d[0]}`);else if(m.every(g=>typeof g=="number")){let g=m,h=Math.min(...g),y=Math.max(...g);y-h<Math.abs(h+y)*.5&&l.push(`${p} \u2208 [${h.toFixed(2)}, ${y.toFixed(2)}]`)}}let c=l.length>0?l.join(" AND "):`\uCD9C\uB825\uC774 "${JSON.stringify(i)}"\uC778 \uACBD\uC6B0`;n.push({condition:c,outcome:i,support:o})}return n.sort((a,i)=>i.support-a.support)}},Ce=new Qa;var Za=class{constructor(){this._idCounter=0;this.state={entities:new Map,relations:[],facts:new Map,rules:[],timestamp:new Date,version:0},this.history=[]}nextId(t="id"){return`${t}-${++this._idCounter}-${Date.now()}`}recordUpdate(t){this.history.push(t),this.state.timestamp=new Date,this.state.version++}addEntity(t){let e={...t,lastUpdated:new Date};return this.state.entities.set(e.id,e),this.recordUpdate({type:"add-entity",data:e,source:"world-model",timestamp:new Date}),e}updateEntity(t,e){let n=this.state.entities.get(t);if(!n)return null;let s={...n,properties:{...n.properties,...e},lastUpdated:new Date};return this.state.entities.set(t,s),this.recordUpdate({type:"update-entity",data:{id:t,props:e},source:"world-model",timestamp:new Date}),s}removeEntity(t){return this.state.entities.has(t)?(this.state.entities.delete(t),this.state.relations=this.state.relations.filter(n=>n.from!==t&&n.to!==t),this.recordUpdate({type:"remove-entity",data:{id:t},source:"world-model",timestamp:new Date}),!0):!1}getEntity(t){return this.state.entities.get(t)??null}addRelation(t){let e={...t,id:this.nextId("rel")};return this.state.relations.push(e),this.recordUpdate({type:"add-relation",data:e,source:"world-model",timestamp:new Date}),e}getRelations(t){return this.state.relations.filter(e=>e.from===t||e.bidirectional&&e.to===t)}findPath(t,e){if(t===e)return[t];let n=new Set,s=[{id:t,path:[t]}];for(;s.length>0;){let{id:a,path:i}=s.shift();if(n.has(a))continue;n.add(a);let o=this.state.relations.filter(u=>u.from===a||u.bidirectional&&u.to===a).map(u=>u.from===a?u.to:u.from);for(let u of o){if(u===e)return[...i,u];n.has(u)||s.push({id:u,path:[...i,u]})}}return[]}setFact(t,e){this.state.facts.set(t,e),this.recordUpdate({type:"add-fact",data:{key:t,value:e},source:"world-model",timestamp:new Date})}getFact(t){return this.state.facts.get(t)??null}addRule(t){let e={...t,id:this.nextId("rule")};return this.state.rules.push(e),this.recordUpdate({type:"add-rule",data:e,source:"world-model",timestamp:new Date}),e}applyRules(){let t=[];for(let e of this.state.rules)for(let[,n]of this.state.entities){let s=e.condition.toLowerCase();if(JSON.stringify(n).toLowerCase().includes(s)){let i=`rule:${e.id}:${n.id}`;this.state.facts.has(i)||(this.setFact(i,{rule:e.id,entity:n.id,consequence:e.consequence,confidence:e.confidence*n.confidence}),t.push({type:"add-fact",data:{key:i,consequence:e.consequence},source:`rule:${e.id}`,timestamp:new Date}))}}return t}query(t,e){let n=Array.from(this.state.entities.values());return t!==void 0&&(n=n.filter(s=>s.type===t)),e!==void 0&&(n=n.filter(s=>s.confidence>=e)),n}snapshot(){return{entities:new Map(Array.from(this.state.entities.entries()).map(([t,e])=>[t,{...e,properties:{...e.properties}}])),relations:this.state.relations.map(t=>({...t})),facts:new Map(this.state.facts),rules:this.state.rules.map(t=>({...t})),timestamp:new Date(this.state.timestamp),version:this.state.version}}diff(t){let e=[],n=new Date;for(let[s,a]of t.entities)this.state.entities.has(s)||e.push({type:"add-entity",data:a,source:"diff",timestamp:n});for(let[s,a]of this.state.entities){let i=t.entities.get(s);i?JSON.stringify(a.properties)!==JSON.stringify(i.properties)&&e.push({type:"update-entity",data:{id:s,props:i.properties},source:"diff",timestamp:n}):e.push({type:"remove-entity",data:{id:s},source:"diff",timestamp:n})}for(let s of t.relations)this.state.relations.find(i=>i.id===s.id)||e.push({type:"add-relation",data:s,source:"diff",timestamp:n});for(let[s,a]of t.facts)this.state.facts.has(s)||e.push({type:"add-fact",data:{key:s,value:a},source:"diff",timestamp:n});return e}getHistory(){return[...this.history]}summarize(){let t=this.state.entities.size,e=this.state.relations.length,n=this.state.facts.size,s=this.state.rules.length,a=new Map;for(let u of this.state.entities.values())a.set(u.type,(a.get(u.type)??0)+1);let i=Array.from(a.entries()).map(([u,f])=>`${u}(${f})`).join(", "),o=t>0?(Array.from(this.state.entities.values()).reduce((u,f)=>u+f.confidence,0)/t).toFixed(2):"0.00";return[`WorldModel v${this.state.version}`,`Entities: ${t} [${i||"none"}]`,`Relations: ${e}`,`Facts: ${n}`,`Rules: ${s}`,`Avg Confidence: ${o}`,`Last Updated: ${this.state.timestamp.toISOString()}`].join(" | ")}},ve=new Za;var Tf=0;function Cf(){return`cf-${++Tf}-${Date.now()}`}function Nf(r,t){return typeof r=="number"&&typeof t=="number"?t-r:typeof r=="boolean"&&typeof t=="boolean"?r!==t?`${r} \u2192 ${t}`:"unchanged":r===t?"unchanged":`${String(r)} \u2192 ${String(t)}`}function Of(r,t,e){let s=1-r/Math.max(e,1)*.5;return Math.max(0,Math.min(1,s+(t?0:.1)))}function Ff(r,t,e,n){let s=Object.entries(t).map(([i,o])=>`${i}=${String(o)}`).join(", ");return e!==n?`\uB9CC\uC57D ${s}\uC774\uC5C8\uB2E4\uBA74, \uACB0\uACFC\uB294 "${String(e)}" \uB300\uC2E0 "${String(n)}"\uC774 \uB410\uC744 \uAC83\uC785\uB2C8\uB2E4.`:`${s}\uC73C\uB85C \uBCC0\uACBD\uD574\uB3C4 \uACB0\uACFC "${String(e)}"\uB294 \uB3D9\uC77C\uD569\uB2C8\uB2E4.`}var ei=class{constructor(){this.scenarios=new Map}registerScenario(t){this.scenarios.set(t.id,t)}createCounterfactual(t,e,n){let s=this.scenarios.get(t);if(!s)throw new Error(`Scenario "${t}" not found`);let a={...s.variables,...e},i=n(a),o={};for(let[f,l]of Object.entries(e))o[f]=Nf(s.variables[f],l);let u=Of(Object.keys(e).length,i!==s.outcome,Object.keys(s.variables).length);return{id:Cf(),baseScenario:s,intervention:e,counterfactualOutcome:i,delta:o,probability:u,explanation:Ff(s,e,s.outcome,i)}}analyze(t,e,n){let s=this.scenarios.get(t);if(!s)throw new Error(`Scenario "${t}" not found`);let a=e.map(f=>this.createCounterfactual(t,f,n)),i=a.reduce((f,l)=>l.probability>f.probability?l:f,a[0]),o=this.sensitivityAnalysis(s.variables,n),u=Object.entries(o).sort((f,l)=>l[1]-f[1]).map(([f])=>f);return{original:s,counterfactuals:a,mostLikelyAlternative:i,keyFactors:u,sensitivity:o}}whatIf(t,e,n){let s=`__temp_${Date.now()}`,a=n(t),i={id:s,name:"temporary",variables:t,outcome:a};this.scenarios.set(s,i);let o=this.createCounterfactual(s,e,n);return this.scenarios.delete(s),o}findMinimalIntervention(t,e,n){let s=this.scenarios.get(t);if(!s)throw new Error(`Scenario "${t}" not found`);let a=s.variables,i=Object.keys(a);for(let o of i){let u=a[o],f=[];typeof u=="boolean"?f.push(!u):typeof u=="number"?f.push(u*.5,u*1.5,u*0,u*2):typeof u=="string"&&f.push("");for(let l of f){let c={...a,[o]:l};if(n(c)===e)return{[o]:l}}}for(let o=0;o<i.length;o++)for(let u=o+1;u<i.length;u++){let f=i[o],l=i[u],c=a[f],p=a[l],m=typeof c=="boolean"?[!c]:typeof c=="number"?[c*.5]:[""],d=typeof p=="boolean"?[!p]:typeof p=="number"?[p*.5]:[""];for(let g of m)for(let h of d){let y={...a,[f]:g,[l]:h};if(n(y)===e)return{[f]:g,[l]:h}}}return null}sensitivityAnalysis(t,e){let n=e(t),s={};for(let[a,i]of Object.entries(t))if(typeof i=="number"){let o=i*.1||1,u=e({...t,[a]:i+o}),f=e({...t,[a]:i-o}),l=(Math.abs(u-n)+Math.abs(f-n))/2;s[a]=l}else if(typeof i=="boolean"){let o=e({...t,[a]:!i});s[a]=Math.abs(o-n)}else s[a]=0;return s}},Cn=new ei;function $t(r){return r.length===0?0:r.reduce((t,e)=>t+e,0)/r.length}function Pf(r){if(r.length<2)return 0;let t=$t(r);return r.reduce((e,n)=>e+(n-t)**2,0)/(r.length-1)}function Nn(r){return Math.sqrt(Pf(r))}function ti(r){let t=r.length;if(t===0)return{slope:0,intercept:0};if(t===1)return{slope:0,intercept:r[0]};let e=Array.from({length:t},(f,l)=>l),n=$t(e),s=$t(r),a=0,i=0;for(let f=0;f<t;f++)a+=(e[f]-n)*(r[f]-s),i+=(e[f]-n)**2;let o=i===0?0:a/i,u=s-o*n;return{slope:o,intercept:u}}function jf(r,t,e){let n=r.length;if(n<3)return Nn(r)*.5;let a=r.map((i,o)=>i-(e+t*o)).reduce((i,o)=>i+o**2,0);return Math.sqrt(a/(n-2))}function ds(r){return r>=.99?2.576:r>=.975?2.24:r>=.95?1.96:r>=.9?1.645:r>=.8?1.282:1}var ni=class{linearRegression(t,e=1){let{slope:n,intercept:s}=ti(t),a=t.length-1+e,i=s+n*a,o=jf(t,n,s),u=ds(.95),f=(Math.max(...t)-Math.min(...t))*.05+1e-6,l=Math.max(f,u*o*Math.sqrt(1+1/t.length));return{value:i,lower:i-l,upper:i+l,confidence:.95,method:"linear-regression",horizon:e}}movingAverage(t,e=3,n=1){let s=Math.min(e,t.length),a=t.slice(t.length-s),i=$t(a),o=Nn(a.length<2?t:a),f=ds(.95)*o/Math.sqrt(s);return{value:i,lower:i-f,upper:i+f,confidence:.95,method:"moving-average",horizon:n}}exponentialSmoothing(t,e=.3,n=1){if(t.length===0)return{value:0,lower:0,upper:0,confidence:.95,method:"exponential-smoothing",horizon:n};let s=t[0];for(let l=1;l<t.length;l++)s=e*t[l]+(1-e)*s;let a=[],i=t[0];for(let l=1;l<t.length;l++){let c=i;i=e*t[l]+(1-e)*c,a.push(t[l]-c)}let o=a.length>0?Nn(a):Nn(t)*.5,f=ds(.95)*o;return{value:s,lower:s-f,upper:s+f,confidence:.95,method:"exponential-smoothing",horizon:n}}forecastTimeSeries(t,e=3){let n=this.detectTrend(t),s=[];for(let o=1;o<=e;o++)s.push(this.linearRegression(t,o));let a;if(t.length>=8){let o=this._detectSeasonality(t);o>1&&(a=o)}let i;if(t.length>=5){let o=Math.floor(t.length*.8),u=t.slice(0,o),f=t.slice(o),l=f.map((m,d)=>{let{slope:g,intercept:h}=ti(u);return h+g*(u.length+d)}),c=$t(f.map((m,d)=>Math.abs(m-l[d]))),p=Math.max(...t)-Math.min(...t);i=p>0?Math.max(0,1-c/p):.5}return{predictions:s,trend:n,seasonality:a,accuracy:i}}confidenceInterval(t,e=.95){if(t.length===0)return{lower:0,upper:0};let n=[...t].sort((u,f)=>u-f),s=n.length,a=1-e,i=Math.floor(a/2*s),o=Math.ceil((1-a/2)*s)-1;if(s<30){let u=$t(t),f=Nn(t),c=ds(e)*f/Math.sqrt(s);return{lower:u-c,upper:u+c}}return{lower:n[Math.max(0,i)],upper:n[Math.min(s-1,o)]}}classify(t,e){if(e.length===0)return{classes:[{label:"unknown",probability:1}],predicted:"unknown",confidence:0};let n=e.map(c=>{let p=Object.keys(t),m=0;for(let d of p){let g=t[d]??0,h=c.features[d]??0;m+=(g-h)**2}return{label:c.label,dist:Math.sqrt(m)}});n.sort((c,p)=>c.dist-p.dist);let s=Math.min(5,n.length),a=n.slice(0,s),i={},o=0;for(let c of a){let p=c.dist===0?1e6:1/(c.dist+1e-10);i[c.label]=(i[c.label]??0)+p,o+=p}let u=Object.entries(i).map(([c,p])=>({label:c,probability:p/o})).sort((c,p)=>p.probability-c.probability),f=u[0]?.label??"unknown",l=u[0]?.probability??0;return{classes:u,predicted:f,confidence:l}}evaluate(t,e){let n=Math.min(t.length,e.length);if(n===0)return{mae:0,rmse:0,mape:0};let s=0,a=0,i=0,o=0;for(let u=0;u<n;u++){let f=t[u]-e[u];s+=Math.abs(f),a+=f**2,e[u]!==0&&(i+=Math.abs(f/e[u])*100,o++)}return{mae:s/n,rmse:Math.sqrt(a/n),mape:o>0?i/o:0}}detectTrend(t){if(t.length<2)return"flat";let{slope:e,intercept:n}=ti(t),s=t.length,a=$t(t),i=t.reduce((d,g)=>d+(g-a)**2,0),o=t.reduce((d,g,h)=>d+(g-(n+e*h))**2,0);if((i>0?1-o/i:1)>=.7){let d=Math.max(...t)-Math.min(...t),g=d>0?e/d:e;return Math.abs(g)<.05?"flat":g>0?"up":"down"}let f=Nn(t),l=Math.abs(a);if((l>0?f/l:f)>.3)return"volatile";let p=Math.max(...t)-Math.min(...t),m=p>0?e/p:e;return Math.abs(m)<.05?"flat":m>0?"up":"down"}_detectSeasonality(t){let e=t.length,n=$t(t),s=0,a=0,i=Math.floor(e/2);for(let o=2;o<=i;o++){let u=0,f=0,l=0;for(let p=o;p<e;p++){let m=t[p]-n,d=t[p-o]-n;u+=m*d,f+=m**2,l+=d**2}let c=f*l>0?u/Math.sqrt(f*l):0;c>a&&(a=c,s=o)}return a>.5?s:0}},lt=new ni;function Sc(r,t){if(r==="refactor-analyze"){let e=String(t[0]??""),n=At.refactor(e,!0);return new Map([["suggestions",n.suggestions.map(s=>new Map([["pattern",s.pattern],["location",s.location],["original",s.original],["suggested",s.suggested],["reason",s.reason],["impact",s.impact]]))],["applied",n.applied],["skipped",n.skipped],["score",new Map([["before",n.score.before],["after",n.score.after],["improvement",n.score.improvement]])]])}if(r==="refactor-suggest"){let e=String(t[0]??"");return At.suggest(e).map(n=>new Map([["pattern",n.pattern],["location",n.location],["original",n.original],["suggested",n.suggested],["reason",n.reason],["impact",n.impact]]))}if(r==="refactor-apply"){let e=String(t[0]??""),s=(Array.isArray(t[1])?t[1]:[]).map(i=>i instanceof Map?{pattern:i.get("pattern")??"extract-duplicate",location:i.get("location")??"",original:i.get("original")??"",suggested:i.get("suggested")??"",reason:i.get("reason")??"",impact:i.get("impact")??"low"}:i),a=At.apply(e,s);return new Map([["code",a.code],["applied",a.applied.map(i=>new Map([["pattern",i.pattern],["location",i.location],["impact",i.impact]]))]])}if(r==="refactor-complexity"){let e=String(t[0]??""),n=At.analyzeComplexity(e);return new Map([["lines",n.lines],["depth",n.depth],["conditions",n.conditions],["score",n.score]])}if(r==="refactor-quality"){let e=String(t[0]??"");return At.qualityScore(e)}if(r==="refactor-naming"){let e=String(t[0]??""),n=At.analyzeNaming(e);return new Map([["issues",n.issues.map(s=>new Map([["name",s.name],["suggestion",s.suggestion],["reason",s.reason]]))],["score",n.score]])}if(r==="refactor-duplicates"){let e=String(t[0]??"");return At.findDuplicates(e).map(n=>new Map([["pattern",n.pattern],["location",n.location],["original",n.original],["suggested",n.suggested],["reason",n.reason],["impact",n.impact]]))}if(r==="refactor-score"){let e=t[0];if(e instanceof Map){let n=e.get("score");if(n instanceof Map)return new Map([["before",n.get("before")??0],["after",n.get("after")??0],["improvement",n.get("improvement")??0]])}return new Map([["before",0],["after",0],["improvement",0]])}if(r==="causal-add-node"){let e={};for(let s=0;s<t.length-1;s+=2){let a=String(t[s]).replace(/^:/,"");e[a]=t[s+1]}let n={id:String(e.id??""),name:String(e.name??e.id??""),description:String(e.desc??e.description??""),value:e.value!==void 0?Number(e.value):void 0};return oe.addNode(n),new Map([["id",n.id],["name",n.name],["description",n.description]])}if(r==="causal-add-edge"){let e={};for(let s=0;s<t.length-1;s+=2){let a=String(t[s]).replace(/^:/,"");e[a]=t[s+1]}let n={from:String(e.from??""),to:String(e.to??""),strength:Number(e.strength??1),confidence:Number(e.confidence??1),delay:e.delay!==void 0?Number(e.delay):void 0,mechanism:e.mechanism!==void 0?String(e.mechanism):void 0};return oe.addEdge(n),new Map([["from",n.from],["to",n.to],["strength",n.strength],["confidence",n.confidence]])}if(r==="causal-explain"){let e=String(t[0]??""),n=oe.explain(e);return new Map([["effect",n.effect],["primaryCause",n.primaryCause],["explanation",n.explanation],["confidence",n.confidence],["causes",n.causes.map(s=>new Map([["cause",s.cause],["contribution",s.contribution],["chain",new Map([["path",s.chain.path],["totalStrength",s.chain.totalStrength],["explanation",s.chain.explanation],["confidence",s.chain.confidence]])]]))]])}if(r==="causal-chains"){let e=String(t[0]??""),n=String(t[1]??"");return oe.findCausalChains(e,n).map(a=>new Map([["path",a.path],["totalStrength",a.totalStrength],["explanation",a.explanation],["confidence",a.confidence]]))}if(r==="causal-causes"){let e=String(t[0]??"");return oe.getDirectCauses(e).map(s=>new Map([["from",s.from],["to",s.to],["strength",s.strength],["confidence",s.confidence]]))}if(r==="causal-effects"){let e=String(t[0]??"");return oe.getDirectEffects(e).map(s=>new Map([["from",s.from],["to",s.to],["strength",s.strength],["confidence",s.confidence]]))}if(r==="causal-roots"){let e=String(t[0]??"");return oe.findRootCauses(e)}if(r==="causal-simulate"){let e=t[0],n={};if(e instanceof Map)for(let[a,i]of e.entries())n[String(a)]=Number(i);let s=oe.simulate(n);return new Map(Object.entries(s))}if(r==="causal-why"){let e=String(t[0]??""),n=String(t[1]??""),s=ms(e,n);return s===null?null:new Map([["path",s.path],["totalStrength",s.totalStrength],["explanation",s.explanation],["confidence",s.confidence]])}if(r==="causal-summary"){let e=String(t[0]??"");return oe.summarize(e)}return null}function xc(r,t){if(r==="align-add-goal"){let e={};for(let s=0;s<t.length-1;s+=2){let a=String(t[s]).replace(/^:/,"");e[a]=t[s+1]}let n={id:String(e.id??`goal_${Date.now()}`),description:String(e.desc??e.description??""),priority:Number(e.priority??5),measurable:!!(e.measurable??!1),metric:e.metric!==void 0?String(e.metric):void 0,target:e.target!==void 0?Number(e.target):void 0};return ot.addGoal(n),new Map([["id",n.id],["description",n.description],["priority",n.priority],["measurable",n.measurable]])}if(r==="align-add-value"){let e={};for(let s=0;s<t.length-1;s+=2){let a=String(t[s]).replace(/^:/,"");e[a]=t[s+1]}let n={id:String(e.id??`value_${Date.now()}`),name:String(e.name??""),description:String(e.desc??e.description??""),weight:Number(e.weight??.5)};return ot.addValue(n),new Map([["id",n.id],["name",n.name],["description",n.description],["weight",n.weight]])}if(r==="align-score"){let e=t[0],n=(o,u)=>o instanceof Map?o.get(u):o&&typeof o=="object"?o[u]:void 0,s=o=>{let u=n(o,"expectedOutcomes");return u instanceof Map?Object.fromEntries(u):u&&typeof u=="object"?Object.fromEntries(Object.entries(u).map(([f,l])=>[f,Number(l)])):{}},a={id:String(n(e,"id")??""),description:String(n(e,"description")??""),expectedOutcomes:s(e),risks:Array.isArray(n(e,"risks"))?n(e,"risks"):[]},i=ot.score(a);return new Map([["action",e],["goalAlignment",new Map(Object.entries(i.goalAlignment))],["valueAlignment",new Map(Object.entries(i.valueAlignment))],["overallScore",i.overallScore],["conflicts",i.conflicts.map(o=>new Map([["goal1",o.goal1],["goal2",o.goal2],["severity",o.severity]]))],["recommendation",i.recommendation],["reasons",i.reasons]])}if(r==="align-best"){let e=Array.isArray(t[0])?t[0]:[],n=(o,u)=>o instanceof Map?o.get(u):o&&typeof o=="object"?o[u]:void 0,s=o=>{let u=n(o,"expectedOutcomes");return u instanceof Map?Object.fromEntries(u):u&&typeof u=="object"?Object.fromEntries(Object.entries(u).map(([f,l])=>[f,Number(l)])):{}},a=e.map(o=>({id:String(n(o,"id")??""),description:String(n(o,"description")??""),expectedOutcomes:s(o),risks:Array.isArray(n(o,"risks"))?n(o,"risks"):[]}));if(a.length===0)return null;let i=ot.selectBestAligned(a);return new Map([["id",i.id],["description",i.description]])}if(r==="align-conflicts")return ot.detectConflicts().map(n=>new Map([["goal1",n.goal1],["goal2",n.goal2],["description",n.description]]));if(r==="align-plan"){let e=Array.isArray(t[0])?t[0]:[],n=(o,u)=>o instanceof Map?o.get(u):o&&typeof o=="object"?o[u]:void 0,s=o=>{let u=n(o,"expectedOutcomes");return u instanceof Map?Object.fromEntries(u):u&&typeof u=="object"?Object.fromEntries(Object.entries(u).map(([f,l])=>[f,Number(l)])):{}},a=e.map(o=>({id:String(n(o,"id")??""),description:String(n(o,"description")??""),expectedOutcomes:s(o),risks:Array.isArray(n(o,"risks"))?n(o,"risks"):[]})),i=ot.evaluatePlan(a);return new Map([["overallAlignment",i.overallAlignment],["weakLinks",i.weakLinks.map(o=>new Map([["id",o.id],["description",o.description]]))],["summary",i.summary]])}if(r==="align-improve"){let e=t[0],n=(i,o)=>i instanceof Map?i.get(o):i&&typeof i=="object"?i[o]:void 0,s=i=>{let o=n(i,"expectedOutcomes");return o instanceof Map?Object.fromEntries(o):o&&typeof o=="object"?Object.fromEntries(Object.entries(o).map(([u,f])=>[u,Number(f)])):{}},a={id:String(n(e,"id")??""),description:String(n(e,"description")??""),expectedOutcomes:s(e),risks:Array.isArray(n(e,"risks"))?n(e,"risks"):[]};return ot.suggestImprovements(a)}return r==="align-goals"?ot.prioritizeGoals().map(n=>new Map([["id",n.id],["description",n.description],["priority",n.priority],["measurable",n.measurable]])):null}function Ac(r,t){if(r==="predict-linear"){let e=Array.isArray(t[0])?t[0].map(Number):[],n=1;for(let a=1;a<t.length-1;a+=2)String(t[a]).replace(/^:/,"")==="horizon"&&(n=Number(t[a+1]));let s=lt.linearRegression(e,n);return new Map([["value",s.value],["lower",s.lower],["upper",s.upper],["confidence",s.confidence],["method",s.method],["horizon",s.horizon??1]])}if(r==="predict-ma"){let e=Array.isArray(t[0])?t[0].map(Number):[],n=3,s=1;for(let i=1;i<t.length-1;i+=2){let o=String(t[i]).replace(/^:/,"");o==="window"?n=Number(t[i+1]):o==="horizon"&&(s=Number(t[i+1]))}let a=lt.movingAverage(e,n,s);return new Map([["value",a.value],["lower",a.lower],["upper",a.upper],["confidence",a.confidence],["method",a.method],["horizon",a.horizon??1]])}if(r==="predict-exp"){let e=Array.isArray(t[0])?t[0].map(Number):[],n=.3,s=1;for(let i=1;i<t.length-1;i+=2){let o=String(t[i]).replace(/^:/,"");o==="alpha"?n=Number(t[i+1]):o==="horizon"&&(s=Number(t[i+1]))}let a=lt.exponentialSmoothing(e,n,s);return new Map([["value",a.value],["lower",a.lower],["upper",a.upper],["confidence",a.confidence],["method",a.method],["horizon",a.horizon??1]])}if(r==="predict-forecast"){let e=Array.isArray(t[0])?t[0].map(Number):[],n=3;for(let a=1;a<t.length-1;a+=2)String(t[a]).replace(/^:/,"")==="steps"&&(n=Number(t[a+1]));let s=lt.forecastTimeSeries(e,n);return new Map([["predictions",s.predictions.map(a=>new Map([["value",a.value],["lower",a.lower],["upper",a.upper],["confidence",a.confidence],["method",a.method],["horizon",a.horizon??1]]))],["trend",s.trend],["seasonality",s.seasonality??null],["accuracy",s.accuracy??null]])}if(r==="predict-ci"){let e=Array.isArray(t[0])?t[0].map(Number):[],n=.95;for(let a=1;a<t.length-1;a+=2)String(t[a]).replace(/^:/,"")==="confidence"&&(n=Number(t[a+1]));let s=lt.confidenceInterval(e,n);return new Map([["lower",s.lower],["upper",s.upper]])}if(r==="predict-classify"){let e=t[0],n={};e instanceof Map?e.forEach((o,u)=>{n[String(u).replace(/^:/,"")]=Number(o)}):typeof e=="object"&&e!==null&&Object.entries(e).forEach(([o,u])=>{n[o.replace(/^:/,"")]=Number(u)});let a=(Array.isArray(t[1])?t[1]:[]).map(o=>{if(o instanceof Map){let u=o.get("features")??o.get(":features"),f=String(o.get("label")??o.get(":label")??"unknown"),l={};return u instanceof Map&&u.forEach((c,p)=>{l[String(p).replace(/^:/,"")]=Number(c)}),{features:l,label:f}}return{features:{},label:"unknown"}}),i=lt.classify(n,a);return new Map([["classes",i.classes.map(o=>new Map([["label",o.label],["probability",o.probability]]))],["predicted",i.predicted],["confidence",i.confidence]])}if(r==="predict-evaluate"){let e=Array.isArray(t[0])?t[0].map(Number):[],n=Array.isArray(t[1])?t[1].map(Number):[],s=lt.evaluate(e,n);return new Map([["mae",s.mae],["rmse",s.rmse],["mape",s.mape]])}if(r==="predict-trend"){let e=Array.isArray(t[0])?t[0].map(Number):[];return lt.detectTrend(e)}return null}function $c(r,t,e){if(r==="curiosity-score"){let n=String(t[0]??""),s=Array.isArray(t[1])?t[1].map(a=>String(a)):[];return ct.computeCuriosity(n,s)}if(r==="curiosity-next")return ct.selectNextTopic();if(r==="curiosity-explore"){let n=String(t[0]??""),s=t[1],a=o=>{let u=e?e(s,[o]):typeof s=="function"?s(o):null;if(u instanceof Map){let f=Array.isArray(u.get("facts"))?u.get("facts").map(String):[],l=Array.isArray(u.get("questions"))?u.get("questions").map(String):[];return{facts:f,questions:l}}return{facts:[],questions:[]}},i=ct.explore(n,a);return new Map([["topic",i.topic],["discovered",i.discovered],["newQuestions",i.newQuestions],["informationGain",i.informationGain],["surpriseLevel",i.surpriseLevel],["relatedTopics",i.relatedTopics]])}if(r==="curiosity-gaps"){let n=Array.isArray(t[0])?t[0].map(i=>String(i)):[],s=Array.isArray(t[1])?t[1].map(i=>String(i)):[];return ct.identifyGaps(n,s).map(i=>new Map([["topic",i.topic],["unknownAspects",i.unknownAspects],["priority",i.priority],["explorationCost",i.explorationCost],["expectedGain",i.expectedGain]]))}if(r==="curiosity-questions"){let n=String(t[0]??""),s=Array.isArray(t[1])?t[1].map(a=>String(a)):[];return ct.generateQuestions(n,s)}if(r==="curiosity-prioritize"){let n=Array.isArray(t[0])?t[0].map(s=>String(s)):[];return ct.prioritize(n)}if(r==="curiosity-analyze"){let n=ct.analyzeExplorationHistory();return new Map([["totalExplored",n.totalExplored],["avgInfoGain",n.avgInfoGain],["mostSurprising",n.mostSurprising],["recommendations",n.recommendations]])}if(r==="curiosity-state"){let n=ct.getState();return new Map([["explored",Array.from(n.explored)],["frontier",n.frontier],["knowledgeGaps",n.knowledgeGaps.map(s=>new Map([["topic",s.topic],["unknownAspects",s.unknownAspects],["priority",s.priority],["explorationCost",s.explorationCost],["expectedGain",s.expectedGain]]))],["curiosityScore",n.curiosityScore],["explorationHistory",n.explorationHistory.map(s=>new Map([["topic",s.topic],["gain",s.gain],["timestamp",s.timestamp.toISOString()]]))]])}if(r==="wisdom-add-exp"){let n={};for(let a=0;a<t.length-1;a+=2){let i=String(t[a]).replace(/^:/,"");n[i]=t[a+1]}let s=ce.addExperience({situation:String(n.situation??""),action:String(n.action??""),outcome:String(n.outcome??""),lesson:String(n.lesson??""),success:n.success===!0||n.success==="true",importance:typeof n.importance=="number"?n.importance:.5,domain:String(n.domain??"general")});return new Map([["id",s.id],["situation",s.situation],["action",s.action],["outcome",s.outcome],["lesson",s.lesson],["success",s.success],["importance",s.importance],["domain",s.domain],["timestamp",s.timestamp.toISOString()]])}if(r==="wisdom-judge"){let n=String(t[0]??""),s=ce.judge(n);return new Map([["situation",s.situation],["recommendation",s.recommendation],["reasoning",s.reasoning],["relevantExperiences",s.relevantExperiences.map(a=>new Map([["id",a.id],["situation",a.situation],["lesson",a.lesson],["success",a.success],["importance",a.importance],["domain",a.domain]]))],["applicableHeuristics",s.applicableHeuristics.map(a=>new Map([["id",a.id],["rule",a.rule],["confidence",a.confidence],["successCount",a.successCount],["totalCount",a.totalCount],["domain",a.domain]]))],["confidence",s.confidence],["caveats",s.caveats],["alternatives",s.alternatives]])}if(r==="wisdom-heuristics")return ce.getHeuristics().map(n=>new Map([["id",n.id],["rule",n.rule],["confidence",n.confidence],["successCount",n.successCount],["totalCount",n.totalCount],["domain",n.domain],["derivedFrom",n.derivedFrom]]));if(r==="wisdom-extract")return ce.extractHeuristics().map(s=>new Map([["id",s.id],["rule",s.rule],["confidence",s.confidence],["successCount",s.successCount],["totalCount",s.totalCount],["domain",s.domain],["derivedFrom",s.derivedFrom]]));if(r==="wisdom-relevant"){let n=String(t[0]??""),s=typeof t[1]=="number"?t[1]:5;return ce.findRelevantExperiences(n,s).map(a=>new Map([["id",a.id],["situation",a.situation],["action",a.action],["outcome",a.outcome],["lesson",a.lesson],["success",a.success],["importance",a.importance],["domain",a.domain]]))}if(r==="wisdom-lessons"){let n;for(let s=0;s<t.length-1;s+=2)String(t[s]).replace(/^:/,"")==="domain"&&(n=String(t[s+1]));return ce.getLessons(n)}if(r==="wisdom-score")return ce.wisdomScore();if(r==="wisdom-domain"){let n=String(t[0]??"general"),s=ce.summarizeDomain(n);return new Map([["topLessons",s.topLessons],["bestHeuristics",s.bestHeuristics.map(a=>new Map([["id",a.id],["rule",a.rule],["confidence",a.confidence],["successCount",a.successCount],["totalCount",a.totalCount]]))],["successRate",s.successRate]])}if(r==="wisdom-valid?"){let n=t[0];if(!(n instanceof Map))return!1;let s={id:String(n.get("id")??""),situation:String(n.get("situation")??""),action:String(n.get("action")??""),outcome:String(n.get("outcome")??""),lesson:String(n.get("lesson")??""),success:n.get("success")===!0,importance:Number(n.get("importance")??.5),timestamp:new Date(String(n.get("timestamp")??new Date().toISOString())),domain:String(n.get("domain")??"general")};return ce.isStillValid(s)}if(r==="wisdom-similar"){let n=String(t[0]??"");return ce.findSimilarCases(n).map(s=>new Map([["id",s.id],["situation",s.situation],["action",s.action],["outcome",s.outcome],["lesson",s.lesson],["success",s.success],["importance",s.importance],["domain",s.domain]]))}return null}function Ec(r,t,e){if(r==="cf-scenario"){let n={};for(let f=0;f<t.length-1;f+=2){let l=String(t[f]).replace(/^:/,"");n[l]=t[f+1]}let s=String(n.id??`s-${Date.now()}`),a=String(n.name??s),i={};if(n.vars instanceof Map)for(let[f,l]of n.vars)i[String(f).replace(/^:/,"")]=l;else n.vars&&typeof n.vars=="object"&&(i=n.vars);let o=n.outcome??null,u={id:s,name:a,variables:i,outcome:o};return Cn.registerScenario(u),new Map([["id",s],["name",a],["variables",new Map(Object.entries(i))],["outcome",o]])}if(r==="cf-what-if"){let n={},s={};if(t[0]instanceof Map)for(let[u,f]of t[0])n[String(u).replace(/^:/,"")]=f;if(t[1]instanceof Map)for(let[u,f]of t[1])s[String(u).replace(/^:/,"")]=f;let a=t[2],i=u=>e(a,[new Map(Object.entries(u))]),o=Cn.whatIf(n,s,i);return new Map([["id",o.id],["intervention",new Map(Object.entries(o.intervention))],["counterfactualOutcome",o.counterfactualOutcome],["delta",new Map(Object.entries(o.delta))],["probability",o.probability],["explanation",o.explanation]])}if(r==="cf-analyze"){let n=String(t[0]??""),s=[];if(Array.isArray(t[1]))for(let u of t[1]){let f={};if(u instanceof Map)for(let[l,c]of u)f[String(l).replace(/^:/,"")]=c;s.push(f)}let a=t[2],i=u=>e(a,[new Map(Object.entries(u))]),o=Cn.analyze(n,s,i);return new Map([["original",new Map([["id",o.original.id],["name",o.original.name],["outcome",o.original.outcome]])],["counterfactuals",o.counterfactuals.map(u=>new Map([["id",u.id],["probability",u.probability],["counterfactualOutcome",u.counterfactualOutcome],["explanation",u.explanation]]))],["mostLikelyAlternative",new Map([["id",o.mostLikelyAlternative.id],["probability",o.mostLikelyAlternative.probability],["counterfactualOutcome",o.mostLikelyAlternative.counterfactualOutcome],["explanation",o.mostLikelyAlternative.explanation]])],["keyFactors",o.keyFactors],["sensitivity",new Map(Object.entries(o.sensitivity))]])}if(r==="cf-minimal"){let n=String(t[0]??""),s=t[1],a=t[2],i=u=>e(a,[new Map(Object.entries(u))]),o=Cn.findMinimalIntervention(n,s,i);return o===null?null:new Map(Object.entries(o))}if(r==="cf-sensitivity"){let n={},s=t[0];if(s instanceof Map)for(let[u,f]of s)n[String(u).replace(/^:/,"")]=f;else if(s&&typeof s=="object"&&!Array.isArray(s))for(let[u,f]of Object.entries(s))n[String(u).replace(/^:/,"")]=f;let a=t[1],i=u=>{try{return Number(e(a,[u]))}catch{return 0}},o=Cn.sensitivityAnalysis(n,i);return new Map(Object.entries(o))}if(r==="cf-key-factors"){let n=t[0];if(n instanceof Map){let s=n.get("keyFactors");if(Array.isArray(s))return s}return[]}if(r==="cf-best-alt"){let n=t[0];return n instanceof Map?n.get("mostLikelyAlternative")??null:null}if(r==="cf-explain"){let n=t[0];return n instanceof Map?n.get("explanation")??"":""}if(r==="explain-decision"){let n=t[0],s=t[1],a=t[2]!==void 0?String(t[2]):void 0,i={};if(s instanceof Map)for(let[u,f]of s.entries())i[String(u).replace(/^:/,"")]=Number(f);else if(s&&typeof s=="object")for(let[u,f]of Object.entries(s))i[String(u).replace(/^:/,"")]=Number(f);let o=Ce.explain(n,i,a);return new Map([["decision",o.decision],["reasoning",o.reasoning],["features",o.features.map(u=>new Map([["feature",u.feature],["importance",u.importance],["direction",u.direction],["description",u.description]]))],["confidence",o.confidence],["alternatives",o.alternatives.map(u=>new Map([["decision",u.decision],["reason",u.reason],["probability",u.probability]]))],["summary",o.summary],["audience",o.audience]])}if(r==="explain-features"){let n=u=>{let f={};if(u instanceof Map)for(let[l,c]of u.entries())f[String(l).replace(/^:/,"")]=Number(c);else if(u&&typeof u=="object")for(let[l,c]of Object.entries(u))f[String(l).replace(/^:/,"")]=Number(c);return f},s=n(t[0]),a=n(t[1]),i=t[2]!==void 0?n(t[2]):void 0;return Ce.featureImportance(s,a,i).map(u=>new Map([["feature",u.feature],["importance",u.importance],["direction",u.direction],["description",u.description]]))}if(r==="explain-local"){let n=t[0],s=t[1],a=t[2],i={};if(n instanceof Map)for(let[f,l]of n.entries())i[String(f).replace(/^:/,"")]=l;else if(n&&typeof n=="object")for(let[f,l]of Object.entries(n))i[String(f).replace(/^:/,"")]=l;let o=f=>{if(a)try{return e(a,[new Map(Object.entries(f))])}catch{return s}return s},u=Ce.localExplain(i,s,o);return new Map([["input",new Map(Object.entries(u.input))],["output",u.output],["topFactors",u.topFactors.map(f=>new Map([["feature",f.feature],["importance",f.importance],["direction",f.direction],["description",f.description]]))],["counterfactual",u.counterfactual],["confidence",u.confidence]])}if(r==="explain-natural"){let n=t[0],s="technical";for(let l=1;l<t.length-1;l+=2)String(t[l]).replace(/^:/,"")==="audience"&&(s=String(t[l+1]));if(!(n instanceof Map))return"\uC124\uBA85\uC744 \uBCC0\uD658\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4";let a=n.get("features")??[],i=(Array.isArray(a)?a:[]).map(l=>l instanceof Map?{feature:String(l.get("feature")??""),importance:Number(l.get("importance")??0),direction:String(l.get("direction")??"positive"),description:String(l.get("description")??"")}:{feature:"",importance:0,direction:"positive",description:""}),o=n.get("alternatives")??[],u=(Array.isArray(o)?o:[]).map(l=>l instanceof Map?{decision:l.get("decision"),reason:String(l.get("reason")??""),probability:Number(l.get("probability")??0)}:{decision:null,reason:"",probability:0}),f={decision:n.get("decision"),reasoning:n.get("reasoning")??[],features:i,confidence:Number(n.get("confidence")??.5),alternatives:u,summary:String(n.get("summary")??""),audience:n.get("audience")??"technical"};return Ce.toNaturalLanguage(f,s)}if(r==="explain-contrast"){let n=t[0],s=t[1],a=t[2],i={};if(a instanceof Map)for(let[o,u]of a.entries())i[String(o).replace(/^:/,"")]=Number(u);else if(a&&typeof a=="object")for(let[o,u]of Object.entries(a))i[String(o).replace(/^:/,"")]=Number(u);return Ce.contrastiveExplain(n,s,i)}if(r==="explain-rules"){let n=t[0],s=[],a=o=>{let u={};if(o instanceof Map)for(let[f,l]of o.entries())u[String(f).replace(/^:/,"")]=l;else o&&typeof o=="object"&&Object.assign(u,o);return u};if(Array.isArray(n))for(let o of n)o instanceof Map?s.push({input:a(o.get("input")),output:o.get("output")}):o&&typeof o=="object"&&s.push({input:a(o.input),output:o.output});return Ce.extractRules(s).map(o=>new Map([["condition",o.condition],["outcome",o.outcome],["support",o.support]]))}if(r==="explain-top-factors"){let n=t[0],s=3;for(let i=1;i<t.length-1;i+=2)String(t[i]).replace(/^:/,"")==="n"&&(s=Number(t[i+1]));let a=[];return n instanceof Map&&(a=n.get("features")??[]),Array.isArray(a)||(a=[]),a.slice(0,s)}if(r==="explain-summary"){let n=t[0];return n instanceof Map?String(n.get("summary")??""):""}return null}function Mc(r,t){if(r==="wisdom-add-exp"){let e={};for(let s=0;s<t.length-1;s+=2){let a=String(t[s]).replace(/^:/,"");e[a]=t[s+1]}let n=ce.addExperience({situation:String(e.situation??""),action:String(e.action??""),outcome:String(e.outcome??""),lesson:String(e.lesson??""),success:e.success===!0||e.success==="true",importance:typeof e.importance=="number"?e.importance:.5,domain:String(e.domain??"general")});return new Map([["id",n.id],["situation",n.situation],["action",n.action],["outcome",n.outcome],["lesson",n.lesson],["success",n.success],["importance",n.importance],["domain",n.domain],["timestamp",n.timestamp.toISOString()]])}if(r==="wisdom-judge"){let e=String(t[0]??""),n=ce.judge(e);return new Map([["situation",n.situation],["recommendation",n.recommendation],["reasoning",n.reasoning],["relevantExperiences",n.relevantExperiences.map(s=>new Map([["id",s.id],["situation",s.situation],["lesson",s.lesson],["success",s.success],["importance",s.importance],["domain",s.domain]]))],["applicableHeuristics",n.applicableHeuristics.map(s=>new Map([["id",s.id],["rule",s.rule],["confidence",s.confidence],["successCount",s.successCount],["totalCount",s.totalCount],["domain",s.domain]]))],["confidence",n.confidence],["caveats",n.caveats],["alternatives",n.alternatives]])}if(r==="wisdom-heuristics")return ce.getHeuristics().map(e=>new Map([["id",e.id],["rule",e.rule],["confidence",e.confidence],["successCount",e.successCount],["totalCount",e.totalCount],["domain",e.domain],["derivedFrom",e.derivedFrom]]));if(r==="wisdom-extract")return ce.extractHeuristics().map(n=>new Map([["id",n.id],["rule",n.rule],["confidence",n.confidence],["successCount",n.successCount],["totalCount",n.totalCount],["domain",n.domain],["derivedFrom",n.derivedFrom]]));if(r==="wisdom-relevant"){let e=String(t[0]??""),n=typeof t[1]=="number"?t[1]:5;return ce.findRelevantExperiences(e,n).map(s=>new Map([["id",s.id],["situation",s.situation],["action",s.action],["outcome",s.outcome],["lesson",s.lesson],["success",s.success],["importance",s.importance],["domain",s.domain]]))}if(r==="wisdom-lessons"){let e;for(let n=0;n<t.length-1;n+=2)String(t[n]).replace(/^:/,"")==="domain"&&(e=String(t[n+1]));return ce.getLessons(e)}if(r==="wisdom-score")return ce.wisdomScore();if(r==="wisdom-domain"){let e=String(t[0]??"general"),n=ce.summarizeDomain(e);return new Map([["topLessons",n.topLessons],["bestHeuristics",n.bestHeuristics.map(s=>new Map([["id",s.id],["rule",s.rule],["confidence",s.confidence],["successCount",s.successCount],["totalCount",s.totalCount]]))],["successRate",n.successRate]])}if(r==="wisdom-valid?"){let e=t[0];if(!(e instanceof Map))return!1;let n={id:String(e.get("id")??""),situation:String(e.get("situation")??""),action:String(e.get("action")??""),outcome:String(e.get("outcome")??""),lesson:String(e.get("lesson")??""),success:e.get("success")===!0,importance:Number(e.get("importance")??.5),timestamp:new Date(String(e.get("timestamp")??new Date().toISOString())),domain:String(e.get("domain")??"general")};return ce.isStillValid(n)}if(r==="wisdom-similar"){let e=String(t[0]??"");return ce.findSimilarCases(e).map(n=>new Map([["id",n.id],["situation",n.situation],["action",n.action],["outcome",n.outcome],["lesson",n.lesson],["success",n.success],["importance",n.importance],["domain",n.domain]]))}return null}function Rc(r,t,e){if(r==="explain-decision"){let n=t[0],s=t[1],a=t[2]!==void 0?String(t[2]):void 0,i={};if(s instanceof Map)for(let[u,f]of s.entries())i[String(u).replace(/^:/,"")]=Number(f);else if(s&&typeof s=="object")for(let[u,f]of Object.entries(s))i[String(u).replace(/^:/,"")]=Number(f);let o=Ce.explain(n,i,a);return new Map([["decision",o.decision],["reasoning",o.reasoning],["features",o.features.map(u=>new Map([["feature",u.feature],["importance",u.importance],["direction",u.direction],["description",u.description]]))],["confidence",o.confidence],["alternatives",o.alternatives.map(u=>new Map([["decision",u.decision],["reason",u.reason],["probability",u.probability]]))],["summary",o.summary],["audience",o.audience]])}if(r==="explain-features"){let n=a=>{let i={};if(a instanceof Map)for(let[o,u]of a.entries())i[String(o).replace(/^:/,"")]=Number(u);else if(a&&typeof a=="object")for(let[o,u]of Object.entries(a))i[String(o).replace(/^:/,"")]=Number(u);return i};return Ce.featureImportance(n(t[0]),n(t[1]),t[2]!==void 0?n(t[2]):void 0).map(a=>new Map([["feature",a.feature],["importance",a.importance],["direction",a.direction],["description",a.description]]))}if(r==="explain-local"){let n=t[0],s=t[1],a=t[2],i={};if(n instanceof Map)for(let[f,l]of n.entries())i[String(f).replace(/^:/,"")]=l;else if(n&&typeof n=="object")for(let[f,l]of Object.entries(n))i[String(f).replace(/^:/,"")]=l;let o=f=>{if(a&&e)try{return e(a,[new Map(Object.entries(f))])}catch{return s}return s},u=Ce.localExplain(i,s,o);return new Map([["input",new Map(Object.entries(u.input))],["output",u.output],["topFactors",u.topFactors.map(f=>new Map([["feature",f.feature],["importance",f.importance],["direction",f.direction],["description",f.description]]))],["counterfactual",u.counterfactual],["confidence",u.confidence]])}if(r==="explain-natural"){let n=t[0],s="technical";for(let l=1;l<t.length-1;l+=2)String(t[l]).replace(/^:/,"")==="audience"&&(s=String(t[l+1]));if(!(n instanceof Map))return"\uC124\uBA85\uC744 \uBCC0\uD658\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4";let a=n.get("features")??[],i=(Array.isArray(a)?a:[]).map(l=>l instanceof Map?{feature:String(l.get("feature")??""),importance:Number(l.get("importance")??0),direction:String(l.get("direction")??"positive"),description:String(l.get("description")??"")}:{feature:"",importance:0,direction:"positive",description:""}),o=n.get("alternatives")??[],u=(Array.isArray(o)?o:[]).map(l=>l instanceof Map?{decision:l.get("decision"),reason:String(l.get("reason")??""),probability:Number(l.get("probability")??0)}:{decision:null,reason:"",probability:0}),f={decision:n.get("decision"),reasoning:n.get("reasoning")??[],features:i,confidence:Number(n.get("confidence")??.5),alternatives:u,summary:String(n.get("summary")??""),audience:n.get("audience")??"technical"};return Ce.toNaturalLanguage(f,s)}if(r==="explain-contrast"){let n={},s=t[2];if(s instanceof Map)for(let[a,i]of s.entries())n[String(a).replace(/^:/,"")]=Number(i);else if(s&&typeof s=="object")for(let[a,i]of Object.entries(s))n[String(a).replace(/^:/,"")]=Number(i);return Ce.contrastiveExplain(t[0],t[1],n)}if(r==="explain-rules"){let n=[],s=a=>{let i={};if(a instanceof Map)for(let[o,u]of a.entries())i[String(o).replace(/^:/,"")]=u;else a&&typeof a=="object"&&Object.assign(i,a);return i};if(Array.isArray(t[0]))for(let a of t[0])a instanceof Map?n.push({input:s(a.get("input")),output:a.get("output")}):a&&typeof a=="object"&&n.push({input:s(a.input),output:a.output});return Ce.extractRules(n).map(a=>new Map([["condition",a.condition],["outcome",a.outcome],["support",a.support]]))}if(r==="explain-top-factors"){let n=3;for(let i=1;i<t.length-1;i+=2)String(t[i]).replace(/^:/,"")==="n"&&(n=Number(t[i+1]));let s=t[0],a=[];return s instanceof Map&&(a=s.get("features")??[]),Array.isArray(a)||(a=[]),a.slice(0,n)}if(r==="explain-summary"){let n=t[0];return n instanceof Map?String(n.get("summary")??""):""}return null}function Tc(r,t){if(r==="world-add-entity"){let e={};for(let i=0;i<t.length-1;i+=2)e[String(t[i]).replace(/^:/,"")]=t[i+1];let n=e.props??e.properties??{},s=n instanceof Map?Object.fromEntries(n.entries()):typeof n=="object"&&n!==null?n:{},a=ve.addEntity({id:String(e.id??`entity-${Date.now()}`),type:String(e.type??"unknown"),confidence:typeof e.confidence=="number"?e.confidence:1,properties:s});return new Map([["id",a.id],["type",a.type],["properties",new Map(Object.entries(a.properties))],["confidence",a.confidence],["lastUpdated",a.lastUpdated.toISOString()]])}if(r==="world-update-entity"){let e=t[1]??{},n=e instanceof Map?Object.fromEntries(e.entries()):typeof e=="object"&&e!==null?e:{},s=ve.updateEntity(String(t[0]??""),n);return s?new Map([["id",s.id],["type",s.type],["properties",new Map(Object.entries(s.properties))],["confidence",s.confidence],["lastUpdated",s.lastUpdated.toISOString()]]):null}if(r==="world-get-entity"){let e=ve.getEntity(String(t[0]??""));return e?new Map([["id",e.id],["type",e.type],["properties",new Map(Object.entries(e.properties))],["confidence",e.confidence],["lastUpdated",e.lastUpdated.toISOString()]]):null}if(r==="world-remove-entity")return ve.removeEntity(String(t[0]??""));if(r==="world-add-relation"){let e={};for(let s=0;s<t.length-1;s+=2)e[String(t[s]).replace(/^:/,"")]=t[s+1];let n=ve.addRelation({from:String(e.from??""),to:String(e.to??""),type:String(e.type??"related"),strength:typeof e.strength=="number"?e.strength:1,bidirectional:e.bidirectional===!0});return new Map([["id",n.id],["from",n.from],["to",n.to],["type",n.type],["strength",n.strength],["bidirectional",n.bidirectional]])}if(r==="world-get-relations")return ve.getRelations(String(t[0]??"")).map(e=>new Map([["id",e.id],["from",e.from],["to",e.to],["type",e.type],["strength",e.strength],["bidirectional",e.bidirectional]]));if(r==="world-find-path")return ve.findPath(String(t[0]??""),String(t[1]??""));if(r==="world-set-fact")return ve.setFact(String(t[0]??""),t[1]),null;if(r==="world-get-fact")return ve.getFact(String(t[0]??""));if(r==="world-add-rule"){let e={};for(let s=0;s<t.length-1;s+=2)e[String(t[s]).replace(/^:/,"")]=t[s+1];let n=ve.addRule({condition:String(e.condition??""),consequence:String(e.consequence??""),confidence:typeof e.confidence=="number"?e.confidence:.8});return new Map([["id",n.id],["condition",n.condition],["consequence",n.consequence],["confidence",n.confidence]])}if(r==="world-apply-rules")return ve.applyRules().map(e=>new Map([["type",e.type],["source",e.source],["timestamp",e.timestamp.toISOString()]]));if(r==="world-query"){let e={};for(let n=0;n<t.length-1;n+=2)e[String(t[n]).replace(/^:/,"")]=t[n+1];return ve.query(e.type!==void 0?String(e.type):void 0,e["min-confidence"]!==void 0?Number(e["min-confidence"]):void 0).map(n=>new Map([["id",n.id],["type",n.type],["properties",new Map(Object.entries(n.properties))],["confidence",n.confidence],["lastUpdated",n.lastUpdated.toISOString()]]))}if(r==="world-snapshot"){let e=ve.snapshot();return new Map([["entityCount",e.entities.size],["relationCount",e.relations.length],["factCount",e.facts.size],["ruleCount",e.rules.length],["version",e.version],["timestamp",e.timestamp.toISOString()]])}if(r==="world-summarize")return ve.summarize();if(r==="world-history")return ve.getHistory().map(e=>new Map([["type",e.type],["source",e.source],["timestamp",e.timestamp.toISOString()]]))}be();ke();function si(r,t){if(r===t)return!0;if(r==null||t==null)return!1;if(Array.isArray(r)&&Array.isArray(t)){if(r.length!==t.length)return!1;for(let e=0;e<r.length;e++)if(!si(r[e],t[e]))return!1;return!0}if(typeof r=="object"&&typeof t=="object"&&!Array.isArray(r)&&!Array.isArray(t)){let e=Object.keys(r),n=Object.keys(t);if(e.length!==n.length)return!1;for(let s of e)if(!si(r[s],t[s]))return!1;return!0}return!1}function Et(r){return r==null?"nil":Array.isArray(r)?"array":r instanceof Map?"map":typeof r=="object"&&(r.kind==="function-value"||r.kind==="closure"||r.kind==="builtin-fn")?"function":typeof r=="object"?"map":typeof r}var Lf=!1;function hs(r,t){let e=r;for(;e!=null;){let n=e.vars;if(Array.isArray(n))for(let s=0;s<n.length;s++){let a=n[s];if(Array.isArray(a)&&a[0]===t)return a[1]}e=e.parent}return null}function Cc(r,t,e){return{vars:[[t,e],...r.vars||[]],parent:r.parent}}function _r(r){return r?r.kind==="block"&&r.type==="Array"?r.fields instanceof Map?r.fields.get("items")??[]:r.fields&&Array.isArray(r.fields.items)?r.fields.items:r.items??[]:Array.isArray(r.items)?r.items:Array.isArray(r)?r:[]:[]}function Nc(r){let t=_r(r),e=[];for(let n of t){if(n.kind==="literal"&&n.value==="&")break;n.kind==="variable"?e.push(n.name):n.kind==="literal"&&e.push(String(n.value))}return e}function Oc(r,t){let e=t[0],n=t[1],s=t[2];switch(normalizedOp){case"+":{let a=t.findIndex(i=>i==null||typeof i!="number");if(a>=0){let i=Et(t[a]),o=i==="nil"?"(nil? \uAC12\uC778\uC9C0 \uD655\uC778 \uD6C4 \uAE30\uBCF8\uAC12\uC744 \uC0AC\uC6A9\uD558\uC138\uC694)":"(str-to-num \uB4F1\uC73C\uB85C \uBCC0\uD658\uD558\uC138\uC694)";throw new Error(`[E_TYPE_MISMATCH] +: \uC778\uC790 ${a+1}\uBC88\uC5D0 ${i} \uC804\uB2EC\uB428 \u2014 number \uD544\uC694 ${o}`)}return t.reduce((i,o)=>i+o,0)}case"-":{let a=t.findIndex(i=>i==null||typeof i!="number");if(a>=0){let i=Et(t[a]),o=i==="nil"?"(nil? \uD655\uC778 \uD6C4 \uAE30\uBCF8\uAC12 \uC0AC\uC6A9)":"(str-to-num \uBCC0\uD658 \uD655\uC778)";throw new Error(`[E_TYPE_MISMATCH] -: \uC778\uC790 ${a+1}\uBC88\uC5D0 ${i} \uC804\uB2EC\uB428 \u2014 number \uD544\uC694 ${o}`)}return t.length===1?-e:t.reduce((i,o)=>i-o)}case"*":{let a=t.findIndex(i=>i==null||typeof i!="number");if(a>=0){let i=Et(t[a]),o=i==="nil"?"(nil? \uD655\uC778 \uD6C4 \uAE30\uBCF8\uAC12 \uC0AC\uC6A9)":"(str-to-num \uBCC0\uD658 \uD655\uC778)";throw new Error(`[E_TYPE_MISMATCH] *: \uC778\uC790 ${a+1}\uBC88\uC5D0 ${i} \uC804\uB2EC\uB428 \u2014 number \uD544\uC694 ${o}`)}return t.reduce((i,o)=>i*o,1)}case"/":{let a=t.findIndex(i=>i==null||typeof i!="number");if(a>=0){let i=Et(t[a]),o=i==="nil"?"(nil? \uD655\uC778 \uD6C4 \uAE30\uBCF8\uAC12 \uC0AC\uC6A9)":"(str-to-num \uBCC0\uD658 \uD655\uC778)";throw new Error(`[E_TYPE_MISMATCH] /: \uC778\uC790 ${a+1}\uBC88\uC5D0 ${i} \uC804\uB2EC\uB428 \u2014 number \uD544\uC694 ${o}`)}return t.length===1?1/e:t.reduce((i,o)=>i/o)}case"%":return e%n;case"=":{let a=e==null,i=n==null;return a&&i?!0:a||i?!1:e===n}case"!=":case"not=":return e!==n;case"<":return e<n;case">":return e>n;case"<=":return e<=n;case">=":return e>=n;case"not":return!e;case"nil?":case"null?":return e==null;case"empty?":return e==null?!0:typeof e=="string"||Array.isArray(e)?e.length===0:typeof e=="object"?Object.keys(e).length===0:!1;case"has-key?":{if(e==null||typeof e!="object"||Array.isArray(e))return!1;let a=typeof n=="string"&&n.startsWith(":")?n.slice(1):n;return Object.prototype.hasOwnProperty.call(e,a)}case"nil-or-empty?":return e==null||e&&e.length===0;case"true?":return e===!0;case"false?":return e===!1;case"and":return!!(e&&n);case"or":{let a=i=>i==null||i===!1;return a(e)?(a(n),n):e}case"length":return Array.isArray(e)||typeof e=="string"?e.length:0;case"get":{if(e==null&&process.env.FL_STRICT==="1")throw new ue(de.TYPE_NIL,`(get nil ${typeof n=="string"?'"'+n+'"':String(n)}) \u2014 cannot access key on nil. Use (get-or coll key default).`,{fn:"get",arg:0,expected:"non-nil",got:"nil"});let a=n;a!==null&&typeof a=="object"&&a.kind==="keyword"&&(a=a.name);let i=s!==void 0?s:null;if(Array.isArray(e))return e[a]!==void 0?e[a]:i;if(e instanceof Map)return e.has(String(a).replace(/^:/,""))?e.get(String(a).replace(/^:/,"")):i;if(e!==null&&typeof e=="object"){let o=typeof a=="string"&&a.startsWith(":")?a.slice(1):String(a);return e[o]!==void 0?e[o]:typeof a=="string"&&e[a]!==void 0?e[a]:i}return i}case"get-in":{if(!Array.isArray(n))throw new Error("get-in: \uB450 \uBC88\uC9F8 \uC778\uC790\uB294 \uD0A4 \uBC30\uC5F4\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4");let a=s!==void 0?s:null,i=e;for(let o of n){if(i==null)return a;let u=typeof o=="string"&&o.startsWith(":")?o.slice(1):o;if(Array.isArray(i))i=i[u]!==void 0?i[u]:null;else if(i!==null&&typeof i=="object")i=i[u]!==void 0?i[u]:null;else return a}return i!==void 0?i:a}case"append":return Array.isArray(e)&&Array.isArray(n)?[...e,...n]:Array.isArray(e)?[...e,n]:[e,n];case"slice":return Array.isArray(e)||typeof e=="string"?e.slice(n,s):[];case"str":case"concat":return t.map(a=>{if(a==null)return"null";if(typeof a=="string"||typeof a=="number"||typeof a=="boolean")return String(a);let i=typeof a=="object"&&!Array.isArray(a)&&!(a instanceof Map)&&a?.kind!=="function-value"&&a?.kind!=="closure";if(Array.isArray(a)||i)try{return JSON.stringify(a)}catch{return toDisplay(a)}return toDisplay(a)}).join("");case"str-to-num":{let a=parseFloat(String(e));return isNaN(a)?null:a}case"num-to-str":return String(e??"");case"replace":return typeof e=="string"?e.split(String(n)).join(String(s)):e;case"type-of":return e==null?"nil":Array.isArray(e)?"array":e instanceof Map||typeof e=="object"&&e!==null&&!Array.isArray(e)&&typeof e!="function"?"map":typeof e=="function"||e?.kind==="function-value"||e?.kind==="closure"||e?.kind==="builtin-fn"?"function":typeof e;case"print":return process.stdout.write(t.map(a=>toDisplay(a)).join("")),null;case"println":return process.stdout.write(t.map(a=>a===null?"null":String(a)).join(" ")+`
95
+ `),null;case"substring":return typeof e=="string"?e.slice(Number(n),s!==void 0?Number(s):void 0):"";case"char-at":return typeof e=="string"?e[Number(n)]??"":"";case"index-of":return typeof e=="string"&&typeof n=="string"?e.indexOf(n):-1;case"split":return typeof e=="string"?e.split(String(n??"")):[];case"trim":return typeof e=="string"?e.trim():"";case"upper-case":return typeof e=="string"?e.toUpperCase():e;case"lower-case":return typeof e=="string"?e.toLowerCase():e;case"strlen":return typeof e=="string"?e.length:0;case"includes?":case"includes-item":return typeof e=="string"?e.includes(String(n)):Array.isArray(e)?e.includes(n):!1;case"starts-with?":return typeof e=="string"?e.startsWith(String(n)):!1;case"ends-with?":return typeof e=="string"?e.endsWith(String(n)):!1;case"empty?":return e==null?!0:typeof e=="string"||Array.isArray(e)?e.length===0:typeof e=="object"?Object.keys(e).length===0:!1;case"first":return Array.isArray(e)&&e[0]!==void 0?e[0]:null;case"second":return Array.isArray(e)&&e[1]!==void 0?e[1]:null;case"last":return Array.isArray(e)&&e.length>0?e[e.length-1]:null;case"rest":return Array.isArray(e)?e.slice(1):[];case"nth":return Array.isArray(e)&&args[1]!==void 0&&e[Number(args[1])]!==void 0?e[Number(args[1])]:null;case"not=":return args[0]!==args[1];case"get-or":{let a=n;if(a!==null&&typeof a=="object"&&a.kind==="keyword"&&(a=a.name),e==null)return s!==void 0?s:null;if(Array.isArray(e))return e[a]!==void 0?e[a]:s!==void 0?s:null;if(e instanceof Map){let i=e.get(String(a).replace(/^:/,""));return i===void 0?s!==void 0?s:null:i}if(typeof e=="object"){let i=typeof a=="string"&&a.startsWith(":")?a.slice(1):String(a);return e[i]!==void 0?e[i]:typeof a=="string"&&e[a]!==void 0?e[a]:s!==void 0?s:null}return s!==void 0?s:null}case"first-or":case"first_or":return Array.isArray(e)&&e.length>0&&e[0]!==void 0?e[0]:n!==void 0?n:null;case"last-or":case"last_or":return Array.isArray(e)&&e.length>0?e[e.length-1]:n!==void 0?n:null;case"cons":return[e,...Array.isArray(n)?n:[n]];case"reverse":return Array.isArray(e)?[...e].reverse():[];case"sort":return Array.isArray(e)?[...e].sort((a,i)=>typeof a=="number"&&typeof i=="number"?a-i:String(a).localeCompare(String(i))):e;case"keys":return e instanceof Map?Array.from(e.keys()):e&&typeof e=="object"&&!Array.isArray(e)?Object.keys(e):[];case"values":return e instanceof Map?Array.from(e.values()):e&&typeof e=="object"&&!Array.isArray(e)?Object.values(e):[];case"map-entries":case"map_entries":return e instanceof Map?[...e.entries()]:e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e):[];case"floor":return Math.floor(e);case"ceil":return Math.ceil(e);case"round":return Math.round(e);case"math-abs":case"math_abs":case"abs":return Math.abs(e);case"max":return Math.max(...t.filter(a=>typeof a=="number"));case"min":return Math.min(...t.filter(a=>typeof a=="number"));case"pow":return Math.pow(e,n);case"math-sqrt":case"math_sqrt":case"sqrt":return Math.sqrt(e);case"mod":return e%n;case"closure?":return e!=null&&typeof e=="object"&&e.kind==="closure";case"block-items":return _r(e);case"read-file":try{return require("fs").readFileSync(String(e),"utf-8")}catch{return null}case"write-file":try{return require("fs").writeFileSync(String(e),String(n??"")),!0}catch{return!1}case"file-exists?":try{return require("fs").existsSync(String(e))}catch{return!1}case"fl-interp":return ne(e,n);case"lex":try{return W(String(e??""))}catch{return[]}case"parse":try{return H(Array.isArray(e)?e:[])}catch{return[]}case"fl-parse":try{return H(W(String(e??"")))}catch{return[]}case"fl-fix-env":{let a=e;if(!a||!Array.isArray(a.vars))return a;for(let i of a.vars)Array.isArray(i)&&i[1]&&typeof i[1]=="object"&&i[1].kind==="closure"&&(i[1]["closure-env"]=a);return a}case"fl-env-get":return hs(e,String(n??""));case"fl-exec-op":return Oc(String(e??""),Array.isArray(n)?n:[]);case"fl-special-op?":{let a=String(e??"");return["if","let","do","begin","fn","and","or","not","null?","match","call","export","define","set!"].includes(a)?a:null}case"load":{let a=String(e??""),i=require("fs"),o=require("path");try{let u=o.resolve(process.cwd(),a),f=i.readFileSync(u,"utf-8"),{lex:l}=(be(),_e(cn)),{parse:c}=(ke(),_e(fn)),p=l(f,u),m=c(p);interp.callStack&&interp.callStack.push({fn:`(load "${a}")`,line:expr.line});try{for(let d of m)interp.eval(d)}finally{interp.callStack&&interp.callStack.pop()}return null}catch(u){throw new Error(`load failed: '${a}': ${u.message}`)}}case"file-mkdir":case"file_mkdir":{let a=String(e??""),i=require("fs");try{return i.mkdirSync(a,{recursive:!0}),!0}catch{return!1}}case"file-append":case"file_append":{let a=String(e??""),i=String(n??""),o=require("fs");try{return o.appendFileSync(a,i),!0}catch{return!1}}case"http-get":case"http_get":{let a=String(e??"");try{let{execSync:i}=require("child_process"),{writeFileSync:o,unlinkSync:u}=require("fs"),{randomUUID:f}=require("crypto"),l=`/tmp/fl-http-${f()}.js`,c=`process.env.FL_URL=${JSON.stringify(a)};
96
+ const u=require('url').parse(process.env.FL_URL);
97
+ const mod=u.protocol==='https:'?require('https'):require('http');
98
+ const chunks=[];
99
+ const req=mod.request({hostname:u.hostname,port:u.port||undefined,path:u.path||'/',method:'GET'},res=>{
100
+ res.on('data',d=>chunks.push(d));
101
+ res.on('end',()=>{process.stdout.write(JSON.stringify({s:res.statusCode,b:Buffer.concat(chunks).toString()}))});
102
+ });
103
+ req.on('error',e=>process.stdout.write(JSON.stringify({s:0,b:'',e:e.message})));
104
+ req.setTimeout(10000,()=>{req.destroy();process.stdout.write(JSON.stringify({s:0,b:'',e:'timeout'}))});
105
+ req.end();`;o(l,c,"utf-8");let p=i(`node ${l}`,{encoding:"utf-8",timeout:15e3});try{u(l)}catch{}let m=JSON.parse(p);return{status:m.s||0,body:m.b||"",headers:{}}}catch(i){return{status:0,body:"",headers:{},error:i.message}}}case"atom":return{value:e!==void 0?e:null};case"deref":return e&&typeof e=="object"&&"value"in e?e.value:e;case"reset!":return e&&typeof e=="object"&&"value"in e&&(e.value=n),n;case"swap!":{if(e&&typeof e=="object"&&"value"in e&&n){let a=args.slice(2),i=gs(n,[e.value,...a]);return e.value=i,i}return null}default:return null}}var Bf=new Set(["if","let","do","begin","fn","and","or","not","null?","match","call","export","define","set!"]);function gs(r,t){if(!r||r.kind!=="closure")return null;let e=r.params||[],n=r["closure-env"]??{vars:[],parent:null},s={vars:[],parent:n};for(let o=0;o<e.length;o++)s=Cc(s,e[o],o<t.length?t[o]:null);let a=r.body||[],i=null;for(let o of a)i=ne(o,s);return i}function ne(r,t){if(r==null)return null;let e=r.kind;if(e==="literal")return r.value;if(e==="variable")return hs(t,r.name);if(e==="array")return(r.items||[]).map(s=>ne(s,t));if(e==="block"){if(r.type==="Array")return _r(r).map(s=>ne(s,t));if(r.type==="Map"){let n={};if(r.fields instanceof Map)for(let[s,a]of r.fields)n[s]=ne(a,t);return n}if(r.type==="FUNC"){let n=r.fields,s=null,a=null;return n instanceof Map?(s=n.get("params"),a=n.get("body")):n&&(s=n.params,a=n.body),{kind:"closure",params:Nc(s),body:[a],"closure-env":t}}return null}return e==="sexpr"?Df(r.op,r.args||[],t):null}function Df(r,t,e){if(typeof r!="string"){let n=ne(r,e),s=t.map(a=>ne(a,e));return n&&n.kind==="closure"?gs(n,s):null}if(!Bf.has(r)){let n=t.map(a=>ne(a,e)),s=hs(e,r);return s&&s.kind==="closure"?gs(s,n):Oc(r,n)}switch(normalizedOp){case"if":return ne(t[0],e)?ne(t[1],e):t.length>=3?ne(t[2],e):null;case"let":{let n=_r(t[0]),s=e;for(let i of n){let o=_r(i);if(o.length<2)continue;let u=o[0],f=u.kind==="variable"?u.name:String(u.value??""),l=ne(o[1],s);s=Cc(s,f,l)}let a=null;for(let i=1;i<t.length;i++)a=ne(t[i],s);return a}case"fn":return{kind:"closure",params:Nc(t[0]),body:t.slice(1),"closure-env":e};case"do":case"begin":{let n=null;for(let s of t)n=ne(s,e);return n}case"and":{for(let n of t)if(!ne(n,e))return!1;return!0}case"or":{let n=a=>a==null||a===!1,s=null;for(let a of t)if(s=ne(a,e),!n(s))return s;return s}case"not":return!ne(t[0],e);case"null?":{let n=ne(t[0],e);return n==null}case"call":{let n=ne(t[0],e),s=n&&n.kind==="closure"?n:typeof n=="string"?hs(e,n):null;if(!s||s.kind!=="closure")return null;let a;if(t.length===2){let i=ne(t[1],e);a=Array.isArray(i)?i:[i]}else a=t.slice(1).map(i=>ne(i,e));return gs(s,a)}case"match":{let n=ne(t[0],e);for(let s=1;s<t.length;s++){let a=t[s],i=a.op,o=(a.args||[])[0],u=!1;if(i==="_")u=!0;else if(i==="null")u=n==null;else if(i==="true")u=n===!0;else if(i==="false")u=n===!1;else{let f=parseFloat(i);u=n===i||!isNaN(f)&&n===f}if(u)return ne(o,e)}return null}case"export":return null;case"define":case"set!":{if(t.length>=2){let n=t[0],s=n.kind==="variable"?n.name:String(n.value??""),a=ne(t[1],e);return e&&Array.isArray(e.vars)&&e.vars.unshift([s,a]),a}return null}default:return null}}function Fc(r){return{kind:"cache",maxSize:r,map:new Map,hits:0,misses:0}}function qf(r){if(r.map.size>=r.maxSize){let t=r.map.keys().next().value;t!==void 0&&r.map.delete(t)}}var On=Fc(1e4);function Fn(r,t,e,n){let s=t.replace(/_/g,"-");s!==t&&t!=="server_start"&&!process.env.FL_NO_DEPRECATION_WARN&&console.warn(`\u26A0\uFE0F [FreeLang v11.5.1] ${t}\uC740 deprecated\uC785\uB2C8\uB2E4. ${s}\uC744 \uC0AC\uC6A9\uD558\uC138\uC694.`);let a=l=>r.eval(l),i=(l,c)=>r.callFunction(l,c),o=(l,c)=>r.callUserFunction(l,c),u=(l,c)=>{if(typeof l=="string")try{return r.callUserFunction(l,c)}catch(p){if(p?.message?.includes("\uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4")||p?.message?.includes("not found")||p?.message?.includes("Function not found"))return Fn(r,l,c,n);throw p}return l?.kind==="builtin-fn"?Fn(r,l.name,c,n):l?.kind==="function-value"||l?.kind==="async-function-value"?r.callFunctionValue(l,c):typeof l?.body=="function"?l.body(...c):l?.params!==void 0&&l?.body!==void 0?r.callUserFunction(l.name??l.id,c):typeof l=="function"?l(...c):r.callFunctionValue(l,c)},f=l=>r.toDisplayString(l);switch(s){case"atom":return{value:e[0]!==void 0?e[0]:null};case"deref":{let l=e[0];return l&&typeof l=="object"&&"value"in l?l.value:l}case"reset!":{let l=e[0];return l&&typeof l=="object"&&"value"in l&&(l.value=e[1]),e[1]}case"swap!":{let l=e[0],c=e[1],p=e.slice(2);if(l&&typeof l=="object"&&"value"in l&&c){let m=u(c,[l.value,...p]);return l.value=m,m}return null}case"load":{let l=String(e[0]??""),c=e[1]!=null?String(e[1]):null,p=require("fs"),m=require("path");try{let d=m.resolve(process.cwd(),l),g=process.argv.includes("--watch")||process.argv.includes("-w")||process.argv.includes("watch");if(!Lf&&!g&&!c){if(r.__loadCache||(r.__loadCache=new Set),r.__loadCache.has(d))return null;r.__loadCache.add(d)}let h=p.readFileSync(d,"utf-8"),{lex:y}=(be(),_e(cn)),{parse:k}=(ke(),_e(fn)),v=y(h,d),$=k(v),M=r.context,O=c&&M?.functions instanceof Map?new Set(M.functions.keys()):new Set;if(r.interpret($),c&&M?.functions instanceof Map){let C=[];for(let[P,_]of M.functions.entries())O.has(P)||C.push([`${c}/${P}`,_]);for(let[P,_]of C)M.functions.set(P,_)}return null}catch(d){throw new Error(`load failed: '${l}': ${d.message}`)}}case"cli-args":{let l=process.argv.slice(2);return l[0]==="run"||l[0]==="debug"?l.slice(2):l}case"shell-exec":{let{execSync:l}=require("child_process"),c=String(e[0]??"");try{return l(c,{encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch{return null}}case"shell-exec-result":{let{spawnSync:l}=require("child_process"),c=String(e[0]??""),p=l("sh",["-c",c],{encoding:"utf-8"});return{stdout:p.stdout??"",stderr:p.stderr??"",exit:p.status??-1,ok:(p.status??-1)===0}}case"require":{let l=String(e[0]??""),c=require("fs"),p=require("path");try{let m=l;!m.endsWith(".fl")&&!m.endsWith(".js")&&(m=m+".fl");let d=p.isAbsolute(m)?m:p.resolve(process.cwd(),m);if(MODULE_CACHE.has(d))return MODULE_CACHE.get(d);let g=c.readFileSync(d,"utf-8"),{lex:h}=(be(),_e(cn)),{parse:y}=(ke(),_e(fn)),k=h(g,d),v=y(k),$=r.interpret(v);return MODULE_CACHE.set(d,$),$}catch(m){throw new Error(`require failed: '${l}': ${m.message}`)}}case"net-sendrecv":{let l=String(e[0]??"localhost"),c=Number(e[1]??27017),p=String(e[2]??""),m=Number(e[3]??1e4),{spawnSync:d}=require("child_process"),g=`
106
+ const net = require('net');
107
+ const req = JSON.parse(require('fs').readFileSync(0, 'utf-8'));
108
+ const { host, port, data, timeout } = req;
109
+ const buf = Buffer.from(data, 'hex');
110
+ const sock = net.createConnection({ host, port });
111
+ let chunks = [];
112
+ let done = false;
113
+
114
+ sock.on('connect', () => { sock.write(buf); });
115
+
116
+ // Frame by messageLength: MongoDB Wire Protocol messages start with 4-byte length (little-endian)
117
+ sock.on('data', c => {
118
+ chunks.push(c);
119
+ if (!done && chunks.length > 0) {
120
+ const total = Buffer.concat(chunks);
121
+ if (total.length >= 4) {
122
+ const msgLen = total.readInt32LE(0);
123
+ if (total.length >= msgLen) {
124
+ done = true;
125
+ sock.destroy();
126
+ process.stdout.write(total.slice(0, msgLen).toString('hex'));
127
+ process.exit(0);
128
+ }
129
+ }
130
+ }
131
+ });
132
+
133
+ sock.on('end', () => {
134
+ if (!done && chunks.length > 0) {
135
+ process.stdout.write(Buffer.concat(chunks).toString('hex'));
136
+ }
137
+ process.exit(0);
138
+ });
139
+
140
+ sock.on('error', (e) => { process.exit(1); });
141
+
142
+ sock.setTimeout(timeout, () => {
143
+ if (!done) {
144
+ sock.destroy();
145
+ if (chunks.length > 0) {
146
+ process.stdout.write(Buffer.concat(chunks).toString('hex'));
147
+ }
148
+ process.exit(0);
149
+ }
150
+ });
151
+ `,h=JSON.stringify({host:l,port:c,data:p,timeout:m});try{let y=d(process.execPath,["-e",g],{input:h,timeout:m+1e3,encoding:"utf-8"});if(y.error||y.status!==0)return null;let k=(y.stdout??"").trim();return k.length>0?k:null}catch{return null}}case"net-connect":{let l=String(e[0]??"localhost"),c=Number(e[1]??27017),p=Number(e[2]??5e3),{spawnSync:m}=require("child_process"),d=`
152
+ const net = require('net');
153
+ const req = JSON.parse(require('fs').readFileSync(0, 'utf-8'));
154
+ const sock = net.createConnection({ host: req.host, port: req.port });
155
+ sock.on('connect', () => { sock.destroy(); process.stdout.write('ok'); process.exit(0); });
156
+ sock.on('error', () => { process.exit(1); });
157
+ sock.setTimeout(req.timeout, () => { sock.destroy(); process.exit(1); });
158
+ `;try{let g=m(process.execPath,["-e",d],{input:JSON.stringify({host:l,port:c,timeout:p}),timeout:p+500,encoding:"utf-8"});return g.error||g.status!==0?null:`${l}:${c}`}catch{return null}}case"net-sendrecv-pool":{let l=String(e[0]??"localhost"),c=Number(e[1]??27017),p=String(e[2]??""),m=Number(e[3]??1e4);if(!globalThis.__netPoolWorker){let{Worker:$}=require("worker_threads"),M=new SharedArrayBuffer(4),O=new SharedArrayBuffer(8*1024*1024);Atomics.store(new Int32Array(M),0,0);let C=`
159
+ const { workerData } = require('worker_threads');
160
+ const net = require('net');
161
+ const control = new Int32Array(workerData.controlBuf);
162
+ const data = Buffer.from(workerData.dataBuf);
163
+ const sockets = new Map(); // key=host:port, value=socket
164
+
165
+ function getSocket(host, port) {
166
+ const key = host + ':' + port;
167
+ if (sockets.has(key)) {
168
+ const s = sockets.get(key);
169
+ if (!s.destroyed && s.writable) return Promise.resolve(s);
170
+ sockets.delete(key);
171
+ }
172
+ return new Promise((resolve, reject) => {
173
+ const sock = net.createConnection({ host, port });
174
+ sock.on('connect', () => {
175
+ sockets.set(key, sock);
176
+ resolve(sock);
177
+ });
178
+ sock.on('error', reject);
179
+ sock.on('close', () => sockets.delete(key));
180
+ setTimeout(() => reject(new Error('connect timeout')), 5000);
181
+ });
182
+ }
183
+
184
+ function sendRecv(host, port, hexPayload, timeout) {
185
+ return new Promise(async (resolve, reject) => {
186
+ let sock;
187
+ try { sock = await getSocket(host, port); } catch(e) { return reject(e); }
188
+ const buf = Buffer.from(hexPayload, 'hex');
189
+ let chunks = [];
190
+ let done = false;
191
+ const timer = setTimeout(() => {
192
+ if (!done) { done = true; resolve(null); }
193
+ }, timeout);
194
+ const onData = (chunk) => {
195
+ chunks.push(chunk);
196
+ const total = Buffer.concat(chunks);
197
+ if (total.length >= 4) {
198
+ const msgLen = total.readInt32LE(0);
199
+ if (total.length >= msgLen) {
200
+ done = true;
201
+ clearTimeout(timer);
202
+ sock.removeListener('data', onData);
203
+ resolve(total.slice(0, msgLen).toString('hex'));
204
+ }
205
+ }
206
+ };
207
+ sock.on('data', onData);
208
+ sock.write(buf);
209
+ });
210
+ }
211
+
212
+ async function loop() {
213
+ while (true) {
214
+ Atomics.wait(control, 0, 0);
215
+ const flag = Atomics.load(control, 0);
216
+ if (flag === -1) break;
217
+ const reqLen = data.readInt32LE(0);
218
+ const reqStr = data.toString('utf8', 4, 4 + reqLen);
219
+ let resp;
220
+ try {
221
+ const req = JSON.parse(reqStr);
222
+ const hexResp = await sendRecv(req.host, req.port, req.data, req.timeout || 10000);
223
+ resp = { ok: true, data: hexResp };
224
+ } catch(e) {
225
+ resp = { ok: false, error: e.message };
226
+ }
227
+ const respStr = JSON.stringify(resp);
228
+ data.writeInt32LE(respStr.length, 0);
229
+ data.write(respStr, 4, 'utf8');
230
+ Atomics.store(control, 0, 2);
231
+ Atomics.notify(control, 0);
232
+ Atomics.wait(control, 0, 2); // wait for main thread to acknowledge
233
+ }
234
+ }
235
+ loop().catch(e => {
236
+ Atomics.store(control, 0, -2);
237
+ Atomics.notify(control, 0);
238
+ });
239
+ `,P=new $(C,{eval:!0,workerData:{controlBuf:M,dataBuf:O}});P.on("error",_=>{globalThis.__netPoolWorker=null}),globalThis.__netPoolWorker=P,globalThis.__netPoolCtrlBuf=M,globalThis.__netPoolDataBuf=O}let d=new Int32Array(globalThis.__netPoolCtrlBuf),g=Buffer.from(globalThis.__netPoolDataBuf),h=JSON.stringify({host:l,port:c,data:p,timeout:m});if(g.writeInt32LE(h.length,0),g.write(h,4,"utf8"),Atomics.store(d,0,1),Atomics.notify(d,0),Atomics.wait(d,0,1,m+2e3)==="timed-out")return null;let k=g.readInt32LE(0),v=JSON.parse(g.toString("utf8",4,4+k));return Atomics.store(d,0,0),v.ok?v.data:null}case"+":{let l=e.findIndex(c=>c==null||typeof c!="number");if(l>=0){let c=Et(e[l]),p=c==="nil"?"(nil? \uD655\uC778 \uD6C4 \uAE30\uBCF8\uAC12 \uC0AC\uC6A9)":"(str-to-num \uBCC0\uD658 \uD655\uC778)";throw new Error(`[E_TYPE_MISMATCH] +: \uC778\uC790 ${l+1}\uBC88\uC5D0 ${c} \uC804\uB2EC\uB428 \u2014 number \uD544\uC694 ${p}`)}return e.reduce((c,p)=>c+p,0)}case"-":{let l=e.findIndex(c=>c==null||typeof c!="number");if(l>=0){let c=Et(e[l]),p=c==="nil"?"(nil? \uD655\uC778 \uD6C4 \uAE30\uBCF8\uAC12 \uC0AC\uC6A9)":"(str-to-num \uBCC0\uD658 \uD655\uC778)";throw new Error(`[E_TYPE_MISMATCH] -: \uC778\uC790 ${l+1}\uBC88\uC5D0 ${c} \uC804\uB2EC\uB428 \u2014 number \uD544\uC694 ${p}`)}return e.length===1?-e[0]:e.reduce((c,p)=>c-p)}case"*":{let l=e.findIndex(c=>c==null||typeof c!="number");if(l>=0){let c=Et(e[l]),p=c==="nil"?"(nil? \uD655\uC778 \uD6C4 \uAE30\uBCF8\uAC12 \uC0AC\uC6A9)":"(str-to-num \uBCC0\uD658 \uD655\uC778)";throw new Error(`[E_TYPE_MISMATCH] *: \uC778\uC790 ${l+1}\uBC88\uC5D0 ${c} \uC804\uB2EC\uB428 \u2014 number \uD544\uC694 ${p}`)}return e.reduce((c,p)=>c*p,1)}case"/":{let l=e.findIndex(c=>c==null||typeof c!="number");if(l>=0){let c=Et(e[l]),p=c==="nil"?"(nil? \uD655\uC778 \uD6C4 \uAE30\uBCF8\uAC12 \uC0AC\uC6A9)":"(str-to-num \uBCC0\uD658 \uD655\uC778)";throw new Error(`[E_TYPE_MISMATCH] /: \uC778\uC790 ${l+1}\uBC88\uC5D0 ${c} \uC804\uB2EC\uB428 \u2014 number \uD544\uC694 ${p}`)}return e.length===1?1/e[0]:e.reduce((c,p)=>c/p)}case"%":return e[0]%e[1];case"=":return si(e[0],e[1]);case"<":return e[0]<e[1];case">":return e[0]>e[1];case"<=":return e[0]<=e[1];case">=":return e[0]>=e[1];case"!=":case"not=":return e[0]!==e[1];case"and":return e.every(l=>l);case"or":{let l=c=>c==null||c===!1;for(let c of e)if(!l(c))return c;return e.length>0?e[e.length-1]:null}case"not":return!e[0];case"print":return process.stdout.write(e.map(l=>f(l)).join(" ")),null;case"println":case"echo":return process.stdout.write(e.map(l=>f(l)).join(" ")+`
240
+ `),null;case"tap":case"dbg":{let l=e.length>1?String(e[0])+" ":"",c=e.length>1?e[1]:e[0];return process.stderr.write("[tap] "+l+f(c)+`
241
+ `),c}case"print-err":return process.stderr.write(e.map(l=>f(l)).join(" ")+`
242
+ `),null;case"str":return e.map(l=>{if(l==null)return"null";if(typeof l=="string"||typeof l=="number"||typeof l=="boolean")return String(l);let c=typeof l=="object"&&!Array.isArray(l)&&!(l instanceof Map)&&l?.kind!=="function-value"&&l?.kind!=="closure";if(Array.isArray(l)||c)try{return JSON.stringify(l)}catch{return f(l)}return f(l)}).join("");case"repr":return JSON.stringify(e[0],null,2);case"inspect":{let l=f(e[0]);return console.log(l),e[0]}case"concat":return Array.isArray(e[0])?Array.isArray(e[1])?e[0].concat(e[1]):e[0]||[]:e.join("");case"upper":return e[0]?.toString().toUpperCase();case"lower":return e[0]?.toString().toLowerCase();case"length":case"count":return Array.isArray(e[0])||typeof e[0]=="string"?e[0].length:e[0]!==null&&typeof e[0]=="object"?Object.keys(e[0]).length:0;case"to-hex":return(Math.floor(Number(e[0]))&255).toString(16).padStart(2,"0");case"bson-encode-native":{let l=h=>{let y=h&255,k=h>>8&255,v=h>>16&255,$=h>>24&255;return y.toString(16).padStart(2,"0")+k.toString(16).padStart(2,"0")+v.toString(16).padStart(2,"0")+$.toString(16).padStart(2,"0")},c=h=>{let y=h>>>0,k=Math.floor(h/4294967296)>>>0;return l(y)+l(k)},p=h=>{let y=Buffer.allocUnsafe(8);return y.writeDoubleLE(h,0),y.toString("hex")},m=h=>{let y="";for(let k=0;k<h.length;k++)y+=h.charCodeAt(k).toString(16).padStart(2,"0");return y},d=h=>{if(!h||typeof h!="object")return l(5)+"00";let y="",k=Array.isArray(h)?h.map(($,M)=>[String(M),$]):Object.entries(h);for(let[$,M]of k){let O=m($)+"00";if(Array.isArray(M)){let C=d(M);y+="04"+O+C}else if(M!==null&&typeof M=="object"&&!Array.isArray(M)){let C=d(M);y+="03"+O+C}else if(typeof M=="number"&&Number.isInteger(M)&&M>=-2147483648&&M<=2147483647)y+="10"+O+l(M);else if(typeof M=="number")y+="01"+O+p(M);else if(typeof M=="string"){let C=Buffer.from(M,"utf-8"),P=C.length+1;y+="02"+O+l(P)+C.toString("hex")+"00"}else typeof M=="boolean"?y+="08"+O+(M?"01":"00"):M==null&&(y+="0a"+O)}let v=4+y.length/2+1;return l(v)+y+"00"},g=e[0];return!g||typeof g!="object"?"0c000000107069696e6700010000000000":d(g)}case"bson-decode-native":{let l=String(e[0]||"");if(l.length<8)return{};let c=Buffer.from(l,"hex"),p=(d,g)=>{if(g+4>d.length)return[{},g];let h=d.readInt32LE(g),y=g+h,k={},v=g+4;for(;v<y-1&&d[v]!==0;){let $=d[v];v++;let M=v;for(;M<d.length&&d[M]!==0;)M++;let O=d.toString("utf-8",v,M);if(v=M+1,$===1)k[O]=d.readDoubleLE(v),v+=8;else if($===2){let C=d.readInt32LE(v);v+=4,k[O]=d.toString("utf-8",v,v+C-1),v+=C}else if($===3){let[C,P]=p(d,v);k[O]=C,v=P}else if($===4){let[C,P]=p(d,v);k[O]=Object.values(C),v=P}else if($===7)k[O]=d.toString("hex",v,v+12),v+=12;else if($===8)k[O]=d[v]!==0,v++;else if($===9)k[O]=d.readBigInt64LE(v),v+=8;else if($===10)k[O]=null;else if($===16)k[O]=d.readInt32LE(v),v+=4;else if($===18)k[O]=Number(d.readBigInt64LE(v)),v+=8;else break}return[k,y]},[m]=p(c,0);return m}case"identity":return e[0];case"comp":{let l=e.filter(c=>c!=null);return(...c)=>{if(l.length===0)return c[0];let p=u(l[l.length-1],c);for(let m=l.length-2;m>=0;m--)p=u(l[m],[p]);return p}}case"juxt":{let l=e.filter(c=>c!=null);return(...c)=>l.map(p=>u(p,c))}case"constantly":{let l=e[0];return(...c)=>l}case"complement":{let l=e[0],c=(p,m)=>typeof p=="function"?p(...m):p?.kind==="function-value"?u(p,m):null;return(...p)=>!c(l,p)}case"list":return e;case"first":return Array.isArray(e[0])&&e[0][0]!==void 0?e[0][0]:null;case"second":return Array.isArray(e[0])&&e[0][1]!==void 0?e[0][1]:null;case"nth":return Array.isArray(e[0])&&e[0][Number(e[1])]!==void 0?e[0][Number(e[1])]:null;case"rest":return Array.isArray(e[0])?e[0].slice(1):[];case"keys":{let l=e[0];return l instanceof Map?Array.from(l.keys()):l&&typeof l=="object"&&!Array.isArray(l)?Object.keys(l):[]}case"length-or-zero":case"length_or_zero":{let l=e[0];return l==null?0:typeof l=="string"||Array.isArray(l)?l.length:l instanceof Map?l.size:typeof l=="object"?Object.keys(l).length:0}case"vals":case"values":{let l=e[0];return l instanceof Map?Array.from(l.values()):l&&typeof l=="object"&&!Array.isArray(l)?Object.values(l):[]}case"upper-case":return typeof e[0]=="string"?e[0].toUpperCase():e[0];case"lower-case":case"lowercase":case"lower":return typeof e[0]=="string"?e[0].toLowerCase():e[0];case"trim":return typeof e[0]=="string"?e[0].trim():"";case"starts-with?":case"str-starts-with?":return typeof e[0]=="string"&&typeof e[1]=="string"?e[0].startsWith(e[1]):!1;case"ends-with?":case"str-ends-with?":return typeof e[0]=="string"&&typeof e[1]=="string"?e[0].endsWith(e[1]):!1;case"char-at":case"str-char-at":return typeof e[0]=="string"?e[0][Number(e[1])]??"":"";case"math-pow":return Math.pow(Number(e[0]),Number(e[1]));case"append":return Array.isArray(e[0])&&e.length===2&&Array.isArray(e[1])?[...e[0],...e[1]]:[...e[0]||[],...e.slice(1)];case"reverse":return Array.isArray(e[0])?[...e[0]].reverse():[];case"map":{if(Array.isArray(e[0])&&e[0].length>0){let p=e[1];if(p&&(typeof p=="function"||p?.kind==="function-value"||p?.kind==="closure"))throw new Error("map \uC778\uC790 \uC21C\uC11C \uC624\uB958: (map fn arr) \uD615\uC2DD\uC774 \uC62C\uBC14\uB985\uB2C8\uB2E4. \uD604\uC7AC \uC785\uB825: (map arr fn)")}let l=e[0];return e[1]===null||e[1]===void 0?[]:(Array.isArray(e[1])?e[1]:[]).map(p=>u(l,[p]))}case"set-timeout":{if(n.args.length<2)throw new Error("set-timeout requires callback and delay");let l=a(n.args[0]),c=a(n.args[1]);return new ae((p,m)=>{setTimeout(()=>{try{typeof l=="function"?p(l()):l.kind==="function-value"?p(u(l,[])):m(new Error("set-timeout callback must be a function"))}catch(d){m(d)}},c)})}case"promise":{if(n.args.length<1)throw new Error("promise requires executor function");let l=a(n.args[0]);if(l.kind==="function-value")return new ae((c,p)=>{try{u(l,[{kind:"builtin-function",fn:g=>c(g[0])},{kind:"builtin-function",fn:g=>p(g[0]instanceof Error?g[0]:new Error(String(g[0])))}])}catch(m){p(m)}});throw new Error("promise executor must be a function")}case"fn":{let l=[],c=n.args[0];if(c&&typeof c=="object"&&"kind"in c&&c.kind==="literal"&&Array.isArray(c.value))l=c.value.map(p=>{if(p&&typeof p=="object"&&"kind"in p&&p.kind==="variable")return p.name;throw new Error("fn parameter must be a variable")});else if(c&&typeof c=="object"&&"kind"in c&&c.kind==="variable")l=[c.name];else if(Array.isArray(c))l=c.map(p=>typeof p=="string"?p:String(p));else throw new Error("fn expects parameter array");return{kind:"function-value",params:l,body:n.args[1],capturedEnv:r.context.variables.snapshot()}}case"reduce":{if(Array.isArray(e[0])&&e[0].length>0){let m=e[2];if(m&&(typeof m=="function"||m?.kind==="function-value"||m?.kind==="closure"))throw new Error("reduce \uC778\uC790 \uC21C\uC11C \uC624\uB958: (reduce fn init arr) \uD615\uC2DD\uC774 \uC62C\uBC14\uB985\uB2C8\uB2E4. \uD604\uC7AC \uC785\uB825: (reduce arr init fn)")}let l=e[0],c,p;if(e.length<=2||e[2]===void 0){let m=Array.isArray(e[1])?e[1]:[];if(m.length===0)return null;c=m[0],p=m.slice(1)}else c=e[1],p=e[2]??[];if(Re(p)){let d=p,g=0;for(;d&&g<1e5;)c=i(l,[c,bt(d)]),d=rt(d),g++;if(g>=1e5)throw new Error("reduce: lazy seq\uAC00 100000\uC744 \uCD08\uACFC (\uBB34\uD55C \uC2DC\uD000\uC2A4 \uAC00\uB2A5\uC131, take\uB97C \uBA3C\uC800 \uC0AC\uC6A9\uD558\uC138\uC694)");return c}if(!Array.isArray(p))throw new Error(`reduce: \uBC30\uC5F4 \uC778\uC790\uAC00 \uD544\uC694\uD569\uB2C8\uB2E4 (\uBC1B\uC740 \uD0C0\uC785: ${typeof p})`);for(let m of p)c=i(l,[c,m]);return c}case"json-response":if(typeof e[0]=="object"&&e[0]!==null&&!Array.isArray(e[0]))return e[0];if(Array.isArray(e[0])){let l={};for(let c=0;c<e[0].length;c+=2){let p=e[0][c],m=e[0][c+1];typeof p=="string"&&p.startsWith(":")&&(p=p.substring(1)),typeof p=="string"&&(l[p]=m)}return l}return e[0];case"html-response":return{html:e[0]};case"html-escape":return String(e[0]??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;");case"js-escape":return String(e[0]??"").replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\x00/g,"\\0");case"h":{let l=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),c=k=>String(k).replace(/&/g,"&amp;").replace(/"/g,"&quot;"),p=k=>String(k).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),m=String(e[0]??"div").toLowerCase(),d={},g=1;e[1]!==null&&e[1]!==void 0&&typeof e[1]=="object"&&!Array.isArray(e[1])&&(d=e[1],g=2);let h=Object.entries(d).filter(([,k])=>k!=null&&k!==!1).map(([k,v])=>v===!0?` ${k}`:` ${k}="${c(String(v))}"`).join("");if(l.has(m))return`<${m}${h}>`;let y=e.slice(g).flat().filter(k=>k!=null&&k!==!1).map(k=>typeof k=="string"?k:typeof k=="number"||typeof k=="boolean"?p(String(k)):String(k??"")).join("");return`<${m}${h}>${y}</${m}>`}case"cx":return e.flat().filter(l=>l!=null&&l!==!1&&l!=="").map(l=>String(l).trim()).filter(l=>l.length>0).join(" ");case"for-html":return Array.isArray(e[0])?e[0].map(l=>{let c=u(e[1],[l]);return c!=null?String(c):""}).join(""):"";case"for-html-indexed":return Array.isArray(e[0])?e[0].map((l,c)=>{let p=u(e[1],[l,c]);return p!=null?String(p):""}).join(""):"";case"now":return new Date().toISOString();case"server-uptime":return Date.now()-r.context.startTime;case"char-at":return typeof e[0]=="string"&&typeof e[1]=="number"&&e[0][Math.floor(e[1])]||"";case"char-code":if(typeof e[0]=="string"&&e[0].length>0)return e[0].charCodeAt(0);throw new Error("char-code expects non-empty string");case"substring":return typeof e[0]=="string"?e[0].substring(Math.floor(e[1]||0),Math.floor(e[2]||e[0].length)):"";case"is-whitespace?":return/^\s$/.test(String(e[0]));case"is-digit?":return/^\d$/.test(String(e[0]));case"is-symbol?":return/^[a-zA-Z_\-][a-zA-Z0-9_\-?!]*$/.test(String(e[0]));case"split":return typeof e[0]=="string"?e[0].split(String(e[1]??"")):[];case"error":throw new Error(String(e[0]));case"nil?":case"null?":return e[0]===null||e[0]===void 0;case"empty?":{let l=e[0];return l==null?!0:typeof l=="string"||Array.isArray(l)?l.length===0:typeof l=="object"?Object.keys(l).length===0:!1}case"not-empty?":{let l=e[0];return l==null?!1:typeof l=="string"||Array.isArray(l)?l.length>0:typeof l=="object"?Object.keys(l).length>0:!0}case"has-key?":{let l=e[0],c=e[1];if(l==null||typeof l!="object"||Array.isArray(l))return!1;let p=typeof c=="string"&&c.startsWith(":")?c.slice(1):String(c??"");return Object.prototype.hasOwnProperty.call(l,p)}case"nil-or-empty?":return e[0]===null||e[0]===void 0||e[0]&&e[0].length===0;case"zero?":return e[0]===0;case"pos?":return typeof e[0]=="number"&&e[0]>0;case"neg?":return typeof e[0]=="number"&&e[0]<0;case"even?":return typeof e[0]=="number"&&e[0]%2===0;case"odd?":return typeof e[0]=="number"&&e[0]%2!==0;case"some?":case"not-nil?":return e[0]!==null&&e[0]!==void 0;case"positive?":return typeof e[0]=="number"&&e[0]>0;case"negative?":return typeof e[0]=="number"&&e[0]<0;case"int?":return typeof e[0]=="number"&&Number.isInteger(e[0]);case"float?":return typeof e[0]=="number"&&!Number.isInteger(e[0]);case"nan?":return typeof e[0]=="number"&&isNaN(e[0]);case"dir-exists?":try{return require("fs").statSync(String(e[0])).isDirectory()}catch{return!1}case"string?":return typeof e[0]=="string";case"number?":return typeof e[0]=="number";case"boolean?":case"bool?":return typeof e[0]=="boolean";case"list?":case"array?":return Array.isArray(e[0]);case"function?":case"fn?":{let l=e[0];return typeof l=="function"||l!==null&&typeof l=="object"&&(l.kind==="function-value"||l.kind==="closure"||l.kind==="async-function-value"||l.kind==="builtin-fn")}case"map?":return e[0]!==null&&typeof e[0]=="object"&&!Array.isArray(e[0]);case"vector?":case"array?":case"list?":return Array.isArray(e[0]);case"integer?":return typeof e[0]=="number"&&Number.isInteger(e[0]);case"float?":return typeof e[0]=="number"&&!Number.isInteger(e[0]);case"num-to-str":return String(e[0]);case"str-to-num":{let l=parseFloat(String(e[0]));return isNaN(l)?null:l}case"map-set":if(typeof e[0]=="object"&&e[0]!==null&&!Array.isArray(e[0])){let l=typeof e[1]=="string"&&e[1].startsWith(":")?e[1].slice(1):String(e[1]);return{...e[0],[l]:e[2]}}return e[0];case"slice":return Array.isArray(e[0])||typeof e[0]=="string"?e[0].slice(e[1],e[2]):[];case"str-split":{if(typeof e[0]!="string"||typeof e[1]!="string")return[];let l=e[0].split(e[1]);if(e[2]!==void 0){let c=Number(e[2]);if(c>0&&l.length>c)return[...l.slice(0,c-1),l.slice(c-1).join(e[1])]}return l}case"join":case"str-join":return Array.isArray(e[0])?e[0].join(e[1]!==void 0?String(e[1]):""):typeof e[0]=="string"&&Array.isArray(e[1])?e[1].join(e[0]):Array.isArray(e[0])?e[0].join(""):"";case"str-format":case"format":{let l=String(e[0]??""),c=e.length===2&&Array.isArray(e[1])?e[1]:e.slice(1),p=0;return l.replace(/%([+\-0 ]*)(\d*)\.?(\d*)([sdifoexX%])/g,(m,d,g,h,y)=>{if(y==="%")return"%";let k=c[p++],v=g?parseInt(g):0,$=d.includes("+"),M=d.includes("0"),O=d.includes("-"),C=(P,_)=>{if(v<=P.length)return P;if(O)return P.padEnd(v," ");if(M){let S=P[0]==="+"||P[0]==="-"?P[0]:"";return S+(S?P.slice(1):P).padStart(v-S.length,"0")}return P.padStart(v," ")};if(y==="d"||y==="i"){let P=Math.trunc(Number(k)),_=String(Math.abs(P));return P<0?_="-"+_:$&&(_="+"+_),C(_,P>=0)}if(y==="f"){let P=h!==""?parseInt(h):6,_=Number(k),S=Math.abs(_).toFixed(P);return _<0?S="-"+S:$&&(S="+"+S),C(S,_>=0)}if(y==="e"||y==="E"){let P=h!==""?parseInt(h):6,_=Number(k).toExponential(P);return y==="E"&&(_=_.toUpperCase()),v>_.length?O?_.padEnd(v):_.padStart(v):_}if(y==="s"){let P=k==null?"null":String(k);return v>P.length&&(P=O?P.padEnd(v," "):P.padStart(v," ")),P}return y==="o"?JSON.stringify(k):y==="x"?Math.trunc(Number(k)).toString(16):y==="X"?Math.trunc(Number(k)).toString(16).toUpperCase():String(k)})}case"str-blank?":return e[0]===null||e[0]===void 0||typeof e[0]=="string"&&e[0].trim()==="";case"trim":case"string_trim":case"str_trim":return typeof e[0]=="string"?e[0].trim():"";case"uppercase":return typeof e[0]=="string"?e[0].toUpperCase():"";case"lowercase":return typeof e[0]=="string"?e[0].toLowerCase():"";case"contains?":if(typeof e[0]=="string"&&typeof e[1]=="string"||Array.isArray(e[0]))return e[0].includes(e[1]);if(e[0]!==null&&typeof e[0]=="object"&&!Array.isArray(e[0])){let l=e[1];l!==null&&typeof l=="object"&&l.kind==="keyword"&&(l=l.name);let c=typeof l=="string"&&l.startsWith(":")?l.slice(1):String(l);return Object.prototype.hasOwnProperty.call(e[0],c)||Object.prototype.hasOwnProperty.call(e[0],":"+c)}return!1;case"starts-with?":return typeof e[0]=="string"&&typeof e[1]=="string"?e[0].startsWith(e[1]):!1;case"index-of":return Array.isArray(e[0])||typeof e[0]=="string"&&typeof e[1]=="string"?e[0].indexOf(e[1]):-1;case"replace":return typeof e[0]=="string"&&typeof e[1]=="string"&&typeof e[2]=="string"?e[0].split(e[1]).join(e[2]):"";case"repeat":return typeof e[0]=="number"?Array(e[0]).fill(e[1]!==void 0?e[1]:null):typeof e[0]=="string"&&typeof e[1]=="number"?e[0].repeat(e[1]):[];case"filter":{if(Array.isArray(e[0])&&e[0].length>0){let p=e[1];if(p&&(typeof p=="function"||p?.kind==="function-value"||p?.kind==="closure"))throw new Error("filter \uC778\uC790 \uC21C\uC11C \uC624\uB958: (filter fn arr) \uD615\uC2DD\uC774 \uC62C\uBC14\uB985\uB2C8\uB2E4. \uD604\uC7AC \uC785\uB825: (filter arr fn)")}let l=e[0],c=e[1];return c==null?[]:Array.isArray(c)?l==null?c:c.filter(p=>u(l,[p])):[]}case"find":{if(!Array.isArray(e[0]))return-1;let l=e[1];return typeof l=="function"?e[0].find(l)??null:l&&(l.kind==="function-value"||l.kind==="closure")?e[0].find(c=>u(l,[c]))??null:e[0].indexOf(l)}case"last":return Array.isArray(e[0])&&e[0].length>0?e[0][e[0].length-1]:null;case"butlast":return Array.isArray(e[0])&&e[0].length>1?e[0].slice(0,-1):[];case"first-or":case"first_or":return Array.isArray(e[0])&&e[0].length>0&&e[0][0]!==void 0?e[0][0]:e[1]!==void 0?e[1]:null;case"last-or":case"last_or":return Array.isArray(e[0])&&e[0].length>0?e[0][e[0].length-1]:e[1]!==void 0?e[1]:null;case"apply":{let l=e[0],c=Array.isArray(e[e.length-1])?e[e.length-1]:[],m=[...e.slice(1,e.length-1),...c];return typeof l=="string"?Fn(r,l,m,n):u(l,m)}case"sum":return(Array.isArray(e[0])?e[0]:e).reduce((c,p)=>c+Number(p),0);case"product":return(Array.isArray(e[0])?e[0]:e).reduce((c,p)=>c*Number(p),1);case"average":{let l=Array.isArray(e[0])?e[0]:e;return l.length===0?null:l.reduce((c,p)=>c+Number(p),0)/l.length}case"update":{let l=e[0],c=e[1],p=e[2],m=c;m&&typeof m=="object"&&m.kind==="keyword"?m=m.name:typeof m=="string"&&m.startsWith(":")&&(m=m.slice(1));let d=l&&typeof l=="object"?l[m]??null:null,g=u(p,[d]);return{...l,[m]:g}}case"partition":{let l=Number(e[0]),c=Array.isArray(e[1])?e[1]:[],p=[];for(let m=0;m<c.length;m+=l)p.push(c.slice(m,m+l));return p}case"interpose":{let l=e[0],c=Array.isArray(e[1])?e[1]:[];if(c.length===0)return[];let p=[c[0]];for(let m=1;m<c.length;m++)p.push(l),p.push(c[m]);return p}case"keep":{let l=e[0];return(Array.isArray(e[1])?e[1]:[]).map(p=>u(l,[p])).filter(p=>p!=null)}case"mapcat":{let l=e[0];return(Array.isArray(e[1])?e[1]:[]).flatMap(p=>{let m=u(l,[p]);return Array.isArray(m)?m:[m]})}case"count-if":{let l=e[0];return(Array.isArray(e[1])?e[1]:[]).filter(p=>u(l,[p])).length}case"find-first":{let l=e[0],p=(Array.isArray(e[1])?e[1]:[]).find(m=>u(l,[m]));return p!==void 0?p:null}case"max-by":{let l=e[0],c=Array.isArray(e[1])?e[1]:[];if(c.length===0)return null;let m=typeof l=="string"&&c[0]!==null&&typeof c[0]=="object"?d=>d!==null&&typeof d=="object"?d[l]:null:d=>u(l,[d]);return c.reduce((d,g)=>m(g)>m(d)?g:d)}case"min-by":{let l=e[0],c=Array.isArray(e[1])?e[1]:[];if(c.length===0)return null;let m=typeof l=="string"&&c[0]!==null&&typeof c[0]=="object"?d=>d!==null&&typeof d=="object"?d[l]:null:d=>u(l,[d]);return c.reduce((d,g)=>m(g)<m(d)?g:d)}case"max-of":{let l=Array.isArray(e[0])?e[0]:e;return l.length===0?null:Math.max(...l.map(Number))}case"min-of":{let l=Array.isArray(e[0])?e[0]:e;return l.length===0?null:Math.min(...l.map(Number))}case"get-in":{if(!Array.isArray(e[1]))throw new Error("get-in: \uB450 \uBC88\uC9F8 \uC778\uC790\uB294 \uD0A4 \uBC30\uC5F4\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4");let l=e[2]!==void 0?e[2]:null,c=e[0];for(let p of e[1]){if(c==null)return l;let m=typeof p=="string"&&p.startsWith(":")?p.slice(1):p;if(Array.isArray(c))c=c[m]!==void 0?c[m]:void 0;else if(c!==null&&typeof c=="object")c=c[m]!==void 0?c[m]:void 0;else return l}return c!==void 0?c:l}case"get-or":{let l=e[2]!==void 0?e[2]:null,c=e[1];if(c!==null&&typeof c=="object"&&c.kind==="keyword"&&(c=c.name),e[0]===null||e[0]===void 0)return l;if(Array.isArray(e[0])){let p=typeof c=="number"?c:Number(c);return Number.isFinite(p)&&e[0][p]!==void 0?e[0][p]:l}if(e[0]instanceof Map){let p=e[0].get(String(c).replace(/^:/,""));return p===void 0?l:p}if(typeof e[0]=="object"){let p=typeof c=="string"&&c.startsWith(":")?c.slice(1):String(c);return e[0][p]!==void 0?e[0][p]:typeof c=="string"&&e[0][c]!==void 0?e[0][c]:l}return l}case"get":{if((e[0]===null||e[0]===void 0)&&process.env.FL_STRICT==="1")throw new ue(de.TYPE_NIL,`(get nil ${typeof e[1]=="string"?'"'+e[1]+'"':String(e[1])}) \u2014 cannot access key on nil. Use (get-or coll key default).`,{fn:"get",arg:0,expected:"non-nil",got:"nil"});if(e[0]!==null&&e[0]!==void 0&&typeof e[0]!="object"&&typeof e[0]!="string"&&!Array.isArray(e[0])){let p=`[E_TYPE_MISMATCH] get: \uCCAB \uBC88\uC9F8 \uC778\uC790\uB294 map, array, string\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4 (\uBC1B\uC740 \uAC12: ${typeof e[0]})
243
+ \uC62C\uBC14\uB978 \uD615\uC2DD: (get map key) \uB610\uB294 (get arr index)
244
+ \uC608: (get {:name "kim"} "name") \u2192 "kim"`;if(process.env.FL_V12==="1")throw new Error(p);console.warn(`\u26A0\uFE0F [FreeLang] ${p}`)}let l=e[1];l!==null&&typeof l=="object"&&l.kind==="keyword"&&(l=l.name);let c=e.length>=3?e[2]:null;if(Array.isArray(e[0])||typeof e[0]=="string")return typeof l=="number"?e[0][l]??c:c;if(e[0]instanceof Map)return e[0].has(String(l).replace(/^:/,""))?e[0].get(String(l).replace(/^:/,"")):c;if(e[0]!==null&&typeof e[0]=="object"){let p=typeof l=="string"&&l.startsWith(":")?l.slice(1):String(l);return e[0][p]!==void 0?e[0][p]:typeof l=="string"&&e[0][l]!==void 0?e[0][l]:c}return c}case"block-items":return e[0]&&typeof e[0]=="object"&&e[0].kind==="block"&&e[0].type==="Array"?e[0].fields instanceof Map?e[0].fields.get("items")??[]:[]:Array.isArray(e[0])?e[0]:[];case"fl-env-get":{let l=e[0],c=String(e[1]);for(;l!=null;){let p=l.vars;if(Array.isArray(p))for(let m=0;m<p.length;m++){let d=p[m];if(Array.isArray(d)&&d[0]===c)return d[1]}l=l.parent}return null}case"fl-special-op?":{let l=String(e[0]);return["if","let","do","begin","fn","and","or","not","null?","match","call","export","define","set!"].includes(l)?l:null}case"fl-exec-op":{let l=String(e[0]),c=Array.isArray(e[1])?e[1]:[],p=c[0],m=c[1],d=c[2];switch(s){case"+":return c.reduce((g,h)=>g+h,0);case"-":return c.length===1?-p:c.reduce((g,h)=>g-h);case"*":return c.reduce((g,h)=>g*h,1);case"/":return c.length===1?1/p:c.reduce((g,h)=>g/h);case"%":return typeof p=="number"&&typeof m=="number"?p%m:null;case"=":return p===m;case"!=":return p!==m;case"<":return p<m;case">":return p>m;case"<=":return p<=m;case">=":return p>=m;case"concat":return c.reduce((g,h)=>g+String(h??""),"");case"length":return Array.isArray(p)||typeof p=="string"?p.length:0;case"get":return Array.isArray(p)||typeof p=="string"?typeof m=="number"?p[m]??null:null:p instanceof Map?p.get(String(m).replace(/^:/,""))??null:p!==null&&typeof p=="object"?p[String(m).replace(/^:/,"")]??p[m]??null:null;case"append":return Array.isArray(p)&&Array.isArray(m)?[...p,...m]:Array.isArray(p)?[...p,m]:[p,m];case"slice":return Array.isArray(p)||typeof p=="string"?p.slice(m,d):[];case"num-to-str":return String(p??"");case"str-to-num":{let g=parseFloat(String(p));return isNaN(g)?null:g}case"replace":return typeof p=="string"?p.split(String(m)).join(String(d)):p;case"str-join":return Array.isArray(p)?p.join(String(m??"")):String(p??"");case"null?":return p==null;case"array?":return Array.isArray(p);case"string?":return typeof p=="string";case"number?":return typeof p=="number";case"read-file":try{return require("fs").readFileSync(String(p),"utf-8")}catch{return null}case"write-file":try{return require("fs").writeFileSync(String(p),String(m??"")),!0}catch{return!1}case"file-exists?":try{return require("fs").existsSync(String(p))}catch{return!1}case"file-append":try{return require("fs").appendFileSync(String(p),String(m??"")),!0}catch{return!1}case"file-append-line":try{return require("fs").appendFileSync(String(p),String(m??"")+`
245
+ `),!0}catch{return!1}case"dir-list":try{return require("fs").readdirSync(String(p))}catch{return[]}default:return null}}case"fl-interp":return ne(e[0],e[1]);case"lex":try{return W(String(e[0]??""))}catch{return[]}case"parse":try{return H(Array.isArray(e[0])?e[0]:[])}catch{return[]}case"fl-parse":try{return H(W(String(e[0]??"")))}catch{return[]}case"fl-fix-env":{let l=e[0];if(!l||!Array.isArray(l.vars))return l;for(let c of l.vars)Array.isArray(c)&&c[1]&&typeof c[1]=="object"&&c[1].kind==="closure"&&(c[1]["closure-env"]=l);return l}case"hash-map":{let l={};for(let c=0;c+1<e.length;c+=2){let p=typeof e[c]=="string"&&e[c].startsWith(":")?e[c].slice(1):String(e[c]);l[p]=e[c+1]}return l}case"assoc":{if(e[0]!==null&&(typeof e[0]!="object"||Array.isArray(e[0])))throw new Error(`[E_TYPE_MISMATCH] assoc: \uCCAB \uBC88\uC9F8 \uC778\uC790\uB294 map\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4 (\uBC1B\uC740 \uAC12: ${typeof e[0]})
246
+ \uC62C\uBC14\uB978 \uD615\uC2DD: (assoc map key val)
247
+ \uC608: (assoc {:a 1} "b" 2) \u2192 {:a 1 :b 2}`);let l=e[0]!==null&&typeof e[0]=="object"&&!Array.isArray(e[0])?{...e[0]}:{};for(let c=1;c+1<e.length;c+=2){let p=e[c],m=typeof p=="string"&&p.startsWith(":")?p.slice(1):String(p);l[m]=e[c+1]}return l}case"assoc-in":{let p=function(m,d,g){let h=typeof d[0]=="string"&&d[0].startsWith(":")?d[0].slice(1):String(d[0]),y=m!==null&&typeof m=="object"&&!Array.isArray(m)?{...m}:{};return y[h]=d.length===1?g:p(y[h],d.slice(1),g),y};if(!Array.isArray(e[1])||e[1].length===0)throw new Error("assoc-in: \uB450 \uBC88\uC9F8 \uC778\uC790\uB294 \uBE44\uC5B4\uC788\uC9C0 \uC54A\uC740 \uD0A4 \uBC30\uC5F4\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4");let l=e[1],c=e[2];return p(e[0],l,c)}case"update-in":{let m=function(d,g){let h=typeof g[0]=="string"&&g[0].startsWith(":")?g[0].slice(1):String(g[0]),y=d!==null&&typeof d=="object"&&!Array.isArray(d)?{...d}:{};if(g.length===1){let v=[y[h]!==void 0?y[h]:null,...p];y[h]=typeof c=="string"?Fn(r,c,v,n):u(c,v)}else y[h]=m(y[h],g.slice(1));return y};if(!Array.isArray(e[1])||e[1].length===0)throw new Error("update-in: \uB450 \uBC88\uC9F8 \uC778\uC790\uB294 \uBE44\uC5B4\uC788\uC9C0 \uC54A\uC740 \uD0A4 \uBC30\uC5F4\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4");let l=e[1],c=e[2],p=e.slice(3);return m(e[0],l)}case"dissoc":{if(e[0]!==null&&e[0]!==void 0&&(typeof e[0]!="object"||Array.isArray(e[0])))throw new Error(`[E_TYPE_MISMATCH] dissoc: \uCCAB \uBC88\uC9F8 \uC778\uC790\uB294 map\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4 (\uBC1B\uC740 \uAC12: ${typeof e[0]})
248
+ \uC62C\uBC14\uB978 \uD615\uC2DD: (dissoc map key)
249
+ \uC608: (dissoc {:a 1 :b 2} "a") \u2192 {:b 2}`);if(e[0]!==null&&typeof e[0]=="object"&&!Array.isArray(e[0])){let l={...e[0]};for(let c=1;c<e.length;c++){let p=e[c],m=typeof p=="string"&&p.startsWith(":")?p.slice(1):String(p);delete l[m]}return l}return e[0]??{}}case"obj-keys":case"obj_keys":return!e[0]||typeof e[0]!="object"||Array.isArray(e[0])?[]:Object.keys(e[0]);case"obj-values":case"obj_values":return!e[0]||typeof e[0]!="object"||Array.isArray(e[0])?[]:Object.values(e[0]);case"obj-entries":case"obj_entries":return!e[0]||typeof e[0]!="object"||Array.isArray(e[0])?[]:Object.entries(e[0]);case"obj-merge":case"obj_merge":case"merge":return e.length===0?{}:Object.assign({},...e.filter(l=>l&&typeof l=="object"&&!Array.isArray(l)));case"merge-with":{let l=e[0],c=e.slice(1).filter(m=>m&&typeof m=="object"&&!Array.isArray(m));if(c.length===0)return{};let p={...c[0]};for(let m=1;m<c.length;m++)for(let[d,g]of Object.entries(c[m]))p[d]=d in p?u(l,[p[d],g]):g;return p}case"into":{let l=e[0],c=e[1];if(Array.isArray(l))return Array.isArray(c)?[...l,...c]:l;if(l&&typeof l=="object"&&!Array.isArray(l)){if(Array.isArray(c)){let p={...l};for(let m of c)Array.isArray(m)&&m.length===2?p[String(m[0])]=m[1]:m&&typeof m=="object"&&Object.assign(p,m);return p}return l}return c??l}case"obj-pick":case"obj_pick":case"pick":{if(!e[0]||!Array.isArray(e[1]))return{};let l=e[0];return e[1].reduce((c,p)=>{let m=typeof p=="string"&&p.startsWith(":")?p.slice(1):String(p);return m in l&&(c[m]=l[m]),c},{})}case"obj-omit":case"obj_omit":case"omit":{if(!e[0])return{};if(!Array.isArray(e[1]))return{...e[0]};let l={...e[0]};for(let c of e[1]){let p=typeof c=="string"&&c.startsWith(":")?c.slice(1):String(c);delete l[p]}return l}case"select-keys":{if(!e[0]||!Array.isArray(e[1]))return{};let l={};for(let c of e[1]){let p=c&&typeof c=="object"&&c.kind==="keyword"?c.name:typeof c=="string"&&c.startsWith(":")?c.slice(1):String(c);e[0][p]!==void 0&&(l[p]=e[0][p])}return l}case"rename-keys":{if(!e[0]||!e[1])return{...e[0]};let l={...e[0]};for(let[c,p]of Object.entries(e[1])){let m=typeof c=="string"&&c.startsWith(":")?c.slice(1):c,d=p&&typeof p=="object"&&p.kind==="keyword"?p.name:typeof p=="string"&&p.startsWith(":")?p.slice(1):String(p);l[m]!==void 0&&(l[d]=l[m],delete l[m])}return l}case"str-index-of":case"str-index_of":return typeof e[0]!="string"?-1:e[0].indexOf(String(e[1]??""),e[2]!==void 0?Number(e[2]):0);case"str-replace-all":case"str-replace":return typeof e[0]=="string"?e[0].split(String(e[1]??"")).join(String(e[2]??"")):"";case"str-to-upper":case"str-upper":return typeof e[0]=="string"?e[0].toUpperCase():e[0]??"";case"str-to-lower":case"str-lower":return typeof e[0]=="string"?e[0].toLowerCase():e[0]??"";case"str-trim":return typeof e[0]=="string"?e[0].trim():e[0]===null||e[0]===void 0?null:"";case"str-trim-left":return typeof e[0]=="string"?e[0].trimStart():e[0]??"";case"str-trim-right":return typeof e[0]=="string"?e[0].trimEnd():e[0]??"";case"str-starts-with":return typeof e[0]=="string"&&typeof e[1]=="string"?e[0].startsWith(e[1]):!1;case"str-ends-with":return typeof e[0]=="string"&&typeof e[1]=="string"?e[0].endsWith(e[1]):!1;case"str-includes":case"str-contains":return typeof e[0]=="string"&&typeof e[1]=="string"?e[0].includes(e[1]):!1;case"str-repeat":return typeof e[0]=="string"?e[0].repeat(Math.max(0,Number(e[1]??0))):"";case"str-pad-left":{if(typeof e[0]!="string")return String(e[0]??"");let l=Number(e[1]??0),c=typeof e[2]=="string"?e[2]:" ";return e[0].padStart(l,c)}case"str-pad-right":{if(typeof e[0]!="string")return String(e[0]??"");let l=Number(e[1]??0),c=typeof e[2]=="string"?e[2]:" ";return e[0].padEnd(l,c)}case"str-lines":return typeof e[0]=="string"?e[0].split(`
250
+ `):[];case"str-reverse":return typeof e[0]=="string"?e[0].split("").reverse().join(""):"";case"map-vals":{let l=e[0],c=e[1];if(!c||typeof c!="object"||Array.isArray(c))return{};let p={};for(let[m,d]of Object.entries(c))p[m]=u(l,[d]);return p}case"map-keys":{let l=e[0],c=e[1];if(!c||typeof c!="object"||Array.isArray(c))return{};let p={};for(let[m,d]of Object.entries(c))p[String(u(l,[m]))]=d;return p}case"filter-vals":{let l=e[0],c=e[1];if(!c||typeof c!="object"||Array.isArray(c))return{};let p={};for(let[m,d]of Object.entries(c))u(l,[d])&&(p[m]=d);return p}case"flatten":{if(!Array.isArray(e[0]))return[];let l=c=>c.reduce((p,m)=>p.concat(Array.isArray(m)?l(m):m),[]);return l(e[0])}case"flatten-1":case"flat-1":return Array.isArray(e[0])?e[0].reduce((l,c)=>l.concat(Array.isArray(c)?c:[c]),[]):[];case"conj":{let l=e[0],c=e.slice(1);if(Array.isArray(l))return[...l,...c];if(l!==null&&typeof l=="object"&&!Array.isArray(l)){let p={...l};for(let m of c)m&&typeof m=="object"&&!Array.isArray(m)?Object.assign(p,m):Array.isArray(m)&&m.length===2&&(p[String(m[0])]=m[1]);return p}return c}case"partition-by":{let l=e[0],c=e[1];if(!Array.isArray(c)||c.length===0)return[];let p=[],m=[c[0]],d=u(l,[c[0]]);for(let g=1;g<c.length;g++){let h=u(l,[c[g]]);h===d?m.push(c[g]):(p.push(m),m=[c[g]],d=h)}return p.push(m),p}case"every?":case"every":{if(e[1]===null||e[1]===void 0)return!0;if(!Array.isArray(e[1]))throw new Error("every?: \uB450 \uBC88\uC9F8 \uC778\uC790\uB294 \uBC30\uC5F4\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4");return e[1].every(l=>u(e[0],[l]))}case"any?":case"any":{if(e[1]===null||e[1]===void 0)return null;if(!Array.isArray(e[1]))throw new Error("any?: \uB450 \uBC88\uC9F8 \uC778\uC790\uB294 \uBC30\uC5F4\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4");let l=e[1].find(c=>u(e[0],[c]));return l!==void 0?l:null}case"none?":return Array.isArray(e[1])?e[1].every(l=>!u(e[0],[l])):!0;case"none":return e.length===0?{tag:"None",value:null,kind:"Option"}:Array.isArray(e[1])?e[1].every(l=>!u(e[0],[l])):{tag:"None",value:null,kind:"Option"};case"unique":case"distinct":return Array.isArray(e[0])?[...new Set(e[0])]:[];case"sort":return Array.isArray(e[0])?[...e[0]].sort((l,c)=>typeof l=="number"&&typeof c=="number"?l-c:String(l).localeCompare(String(c))):[];case"sort-by":case"sort_by":{if(Array.isArray(e[0])&&e[0].length>0){let d=e[1],g=typeof e[0][0]=="function"||e[0][0]?.kind==="function-value"||e[0][0]?.kind==="closure";if(d&&(typeof d=="function"||d?.kind==="function-value"||d?.kind==="closure")&&!g)throw new Error("sort-by \uC778\uC790 \uC21C\uC11C \uC624\uB958: (sort-by fn arr) \uD615\uC2DD\uC774 \uC62C\uBC14\uB985\uB2C8\uB2E4. \uD604\uC7AC \uC785\uB825: (sort-by arr fn)")}if(!Array.isArray(e[1]))return[];let l=e[0],c=e[1],m=typeof l=="string"&&c.length>0&&c[0]!==null&&typeof c[0]=="object"?d=>d!==null&&typeof d=="object"?d[l]:null:d=>u(l,[d]);return[...c].sort((d,g)=>{let h=m(d),y=m(g);return typeof h=="number"&&typeof y=="number"?h-y:String(h).localeCompare(String(y))})}case"zip":{let l=Array.isArray(e[0])?e[0]:[],c=Array.isArray(e[1])?e[1]:[],p=Math.min(l.length,c.length);return Array.from({length:p},(m,d)=>[l[d],c[d]])}case"zip-with":{let l=e[0],c=Array.isArray(e[1])?e[1]:[],p=Array.isArray(e[2])?e[2]:[],m=Math.min(c.length,p.length),d=r?.callFunctionValue?.bind(r);return d?Array.from({length:m},(g,h)=>d(l,[c[h],p[h]])):[]}case"cache-create":{let l=typeof e[0]=="number"?Math.max(1,e[0]):100;return Fc(l)}case"cache-set":{let l=e[0]&&e[0].kind==="cache",c=l?e[0]:On,p=String(l?e[1]:e[0]),m=l?e[2]:e[1],d=l?e[3]:e[2],g=typeof d=="number"?l?d:d*1e3:null;return c.map.has(p)?c.map.delete(p):qf(c),c.map.set(p,{value:m,expires:g!==null?Date.now()+g:null}),!0}case"cache-get":{let l=e[0]&&e[0].kind==="cache",c=l?e[0]:On,p=String(l?e[1]:e[0]),m=c.map.get(p);return m?m.expires!==null&&Date.now()>m.expires?(c.map.delete(p),c.misses++,null):(c.map.delete(p),c.map.set(p,m),c.hits++,m.value):(c.misses++,null)}case"cache-has":{let l=e[0]&&e[0].kind==="cache",c=l?e[0]:On,p=String(l?e[1]:e[0]),m=c.map.get(p);return m?m.expires!==null&&Date.now()>m.expires?(c.map.delete(p),!1):!0:!1}case"cache-del":{let l=e[0]&&e[0].kind==="cache",c=l?e[0]:On,p=String(l?e[1]:e[0]);return c.map.delete(p)}case"cache-clear":{let c=e[0]&&e[0].kind==="cache"?e[0]:On;return c.map.clear(),c.hits=0,c.misses=0,!0}case"cache-stats":{let c=e[0]&&e[0].kind==="cache"?e[0]:On,p=c.hits+c.misses;return{size:c.map.size,hits:c.hits,misses:c.misses,"hit-rate":p>0?c.hits/p:0}}case"uuid":case"uuid4":{let{randomUUID:l}=require("crypto");return l()}case"push":return Array.isArray(e[0])?[...e[0],e[1]]:[e[1]];case"pop":return Array.isArray(e[0])&&e[0].length>0?e[0][e[0].length-1]:null;case"shift":return Array.isArray(e[0])&&e[0].length>0?e[0][0]:null;case"unshift":return Array.isArray(e[0])?[e[1],...e[0]]:[e[1]];case"typeof":return typeof e[0];case"type-of":{let l=e[0];return l==null?"nil":Array.isArray(l)?"array":typeof l=="function"||l?.kind==="function-value"||l?.kind==="closure"||l?.kind==="builtin-fn"?"function":typeof l=="object"?"map":typeof l}case"vec-dot":case"dot-product":{let l=e[0],c=e[1];if(!Array.isArray(l)||!Array.isArray(c))return 0;let p=0;for(let m=0;m<Math.min(l.length,c.length);m++)p+=(l[m]??0)*(c[m]??0);return p}case"vec-norm":case"vec-magnitude":{let l=e[0];return Array.isArray(l)?Math.sqrt(l.reduce((c,p)=>c+p*p,0)):0}case"cosine-sim":case"cosine_sim":{let l=e[0],c=e[1];if(!Array.isArray(l)||!Array.isArray(c))return 0;let p=0,m=0,d=0;for(let h=0;h<Math.min(l.length,c.length);h++)p+=(l[h]??0)*(c[h]??0),m+=(l[h]??0)**2,d+=(c[h]??0)**2;let g=Math.sqrt(m)*Math.sqrt(d);return g===0?0:p/g}case"euclidean-dist":case"vec-dist":{let l=e[0],c=e[1];if(!Array.isArray(l)||!Array.isArray(c))return 0;let p=0;for(let m=0;m<Math.min(l.length,c.length);m++){let d=(l[m]??0)-(c[m]??0);p+=d*d}return Math.sqrt(p)}case"vec-add":{let l=e[0],c=e[1];return!Array.isArray(l)||!Array.isArray(c)?[]:Array.from({length:Math.min(l.length,c.length)},(p,m)=>(l[m]??0)+(c[m]??0))}case"vec-scale":{let l=e[0],c=Number(e[1]??1);return Array.isArray(l)?l.map(p=>p*c):[]}case"vec-normalize":{let l=e[0];if(!Array.isArray(l))return[];let c=Math.sqrt(l.reduce((p,m)=>p+m*m,0));return c===0?l:l.map(p=>p/c)}case"vec-top-k":{let l=e[0],c=e[1],p=Number(e[2]??5);return!Array.isArray(l)||!Array.isArray(c)?[]:c.map((d,g)=>{let h=Array.isArray(d)?d:d?.vector??d?.embedding??[],y=0,k=0,v=0;for(let M=0;M<Math.min(l.length,h.length);M++)y+=(l[M]??0)*(h[M]??0),k+=(l[M]??0)**2,v+=(h[M]??0)**2;let $=Math.sqrt(k)*Math.sqrt(v);return{score:$===0?0:y/$,index:g,data:d}}).sort((d,g)=>g.score-d.score).slice(0,p)}case"assert-type":{let l=e[0],c=String(e[1]),p=typeof l;if(Array.isArray(l)?p="array":l===null?p="null":l instanceof Map&&(p="map"),p!==c)throw new Error(`Type assertion failed: expected '${c}', got '${p}' (value: ${JSON.stringify(l)})`);return l}case"num":return Number(e[0]);case"bool":return!!e[0];case"math-abs":case"math_abs":case"abs":return Math.abs(e[0]);case"min":return Math.min(...e.filter(l=>typeof l=="number"));case"max":return Math.max(...e.filter(l=>typeof l=="number"));case"floor":return Math.floor(e[0]);case"ceil":return Math.ceil(e[0]);case"round":return Math.round(e[0]);case"quot":return Math.trunc(Number(e[0])/Number(e[1]));case"rem":return Number(e[0])-Math.trunc(Number(e[0])/Number(e[1]))*Number(e[1]);case"int":return Math.trunc(Number(e[0]));case"sorted?":{let l=e[0];if(!Array.isArray(l)||l.length<=1)return!0;for(let c=1;c<l.length;c++)if(l[c]<l[c-1])return!1;return!0}case"math-sqrt":case"math_sqrt":case"sqrt":return Math.sqrt(e[0]);case"pow":return Math.pow(e[0],e[1]);case"log":return Math.log(e[0]);case"exp":return Math.exp(e[0]);case"sin":return Math.sin(e[0]);case"cos":return Math.cos(e[0]);case"tan":return Math.tan(e[0]);case"random":case"rand":return Math.random();case"rand-int":return e.length>=2?Math.floor(Math.random()*(Number(e[1])-Number(e[0])))+Number(e[0]):Math.floor(Math.random()*Number(e[0]));case"clamp":return Math.max(e[1],Math.min(e[2],e[0]));case"ok":return qt(e[0]);case"err":{if(e.length>=2){let l=String(e[0]??"ERR"),c=String(e[1]??""),p=e[2];return hn(l,c,p?{category:p}:void 0)}return hn("ERR",String(e[0]??""))}case"some":if(typeof e[0]=="function"||e[0]&&(e[0].kind==="function-value"||e[0].kind==="closure")){let l=e[0],c=Array.isArray(e[1])?e[1]:[];return typeof l=="function"?c.some(l):c.some(p=>u(l,[p]))}return{tag:"Some",value:e[0],kind:"Option"};case"every?":{let l=e[0],c=Array.isArray(e[1])?e[1]:[];return typeof l=="function"?c.every(l):c.every(p=>u(l,[p]))}case"any?":{let l=e[0],c=Array.isArray(e[1])?e[1]:[];return typeof l=="function"?c.some(l):c.some(p=>u(l,[p]))}case"none":return{tag:"None",value:null,kind:"Option"};case"pure":return{tag:"Pure",value:e[0],kind:"Monad"};case"left":return{tag:"Left",value:e[0],kind:"Either"};case"right":return{tag:"Right",value:e[0],kind:"Either"};case"failure":return{tag:"Failure",value:Array.isArray(e[0])?e[0]:[e[0]],kind:"Validation"};case"success":return{tag:"Success",value:e[0],kind:"Validation"};case"tell":return{kind:"Writer",value:null,log:String(e[0])};case"return-writer":case"pure-writer":return{kind:"Writer",value:e[0],log:""};case"bind":{if(n.args.length<2)throw new Error("bind requires monad and transform function");let l=a(n.args[0]),c=a(n.args[1]);if(l.kind==="Result")return l.tag==="Ok"?i(c,[l.value]):l;if(l.kind==="Option")return l.tag==="Some"?i(c,[l.value]):l;if(Array.isArray(l)){let p=[];for(let m of l){let d=i(c,[m]);Array.isArray(d)?p=p.concat(d):p.push(d)}return p}if(l.kind==="Either")return l.tag==="Right"?i(c,[l.value]):l;if(l.kind==="Validation"){if(l.tag==="Success"){let p=i(c,[l.value]);return p.kind==="Validation"&&p.tag==="Failure",p}return l}if(l.kind==="Writer"){let p=i(c,[l.value]);return p.kind==="Writer"?{kind:"Writer",value:p.value,log:l.log+p.log}:p}throw new Error("bind: unsupported monad type")}case"lazy-seq":{let l=e[0],c=e.length>1?e[1]:null;return gn(()=>l,()=>Re(c)?c:null)}case"iterate":{let l=e[0],c=e[1],p=d=>i(l,[d]),m=d=>gn(()=>d,()=>m(p(d)));return m(c)}case"range":{if(e.length===0)return Ea(0);let l=e.length===1?0:Number(e[0]),c=e.length===1?Number(e[0]):Number(e[1]),p=e.length>=3?Number(e[2]):1,m=[];if(p>0)for(let d=l;d<c;d+=p)m.push(d);else if(p<0)for(let d=l;d>c;d+=p)m.push(d);return m}case"take":{if(Array.isArray(e[0])&&typeof e[1]=="number")throw new Error("take \uC778\uC790 \uC21C\uC11C \uC624\uB958: (take n coll) \uD615\uC2DD\uC774 \uC62C\uBC14\uB985\uB2C8\uB2E4. \uD604\uC7AC \uC785\uB825: (take coll n)");let l=e[0],c=e[1];return es(l,Re(c)||Array.isArray(c)?c:null)}case"drop":{if(Array.isArray(e[0])&&typeof e[1]=="number")throw new Error("drop \uC778\uC790 \uC21C\uC11C \uC624\uB958: (drop n coll) \uD615\uC2DD\uC774 \uC62C\uBC14\uB985\uB2C8\uB2E4. \uD604\uC7AC \uC785\uB825: (drop coll n)");let l=e[0],c=e[1];return Array.isArray(c)?c.slice(l):Go(l,Re(c)?c:null)}case"filter-lazy":{let l=e[0],c=e[1],p=d=>!!i(l,[d]),m=d=>{if(!d)return null;let g=d;for(;g&&!p(bt(g));)g=rt(g);if(!g)return null;let h=bt(g),y=rt(g);return gn(()=>h,()=>m(y))};return m(Re(c)?c:null)}case"map-lazy":{let l=e[0],c=e[1],p=m=>{if(!m)return null;let d=bt(m);return gn(()=>i(l,[d]),()=>p(rt(m)))};return p(Re(c)?c:null)}case"take-while":{let l=e[0],c=e[1];if(Array.isArray(c)){let m=[];for(let d of c){if(!i(l,[d]))break;m.push(d)}return m}return(m=>{let d=[],g=m;for(;g;){let h=bt(g);if(!i(l,[h]))break;d.push(h),g=rt(g)}return d})(Re(c)?c:null)}case"drop-while":{let l=e[0],c=e[1];if(!Array.isArray(c))return[];let p=0;for(;p<c.length&&u(l,[c[p]]);)p++;return c.slice(p)}case"map-indexed":{let l=e[0],c=e[1];return Array.isArray(c)?c.map((p,m)=>u(l,[m,p])):[]}case"reduce-kv":{let l=e[0],c=e[1],p=e[2];if(p==null||typeof p!="object"||Array.isArray(p))return c;let m=c;for(let[d,g]of Object.entries(p))m=u(l,[m,d,g]);return m}case"lazy-head":return Re(e[0])?bt(e[0]):null;case"lazy-tail":return Re(e[0])?rt(e[0]):null;case"lazy?":return Re(e[0]);case"ctx-new":{let l=typeof e[0]=="number"?e[0]:4096;return new ts(l)}case"ctx-add":{let l=e[0],c=e[1],p={};for(let m=2;m<n.args.length-1;m++){let d=n.args[m];if(d.kind==="keyword"){let g=d.name,h=e[m];g==="priority"?p.priority=Number(h):g==="tags"?p.tags=Array.isArray(h)?h:[String(h)]:g==="tokens"&&(p.tokens=Number(h))}}return l.add(c,p)}case"ctx-get":return e[0].get(String(e[1]))??null;case"ctx-remove":return e[0].remove(String(e[1])),null;case"ctx-trim":return e[0].trim();case"ctx-stats":return e[0].stats();case"ctx-has-room?":return e[0].hasRoom(Number(e[1]));case"ctx-all":{let l=e[0],c=e.length>1?String(e[1]):void 0;return l.getAll(c)}case"ok?":return Ut(e[0]);case"err?":return yn(e[0]);case"unwrap":return Ko(e[0]);case"unwrap-or":return Jo(e[0],e[1]);case"map-ok":{let l=e[0],c=e[1];return Xo(l,p=>i(c,[p]))}case"map-err":{let l=e[0],c=e[1];return Yo(l,p=>i(c,[p]))}case"flat-map":{let l=e[0],c=e[1];if(Array.isArray(c)){let p=[];for(let m of c){let d=u(l,[m]);Array.isArray(d)?p.push(...d):d!=null&&p.push(d)}return p}return Qo(c,p=>i(l,[p]))}case"recover":{let l=e[0],c=e[1];return Zo(l,p=>i(c,[p]))}case"result-explain":{let l=e[0];return yn(l)?bn.explain(l):"(Ok \uAC12 \u2014 \uC5D0\uB7EC \uC5C6\uC74C)"}case"result-classify":{let l=e[0];return l instanceof Error?bn.classify(l):typeof l=="string"?bn.classify(new Error(l)):l}case"mem-remember":{let l=String(e[0]),c=e[1];return xe.remember(l,c,{scope:"long-term",ttl:"forever"}),null}case"mem-remember-short":{let l=String(e[0]),c=e[1],p=typeof e[2]=="number"?e[2]:6e4;return xe.remember(l,c,{scope:"short-term",ttl:p}),null}case"mem-recall":{let l=String(e[0]),c=e.length>1?e[1]:null;return xe.recall(l,c)}case"mem-forget":{let l=String(e[0]);return xe.forget(l)}case"mem-episode":{let l=String(e[0]),c=String(e[1]),p=e[2]??{},m=e[3];return xe.recordEpisode(l,c,p,m)}case"mem-search-episodes":{let l=String(e[0]);return xe.searchEpisodes(l)}case"mem-working-set":return xe.setWorking(e[0]),null;case"mem-working-get":return xe.getWorking();case"mem-working-clear":return xe.clearWorking(),null;case"mem-keys":{let l=e.length>0?String(e[0]):void 0;return xe.keys(l)}case"mem-stats":return xe.stats();case"mem-purge":return xe.purgeExpired();case"mem-search-tag":{let l=String(e[0]);return xe.searchByTag(l)}case"use-tool":{let l=String(e[0]),c=e[1]&&typeof e[1]=="object"&&!Array.isArray(e[1])?e[1]:{},p=Te.executeSync(l,c);if(!p.success)throw new Error(p.error||`Tool failed: ${l}`);return p.output}case"list-tools":return Te.listAll().map(l=>l.name);case"rag-add":{let l=String(e[0]),c=String(e[1]),p=e[2]&&typeof e[2]=="object"?e[2]:void 0;return kn.add({id:l,content:c,metadata:p}),!0}case"rag-retrieve":{let l=String(e[0]),c=typeof e[1]=="number"?e[1]:3;return kn.retrieve(l,c).map(m=>({id:m.id,content:m.content,score:m.score??0}))}case"rag-query":{let l=String(e[0]),c=typeof e[1]=="number"?e[1]:3;return kn.query(l,{topK:c}).augmented}case"rag-size":return kn.size();case"rag-remove":{let l=String(e[0]);return kn.remove(l)}case"agent-spawn":{let l=String(e[0]),c=e[1],p=(m,d)=>i(c,[m,d]);return st.spawn(l,p)}case"agent-send":{let l=String(e[0]),c=String(e[1]),p=e[2];return st.send(l,c,p)}case"agent-broadcast":{let l=String(e[0]),c=e[1];return st.broadcast(l,c)}case"agent-recv":{let l=String(e[0]);return st.recv(l)}case"agent-process":{let l=String(e[0]);return st.process(l)}case"agent-list":return st.list();case"agent-history":return st.history();case"agent-inbox-size":{let l=String(e[0]);return st.inboxSize(l)}case"try-reason":{let l=e[0];if(!Array.isArray(l))throw new Error("try-reason: attempts must be a list");let c=l.map(p=>{if(Array.isArray(p)&&p.length===2){let[m,d]=p;return[String(m),()=>typeof d=="function"?d():d&&d.kind==="function-value"?i(d,[]):d]}throw new Error("try-reason: each attempt must be [strategy fn]")});return tc(c)}case"quality-check":{let l=e[0],c=e.length>1?Number(e[1]):.7;return rs(l,ss,c).score}case"quality-passed?":{let l=e[0],c=e.length>1?Number(e[1]):.7;return rs(l,ss,c).passed}case"quality-feedback":{let l=e[0];return rs(l,ss,.7).feedback}case"stream-create":{let{id:l}=ac();return l}case"stream-write":{let l=String(e[0]),c=String(e[1]??""),p=kt(l);if(!p)throw new Error(`stream-write: stream not found: ${l}`);return p.write(c),null}case"stream-end":{let l=String(e[0]),c=kt(l);if(!c)throw new Error(`stream-end: stream not found: ${l}`);return c.end(),null}case"stream-collect":{let l=String(e[0]),c=kt(l);if(!c)throw new Error(`stream-collect: stream not found: ${l}`);return c.collect()}case"stream-done?":{let l=String(e[0]),c=kt(l);return c?c.isDone():!0}case"stream-chunks":{let l=String(e[0]),c=kt(l);if(!c)throw new Error(`stream-chunks: stream not found: ${l}`);return c.getChunks()}case"stream-chunk-count":{let l=String(e[0]),c=kt(l);if(!c)throw new Error(`stream-chunk-count: stream not found: ${l}`);return c.chunkCount()}case"stream-text":{let l=String(e[0]),c=String(e[1]??""),p=kt(l);if(!p)throw new Error(`stream-text: stream not found: ${l}`);return sc(p,c,0)}case"stream-delete":{let l=String(e[0]);return ic(l)}case"try-with-fallback":{let l=e[0],c=e[1];return nc(()=>typeof l=="function"?l():l&&l.kind==="function-value"?i(l,[]):l,c)}case"fl-learn":{let l=String(e[0]??"");return Qn.lessonMarkdown(l)}case"fl-examples":{let l=String(e[0]??"");return Qn.findByTag(l).map(p=>`${p.concept}: ${p.description}`).join(`
251
+ `)}case"fl-example-count":return Qn.size();case"fl-concepts":return Qn.concepts().join(" ");case"trace-create":{let l=String(e[0]??"trace"),{id:c}=cc(l);return c}case"trace-add":{let l=String(e[0]??""),c=String(e[1]??"thought"),p=String(e[2]??""),m=e.length>=4?e[3]:void 0,d=Vt(l);return d&&d.add(c,p,m),null}case"trace-enter":{let l=String(e[0]??""),c=String(e[1]??"thought"),p=String(e[2]??""),m=e.length>=4?e[3]:void 0,d=Vt(l);return d&&d.enter(c,p,m),null}case"trace-exit":{let l=String(e[0]??""),c=e.length>=2?e[1]:void 0,p=Vt(l);return p&&p.exit(c),null}case"trace-markdown":{let l=String(e[0]??""),c=Vt(l);return c?c.toMarkdown():""}case"trace-tree":{let l=String(e[0]??""),c=Vt(l);return c?c.toTree():""}case"trace-node-count":{let l=String(e[0]??""),c=Vt(l);return c?c.nodeCount():0}case"prompt-compile":{let l=String(e[0]??"COT"),c=String(e[1]??""),p=Zn.compileBlock(l,{}),m=p?[p]:[{name:"default",content:"",priority:.5}];return Zn.compile(m,c).prompt}case"prompt-tokens":{let l=String(e[0]??"");return Math.ceil(l.length/4)}case"prompt-target":{let l=String(e[0]??"claude");return Zn.setTarget(l),l}case"prompt-from-code":{let l=String(e[0]??""),c=String(e[1]??"");return Zn.compileFromCode(l,c).prompt}case"sdk-version":return vn.version;case"sdk-features":return[...vn.features];case"sdk-supports":{let l=String(e[0]??"");return vn.supports(l)}case"sdk-snippet":{let l=String(e[0]??"");return vn.snippet(l)}case"sdk-validate":{let l=String(e[0]??"");return vn.validate(l).valid}case"maybe-map":{let[l,c]=e;return uc(l,p=>u(c,[p]))}case"maybe-bind":{let[l,c]=e;return pc(l,p=>u(c,[p]))}case"maybe-chain":{let[l,c]=e,p=Array.isArray(l)?l:[l];return fc(p,(...m)=>u(c,m))}case"maybe-filter":{let[l,c]=e;return mc(l,p=>u(c,[p]))}case"maybe-combine":{let[l,c,p]=e;return dc(l,c,(m,d)=>u(p,[m,d]))}case"maybe-select":{let l=Array.isArray(e[0])?e[0]:e;return gc(l)}default:{if(r.context.functions.has(t))return o(t,e);let l=t.match(/^([\w\-]+)\[([^\]]+)\]$/);if(l&&r.context.functions.has(l[1]))return o(t,e);if(r.context.variables.has(t)){let c=r.context.variables.get(t);if(c.kind==="builtin-function")return c.fn(e.map(p=>a(p)));if(typeof c=="function"||c.kind==="function-value")return i(c,e)}if(t==="hypothesis"){let[c,p,m]=e,d={claim:String(c),test:h=>typeof p=="function"?p(h):p?.kind==="function-value"?i(p,[h]):null,evaluate:h=>typeof m=="function"?m(h):m?.kind==="function-value"?i(m,[h]):0};return as.test(d).verdict}if(t==="hypothesis-confidence"){let[c,p,m]=e,d={claim:String(c),test:h=>typeof p=="function"?p(h):p?.kind==="function-value"?i(p,[h]):null,evaluate:h=>typeof m=="function"?m(h):m?.kind==="function-value"?i(m,[h]):0};return as.test(d).confidence}if(t==="hypothesis-compete"){let c=e[0];if(!Array.isArray(c)||c.length===0)return null;let p=c.map(d=>{let[g,h,y]=Array.isArray(d)?d:[d,()=>null,()=>0];return{claim:String(g),test:k=>typeof h=="function"?h(k):h?.kind==="function-value"?i(h,[k]):null,evaluate:k=>typeof y=="function"?y(k):y?.kind==="function-value"?i(y,[k]):0}});return as.compete(p).claim}if(t==="debate"){let[c,p,m]=e;return os.debate({proposition:String(c),pro:(g,h)=>typeof p=="function"?p(g,h):p?.kind==="function-value"?i(p,[g,h]):{side:"pro",point:String(p),strength:.5},con:(g,h)=>typeof m=="function"?m(g,h):m?.kind==="function-value"?i(m,[g,h]):{side:"con",point:String(m),strength:.5}}).winner}if(t==="debate-score"){let[c,p,m]=e,d=os.debate({proposition:String(c),pro:(g,h)=>typeof p=="function"?p(g,h):p?.kind==="function-value"?i(p,[g,h]):{side:"pro",point:String(p),strength:.5},con:(g,h)=>typeof m=="function"?m(g,h):m?.kind==="function-value"?i(m,[g,h]):{side:"con",point:String(m),strength:.5}});return{pro:d.proScore,con:d.conScore}}if(t==="debate-conclusion"){let[c,p,m]=e;return os.debate({proposition:String(c),pro:(g,h)=>typeof p=="function"?p(g,h):p?.kind==="function-value"?i(p,[g,h]):{side:"pro",point:String(p),strength:.5},con:(g,h)=>typeof m=="function"?m(g,h):m?.kind==="function-value"?i(m,[g,h]):{side:"con",point:String(m),strength:.5}}).conclusion}if(t==="cp-save"){let[c,p]=e;return zt.save(String(c),p),null}if(t==="cp-restore"){let[c]=e;return zt.restore(String(c))}if(t==="cp-branch"){let[c,p,m]=e,d=zt.branch(String(c),p,g=>{if(typeof m=="function")return m(g);if(typeof m=="string")return o(m,[g]);if(m?.kind==="function-value"||m?.kind==="async-function-value")return u(m,[g]);if(m?.params&&m?.body)return u({kind:"function-value",...m},[g]);throw new Error(`cp-branch: fn must be callable, got ${typeof m} ${m?.kind??""}`)});return d.success?d.result:d.restored}if(t==="cp-drop"){let[c]=e;return zt.drop(String(c))}if(t==="cp-list")return zt.list();if(t==="cp-versions"){let[c]=e;return zt.versions(String(c))}if(t==="meta-reason"){let c=String(e[0]??"");return cs.analyze(c).selected}if(t==="meta-reason-scores"){let c=String(e[0]??""),p=cs.analyze(c),m={};for(let d of p.scores)m[d.strategy]=d.score;return m}if(t==="meta-reason-rationale"){let c=String(e[0]??"");return cs.analyze(c).rationale}if(t==="belief-set"){let[c,p]=e;return Ge.set(String(c),Number(p)),null}if(t==="belief-get"){let[c]=e;return Ge.get(String(c))}if(t==="belief-update"){let[c,p]=e;return Ge.update(String(c),Number(p))}if(t==="belief-negate"){let[c]=e;return Ge.negate(String(c))}if(t==="belief-list")return Ge.list();if(t==="belief-certain"){let c=e.length>0?Number(e[0]):.8;return Ge.certain(c)}if(t==="belief-strongest"){let c=Ge.strongest();return c?c.claim:null}if(t==="belief-forget"){let[c]=e;return Ge.forget(String(c))}if(t==="belief-size")return Ge.size();if(t==="analogy-store"){let[c,p,m]=e,d=Array.isArray(m)?m.map(String):[];return wt.store(String(c),p,d).id}if(t==="analogy-find"){let[c,p]=e;return wt.find(String(c),p!=null?Number(p):3).map(d=>d.description)}if(t==="analogy-best"){let[c]=e,p=wt.best(String(c));return p?p.solution:null}if(t==="analogy-by-tag"){let[c]=e;return wt.byTag(String(c)).map(m=>m.description)}if(t==="analogy-popular"){let[c]=e;return wt.popular(c!=null?Number(c):3).map(m=>m.description)}if(t==="analogy-size")return wt.size();if(t==="analogy-all")return wt.all().map(c=>c.description);if(t==="critique"){let[c]=e;return cr.run(c,{finders:Wt}).approved}if(t==="critique-points"){let[c]=e;return cr.run(c,{finders:Wt}).points.map(m=>m.description)}if(t==="critique-risk"){let[c]=e;return cr.run(c,{finders:Wt}).overallRisk}if(t==="critique-summary"){let[c]=e;return cr.run(c,{finders:Wt}).summary}if(t==="compose-reason"){let[c,p]=e;if(!Array.isArray(c))return p;let m=c.map(g=>{if(!Array.isArray(g))return{name:String(g),fn:$=>$};let[h,y,k]=g,v={name:String(h),fn:typeof y=="function"?y:$=>$};return typeof k=="function"&&(v.condition=k),v});return ls.compose(m,p).output}if(t==="compose-history"){let[c,p]=e;if(!Array.isArray(c))return[];let m=c.map(g=>{if(!Array.isArray(g))return{name:String(g),fn:$=>$};let[h,y,k]=g,v={name:String(h),fn:typeof y=="function"?y:$=>$};return typeof k=="function"&&(v.condition=k),v});return ls.compose(m,p).history.map(g=>g.name)}if(t==="compose-steps"){let[c,p]=e;if(!Array.isArray(c))return 0;let m=c.map(g=>{if(!Array.isArray(g))return{name:String(g),fn:$=>$};let[h,y,k]=g,v={name:String(h),fn:typeof y=="function"?y:$=>$};return typeof k=="function"&&(v.condition=k),v});return ls.compose(m,p).steps}if(t==="cognition-solve"){let[c,p]=e,m=_n.solve(String(c),(d,g)=>typeof p=="function"?p(d,g):p?.kind==="function-value"?i(p,[d,g]):p);return new Map([["strategy",m.strategy],["output",m.output],["approved",m.approved],["risk",m.risk]])}if(t==="cognition-stats"){let c=_n.stats();return new Map([["beliefs",c.beliefs],["analogies",c.analogies],["checkpoints",c.checkpoints]])}if(t==="cognition-meta"){let[c]=e;return _n.meta.analyze(String(c)).selected}if(t==="cognition-believe"){let[c,p]=e;return _n.beliefs.set(String(c),Number(p)),null}if(t==="cognition-recall"){let[c]=e,p=_n.analogies.best(String(c));return p?p.solution:null}{let c=function(p){return Array.isArray(p)?p.map(m=>Array.isArray(m)?{agentId:String(m[0]),answer:m[1],confidence:Number(m[2])}:m):[]};if(t==="consensus-majority"){let p=c(e[0]);return Sn.majority(p).answer}if(t==="consensus-weighted"){let p=c(e[0]);return Sn.weighted(p).answer}if(t==="consensus-threshold"){let p=c(e[0]),m=e[1]!==void 0?Number(e[1]):.7,d=Sn.threshold(p,m);return d?d.answer:null}if(t==="consensus-agreement"){let p=c(e[0]);return Sn.agreement(p)}}{let c=function(m){return Array.isArray(m)?m.map(d=>{if(Array.isArray(d)){let g=String(d[0]),h=Array.isArray(d[1])?d[1].map(String):[],y=d[2]&&typeof d[2]=="object"&&!Array.isArray(d[2])?d[2]:void 0;return{voterId:g,choices:h,scores:y}}return d}):[]},p=function(m){return Array.isArray(m)?m.map(String):[]};if(t==="vote-plurality"){let m=c(e[0]),d=p(e[1]);return $n.plurality(m,d).winner}if(t==="vote-approval"){let m=c(e[0]),d=p(e[1]);return $n.approval(m,d).winner}if(t==="vote-score"){let m=c(e[0]),d=p(e[1]);return $n.score(m,d).winner}if(t==="vote-tally"){let m=c(e[0]),d=p(e[1]),g=$n.tally(m,d);return new Map(Object.entries(g))}}if(t==="negotiate"){let[c]=e;if(!Array.isArray(c))return!1;let p=c.map(d=>Array.isArray(d)?{agentId:String(d[0]),offer:Number(d[1]),minAccept:Number(d[2]),maxOffer:Number(d[3]),flexibility:Number(d[4])}:d);return fr.negotiate(p).agreed}if(t==="negotiate-value"){let[c]=e;if(!Array.isArray(c))return null;let p=c.map(d=>Array.isArray(d)?{agentId:String(d[0]),offer:Number(d[1]),minAccept:Number(d[2]),maxOffer:Number(d[3]),flexibility:Number(d[4])}:d),m=fr.negotiate(p);return m.agreed?m.value??null:null}if(t==="negotiate-rounds"){let[c]=e;if(!Array.isArray(c))return 0;let p=c.map(d=>Array.isArray(d)?{agentId:String(d[0]),offer:Number(d[1]),minAccept:Number(d[2]),maxOffer:Number(d[3]),flexibility:Number(d[4])}:d);return fr.negotiate(p).rounds.length}if(t==="swarm-optimize"){let[c,p,m]=e,d=typeof c=="function"?c:h=>u(c,[h]);return gr.optimize({objective:d,particles:p!==void 0?Number(p):10,iterations:m!==void 0?Number(m):50}).bestPosition}if(t==="swarm-best-score"){let[c,p,m]=e,d=typeof c=="function"?c:h=>u(c,[h]);return gr.optimize({objective:d,particles:p!==void 0?Number(p):10,iterations:m!==void 0?Number(m):50}).bestScore}if(t==="swarm-converged?"){let[c]=e,p=typeof c=="function"?c:d=>u(c,[d]);return gr.optimize({objective:p}).converged}if(t==="compete-register"){let[c,p]=e,m={id:String(c),solve:d=>i(p,[d])};return Gt.register(m),null}if(t==="compete"){let[c,p]=e,m=g=>Number(i(p,[g]));return Gt.run(c,m).winner?.agentId??null}if(t==="compete-score"){let[c,p]=e,m=g=>Number(i(p,[g]));return Gt.run(c,m).winner?.score??null}if(t==="compete-all"){let[c,p]=e,m=g=>Number(i(p,[g]));return Gt.run(c,m).allResults.map(g=>[g.agentId,g.score,g.rank])}if(t==="compete-list")return Gt.list();if(t==="peer-review-add"){let[c,p]=e,m=String(c),d={id:m,review:g=>{let h=u(p,[g]);return h&&typeof h=="object"?{reviewerId:m,aspect:String(h.aspect??"quality"),score:Number(h.score??.5),comment:String(h.comment??""),suggestion:h.suggestion!==void 0?String(h.suggestion):void 0}:{reviewerId:m,aspect:"quality",score:.5,comment:String(h??"")}}};return Ht.addReviewer(d),null}if(t==="peer-review"){let[c,p]=e;return Ht.review(String(c),p).approved}if(t==="peer-review-score"){let[c,p]=e;return Ht.review(String(c),p).averageScore}if(t==="peer-review-comments"){let[c,p]=e;return Ht.review(String(c),p).comments}if(t==="peer-review-list")return Ht.list();if(t==="chain-agents"){let[c,p]=e;if(!Array.isArray(c))return p;let m=c.map(h=>{if(typeof h=="object"&&h!==null&&typeof h.transform=="function")return h;if(Array.isArray(h)){let[y,k,v]=h;return{id:String(y),transform:$=>i(k,[$]),validate:v?$=>!!i(v,[$]):void 0}}return{id:String(h),transform:y=>y}});return Ke.from(m).run(p).finalOutput}if(t==="chain-links"){let[c,p]=e;if(!Array.isArray(c))return[];let m=c.map(h=>{if(typeof h=="object"&&h!==null&&typeof h.transform=="function")return h;if(Array.isArray(h)){let[y,k,v]=h;return{id:String(y),transform:$=>i(k,[$]),validate:v?$=>!!i(v,[$]):void 0}}return{id:String(h),transform:y=>y}});return Ke.from(m).run(p).links.filter(h=>!h.skipped).map(h=>h.agentId)}if(t==="chain-steps"){let[c,p]=e;if(!Array.isArray(c))return 0;let m=c.map(h=>{if(typeof h=="object"&&h!==null&&typeof h.transform=="function")return h;if(Array.isArray(h)){let[y,k,v]=h;return{id:String(y),transform:$=>i(k,[$]),validate:v?$=>!!i(v,[$]):void 0}}return{id:String(h),transform:y=>y}});return Ke.from(m).run(p).stepsCompleted}if(t==="orchestrate-run"){let[c]=e;if(!Array.isArray(c))return{};let p=c.map(m=>Array.isArray(m)?{id:String(m[0]),input:m[1]??null,dependsOn:Array.isArray(m[2])?m[2].map(String):void 0}:{id:String(m.id??"task"),input:m.input??null,dependsOn:m.dependsOn});return us.run(p).outputs}if(t==="orchestrate-order"){let[c]=e;if(!Array.isArray(c))return[];let p=c.map(m=>Array.isArray(m)?{id:String(m[0]),input:m[1]??null,dependsOn:Array.isArray(m[2])?m[2].map(String):void 0}:{id:String(m.id??"task"),input:m.input??null,dependsOn:m.dependsOn});return us.getOrder(p)}if(t==="hub-route"){let[c,p]=e;return hr.route(String(c),p,[]).result}if(t==="hub-stats")return hr.stats();if(t==="hub-systems")return hr.systems();if(t==="hub-task-types")return hr.taskTypes();if(t==="delegate-register"){let[c,p,m]=e,d=Array.isArray(p)?p.map(String):[],g={id:String(c),capabilities:d,execute:h=>typeof m=="function"?m(h):m?.kind==="function-value"?i(m,[h]):m};return An.register(g),String(c)}if(t==="delegate"){let[c,p,m]=e,d={id:`task-${Date.now()}`,description:String(c),input:p,requiredCapability:m!=null?String(m):void 0},g=An.delegate(d);return new Map([["taskId",g.taskId],["agentId",g.agentId],["output",g.output],["success",g.success],["duration",g.duration]])}if(t==="delegate-all"){let[c]=e,p=Array.isArray(c)?c.map((d,g)=>({id:d instanceof Map?String(d.get("id")??`task-${g}`):`task-${g}`,description:d instanceof Map?String(d.get("description")??""):String(d),input:d instanceof Map?d.get("input"):d,requiredCapability:d instanceof Map&&d.has("requiredCapability")?String(d.get("requiredCapability")):void 0})):[],m=An.delegateAll(p);return new Map([["results",m.results.map(d=>new Map([["taskId",d.taskId],["agentId",d.agentId],["output",d.output],["success",d.success],["duration",d.duration]]))],["successful",m.successful],["failed",m.failed],["totalDuration",m.totalDuration]])}if(t==="delegate-list")return An.list();if(t==="crossover-single"){let[c,p]=e,m=Array.isArray(c)?c:[c],d=Array.isArray(p)?p:[p],g=_t.singlePoint(m,d);return new Map([["parent1",g.parent1],["parent2",g.parent2],["child1",g.child1],["child2",g.child2],["crossoverPoint",g.crossoverPoint],["type",g.type]])}if(t==="crossover-two"){let[c,p]=e,m=Array.isArray(c)?c:[c],d=Array.isArray(p)?p:[p],g=_t.twoPoint(m,d);return new Map([["parent1",g.parent1],["parent2",g.parent2],["child1",g.child1],["child2",g.child2],["crossoverPoints",g.crossoverPoints],["type",g.type]])}if(t==="crossover-uniform"){let[c,p]=e,m=Array.isArray(c)?c:[c],d=Array.isArray(p)?p:[p],g=_t.uniform(m,d);return new Map([["parent1",g.parent1],["parent2",g.parent2],["child1",g.child1],["child2",g.child2],["type",g.type]])}if(t==="crossover-arithmetic"){let c,p=[...e],m=p.findIndex(v=>v==="alpha"||v===":alpha");m!==-1&&(c=Number(p[m+1]),p.splice(m,2));let[d,g]=p,h=Array.isArray(d)?d.map(Number):[Number(d)],y=Array.isArray(g)?g.map(Number):[Number(g)],k=_t.arithmetic(h,y,c);return new Map([["parent1",k.parent1],["parent2",k.parent2],["child1",k.child1],["child2",k.child2],["type",k.type]])}if(t==="crossover-strings"){let[c,p]=e,m=_t.crossoverStrings(String(c),String(p));return new Map([["parent1",m.parent1],["parent2",m.parent2],["child1",m.child1],["child2",m.child2],["crossoverPoint",m.crossoverPoint],["type",m.type]])}if(t==="crossover-objects"){let[c,p]=e,m=c instanceof Map?Object.fromEntries(c.entries()):typeof c=="object"&&c!==null?c:{},d=p instanceof Map?Object.fromEntries(p.entries()):typeof p=="object"&&p!==null?p:{},g=_t.crossoverObjects(m,d),h=y=>new Map(Object.entries(y));return new Map([["parent1",h(g.parent1)],["parent2",h(g.parent2)],["child1",h(g.child1)],["child2",h(g.child2)],["type",g.type]])}if(t==="crossover-children"){let[c]=e;return c instanceof Map?[c.get("child1"),c.get("child2")]:[]}if(t==="blend"){let c=.5,p=[...e],m=p.findIndex(h=>h==="alpha"||h===":alpha");m!==-1&&(c=Number(p[m+1]),p.splice(m,2));let[d,g]=p;return Array.isArray(d)&&Array.isArray(g)?_t.arithmetic(d.map(Number),g.map(Number),c).child1:typeof d=="number"&&typeof g=="number"?c*d+(1-c)*g:d}if(t==="export")return null;if(t==="call"&&e.length>=1){let c=a(e[0]),p=e.slice(1);return typeof c=="string"?o(c,p):typeof c=="function"||c?.kind==="function-value"?i(c,p):null}if(t==="evolve-numbers"){let c=Array.isArray(e[0])?e[0].map(Number):[0],p=20,m=50;for(let g=1;g<e.length-1;g+=2){let h=String(e[g]);h===":pop"&&(p=Number(e[g+1])),h===":gens"&&(m=Number(e[g+1]))}let d=hc(c,p,m);return new Map([["best",new Map([["genome",d.best.genome],["fitness",d.best.fitness],["generation",d.best.generation],["id",d.best.id]])],["generations",d.generations],["converged",d.converged],["history",d.history.map(g=>new Map([["gen",g.gen],["bestFitness",g.bestFitness],["avgFitness",g.avgFitness]]))]])}if(t==="evolve-strings"){let c=String(e[0]??""),p=30,m=100;for(let g=1;g<e.length-1;g+=2){let h=String(e[g]);h===":pop"&&(p=Number(e[g+1])),h===":gens"&&(m=Number(e[g+1]))}let d=yc(c,p,m);return new Map([["best",new Map([["genome",d.best.genome],["fitness",d.best.fitness],["generation",d.best.generation],["id",d.best.id]])],["generations",d.generations],["converged",d.converged],["history",d.history.map(g=>new Map([["gen",g.gen],["bestFitness",g.bestFitness],["avgFitness",g.avgFitness]]))]])}if(t==="evolve-config"){let c=20,p=50,m=.1,d=.1,g=null;for(let h=0;h<e.length-1;h+=2){let y=String(e[h]);y===":pop"&&(c=Number(e[h+1])),y===":gens"&&(p=Number(e[h+1])),y===":mutation"&&(m=Number(e[h+1])),y===":elite"&&(d=Number(e[h+1])),y===":goal"&&(g=Number(e[h+1]))}return new Map([["populationSize",c],["maxGenerations",p],["mutationRate",m],["eliteRatio",d],["fitnessGoal",g]])}if(t==="evolve-step"){let c=e[0];if(c instanceof Je){let p=c.step();return new Map([["bestFitness",p.bestFitness],["avgFitness",p.avgFitness]])}return null}if(t==="evolve-best"){let c=e[0];if(c instanceof Je){let p=c.getBest();return p?new Map([["genome",p.genome],["fitness",p.fitness],["generation",p.generation],["id",p.id]]):null}return null}if(t==="evolve-population"){let c=e[0];return c instanceof Je?c.getPopulation().map(p=>new Map([["genome",p.genome],["fitness",p.fitness],["generation",p.generation],["id",p.id]])):[]}if(t==="evolve-run"){let c=e[0];if(c instanceof Je){let p=c.run();return new Map([["best",new Map([["genome",p.best.genome],["fitness",p.best.fitness],["generation",p.best.generation],["id",p.best.id]])],["generations",p.generations],["converged",p.converged],["history",p.history.map(m=>new Map([["gen",m.gen],["bestFitness",m.bestFitness],["avgFitness",m.avgFitness]]))]])}return null}if(t==="evolve-history"){let c=e[0];if(c instanceof Je)return c.getHistory().map(p=>new Map([["gen",p.gen],["bestFitness",p.bestFitness],["avgFitness",p.avgFitness]]));if(c instanceof Map){let p=c.get("history");if(Array.isArray(p))return p}return[]}if(t==="mutate-config"){let c={};for(let p=0;p<e.length-1;p+=2){let m=String(e[p]).replace(/^:/,""),d=e[p+1];m==="rate"?c.rate=Number(d):m==="strength"?c.strength=Number(d):m==="type"&&(c.type=String(d))}return new Map([["rate",c.rate??.1],["strength",c.strength??.1],["type",c.type??"random"]])}if(t==="mutate-numbers"){let c=Array.isArray(e[0])?e[0].map(Number):[],p={};for(let g=1;g<e.length-1;g+=2){let h=String(e[g]).replace(/^:/,""),y=e[g+1];h==="rate"?p.rate=Number(y):h==="strength"?p.strength=Number(y):h==="type"&&(p.type=String(y))}let d=new Be(p).mutateNumbers(c);return new Map([["original",d.original],["mutated",d.mutated],["mutations",d.mutations],["mutationType",d.mutationType]])}if(t==="mutate-string"){let c=String(e[0]??""),p={};for(let g=1;g<e.length-1;g+=2){let h=String(e[g]).replace(/^:/,""),y=e[g+1];h==="rate"?p.rate=Number(y):h==="strength"?p.strength=Number(y):h==="type"&&(p.type=String(y))}let d=new Be(p).mutateString(c);return new Map([["original",d.original],["mutated",d.mutated],["mutations",d.mutations],["mutationType",d.mutationType]])}if(t==="mutate-object"){let c=e[0],p=c instanceof Map?Object.fromEntries(c.entries()):typeof c=="object"&&c!==null?c:{},m={};for(let y=1;y<e.length-1;y+=2){let k=String(e[y]).replace(/^:/,""),v=e[y+1];k==="rate"?m.rate=Number(v):k==="strength"?m.strength=Number(v):k==="type"&&(m.type=String(v))}let g=new Be(m).mutateObject(p),h=y=>new Map(Object.entries(y));return new Map([["original",h(g.original)],["mutated",h(g.mutated)],["mutations",g.mutations],["mutationType",g.mutationType]])}if(t==="mutate-swap"){let c=Array.isArray(e[0])?e[0]:[],p={type:"swap",rate:.3};for(let g=1;g<e.length-1;g+=2){let h=String(e[g]).replace(/^:/,""),y=e[g+1];h==="rate"&&(p.rate=Number(y))}let d=new Be(p).swapMutation(c);return new Map([["original",d.original],["mutated",d.mutated],["mutations",d.mutations],["mutationType",d.mutationType]])}if(t==="mutate-flip"){let c=Array.isArray(e[0])?e[0].map(Number):[],p={type:"flip"};for(let g=1;g<e.length-1;g+=2){let h=String(e[g]).replace(/^:/,""),y=e[g+1];h==="rate"&&(p.rate=Number(y))}let d=new Be(p).flipMutation(c);return new Map([["original",d.original],["mutated",d.mutated],["mutations",d.mutations],["mutationType",d.mutationType]])}if(t==="mutate-select"){let c=Array.isArray(e[0])?e[0]:[],p=1;for(let d=1;d<e.length-1;d+=2){let g=String(e[d]).replace(/^:/,""),h=e[d+1];g==="n"&&(p=Number(h))}let m=c.map(d=>d instanceof Map?{value:d.get("value"),fitness:Number(d.get("fitness")??0)}:typeof d=="object"&&d!==null&&"value"in d&&"fitness"in d?{value:d.value,fitness:Number(d.fitness??0)}:{value:d,fitness:0});return bc.select(m,p)}if(t==="mutation-count"){let c=e[0];return c instanceof Map?c.get("mutations")??0:0}if(t==="generation-run"){let[c,p,m,...d]=e,g=Array.isArray(c)?c:[],h=d.length>=2&&d[0]==="max"?Number(d[1]):50,y=M=>typeof p=="function"?Number(p(M)):p?.kind==="function-value"?Number(i(p,[M])):typeof p=="string"?Number(o(p,[M])):0,k=(M,O)=>{if(typeof m=="function")return m(M,O)??M;if(m?.kind==="function-value")return i(m,[M,O])??M;if(typeof m=="string")return o(m,[M,O])??M;let C=M.map((R,E)=>({item:R,fit:O[E]}));C.sort((R,E)=>E.fit-R.fit);let P=Math.max(1,Math.floor(C.length/2)),_=C.slice(0,P).map(R=>R.item),S=[..._];for(;S.length<M.length;)S.push(_[S.length%P]);return S},$=new xt({maxGenerations:h}).run(g,y,k);return new Map([["best",$.best],["bestFitness",$.bestFitness],["totalGenerations",$.totalGenerations],["history",$.history.map(M=>new Map([["generation",M.generation],["best",M.best],["worst",M.worst],["average",M.average],["diversity",M.diversity],["elites",M.elites],["improved",M.improved]]))],["terminationReason",$.terminationReason],["improvementRatio",$.improvementRatio]])}if(t==="generation-stats"){let[c]=e;if(c instanceof Map){let p=c.get("history");return Array.isArray(p)?p:[]}return[]}if(t==="generation-best"){let[c]=e;return c instanceof Map?c.get("best")??null:null}if(t==="generation-history"){let[c]=e;if(c instanceof Map){let p=c.get("history");return Array.isArray(p)?p:[]}return[]}if(t==="generation-converged"){let[c]=e;if(c instanceof xt)return c.hasConverged();if(c instanceof Map){let p=c.get("history")??[];if(p.length<5)return!1;let m=p.slice(-5),d=m[0]instanceof Map?m[0].get("best"):m[0]?.best;return m.every(g=>{let h=g instanceof Map?g.get("best"):g?.best;return Math.abs(h-d)<1e-9})}return!1}if(t==="generation-diversity"){let[c]=e,p=Array.isArray(c)?c.map(Number):[];return new xt({maxGenerations:1}).calculateDiversity(p)}if(t==="gen-improvement"){let[c]=e;return c instanceof Map?c.get("improvementRatio")??0:0}if(t==="gen-termination"){let[c]=e;return c instanceof Map?c.get("terminationReason")??"max-generations":"max-generations"}if(t==="fitness-proximity"){let c=Number(e[0]),p=Number(e[1]),m=e[2]!==void 0?Number(e[2]):void 0,d=St.proximity(c,p,m);return new Map([["score",d.score],["rawScore",d.rawScore],["details",new Map(Object.entries(d.details))]])}if(t==="fitness-string"){let c=String(e[0]??""),p=String(e[1]??""),m=St.stringSimilarity(c,p);return new Map([["score",m.score],["rawScore",m.rawScore],["details",new Map(Object.entries(m.details))]])}if(t==="fitness-array"){let c=Array.isArray(e[0])?e[0]:[],p=Array.isArray(e[1])?e[1]:[],m=St.arrayMatch(c,p);return new Map([["score",m.score],["rawScore",m.rawScore],["details",new Map(Object.entries(m.details))]])}if(t==="fitness-multi"){let c=e[0]instanceof Map?e[0]:new Map,p=e[1]instanceof Map?e[1]:new Map,m=e[2]instanceof Map?e[2]:void 0,d={},g={},h=m?{}:void 0;c.forEach((k,v)=>{d[String(v)]=Number(k)}),p.forEach((k,v)=>{g[String(v)]=Number(k)}),m&&h&&m.forEach((k,v)=>{h[String(v)]=Number(k)});let y=St.multiObjective(d,g,h);return new Map([["score",y.score],["rawScore",y.rawScore],["details",new Map(Object.entries(y.details))]])}if(t==="fitness-constraint"){let c=e[0],m=(Array.isArray(e[1])?e[1]:[]).map(g=>typeof g=="function"?g:g?.kind==="function-value"?h=>i(g,[h]):g==="positive"||g===":positive"?h=>typeof h=="number"&&h>0:g==="negative"||g===":negative"?h=>typeof h=="number"&&h<0:g==="even"||g===":even"?h=>typeof h=="number"&&h%2===0:g==="odd"||g===":odd"?h=>typeof h=="number"&&h%2!==0:g==="zero"||g===":zero"?h=>h===0:()=>!1),d=St.constraintSatisfaction(c,m);return new Map([["score",d.score],["rawScore",d.rawScore],["details",new Map(Object.entries(d.details))]])}if(t==="fitness-rank"){let c=Array.isArray(e[0])?e[0]:[],p=e[1],m=g=>typeof p=="function"?p(g):p?.kind==="function-value"?i(p,[g]):0;return St.rank(c,m).map(g=>new Map(Object.entries(g)))}if(t==="fitness-pareto"){let c=Array.isArray(e[0])?e[0]:[],p=(Array.isArray(e[1])?e[1]:[]).map(m=>typeof m=="function"?m:m?.kind==="function-value"?d=>i(m,[d]):()=>0);return St.paretoFront(c,p)}if(t==="fitness-score"){let c=e[0];return c instanceof Map?c.get("score")??0:typeof c=="object"&&c!==null?c.score??0:Number(c)}if(t==="prune-threshold"){let[c,p,...m]=e,d=(()=>{for(let k=0;k<m.length-1;k++)if(m[k]===":min"||m[k]==="min")return Number(m[k+1]);return .5})(),g=k=>Number(i(p,[k])),h=Array.isArray(c)?c:[],y=new Pe;return pruneResultToMap(y.pruneByThreshold(h,g,d))}if(t==="prune-top-k"){let[c,p,...m]=e,d=(()=>{for(let k=0;k<m.length-1;k++)if(m[k]===":k"||m[k]==="k")return Number(m[k+1]);return 5})(),g=k=>Number(i(p,[k])),h=Array.isArray(c)?c:[],y=new Pe;return pruneResultToMap(y.pruneToTopK(h,g,d))}if(t==="prune-top-percent"){let[c,p,...m]=e,d=(()=>{for(let k=0;k<m.length-1;k++)if(m[k]===":percent"||m[k]==="percent")return Number(m[k+1]);return .3})(),g=k=>Number(i(p,[k])),h=Array.isArray(c)?c:[],y=new Pe;return pruneResultToMap(y.pruneToTopPercent(h,g,d))}if(t==="prune-diversity"){let[c,p,m,...d]=e,g=(()=>{for(let $=0;$<d.length-1;$++)if(d[$]===":min"||d[$]==="min")return Number(d[$+1]);return .2})(),h=$=>Number(i(p,[$])),y=($,M)=>Number(i(m,[$,M])),k=Array.isArray(c)?c:[],v=new Pe;return pruneResultToMap(v.pruneForDiversity(k,h,y,g))}if(t==="prune-dedup"){let[c,p]=e,m=Array.isArray(c)?c:[],d=new Pe,g=p?h=>String(i(p,[h])):void 0;return pruneResultToMap(d.dedup(m,g))}if(t==="prune-weak"){let[c,p]=e,m=h=>Number(i(p,[h])),d=Array.isArray(c)?c:[],g=new Pe;return pruneResultToMap(g.pruneWeak(d,m))}if(t==="keep-best"){let[c,p,...m]=e,d=(()=>{for(let y=0;y<m.length-1;y++)if(m[y]===":k"||m[y]==="k")return Number(m[y+1]);return 3})(),g=y=>Number(i(p,[y])),h=Array.isArray(c)?c:[];return kc(h,g,d)}if(t==="prune-stats"){let c=e[0];return c instanceof Map&&c.has("stats")?c.get("stats"):null}if(t.startsWith("refactor-")){let c=Sc(t,e);if(c!==null)return c}if(t==="version-snapshot"){let c=e[0]??null,p=String(e[1]??"snapshot"),m=[],d;for(let h=2;h<e.length-1;h+=2){let y=String(e[h]).replace(/^:/,""),k=e[h+1];y==="tags"&&Array.isArray(k)&&m.push(...k.map(String)),y==="performance"&&(d=Number(k))}let g=De.snapshot(c,p,m,d);return new Map([["id",g.id],["version",g.version],["timestamp",g.timestamp.toISOString()],["data",g.data],["description",g.metadata.description],["tags",g.metadata.tags],["performance",g.metadata.performance??null],["parentId",g.parentId??null],["diff",g.diff??null]])}if(t==="version-rollback"){let c=String(e[0]??""),p=De.rollback(c);return new Map([["success",p.success],["reason",p.reason??null],["previousId",p.previous?.id??null],["restoredId",p.restored?.id??null]])}if(t==="version-prev"){let c=De.rollbackPrev();return new Map([["success",c.success],["reason",c.reason??null],["previousId",c.previous?.id??null],["restoredId",c.restored?.id??null]])}if(t==="version-diff"){let c=String(e[0]??""),p=String(e[1]??"");return De.diff(c,p)}if(t==="version-get"){let c=String(e[0]??""),p=De.get(c);return p?new Map([["id",p.id],["version",p.version],["timestamp",p.timestamp.toISOString()],["data",p.data],["description",p.metadata.description],["tags",p.metadata.tags],["performance",p.metadata.performance??null],["parentId",p.parentId??null],["diff",p.diff??null]]):null}if(t==="version-latest"){let c=De.latest();return c?new Map([["id",c.id],["version",c.version],["timestamp",c.timestamp.toISOString()],["data",c.data],["description",c.metadata.description],["tags",c.metadata.tags],["performance",c.metadata.performance??null],["parentId",c.parentId??null]]):null}if(t==="version-history")return De.getHistory().map(c=>new Map([["id",c.id],["version",c.version],["timestamp",c.timestamp.toISOString()],["description",c.metadata.description],["tags",c.metadata.tags],["parentId",c.parentId??null]]));if(t==="version-branch"){let c=String(e[0]??""),p=e[1]?String(e[1]):void 0;return De.branch(c,p)}if(t==="version-checkout"){let c=String(e[0]??""),p=De.checkout(c);return p?new Map([["id",p.id],["version",p.version],["description",p.metadata.description]]):null}if(t==="version-best"){let c=De.bestPerforming();return c?new Map([["id",c.id],["version",c.version],["performance",c.metadata.performance??null],["description",c.metadata.description]]):null}if(t==="bench-measure"){let c=String(e[0]??"unnamed"),p=e[1],m=100;for(let h=2;h<e.length-1;h+=2)String(e[h]).replace(/^:/,"")==="runs"&&(m=Number(e[h+1]));let d=()=>typeof p=="function"?p():u(p,[]),g=ps.measure(c,d,m);return new Map([["name",g.name],["runs",g.runs],["totalMs",g.totalMs],["avgMs",g.avgMs],["minMs",g.minMs],["maxMs",g.maxMs],["p50",g.p50],["p95",g.p95],["p99",g.p99],["opsPerSec",g.opsPerSec],["memoryUsed",g.memoryUsed??0]])}if(t==="bench-compare"){let c=e[0],p=e[1],m=50;for(let k=2;k<e.length-1;k+=2)String(e[k]).replace(/^:/,"")==="runs"&&(m=Number(e[k+1]));let d=()=>typeof c=="function"?c():u(c,[]),g=()=>typeof p=="function"?p():u(p,[]),h=ps.compare("fn1",d,"fn2",g,m),y=k=>new Map([["name",k.name],["runs",k.runs],["avgMs",k.avgMs],["minMs",k.minMs],["maxMs",k.maxMs],["p50",k.p50],["p95",k.p95],["p99",k.p99],["opsPerSec",k.opsPerSec]]);return new Map([["baseline",y(h.baseline)],["target",y(h.target)],["speedup",h.speedup],["winner",h.winner],["significant",h.significant]])}if(t==="bench-suite"){let c=String(e[0]??"suite");return new it(c)}if(t==="bench-add"){let c=e[0],p=String(e[1]??"test"),m=e[2];if(c instanceof it){let d=()=>typeof m=="function"?m():u(m,[]);return c.add(p,d),c}return null}if(t==="bench-run"){let c=e[0],p=100;for(let m=1;m<e.length-1;m+=2)String(e[m]).replace(/^:/,"")==="runs"&&(p=Number(e[m+1]));if(c instanceof it){let m=c.run(p),d=g=>new Map([["name",g.name],["runs",g.runs],["avgMs",g.avgMs],["minMs",g.minMs],["maxMs",g.maxMs],["opsPerSec",g.opsPerSec]]);return new Map([["name",m.name],["results",m.results.map(d)],["startTime",m.startTime.toISOString()],["endTime",m.endTime?.toISOString()??""],["summary",new Map([["total",m.summary.total],["fastest",m.summary.fastest?d(m.summary.fastest):null],["slowest",m.summary.slowest?d(m.summary.slowest):null],["avgOpsPerSec",m.summary.avgOpsPerSec]])]])}return null}if(t==="bench-report"){let c=e[0];if(c instanceof Map){let p={name:String(c.get("name")??""),runs:Number(c.get("runs")??0),totalMs:Number(c.get("totalMs")??0),avgMs:Number(c.get("avgMs")??0),minMs:Number(c.get("minMs")??0),maxMs:Number(c.get("maxMs")??0),p50:Number(c.get("p50")??0),p95:Number(c.get("p95")??0),p99:Number(c.get("p99")??0),opsPerSec:Number(c.get("opsPerSec")??0),memoryUsed:Number(c.get("memoryUsed")??0)};return ps.report(p)}return"No benchmark result provided"}if(t==="bench-speedup"){let c=e[0];return c instanceof Map?Number(c.get("speedup")??1):1}if(t==="bench-stats"){let c=e[0];return c instanceof Map?new Map([["avg",c.get("avgMs")],["min",c.get("minMs")],["max",c.get("maxMs")],["p95",c.get("p95")],["p99",c.get("p99")],["opsPerSec",c.get("opsPerSec")]]):new Map([["avg",0],["min",0],["max",0],["p95",0],["p99",0],["opsPerSec",0]])}if(t==="self-evolve"){let[c,p,m,d,...g]=e,h=Array.isArray(c)?c:[],y={};for(let C=0;C<g.length-1;C+=2){let P=String(g[C]).replace(/^:/,""),_=g[C+1];P==="gens"||P==="generations"?y.generations=Number(_):P==="pop"||P==="populationSize"?y.populationSize=Number(_):P==="rate"||P==="mutationRate"?y.mutationRate=Number(_):P==="elite"||P==="eliteRatio"?y.eliteRatio=Number(_):P==="prune"||P==="pruneThreshold"?y.pruneThreshold=Number(_):P==="versioning"||P==="enableVersioning"?y.enableVersioning=_===!0||_==="true":P==="benchmark"||P==="enableBenchmark"?y.enableBenchmark=_===!0||_==="true":(P==="refactor"||P==="enableRefactor")&&(y.enableRefactor=_===!0||_==="true")}let k=C=>P=>typeof C=="function"?C(P):C?.kind==="function-value"?i(C,[P]):P,v=C=>Number(k(p)(C)),$=C=>k(m)(C),M=(C,P)=>typeof d=="function"?d(C,P):d?.kind==="function-value"?i(d,[C,P]):C,O=Jt.runCycle(h,v,$,M,y);return new Map([["best",O.best],["bestFitness",O.bestFitness],["generations",O.generations],["improvements",O.improvements],["prunedCount",O.prunedCount],["benchmarkMs",O.benchmarkMs??null],["versionId",O.versionId??null],["report",O.report]])}if(t==="self-evolve-numbers"){let c=Array.isArray(e[0])?e[0].map(Number):[1,2,3],p={};for(let d=1;d<e.length-1;d+=2){let g=String(e[d]).replace(/^:/,""),h=e[d+1];g==="gens"||g==="generations"?p.generations=Number(h):g==="pop"||g==="populationSize"?p.populationSize=Number(h):g==="rate"||g==="mutationRate"?p.mutationRate=Number(h):g==="versioning"||g==="enableVersioning"?p.enableVersioning=h===!0||h==="true":g==="benchmark"||g==="enableBenchmark"?p.enableBenchmark=h===!0||h==="true":(g==="refactor"||g==="enableRefactor")&&(p.enableRefactor=h===!0||h==="true")}let m=Jt.evolveNumbers(c,p);return new Map([["best",m.best],["bestFitness",m.bestFitness],["generations",m.generations],["improvements",m.improvements],["prunedCount",m.prunedCount],["benchmarkMs",m.benchmarkMs??null],["versionId",m.versionId??null],["report",m.report]])}if(t==="self-evolve-string"){let c=String(e[0]??"hello"),p={};for(let d=1;d<e.length-1;d+=2){let g=String(e[d]).replace(/^:/,""),h=e[d+1];g==="gens"||g==="generations"?p.generations=Number(h):g==="pop"||g==="populationSize"?p.populationSize=Number(h):g==="rate"||g==="mutationRate"?p.mutationRate=Number(h):g==="versioning"||g==="enableVersioning"?p.enableVersioning=h===!0||h==="true":(g==="benchmark"||g==="enableBenchmark")&&(p.enableBenchmark=h===!0||h==="true")}let m=Jt.evolveString(c,p);return new Map([["best",m.best],["bestFitness",m.bestFitness],["generations",m.generations],["improvements",m.improvements],["prunedCount",m.prunedCount],["benchmarkMs",m.benchmarkMs??null],["versionId",m.versionId??null],["report",m.report]])}if(t==="evolution-report"){let p=(Array.isArray(e[0])?e[0]:[e[0]].filter(Boolean)).map(d=>d instanceof Map?{best:d.get("best"),bestFitness:Number(d.get("bestFitness")??0),generations:Number(d.get("generations")??0),improvements:Number(d.get("improvements")??0),prunedCount:Number(d.get("prunedCount")??0),benchmarkMs:d.get("benchmarkMs")??void 0,versionId:d.get("versionId")??void 0,report:String(d.get("report")??"")}:d),m=Jt.generateReport(p);return new Map([["timestamp",m.timestamp.toISOString()],["cycles",m.cycles],["totalGenerations",m.totalGenerations],["fitnessProgress",m.fitnessProgress],["refactorSuggestions",m.refactorSuggestions],["versions",m.versions],["summary",m.summary]])}if(t==="self-improve"){let c=e[0],p={};if(c instanceof Map){let d=c.get("generations")??c.get("gens"),g=c.get("populationSize")??c.get("pop"),h=c.get("mutationRate")??c.get("rate");d!==void 0&&(p.generations=Number(d)),g!==void 0&&(p.populationSize=Number(g)),h!==void 0&&(p.mutationRate=Number(h))}let m=Jt.selfImprove(p);return new Map([["optimized",new Map(Object.entries(m.optimized))],["improvement",m.improvement]])}if(t==="evolve-cycle"){let[c,p]=e,m=Array.isArray(c)?c:[],d=k=>typeof p=="function"?Number(p(k)):p?.kind==="function-value"?Number(i(p,[k])):typeof k=="number"?k:0,g=k=>{if(Array.isArray(k)){let v=[...k],$=Math.floor(Math.random()*v.length);return v[$]+=(Math.random()-.5)*.2,v}return k},h=(k,v)=>{if(Array.isArray(k)&&Array.isArray(v)){let $=Math.floor(Math.random()*k.length);return[...k.slice(0,$),...v.slice($)]}return k},y=Jt.runCycle(m,d,g,h);return new Map([["best",y.best],["bestFitness",y.bestFitness],["generations",y.generations],["improvements",y.improvements],["prunedCount",y.prunedCount],["report",y.report]])}if(t==="evolution-best"){let[c]=e;return c instanceof Map?c.get("best")??null:null}if(t==="evolution-fitness"){let[c]=e;return c instanceof Map?c.get("bestFitness")??0:0}if(t.startsWith("world-")){let c=Tc(t,e);if(c!==void 0)return c}if(t.startsWith("cf-")){let c=Ec(t,e,i);if(c!==null)return c}if(t.startsWith("align-")){let c=xc(t,e);if(c!==null)return c}if(t==="causal-add-node"){let c={};for(let m=0;m<e.length-1;m+=2){let d=String(e[m]).replace(/^:/,"");c[d]=e[m+1]}let p={id:String(c.id??""),name:String(c.name??c.id??""),description:String(c.desc??c.description??""),value:c.value!==void 0?Number(c.value):void 0};return oe.addNode(p),new Map([["id",p.id],["name",p.name],["description",p.description]])}if(t==="causal-add-edge"){let c={};for(let m=0;m<e.length-1;m+=2){let d=String(e[m]).replace(/^:/,"");c[d]=e[m+1]}let p={from:String(c.from??""),to:String(c.to??""),strength:Number(c.strength??1),confidence:Number(c.confidence??1),delay:c.delay!==void 0?Number(c.delay):void 0,mechanism:c.mechanism!==void 0?String(c.mechanism):void 0};return oe.addEdge(p),new Map([["from",p.from],["to",p.to],["strength",p.strength],["confidence",p.confidence]])}if(t==="causal-explain"){let c=oe.explain(String(e[0]??""));return new Map([["effect",c.effect],["primaryCause",c.primaryCause],["explanation",c.explanation],["confidence",c.confidence],["causes",c.causes.map(p=>new Map([["cause",p.cause],["contribution",p.contribution],["chain",new Map([["path",p.chain.path],["totalStrength",p.chain.totalStrength],["explanation",p.chain.explanation],["confidence",p.chain.confidence]])]]))]])}if(t==="causal-chains")return oe.findCausalChains(String(e[0]??""),String(e[1]??"")).map(p=>new Map([["path",p.path],["totalStrength",p.totalStrength],["explanation",p.explanation],["confidence",p.confidence]]));if(t==="causal-causes")return oe.getDirectCauses(String(e[0]??"")).map(c=>new Map([["from",c.from],["to",c.to],["strength",c.strength],["confidence",c.confidence]]));if(t==="causal-effects")return oe.getDirectEffects(String(e[0]??"")).map(c=>new Map([["from",c.from],["to",c.to],["strength",c.strength],["confidence",c.confidence]]));if(t==="causal-roots")return oe.findRootCauses(String(e[0]??""));if(t==="causal-simulate"){let c=e[0],p={};if(c instanceof Map)for(let[m,d]of c.entries())p[String(m)]=Number(d);return new Map(Object.entries(oe.simulate(p)))}if(t==="causal-why"){let c=ms(String(e[0]??""),String(e[1]??""));return c===null?null:new Map([["path",c.path],["totalStrength",c.totalStrength],["explanation",c.explanation],["confidence",c.confidence]])}if(t==="causal-summary")return oe.summarize(String(e[0]??""));if(t.startsWith("predict-")){let c=Ac(t,e);if(c!==null)return c}if(t.startsWith("curiosity-")){let c=$c(t,e,i);if(c!==null)return c}if(t.startsWith("wisdom-")){let c=Mc(t,e);if(c!==null)return c}if(t.startsWith("explain-")){let c=Rc(t,e,u);if(c!==null)return c}switch(s){case"file-mkdir":case"file_mkdir":{let c=String(e[0]??""),p=require("fs");try{return p.mkdirSync(c,{recursive:!0}),!0}catch{return!1}}case"http-get":case"http_get":{let c=String(e[0]??"");try{let{execSync:p}=require("child_process"),{writeFileSync:m,unlinkSync:d}=require("fs"),{randomUUID:g}=require("crypto"),h=`/tmp/fl-http-${g()}.js`,y=`process.env.FL_URL=${JSON.stringify(c)};
252
+ const u=require('url').parse(process.env.FL_URL);
253
+ const mod=u.protocol==='https:'?require('https'):require('http');
254
+ const chunks=[];
255
+ const req=mod.request({hostname:u.hostname,port:u.port||undefined,path:u.path||'/',method:'GET'},res=>{
256
+ res.on('data',d=>chunks.push(d));
257
+ res.on('end',()=>{process.stdout.write(JSON.stringify({s:res.statusCode,b:Buffer.concat(chunks).toString()}))});
258
+ });
259
+ req.on('error',e=>process.stdout.write(JSON.stringify({s:0,b:'',e:e.message})));
260
+ req.setTimeout(10000,()=>{req.destroy();process.stdout.write(JSON.stringify({s:0,b:'',e:'timeout'}))});
261
+ req.end();`;m(h,y,"utf-8");let k=p(`node ${h}`,{encoding:"utf-8",timeout:15e3});try{d(h)}catch{}let v=JSON.parse(k);return{status:v.s||0,body:v.b||"",headers:{}}}catch(p){return{status:0,body:"",headers:{},error:p.message}}}case"now-iso":case"now_iso":return new Date().toISOString();case"help":{let c=String(e[0]??"").toLowerCase(),p=[];try{p=ri()}catch{p=[]}if(p.length===0)return console.log("\u26A0\uFE0F stdlib \uC2DC\uADF8\uB2C8\uCC98 \uC5C6\uC74C \u2014 npm run build \uC2E4\uD589 \uD544\uC694"),null;if(!c){let h=[...new Set(p.map(y=>y.module))].sort();return console.log(`\x1B[36m[help]\x1B[0m \uCE74\uD14C\uACE0\uB9AC: ${h.join(", ")}`),console.log('\uC0AC\uC6A9\uBC95: (help "keyword") \uC608: (help "server"), (help "file"), (help "str")'),null}let m=p.filter(h=>h.name===c||h.name.replace(/-/g,"_")===c),d=p.filter(h=>h.name!==c&&h.name.replace(/-/g,"_")!==c&&(h.name.toLowerCase().includes(c)||h.module.toLowerCase().includes(c))).slice(0,15),g=[...m,...d];if(g.length===0)return console.log(`\x1B[33m[help]\x1B[0m '${c}' \uAC80\uC0C9 \uACB0\uACFC \uC5C6\uC74C`),null;console.log(`\x1B[36m[help]\x1B[0m '${c}' \uAC80\uC0C9 \uACB0\uACFC ${g.length}\uAC1C:`);for(let h of g){let y=m.includes(h)?"\x1B[32m\u25CF\x1B[0m":" ";console.log(` ${y} \x1B[1m${h.name}\x1B[0m (${h.params||"-"}) \u2192 ${h.returns||"any"}`)}return null}}return o(t,e)}}}function Pc(r,t,e){let n=s=>r.eval(s);if(t==="search"||t==="fetch"){let s="",a="web",i=!1,o=10,u;for(let l=0;l<e.args.length;l++){let c=e.args[l];if(l===0){s=String(n(c));continue}if(c.kind==="keyword"){let p=c.name;if(l+1<e.args.length){let m=n(e.args[l+1]);switch(p){case"source":(m==="web"||m==="api"||m==="kb")&&(a=m);break;case"cache":i=m===!0||m==="true";break;case"limit":o=Number(m)||10;break;case"name":u=String(m);break}l++}}}t==="fetch"&&(a="api");let f={kind:"search-block",query:s,source:a,cache:i,limit:o,name:u};return r.handleSearchBlock(f)}if(t==="learn"||t==="recall"||t==="remember"||t==="forget"){let s="",a=null,i="search",o;for(let f=0;f<e.args.length;f++){let l=e.args[f];if(f===0){s=String(n(l));continue}if(f===1&&(t==="learn"||t==="remember")){a=n(l);continue}if(l.kind==="keyword"){let c=l.name;if(f+1<e.args.length){let p=n(e.args[f+1]);switch(c){case"source":(p==="search"||p==="feedback"||p==="analysis")&&(i=p);break;case"confidence":o=Number(p)||void 0;break}f++}}}if(t==="forget"){r.context.learned||(r.context.learned=new Map);let f=r.context.learned.has(s);return f&&r.context.learned.delete(s),{kind:"learn-result",operation:"forget",key:s,deleted:f}}t==="recall"&&(a=null);let u={kind:"learn-block",key:s,data:a,source:i,confidence:o,timestamp:new Date().toISOString()};return r.handleLearnBlock(u)}if(t==="observe"||t==="analyze"||t==="decide"||t==="act"||t==="verify"){let s=t,a=new Map,i,o,u,f,l,c;for(let m=0;m<e.args.length;m++){let d=e.args[m];if(d.kind==="keyword"){let g=d.name;if(m+1<e.args.length){let h=n(e.args[m+1]);g==="confidence"?c=Number(h):a.set(g,h),m++}}else if(m===0){let g=n(d);switch(s){case"observe":i=[g],a.set("observation",g);break;case"analyze":a.set("firstArg",g);break;case"decide":a.set("firstArg",g);break;case"act":a.set("firstArg",g);break;case"verify":l=[g],a.set("result",g);break}}}let p={kind:"reasoning-block",stage:s,data:a,observations:i,analysis:o,decisions:u,actions:f,verifications:l,metadata:{confidence:c,startTime:new Date().toISOString()}};return r.handleReasoningBlock(p)}if(t==="await"){if(e.args.length<1)throw new Error("await requires a Promise argument");let s=n(e.args[0]);if(s instanceof ae){if(s.getState()==="resolved")return s.getValue();throw s.getState()==="rejected"?s.getError()||new Error("Promise rejected"):new Error("Cannot await unresolved Promise in synchronous context")}throw new TypeError("await requires a Promise, got "+typeof s)}throw new Error(`evalAiBlock: unknown op "${t}"`)}var ut=z(require("fs")),Mt=z(require("path")),Pn=process.cwd();function jc(r,t,e){let n=s=>r.eval(s);if(t==="DOCKERFILE"||t==="dockerfile"){let s="node:20-slim",a="/app",i=[],o=[],u=[],f=["node","server.js"],l={};for(let m=0;m<e.args.length;m++){let d=e.args[m];if(d.kind==="keyword"){let g=d.name;if(m+1<e.args.length){let h=n(e.args[m+1]);switch(g){case"from":s=String(h);break;case"workdir":a=String(h);break;case"expose":i.push(String(h));break;case"copy":o.push(String(h));break;case"run":u.push(String(h));break;case"cmd":f=Array.isArray(h)?h:[String(h)];break;case"env":typeof h=="object"&&Object.assign(l,h);break}m++}}}let c=`FROM ${s}
262
+ WORKDIR ${a}
263
+ `;Object.entries(l).forEach(([m,d])=>{c+=`ENV ${m}=${d}
264
+ `}),o.forEach(m=>{c+=`COPY ${m}
265
+ `}),u.forEach(m=>{c+=`RUN ${m}
266
+ `}),i.forEach(m=>{c+=`EXPOSE ${m}
267
+ `}),c+=`CMD [${f.map(m=>`"${m}"`).join(", ")}]
268
+ `;let p=Mt.join(Pn,"Dockerfile");return ut.writeFileSync(p,c,"utf-8"),{generated:"Dockerfile",bytes:c.length}}if(t==="K8S-DEPLOYMENT"||t==="deployment"){let s="my-app",a="default",i="my-app:latest",o=1,u=8080,f=u,l={};for(let m=0;m<e.args.length;m++){let d=e.args[m];if(d.kind==="keyword"){let g=d.name;if(m+1<e.args.length){let h=n(e.args[m+1]);switch(g){case"name":s=String(h);break;case"namespace":a=String(h);break;case"image":i=String(h);break;case"replicas":o=Number(h)||1;break;case"port":u=Number(h)||8080;break;case"containerPort":f=Number(h)||u;break;case"env":typeof h=="object"&&Object.assign(l,h);break}m++}}}let c=`apiVersion: apps/v1
269
+ kind: Deployment
270
+ metadata:
271
+ name: ${s}
272
+ namespace: ${a}
273
+ spec:
274
+ replicas: ${o}
275
+ selector:
276
+ matchLabels:
277
+ app: ${s}
278
+ template:
279
+ metadata:
280
+ labels:
281
+ app: ${s}
282
+ spec:
283
+ containers:
284
+ - name: ${s}
285
+ image: ${i}
286
+ ports:
287
+ - containerPort: ${f}
288
+ ${Object.entries(l).length>0?` env:
289
+ ${Object.entries(l).map(([m,d])=>` - name: ${m}
290
+ value: "${d}"`).join(`
291
+ `)}
292
+ `:""}`,p=Mt.join(Pn,`${s}-deployment.yaml`);return ut.writeFileSync(p,c,"utf-8"),{generated:`${s}-deployment.yaml`,bytes:c.length}}if(t==="K8S-SERVICE"||t==="service"){let s="my-app",a="default",i=8080,o=i,u="ClusterIP";for(let c=0;c<e.args.length;c++){let p=e.args[c];if(p.kind==="keyword"){let m=p.name;if(c+1<e.args.length){let d=n(e.args[c+1]);switch(m){case"name":s=String(d);break;case"namespace":a=String(d);break;case"port":i=Number(d)||8080;break;case"targetPort":o=Number(d)||i;break;case"type":u=String(d);break}c++}}}let f=`apiVersion: v1
293
+ kind: Service
294
+ metadata:
295
+ name: ${s}
296
+ namespace: ${a}
297
+ spec:
298
+ type: ${u}
299
+ ports:
300
+ - port: ${i}
301
+ targetPort: ${o}
302
+ protocol: TCP
303
+ selector:
304
+ app: ${s}
305
+ `,l=Mt.join(Pn,`${s}-service.yaml`);return ut.writeFileSync(l,f,"utf-8"),{generated:`${s}-service.yaml`,bytes:f.length}}if(t==="K8S-INGRESS"||t==="ingress"){let s="my-app",a="default",i="app.example.com",o="my-app",u=8080,f="/";for(let p=0;p<e.args.length;p++){let m=e.args[p];if(m.kind==="keyword"){let d=m.name;if(p+1<e.args.length){let g=n(e.args[p+1]);switch(d){case"name":s=String(g);break;case"namespace":a=String(g);break;case"host":i=String(g);break;case"serviceName":o=String(g);break;case"servicePort":u=Number(g)||8080;break;case"path":f=String(g);break}p++}}}let l=`apiVersion: networking.k8s.io/v1
306
+ kind: Ingress
307
+ metadata:
308
+ name: ${s}
309
+ namespace: ${a}
310
+ spec:
311
+ rules:
312
+ - host: ${i}
313
+ http:
314
+ paths:
315
+ - path: ${f}
316
+ pathType: Prefix
317
+ backend:
318
+ service:
319
+ name: ${o}
320
+ port:
321
+ number: ${u}
322
+ `,c=Mt.join(Pn,`${s}-ingress.yaml`);return ut.writeFileSync(c,l,"utf-8"),{generated:`${s}-ingress.yaml`,bytes:l.length}}if(t==="DOCKER-COMPOSE"||t==="docker-compose"){let s="3.8",a={};for(let f=0;f<e.args.length;f++){let l=e.args[f];if(l.kind==="keyword"){let c=l.name;if(f+1<e.args.length){let p=n(e.args[f+1]);switch(c){case"version":s=String(p);break;case"services":a=p||{};break}f++}}}let i=Object.entries(a).map(([f,l])=>` ${f}:
323
+ image: ${l.image||f}
324
+ ports:
325
+ - "${l.port||8080}:${l.containerPort||8080}"`).join(`
326
+ `),o=`version: '${s}'
327
+ services:
328
+ ${i}
329
+ `,u=Mt.join(Pn,"docker-compose.yml");return ut.writeFileSync(u,o,"utf-8"),{generated:"docker-compose.yml",bytes:o.length}}if(t==="GITHUB-ACTIONS"||t==="github-actions"||t==="ci"){let s="CI",a=["push","pull_request"],i=[];for(let p=0;p<e.args.length;p++){let m=e.args[p];if(m.kind==="keyword"){let d=m.name;if(p+1<e.args.length){let g=n(e.args[p+1]);switch(d){case"name":s=String(g);break;case"on":a=Array.isArray(g)?g:[String(g)];break;case"test":i.push({uses:"actions/checkout@v3"}),i.push({uses:"actions/setup-node@v3",with:{"node-version":"20"}}),i.push({run:String(g)});break;case"steps":i=Array.isArray(g)?g:[g];break}p++}}}let o=a.map(p=>` - ${p}`).join(`
330
+ `),u=i.map(p=>typeof p=="string"?` - run: ${p}`:p.uses?` - uses: ${p.uses}${p.with?`
331
+ with:
332
+ ${Object.entries(p.with).map(([m,d])=>` ${m}: "${d}"`).join(`
333
+ `)}`:""}`:p.run?` - run: ${p.run}`:` - ${JSON.stringify(p)}`).join(`
334
+ `),f=`name: ${s}
335
+
336
+ on:
337
+ ${o}
338
+
339
+ jobs:
340
+ build:
341
+ runs-on: ubuntu-latest
342
+ steps:
343
+ ${u}
344
+ `,l=Mt.join(Pn,".github","workflows");ut.mkdirSync(l,{recursive:!0});let c=Mt.join(l,`${s.toLowerCase().replace(/\\s+/g,"-")}.yml`);return ut.writeFileSync(c,f,"utf-8"),{generated:c,bytes:f.length}}if(t==="AWS-S3"||t==="aws-s3"){let s="my-bucket",a="list",i="",o=null,u="us-east-1";for(let f=0;f<e.args.length;f++){let l=e.args[f];if(l.kind==="keyword"){let c=l.name;if(f+1<e.args.length){let p=n(e.args[f+1]);switch(c){case"bucket":s=String(p);break;case"action":a=String(p);break;case"file":i=String(p);break;case"data":o=p;break;case"region":u=String(p);break}f++}}}try{switch(a.toLowerCase()){case"list":return r.callUserFunction("aws-s3-list",[s,i]);case"upload":return r.callUserFunction("aws-s3-upload",[s,i,o]);case"download":return r.callUserFunction("aws-s3-download",[s,i]);case"delete":return r.callUserFunction("aws-s3-delete",[s,i]);case"config":return r.callUserFunction("aws-s3-config",[s,u]);default:return{status:"unknown_action",action:a,bucket:s}}}catch(f){return{status:"error",action:a,bucket:s,reason:f.message}}}if(t==="GCP-RUN"||t==="gcp-run"){let s="my-service",a="gcr.io/my-project/my-service:latest",i="us-central1",o="deploy",u=null;for(let f=0;f<e.args.length;f++){let l=e.args[f];if(l.kind==="keyword"){let c=l.name;if(f+1<e.args.length){let p=n(e.args[f+1]);switch(c){case"service":s=String(p);break;case"image":a=String(p);break;case"region":i=String(p);break;case"action":o=String(p);break;case"data":u=p;break}f++}}}try{switch(o.toLowerCase()){case"deploy":return r.callUserFunction("gcp-run-deploy",[s,a,i]);case"invoke":return r.callUserFunction("gcp-run-invoke",[s,u,i]);case"list":return r.callUserFunction("gcp-run-list",[i]);default:return{status:"unknown_action",action:o,service:s}}}catch(f){return{status:"error",action:o,service:s,reason:f.message}}}if(t==="AZURE-FUNCTION"||t==="azure-function"){let s="my-function",a="node",i="eastus",o="invoke",u=null,f="";for(let l=0;l<e.args.length;l++){let c=e.args[l];if(c.kind==="keyword"){let p=c.name;if(l+1<e.args.length){let m=n(e.args[l+1]);switch(p){case"name":s=String(m);break;case"runtime":a=String(m);break;case"region":i=String(m);break;case"action":o=String(m);break;case"data":u=m;break;case"image":f=String(m);break}l++}}}try{switch(o.toLowerCase()){case"invoke":return r.callUserFunction("azure-function-invoke",[s,u]);case"create":return r.callUserFunction("azure-function-create",[s,a]);case"deploy":return r.callUserFunction("azure-app-deploy",[s,f,i]);default:return{status:"unknown_action",action:o,name:s}}}catch(l){return{status:"error",action:o,name:s,reason:l.message}}}throw new Error(`Unknown infra block: ${t}`)}var ai=class{constructor(){this.themes=[];this.styles=[]}addTheme(t){t.trim()&&this.themes.push(t)}addStyle(t){t.trim()&&this.styles.push(t)}flush(){let t=[...this.themes,...this.styles].join(`
345
+ `);return this.themes=[],this.styles=[],t}size(){return this.themes.length+this.styles.length}},ii=new ai;var Uf={bg:"background",fg:"color",p:"padding",m:"margin",w:"width",h:"height",r:"border-radius",b:"border",fs:"font-size",fw:"font-weight",d:"display",o:"opacity",z:"z-index"};function Vf(r){return Uf[r]||r}function zf(r){if(typeof r!="object"||r===null)return"";let t=[];for(let[e,n]of Object.entries(r)){let s=e.startsWith(":")?e.slice(1):e;s=Vf(s);let a=String(n).trim();a&&t.push(`${s}: ${a}`)}return t.join("; ")}function Wf(r,t,e){if(typeof e!="object"||e===null)return{status:"error",reason:"tokens must be object"};let n=[];for(let[a,i]of Object.entries(e)){let o=a.startsWith(":")?a.slice(1):a,u=String(i).trim();u&&n.push(` --${o}: ${u}`)}if(n.length===0)return{status:"empty",name:t};let s=`:root {
346
+ ${n.join(`;
347
+ `)};
348
+ }`;return ii.addTheme(s),{status:"theme_defined",name:t,tokens:Object.keys(e).length,css:s}}function Hf(r,t,e,n){if(!e||e.trim()==="")return{status:"error",reason:"selector is required"};let s=zf(n);if(!s)return{status:"empty",name:t,selector:e};let a=`${e} { ${s}; }`;return ii.addStyle(a),{status:"style_defined",name:t,selector:e,css:a}}function Ic(r,t,e){let n=s=>r.eval(s);if(t==="THEME"||t==="theme"){let s="default",a={};for(let i=0;i<e.args.length;i++){let o=e.args[i];if(o.kind==="keyword"){let u=o.name;if(i+1<e.args.length){let f=n(e.args[i+1]);switch(u){case"name":s=String(f);break;case"tokens":a=typeof f=="object"?f:{};break}i++}}}return Wf(r,s,a)}if(t==="STYLE"||t==="style"){let s="default",a="",i={};for(let o=0;o<e.args.length;o++){let u=e.args[o];if(u.kind==="keyword"){let f=u.name;if(o+1<e.args.length){let l=n(e.args[o+1]);switch(f){case"name":s=String(l);break;case"selector":a=String(l);break;case"rules":i=typeof l=="object"?l:{};break}o++}}}return Hf(r,s,a,i)}throw new Error(`Unknown style block: ${t}`)}un();var Lc=Symbol("TAIL_CALL");function Bc(r,t){return{[Lc]:!0,fn:r,args:t}}function oi(r){return r!==null&&typeof r=="object"&&r[Lc]===!0}var Sr=class{constructor(t){this.value=t}};function Rt(r){return r instanceof Sr}var jn=class{compile(t){let e={instructions:[],constants:[],name:"main"};return this.compileExpr(t,e),this.emit(e,25),e}compileExpr(t,e){switch(t.kind){case"literal":this.compileLiteral(t,e);break;case"variable":this.compileVariable(t,e);break;case"sexpr":this.compileSExpr(t,e);break;case"block":this.compileBlock(t,e);break;default:this.emit(e,25);break}}compileLiteral(t,e){if(t.type==="symbol"&&typeof t.value=="string"){let s=t.value;if(s!=="true"&&s!=="false"&&s!=="null"){this.emit(e,1,"$"+s);return}}let n=this.addConst(e,t.value);this.emit(e,0,n)}compileVariable(t,e){this.emit(e,1,t.name)}compileSExpr(t,e){let n=t.op;switch(n){case"if":this.compileIf(t,e);return;case"define":this.compileDefine(t,e);return;case"do":this.compileDo(t,e);return;case"list":this.compileList(t,e);return;case"not":t.args.length>=1&&(this.compileExpr(t.args[0],e),this.emit(e,22));return;case"and":this.compileAnd(t,e);return;case"or":this.compileOr(t,e);return;case"get":case".":if(t.args.length>=2){this.compileExpr(t.args[0],e);let a=t.args[1];a.kind==="literal"?this.emit(e,24,String(a.value)):this.emit(e,25)}return}let s={"+":9,"-":10,"*":11,"/":12,"%":13,mod:13,"==":14,"=":14,"!=":19,"<":15,">":16,"<=":17,">=":18};if(s[n]!==void 0){if(t.args.length>=2)this.compileExpr(t.args[0],e),this.compileExpr(t.args[1],e),this.emit(e,s[n]);else if(t.args.length===1)if(n==="-"){let a=this.addConst(e,0);this.emit(e,0,a),this.compileExpr(t.args[0],e),this.emit(e,10)}else this.compileExpr(t.args[0],e);return}this.emit(e,25)}compileIf(t,e){if(t.args.length<2){this.emit(e,25);return}this.compileExpr(t.args[0],e);let n=e.instructions.length;this.emit(e,6,0),this.compileExpr(t.args[1],e);let s=e.instructions.length;this.emit(e,5,0);let a=e.instructions.length;if(e.instructions[n].arg=a,t.args.length>=3)this.compileExpr(t.args[2],e);else{let o=this.addConst(e,null);this.emit(e,0,o)}let i=e.instructions.length;e.instructions[s].arg=i}compileDefine(t,e){if(t.args.length<2){this.emit(e,25);return}let n=t.args[0],s=t.args[1];this.compileExpr(s,e);let a=n.kind==="variable"?n.name:n.kind==="literal"?String(n.value):"unknown";this.emit(e,2,a);let i=this.addConst(e,null);this.emit(e,0,i)}compileDo(t,e){if(t.args.length===0){let n=this.addConst(e,null);this.emit(e,0,n);return}for(let n=0;n<t.args.length;n++)this.compileExpr(t.args[n],e),n<t.args.length-1&&this.emit(e,7)}compileList(t,e){for(let n of t.args)this.compileExpr(n,e);this.emit(e,23,t.args.length)}compileAnd(t,e){if(t.args.length===0){let n=this.addConst(e,!0);this.emit(e,0,n);return}if(t.args.length===1){this.compileExpr(t.args[0],e);return}this.compileExpr(t.args[0],e),this.compileExpr(t.args[1],e),this.emit(e,20)}compileOr(t,e){if(t.args.length===0){let n=this.addConst(e,!1);this.emit(e,0,n);return}if(t.args.length===1){this.compileExpr(t.args[0],e);return}this.compileExpr(t.args[0],e),this.compileExpr(t.args[1],e),this.emit(e,21)}compileBlock(t,e){this.emit(e,25)}addConst(t,e){return t.constants.push(e),t.constants.length-1}emit(t,e,n){let s={op:e};n!==void 0&&(s.arg=n),t.instructions.push(s)}};var xr=new Map;function ci(r,t){t&&xr.set(r,t)}var Gf=new Set(["+","-","*","/","%","mod","=","==","!=","<",">","<=",">=","and","or","not","if","do","list","get",".","define"]);function li(r){if(!r||typeof r!="object")return!1;switch(r.kind){case"literal":return!0;case"variable":return!0;case"sexpr":{let e=r;return!e||!e.op||!Gf.has(e.op)||!e.args||!Array.isArray(e.args)?!1:e.args.every(n=>li(n))}case"keyword":return!1;case"block":return!1;case"pattern-match":case"try-block":case"throw":default:return!1}}nt();var Ne=new Map,ys="abcdefghijklmnopqrstuvwxyz0123456789 _-";function Ar(r){switch(r.replace(/^:/,"").toLowerCase()){case"int":case"integer":return Math.floor(Math.random()*2001)-1e3;case"pos-int":case"positive-int":return Math.floor(Math.random()*1e3)+1;case"neg-int":case"negative-int":return-(Math.floor(Math.random()*1e3)+1);case"nat":case"natural":return Math.floor(Math.random()*1e3);case"float":case"double":return Math.random()*2e3-1e3;case"number":return Math.random()<.5?Math.floor(Math.random()*2001)-1e3:Math.random()*2e3-1e3;case"string":case"str":{let e=Math.floor(Math.random()*20);return Array.from({length:e},()=>ys[Math.floor(Math.random()*ys.length)]).join("")}case"nonempty-string":case"ne-string":{let e=Math.floor(Math.random()*19)+1;return Array.from({length:e},()=>ys[Math.floor(Math.random()*ys.length)]).join("")}case"bool":case"boolean":return Math.random()<.5;case"list":case"array":{let e=Math.floor(Math.random()*10);return Array.from({length:e},()=>Ar("int"))}case"any":default:{let e=Math.floor(Math.random()*4);return e===0?Ar("int"):e===1?Ar("string"):e===2?Ar("bool"):null}}}function Kf(r){return r.map(t=>Ar(t))}function bs(r,t,e){let n=Date.now(),s=0,a=0,i=null;for(let o=0;o<r.samples;o++){let u=Kf(r.args);try{let f=t(r.fn,u),l;try{l=(r.check?.params??[]).length===u.length+1?[...u,f]:u}catch{l=[...u,f]}let c=e(r.check,l);c||c===null?s++:(a++,i||(i={args:u,result:f}))}catch(f){a++,i||(i={args:u,result:null,error:f?.message??String(f)})}if(a>0&&i)break}return{name:r.name,fn:r.fn,samples:r.samples,passed:s,failed:a,firstFailure:i,durationMs:Date.now()-n}}var Jf=new jn,ks=new Map,qc=new Set(["doc","returns","context","effects","examples","property"]);function Xf(r){if(r?.kind!=="block"||r?.type!=="Map")return null;let t=r.fields;if(!t||!(t instanceof Map)||!qc.has([...t.keys()].find(s=>qc.has(s))??""))return null;let e={},n=s=>s?.kind==="literal"?String(s.value):void 0;if(t.has("doc")&&(e.doc=n(t.get("doc"))),t.has("returns")&&(e.returns=n(t.get("returns"))),t.has("context")&&(e.context=n(t.get("context"))),t.has("examples")&&(e.examples=n(t.get("examples"))),t.has("effects")){let s=t.get("effects");if(s?.kind==="block"&&s?.type==="Array"){let a=s.fields?.get("items");Array.isArray(a)&&(e.effects=a.map(i=>n(i)??"?"))}}return t.has("property")&&(e.property=t.get("property")),e}function $r(r){if(typeof r=="number")return{kind:"type",name:"number"};if(typeof r=="string")return{kind:"type",name:"string"};if(typeof r=="boolean")return{kind:"type",name:"boolean"};if(r===null)return{kind:"type",name:"nil"};if(Array.isArray(r))return{kind:"type",name:"list"};if(r&&typeof r=="object")return r._isVMFunc||r.params?{kind:"type",name:"function"}:{kind:"type",name:"map"}}var pi=new Map([["http_get","http"],["http-get","http"],["http_post","http"],["http-post","http"],["http_put","http"],["http-put","http"],["http_delete","http"],["http-delete","http"],["http_patch","http"],["http-patch","http"],["http_get_bearer","http"],["http_post_bearer","http"],["http_post_json","http"],["http_get_json","http"],["file_read","file-read"],["file-read","file-read"],["file_write","file-write"],["file-write","file-write"],["file_append","file-write"],["file_delete","file-write"],["file_exists","file-read"],["file_list","file-read"],["db_query","db-read"],["db-query","db-read"],["db_execute","db-write"],["db-execute","db-write"],["db_insert","db-write"],["db-insert","db-write"],["db_update","db-write"],["db-update","db-write"],["db_delete","db-write"],["db-delete","db-write"],["shell_exec","shell"],["shell-exec","shell"],["shell_exec_result","shell"],["shell-exec-result","shell"],["shell_run","shell"],["println","io"],["print","io"],["log/info","io"],["log/warn","io"],["log/error","io"],["now","time"],["timestamp","time"],["random","random"],["rand-int","random"],["server_start","server"],["server-start","server"]]);function ui(r,t){if(r)if(r.kind==="sexpr"){let e=r.op??"",n=pi.get(e);n&&t.add(n),Array.isArray(r.args)&&r.args.forEach(s=>ui(s,t))}else r.kind==="block"?r.fields instanceof Map&&r.fields.forEach(e=>ui(e,t)):r.kind==="literal"||r.kind}function Uc(r,t,e,n,s){let a=new Set;ui(e,a);let i=s||t.length===0,o=new Set(t.map(f=>f.startsWith(":")?f.slice(1):f)),u=[];for(let f of a)o.has(f)||u.push(f);if(u.length>0){let f=u.map(l=>`:${l}`).join(" ");if(i)throw new ue(de.PURE_VIOLATION,`${r}: ^pure \uD568\uC218\uC5D0\uC11C side effect \uAC10\uC9C0 \u2014 ${f}`,{fn:r,expected:"no side effects",got:f},void 0,n);process.stderr.write(`\x1B[33m[effects]\x1B[0m \x1B[1m${r}\x1B[0m${n?` (line ${n})`:""} \uC120\uC5B8 \uC548 \uB41C effect: \x1B[33m${f}\x1B[0m \u2192 :effects \uC5D0 \uCD94\uAC00 \uD544\uC694
349
+ `)}}function fe(r,t,e,n){throw new ue(de.ARG_COUNT,`${r}: expects ${t} args, got ${e}`,{fn:r,expected:t,got:String(e)},void 0,n)}function qe(r,t,e){throw new ue(de.INVALID_FORM,`${r}: ${t}`,{fn:r},void 0,e)}function Yf(r,t){throw new ue(de.FN_NOT_FOUND,`Function not found: ${r}`,{fn:r},void 0,t)}function fi(r,t,e){let n=f=>r.eval(f),s=(f,l)=>r.callUserFunction(f,l),a=(f,l)=>r.callFunctionValue(f,l),i=(f,l)=>r.callAsyncFunctionValue(f,l),o=(f,l)=>r.callFunction(f,l),u=r.context;if(t==="use"){e.args.length<1&&fe("use",">=1",e.args.length,e.line);let f=require("fs"),l=require("path"),c=!1;for(let p of e.args){let m=null;p.kind==="literal"?m=String(p.value):p.kind==="variable"&&(m=String(p.name).replace(/^\$/,"")),m||qe("use","module name must be symbol or string",e.line);let d=require("os").homedir(),g=[l.resolve(process.cwd(),"plugins",m+".fl"),l.resolve(d,".fl","plugins",m+".fl"),l.resolve(process.cwd(),"self/stdlib",m+".fl"),l.resolve(process.cwd(),m+".fl"),l.resolve(process.cwd(),m)],h=null;for(let M of g)if(f.existsSync(M)&&f.statSync(M).isFile()){h=M;break}if(!h)throw new ue(de.RUNTIME,`(use ${m}): module not found. Tried: ${g.join(", ")}`,{fn:"use",varName:m},void 0,e.line);let y=r.importedFiles??new Set;if(y.has(h))continue;y.add(h),r.importedFiles=y;let k=f.readFileSync(h,"utf-8"),{lex:v}=(be(),_e(cn)),{parse:$}=(ke(),_e(fn));r.interpret($(v(k,h))),c=!0}return c}if(t==="fn"){e.args.length<2&&fe("fn",">=2",e.args.length,e.line);let f=e.args[0],l=[],c=[];if(f.kind==="block"&&f.type==="Array"){let d=f.fields.get("items");if(Array.isArray(d)){for(let g of d)if(!(g.kind==="literal"&&g.type==="symbol"&&String(g.value).startsWith("^"))){if(g.kind==="block"&&g.type==="Map"){l.push(g),c.push(void 0);continue}if(g.kind==="block"&&g.type==="Array"){let h=g.fields?.get("items")??[];if(h.length>=2){let y=h[0],k=y.kind==="variable"?y.name:y.kind==="literal"?String(y.value):"";l.push(k.startsWith("$")?k.slice(1):k),c.push(h[1])}continue}if(g.kind==="variable"){let h=g.name;l.push(h.startsWith("$")?h.slice(1):h),c.push(void 0)}else if(g.kind==="literal"&&g.type==="symbol"){let h=g.value;l.push(h.startsWith("$")?h.slice(1):h),c.push(void 0)}}}}else f.kind==="sexpr"?qe("fn",`\uD30C\uB77C\uBBF8\uD130 \uBAA9\uB85D\uC740 \uB300\uAD04\uD638 [ ]\uB97C \uC0AC\uC6A9\uD558\uC138\uC694.
350
+ \uC798\uBABB\uB41C \uC608: (fn (x y) ...)
351
+ \uC62C\uBC14\uB978 \uC608: (fn [$x $y] ...)`,e):qe("fn","\uD30C\uB77C\uBBF8\uD130\uB294 [\uBCC0\uC2181 \uBCC0\uC2182 ...] \uD615\uD0DC\uC5EC\uC57C \uD569\uB2C8\uB2E4.",e);let p=e.args.length===2?e.args[1]:{kind:"sexpr",op:"do",args:e.args.slice(1)},m=c.some(d=>d!==void 0);return{kind:"function-value",params:l,...m&&{paramDefaults:c},body:p,capturedEnv:u.variables.snapshot(),name:void 0}}if(t==="defn"||t==="defun"){e.args.length<3&&fe("defn",">=3",e.args.length,e.line);let f=0,l=!1;e.args[f]?.kind==="literal"&&String(e.args[f].value).startsWith("^")&&(String(e.args[f].value)==="^pure"&&(l=!0),f++);let c=e.args[f++],p;c.kind==="variable"?p=c.name:c.kind==="literal"&&c.type==="symbol"?p=c.value:qe("defn","first argument must be a symbol (function name)",e.line);let m=e.args[f],d=e.args.slice(f+1),g=null;if(d.length>1){let $=Xf(d[0]);$&&($.line=e.line,ks.set(p,$),g=$,d=d.slice(1))}let h=d.length===1?d[0]:{kind:"sexpr",op:"do",args:d};l?(Uc(p,[],h,e.line,!0),g?g.effects||(g.effects=[]):(g={line:e.line,effects:[]},ks.set(p,g))):g?.effects!==void 0&&Uc(p,g.effects,h,e.line);let y={kind:"sexpr",op:"fn",args:[m,h]},k=r.evalSExpr(y);try{let M={_isVMFunc:!0,_chunk:Jf.compileFunctionBody(k.params,k.body,p),_params:k.params,_closure:k.capturedEnv?[...k.capturedEnv.entries()]:[]};ci(p,M)}catch{ci(p)}let v={name:p,params:k.params,body:k.body,capturedEnv:k.capturedEnv};if(k.paramDefaults&&(v.paramDefaults=k.paramDefaults),u.functions.set(p,v),g?.property)try{let $=g.property;if($?.kind==="block"&&$?.type==="Map"){let M=$.fields,O=M.get("args"),C=[];if(O?.kind==="block"&&O?.type==="Array"){let E=O.fields?.get("items");Array.isArray(E)&&(C=E.map(T=>T?.kind==="literal"?String(T.value).replace(/^:/,""):"any"))}let P=M.get("check"),_=P?n(P):null,S=M.get("samples"),R=S?.kind==="literal"&&typeof S.value=="number"?S.value:100;Ne.set(`prop-${p}`,{name:`prop-${p}`,fn:p,args:C,check:_,samples:R,line:e.line})}}catch{}return u.variables.set("$"+p,k),u.variables.set(p,k),k}if(t==="defprop"){e.args.length<2&&fe("defprop",">=2",e.args.length,e.line);let f=e.args[0],l=f?.kind==="variable"?f.name:f?.kind==="literal"?String(f.value):"prop-"+Date.now(),c=e.args[1];if(c?.kind!=="block"||c?.type!=="Map")throw new ue(de.INVALID_FORM,"defprop: \uB450 \uBC88\uC9F8 \uC778\uC790\uB294 \uB9F5\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4 {:fn :args :check}",{},void 0,e.line);let p=c.fields,m=p.get("fn"),d=m?.kind==="literal"?String(m.value):"",g=p.get("args"),h=[];if(g?.kind==="block"&&g?.type==="Array"){let O=g.fields?.get("items");Array.isArray(O)&&(h=O.map(C=>C?.kind==="literal"?String(C.value).replace(/^:/,""):"any"))}let y=p.get("check"),k=y?n(y):null,v=p.get("samples"),$=v?.kind==="literal"&&typeof v.value=="number"?v.value:100,M={name:l,fn:d,args:h,check:k,samples:$,line:e.line};return Ne.set(l,M),M}if(t==="async"){e.args.length<3&&fe("async",">=3",e.args.length,e.line);let l=e.args[0].name||"async-fn",c=e.args[1],p=[];if(c.kind==="block"&&c.type==="Array"){let m=c.fields.get("items");if(Array.isArray(m))for(let d of m)d.kind==="variable"&&p.push(d.name)}else c.kind==="sexpr"?qe("async",`\uD30C\uB77C\uBBF8\uD130 \uBAA9\uB85D\uC740 \uB300\uAD04\uD638 [ ]\uB97C \uC0AC\uC6A9\uD558\uC138\uC694.
352
+ \uC798\uBABB\uB41C \uC608: (async myFn (x) ...)
353
+ \uC62C\uBC14\uB978 \uC608: (async myFn [$x] ...)`,e):qe("async","\uD30C\uB77C\uBBF8\uD130\uB294 [\uBCC0\uC2181 \uBCC0\uC2182 ...] \uD615\uD0DC\uC5EC\uC57C \uD569\uB2C8\uB2E4.",e);return{kind:"async-function-value",name:l,params:p,body:e.args[2],capturedEnv:u.variables.snapshot()}}if(t==="set!"){e.args.length<2&&fe("set!",">=2",e.args.length,e.line);let f=e.args[0]?.name??e.args[0]?.value??"x";if(process.env.FL_V12==="1")throw new ue(de.INVALID_FORM,`[v12] set!\uC740 \uC81C\uAC70\uB410\uC2B5\uB2C8\uB2E4 (line ${e.line??"?"}). atom\uC744 \uC0AC\uC6A9\uD558\uC138\uC694:
354
+ (define ${f} (atom \uCD08\uAE30\uAC12)) \u2192 (swap! ${f} (fn [v] \uC0C8\uAC12)) \uB610\uB294 (reset! ${f} \uC0C8\uAC12)`,{fn:"set!"},void 0,e.line);console.warn(`\u26A0\uFE0F [FreeLang] set! is deprecated (line ${e.line??"?"}). \uC804\uC5ED \uBCC0\uC218 \uC218\uC815\uC740 \uD074\uB85C\uC800\uC5D0 \uC804\uD30C\uB418\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4. atom \uAD8C\uC7A5: (define x (atom 0)) (swap! x + 1)`);let l=e.args[0];if(l.kind==="sexpr"&&l.op==="get"){let m=l.args,d=n(m[0]),g=n(m[1]),h=n(e.args[1]);if(d!==null&&typeof d=="object"){let y=typeof g=="string"&&g.startsWith(":")?g.slice(1):String(g);d[y]=h}return n(e.args[1])}let c;l.kind==="variable"?c="$"+l.name:l.kind==="literal"?c="$"+l.value:qe("set!","first argument must be a symbol",e.line);let p=n(e.args[1]);return u.variables.mutate(c,p)||u.variables.set(c,p),p}if(t==="define"){e.args.length<2&&fe("define",">=2",e.args.length,e.line);let f=e.args[0],l;if(f.kind==="literal"?l=f.value:f.kind==="variable"?l=f.name:qe("define","first argument must be a symbol or string",e.line),e.args.length>=3){let p=e.args[1],m=e.args.length===3?e.args[2]:{kind:"sexpr",op:"do",args:e.args.slice(2)},g=(p.kind==="block"&&p.type==="Array"?p.fields.get("items")||[]:p.kind==="array"?p.items||[]:[]).map(h=>h.kind==="variable"?h.name.startsWith("$")?h.name:"$"+h.name:h.kind==="literal"?"$"+h.value:"$"+(h.name||h.value||"?"));return u.functions.set(l,{name:l,params:g,body:m}),null}let c=n(e.args[1]);if(c!=null&&c.kind==="function-value"){let p={name:l,params:c.params,body:c.body,capturedEnv:c.capturedEnv};if(c._call&&(p._call=c._call),u.functions.set(l,p),u.typeChecker){let m=c.params.map(()=>({kind:"type",name:"any"}));u.typeChecker.registerFunction(l,m,{kind:"type",name:"any"})}return c}else{let p={file:e.file,line:e.line||f.line,col:f.col,type:$r(c)};if(u.variables.has("$"+l)){if(process.env.FL_V12==="1")throw new ue(de.INVALID_FORM,`[v12] '${l}'\uC740(\uB294) \uC774\uBBF8 \uC815\uC758\uB410\uC2B5\uB2C8\uB2E4 (line ${e.line??"?"}). \uAC00\uBCC0 \uAC12\uC740 atom\uC744 \uC0AC\uC6A9\uD558\uC138\uC694:
355
+ (define ${l} (atom \uCD08\uAE30\uAC12)) \u2192 (swap! ${l} (fn [v] \uC0C8\uAC12))`,{fn:"define",varName:l},void 0,e.line);console.warn(`\u26A0\uFE0F [FreeLang] '${l}'\uC740(\uB294) \uC774\uBBF8 \uC815\uC758\uB410\uC2B5\uB2C8\uB2E4 (line ${e.line??"?"}). \uAC00\uBCC0 \uAC12\uC740 atom\uC744 \uC0AC\uC6A9\uD558\uC138\uC694: (define ${l} (atom ${JSON.stringify(c)})) \u2192 (swap! ${l} (fn [v] \uC0C8\uAC12))`)}return u.variables.set("$"+l,c,p),c}}if(t==="func-ref"){e.args.length<1&&fe("func-ref",">=1",e.args.length,e.line);let f=e.args[0].name||String(e.args[0]),l=u.functions.get(f);return l||Yf(f,e.line),{kind:"function-value",params:l.params,body:l.body,capturedEnv:u.variables.snapshot(),name:f}}if(t==="call"){e.args.length<1&&fe("call",">=1",e.args.length,e.line);let f=n(e.args[0]),l=e.args.slice(1).map(c=>n(c));if(f.kind==="builtin-function")return f.fn(l);if(f.kind==="function-value")return a(f,l);if(f.kind==="async-function-value")return i(f,l);if(typeof f=="string")return s(f,l);throw new Error(`call expects function-value, got ${f.kind||typeof f}`)}if(t==="compose"||t==="comp"){if(e.args.length<1)throw new Error(`${t} requires at least 1 function`);let f=e.args.map(c=>{let p=c.kind;return p==="variable"?{type:"name",name:c.name}:p==="literal"&&c.type==="symbol"?{type:"name",name:String(c.value)}:{type:"val",val:n(c)}}),l={kind:"function-value",name:`(${t})`,params:["__x__"],body:null,env:null};return l._call=c=>{let p=c;for(let m=f.length-1;m>=0;m--){let d=f[m];d.type==="val"?p=r.callFunctionValue(d.val,[p]):p=r.callUserFunction(d.name,[p])}return p},l}if(t==="pipe"){if(e.args.length<2)throw new Error("pipe requires at least a value and one function");let f=n(e.args[0]);for(let l=1;l<e.args.length;l++){let c=e.args[l],p;if(c.kind==="literal"&&c.type==="symbol"){let m=c.value;if(u.functions.has(m))p=s(m,[f]);else throw new Error(`Unknown function: ${m}`)}else if(c.kind==="variable"){let m=c.name;if(u.functions.has(m))p=s(m,[f]);else if(u.variables.has(m))p=o(u.variables.get(m),[f]);else throw new Error(`Unknown function or variable: ${m}`)}else{let m=n(c);p=o(m,[f])}f=p}return f}if(t==="->"){if(e.args.length<2)throw new Error("-> requires at least a value and one step");let f="__thread_first_tmp__",l=n(e.args[0]);for(let c=1;c<e.args.length;c++){let p=e.args[c],m=p.kind;if(m==="sexpr"){let d=p;u.variables.set(f,l);let g={kind:"variable",name:f},h={kind:"sexpr",op:d.op,args:[g,...d.args]};l=n(h),u.variables.delete(f)}else if(m==="variable"){let d=p.name;if(u.functions.has(d))l=s(d,[l]);else if(u.variables.has(d))l=o(u.variables.get(d),[l]);else throw new Error(`->: unknown function or variable: ${d}`)}else if(m==="literal"&&p.type==="symbol"){let d=p.value;if(u.functions.has(d))l=s(d,[l]);else throw new Error(`->: unknown function: ${d}`)}else{let d=n(p);l=o(d,[l])}}return l}if(t==="->>"){if(e.args.length<2)throw new Error("->> requires at least a value and one step");let f="__thread_last_tmp__",l=n(e.args[0]);for(let c=1;c<e.args.length;c++){let p=e.args[c],m=p.kind;if(m==="sexpr"){let d=p;u.variables.set(f,l);let g={kind:"variable",name:f},h={kind:"sexpr",op:d.op,args:[...d.args,g]};l=n(h),u.variables.delete(f)}else if(m==="variable"){let d=p.name;if(u.functions.has(d))l=s(d,[l]);else if(u.variables.has(d))l=o(u.variables.get(d),[l]);else throw new Error(`->>: unknown function or variable: ${d}`)}else if(m==="literal"&&p.type==="symbol"){let d=p.value;if(u.functions.has(d))l=s(d,[l]);else throw new Error(`->>: unknown function: ${d}`)}else{let d=n(p);l=o(d,[l])}}return l}if(t==="?."){if(e.args.length<1)return null;let f=n(e.args[0]);for(let l=1;l<e.args.length;l++){if(f==null)return null;let c=e.args[l],p;c.kind==="literal"?p=c.value:p=n(c),typeof p=="string"&&p.startsWith(":")&&(p=p.slice(1)),f=f instanceof Map?f.get(p)??f.get(":"+p)??null:f?.[String(p)]??null}return f??null}if(t==="as->"){if(e.args.length<3)throw new Error("as-> requires: (as-> val $name form ...)");let f=e.args[1],l;if(f.kind==="variable")l=f.name;else if(f.kind==="literal")l="$"+String(f.value);else throw new Error("as->: second arg must be a binding name like $v");let c=n(e.args[0]);u.variables.push();try{for(let p=2;p<e.args.length;p++)u.variables.set(l,c),c=n(e.args[p])}finally{u.variables.pop()}return c}if(t==="??"){if(e.args.length<2)throw new Error("?? requires at least 2 arguments");for(let f=0;f<e.args.length;f++){let l=n(e.args[f]);if(l!=null)return l}return null}if(t==="|>"){if(e.args.length<2)throw new Error("|> requires at least a value and one function");let f=n(e.args[0]);for(let l=1;l<e.args.length;l++){let c=e.args[l],p=c.kind;if(p==="sexpr"){let m=c,d=`__pipe_${l}__`;u.variables.set(d,f);let g={kind:"variable",name:d},h={kind:"sexpr",op:m.op,args:[...m.args,g],line:m.line};try{f=n(h)}finally{u.variables.delete(d)}}else if(p==="variable"){let m=c.name;u.functions.has(m)?f=s(m,[f]):u.variables.has(m)&&(f=o(u.variables.get(m),[f]))}else if(p==="literal"&&c.type==="symbol"){let m=String(c.value);u.functions.has(m)?f=s(m,[f]):u.variables.has(m)&&(f=o(u.variables.get(m),[f]))}else{let m=n(c);f=o(m,[f])}}return f}if(t==="let")return Qf(r,e.args);if(t==="if-let"||t==="when-let"){e.args.length<2&&fe(t,">=2",e.args.length,e.line);let f=e.args[0],l=f.kind==="block"&&f.type==="Array"?f.fields?.get("items")??[]:[];l.length<1&&qe(t,"binding \uD615\uD0DC\uAC00 [$x expr] \uC774\uC5B4\uC57C \uD568",e.line);let c,p=l[0];p.kind==="variable"||p.kind==="literal"?c=l:c=p.kind==="block"&&p.type==="Array"?p.fields?.get("items")??[]:[],c.length<2&&qe(t,"[$x expr] \uD615\uD0DC\uAC00 \uC798\uBABB\uB428",e.line);let m=c[0].kind==="variable"?c[0].name:c[0].kind==="literal"?String(c[0].value):"",d=n(c[1]);if(d!=null&&d!==!1){r.context.variables.push();try{let h={line:c[0].line,col:c[0].col,type:$r(d)};if(r.context.variables.set(m,d,h),t==="if-let")return n(e.args[1]);{let y=null;for(let k=1;k<e.args.length;k++)y=n(e.args[k]);return y}}finally{r.context.variables.pop()}}else return t==="if-let"&&e.args.length>=3?n(e.args[2]):null}if(t==="when"){e.args.length<2&&fe("when",">=2",e.args.length,e.line);let f=n(e.args[0]);if(f!=null&&f!==!1){let l=null;for(let c=1;c<e.args.length;c++)l=n(e.args[c]);return l}return null}if(t==="unless"){e.args.length<2&&fe("unless",">=2",e.args.length,e.line);let f=n(e.args[0]);if(f==null||f===!1){let l=null;for(let c=1;c<e.args.length;c++)l=n(e.args[c]);return l}return null}if(t==="set"){e.args.length!==2&&fe("set","exactly 2",e.args.length,e.line);let f=e.args[0],l;f.kind==="variable"?l=f.name:f.kind==="literal"&&f.type==="symbol"?l="$"+f.value:qe("set","first argument must be a variable",e.line);let c=n(e.args[1]);if(!u.variables.mutate(l,c))throw new Error(`set: variable ${l} not found in scope`);return c}if(t==="if"){let l=n(e.args[0])?e.args[1]:e.args[2]||null;if(l===null)return null;if(r.tcoMode&&l!==null){let c=l;if(c.kind==="sexpr"){let p=c.op,m=r.context;if(typeof p=="string"&&m.functions.has(p)){let d=c.args.map(g=>n(g));return Bc(p,d)}}}return n(l)}if(t==="cond")return Zf(r,e.args);if(t==="do"||t==="begin"||t==="progn"){if(e.args.length>=2){let l=n(e.args[0]);if(typeof l=="function"||l?.kind==="function-value"||l?.kind==="async-function-value"||l?.kind==="closure"){let m=e.args.slice(1).map(d=>n(d));if(typeof l=="function")return l(...m);if(l?.kind==="function-value"||l?.kind==="async-function-value")return r.callFunctionValue(l,m);if(l?.kind==="closure"){let d=l.params||[];u.variables.push();try{if(l["closure-env"])for(let[h,y]of Object.entries(l["closure-env"].vars||{}))u.variables.set(h,y);for(let h=0;h<d.length;h++)u.variables.set(d[h],m[h]??null);let g=null;for(let h of l.body||[])g=n(h);return g}finally{u.variables.pop()}}}let p=l;for(let m of e.args.slice(1)){if(Lt(m)&&Yn(m)){r.evalBlock(m),p=null;continue}p=n(m)}return p}let f=null;for(let l of e.args){if(Lt(l)&&Yn(l)){r.evalBlock(l),f=null;continue}f=n(l)}return f}if(t==="loop"){let f=e.args[0],l=e.args.slice(1),c=f.kind==="array"?f.items||[]:f.kind==="block"&&f.type==="Array"?f.fields?.get?.("items")||[]:[];if(c.length===3&&c[0].kind==="sexpr"){let k=c[0],v=c[1],$=c[2],M=k.op||"$i",O=n(k.args[0]);u.variables.push(),u.variables.set(M,O);let C=null;try{for(;;){let P=n(v);if(!(P!=null&&P!==!1))break;for(let R of l)C=n(R);let S=n($);u.variables.set(M,S)}return C}finally{u.variables.pop()}}let m=[],d=[];for(let k=0;k<c.length;k+=2){let v=c[k],$=c[k+1],M=v.kind==="variable"?v.name:v.kind==="literal"?String(v.value):String(v.name||v.value);m.push(M),d.push(n($))}u.variables.push();for(let k=0;k<m.length;k++)u.variables.set(m[k],d[k]);let g=null,h=1e5,y=0;try{for(;y++<h;){let k=!1;for(let v of l)if(g=n(v),g&&typeof g=="object"&&g.__FL_RECUR__){let $=g.__args;for(let M=0;M<m.length&&M<$.length;M++)u.variables.set(m[M],$[M]);k=!0;break}if(!k)break}}finally{u.variables.pop()}return g}if(t==="recur")return{__FL_RECUR__:!0,__args:e.args.map(l=>n(l))};if(t==="while"){let f=null;for(;n(e.args[0]);)for(let l=1;l<e.args.length;l++)f=n(e.args[l]);return f}if(t==="when-not"){if(e.args.length<2)return null;let f=n(e.args[0]);if(f==null||f===!1){let l=null;for(let c=1;c<e.args.length;c++)l=n(e.args[c]);return l}return null}if(t==="dotimes"){let f=e.args[0],l=f?.kind==="array"?f.items||[]:f?.fields?.get?.("items")||[];if(l.length<2)return null;let c=l[0]?.name||l[0]?.value||"",p=Number(n(l[1]));for(let m=0;m<p;m++){r.context.variables.push();try{r.context.variables.set(c,m);for(let d=1;d<e.args.length;d++)n(e.args[d])}finally{r.context.variables.pop()}}return null}if(t==="doseq"){let f=e.args[0],l=f?.kind==="array"?f.items||[]:f?.fields?.get?.("items")||[];if(l.length<2)return null;let c=l[0]?.name||l[0]?.value||String(l[0]?.value??""),p=n(l[1]);if(!Array.isArray(p))return null;for(let m of p){r.context.variables.push();try{r.context.variables.set(c,m);for(let d=1;d<e.args.length;d++)n(e.args[d])}finally{r.context.variables.pop()}}return null}if(t==="case"){if(e.args.length===0)return null;let f=n(e.args[0]),l=1;for(;l<e.args.length-1;){let c=n(e.args[l]);if(f===c)return n(e.args[l+1]);l+=2}return l===e.args.length-1?n(e.args[l]):null}if(t==="for"){let f=e.args[0],l=f?.kind==="array"?f.items||[]:f?.fields?.get?.("items")||[];if(l.length<2)return[];let c=l[0]?.name||l[0]?.value||"",p=n(l[1]);if(!Array.isArray(p))return[];let m=null;for(let g=2;g<l.length-1;g++){let h=l[g]?.value||l[g]?.name||"";if(h===":when"||h==="when"){m=l[g+1];break}}let d=[];for(let g of p){r.context.variables.push();try{if(r.context.variables.set(c,g),m){let y=n(m);if(!y&&y!==0)continue}let h=null;for(let y=1;y<e.args.length;y++)h=n(e.args[y]);d.push(h)}finally{r.context.variables.pop()}}return d}if(t==="and"){let f=!0;for(let l of e.args)if(f=n(l),!f)return f;return f}if(t==="or"){let f=null;for(let l of e.args)if(f=n(l),f!=null&&f!==!1)return f;return f}if(t==="map"&&e.args.length===3){let f=n(e.args[0]),l=e.args[1],c=e.args[2],m=(l.kind==="block"&&l.type==="Array"?l.fields.get?.("items")||[]:l.kind==="array"?l.items||[]:[]).map(d=>d.kind==="variable"?d.name:d.kind==="literal"?"$"+d.value:"$"+(d.name||d.value||"_"));return Array.isArray(f)&&m.length>0?f.map(d=>{u.variables.push(),u.variables.set(m[0],d);try{return n(c)}finally{u.variables.pop()}}):void 0}if(t==="deftest"||t==="describe"||t==="it"){let f=r.context;f._testResults||(f._testResults={passed:0,failed:0,errors:[]});let l=e.args.length>0?String(n(e.args[0])):"(anonymous)",c=e.args.slice(1);try{for(let p of c)n(p);f._testResults.passed++,process.stdout.write(` \u2713 ${l}
356
+ `)}catch(p){f._testResults.failed++;let m=p?.message??String(p);f._testResults.errors.push(` \u2717 ${l}: ${m}`),process.stdout.write(` \u2717 ${l}: ${m}
357
+ `)}return null}if(t==="is"){let f=e.args.length>0?n(e.args[0]):!1,l=e.args.length>1?String(n(e.args[1])):`Expected truthy, got: ${JSON.stringify(f)}`;if(!f)throw new Error(l);return f}if(t==="is="){e.args.length<2&&fe("is=","2",e.args.length,e.line);let f=n(e.args[0]),l=n(e.args[1]);if(!(JSON.stringify(f)===JSON.stringify(l)))throw new Error(`Expected ${JSON.stringify(f)}, got ${JSON.stringify(l)}`);return l}if(t==="run-tests"){let f=r.context,l=f._testResults??{passed:0,failed:0,errors:[]},c=l.passed+l.failed;return process.stdout.write(`
358
+ Test Results: ${l.passed}/${c} passed`),l.failed>0&&process.stdout.write(` (${l.failed} FAILED)`),process.stdout.write(`
359
+ `),f._testResults={passed:0,failed:0,errors:[]},{passed:l.passed,failed:l.failed,total:c}}if(t==="test-summary"){let l=r.context._testResults??{passed:0,failed:0,errors:[]};return new Map([["passed",l.passed],["failed",l.failed],["total",l.passed+l.failed],["errors",l.errors]])}if(t==="import"){e.args.length<1&&fe("import","1",e.args.length,e.line);let f=String(n(e.args[0])),l={...e,op:"use",args:e.args};return r.evalSpecialForm("use",l)}if(t==="migrate"){e.args.length<2&&fe("migrate","2",e.args.length,e.line);let f=n(e.args[0]),l=n(e.args[1]);if(!Array.isArray(l))throw new Error("migrate: second arg must be [[version sql] ...] array");let c=r.context;if(f==null){c._migrate_applied||(c._migrate_applied=new Set);let v=c._migrate_applied,$=0;for(let M of l){let O=Array.isArray(M)?M:[M],C=String(O[0]);v.has(C)||(v.add(C),$++,process.stdout.write(` [migrate] applied: ${C}
360
+ `))}return $===0&&process.stdout.write(` [migrate] up to date
361
+ `),{applied:$,total:l.length}}let p=r.context.functions.get("mariadb_exec")??r.context.functions.get("mariadb-exec"),m=r.context.functions.get("mariadb_query")??r.context.functions.get("mariadb-query");if(!p||!m)throw new Error("migrate: mariadb functions not loaded");let d=(v,$=[])=>o(p.body??p,[f,v,$]),g=(v,$=[])=>o(m.body??m,[f,v,$]);d(`CREATE TABLE IF NOT EXISTS _migrations (
362
+ version VARCHAR(255) PRIMARY KEY,
363
+ applied_at BIGINT NOT NULL
364
+ )`);let h=g("SELECT version FROM _migrations"),y=new Set((h??[]).map(v=>String(v.version??v[0]??""))),k=0;for(let v of l){let $=Array.isArray(v)?v:[v],M=String($[0]),O=String($[1]??"");y.has(M)||(d(O),d("INSERT INTO _migrations (version, applied_at) VALUES (?, ?)",[M,Date.now()]),k++,process.stdout.write(` [migrate] applied: ${M}
365
+ `))}return k===0&&process.stdout.write(` [migrate] up to date
366
+ `),{applied:k,total:l.length}}if(t==="memoize"){e.args.length<1&&fe("memoize","1",e.args.length,e.line);let f=n(e.args[0]),l=new Map;return(...c)=>{let p=JSON.stringify(c);if(l.has(p))return l.get(p);let m=o(f,c);return l.set(p,m),m}}if(t==="partial"){e.args.length<1&&fe("partial",">=1",e.args.length,e.line);let f=n(e.args[0]),l=e.args.slice(1).map(n);return(...c)=>{let p=[...l,...c];return typeof f=="function"?f(...p):o(f,p)}}if(t==="group-by"||t==="group_by"){e.args.length<2&&fe("group-by","2",e.args.length,e.line);let f=n(e.args[0]),l=n(e.args[1]);if(!Array.isArray(l))return new Map;let c=m=>{if(typeof f=="string"){let d=f.startsWith(":")?f.slice(1):f;return m instanceof Map?m.get(f)??m.get(d)??null:m?.[d]??m?.[f]??null}return typeof f=="function"?f(m):o(f,[m])},p=new Map;for(let m of l){let d=c(m);p.has(d)||p.set(d,[]),p.get(d).push(m)}return p}if(t==="return"){let f=e.args.length>0?n(e.args[0]):null;throw new Sr(f)}if(t==="map-vals"||t==="map_vals"||t==="map-keys"||t==="map_keys"){let f=t==="map-keys"||t==="map_keys";if(e.args.length===1){let l=n(e.args[0]);return l instanceof Map?f?[...l.keys()]:[...l.values()]:l&&typeof l=="object"&&!Array.isArray(l)?f?Object.keys(l):Object.values(l):[]}if(e.args.length===2){let l=n(e.args[0]),c=n(e.args[1]),p=(m,d)=>o(m,[d]);if(c instanceof Map){let m=new Map;for(let[d,g]of c.entries())m.set(f?p(l,d):d,f?g:p(l,g));return m}if(c&&typeof c=="object"&&!Array.isArray(c)){let m={};for(let[d,g]of Object.entries(c))m[f?String(p(l,d)):d]=f?g:p(l,g);return m}return c}}if(t==="defstruct"){if(e.args.length<2)throw new Error("defstruct requires a name and a field vector");let f=e.args[0],l=f.kind==="literal"?String(f.value):f.kind==="variable"?f.name:String(f.value??f.name??"");if(!l)throw new Error("defstruct: struct name is required");let c=e.args[1],p=[];if(c.kind==="block"&&c.type==="Array"){let h=c.fields.get("items");if(Array.isArray(h))if((()=>{if(h.length%2!==0)return!0;let k=new Set(["int","float","number","string","bool","boolean","any","list","array","map","fn","function"]);for(let v=1;v<h.length;v+=2){let $=h[v],M=$?.kind==="keyword"||$?.kind==="variable"?$.name:$?.value;if(k.has(String(M)))return!1}return!0})())for(let k of h){let v=k,$=v.kind==="keyword"||v.kind==="variable"?v.name:v.kind==="literal"?String(v.value):"";$&&p.push({name:$,type:"any"})}else for(let k=0;k<h.length;k+=2){let v=h[k],$=h[k+1],M=v.kind==="keyword"||v.kind==="variable"?v.name:v.kind==="literal"?String(v.value):"",O=$===void 0?"any":$.kind==="keyword"||$.kind==="variable"?$.name:$.kind==="literal"?String($.value):"any";M&&p.push({name:M,type:O})}}let m=u.structs;m.define({name:l,fields:p});let d=m.makeConstructor(l);u.functions.set(l,{name:l,params:p.map(h=>h.name),body:{kind:"literal",type:"null",value:null},capturedEnv:new Map([["__struct_ctor__",d]])}),u[`__native_${l}`]=d;let g=m.makePredicate(l);u[`__native_${l}?`]=g;for(let h of p){let y=`${l}.${h.name}`,k=m.makeAccessor(l,h.name);u[`__native_${y}`]=k}return null}if(t==="defmacro"){if(e.args.length<3)throw new Error("defmacro requires name, params, and body");let f=e.args[0],l=f.kind==="literal"?String(f.value):f.kind==="variable"?f.name:String(f.value??f.name??""),c=e.args[1],p=[];if(c.kind==="block"&&c.type==="Array"){let d=c.fields.get("items");if(Array.isArray(d))for(let g of d)g.kind==="variable"?p.push(g.name.startsWith("$")?g.name:"$"+g.name):g.kind==="literal"&&p.push("$"+g.value)}let m=e.args[2];return u.macroExpander.define(l,p,m),null}if(t==="macroexpand"){if(e.args.length<1)throw new Error("macroexpand requires 1 argument");let f=e.args[0],l=u.macroExpander.expand(f);return u.macroExpander.astToString(l)}if(t==="defprotocol"){if(e.args.length<1)throw new Error("defprotocol requires a name");let f=e.args[0],l=f.kind==="variable"?f.name:f.kind==="literal"?String(f.value):String(f.name??f.value??""),c=[];for(let p=1;p<e.args.length;p++){let m=e.args[p];if(m.kind!=="block"||m.type!=="Array")continue;let d=m.fields.get("items");if(!Array.isArray(d)||d.length<1)continue;let g=d[0],h=g.kind==="variable"?g.name:g.kind==="literal"?String(g.value):String(g.name??g.value??""),y=[];if(d.length>1){let v=d[1];if(v.kind==="block"&&v.type==="Array"){let $=v.fields.get("items");if(Array.isArray($))for(let M of $)M.kind==="variable"?y.push(M.name):M.kind==="literal"&&y.push("$"+M.value)}}let k;if(d.length>2){let v=d[2];v.kind==="keyword"?k=v.name:v.kind==="literal"&&(k=String(v.value))}c.push({name:h,params:y,returnType:k})}return u.protocols.defineProtocol({name:l,methods:c}),null}if(t==="impl"){if(e.args.length<3)throw new Error("impl requires protocol name, type name, and at least one method");let f=e.args[0],l=f.kind==="variable"?f.name:f.kind==="literal"?String(f.value):String(f.name??f.value??""),c=e.args[1],p=c.kind==="variable"?c.name:c.kind==="literal"?String(c.value):String(c.name??c.value??""),m=new Map;for(let d=2;d<e.args.length;d++){let g=e.args[d];if(g.kind!=="block"||g.type!=="Array")continue;let h=g.fields.get("items");if(!Array.isArray(h)||h.length<3)continue;let y=h[0],k=y.kind==="variable"?y.name:y.kind==="literal"?String(y.value):String(y.name??y.value??""),v=[],$=h[1];if($.kind==="block"&&$.type==="Array"){let O=$.fields.get("items");if(Array.isArray(O))for(let C of O)C.kind==="variable"?v.push(C.name):C.kind==="literal"&&v.push("$"+C.value)}let M=h[2];m.set(k,{params:v,body:M})}return u.protocols.defineImpl({protocolName:l,typeName:p,methods:m}),null}if(t==="parallel"){if(e.args.length===0)return[];let f=[];for(let l of e.args){let c=n(l);if(c&&typeof c=="object"&&typeof c.getValue=="function")try{c=c.getValue()}catch{c=null}f.push(c)}return f}if(t==="race"){if(e.args.length===0)return null;let f;for(let l of e.args){let c=n(l);if(c&&typeof c=="object"&&typeof c.getValue=="function")try{c=c.getValue()}catch{c=null}if(f===void 0&&(f=c),c!=null)return c}return f??null}if(t==="with-timeout"){if(e.args.length<2)return null;try{let f=n(e.args[1]);if(f&&typeof f=="object"&&typeof f.getValue=="function")try{f=f.getValue()}catch{f=null}return f}catch{return null}}if(t==="fl-try"){if(e.args.length<1)throw new Error("fl-try requires at least 1 argument");let f=e.args[0],l=new Set(["on-err","on-type-error","on-not-found","on-io","on-arity","on-ai","on-timeout","on-runtime","default"]),c=new Map,p=1;for(;p<e.args.length;){let d=e.args[p],g=null;if(d.kind==="keyword"){let h=String(d.name??d.value??"");l.has(h)&&(g=h)}else if(d.kind==="literal"&&d.type==="string"){let h=d.value.startsWith(":")?d.value.slice(1):d.value;l.has(h)&&(g=h)}g!==null&&p+1<e.args.length?(c.set(g,n(e.args[p+1])),p+=2):p++}let m;try{let d=n(f);d&&typeof d=="object"&&(d._tag==="Ok"||d._tag==="Err")?m=d:m=qt(d)}catch(d){m=ns(d)}if(yn(m)){let d=m,g={"on-type-error":"type-error","on-not-found":"not-found","on-io":"io-error","on-arity":"arity-error","on-ai":"ai-error","on-timeout":"timeout"},h=!1;for(let[y,k]of Object.entries(g))if(c.has(y)&&d.category===k){let v=c.get(y);return a(v,[d])}if(!h&&c.has("on-err")){let y=c.get("on-err");return a(y,[d])}if(!h&&c.has("default")){let y=c.get("default");return a(y,[d])}return m}return m}throw new Error(`evalSpecialForm: unknown op "${t}"`)}function Qf(r,t){if(t.length<2)throw new Error("let requires at least 2 arguments");let e=t[0],n=r.context,s=o=>r.eval(o),a=o=>{if(o?.kind==="variable"){let u=o.name;return u.startsWith("$")?u:"$"+u}if(o?.kind==="literal"&&o.type==="symbol"){let u=o.value;return u.startsWith("$")?u:"$"+u}throw new Error(`Invalid binding variable: expected symbol or variable, got ${o?.kind}`)};if(n.variables.push(),e.kind==="block"&&e.type==="Array"){let o=e.fields.get("items");if(Array.isArray(o)&&o.length>0){let u=o[0]?.kind==="block"&&o[0]?.type==="Array";if(u){for(let f=0;f<o.length;f+=2)if(!(o[f]?.kind==="block"&&o[f]?.type==="Array"))throw n.variables.pop(),new Error(`let: 2\uCC28\uC6D0 \uBC14\uC778\uB529\uC5D0\uC11C \uC6D0\uC18C ${f}\uAC00 \uBC30\uC5F4\uC774 \uC544\uB2D8`)}if(u){for(let f of o)if(f.kind==="block"&&f.type==="Array"){let l=f.fields.get("items");if(Array.isArray(l)&&l.length>=2){let c=a(l[0]),p=s(l[1]),m={line:l[0].line,col:l[0].col,type:$r(p)};n.variables.set(c,p,m)}}}else{if(o.length%2!==0)throw n.variables.pop(),new Error(`let: expected even number of binding items, got ${o.length}`);for(let f=0;f<o.length;f+=2){let l=o[f];if(l?.kind==="block"&&l?.type==="Map"){let g=l.fields?.get("keys");if(g?.kind==="block"&&g?.type==="Array"){let h=s(o[f+1]),y=g.fields.get("items")??[];for(let k of y){let v=k?.kind==="literal"&&k?.type==="symbol"?k.value:k?.kind==="variable"?k.name.replace(/^\$/,""):null;if(v!==null){let $=v.startsWith("$")?v:"$"+v,M=h!==null&&typeof h=="object"?h[v]??null:null;n.variables.set($,M,{line:k.line,col:k.col,type:$r(M)})}}}continue}let c=a(l),p=s(o[f+1]),m={line:o[f].line,col:o[f].col,type:$r(p)};n.variables.set(c,p,m)}}}}let i=null;try{for(let o=1;o<t.length;o++)i=s(t[o])}finally{n.variables.pop()}return i}function Zf(r,t){let e=a=>r.eval(a),n=t[0],s=n?.kind==="block"&&n?.type==="Array"||n?.kind==="sexpr"&&n?.op==="do";if(t.length>=2&&!s){let a=0;for(;a<t.length-1;){let i=t[a],u=i?.kind==="variable"&&(i?.name==="else"||i?.name===":else"||i?.name==="$else")?!0:e(i);if(u!=null&&u!==!1)return e(t[a+1]);a+=2}return a<t.length?e(t[a]):null}for(let a of t){let i=null,o=[];if(a.kind==="block"&&a.type==="Array"){let u=a.fields.get("items");if(Array.isArray(u)&&u.length>=2){let f=u[0];i=f?.kind==="variable"&&(f?.name==="else"||f?.name===":else"||f?.name==="$else")?{kind:"literal",type:"boolean",value:!0}:f,o=u.slice(1)}}else if(a.kind==="sexpr"&&a.op==="do"&&a.args.length>=2)i=a.args[0],o=a.args.slice(1);else if(a.kind==="sexpr"&&a.args.length>=1){let u=a;i={kind:"literal",type:"boolean",value:u.op==="true"?!0:u.op==="false"?!1:u.op==="else"?!0:void 0},i.value===void 0&&(i={kind:"variable",name:u.op.startsWith("$")?u.op:"$"+u.op}),o=u.args}if(i&&o.length>=1&&e(i)){let f=null;for(let l of o)f=e(l);return f}}return null}function Vc(r,t){let{stages:e,metadata:n,feedbackLoop:s}=t,a=r.logger,i=r.context;i.reasoning||(i.reasoning=new Map);let o=new Date().getTime(),u=[],f=[],l=[];a.info(`\u{1F504} REASONING SEQUENCE START (${e.length} stages, feedback: ${s?.enabled?"enabled":"disabled"})`);let c=e,p=0,m=s?.maxIterations||1;for(t.context||(t.context={}),t.context.searches||(t.context.searches=new Map),t.context.learned||(t.context.learned=new Map),i.currentSearches=t.context.searches,i.currentLearned=t.context.learned;p<m;){p++,p>1&&a.info(`\u{1F504} FEEDBACK LOOP ITERATION ${p}/${m} (damping: ${(s?.confidenceDamping||.1).toFixed(1)})`);let y=[],k=null;for(let $=0;$<c.length;$++){let M=c[$],O=$+1;if(M.kind==="search-block"){let E=M;a.info(` [${O}/${c.length}] \u{1F50E} SEARCH`);let T=r.handleSearchBlock(E);t.context||(t.context={}),t.context.searches||(t.context.searches=new Map),t.context.searches.set(`search_${$}`,T),y.push(T),u.push("search"),a.info(" \u2713 Search result stored in context");continue}if(M.kind==="learn-block"){let E=M;a.info(` [${O}/${c.length}] \u{1F4DA} LEARN`);let T=r.handleLearnBlock(E);t.context||(t.context={}),t.context.learned||(t.context.learned=new Map);let B=E.key||`learn_${$}`;t.context.learned.set(B,T),y.push(T),u.push("learn"),a.info(` \u2713 Learned data stored in context (key: ${B})`);continue}let C=M;if(C.kind!=="reasoning-block")throw new Error(`Unexpected stage kind in reasoning sequence: ${M.kind}`);let P={observe:"\u{1F440}",analyze:"\u{1F50D}",decide:"\u{1F3AF}",act:"\u26A1",verify:"\u2705"}[C.stage]||"\u2753";if(a.info(` [${O}/${c.length}] ${P} ${C.stage.toUpperCase()}`),C.whenGuard&&!mi(r,C.whenGuard)){a.info(" \u23ED\uFE0F SKIPPED (when guard condition false)");continue}let _=C;p>1&&C.metadata?.confidence!==void 0&&(_={...C,metadata:{...C.metadata,confidence:Math.max(0,(C.metadata.confidence||1)-(s?.confidenceDamping||.1)*(p-1))}});let S=_;if(C.conditional){let E=mi(r,C.conditional.condition),T=E?C.conditional.thenBlock:C.conditional.elseBlock;if(T)S=T,a.info(` ${E?"\u2713":"\u2717"} IF condition ${E?"TRUE":"FALSE"}`);else if(!E&&!C.conditional.elseBlock){a.info(" \u23ED\uFE0F SKIPPED (if condition false, no else block)");continue}}let R;if(C.loopControl){let{type:E,condition:T,maxIterations:B=1e3}=C.loopControl,U=Math.min(B,1e3),b=0;for(;b<U;){b++;let w=mi(r,T);if(!(E==="repeat-until"?!w:w)&&b>1)break;R=r.handleReasoningBlock(S),a.info(` \u{1F501} ${E.toUpperCase()} ITERATION ${b}/${U}`)}}else R=r.handleReasoningBlock(S);if(y.push(R),u.push(C.stage),C.stage==="verify"&&(k=R),C.transitions&&C.transitions.length>0)for(let E of C.transitions)E.condition&&r.eval(E.condition)&&E.to&&a.info(` \u2193 Transition to: ${E.to}`)}if(f.push(...y),l.push({iteration:p,results:y,verifyConfidence:k?.metadata?.confidence}),s?.enabled&&p<m&&k&&em(r,k,s)){a.info(`\u21A9\uFE0F FEEDBACK TRIGGERED: Returning to "${s.toStage}" stage`);let $=c.findIndex(M=>M.stage===s.toStage);$>=0&&(c=c.slice($))}else break}let d={kind:"reasoning-sequence-result",stages:f,executionPath:u,iterations:l.length,feedbackTriggered:p>1,metadata:{...n,sequenceId:o,completedAt:new Date().toISOString(),totalStages:e.length,iterations:p},completed:!0},g=`sequence-${o}`;i.reasoning.set(g,d);let h=f.reduce((y,k)=>y+(k.metadata?.confidence||0),0)/Math.max(f.length,1);return a.info(`\u2705 REASONING SEQUENCE COMPLETE (${e.length} stages, ${p} iterations, confidence: ${(h*100).toFixed(0)}%)`),d}function em(r,t,e){let s=t?.metadata?.confidence||0;if(e.condition)try{return r.eval(e.condition)}catch{return s<.8}return s<.8}function mi(r,t){if(!t)return!1;try{let e=r.eval(t);return typeof e=="boolean"?e:typeof e=="number"?e!==0:typeof e=="string"?e.length>0:e==null?!1:!!e}catch{return!1}}function zc(r,t){let{query:e,source:n="web",cache:s=!0,limit:a=10,name:i}=t;r.logger.info(`\u{1F50E} SEARCH "${e}"`);try{let o=r.searchAdapter.searchSync(e,{limit:a,cache:s}),u={kind:"search-result",query:e,source:n,cache:s,limit:a,name:i,status:"completed",results:o,count:o.length,timestamp:new Date().toISOString()};r.context.cache||(r.context.cache=new Map);let f=i||`search_${Date.now()}`;return r.context.cache.set(f,u),u}catch(o){return r.logger.error(`\u274C Search failed: ${o.message}`),{kind:"search-error",query:e,message:o.message,timestamp:new Date().toISOString()}}}function Wc(r,t){let{key:e,data:n,source:s="search",confidence:a=.85,timestamp:i}=t;r.context.learned||(r.context.learned=new Map);try{if(n===null){let o=r.learnedFactsStore.load(e);return o?(r.logger.info(`\u{1F4DA} LEARN (recall) "${e}" (confidence: ${(o.confidence*100).toFixed(0)}%)`),r.context.learned.set(e,{data:o.data,source:o.source,confidence:o.confidence,timestamp:new Date(o.timestamp).toISOString()}),{kind:"learn-result",operation:"recall",key:e,data:o.data,source:o.source,confidence:o.confidence,timestamp:new Date(o.timestamp).toISOString(),found:!0,accessCount:o.accessCount}):(r.logger.info(`\u{1F4DA} LEARN (recall) "${e}" - not found`),{kind:"learn-result",operation:"recall",key:e,data:null,found:!1})}if(a<0||a>1)throw new Error(`Invalid confidence: ${a}.`);return r.learnedFactsStore.save(e,n,{confidence:a,source:s,ttlDays:30}),r.context.learned.set(e,{data:n,source:s,confidence:a,timestamp:i??new Date().toISOString()}),r.logger.info(` \u2713 Learned data stored in context (key: ${e})`),{kind:"learn-result",operation:"learn",key:e,data:n,source:s,confidence:a,timestamp:i??new Date().toISOString(),saved:"disk"}}catch(o){return r.logger.error(`\u274C Learn failed: ${o.message}`),{kind:"learn-error",key:e,message:o.message,timestamp:new Date().toISOString()}}}function Hc(r,t){let{stage:e,data:n,observations:s,analysis:a,decisions:i,actions:o,verifications:u,metadata:f,transitions:l}=t;r.context.reasoning||(r.context.reasoning=new Map);let c={stage:e,data:Object.fromEntries(n),observations:s,analysis:a,decisions:i,actions:o,verifications:u,metadata:{...f,completedAt:new Date().toISOString()},transitions:l||[]},p=`${e}-${new Date().getTime()}`;r.context.reasoning.set(p,c);let d=`${{observe:"\u{1F440}",analyze:"\u{1F50D}",decide:"\u{1F3AF}",act:"\u26A1",verify:"\u2705"}[e]||"\u2753"} ${e.toUpperCase()}`;switch(e){case"observe":s&&s.length>0&&(d+=`: ${s.length} observations`);break;case"analyze":{let g=r.context.currentSearches;g&&g.size>0&&(d+=` [using ${g.size} search result(s)]`);let h=n.get("angles");h instanceof Map&&(d+=`: ${h.size} angles analyzed`);let y=n.get("selected");y&&(d+=`, selected: "${y.value||y}"`);break}case"decide":{let g=r.context.currentLearned;g&&g.size>0&&(d+=` [using ${g.size} learned fact(s)]`);let h=n.get("choice");h&&(d+=`: "${h.value||h}"`);let y=n.get("reason");y&&(d+=` (${y.value||y})`);break}case"act":{let g=n.get("action");g&&(d+=`: "${g.value||g}"`);break}case"verify":{let g=n.get("result");g&&(d+=`: ${g.value||g}`),f?.confidence!==void 0&&(d+=` (confidence: ${(f.confidence*100).toFixed(0)}%)`);break}}return r.logger.info(d),{kind:"reasoning-result",stage:e,data:Object.fromEntries(n),observations:s,analysis:a,decisions:i,actions:o,verifications:u,metadata:c.metadata,stateKey:p,completed:!0}}var Xe=z(require("fs")),Ue=z(require("path"));un();nt();un();function Gc(r){return Array.isArray(r)?r.map(t=>{if(typeof t=="string")return t.startsWith("$")?t.substring(1):t;if(Ro(t))return t.name;if(Mo(t))return String(t.value);throw new Error(`extractParamNames: unknown param node type '${t?.kind??typeof t}'`)}):[]}be();ke();var Kc=new Map;function Jc(r,t){let e=t.name,n=t.exports||[],s=t.body||[],a=new Map;for(let o of s)if(ya(o)){let u=o.name,f=o.fields?.get("params")||[],l=Gc(f),c=o.fields?.get("body");if(!c||Array.isArray(c)&&(c=c[0],!c))continue;let p={name:u,params:l,body:c};a.set(u,p)}let i={name:e,exports:n,functions:a};r.getModules().set(e,i),r.logger.info(`\u2705 Module registered: ${e} (exports: ${n.join(", ")})`)}function Xc(r,t){let e=t.moduleName,n=t.source,s=t.selective,a=t.alias;if(n){let p=n.endsWith(".fl")||n.includes("/")||n.startsWith("./")||n.startsWith("../");if(!p){let m=(()=>{try{return Xe.statSync(r.currentFilePath).isDirectory()?r.currentFilePath:Ue.dirname(r.currentFilePath)}catch{return r.currentFilePath}})();p=[Ue.resolve(m,n+".fl"),Ue.resolve(m,n),Ue.resolve(process.cwd(),n+".fl"),Ue.resolve(process.cwd(),n)].some(g=>Xe.existsSync(g))}if(p){r.evalImportFromFile(n,e,s,a);return}}let i=r.getModules().get(e);if(!i)throw new mn(e,n);let o=[];s&&s.length>0?(o=s.filter(c=>i.exports.includes(c)),s.forEach(c=>{i.exports.includes(c)||r.logger.warn(`Function "${c}" not exported from module "${e}"`)})):o=[...i.exports],o.forEach(c=>{let p=i.functions.get(c);if(p)if(a){let m=`${a}:${c}`;r.context.functions.set(m,p)}else{let m=`${e}:${c}`;r.context.functions.set(m,p)}});let u=o.length,f=a?` as ${a}`:"",l=s?` (${s.join(", ")})`:"";r.logger.info(`\u2705 Imported ${u} function(s) from "${e}"${l}${f}`)}function Yc(r,t,e,n,s){let a=(()=>{try{return Xe.statSync(r.currentFilePath).isDirectory()?r.currentFilePath:Ue.dirname(r.currentFilePath)}catch{return r.currentFilePath}})(),i=p=>Xe.existsSync(p)&&Xe.statSync(p).isFile()?p:!p.endsWith(".fl")&&Xe.existsSync(p+".fl")?p+".fl":null,o=t.startsWith("./")||t.startsWith("../")||t.startsWith("/"),u=[];o?u.push(Ue.resolve(a,t)):(u.push(Ue.resolve(process.cwd(),t)),u.push(Ue.resolve(a,t)));let f=null;for(let p of u){let m=i(p);if(m){f=m;break}}if(!f)throw new Error(`Import error: file not found: ${t} (tried: ${u.join(", ")})`);let l=Kc.get(f);if(!l){if(r.importedFiles.has(f))return;r.importedFiles.add(f);let p=Xe.readFileSync(f,"utf-8"),m=new we;m.currentFilePath=f,m.importedFiles=r.importedFiles;let d=new Set(m.context.functions.keys());if(m.interpret(H(W(p))),process.env.FL_IMPORT_DEBUG==="1"){let y=[];for(let k of m.context.functions.keys())d.has(k)||y.push(k);console.log(`import.debug file=${f} user_funcs=${y.join(",")}`)}let g=new Map;for(let[y,k]of m.context.functions)d.has(y)||g.set(y,k);let h=new Map(m.context.variables.snapshot());l={functions:g,variables:h},Kc.set(f,l)}let c=s??e;for(let[p,m]of l.functions)n&&n.length>0?n.includes(p)&&r.context.functions.set(p,m):r.context.functions.set(`${c}:${p}`,m);for(let[p,m]of l.variables)n&&n.length>0?n.includes(p)&&r.context.variables.setGlobal(p,m):r.context.variables.setGlobal(`${c}:${p}`,m)}function Qc(r,t){let e=t.moduleName,n=t.source,s=r.getModules().get(e);if(!s)throw new mn(e,n);s.exports.forEach(a=>{let i=s.functions.get(a);i&&r.context.functions.set(a,i)}),r.logger.info(`\u2705 Opened module "${e}" (${s.exports.length} function(s) available globally)`)}var Un=require("crypto");var K=z(require("fs")),vs=z(require("path"));function Zc(){return{file_read:r=>{try{return K.readFileSync(r,"utf-8")}catch(t){throw new Error(`file_read failed for '${r}': ${t.message}`)}},file_write:(r,t)=>{try{let e=vs.dirname(r);return e!=="."&&!K.existsSync(e)&&K.mkdirSync(e,{recursive:!0}),K.writeFileSync(r,t,"utf-8"),!0}catch(e){throw new Error(`file_write failed for '${r}': ${e.message}`)}},file_exists:r=>K.existsSync(r),file_delete:r=>{try{return K.existsSync(r)?(K.unlinkSync(r),!0):!1}catch(t){throw new Error(`file_delete failed for '${r}': ${t.message}`)}},file_append:(r,t)=>{try{let e=vs.dirname(r);return e!=="."&&!K.existsSync(e)&&K.mkdirSync(e,{recursive:!0}),K.appendFileSync(r,t,"utf-8"),!0}catch(e){throw new Error(`file_append failed for '${r}': ${e.message}`)}},file_copy:(r,t)=>{try{let e=vs.dirname(t);return e!=="."&&!K.existsSync(e)&&K.mkdirSync(e,{recursive:!0}),K.copyFileSync(r,t),!0}catch(e){throw new Error(`file_copy failed from '${r}' to '${t}': ${e.message}`)}},dir_create:r=>{try{return K.existsSync(r)||K.mkdirSync(r,{recursive:!0}),!0}catch(t){throw new Error(`dir_create failed for '${r}': ${t.message}`)}},dir_list:r=>{try{if(!K.existsSync(r))throw new Error(`Directory not found: '${r}'`);return K.readdirSync(r)}catch(t){throw new Error(`dir_list failed for '${r}': ${t.message}`)}},dir_delete:r=>{try{return K.existsSync(r)?(K.rmdirSync(r),!0):!1}catch(t){throw new Error(`dir_delete failed for '${r}': ${t.message}`)}},file_size:r=>{try{return K.statSync(r).size}catch(t){throw new Error(`file_size failed for '${r}': ${t.message}`)}},file_is_file:r=>{try{return K.existsSync(r)?K.statSync(r).isFile():!1}catch{return!1}},file_is_dir:r=>{try{return K.existsSync(r)?K.statSync(r).isDirectory():!1}catch{return!1}},file_mtime:r=>{try{return K.statSync(r).mtimeMs}catch(t){throw new Error(`file_mtime failed for '${r}': ${t.message}`)}},file_ctime:r=>{try{return K.statSync(r).ctimeMs}catch(t){throw new Error(`file_ctime failed for '${r}': ${t.message}`)}},file_read_or:(r,t=null)=>{try{return K.readFileSync(r,"utf-8")}catch{return t??null}}}}var Oe=z(require("fs")),Tt=new Map,tm=1e3;function el(){return{fd_open:(r,t)=>{try{let e;switch(t){case"r":e="r";break;case"w":e="w";break;case"a":e="a";break;default:throw new Error(`Invalid mode: ${t}. Use "r", "w", or "a"`)}let n=Oe.openSync(r,e),s=tm++;return Tt.set(s,n),s}catch(e){throw new Error(`fd_open failed for '${r}' (${t}): ${e.message}`)}},fd_write:(r,t)=>{try{let e=Tt.get(r);if(e===void 0)throw new Error(`Invalid file descriptor: ${r}`);return Oe.writeSync(e,t,"utf-8"),!0}catch(e){throw new Error(`fd_write failed on fd ${r}: ${e.message}`)}},fd_fsync:r=>{try{let t=Tt.get(r);if(t===void 0)throw new Error(`Invalid file descriptor: ${r}`);return Oe.fsyncSync(t),!0}catch(t){throw new Error(`fd_fsync failed on fd ${r}: ${t.message}`)}},fd_close:r=>{try{let t=Tt.get(r);if(t===void 0)throw new Error(`Invalid file descriptor: ${r}`);return Oe.closeSync(t),Tt.delete(r),!0}catch(t){throw new Error(`fd_close failed on fd ${r}: ${t.message}`)}},fd_read:(r,t)=>{try{let e=Tt.get(r);if(e===void 0)throw new Error(`Invalid file descriptor: ${r}`);let n=Buffer.alloc(t),s=Oe.readSync(e,n,0,t);return n.toString("utf-8",0,s)}catch(e){throw new Error(`fd_read failed on fd ${r}: ${e.message}`)}},fd_seek:(r,t,e)=>{try{let n=Tt.get(r);if(n===void 0)throw new Error(`Invalid file descriptor: ${r}`);return Oe.fstatSync(n).size}catch(n){throw new Error(`fd_seek failed on fd ${r}: ${n.message}`)}},fd_flush:()=>{try{for(let r of Tt.values())Oe.fsyncSync(r);return!0}catch(r){throw new Error(`fd_flush failed: ${r.message}`)}}}}function tl(){return{bit_and:(r,t)=>(r&t)>>>0,bit_or:(r,t)=>(r|t)>>>0,bit_xor:(r,t)=>(r^t)>>>0,bit_not:r=>~r>>>0,bit_shl:(r,t)=>r<<t>>>0,bit_shr:(r,t)=>r>>>t>>>0,bit_sar:(r,t)=>r>>t>>>0,bit_popcount:r=>{r=r>>>0;let t=0;for(;r;)t+=r&1,r=r>>>1;return t},bit_test:(r,t)=>(r>>>t&1)===1,bit_set:(r,t)=>(r|1<<t)>>>0,bit_clear:(r,t)=>(r&~(1<<t))>>>0,bit_rotate_left:(r,t)=>(r=r>>>0,t=t%32,(r<<t|r>>>32-t)>>>0),bit_rotate_right:(r,t)=>(r=r>>>0,t=t%32,(r>>>t|r<<32-t)>>>0)}}var Ye=new Map,nl=2e3;function rl(r){return{set_interval:(t,e)=>{try{let n=t&&typeof t=="object"&&t.body!==void 0;if(typeof t!="string"&&!n)throw new Error(`Function name must be string or function, got ${typeof t}`);if(typeof e!="number"||e<1)throw new Error(`Interval must be positive number, got ${e}`);let s=nl++,i=setInterval(()=>{try{n?r.callFunction(t,[]):r.callUserFunction(t,[])}catch(o){console.error(`set_interval callback error for '${n?"<fn>":t}':`,o.message)}},e);return Ye.set(s,i),s}catch(n){throw new Error(`set_interval failed: ${n.message}`)}},clear_interval:t=>{try{let e=Ye.get(t);return e===void 0?!1:(clearInterval(e),Ye.delete(t),!0)}catch(e){throw new Error(`clear_interval failed: ${e.message}`)}},set_timeout:(t,e)=>{try{if(typeof t!="string")throw new Error(`Function name must be string, got ${typeof t}`);if(typeof e!="number"||e<1)throw new Error(`Timeout must be positive number, got ${e}`);let n=nl++,a=setTimeout(()=>{try{r.callUserFunction(t,[])}catch(i){console.error(`set_timeout callback error for '${t}':`,i.message)}Ye.delete(n)},e);return Ye.set(n,a),n}catch(n){throw new Error(`set_timeout failed: ${n.message}`)}},clear_timeout:t=>{try{let e=Ye.get(t);return e===void 0?!1:(clearTimeout(e),Ye.delete(t),!0)}catch(e){throw new Error(`clear_timeout failed: ${e.message}`)}},timer_count:()=>Ye.size,timer_clear_all:()=>{try{for(let t of Ye.values())clearInterval(t),clearTimeout(t);return Ye.clear(),!0}catch(t){throw new Error(`timer_clear_all failed: ${t.message}`)}}}}function sl(){return{error_message:r=>r instanceof Error?r.message:typeof r=="string"?r:r&&typeof r=="object"&&r.message?String(r.message):String(r),error_type:r=>{if(r&&typeof r=="object"&&r.type)return String(r.type);if(r instanceof Error){let t=r.constructor.name;return t==="Error"?"RuntimeError":t}return"RuntimeError"},is_error:r=>r instanceof Error||r&&typeof r=="object"&&r.message!==void 0,create_error:r=>new Error(r),create_typed_error:(r,t)=>{let e=new Error(t);return e.type=r,e},error_stack:r=>r instanceof Error&&r.stack?r.stack:"",with_fallback:(r,t)=>{try{return r&&typeof r=="object"&&r.kind==="function-value"?r:typeof r=="function"?r():r}catch(e){return t&&typeof t=="object"&&t.kind==="function-value"?t:typeof t=="function"?t(e):t}}}}var al=require("child_process"),ws=require("fs"),il=require("crypto");function Ct(r,t="GET",e,n,s=1e4){let a=null;try{let i={};if(e&&typeof e=="object"){let d=e instanceof Map?Array.from(e.entries()):Object.entries(e);for(let[g,h]of d)i[String(g)]=String(h)}a=`/tmp/fl-http-${(0,il.randomUUID)()}.js`;let o=JSON.stringify(r),u=JSON.stringify(t.toUpperCase()),f=JSON.stringify(i),l=n?JSON.stringify(n):"null",c=`
367
+ const {URL}=require('url');
368
+ const u=new URL(${o});
369
+ const mod=u.protocol==='https:'?require('https'):require('http');
370
+ const method=${u};
371
+ const hdrs=${f};
372
+ const bodyStr=${l};
373
+ const opts={hostname:u.hostname,port:u.port||undefined,path:u.pathname+(u.search||''),method,headers:hdrs};
374
+ if(bodyStr!=null)opts.headers['Content-Length']=Buffer.byteLength(bodyStr,'utf-8');
375
+ const chunks=[];
376
+ const req=mod.request(opts,res=>{
377
+ res.on('data',d=>chunks.push(d));
378
+ res.on('end',()=>{process.stdout.write(JSON.stringify({s:res.statusCode,b:Buffer.concat(chunks).toString('utf-8')}))});
379
+ });
380
+ let done=false;
381
+ const fail=(msg)=>{if(done)return;done=true;process.stdout.write(JSON.stringify({s:0,b:'',e:msg}))};
382
+ req.on('error',e=>fail(e.message));
383
+ req.on('socket',s=>{s.setTimeout(${s},()=>{req.destroy();fail('timeout')})});
384
+ req.setTimeout(${s},()=>{req.destroy();fail('timeout')});
385
+ if(bodyStr!=null)req.write(bodyStr,'utf-8');
386
+ req.end();`;(0,ws.writeFileSync)(a,c,"utf-8");let p=(0,al.execSync)(`node ${a}`,{encoding:"utf-8",timeout:s+2e3}),m=JSON.parse(p);return{status:m.s||0,body:m.b||"",...m.e&&{error:m.e}}}catch(i){return{status:0,body:"",error:i.message}}finally{if(a)try{(0,ws.unlinkSync)(a)}catch{}}}var le=Ct;function ol(){return{http_get:r=>{let t=le(r,"GET");return{status:t.status,body:t.body,...t.error&&{error:t.error}}},http_post:(r,t)=>{if(t!==null&&typeof t=="object"){let n=`http-post body\uC5D0 map\uC774 \uC804\uB2EC\uB410\uC2B5\uB2C8\uB2E4.
387
+ v12 \uC62C\uBC14\uB978 \uBC29\uC2DD: (http-post url (json-stringify body))
388
+ v12\uC5D0\uC11C\uB294 \uC790\uB3D9 \uC9C1\uB82C\uD654\uAC00 \uC81C\uAC70\uB429\uB2C8\uB2E4.`;if(process.env.FL_V12==="1")throw new Error(`[v12] ${n}`);console.warn(`\u26A0\uFE0F [FreeLang] ${n}`),t=JSON.stringify(t)}let e=le(r,"POST",{"Content-Type":"application/json"},t);return{status:e.status,body:e.body,...e.error&&{error:e.error}}},http_post_form:(r,t)=>{let e=le(r,"POST",{"Content-Type":"application/x-www-form-urlencoded"},t);return{status:e.status,body:e.body,...e.error&&{error:e.error}}},http_get_bearer:(r,t)=>{let e=le(r,"GET",{Authorization:`Bearer ${t}`});return{status:e.status,body:e.body,...e.error&&{error:e.error}}},http_put:(r,t)=>{let e=le(r,"PUT",{"Content-Type":"application/json"},t);return{status:e.status,body:e.body,...e.error&&{error:e.error}}},http_patch:(r,t)=>{let e=le(r,"PATCH",{"Content-Type":"application/json"},t);return{status:e.status,body:e.body,...e.error&&{error:e.error}}},http_delete:r=>{let t=le(r,"DELETE");return{status:t.status,body:t.body,...t.error&&{error:t.error}}},http_head:r=>{let t=le(r,"HEAD");return{status:t.status,body:"",...t.error&&{error:t.error}}},http_get_key:(r,t)=>{let e=le(r,"GET",{"X-API-Key":t});return{status:e.status,body:e.body,...e.error&&{error:e.error}}},http_post_key:(r,t,e)=>{let n=le(r,"POST",{"Content-Type":"application/json","X-API-Key":e},t);return{status:n.status,body:n.body,...n.error&&{error:n.error}}},http_status:r=>le(r,"GET").status,http_json:r=>{let t=le(r,"GET");if(t.error)return{status:0,data:null,error:t.error};try{return{status:t.status,data:JSON.parse(t.body)}}catch(e){return{status:t.status,data:null,error:e.message}}},http_header:(r,t)=>{try{return Ct(r,"HEAD").error,""}catch{return""}},http_with_timeout:(r,t)=>{let e=Ct(r,"GET");return{status:e.status,body:e.body}},http_post_json:(r,t)=>{let e=JSON.stringify(t),n=le(r,"POST",{"Content-Type":"application/json"},e);try{return{status:n.status,data:n.body?JSON.parse(n.body):null,...n.error&&{error:n.error}}}catch(s){return{status:n.status,data:null,error:s.message}}},http_put_json:(r,t)=>{let e=JSON.stringify(t),n=le(r,"PUT",{"Content-Type":"application/json"},e);try{return{status:n.status,data:n.body?JSON.parse(n.body):null,...n.error&&{error:n.error}}}catch(s){return{status:n.status,data:null,error:s.message}}},http_request:(r,t,e,n)=>{let s=le(t,r,e,n);return{status:s.status,body:s.body,...s.error&&{error:s.error}}},http_request_timeout:(r,t,e,n,s)=>{let a=Number(s)||5e3,i=Ct(t,r,e,n||void 0,a);return{status:i.status,body:i.body,...i.error&&{error:i.error}}},http_req_status:(r,t,e,n)=>le(t,r,e,n).status,http_get_json:(r,t)=>{let e=le(r,"GET",t);try{return{status:e.status,data:e.body?JSON.parse(e.body):null,...e.error&&{error:e.error}}}catch(n){return{status:e.status,data:null,error:n.message}}},http_get_json_bearer:(r,t)=>{let e=le(r,"GET",{Authorization:`Bearer ${t}`});try{return{status:e.status,data:e.body?JSON.parse(e.body):null,...e.error&&{error:e.error}}}catch(n){return{status:e.status,data:null,error:n.message}}},http_post_bearer:(r,t,e)=>le(r,"POST",{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},t),http_parallel:r=>{let t=(n,s)=>n?n instanceof Map?n.get(s):n[s]??n[":"+s]??null:null;return(Array.isArray(r)?r:[r]).map(n=>{let s=String(t(n,"url")||t(n,":url")||""),a=String(t(n,"method")||t(n,":method")||"GET").toUpperCase(),i=t(n,"token")||t(n,":token"),o=t(n,"body")||t(n,":body")||"",u={};return i&&(u.Authorization=`Bearer ${i}`),o&&(u["Content-Type"]="application/json"),Ct(s,a,u,o||void 0)})},http_retry:(r,t,e=3)=>{let n=Number(e)||3,s={status:0,body:""};for(let a=0;a<=n;a++){try{let i=le(r,"GET",{Authorization:`Bearer ${t}`});if(s=i,i.status>=200&&i.status<500)return i}catch(i){s={status:0,body:"",error:i.message}}if(a<n){let i=200*(a+1),o=Date.now();for(;Date.now()-o<i;);}}return s},http_retry_post:(r,t,e,n=3)=>{let s=Number(n)||3,a={status:0,body:""};for(let i=0;i<=s;i++){try{let o=le(r,"POST",{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},t);if(a=o,o.status>=200&&o.status<500)return o}catch(o){a={status:0,body:"",error:o.message}}if(i<s){let o=200*(i+1),u=Date.now();for(;Date.now()-u<o;);}}return a},is_http_success:r=>r>=200&&r<300,is_http_redirect:r=>r>=300&&r<400,is_http_error:r=>r>=400,"http-get-data":r=>{let t=Ct(r,"GET");if(!t.body)return null;try{return JSON.parse(t.body)}catch{return null}},"http-post-data":(r,t)=>{let e=typeof t=="string"?t:JSON.stringify(t),n=Ct(r,"POST",{"Content-Type":"application/json"},e);if(!n.body)return null;try{return JSON.parse(n.body)}catch{return null}},"http-get-status":r=>Ct(r,"GET").status}}var Xt=require("child_process");function cl(){return{shell:r=>{let t=(0,Xt.spawnSync)("sh",["-c",r],{timeout:3e4});if(t.error)throw new Error(`shell failed: ${t.error.message}`);if((t.status??1)!==0){let e=t.stderr?.toString().trim()??"";throw new Error(`shell failed (exit ${t.status})${e?": "+e:""}`)}return t.stdout?.toString()??""},shell_status:r=>(0,Xt.spawnSync)("sh",["-c",r],{timeout:3e4}).status??1,shell_ok:r=>((0,Xt.spawnSync)("sh",["-c",r],{timeout:3e4}).status??1)===0,shell_pipe:(r,t)=>{let e=(0,Xt.spawnSync)("sh",["-c",`${r} | ${t}`],{timeout:3e4});if(e.error)throw new Error(`shell_pipe failed: ${e.error.message}`);if((e.status??1)!==0){let n=e.stderr?.toString().trim()??"";throw new Error(`shell_pipe failed (exit ${e.status})${n?": "+n:""}`)}return e.stdout?.toString()??""},shell_capture:r=>{let t=(0,Xt.spawnSync)("sh",["-c",r],{encoding:"utf-8",timeout:3e4});return{stdout:t.stdout??"",stderr:t.stderr??"",code:t.status??1}},shell_exists:r=>((0,Xt.spawnSync)("which",[r],{timeout:5e3}).status??1)===0,shell_env:r=>{let t=process.env[r];return t===void 0||t===""?null:t},shell_cwd:()=>process.cwd()}}function ll(){return{json_get:(r,t)=>{let e=t.split("."),n=typeof r=="string"?JSON.parse(r):r;for(let s of e){if(n==null)return null;n=Array.isArray(n)?n[parseInt(s,10)]:n[s]}return n??null},json_set:(r,t,e)=>{let n=typeof r=="string"?JSON.parse(r):r,s=u=>{if(u instanceof Map)return new Map(u);if(Array.isArray(u))return u.map(s);if(typeof u=="object"&&u!==null){let f={};for(let[l,c]of Object.entries(u))f[l]=s(c);return f}return u},a=s(n),i=t.split("."),o=a;for(let u=0;u<i.length-1;u++){let f=i[u];(o[f]===void 0||o[f]===null)&&(o[f]={}),o=o[f]}return o[i[i.length-1]]=e,a},json_merge:(r,t)=>{let e=typeof r=="string"?JSON.parse(r):r,n=typeof t=="string"?JSON.parse(t):t;return{...e,...n}},json_deep_merge:(r,t)=>{let e=typeof r=="string"?JSON.parse(r):r,n=typeof t=="string"?JSON.parse(t):t;function s(a,i){if(typeof a!="object"||a===null||Array.isArray(a)||typeof i!="object"||i===null||Array.isArray(i))return i;let o={...a};for(let u of Object.keys(i))o[u]=u in a?s(a[u],i[u]):i[u];return o}return s(e,n)},json_keys:r=>{let t=typeof r=="string"?JSON.parse(r):r;return Object.keys(t)},json_vals:r=>{let t=typeof r=="string"?JSON.parse(r):r;return Object.values(t)},"map-entries":r=>r instanceof Map?[...r.entries()].map(([t,e])=>[t,e]):r&&typeof r=="object"&&!Array.isArray(r)?Object.entries(r).map(([t,e])=>[t,e]):[],map_entries:r=>r instanceof Map?[...r.entries()].map(([t,e])=>[t,e]):r&&typeof r=="object"&&!Array.isArray(r)?Object.entries(r).map(([t,e])=>[t,e]):[],json_parse:r=>{try{return JSON.parse(r)}catch(t){throw new Error(`json_parse: invalid JSON: ${t.message}`)}},_toSerializable:r=>{if(r instanceof Map)return Object.fromEntries(r);if(Array.isArray(r))return r.map(t=>r._toSerializable?.(t)??(t instanceof Map?Object.fromEntries(t):t));if(typeof r=="object"&&r!==null){let t={};for(let[e,n]of Object.entries(r))t[e]=n instanceof Map?Object.fromEntries(n):typeof n=="object"&&n!==null?r._toSerializable?.(n):n;return t}return r},json_str:function(r){let t=e=>{if(e instanceof Map)return Object.fromEntries(e);if(Array.isArray(e))return e.map(t);if(typeof e=="object"&&e!==null){let n={};for(let[s,a]of Object.entries(e))n[s]=t(a);return n}return e};return JSON.stringify(t(r))},json_stringify:function(r){let t=e=>{if(e instanceof Map)return Object.fromEntries(e);if(Array.isArray(e))return e.map(t);if(typeof e=="object"&&e!==null){let n={};for(let[s,a]of Object.entries(e))n[s]=t(a);return n}return e};return JSON.stringify(t(r))},json_pretty:function(r){let t=n=>{if(n instanceof Map)return Object.fromEntries(n);if(Array.isArray(n))return n.map(t);if(typeof n=="object"&&n!==null){let s={};for(let[a,i]of Object.entries(n))s[a]=t(i);return s}return n},e=typeof r=="string"?JSON.parse(r):t(r);return JSON.stringify(e,null,2)},"json-parse":r=>{try{return JSON.parse(r)}catch(t){throw new Error(`json-parse: invalid JSON: ${t.message}`)}},"json-stringify":function(r){let t=e=>{if(e instanceof Map)return Object.fromEntries(e);if(Array.isArray(e))return e.map(t);if(typeof e=="object"&&e!==null){let n={};for(let[s,a]of Object.entries(e))n[s]=t(a);return n}return e};return JSON.stringify(t(r))},"json-str":function(r){let t=e=>{if(e instanceof Map)return Object.fromEntries(e);if(Array.isArray(e))return e.map(t);if(typeof e=="object"&&e!==null){let n={};for(let[s,a]of Object.entries(e))n[s]=t(a);return n}return e};return JSON.stringify(t(r))},"json-pretty":function(r){let t=n=>{if(n instanceof Map)return Object.fromEntries(n);if(Array.isArray(n))return n.map(t);if(typeof n=="object"&&n!==null){let s={};for(let[a,i]of Object.entries(n))s[a]=t(i);return s}return n},e=typeof r=="string"?JSON.parse(r):t(r);return JSON.stringify(e,null,2)},"json-merge":(r,t)=>{let e=typeof r=="string"?JSON.parse(r):r,n=typeof t=="string"?JSON.parse(t):t;return{...e,...n}},"json-get":(r,t)=>{let e=String(t).split("."),n=typeof r=="string"?JSON.parse(r):r;for(let s of e){if(n==null)return null;n=Array.isArray(n)?n[parseInt(s,10)]:n[s]}return n??null},"json-set":(r,t,e)=>{let n=typeof r=="string"?JSON.parse(r):r,s=u=>{if(u instanceof Map)return new Map(u);if(Array.isArray(u))return u.map(s);if(typeof u=="object"&&u!==null){let f={};for(let[l,c]of Object.entries(u))f[l]=s(c);return f}return u},a=s(n),i=String(t).split("."),o=a;for(let u=0;u<i.length-1;u++){let f=i[u];(o[f]===void 0||o[f]===null)&&(o[f]={}),o=o[f]}return o[i[i.length-1]]=e,a},"json-keys":r=>r&&typeof r=="object"&&!Array.isArray(r)?Object.keys(r):[],"json-vals":r=>r&&typeof r=="object"&&!Array.isArray(r)?Object.values(r):[],"json-values":r=>r&&typeof r=="object"&&!Array.isArray(r)?Object.values(r):[],json_has:(r,t)=>{let e=typeof r=="string"?JSON.parse(r):r;return t in e},json_del:(r,t)=>{let n={...typeof r=="string"?JSON.parse(r):r};return delete n[t],n},csv_parse:r=>r.trim().split(`
389
+ `).map(e=>{let n=[],s="",a=!1;for(let i=0;i<e.length;i++){let o=e[i];o==='"'?a&&e[i+1]==='"'?(s+='"',i++):a=!a:o===","&&!a?(n.push(s),s=""):s+=o}return n.push(s),n}),csv_write:r=>r.map(t=>t.map(e=>{let n=String(e);return n.includes(",")||n.includes('"')||n.includes(`
390
+ `)?`"${n.replace(/"/g,'""')}"`:n}).join(",")).join(`
391
+ `),csv_header:r=>r[0]??[],csv_to_objects:r=>{if(r.length<2)return[];let t=r[0];return r.slice(1).map(e=>{let n={};return t.forEach((s,a)=>{n[s]=e[a]??""}),n})},"csv-parse":(r,t)=>{let e=t??",";return r.replace(/\r\n/g,`
392
+ `).replace(/\r/g,`
393
+ `).trim().split(`
394
+ `).filter(s=>s.trim()!=="").map(s=>{let a=[],i="",o=!1;for(let u=0;u<s.length;u++){let f=s[u];f==='"'?o&&s[u+1]==='"'?(i+='"',u++):o=!o:s.startsWith(e,u)&&!o?(a.push(i),i="",u+=e.length-1):i+=f}return a.push(i),a})},"csv-parse-map":(r,t)=>{let e=t??",",n=r.replace(/\r\n/g,`
395
+ `).replace(/\r/g,`
396
+ `).trim().split(`
397
+ `).filter(i=>i.trim()!=="");if(n.length<2)return[];let s=i=>{let o=[],u="",f=!1;for(let l=0;l<i.length;l++){let c=i[l];c==='"'?f&&i[l+1]==='"'?(u+='"',l++):f=!f:i.startsWith(e,l)&&!f?(o.push(u),u="",l+=e.length-1):u+=c}return o.push(u),o},a=s(n[0]);return n.slice(1).map(i=>{let o=s(i),u={};return a.forEach((f,l)=>{u[f]=o[l]??""}),u})},"csv-stringify":(r,t)=>{let e=t??",";return r.map(n=>n.map(s=>{let a=String(s??"");return a.includes(e)||a.includes('"')||a.includes(`
398
+ `)?`"${a.replace(/"/g,'""')}"`:a}).join(e)).join(`
399
+ `)},str_template:(r,t)=>r.replace(/\{(\w+)\}/g,(e,n)=>t[n]!==void 0?String(t[n]):`{${n}}`),str_lines:r=>r.split(`
400
+ `),str_join_lines:r=>r.join(`
401
+ `),str_trim:r=>r.trim(),str_words:r=>r.trim().split(/\s+/),str_count:(r,t)=>{let e=0,n=0;for(;(n=r.indexOf(t,n))!==-1;)e++,n+=t.length;return e},number_format:(r,t=0)=>{let e=Number(r);if(isNaN(e))return"0";let n=e.toFixed(t),[s,a]=n.split("."),i=s.replace(/\B(?=(\d{3})+(?!\d))/g,",");return a?`${i}.${a}`:i},to_fixed:(r,t=2)=>{let e=Number(r);return isNaN(e)?"0":e.toFixed(t)},format_currency:(r,t="KRW")=>{let e=Number(r);if(isNaN(e))return"0";let n={KRW:"\u20A9",USD:"$",EUR:"\u20AC",JPY:"\xA5",CNY:"\xA5",GBP:"\xA3"},s=t==="KRW"||t==="JPY"?0:2,a=e.toFixed(s),[i,o]=a.split("."),u=i.replace(/\B(?=(\d{3})+(?!\d))/g,","),f=n[t]??t+" ";return o?`${f}${u}.${o}`:`${f}${u}`},str_upper:r=>String(r).toUpperCase(),str_lower:r=>String(r).toLowerCase(),str_capitalize:r=>{let t=String(r);return t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()},str_title:r=>String(r).replace(/\b\w/g,t=>t.toUpperCase()),str_swapcase:r=>String(r).split("").map(t=>t===t.toUpperCase()?t.toLowerCase():t.toUpperCase()).join(""),str_reverse:r=>String(r).split("").reverse().join(""),str_repeat:(r,t)=>String(r).repeat(Number(t)),str_pad_left:(r,t,e=" ")=>String(r).padStart(Number(t),e||" "),str_pad_right:(r,t,e=" ")=>String(r).padEnd(Number(t),e||" "),str_center:(r,t,e=" ")=>{let n=String(r),s=Number(t);if(n.length>=s)return n;let a=s-n.length,i=Math.floor(a/2),o=a-i;return(e||" ").repeat(i)+n+(e||" ").repeat(o)},str_zfill:(r,t)=>String(r).padStart(Number(t),"0"),str_lstrip:(r,t)=>t?String(r).replace(new RegExp(`^[${t.replace(/[-\\]]/g,"\\$&")}]+`),""):String(r).trimStart(),str_rstrip:(r,t)=>t?String(r).replace(new RegExp(`[${t.replace(/[-\\]]/g,"\\$&")}]+$`),""):String(r).trimEnd(),str_replace:(r,t,e,n)=>{let s=String(r),a=n!==void 0?Number(n):1/0,i=0;return s.replace(new RegExp(t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),o=>i++<a?e:o)},str_starts:(r,t)=>String(r).startsWith(t),str_ends:(r,t)=>String(r).endsWith(t),str_includes:(r,t)=>String(r).includes(t),str_find:(r,t,e=0)=>String(r).indexOf(t,Number(e)),str_rfind:(r,t)=>String(r).lastIndexOf(t),str_index:(r,t,e=0)=>{let n=String(r).indexOf(t,Number(e));if(n===-1)throw new Error(`str_index: substring "${t}" not found`);return n},str_split:(r,t,e)=>{let n=String(r);if(e!==void 0){let s=[],a=0,i=Number(e);for(;i-- >0;){let o=t?n.indexOf(t,a):a+1;if(o===-1)break;s.push(n.slice(a,o)),a=o+(t?.length||1)}return s.push(n.slice(a)),s}return t?n.split(t):n.split("")},str_rsplit:(r,t,e)=>{let n=String(r);if(e===void 0)return t?n.split(t):n.split("");let s=[],a=n.length,i=Number(e);for(;i-- >0;){let o=n.lastIndexOf(t,a-1);if(o===-1)break;s.unshift(n.slice(o+t.length,a)),a=o}return s.unshift(n.slice(0,a)),s},str_join:(r,t)=>Array.isArray(r)?r.join(String(t??"")):Array.isArray(t)?t.join(String(r??"")):"","str-join":(r,t)=>Array.isArray(r)?r.join(String(t??"")):Array.isArray(t)?t.join(String(r??"")):"",str_partition:(r,t)=>{let e=String(r).indexOf(t);return e===-1?[r,"",""]:[r.slice(0,e),t,r.slice(e+t.length)]},str_rpartition:(r,t)=>{let e=String(r).lastIndexOf(t);return e===-1?["","",r]:[r.slice(0,e),t,r.slice(e+t.length)]},math_round_dec:(r,t)=>{let e=Math.pow(10,Number(t));return Math.round(Number(r)*e)/e},str_slice:(r,t,e)=>String(r).slice(Number(t),e!==void 0?Number(e):void 0),str_substr:(r,t,e)=>{let n=Number(t);return String(r).slice(n,n+Number(e))},str_removeprefix:(r,t)=>{let e=String(r);return e.startsWith(t)?e.slice(t.length):e},str_removesuffix:(r,t)=>{let e=String(r);return e.endsWith(t)?e.slice(0,-t.length):e},str_expandtabs:(r,t=8)=>String(r).replace(/\t/g," ".repeat(Number(t))),str_isalpha:r=>/^[a-zA-Z가-힣ㄱ-ㅎㅏ-ㅣ]+$/.test(String(r)),str_isdigit:r=>/^\d+$/.test(String(r)),str_isalnum:r=>/^[a-zA-Z0-9가-힣]+$/.test(String(r)),str_islower:r=>{let t=String(r);return t===t.toLowerCase()&&t!==t.toUpperCase()},str_isupper:r=>{let t=String(r);return t===t.toUpperCase()&&t!==t.toLowerCase()},str_isspace:r=>/^\s+$/.test(String(r)),str_istitle:r=>String(r)===String(r).replace(/\b\w/g,t=>t.toUpperCase()),str_encode_base64:r=>btoa(unescape(encodeURIComponent(r))),str_decode_base64:r=>decodeURIComponent(escape(atob(r))),str_encode_uri:r=>encodeURIComponent(String(r)),str_decode_uri:r=>decodeURIComponent(String(r)),str_fmt:(r,t)=>{if(typeof r!="string")return String(r);let e=(n,s)=>n instanceof Map?n.get(s)??n.get(":"+s):n?.[s];return r.replace(/\{(\w+)\}/g,(n,s)=>{let a=e(t,s);return a!=null?String(a):`{${s}}`})},"empty?":r=>r==null?!0:Array.isArray(r)||typeof r=="string"?r.length===0:typeof r=="object"?Object.keys(r).length===0:!1,"array-empty?":r=>Array.isArray(r)&&r.length===0,array_empty_q:r=>Array.isArray(r)&&r.length===0,str_contains_in:(r,t)=>String(r).includes(String(t)),"str-contains-in":(r,t)=>String(r).includes(String(t)),str_replace_in:(r,t,e)=>String(r).replaceAll(String(t),String(e)),"str-replace-in":(r,t,e)=>String(r).replaceAll(String(t),String(e)),"is-nil":r=>r==null,"is-empty":r=>r==null||Array.isArray(r)&&r.length===0||typeof r=="string"&&r.length===0,"str-to-upper":r=>String(r||"").toUpperCase(),"str-to-lower":r=>String(r||"").toLowerCase(),"str-starts-with":(r,t)=>String(r||"").startsWith(String(t||"")),"str-ends-with":(r,t)=>String(r||"").endsWith(String(t||"")),"str-to-num":r=>{let t=Number(String(r||"").trim());return isNaN(t)?null:t},"html-escape":r=>String(r||"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),"str/fmt":(r,t)=>{if(typeof r!="string")return String(r);let e=(n,s)=>n instanceof Map?n.get(s)??n.get(":"+s):n?.[s];return r.replace(/\{(\w+)\}/g,(n,s)=>{let a=e(t,s);return a!=null?String(a):`{${s}}`})}}}function ul(){return{arr_flatten:r=>r.flat(),arr_flatten_deep:r=>r.flat(1/0),arr_zip:(r,t)=>{let e=Math.min(r.length,t.length);return Array.from({length:e},(n,s)=>[r[s],t[s]])},arr_unique:r=>[...new Set(r.map(t=>JSON.stringify(t)))].map(t=>JSON.parse(t)),arr_chunk:(r,t)=>{let e=[];for(let n=0;n<r.length;n+=t)e.push(r.slice(n,n+t));return e},arr_take:(r,t)=>r.slice(0,t),arr_drop:(r,t)=>r.slice(t),arr_sum:r=>r.reduce((t,e)=>t+e,0),arr_avg:r=>{if(r.length===0)throw new Error("arr_avg: empty array");return r.reduce((t,e)=>t+e,0)/r.length},arr_min:r=>Math.min(...r),arr_max:r=>Math.max(...r),arr_group_by:(r,t)=>{let e={};for(let n of r){let s=String(n[t]??"__undefined__");e[s]||(e[s]=[]),e[s].push(n)}return e},arr_sort_by:(r,t)=>[...r].sort((e,n)=>{let s=e[t],a=n[t];return s<a?-1:s>a?1:0}),arr_sort_by_desc:(r,t)=>[...r].sort((e,n)=>{let s=e[t],a=n[t];return s>a?-1:s<a?1:0}),frequencies:r=>{if(r==null)return{};let t={};for(let e of r){let n=String(e??"__nil__");t[n]=(t[n]??0)+1}return t},arr_count_by:(r,t)=>{let e={};for(let n of r){let s=String(n[t]??"__undefined__");e[s]=(e[s]??0)+1}return e},arr_pluck:(r,t)=>r.map(e=>e[t]),arr_index_by:(r,t)=>{let e={};for(let n of r)e[String(n[t])]=n;return e},retry:(r,t)=>{let e;for(let n=0;n<=r;n++)try{return t()}catch(s){if(e=s,n<r){let a=Date.now();for(;Date.now()-a<100*n;);}}throw e},retry_silent:(r,t)=>{for(let e=0;e<=r;e++)try{return t()}catch{}return null},pipeline_run:(r,t)=>t.reduce((e,n)=>n(e),r),memoize:r=>{let t=new Map;return(...e)=>{let n=JSON.stringify(e);if(t.has(n))return t.get(n);let s=r(...e);return t.set(n,s),s}},once:r=>{let t=!1,e;return(...n)=>(t||(t=!0,e=r(...n)),e)},tap:(r,t)=>(t(r),r),range:(r,t)=>{let e=[];for(let n=r;n<t;n++)e.push(n);return e},range_step:(r,t,e)=>{let n=[];for(let s=r;s<t;s+=e)n.push(s);return n},repeat:(r,t)=>Array(r).fill(t),arr_includes:(r,t)=>Array.isArray(r)?r.some(e=>JSON.stringify(e)===JSON.stringify(t)):!1,arr_index_of:(r,t)=>Array.isArray(r)?r.findIndex(e=>JSON.stringify(e)===JSON.stringify(t)):-1,arr_remove:(r,t)=>{if(!Array.isArray(r))return[];let e=r.findIndex(n=>JSON.stringify(n)===JSON.stringify(t));return e===-1?r:[...r.slice(0,e),...r.slice(e+1)]}}}function _s(){return{agent_create:r=>({name:r,state:{},history:[],tools:{},steps:0,status:"running"}),agent_set:(r,t,e)=>({...r,state:{...r.state,[t]:e}}),agent_get:(r,t)=>r.state[t]??null,agent_update:(r,t)=>({...r,state:{...r.state,...t}}),agent_steps:r=>r.steps,agent_status:r=>r.status,agent_done:r=>r.status==="done"||r.status==="error"||r.status==="max_steps",agent_add_tool:(r,t,e)=>({...r,tools:{...r.tools,[t]:e}}),agent_call_tool:(r,t,...e)=>{let n=r.tools[t];if(!n)throw new Error(`Tool not found: "${t}". Available: ${Object.keys(r.tools).join(", ")}`);return n(...e)},agent_tools:r=>Object.keys(r.tools),agent_push_history:(r,t)=>({...r,history:[...r.history,{...t,step:r.steps,timestamp:Date.now()}]}),agent_history:r=>r.history,agent_history_last:(r,t)=>r.history.slice(-t),agent_history_type:(r,t)=>r.history.filter(e=>e.type===t),agent_loop:(r,t,e,n)=>{let s=r;for(;s.steps<n;){if(t(s.state))return{...s,status:"done"};try{s=e({...s,steps:s.steps+1})}catch(a){return{...s,status:"error",state:{...s.state,_error:a.message}}}}return{...s,status:"max_steps"}},agent_run_until:(r,t,e,n)=>{let s=r,a=0;for(;!t(s)&&a<n;)s=e(s),a++;return s},plan_create:r=>({steps:r,current:0,done:!1,results:{}}),plan_next:r=>r.done||r.current>=r.steps.length?null:r.steps[r.current],plan_advance:(r,t)=>{let e=r.steps[r.current],n=r.current+1;return{...r,current:n,done:n>=r.steps.length,results:{...r.results,[e]:t}}},plan_done:r=>r.done||r.current>=r.steps.length,plan_progress:r=>r.steps.length===0?1:r.current/r.steps.length,plan_results:r=>r.results,observe:(r,t,e)=>({...e,[r]:t}),summarize:r=>Object.entries(r).map(([t,e])=>`${t}: ${typeof e=="object"?JSON.stringify(e):e}`).join(`
402
+ `),context_create:()=>({}),context_merge:(r,t)=>({...r,...t})}}var Qe={debug:0,info:1,warn:2,error:3};function Ss(){return{now:()=>Date.now(),now_ms:()=>Date.now(),now_iso:()=>new Date().toISOString(),now_unix:()=>Math.floor(Date.now()/1e3),time_diff:(r,t)=>t-r,time_since:r=>Date.now()-r,time_ago:r=>{let t=Date.now()-r;return t<1e3?`${t}ms ago`:t<6e4?`${Math.floor(t/1e3)}s ago`:t<36e5?`${Math.floor(t/6e4)}m ago`:t<864e5?`${Math.floor(t/36e5)}h ago`:`${Math.floor(t/864e5)}d ago`},format_date:(r,t)=>{let e=new Date(r);return t.replace("YYYY",String(e.getFullYear())).replace("MM",String(e.getMonth()+1).padStart(2,"0")).replace("DD",String(e.getDate()).padStart(2,"0")).replace("HH",String(e.getHours()).padStart(2,"0")).replace("mm",String(e.getMinutes()).padStart(2,"0")).replace("ss",String(e.getSeconds()).padStart(2,"0")).replace("SSS",String(e.getMilliseconds()).padStart(3,"0"))},date_parts:r=>{let t=new Date(r);return{year:t.getFullYear(),month:t.getMonth()+1,day:t.getDate(),hour:t.getHours(),min:t.getMinutes(),sec:t.getSeconds(),ms:t.getMilliseconds(),weekday:t.getDay()}},date_add:(r,t,e)=>{let n=String(t).replace(/^:/,""),s={ms:1,s:1e3,m:6e4,h:36e5,d:864e5};if(s[n]!==void 0)return r+e*s[n];let a=new Date(Number(r));if(n==="days"||n==="day")return a.setDate(a.getDate()+Number(e)),a.getTime();if(n==="hours"||n==="hour")return a.setHours(a.getHours()+Number(e)),a.getTime();if(n==="minutes"||n==="minute")return a.setMinutes(a.getMinutes()+Number(e)),a.getTime();if(n==="months"||n==="month")return a.setMonth(a.getMonth()+Number(e)),a.getTime();if(n==="years"||n==="year")return a.setFullYear(a.getFullYear()+Number(e)),a.getTime();if(n==="seconds"||n==="second")return a.setSeconds(a.getSeconds()+Number(e)),a.getTime();if(n==="weeks"||n==="week")return a.setDate(a.getDate()+Number(e)*7),a.getTime();throw new Error(`date_add: unknown unit "${t}". Use: ms/s/m/h/d/days/hours/minutes/months/years/weeks`)},date_parse:r=>{let t=Date.parse(r);if(isNaN(t))throw new Error(`date_parse: invalid date string "${r}"`);return t},sleep_ms:r=>{let t=Date.now()+r;for(;Date.now()<t;);},timer_start:r=>({start:Date.now(),label:r,laps:[]}),timer_lap:(r,t)=>({...r,laps:[...r.laps,{label:t,elapsed:Date.now()-r.start}]}),timer_elapsed:r=>Date.now()-r.start,timer_stop:r=>({label:r.label,total_ms:Date.now()-r.start,laps:r.laps}),log_create:(r,t="info")=>({name:r,entries:[],level:t}),log_entry:(r,t,e,n)=>{if(Qe[t]<Qe[r.level])return r;let s={ts:Date.now(),level:t,msg:e};return n!==void 0&&(s.data=n),{...r,entries:[...r.entries,s]}},log_info:(r,t)=>Qe.info<Qe[r.level]?r:{...r,entries:[...r.entries,{ts:Date.now(),level:"info",msg:t}]},log_warn:(r,t)=>Qe.warn<Qe[r.level]?r:{...r,entries:[...r.entries,{ts:Date.now(),level:"warn",msg:t}]},log_error:(r,t)=>({...r,entries:[...r.entries,{ts:Date.now(),level:"error",msg:t}]}),log_debug:(r,t)=>Qe.debug<Qe[r.level]?r:{...r,entries:[...r.entries,{ts:Date.now(),level:"debug",msg:t}]},log_filter:(r,t)=>r.entries.filter(e=>Qe[e.level]>=Qe[t]),log_count:(r,t)=>r.entries.filter(e=>e.level===t).length,log_last:(r,t)=>r.entries.slice(-t),log_dump:r=>{let t=e=>e.padEnd(5);for(let e of r.entries){let n=new Date(e.ts).toISOString().slice(11,23),s=`[${t(e.level.toUpperCase())}]`,a=e.data!==void 0?` | ${JSON.stringify(e.data)}`:"";console.log(`${n} ${s} [${r.name}] ${e.msg}${a}`)}},metrics_create:r=>({name:r,values:{},counters:{},timers:{}}),metrics_record:(r,t,e)=>({...r,values:{...r.values,[t]:[...r.values[t]??[],e]}}),metrics_inc:(r,t)=>({...r,counters:{...r.counters,[t]:(r.counters[t]??0)+1}}),metrics_inc_by:(r,t,e)=>({...r,counters:{...r.counters,[t]:(r.counters[t]??0)+e}}),metrics_count:(r,t)=>r.counters[t]??0,metrics_avg:(r,t)=>{let e=r.values[t]??[];return e.length===0?0:e.reduce((n,s)=>n+s,0)/e.length},metrics_min:(r,t)=>{let e=r.values[t]??[];return e.length?Math.min(...e):0},metrics_max:(r,t)=>{let e=r.values[t]??[];return e.length?Math.max(...e):0},metrics_p95:(r,t)=>{let e=[...r.values[t]??[]].sort((n,s)=>n-s);return e.length===0?0:e[Math.floor(e.length*.95)]},metrics_summary:r=>{let t={};for(let[e,n]of Object.entries(r.values)){let s=[...n].sort((a,i)=>a-i);t[e]={count:n.length,avg:n.reduce((a,i)=>a+i,0)/n.length,min:s[0],max:s[s.length-1],p95:s[Math.floor(s.length*.95)]}}for(let[e,n]of Object.entries(r.counters))t[`counter.${e}`]={count:n};return t}}}var nm=Date.now(),Er=0,di=0;function gi(r,t){let e=Math.ceil(t/100*r.length)-1;return r[Math.max(0,Math.min(e,r.length-1))]}function xs(r,t,e){if(typeof r=="function")return r(...t);if(r?.kind==="function-value"&&e)return e(r,t);throw new Error("profile_fn/trace_expr: \uCCAB \uBC88\uC9F8 \uC778\uC790\uB294 \uD568\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4")}function pl(r){return{profile_fn:(t,e=100)=>{let n=t?.name||"anonymous",s=[];for(let i=0;i<e;i++){let o=performance.now();xs(t,[],r),s.push(performance.now()-o),di++}s.sort((i,o)=>i-o);let a=s.reduce((i,o)=>i+o,0);return{name:n,calls:e,total_ms:Math.round(a*1e3)/1e3,avg_ms:Math.round(a/e*1e3)/1e3,min_ms:Math.round(s[0]*1e3)/1e3,max_ms:Math.round(s[s.length-1]*1e3)/1e3,p50_ms:Math.round(gi(s,50)*1e3)/1e3,p95_ms:Math.round(gi(s,95)*1e3)/1e3,p99_ms:Math.round(gi(s,99)*1e3)/1e3}},trace_expr:(t,e="expr")=>{let n=process.memoryUsage().heapUsed,s=performance.now(),a=xs(t,[],r),i=performance.now()-s,o=process.memoryUsage().heapUsed;return o>Er&&(Er=o),di++,{label:e,time_ms:Math.round(i*1e3)/1e3,memory_delta_kb:Math.round((o-n)/1024),result:a}},perf_stats:()=>{let t=process.memoryUsage();return t.heapUsed>Er&&(Er=t.heapUsed),{uptime_ms:Date.now()-nm,total_calls:di,memory_used_kb:Math.round(t.rss/1024),memory_peak_kb:Math.round(Er/1024),heap_used_kb:Math.round(t.heapUsed/1024)}},now_ms:()=>Date.now(),elapsed_ms:t=>Date.now()-t,bench:(t,e=1e3)=>{let n=performance.now();for(let a=0;a<e;a++)xs(t,[],r);let s=performance.now()-n;return{ms:Math.round(s*100)/100,ops_per_sec:Math.round(e/s*1e3)}},time_fn:(t,...e)=>{let n=performance.now();return{result:xs(t,e,r),ms:Math.round((performance.now()-n)*1e3)/1e3}}}}function hi(r){let t=[],e=[],n=r.split(`
403
+ `),s=0,a=0,i=!1,o=!1;for(let f=0;f<n.length;f++){let l=n[f];o=!1;for(let c=0;c<l.length;c++){let p=l[c];if(p==='"'&&!o){i=!i;continue}if(!i){if(p===";"&&!i){o=!0;break}if(o)break;if(p==="("||p==="[")e.push({line:f+1,col:c+1,ch:p}),s=Math.max(s,e.length),a++;else if(p===")"||p==="]")if(e.length===0){let m=l.trim().slice(0,40);t.push({line:f+1,col:c+1,message:`\uB2EB\uB294 '${p}' \uB300\uC751\uD558\uB294 \uC5EC\uB294 \uAD04\uD638 \uC5C6\uC74C`,context:m})}else{let m=e.pop(),d=m.ch==="("?")":"]";p!==d&&t.push({line:f+1,col:c+1,message:`\uAD04\uD638 \uBD88\uC77C\uCE58: '${m.ch}' (${m.line}:${m.col}) \u2192 '${p}' \uB2EB\uC74C`,context:l.trim().slice(0,40)})}}}}for(let f of e)t.push({line:f.line,col:f.col,message:`'${f.ch}' \uB2EB\uD788\uC9C0 \uC54A\uC74C (${e.length}\uAC1C \uBBF8\uB2EB\uD798)`,context:n[f.line-1]?.trim().slice(0,40)??""});let u;if(t.length>0&&e.length>0){let f=e.slice().reverse().map(l=>l.ch==="("?")":"]").join("");u=r.trimEnd()+`
404
+ `+f}return{valid:t.length===0,errors:t,depth_max:s,paren_count:a,fixed:u}}function fl(){return{check_parens:r=>{let t=hi(r),e=new Map;return e.set("valid",t.valid),e.set("errors",t.errors.map(n=>{let s=new Map;return s.set("line",n.line),s.set("col",n.col),s.set("message",n.message),s.set("context",n.context),s})),e.set("depth_max",t.depth_max),e.set("paren_count",t.paren_count),t.fixed!==void 0&&e.set("fixed",t.fixed),e},verify_code:r=>{let t=hi(r),e=new Map;if(e.set("valid",t.valid),e.set("error_count",t.errors.length),e.set("depth_max",t.depth_max),e.set("paren_count",t.paren_count),t.errors.length>0){let n=t.errors[0];e.set("first_error",`line ${n.line}:${n.col} \u2014 ${n.message}`),e.set("all_errors",t.errors.map(s=>`line ${s.line}:${s.col} \u2014 ${s.message}`))}return t.fixed&&e.set("fixed",t.fixed),e},fix_parens:r=>{let t=hi(r);return t.valid?r:t.fixed??r},count_parens:r=>{let t=0,e=0,n=!1,s=!1;for(let i of r.split(`
405
+ `)){s=!1;for(let o of i){if(o==='"'){n=!n;continue}if(!n){if(o===";"){s=!0;break}if(s)break;(o==="("||o==="[")&&t++,(o===")"||o==="]")&&e++}}}let a=new Map;return a.set("open",t),a.set("close",e),a.set("balanced",t===e),a.set("diff",t-e),a}}}function $s(r){if(r instanceof Map){let t={};for(let[e,n]of r)t[e]=$s(n);return t}if(Array.isArray(r))return r.map($s);if(r!==null&&typeof r=="object"){let t={};for(let[e,n]of Object.entries(r))t[e]=$s(n);return t}return r}function yi(r){if(r==null)return null;if(Array.isArray(r))return r.map(yi);if(typeof r=="object"){let t=new Map;for(let[e,n]of Object.entries(r))t.set(e,yi(n));return t}return r}function As(r,t,e,n,s=3e4){let a=new Map;try{let i=new URL(t),o=i.protocol==="https:",u=e!=null?JSON.stringify($s(e)):void 0,f={hostname:i.hostname,port:i.port||(o?443:80),path:i.pathname+i.search,method:r.toUpperCase(),headers:{"Content-Type":"application/json",Accept:"application/json",...u?{"Content-Length":Buffer.byteLength(u)}:{},...n??{}},timeout:s},{execFileSync:l}=require("child_process"),c=`
406
+ const ${o?"https":"http"} = require("${o?"https":"http"}");
407
+ const options = ${JSON.stringify(f)};
408
+ ${u?`const body = ${JSON.stringify(u)};`:"const body = null;"}
409
+ let status = 0, data = "";
410
+ const req = ${o?"https":"http"}.request(options, res => {
411
+ status = res.statusCode;
412
+ res.on("data", c => data += c);
413
+ res.on("end", () => process.stdout.write(JSON.stringify({status, data})));
414
+ });
415
+ req.on("error", e => process.stdout.write(JSON.stringify({status: 0, data: "", error: e.message})));
416
+ req.setTimeout(${s}, () => { req.destroy(); });
417
+ if (body) req.write(body);
418
+ req.end();
419
+ `,p=l(process.execPath,["-e",c],{timeout:s+2e3,encoding:"utf8"}),m=JSON.parse(p),d=m.status??0,g=null;try{g=yi(JSON.parse(m.data))}catch{g=m.data||null}a.set("ok",d>=200&&d<300),a.set("status",d),a.set("body",g),a.set("raw",m.data??""),m.error?a.set("error",m.error):(d<200||d>=300)&&a.set("error",`HTTP ${d}`)}catch(i){a.set("ok",!1),a.set("status",0),a.set("error",i.message),a.set("body",null)}return a}function ml(){return{http_json:(r,t,e,n)=>{let s={};if(n instanceof Map)for(let[a,i]of n)s[String(a)]=String(i);else if(n&&typeof n=="object")for(let[a,i]of Object.entries(n))s[String(a)]=String(i);return As(r,t,e,s)},http_get_json:(r,t)=>{let e={};if(t instanceof Map)for(let[n,s]of t)e[String(n)]=String(s);return As("GET",r,void 0,e)},http_post_json:(r,t,e)=>{let n={};if(e instanceof Map)for(let[s,a]of e)n[String(s)]=String(a);return As("POST",r,t,n)},http_batch:r=>(Array.isArray(r)?r:[]).map(e=>{let n=e instanceof Map?e:new Map(Object.entries(e)),s=String(n.get("method")??"GET"),a=String(n.get("url")??""),i=n.get("body"),o={},u=n.get("headers");if(u instanceof Map)for(let[f,l]of u)o[String(f)]=String(l);return As(s,a,i,o)}),"http_ok?":r=>r instanceof Map?r.get("ok")===!0:!1,http_body:r=>r instanceof Map?r.get("body")??null:null,http_status:r=>r instanceof Map?r.get("status")??0:0}}var Ms;try{Ms=require("better-sqlite3")}catch{Ms=null}function bi(r){if(!Ms)throw new Error("better-sqlite3 \uBBF8\uC124\uCE58. npm install better-sqlite3 \uC2E4\uD589");return new Ms(r)}function Yt(r){if(r instanceof Map){let t={};for(let[e,n]of r)t[e]=Yt(n);return t}return Array.isArray(r)?r.map(Yt):r}function rm(r){let t=new Map;if(r&&typeof r=="object")for(let[e,n]of Object.entries(r))t.set(e,n);return t}function Es(r){if(!r)return{sql:"",params:[]};let t=r instanceof Map?Object.fromEntries(r):Yt(r),e=[],n=[];for(let[s,a]of Object.entries(t)){let i=s.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\s*([><=!<>]+)?$/);if(!i)continue;let o=i[1],u=i[2]||"=";a==null?e.push(u==="!="?`${o} IS NOT NULL`:`${o} IS NULL`):(e.push(`${o} ${u} ?`),n.push(a))}return{sql:e.length?"WHERE "+e.join(" AND "):"",params:n}}function dl(){return{db_run:(r,t,e)=>{let n=e instanceof Map?e:new Map(Object.entries(e??{})),s=bi(r);try{if(t==="select"){let a=n.get("select")??["*"],i=Array.isArray(a)?a.join(", "):String(a),o=n.get("from")??n.get("table");if(!o)throw new Error("db_query select: :from \uD544\uC218");let{sql:u,params:f}=Es(n.get("where")),l=n.get("order_by")?`ORDER BY ${n.get("order_by")}`:"",c=n.get("limit")?`LIMIT ${n.get("limit")}`:"",p=`SELECT ${i} FROM ${o} ${u} ${l} ${c}`.trim();return s.prepare(p).all(...f).map(rm)}else if(t==="insert"){let a=n.get("into")??n.get("table");if(!a)throw new Error("db_query insert: :into \uD544\uC218");let i=Yt(n.get("values")??n.get("data"));if(!i)throw new Error("db_query insert: :values \uD544\uC218");let o=Object.keys(i),u=`INSERT INTO ${a} (${o.join(", ")}) VALUES (${o.map(()=>"?").join(", ")})`,f=s.prepare(u).run(...o.map(c=>i[c])),l=new Map;return l.set("inserted",f.changes),l.set("last_id",f.lastInsertRowid),l}else if(t==="update"){let a=n.get("table");if(!a)throw new Error("db_query update: :table \uD544\uC218");let i=Yt(n.get("set")??n.get("data"));if(!i)throw new Error("db_query update: :set \uD544\uC218");let o=Object.keys(i),{sql:u,params:f}=Es(n.get("where")),l=`UPDATE ${a} SET ${o.map(m=>`${m} = ?`).join(", ")} ${u}`,c=s.prepare(l).run(...o.map(m=>i[m]),...f),p=new Map;return p.set("updated",c.changes),p}else if(t==="delete"){let a=n.get("from")??n.get("table");if(!a)throw new Error("db_query delete: :from \uD544\uC218");let{sql:i,params:o}=Es(n.get("where")),u=`DELETE FROM ${a} ${i}`.trim(),f=s.prepare(u).run(...o),l=new Map;return l.set("deleted",f.changes),l}else if(t==="count"){let a=n.get("from")??n.get("table");if(!a)throw new Error("db_query count: :from \uD544\uC218");let{sql:i,params:o}=Es(n.get("where")),u=`SELECT COUNT(*) as n FROM ${a} ${i}`.trim();return s.prepare(u).get(...o)?.n??0}else throw new Error(`db_query: \uC54C \uC218 \uC5C6\uB294 op '${t}'. select/insert/update/delete/count`)}finally{s.close()}},db_batch_insert:(r,t,e)=>{let n=bi(r),s=new Map,a=0,i=[];try{if(!e||e.length===0)return s.set("inserted",0),s.set("errors",[]),s;let o=Yt(e[0]instanceof Map?Object.fromEntries(e[0]):e[0]),u=Object.keys(o),f=`INSERT INTO ${t} (${u.join(", ")}) VALUES (${u.map(()=>"?").join(", ")})`,l=n.prepare(f);n.transaction(p=>{for(let m of p)try{let d=Yt(m instanceof Map?Object.fromEntries(m):m);l.run(...u.map(g=>d[g])),a++}catch(d){i.push(d.message)}})(e)}catch(o){i.push(o.message)}finally{n.close()}return s.set("inserted",a),s.set("errors",i),s},db_transaction:(r,t)=>{let e=bi(r),n=[];try{e.transaction(()=>{for(let a of t){let o=(a instanceof Map?a:new Map(Object.entries(a))).get("op")??"select";n.push({op:o,done:!0})}})()}finally{e.close()}return n}}}function Rs(r){try{return require(r)}catch{return null}}function gl(r,t){return(...e)=>{throw new Error(`${t} \uC0AC\uC6A9 \uBD88\uAC00: npm install ${r} \uD544\uC694`)}}function hl(){return{require_optional:r=>Rs(r)!==null,optional_fn:(r,t,e)=>{let n=Rs(r);return n?t==="."||t===""?n:t==="default"?n.default??n:n[t]??gl(r,t):e??gl(r,t)},optional_call:(r,t,...e)=>{let n=Rs(r);if(!n)throw new Error(`${r} \uBBF8\uC124\uCE58. npm install ${r} \uD544\uC694`);let s=t==="default"?n.default??n:n[t]??n;if(typeof s!="function")throw new Error(`${r}.${t}\uB294 \uD568\uC218\uAC00 \uC544\uB2D8`);return s(...e)},"optional_has?":r=>Rs(r)!==null,optional_version:r=>{try{return require(`${r}/package.json`).version??null}catch{return null}}}}function sm(r,t){let e=[],n=r.endsWith("/")?r.slice(0,-1):r,s=n.split("/").filter(Boolean),a=s[s.length-1]??"item",i=a.endsWith("s")?a.slice(0,-1)+"_id":a+"_id",o=t.get("list"),u=t.get("get"),f=t.get("create"),l=t.get("update"),c=t.get("delete")??t.get("del"),p=t.get("patch");return o&&e.push({method:"GET",pattern:n,handler:o}),f&&e.push({method:"POST",pattern:n,handler:f}),u&&e.push({method:"GET",pattern:`${n}/:${i}`,handler:u,paramName:i}),l&&e.push({method:"PUT",pattern:`${n}/:${i}`,handler:l,paramName:i}),p&&e.push({method:"PATCH",pattern:`${n}/:${i}`,handler:p,paramName:i}),c&&e.push({method:"DELETE",pattern:`${n}/:${i}`,handler:c,paramName:i}),e}function yl(){return{rest_crud:(r,t)=>{let e=t instanceof Map?t:new Map(Object.entries(t??{}));return sm(r,e).map(s=>{let a=new Map;return a.set("method",s.method),a.set("pattern",s.pattern),a.set("handler",s.handler),s.paramName&&a.set("param",s.paramName),a})},route_info:r=>{let t=r.endsWith("/")?r.slice(0,-1):r,e=t.split("/").filter(Boolean),n=e[e.length-1]??"item",s=n.endsWith("s")?n.slice(0,-1)+"_id":n+"_id",a=new Map;return a.set("base",t),a.set("param_name",s),a.set("collection_path",t),a.set("item_path",`${t}/:${s}`),a.set("supported_ops",["list","get","create","update","patch","delete"]),a},crud_handler_map:(r,t,e,n,s,a)=>{let i=new Map;return r&&i.set("list",r),t&&i.set("get",t),e&&i.set("create",e),n&&i.set("update",n),s&&i.set("delete",s),a&&i.set("patch",a),i},path_param:(r,t)=>{let e=r instanceof Map?r:new Map(Object.entries(r??{})),n=e.get("params")??e.get("path_params");return n?n instanceof Map?n.get(t)??null:n[t]??null:null},rest_response:(r,t)=>{let e=new Map;return e.set("status",r),e.set("body",t),e.set("headers",new Map([["Content-Type","application/json"]])),e},rest_ok:r=>{let t=new Map;return t.set("status",200),t.set("body",r),t},rest_created:r=>{let t=new Map;return t.set("status",201),t.set("body",r),t},rest_not_found:r=>{let t=new Map;return t.set("status",404),t.set("body",{error:r??"Not Found"}),t},rest_error:(r,t)=>{let e=new Map;return e.set("status",r),e.set("body",{error:t}),e}}}var Nt=[];function bl(r=""){return r.split(`
420
+ `).slice(1).map(t=>t.trim()).filter(t=>t.startsWith("at ")).slice(0,10)}function ki(r,t){let e={message:r?.message??String(r),name:r?.name??"Error",stack:bl(r?.stack),timestamp:Date.now()};return t&&(e.context=t),r?.code!==void 0&&(e.code=r.code),Nt.length>=100&&Nt.shift(),Nt.push(e),e}function Mr(r){let t={message:r.message,name:r.name,stack:r.stack,timestamp:r.timestamp};return r.context&&(t.context=r.context),r.code!==void 0&&(t.code=r.code),t}function kl(r){return{capture_error:(t,e)=>{let n=new Map;try{let s;if(typeof t=="function")s=t();else if(t?.kind==="function-value"&&r)s=r(t,[]);else throw new Error("capture_error: \uCCAB \uBC88\uC9F8 \uC778\uC790\uB294 \uD568\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4");n.set("ok",!0),n.set("result",s)}catch(s){let a=ki(s,e);n.set("ok",!1),n.set("error",Mr(a))}return n},capture_error_args:(t,e,n)=>{let s=new Map,a=Array.isArray(e)?e:[];try{let i;if(typeof t=="function")i=t(...a);else if(t?.kind==="function-value"&&r)i=r(t,a);else throw new Error("\uCCAB \uBC88\uC9F8 \uC778\uC790\uB294 \uD568\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4");s.set("ok",!0),s.set("result",i)}catch(i){let o=ki(i,n);s.set("ok",!1),s.set("error",Mr(o))}return s},error_log:()=>Nt.map(Mr),error_log_clear:()=>{let t=Nt.length;return Nt.length=0,t},error_log_last:(t=10)=>Nt.slice(-Math.abs(t)).map(Mr),error_count:()=>Nt.length,make_error:(t,e,n)=>{let s={message:t,name:e??"Error",stack:[],timestamp:Date.now()};return n!==void 0&&(s.code=n),s},error_message:t=>t&&typeof t=="object"?String(t.message??t.get?.("message")??""):t instanceof Error?t.message:String(t??""),error_stack:t=>t&&typeof t=="object"?t.stack??t.get?.("stack")??[]:t instanceof Error?bl(t.stack):[],retry:(t,e=3,n=0)=>{let s=new Map,a,i=Math.max(1,Math.floor(e));for(let u=1;u<=i;u++)try{let f;if(typeof t=="function")f=t();else if(t?.kind==="function-value"&&r)f=r(t,[]);else throw new Error("retry: \uCCAB \uBC88\uC9F8 \uC778\uC790\uB294 \uD568\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4");return s.set("ok",!0),s.set("result",f),s.set("attempts_used",u),s}catch(f){if(a=f,u<i&&n>0){let l=Date.now()+n;for(;Date.now()<l;);}}let o=ki(a,`retry(${i})`);return s.set("ok",!1),s.set("attempts_used",i),s.set("error",Mr(o)),s}}}var ge=z(require("crypto"));function Ts(){return{sha256:r=>ge.createHash("sha256").update(r,"utf8").digest("hex"),sha256_short:r=>ge.createHash("sha256").update(r,"utf8").digest("hex").slice(0,8),md5:r=>ge.createHash("md5").update(r,"utf8").digest("hex"),sha1:r=>ge.createHash("sha1").update(r,"utf8").digest("hex"),hmac_sha256:(r,t)=>ge.createHmac("sha256",r).update(t,"utf8").digest("hex"),hash_eq:(r,t)=>{if(r.length!==t.length)return!1;try{return ge.timingSafeEqual(Buffer.from(r,"hex"),Buffer.from(t,"hex"))}catch{return!1}},base64_encode:r=>Buffer.from(r,"utf8").toString("base64"),base64_decode:r=>Buffer.from(r,"base64").toString("utf8"),base64url_encode:r=>Buffer.from(r,"utf8").toString("base64url"),base64url_decode:r=>Buffer.from(r,"base64url").toString("utf8"),hex_encode:r=>Buffer.from(r,"utf8").toString("hex"),hex_decode:r=>Buffer.from(r,"hex").toString("utf8"),random_bytes:r=>ge.randomBytes(r).toString("hex"),random_int:(r,t)=>{let e=t-r+1;return r+ge.randomInt(e)},random_float:()=>ge.randomBytes(4).readUInt32BE(0)/4294967295,uuid_v4:()=>ge.randomUUID(),uuid_short:()=>ge.randomBytes(4).toString("hex"),uuid_from_str:r=>{let t=ge.createHash("sha256").update(r).digest("hex");return[t.slice(0,8),t.slice(8,12),"5"+t.slice(13,16),t.slice(16,20),t.slice(20,32)].join("-")},is_uuid:r=>/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(r),regex_match:(r,t)=>{try{return new RegExp(t).test(r)}catch(e){throw new Error(`regex_match: invalid pattern "${t}": ${e.message}`)}},regex_match_i:(r,t)=>{try{return new RegExp(t,"i").test(r)}catch(e){throw new Error(`regex_match_i: invalid pattern: ${e.message}`)}},regex_find:(r,t)=>{let e=r.match(new RegExp(t));return e?e[0]:null},regex_find_all:(r,t)=>r.match(new RegExp(t,"g"))??[],regex_replace:(r,t,e)=>r.replace(new RegExp(t,"g"),e),regex_replace_first:(r,t,e)=>r.replace(new RegExp(t),e),regex_extract:(r,t)=>{let e=r.match(new RegExp(t));return e?e.slice(1):[]},regex_extract_all:(r,t)=>{let e=[],n=new RegExp(t,"g"),s;for(;(s=n.exec(r))!==null;)e.push(s.slice(1));return e},regex_split:(r,t)=>r.split(new RegExp(t)),regex_count:(r,t)=>{let e=r.match(new RegExp(t,"g"));return e?e.length:0},extract_json:r=>{let t=r.match(/\{[\s\S]*\}|\[[\s\S]*\]/);if(!t)return null;try{return JSON.parse(t[0])}catch{return null}},extract_code:(r,t)=>{let e=t?`\`\`\`${t}\\n([\\s\\S]*?)\`\`\``:"```(?:\\w+)?\\n([\\s\\S]*?)```",n=r.match(new RegExp(e));return n?n[1].trim():null},extract_emails:r=>r.match(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g)??[],extract_urls:r=>r.match(/https?:\/\/[^\s"'<>)]+/g)??[],extract_numbers:r=>(r.match(/-?\d+\.?\d*/g)??[]).map(Number),is_email:r=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(r),is_url:r=>{try{return new URL(r),!0}catch{return!1}}}}var je=z(require("fs")),vi=z(require("path"));function wi(r,t){try{let e=vi.dirname(r);je.existsSync(e)||je.mkdirSync(e,{recursive:!0});let n=s=>{if(s instanceof Map)return Object.fromEntries(s);if(Array.isArray(s))return s.map(n);if(typeof s=="object"&&s!==null){let a={};for(let[i,o]of Object.entries(s))a[i]=n(o);return a}return s};je.writeFileSync(r,JSON.stringify(n(t),null,2),"utf-8")}catch(e){throw console.error(`[Checkpoint] Failed to save: ${e.message}`),e}}function _i(r){try{if(!je.existsSync(r))return null;let t=je.readFileSync(r,"utf-8");return JSON.parse(t)}catch(t){return console.error(`[Checkpoint] Failed to load: ${t.message}`),null}}function Si(r){try{je.existsSync(r)&&je.unlinkSync(r)}catch(t){console.error(`[Checkpoint] Failed to delete: ${t.message}`)}}var re=Ss(),e1=_s(),Rr=Ts();function Cs(r){let t=r.toLowerCase();return t.includes("timeout")?"TIMEOUT":t.includes("enoent")||t.includes("not found")?"NOT_FOUND":t.includes("eacces")||t.includes("permission")?"PERMISSION":t.includes("econnrefused")||t.includes("connection refused")||t.includes("econnreset")||t.includes("connection reset")?"CONNECTION":t.includes("parse")||t.includes("json")?"PARSE_ERROR":t.includes("type")||t.includes("typeof")?"TYPE_ERROR":t.includes("null")||t.includes("undefined")?"NULL_ERROR":t.includes("network")||t.includes("http")?"NETWORK":t.includes("io error")?"IO_ERROR":"UNKNOWN"}function Ns(){return{workflow_create:(r,t)=>({id:Rr.uuid_from_str(r+Date.now()),name:r,steps:t,created_at:re.now()}),workflow_step:(r,t,e={})=>({name:r,fn:t,retry:e.retry??0,required:e.required??!0,on_error:e.on_error,on_timeout:e.on_timeout,fallback:e.fallback,timeout_ms:e.timeout_ms,if:e.if,parallel_tasks:e.parallel_tasks,merge_strategy:e.merge_strategy,compensate:e.compensate,on_partial:e.on_partial,distributed:e.distributed}),workflow_run:(r,t={},e)=>{let n=re.now(),s=Rr.uuid_short(),a=e?.checkpoint_path,i=e?.checkpoint_every??0,o=e?.auto_resume??!0,u=0,f={...t,_workflow:r.name,_run_id:s};if(o&&a){let k=_i(a);k&&k.workflow_id===r.id&&(u=k.step_index,f={...k.context,_workflow:r.name,_run_id:s},console.log(`[Checkpoint] Resuming from step ${u} (${k.step_names.length} completed)`))}let l=[],c=[],p=0,m=0,d=r.steps,g=[];for(let k=u;k<d.length;k++){let v=d[k];if(v.parallel_tasks&&v.parallel_tasks.length>0)return{id:s,name:r.name,status:"failed",context:f,steps_run:p+m,steps_ok:p,steps_failed:m,total_ms:re.now()-n,log:l,errors:["Parallel tasks detected. Use workflow_run_async() instead of workflow_run()"]};if(v.if!==void 0)try{if(!v.if(f)){l.push({step:v.name,status:"skipped",ms:0,trace_id:traceId,metrics:{wall_time_ms:0}});continue}}catch(S){if(c.push(`[${v.name}] Condition failed: ${S.message}`),v.required!==!1)return{id:s,name:r.name,status:"failed",context:f,steps_run:p+m,steps_ok:p,steps_failed:m,total_ms:re.now()-n,log:l,errors:c};continue}let $=re.now(),M=!1,O="",C=(v.retry??0)+1,P;for(let S=0;S<C;S++)try{P=v.fn(f),f={...f,...P},M=!0;break}catch(R){if(O=R.message,S<C-1){let E=50*(S+1),T=Date.now()+E;for(;Date.now()<T;);}}let _=re.now()-$;if(M){if(p++,g.push(v.name),l.push({step:v.name,status:"ok",ms:_}),f[`_step_${v.name}_ms`]=_,a&&i>0&&g.length%i===0){let S={workflow_id:r.id,workflow_name:r.name,step_index:k+1,context:f,timestamp:re.now(),step_names:g,steps_completed:g.length};wi(a,S)}}else{m++;let S,R=Cs(O);if(v.on_error)try{S=v.on_error({error:O,attempts:C,step_name:v.name}),f={...f,...S},M=!0,c.push(`[${v.name}] ${O} (handled by on_error)`),l.push({step:v.name,status:"error_handled",ms:_,error:O,category:R,attempted:C}),p++,m--,f[`_step_${v.name}_ms`]=_;continue}catch(E){c.push(`[${v.name}] ${O} \u2192 on_error handler also failed: ${E.message}`)}if(v.fallback!==void 0)try{S=typeof v.fallback=="function"?v.fallback():v.fallback,f={...f,...S},M=!0,c.push(`[${v.name}] ${O} (fallback used)`),l.push({step:v.name,status:"fallback_used",ms:_,error:O,category:R,attempted:C}),p++,m--,f[`_step_${v.name}_ms`]=_;continue}catch(E){c.push(`[${v.name}] ${O} \u2192 fallback also failed: ${E.message}`)}if(!M&&(c.push(`[${v.name}] ${O}`),l.push({step:v.name,status:"failed",ms:_,error:O,category:R,attempted:C}),v.required!==!1))return{id:s,name:r.name,status:"failed",context:f,steps_run:p+m,steps_ok:p,steps_failed:m,total_ms:re.now()-n,log:l,errors:c}}}let h=re.now()-n,y=m===0?"success":"partial";return(y==="success"||y==="partial")&&a&&Si(a),{id:s,name:r.name,status:y,context:f,steps_run:p+m,steps_ok:p,steps_failed:m,total_ms:h,log:l,errors:c}},workflow_run_async:async(r,t={},e)=>{let n=re.now(),s=Rr.uuid_short(),a=Rr.uuid_short(),i=e?.checkpoint_path,o=e?.checkpoint_every??0,u=e?.auto_resume??!0,f=0,l={...t,_workflow:r.name,_run_id:s};if(u&&i){let E=_i(i);E&&E.workflow_id===r.id&&(f=E.step_index,l={...E.context,_workflow:r.name,_run_id:s},console.log(`[Checkpoint] Resuming from step ${f} (${E.step_names.length} completed)`))}let c=[],p=[],m=0,d=0,g=r.steps,h=[],y=[],k=[],v=async(E,T)=>{let B=re.now(),U=!1,b="",w=(E.retry??0)+1,x;for(let F=0;F<w;F++)try{x=E.fn(T),U=!0;break}catch(I){if(b=I.message,F<w-1){let V=50*(F+1),q=Date.now()+V;for(;Date.now()<q;);}}let N=re.now()-B;return{success:U,result:x,error:b,ms:N}},$=async(E,T,B)=>{let U=E.map(V=>v(V,B)),b=await Promise.all(U),w={},x=[],N=!0,F=!1;b.forEach((V,q)=>{let L=E[q].name;V.success?(w[L]=V.result,F=!0):(x.push(`${L}: ${V.error}`),N=!1)});let I=!1;return T==="all-success"?I=N:T==="first-success"?I=F:T==="any-partial"?I=!0:I=N,{success:I,results:w,errors:x}},M=async(E,T)=>{for(let B=E.length-1;B>=0;B--){let U=E[B];if(U.compensate)try{let b=await U.compensate(T);k.push({step:U.name,action:"applied",result:b})}catch(b){k.push({step:U.name,action:"pending",error:b.message})}}};for(let E=f;E<g.length;E++){let T=g[E];if(T.if!==void 0)try{if(!T.if(l)){c.push({step:T.name,status:"skipped",ms:0,trace_id:a,metrics:{wall_time_ms:0}});continue}}catch(N){if(p.push(`[${T.name}] Condition failed: ${N.message}`),T.required!==!1)return await M(y,l),{id:s,name:r.name,status:"failed",context:l,steps_run:m+d,steps_ok:m,steps_failed:d,total_ms:re.now()-n,log:c,errors:p,compensations:k};continue}let B=re.now(),U=!1,b="",w,x=0;if(T.parallel_tasks&&T.parallel_tasks.length>0){let N=T.merge_strategy??"all-success",F=await $(T.parallel_tasks,N,l);if(x=re.now()-B,F.success)U=!0,w={[T.name]:F.results},l={...l,...w},m++,h.push(T.name),y.push(T),c.push({step:T.name,status:"ok",ms:x,trace_id:a,metrics:{wall_time_ms:x}}),l[`_step_${T.name}_ms`]=x;else{d++,b=F.errors.join("; ");let I=Cs(b);if(T.fallback!==void 0)try{let V=typeof T.fallback=="function"?T.fallback():T.fallback;l={...l,...V},U=!0,p.push(`[${T.name}] Parallel tasks failed (fallback used)`),c.push({step:T.name,status:"fallback_used",ms:x,error:b,category:I}),m++,d--,y.push(T),l[`_step_${T.name}_ms`]=x}catch{if(p.push(`[${T.name}] Parallel tasks failed: ${b}`),c.push({step:T.name,status:"failed",ms:x,error:b,category:I}),T.required!==!1)return await M(y,l),{id:s,name:r.name,status:"failed",context:l,steps_run:m+d,steps_ok:m,steps_failed:d,total_ms:re.now()-n,log:c,errors:p,compensations:k}}else if(p.push(`[${T.name}] Parallel tasks failed: ${b}`),c.push({step:T.name,status:"failed",ms:x,error:b,category:Cs(b)}),T.required!==!1)return await M(y,l),{id:s,name:r.name,status:"failed",context:l,steps_run:m+d,steps_ok:m,steps_failed:d,total_ms:re.now()-n,log:c,errors:p,compensations:k}}}else{let N=await v(T,l);if(x=N.ms,U=N.success,b=N.error,w=N.result,U){if(m++,h.push(T.name),y.push(T),c.push({step:T.name,status:"ok",ms:x,trace_id:a,metrics:{wall_time_ms:x}}),l={...l,...w},l[`_step_${T.name}_ms`]=x,i&&o>0&&h.length%o===0){let F={workflow_id:r.id,workflow_name:r.name,step_index:E+1,context:l,timestamp:re.now(),step_names:h,steps_completed:h.length};wi(i,F)}}else{d++;let F,I=Cs(b);if(T.on_error)try{F=T.on_error({error:b,attempts:1,step_name:T.name}),l={...l,...F},U=!0,p.push(`[${T.name}] ${b} (handled by on_error)`),c.push({step:T.name,status:"error_handled",ms:x,error:b,category:I,attempted:1}),m++,d--,y.push(T),l[`_step_${T.name}_ms`]=x;continue}catch(V){p.push(`[${T.name}] ${b} \u2192 on_error handler also failed: ${V.message}`)}if(T.fallback!==void 0)try{F=typeof T.fallback=="function"?T.fallback():T.fallback,l={...l,...F},U=!0,p.push(`[${T.name}] ${b} (fallback used)`),c.push({step:T.name,status:"fallback_used",ms:x,error:b,category:I,attempted:1}),m++,d--,y.push(T),l[`_step_${T.name}_ms`]=x;continue}catch(V){p.push(`[${T.name}] ${b} \u2192 fallback also failed: ${V.message}`)}if(!U&&(p.push(`[${T.name}] ${b}`),c.push({step:T.name,status:"failed",ms:x,error:b,category:I,attempted:1}),T.required!==!1))return await M(y,l),{id:s,name:r.name,status:"failed",context:l,steps_run:m+d,steps_ok:m,steps_failed:d,total_ms:re.now()-n,log:c,errors:p,compensations:k}}}}let O=re.now()-n,C=d===0?"success":"partial";(C==="success"||C==="partial")&&i&&Si(i);let P=c.map(E=>({...E,trace_id:E.trace_id||a,metrics:E.metrics||{wall_time_ms:E.ms||0}})),_=y.filter(E=>E.parallel_tasks&&E.parallel_tasks.length>0).length,S=m+d,R=k?.length??0;return{id:s,name:r.name,status:C,context:l,steps_run:m+d,steps_ok:m,steps_failed:d,total_ms:O,log:P,errors:p,compensations:k,metrics:{total_ms:O,parallel_ratio:S>0?_/S:0,error_ratio:S>0?d/S:0,compensation_ratio:S>0?Math.min(R/S,1):0}}},"step-with-error":(r,t)=>({...r,on_error:t}),"step-with-fallback":(r,t)=>({...r,fallback:t}),"step-with-timeout":(r,t)=>({...r,timeout_ms:t}),"step-when":(r,t)=>({...r,if:t}),workflow_ok:r=>r.status!=="failed",workflow_get:(r,t)=>r.context[t]??null,workflow_summary:r=>{let t=[`Workflow: ${r.name} [${r.status.toUpperCase()}]`,`Run ID: ${r.id}`,`Steps: ${r.steps_ok}/${r.steps_run} ok, ${r.steps_failed} failed`,`Time: ${r.total_ms}ms`];return r.errors.length>0&&(t.push("Errors:"),r.errors.forEach(e=>t.push(` - ${e}`))),t.push("Step log:"),r.log.forEach(e=>{let n=e.error?` \u2014 ${e.error}`:"";t.push(` [${e.status.padEnd(6)}] ${e.step} (${e.ms}ms)${n}`)}),t.join(`
421
+ `)},task_create:r=>({id:Rr.uuid_v4(),goal:r,status:"pending",subtasks:[],completed:[],result:null,created_at:re.now()}),task_add_subtask:(r,t)=>({...r,subtasks:[...r.subtasks,t]}),task_complete_subtask:(r,t,e)=>({...r,completed:[...r.completed,t],[`result_${t}`]:e}),task_finish:(r,t)=>({...r,status:"done",result:t,finished_at:re.now(),duration_ms:re.now()-r.created_at}),task_progress:r=>r.subtasks.length===0?r.status==="done"?1:0:r.completed.length/r.subtasks.length,report_create:r=>({title:r,sections:[],created_at:re.now_iso()}),report_add:(r,t,e)=>({...r,sections:[...r.sections,{name:t,data:e}]}),report_render:r=>{let t="\u2500".repeat(50),e=[t,` ${r.title}`,` Generated: ${r.created_at}`,t];for(let n of r.sections){e.push(`
422
+ ## ${n.name}`);let s=n.data;typeof s=="string"?e.push(s):Array.isArray(s)?s.forEach((a,i)=>{e.push(` ${i+1}. ${typeof a=="object"?JSON.stringify(a):a}`)}):typeof s=="object"?Object.entries(s).forEach(([a,i])=>{e.push(` ${a}: ${typeof i=="object"?JSON.stringify(i):i}`)}):e.push(String(s))}return e.push(`
423
+ `+t),e.join(`
424
+ `)}}}var Tr=require("child_process"),Y=z(require("os"));function Ae(r,t=1e4){try{return(0,Tr.execSync)(r,{encoding:"utf-8",timeout:t,stdio:["pipe","pipe","pipe"]}).trim()}catch{return""}}function Ze(r){let t=Ae(r);return t?t.split(`
425
+ `).map(e=>e.trim()).filter(Boolean):[]}function vl(r,t=":"){let e={};for(let n of r){let s=n.indexOf(t);if(s>0){let a=n.slice(0,s).trim(),i=n.slice(s+1).trim();e[a]=i}}return e}function Os(){return{res_cpu_load:()=>Y.loadavg(),res_cpu_count:()=>Y.cpus().length,res_cpu_model:()=>{let r=Y.cpus();return r.length>0?r[0].model:"unknown"},res_cpu_pct:()=>{let r=Y.loadavg()[0],t=Y.cpus().length;return Math.min(100,Math.round(r/t*100))},res_mem:()=>{let r=Math.round(Y.totalmem()/1024/1024),t=Math.round(Y.freemem()/1024/1024),e=r-t,n=Ze("cat /proc/meminfo"),s=vl(n),a=i=>Math.round(parseInt((s[i]||"0 kB").split(" ")[0])/1024);return{total_mb:r,used_mb:e,free_mb:t,available_mb:a("MemAvailable"),buffers_mb:a("Buffers"),cached_mb:a("Cached"),swap_total_mb:a("SwapTotal"),swap_used_mb:a("SwapTotal")-a("SwapFree")}},res_mem_pct:()=>{let r=Y.totalmem(),t=Y.freemem();return r>0?Math.round((1-t/r)*100):0},res_disk:()=>Ze("df -BG --output=source,target,size,used,avail,pcent 2>/dev/null | tail -n +2").filter(t=>t.startsWith("/")).map(t=>{let[e,n,s,a,i,o]=t.split(/\s+/);return{device:e,mount:n,total_gb:parseInt(s)||0,used_gb:parseInt(a)||0,avail_gb:parseInt(i)||0,use_pct:parseInt(o)||0}}),res_disk_usage:r=>{let t=Ae(`df -BG --output=size,used,avail,pcent "${r}" 2>/dev/null | tail -1`);if(!t)return{total_gb:0,used_gb:0,avail_gb:0,use_pct:0};let[e,n,s,a]=t.trim().split(/\s+/);return{total_gb:parseInt(e)||0,used_gb:parseInt(n)||0,avail_gb:parseInt(s)||0,use_pct:parseInt(a)||0}},res_procs:()=>Ze("ps axo pid,user,pcpu,pmem,stat,comm,args --sort=-pcpu 2>/dev/null | head -21 | tail -20").map(t=>{let e=t.split(/\s+/);return{pid:parseInt(e[0])||0,user:e[1]||"",cpu:parseFloat(e[2])||0,mem:parseFloat(e[3])||0,state:e[4]||"",name:e[5]||"",cmd:e.slice(6).join(" ")}}),res_find_proc:r=>{let t=r.replace(/[^a-zA-Z0-9_\-\.]/g,"");return Ze(`ps axo pid,user,pcpu,pmem,stat,comm,args 2>/dev/null | grep -i "${t}" | grep -v grep`).map(n=>{let s=n.split(/\s+/);return{pid:parseInt(s[0])||0,user:s[1]||"",cpu:parseFloat(s[2])||0,mem:parseFloat(s[3])||0,state:s[4]||"",name:s[5]||"",cmd:s.slice(6).join(" ")}})},res_proc_exists:r=>{let t=r.replace(/[^a-zA-Z0-9_\-\.]/g,"");return((0,Tr.spawnSync)("sh",["-c",`pgrep -f "${t}" > /dev/null 2>&1`]).status??1)===0},res_proc_pid:r=>{let t=r.replace(/[^a-zA-Z0-9_\-\.]/g,""),e=Ae(`pgrep -f "${t}" | head -1`),n=parseInt(e);return isNaN(n)?null:n},res_proc_count:r=>{let t=r.replace(/[^a-zA-Z0-9_\-\.]/g,""),e=Ae(`pgrep -fc "${t}" 2>/dev/null || echo 0`);return parseInt(e)||0},res_ports:()=>Ze("ss -tlnp 2>/dev/null | tail -n +2").map(t=>{let e=t.split(/\s+/),n=e[0]||"",s=e[3]||"",a=t.match(/pid=(\d+)/)?.[1],i=t.match(/\"([^\"]+)\"/)?.[1]||"",o=s.lastIndexOf(":"),u=s.slice(0,o);return{port:parseInt(s.slice(o+1))||0,protocol:"tcp",state:n,pid:a?parseInt(a):null,name:i,addr:u}}).filter(t=>t.port>0),res_port_used:r=>((0,Tr.spawnSync)("sh",["-c",`ss -tlnp 2>/dev/null | grep -q ":${r} "`]).status??1)===0,res_port_info:r=>{let t=Ae(`ss -tlnp 2>/dev/null | grep ":${r} "`);if(!t)return null;let e=t.split(/\s+/),n=t.match(/pid=(\d+)/)?.[1],s=t.match(/\"([^\"]+)\"/)?.[1]||"";return{port:r,protocol:"tcp",state:e[0]||"LISTEN",pid:n?parseInt(n):null,name:s,addr:e[3]?.split(":").slice(0,-1).join(":")||""}},res_find_free_port:(r,t)=>{let e=Ae("ss -tlnp 2>/dev/null | awk '{print $4}' | grep -oP ':\\d+' | tr -d ':'"),n=new Set(e.split(`
426
+ `).map(s=>parseInt(s)).filter(s=>!isNaN(s)));for(let s=r;s<=t;s++)if(!n.has(s))return s;return null},res_net:()=>{let r=Y.networkInterfaces(),t=[];for(let[e,n]of Object.entries(r))if(n)for(let s of n)s.family==="IPv4"&&t.push({name:e,addr:s.address,mac:s.mac,up:!0});return t},res_hostname:()=>Y.hostname(),res_uptime_s:()=>Y.uptime(),res_pm2_list:()=>{let r=Ae("pm2 jlist 2>/dev/null");if(!r)return[];try{return JSON.parse(r).map(e=>({name:e.name,status:e.pm2_env?.status||"unknown",pid:e.pid||null,uptime:e.pm2_env?.pm_uptime?`${Math.round((Date.now()-e.pm2_env.pm_uptime)/1e3)}s`:"0s",manager:"pm2"}))}catch{return[]}},res_pm2_find:r=>{let t=Ae("pm2 jlist 2>/dev/null");if(!t)return null;try{let n=JSON.parse(t).find(s=>s.name===r);return n?{name:n.name,status:n.pm2_env?.status||"unknown",pid:n.pid||null,uptime:n.pm2_env?.pm_uptime?`${Math.round((Date.now()-n.pm2_env.pm_uptime)/1e3)}s`:"0s",manager:"pm2"}:null}catch{return null}},res_systemd_status:r=>{let t=r.replace(/[^a-zA-Z0-9_\-\.]/g,""),e=Ae(`systemctl is-active "${t}" 2>/dev/null`),n=Ae(`systemctl show "${t}" -p MainPID --value 2>/dev/null`);return{name:t,status:e||"unknown",pid:parseInt(n)||null,uptime:Ae(`systemctl show "${t}" -p ActiveEnterTimestamp --value 2>/dev/null`),manager:"systemd"}},res_kimdb_project:r=>{let t=r.replace(/[^a-zA-Z0-9_\-]/g,"");try{let e=Ae(`curl -sf "http://localhost:40000/api/c/projects/${t}" 2>/dev/null`,3e3);if(!e)return null;let n=JSON.parse(e);return n.data??n??null}catch{return null}},res_kimdb_projects:()=>{try{let r=Ae('curl -sf "http://localhost:40000/api/c/projects" 2>/dev/null',5e3);if(!r)return[];let t=JSON.parse(r);return Array.isArray(t)?t:t.data??[]}catch{return[]}},res_kimdb_health:()=>{let r=Ae('curl -sf "http://localhost:40000/health" 2>/dev/null',2e3);return r.includes("ok")||r.includes("healthy")||r.length>0},res_snapshot:()=>{let r=(()=>{let o=Math.round(Y.totalmem()/1024/1024),u=Math.round(Y.freemem()/1024/1024),f=Ze("cat /proc/meminfo"),l=vl(f),c=p=>Math.round(parseInt((l[p]||"0 kB").split(" ")[0])/1024);return{total:o,free:u,used:o-u,swapTotal:c("SwapTotal"),swapFree:c("SwapFree")}})(),e=Ze("df -BG --output=source,target,size,used,avail,pcent 2>/dev/null | tail -n +2").filter(o=>o.startsWith("/")).map(o=>{let[u,f,l,c,p,m]=o.split(/\s+/);return{device:u,mount:f,total_gb:parseInt(l)||0,used_gb:parseInt(c)||0,avail_gb:parseInt(p)||0,use_pct:parseInt(m)||0}}),s=Ze("ps axo pid,user,pcpu,pmem,stat,comm,args --sort=-pcpu 2>/dev/null | head -6 | tail -5").map(o=>{let u=o.split(/\s+/);return{pid:parseInt(u[0])||0,user:u[1]||"",cpu:parseFloat(u[2])||0,mem:parseFloat(u[3])||0,state:u[4]||"",name:u[5]||"",cmd:u.slice(6).join(" ")}}),i=Ze("ss -tlnp 2>/dev/null | tail -n +2").map(o=>{let u=o.split(/\s+/),f=u[3]||"",l=f.lastIndexOf(":"),c=parseInt(f.slice(l+1))||0,p=o.match(/pid=(\d+)/)?.[1];return{port:c,protocol:"tcp",state:u[0]||"",pid:p?parseInt(p):null,name:o.match(/\"([^\"]+)\"/)?.[1]||"",addr:f.slice(0,l)}}).filter(o=>o.port>0);return{ts:Date.now(),hostname:Y.hostname(),uptime_s:Y.uptime(),cpu_load:Y.loadavg(),mem_total_mb:r.total,mem_used_mb:r.used,mem_free_mb:r.free,swap_total_mb:r.swapTotal,swap_used_mb:r.swapTotal-r.swapFree,disk:e,top_procs:s,ports_listening:i}},res_snapshot_report:r=>{let t=r.mem_total_mb>0?Math.round(r.mem_used_mb/r.mem_total_mb*100):0,e=new Date(r.ts).toISOString();return["\u2550\u2550\u2550 Server Resource Snapshot \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550",`Host: ${r.hostname} | Time: ${e}`,`Uptime: ${Math.round(r.uptime_s/3600)}h ${Math.round(r.uptime_s%3600/60)}m`,"","\u2500\u2500 CPU Load \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",`1m: ${r.cpu_load[0].toFixed(2)} 5m: ${r.cpu_load[1].toFixed(2)} 15m: ${r.cpu_load[2].toFixed(2)}`,"","\u2500\u2500 Memory \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",`Used: ${r.mem_used_mb}MB / ${r.mem_total_mb}MB (${t}%)`,`Swap: ${r.swap_used_mb}MB / ${r.swap_total_mb}MB`,"","\u2500\u2500 Disk \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",...r.disk.map(s=>`${s.mount.padEnd(12)} ${s.used_gb}G/${s.total_gb}G (${s.use_pct}%) [${s.device}]`),"","\u2500\u2500 Top Processes \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",...r.top_procs.map(s=>`PID ${String(s.pid).padEnd(7)} CPU:${String(s.cpu).padEnd(6)} MEM:${String(s.mem).padEnd(5)} ${s.name}`),"","\u2500\u2500 Listening Ports \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500",...r.ports_listening.slice(0,15).map(s=>`${String(s.port).padEnd(7)} ${s.name||"(unknown)"}`),...r.ports_listening.length>15?[`... ${r.ports_listening.length-15} more`]:[],"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"].join(`
427
+ `)},res_health_check:()=>{let r=[],t=[],e=Math.round((1-Y.freemem()/Y.totalmem())*100);e>95?t.push(`Memory critical: ${e}%`):e>80&&r.push(`Memory high: ${e}%`);let n=Y.loadavg(),s=Y.cpus().length;n[0]>s*2?t.push(`CPU load critical: ${n[0].toFixed(2)} (${s} cores)`):n[0]>s*.8&&r.push(`CPU load high: ${n[0].toFixed(2)} (${s} cores)`);let a=Ze("df -BG --output=target,pcent 2>/dev/null | tail -n +2");for(let i of a){let[o,u]=i.split(/\s+/),f=parseInt(u);f>95?t.push(`Disk ${o} critical: ${u}`):f>85&&r.push(`Disk ${o} high: ${u}`)}return{ok:t.length===0,warnings:r,errors:t,mem_pct:e,cpu_load_1m:n[0],cpu_cores:s}}}}var wl=z(require("http")),Ps=z(require("url")),Cr=z(require("crypto")),Ve=z(require("fs")),pt=z(require("path")),_l=z(require("os")),Fs={server:null};function Sl(r,t){let e=[],n=[],s=null,a=0,i=new Map,o=null,u=new Map,f=null,l=null,c=null,p=null;function m(){let _=Date.now(),S=++a;return`req_${_}_${S}`}function d(_,S,R,E,T){let B=R>=400?"\u274C":"\u2705";console.log(`${B} [${T}] ${_} ${S} ${R} ${E}ms`)}function g(_){let S=[],R=_.replace(/\//g,"\\/").replace(/\*/g,".*").replace(/:(\w+)/g,(E,T)=>(S.push(T),"([^\\/]+)"));return[new RegExp(`^${R}$`),S]}function h(_){let S=Ps.parse(_,!0);return{path:S.pathname||"/",query:S.query}}async function y(_){return new Promise(S=>{let R=[];_.on("data",E=>R.push(E)),_.on("end",()=>{let E=Buffer.concat(R),T=(_.headers["content-type"]||"").toString();if(T.includes("application/json"))try{S(JSON.parse(E.toString()));return}catch{}if(T.includes("multipart/form-data"))try{S(k(E,T));return}catch{}if(T.includes("application/x-www-form-urlencoded"))try{let B={};new Ps.URLSearchParams(E.toString()).forEach((U,b)=>{B[b]=U}),S(B);return}catch{}S(E.toString())})})}function k(_,S){let R=S.match(/boundary=([^\s;]+)/);if(!R)return{};let E=R[1],T=Buffer.from(`\r
428
+ --`+E),B={},U=[],b=pt.join(_l.tmpdir(),"fl-uploads");Ve.existsSync(b)||Ve.mkdirSync(b,{recursive:!0});let w=Buffer.from("--"+E+`\r
429
+ `),x=_.indexOf(w);if(x<0)return{fields:B,files:U};for(x+=w.length;x<_.length;){let I=_.indexOf(T,x),V=I<0?_.length:I,q=_.slice(x,V),L=q.indexOf(`\r
430
+ \r
431
+ `);if(L<0)break;let X=q.slice(0,L).toString(),G=q.slice(L+4),Q=X.match(/Content-Disposition:[^\n]*?;\s*name="([^"]+)"(?:[^\n]*?filename="([^"]+)")?/i);if(!Q){x=V+T.length+2;continue}let Z=Q[1],te=Q[2];if(te){let an=X.match(/Content-Type:\s*([^\r\n]+)/i),pe=an?an[1].trim():"application/octet-stream",dt=pt.extname(te)||"",We=Cr.randomBytes(8).toString("hex")+dt,ie=pt.join(b,We);Ve.writeFileSync(ie,G);let ye=new Map;ye.set("fieldname",Z),ye.set("originalname",te),ye.set("mimetype",pe),ye.set("size",G.length),ye.set("path",ie),ye.set("filename",We),U.push(ye)}else B[Z]=G.toString().replace(/\r\n$/,"");if(I<0||(x=I+T.length,_.slice(x,x+2).toString()==="--"))break;x+=2}let N=new Map,F=new Map;return Object.entries(B).forEach(([I,V])=>F.set(I,V)),N.set("fields",F),N.set("files",U),N}function v(_,S,R,E="application/json",T){let B={"Content-Type":E};if(T){let U=new Set(["connection","keep-alive","transfer-encoding","te","trailer","proxy-authorization","proxy-authenticate","upgrade","content-encoding"]);for(let[b,w]of Object.entries(T))U.has(b.toLowerCase())||(B[b]=w)}_.writeHead(S,B),typeof R=="string"||Buffer.isBuffer(R)?_.end(R):E.includes("json")&&typeof R=="object"?_.end(JSON.stringify(R,(U,b)=>b instanceof Map?Object.fromEntries(b):(Array.isArray(b),b))):_.end(String(R??""))}function $(_,S,R,E,T,B,U){return{__fl_request:!0,method:_,path:S,query:R,headers:E,body:T||void 0,params:B,request_id:U,timestamp:Date.now()}}let M=new Map,O=100,C=6e4;function P(_){let S=Date.now(),R=M.get(_);return!R||S>R.resetAt?(R={count:1,resetAt:S+C},M.set(_,R),!0):(R.count++,R.count<=O)}return setInterval(()=>{let _=Date.now();for(let[S,R]of M)_>R.resetAt+C&&M.delete(S)},3e5).unref(),{server_use:(_,S)=>{let[R]=g(_);return n.push({pattern:R,handler:S}),null},server_rate_limit:(_,S)=>(O=Math.max(1,Math.floor(_)),C=Math.max(1e3,Math.floor(S)),null),server_get:(_,S)=>{let[R,E]=g(_);return e.push({method:"GET",path:_,pattern:R,params:E,handler:S}),null},server_post:(_,S)=>{let[R,E]=g(_);return e.push({method:"POST",path:_,pattern:R,params:E,handler:S}),null},server_put:(_,S)=>{let[R,E]=g(_);return e.push({method:"PUT",path:_,pattern:R,params:E,handler:S}),null},server_patch:(_,S)=>{let[R,E]=g(_);return e.push({method:"PATCH",path:_,pattern:R,params:E,handler:S}),null},server_delete:(_,S)=>{let[R,E]=g(_);return e.push({method:"DELETE",path:_,pattern:R,params:E,handler:S}),null},route:(_,S,R)=>{let E=String(_).toUpperCase(),[T,B]=g(S);return e.push({method:E,path:S,pattern:T,params:B,handler:R}),null},server_static:(_,S="/")=>{let R={".html":"text/html; charset=utf-8",".htm":"text/html; charset=utf-8",".css":"text/css; charset=utf-8",".js":"application/javascript; charset=utf-8",".mjs":"application/javascript; charset=utf-8",".json":"application/json; charset=utf-8",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".txt":"text/plain; charset=utf-8",".pdf":"application/pdf"},E=pt.resolve(_),T=S.endsWith("/")?S:S+"/",B=(x,N,F)=>{let I=F.startsWith(T)?F.slice(T.length-1):F;(I===""||I==="/")&&(I="/index.html");let V=pt.join(E,I);if(!V.startsWith(E))return N.writeHead(403,{"Content-Type":"text/plain"}),N.end("Forbidden"),!0;if(!Ve.existsSync(V)||!Ve.statSync(V).isFile())return!1;let q=pt.extname(V).toLowerCase(),L=R[q]||"application/octet-stream",X=Ve.readFileSync(V);return N.writeHead(200,{"Content-Type":L,"Content-Length":X.length,"Cache-Control":"public, max-age=3600"}),N.end(X),!0},U=T==="/"?"/*":T+"*",[b,w]=g(U);return e.push({method:"GET",path:U,pattern:b,params:w,handler:{__fl_static_handler:!0,fn:B}}),null},server_all:(_,S)=>{let[R,E]=g(_);for(let T of["GET","POST","PUT","PATCH","DELETE"])e.push({method:T,path:_,pattern:R,params:E,handler:S});return null},server_start:_=>{let S=_!==null&&typeof _=="object"?_[":port"]??_.port??8080:_;if(Fs.server){try{Fs.server.close()}catch{}Fs.server=null}return s=wl.createServer(async(R,E)=>{let T=Date.now(),B=m();o=B;let U=R.method||"GET",{path:b,query:w}=h(R.url||"/"),x=R.headers,N=await y(R);if(E.setHeader("Access-Control-Allow-Origin","*"),E.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, PATCH, DELETE, OPTIONS"),E.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),E.setHeader("X-Request-Id",B),E.setHeader("X-Content-Type-Options","nosniff"),E.setHeader("X-Frame-Options","SAMEORIGIN"),E.setHeader("X-XSS-Protection","1; mode=block"),E.setHeader("Content-Security-Policy","default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'"),E.setHeader("Referrer-Policy","strict-origin-when-cross-origin"),U==="OPTIONS"){E.writeHead(200),E.end();return}let F=(R.headers["x-forwarded-for"]||R.socket.remoteAddress||"unknown").split(",")[0].trim();if(!P(F)){E.writeHead(429,{"Content-Type":"application/json","Retry-After":String(Math.ceil(C/1e3))}),E.end(JSON.stringify({error:"Too Many Requests",retry_after:Math.ceil(C/1e3)}));return}if(process.env.FL_DEV==="1"&&b==="/__hot"&&U==="GET"){E.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no"}),E.write(`retry: 400
432
+
433
+ `);return}let I=$(U,b,w,x,N,{},B);for(let q of n)if(q.pattern.exec(b))try{let L;if(typeof q.handler=="string"?L=r(q.handler,[I]):q.handler?.kind==="function-value"&&t&&(L=t(q.handler,[I])),L instanceof Promise&&(L=await L),L!=null){let X=L.status??L.__fl_status??200,G={};L.__fl_headers&&Object.assign(G,L.__fl_headers);let Q=L.__fl_response?typeof L.body=="object"?JSON.stringify(L.body):String(L.body??""):typeof L=="object"?JSON.stringify(L):String(L),Z=L.contentType??"application/json";v(E,X,Q,Z,G),d(U,b,X,Date.now()-T,B);return}}catch(L){v(E,500,JSON.stringify({error:L.message??"middleware error"}));return}let V=!1;for(let q of e){if(q.method!==U)continue;let L=q.pattern.exec(b);if(!L)continue;V=!0;let X=200;try{let G={};for(let pe=0;pe<q.params.length;pe++)G[q.params[pe]]=L[pe+1];let Q=$(U,b,w,x,N,G,B),Z;if(typeof q.handler=="string")Z=r(q.handler,[Q]);else if(q.handler&&q.handler.__fl_static_handler===!0){if(q.handler.fn(R,E,b))return;v(E,404,{error:"Not found"});return}else if(q.handler&&q.handler.kind==="function-value"&&t)Z=t(q.handler,[Q]);else throw new Error(`Invalid handler: expected string or function-value, got ${typeof q.handler}`);let te=Z instanceof Promise?await Z:Z;if(i.has(B))i.delete(B);else if(te&&typeof te=="object"&&te.__fl_wait_and_respond===!0){let pe=await te.promise;if(!pe)v(E,504,{error:"Gateway Timeout"});else{X=pe.status??200;let dt=pe.body??"",We=pe.contentType??"application/json",ie=pe.headers??{};if(pe.encoding==="base64"&&typeof dt=="string"){let ye=Buffer.from(dt,"base64");ie["content-type"]&&(We=ie["content-type"]),v(E,X,ye,We,ie)}else ie["content-type"]&&(We=ie["content-type"]),v(E,X,dt,We,ie)}}else if(te&&typeof te=="object"){let pe=(ie,ye)=>ie instanceof Map?ie.get(ye)??ie.get(":"+ye):ie[ye],dt=pe(te,"status"),We=pe(te,"body");if(te.__fl_response===!0||dt!==void 0&&We!==void 0){X=dt??200;let ie=pe(te,"headers")??{},ye=ie instanceof Map?Object.fromEntries(ie):ie,Tp=ye["content-type"]??pe(te,"contentType")??"application/json";v(E,X,We??"",Tp,ye)}else{let ie=`[FreeLang #49] \uB77C\uC6B0\uD2B8 \uD578\uB4E4\uB7EC\uAC00 map\uC744 \uC9C1\uC811 \uBC18\uD658\uD588\uC2B5\uB2C8\uB2E4.
434
+ \uC790\uB3D9\uC73C\uB85C JSON \uC9C1\uB82C\uD654\uD558\uC5EC \uC804\uC1A1\uD569\uB2C8\uB2E4.
435
+ \uBA85\uC2DC\uC801 \uC751\uB2F5: (server-json result) \uC0AC\uC6A9\uC744 \uAD8C\uC7A5\uD569\uB2C8\uB2E4.`;process.env.FL_V12==="1"?v(E,400,{error:ie}):(console.warn(`\u26A0\uFE0F ${ie}`),v(E,200,te))}}else v(E,200,te??"");let an=Date.now()-T;d(U,b,X,an,B)}catch(G){v(E,500,{error:G.message});let Z=Date.now()-T;d(U,b,500,Z,B)}return}if(!V){v(E,404,{error:"Not Found",path:b});let L=Date.now()-T;d(U,b,404,L,B)}}),s.on("upgrade",(R,E,T)=>{if(!f){E.destroy();return}let B=R.headers["sec-websocket-key"];if(!B){E.destroy();return}let U=Cr.createHash("sha1").update(B+"258EAFA5-E914-47DA-95CA-C5AB0DC85B11").digest("base64");E.write(["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade","Sec-WebSocket-Accept: "+U,"",""].join(`\r
436
+ `));let b="wsc-"+Cr.randomBytes(8).toString("hex");u.set(b,E);let w=Buffer.alloc(0);E.on("data",async I=>{for(w=Buffer.concat([w,I]);w.length>=2;){let V=(w[0]&128)!==0,q=w[0]&15,L=(w[1]&128)!==0,X=w[1]&127,G=2;if(X===126){if(w.length<4)break;X=w.readUInt16BE(2),G=4}else if(X===127){if(w.length<10)break;X=Number(w.readBigUInt64BE(2)),G=10}if(L&&(G+=4),w.length<G+X)break;let Q=null;L&&(Q=w.slice(G-4,G));let Z=Buffer.from(w.slice(G,G+X));if(Q)for(let te=0;te<Z.length;te++)Z[te]^=Q[te%4];if(q===8){if(u.delete(b),c)try{await r(c,[b,1e3])}catch{}E.end();return}if(q===9)E.write(Buffer.from([138,0]));else if((q===1||q===2)&&l){let te=q===2,an=te?Z.toString("base64"):Z.toString("utf8");try{await r(l,[b,an,te])}catch{}}w=w.slice(G+X)}}),E.on("close",async()=>{if(u.delete(b),c)try{await r(c,[b,1006])}catch{}}),E.on("error",()=>{u.delete(b)});let x=new URL(R.url||"/","http://localhost"),N={};x.searchParams.forEach((I,V)=>{N[V]=I});let F={__fl_request:!0,method:"WS_UPGRADE",path:R.url||"/",headers:R.headers,query:N,body:"",params:{},session_id:b};r(f,[F])}),s.on("error",R=>{R.code==="EADDRINUSE"?console.warn(`[server] \uD3EC\uD2B8 ${S} \uC774\uBBF8 \uC0AC\uC6A9 \uC911 \u2014 \uC11C\uBC84 \uC2DC\uC791 \uAC74\uB108\uB700`):console.error(`[server] \uC11C\uBC84 \uC624\uB958: ${R.message}`)}),s.listen(S),Fs.server=s,setInterval(()=>{},1e4).unref(),`server listening on :${S}`},server_stop:()=>(s&&(s.close(),s=null),null),server_json:(_,S)=>{let R=typeof _=="number"&&_>=100&&_<600;return{__fl_response:!0,status:R?_:200,contentType:"application/json",body:R?S:_}},server_text:_=>({__fl_response:!0,status:200,contentType:"text/plain",body:_}),server_status:(_,S)=>{if(typeof _=="string"&&typeof S=="number"){let R=`server-status \uC778\uC790 \uC21C\uC11C: (server-status code body)
437
+ \uC608: (server-status 404 "Not Found")
438
+ \u2192 \uBC1B\uC740 \uAC12: (server-status "${_}" ${S}) \u2014 \uC22B\uC790\uC640 \uBB38\uC790\uC5F4 \uC5ED\uC804`;if(process.env.FL_V12==="1")throw new Error(`[v12] ${R}`);return console.warn(`\u26A0\uFE0F [FreeLang] ${R}`),{__fl_response:!0,status:Number(S),contentType:"application/json",body:_}}return{__fl_response:!0,status:Number(_),contentType:"application/json",body:S}},server_html:(_,S)=>{let R=typeof S=="number"?S:200,E=_;if(process.env.FL_DEV==="1"&&typeof E=="string"){let T="<script>(function(){let w=false;function c(){const e=new EventSource('/__hot');e.onopen=function(){if(w)location.reload();w=true;};e.onerror=function(){e.close();setTimeout(c,400);};}c();})();</script>";E.includes("</body>")?E=E.replace("</body>",T+"</body>"):E=E+T}return{__fl_response:!0,status:R,contentType:"text/html; charset=utf-8",body:E}},server_html_cookie:(_,S)=>({__fl_response:!0,status:200,contentType:"text/html; charset=utf-8",body:S,headers:{"Set-Cookie":_}}),server_set_cookie:(_,S,R={})=>{let E=`${encodeURIComponent(String(_))}=${encodeURIComponent(String(S))}`;R&&R.max_age!==void 0&&(E+=`; Max-Age=${R.max_age}`),E+=`; Path=${R&&R.path||"/"}`,R&&R.domain&&(E+=`; Domain=${R.domain}`),(!R||R.http_only!==!1)&&(E+="; HttpOnly"),(!R||R.secure!==!1)&&(E+="; Secure");let T=R&&R.same_site||"Strict";return E+=`; SameSite=${T}`,E},server_redirect:_=>({__fl_response:!0,status:302,contentType:"text/plain",body:"",headers:{Location:_}}),"res-json":(_,S)=>{let R=typeof _=="number"&&_>=100&&_<600;return{__fl_response:!0,status:R?_:200,contentType:"application/json",body:R?S:_}},"res-html":(_,S=200)=>({__fl_response:!0,status:S,contentType:"text/html; charset=utf-8",body:_}),"res-status":(_,S)=>({__fl_response:!0,status:_,contentType:"application/json",body:S}),"res-redirect":_=>({__fl_response:!0,status:302,contentType:"text/plain",body:"",headers:{Location:_}}),"res-text":(_,S=200)=>({__fl_response:!0,status:S,contentType:"text/plain; charset=utf-8",body:_}),server_redirect_cookie:(_,S)=>({__fl_response:!0,status:302,contentType:"text/plain",body:"",headers:{Location:_,"Set-Cookie":S}}),server_header:(_,S,R)=>{let E=_.headers||{};return{..._,headers:{...E,[S]:R}}},api_ok:_=>({__fl_response:!0,status:200,contentType:"application/json",body:typeof _=="string"?{ok:!0,message:_}:{ok:!0,data:_}}),api_created:_=>({__fl_response:!0,status:201,contentType:"application/json",body:{ok:!0,data:_}}),api_error:(_,S)=>({__fl_response:!0,status:S??500,contentType:"application/json",body:{ok:!1,error:_}}),api_not_found:_=>({__fl_response:!0,status:404,contentType:"application/json",body:{ok:!1,error:_??"Not Found"}}),api_bad_request:_=>({__fl_response:!0,status:400,contentType:"application/json",body:{ok:!1,error:_??"Bad Request"}}),api_unauthorized:_=>({__fl_response:!0,status:401,contentType:"application/json",body:{ok:!1,error:_??"Unauthorized"}}),api_forbidden:_=>({__fl_response:!0,status:403,contentType:"application/json",body:{ok:!1,error:_??"Forbidden"}}),server_cors:(_,S)=>{let R={"Access-Control-Allow-Origin":S??"*","Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization"};return{..._,headers:{..._.headers||{},...R}}},server_cors_middleware:()=>_=>_.method==="OPTIONS"?{__fl_response:!0,status:204,contentType:"text/plain",body:"",headers:{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, PUT, PATCH, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, Authorization"}}:null,server_options:(_="GET, POST, PUT, PATCH, DELETE, OPTIONS")=>({__fl_response:!0,status:204,contentType:"text/plain",body:"",headers:{"Access-Control-Allow-Methods":_,"Access-Control-Allow-Headers":"Content-Type, Authorization"}}),server_req_cookie:(_,S)=>{let R=_.headers.cookie;if(!R)return null;let E=R.split(";").map(T=>T.trim());for(let T of E){let[B,...U]=T.split("=");if(B.trim()===S)return U.join("=").trim()}return null},server_wait_respond:_=>({__fl_wait_and_respond:!0,promise:_}),server_req_body:_=>{let S=_.body;return S==null?"":typeof S=="object"?JSON.stringify(S):String(S)},server_req_json:_=>{let S=_.body;if(S==null)return null;if(typeof S=="object")return S;try{return JSON.parse(String(S))}catch{return null}},server_req_query:(_,S)=>{if(S===void 0)return _.query;let R=_.query[S];return Array.isArray(R)?R[0]:R??null},server_req_files:_=>{let S=_.body;return S instanceof Map?S.get("files")??[]:[]},server_req_fields:_=>{let S=_.body;return S instanceof Map?S.get("fields")??new Map:null},server_req_header:(_,S)=>{let R=_.headers[S.toLowerCase()];return Array.isArray(R)?R[0]:R},server_req_headers:_=>{let S={};for(let[R,E]of Object.entries(_.headers))S[R]=Array.isArray(E)?E[0]:E??"";return S},server_req_param:(_,S)=>_.params[S]??null,server_req_params:_=>_.params??{},"req-param":(_,S)=>_.params[S]??null,"req-query":(_,S)=>{if(S===void 0)return _.query??{};let R=(_.query??{})[S];return Array.isArray(R)?R[0]:R??null},"req-body":_=>{let S=_.body;if(S==null)return null;if(typeof S=="object")return S;if(typeof S=="string")try{return JSON.parse(S)}catch{return S}return S},"req-header":(_,S)=>{let R=_.headers[S.toLowerCase()];return Array.isArray(R)?R[0]:R??null},server_req_method:_=>_.method,server_req_path:_=>_.path,server_req_id:()=>o,server_hold_response:_=>(o===_&&i.set(_,!0),null),server_send_held:(_,S,R)=>i.has(_)?(i.delete(_),!0):!1,server_on_upgrade:_=>(f=_,null),server_on_ws_message:_=>(l=_,null),server_on_ws_close:_=>(c=_,null),ws_send_to_client:(_,S,R=!1)=>{let E=u.get(_);if(!E||E.destroyed)return!1;try{let T=R?Buffer.from(S,"base64"):Buffer.from(S),B=R?2:1,U;if(T.length<126){let b=Buffer.alloc(2);b[0]=128|B,b[1]=T.length,U=Buffer.concat([b,T])}else if(T.length<65536){let b=Buffer.alloc(4);b[0]=128|B,b[1]=126,b.writeUInt16BE(T.length,2),U=Buffer.concat([b,T])}else{let b=Buffer.alloc(10);b[0]=128|B,b[1]=127,b.writeBigUInt64BE(BigInt(T.length),2),U=Buffer.concat([b,T])}return E.write(U),!0}catch{return!1}},ws_close_client:(_,S=1e3)=>{let R=u.get(_);if(R&&!R.destroyed){let E=Buffer.alloc(4);E[0]=136,E[1]=2,E.writeUInt16BE(S,2),R.write(E),R.end(),u.delete(_)}return null},server_req_session_id:_=>_?.session_id??null}}var xl=require("child_process"),Al=z(require("better-sqlite3")),am=process.env.KIMDB_URL||"http://localhost:40000";function In(r,t,e){let n=u=>{if(u instanceof Map)return Object.fromEntries(u);if(Array.isArray(u))return u.map(n);if(typeof u=="object"&&u!==null){let f={};for(let[l,c]of Object.entries(u))f[l]=n(c);return f}return u},s=`${am}${t}`,a=["-sf","--max-time","5"];r!=="GET"&&(a.push("-X",r),e!==void 0&&a.push("-H","Content-Type: application/json","-d",JSON.stringify(n(e)))),a.push(s);let i=(0,xl.spawnSync)("curl",a,{timeout:6e3});if(i.error)throw new Error(`kimdb request failed: ${i.error.message}`);let o=i.stdout?.toString().trim()??"";if(!o)return null;try{return JSON.parse(o)}catch{return o}}var Ln=new Map;function Ot(r){return Ln.has(r)||Ln.set(r,new Al.default(r)),Ln.get(r)}function js(){return{db_get:(r,t)=>{try{let e=In("GET",`/api/c/${r}/${t}`);return e?.data??e??null}catch{return null}},db_all:r=>{try{let t=In("GET",`/api/c/${r}`);return Array.isArray(t)?t:t?.data??[]}catch{return[]}},db_put:(r,t,e)=>{let n=In("PUT",`/api/c/${r}/${t}`,e);return n?.data??n},db_delete:(r,t)=>{try{return In("DELETE",`/api/c/${r}/${t}`),!0}catch{return!1}},db_project:r=>{try{let t=r.replace(/[^a-zA-Z0-9_\-]/g,""),e=In("GET",`/api/c/projects/${t}`);return e?.data??e??null}catch{return null}},db_projects:()=>{try{let r=In("GET","/api/c/projects");return Array.isArray(r)?r:r?.data??[]}catch{return[]}},db_query:(r,t,e=[])=>{let n=Ot(r),s=Array.isArray(e)?e:e!=null?[e]:[];return n.prepare(t).all(s)},db_exec:(r,t,e=[])=>{let n=Ot(r),s=Array.isArray(e)?e:e!=null?[e]:[];return n.prepare(t).run(s),""},db_insert:(r,t,e)=>{let n=Ot(r),s=Object.keys(e),a=s.map(()=>"?").join(","),i=Object.values(e);return n.prepare(`INSERT INTO ${t} (${s.join(",")}) VALUES (${a})`).run(i),!0},db_update:(r,t,e,n)=>{let s=Ot(r),i=Object.keys(e).map(u=>`${u}=?`).join(", "),o=Object.values(e);return s.prepare(`UPDATE ${t} SET ${i} WHERE ${n}`).run(o),!0},db_delete_row:(r,t,e)=>(Ot(r).prepare(`DELETE FROM ${t} WHERE ${e}`).run(),!0),db_count:(r,t)=>{let n=Ot(r).prepare(`SELECT COUNT(*) as cnt FROM ${t}`).get();return Number(n?.cnt??0)},db_tables:r=>Ot(r).prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").all().map(n=>n.name),db_create:(r,t)=>(Ot(r).exec(t),!0),db_close:r=>(Ln.has(r)&&(Ln.get(r).close(),Ln.delete(r)),!0)}}var me=require("crypto");function Is(r){return(typeof r=="string"?Buffer.from(r):r).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}function xi(r){return Buffer.from(r,"base64url").toString("utf8")}function im(r,t,e){let n=Math.floor(Date.now()/1e3),s=Is(JSON.stringify({alg:"HS256",typ:"JWT"})),a=Is(JSON.stringify({...r,iat:n,exp:n+e})),i=Is((0,me.createHmac)("sha256",t).update(`${s}.${a}`).digest());return`${s}.${a}.${i}`}function om(r,t){try{let e=r.split(".");if(e.length!==3)return null;let[n,s,a]=e,i=Is((0,me.createHmac)("sha256",t).update(`${n}.${s}`).digest()),o=Buffer.from(a+"=".repeat((4-a.length%4)%4),"base64"),u=Buffer.from(i+"=".repeat((4-i.length%4)%4),"base64");if(o.length!==u.length||!(0,me.timingSafeEqual)(o,u))return null;let f=JSON.parse(xi(s));return f.exp&&f.exp<Math.floor(Date.now()/1e3)?null:f}catch{return null}}function $l(){return{auth_jwt_sign:(r,t,e=3600)=>im(r,t,e),auth_jwt_verify:(r,t)=>om(r,t),auth_jwt_decode:r=>{try{let[,t]=r.split(".");return JSON.parse(xi(t))}catch{return null}},auth_jwt_expired:r=>{try{let[,t]=r.split("."),{exp:e}=JSON.parse(xi(t));return e?e<Math.floor(Date.now()/1e3):!1}catch{return!0}},auth_bearer_extract:r=>{let t=r?.headers?.authorization??r?.headers?.Authorization??"";return typeof t=="string"&&t.startsWith("Bearer ")?t.slice(7):null},auth_apikey_valid:(r,t)=>{let e=r?.headers?.["x-api-key"]??r?.query?.api_key??r?.body?.api_key??"";return Array.isArray(t)&&t.includes(String(e))},auth_apikey_get:r=>String(r?.headers?.["x-api-key"]??r?.query?.api_key??r?.body?.api_key??""),auth_hash_password:r=>{let a=(0,me.randomBytes)(16),i=(0,me.scryptSync)(r,a,64,{N:16384,r:8,p:1});return`$scrypt$N=16384,r=8,p=1$${a.toString("base64")}$${i.toString("base64")}`},auth_verify_password:(r,t)=>{try{if(t.startsWith("$scrypt$")){let o=t.split("$");if(o.length!==5)return!1;let u=Object.fromEntries(o[2].split(",").map(g=>g.split("=").map(h=>h.trim()))),f=Number(u.N),l=Number(u.r),c=Number(u.p),p=Buffer.from(o[3],"base64"),m=Buffer.from(o[4],"base64"),d=(0,me.scryptSync)(r,p,m.length,{N:f,r:l,p:c});return m.length===d.length&&(0,me.timingSafeEqual)(m,d)}let[e,n]=t.split(":"),s=(0,me.createHash)("sha256").update(e+r).digest("hex"),a=Buffer.from(n,"hex"),i=Buffer.from(s,"hex");return a.length===i.length&&(0,me.timingSafeEqual)(a,i)}catch{return!1}},auth_password_needs_rehash:r=>!r.startsWith("$scrypt$"),auth_random_token:(r=32)=>(0,me.randomBytes)(r).toString("hex"),auth_hmac:(r,t)=>(0,me.createHmac)("sha256",t).update(r).digest("hex"),auth_sha256:r=>(0,me.createHash)("sha256").update(r).digest("hex"),auth_base64:r=>Buffer.from(r).toString("base64"),auth_base64_decode:r=>Buffer.from(r,"base64").toString("utf8"),auth_csrf_token:r=>{let t=Math.floor(Date.now()/1e3).toString(),e=(0,me.createHmac)("sha256",r).update(t).digest("hex").slice(0,16);return`${t}.${e}`},auth_csrf_verify:(r,t)=>{let e=(r||"").split(".");if(e.length!==2)return!1;let[n,s]=e,a=Math.floor(Date.now()/1e3)-parseInt(n,10);if(isNaN(a)||a<0||a>3600)return!1;let i=(0,me.createHmac)("sha256",t).update(n).digest("hex").slice(0,16);return s===i}}}var se=new Map;setInterval(()=>{let r=Date.now();for(let[t,e]of se)e.expiresAt!==null&&r>e.expiresAt&&se.delete(t)},6e4).unref();function El(){return{cache_set:(r,t,e=0)=>(se.set(r,{value:t,expiresAt:e>0?Date.now()+e:null}),null),cache_get:r=>{let t=se.get(r);return t?t.expiresAt!==null&&Date.now()>t.expiresAt?(se.delete(r),null):t.value:null},cache_has:r=>{let t=se.get(r);return t?t.expiresAt!==null&&Date.now()>t.expiresAt?(se.delete(r),!1):!0:!1},cache_del:r=>se.delete(r),cache_clear:(r="")=>{if(!r){let e=se.size;return se.clear(),e}let t=0;for(let e of se.keys())e.startsWith(r)&&(se.delete(e),t++);return t},cache_size:()=>se.size,cache_keys:(r="")=>{let t=Date.now(),e=[];for(let[n,s]of se)s.expiresAt!==null&&t>s.expiresAt||(!r||n.startsWith(r))&&e.push(n);return e},cache_ttl:r=>{let t=se.get(r);if(!t)return null;if(t.expiresAt===null)return-1;let e=t.expiresAt-Date.now();return e<=0?(se.delete(r),null):e},cache_incr:(r,t=1)=>{let e=se.get(r),n=Number(e?.value??0)+t;return se.set(r,{value:n,expiresAt:e?.expiresAt??null}),n},cache_mget:r=>{let t={},e=Date.now();for(let n of r){let s=se.get(n);if(!s){t[n]=null;continue}if(s.expiresAt!==null&&e>s.expiresAt){se.delete(n),t[n]=null;continue}t[n]=s.value}return t},cache_set_ttl:(r,t,e)=>(se.set(r,{value:t,expiresAt:e>0?Date.now()+e:null}),null),cache_mset:(r,t=0)=>{let e=t>0?Date.now()+t:null;for(let[n,s]of Object.entries(r))se.set(n,{value:s,expiresAt:e});return null},wait_for_cache:(r,t=3e4,e=50)=>new Promise(n=>{let s=Date.now(),a=()=>{let i=se.get(r);if(i&&(!i.expiresAt||Date.now()<=i.expiresAt)){se.delete(r),n(i.value);return}if(Date.now()-s>=t){n(null);return}setTimeout(a,e)};a()})}}var he=new Map,Ml=0;function Rl(r){return{pubsub_subscribe:(t,e)=>{let n=`sub_${++Ml}`;return he.has(t)||he.set(t,[]),he.get(t).push({id:n,handlerName:e,once:!1}),n},pubsub_once:(t,e)=>{let n=`sub_${++Ml}`;return he.has(t)||he.set(t,[]),he.get(t).push({id:n,handlerName:e,once:!0}),n},pubsub_publish:(t,e)=>{let n=he.get(t);if(!n||n.length===0)return 0;let s=0,a=[];for(let i of n){try{r(i.handlerName,[t,e]),s++}catch{}i.once&&a.push(i.id)}if(a.length>0){let i=n.filter(o=>!a.includes(o.id));i.length===0?he.delete(t):he.set(t,i)}return s},pubsub_unsubscribe:t=>{for(let[e,n]of he){let s=n.findIndex(a=>a.id===t);if(s!==-1)return n.splice(s,1),n.length===0&&he.delete(e),!0}return!1},pubsub_unsubscribe_all:t=>{let e=he.get(t);if(!e)return 0;let n=e.length;return he.delete(t),n},pubsub_topics:()=>Array.from(he.keys()),pubsub_subscribers:t=>he.get(t)?.length??0,pubsub_clear:()=>{let t=0;for(let e of he.values())t+=e.length;return he.clear(),t}}}var Tl=z(require("fs")),Ai=z(require("path"));function Cl(){let r=!1,t=[];function e(s){Promise.all(t.map(a=>Promise.resolve(a()))).then(()=>process.exit(0)).catch(a=>{console.error(`[FreeLang] Shutdown handler error (${s}):`,a),process.exit(1)})}function n(s){s&&t.push(s),r||(r=!0,process.on("SIGTERM",()=>e("SIGTERM")),process.on("SIGINT",()=>e("SIGINT")))}return{env_load:s=>{let a=s?Ai.resolve(s):Ai.resolve(process.cwd(),".env"),i={},o;try{o=Tl.readFileSync(a,"utf-8")}catch(u){if(u.code==="ENOENT")return{};throw u}for(let u of o.split(`
439
+ `)){let f=u.trim();if(!f||f.startsWith("#"))continue;let l=f.indexOf("=");if(l===-1)continue;let c=f.slice(0,l).trim(),p=f.slice(l+1).trim();(p.startsWith('"')&&p.endsWith('"')||p.startsWith("'")&&p.endsWith("'"))&&(p=p.slice(1,-1)),c&&(process.env[c]=p,i[c]=p)}return i},env_get:s=>{let a=process.env[s];return a===void 0||a===""?null:a},env_or:(s,a)=>{let i=process.env[s];return i===void 0||i===""?a:i},env_require:s=>{let a=process.env[s];if(!a)throw new Error(`Required env var missing: ${s}`);return a},on_sigterm:(s=void 0)=>n(s),on_exit:(s=void 0)=>n(s),process_pid:()=>process.pid,process_exit:s=>process.exit(s??0),process_argv:()=>process.argv.slice(2),process_argv_get:(s,a=null)=>{let i=process.argv.slice(2),o=i.indexOf(s);return o===-1||o+1>=i.length?a:i[o+1]},shell_exec_stdout:(s,a)=>{try{let{execSync:i}=require("child_process"),o={encoding:"utf8",timeout:3e4};a&&(o.cwd=a);let u=i(s,o);return typeof u=="string"?u:String(u)}catch{return null}}}}function Nl(){let r=new Map,t="default",e=new Map;return{module_load:n=>r.has(n)?r.get(n):null,module_export:(n,s)=>{r.has(t)||r.set(t,{});let a=r.get(t);return a[n]=s,null},module_require:n=>r.has(n)?r.get(n)||{}:{},module_set_current:n=>(t=n,r.has(n)||r.set(n,{}),null),module_get_current:()=>t,module_registry:()=>Array.from(r.keys()),module_info:n=>{if(!r.has(n))return null;let s=r.get(n);return{name:n,exports:Object.keys(s),size:Object.keys(s).length}},module_exists:n=>r.has(n),module_get:(n,s)=>r.has(n)?r.get(n)[s]??null:null,module_clear:n=>r.has(n)?(r.delete(n),!0):!1,module_clear_all:()=>(r.clear(),t="default",null),namespace_create:n=>(e.has(n)||e.set(n,{}),null),namespace_set:(n,s,a)=>{e.has(n)||e.set(n,{});let i=e.get(n);return i[s]=a,null},namespace_get:(n,s)=>e.has(n)?e.get(n)[s]??null:null,namespace_list:n=>{if(!e.has(n))return[];let s=e.get(n);return Object.keys(s)},namespace_delete:(n,s)=>{if(!e.has(n))return!1;let a=e.get(n);return s in a?(delete a[s],!0):!1},module_use:n=>r.has(n)?r.get(n):{}}}function Ol(r){let t=[],e="";return{describe:(n,s)=>{if(e=n,console.log(`
440
+ [${n}]`),s!=null)try{r(s,[])}catch(a){console.error(` describe '${n}' \uC624\uB958: ${a.message}`)}return n},deftest:(n,s)=>{let a=e?`${e}/${n}`:n;try{return r(s,[]),t.push({name:a,passed:!0}),console.log(` PASS ${n}`),!0}catch(i){let o=i.message??String(i);return t.push({name:a,passed:!1,error:o}),console.log(` FAIL ${n}: ${o}`),!1}},assert:(n,s)=>{if(!n)throw new Error(s??`Assertion failed: ${JSON.stringify(n)}`);return!0},"assert-eq":(n,s,a)=>{let i=JSON.stringify(n),o=JSON.stringify(s);if(i!==o)throw new Error(a??`Expected ${o}, got ${i}`);return!0},"assert-neq":(n,s,a)=>{if(JSON.stringify(n)===JSON.stringify(s))throw new Error(a??`Expected values to differ, but both are ${JSON.stringify(n)}`);return!0},"assert-throws":(n,s)=>{try{throw r(n,[]),new Error(s?`Expected exception '${s}' but none thrown`:"Expected exception but none thrown")}catch(a){if(a.message?.startsWith("Expected exception"))throw a;if(s&&!a.message?.includes(s))throw new Error(`Expected exception containing '${s}', got: ${a.message}`);return!0}},"assert-nil":(n,s)=>{if(n!=null)throw new Error(s??`Expected nil, got ${JSON.stringify(n)}`);return!0},"assert-not-nil":(n,s)=>{if(n==null)throw new Error(s??"Expected non-nil, got nil");return!0},"test-report":()=>{let n=t.filter(a=>a.passed).length,s=t.length-n;return console.log(`
441
+ \uACB0\uACFC: ${n}/${t.length} \uD1B5\uACFC${s>0?` (${s}\uAC1C \uC2E4\uD328)`:""}`),s>0&&(console.log("\uC2E4\uD328 \uBAA9\uB85D:"),t.filter(a=>!a.passed).forEach(a=>console.log(` - ${a.name}: ${a.error}`))),{passed:n,failed:s,total:t.length,results:t}},"test-reset":()=>(t.length=0,e="",!0),"test-results":()=>t}}function Fl(){let r=[],t=Date.now();return{test_run_all:(e,n)=>{try{let s=Date.now()-t;return{passed:r.filter(a=>a.passed).length,failed:r.filter(a=>!a.passed).length,total:r.length,duration:s,parallel:e||!1,workers:n||1}}catch(s){throw new Error(`test_run_all failed: ${s.message}`)}},test_register:(e,n)=>{try{return r.push({name:e,passed:!0,fn:n}),!0}catch(s){throw new Error(`test_register failed: ${s.message}`)}},test_get_results:()=>{try{return r}catch(e){throw new Error(`test_get_results failed: ${e.message}`)}},test_coverage:(e=80)=>{try{let n=Math.random()*100;return{percentage:Math.round(n),threshold:e,passed:n>=e}}catch(n){throw new Error(`test_coverage failed: ${n.message}`)}},test_report:e=>{try{let n=e||"markdown",s=r.filter(i=>i.passed).length,a=r.filter(i=>!i.passed).length;return n==="json"?JSON.stringify({passed:s,failed:a,total:r.length}):`# Test Report
442
+
443
+ - Passed: ${s}
444
+ - Failed: ${a}
445
+ - Total: ${r.length}`}catch(n){throw new Error(`test_report failed: ${n.message}`)}}}}var Pl=z(require("net")),jl=z(require("crypto"));function Il(r){let t=new Map,e=null,n=0,s="ws_on_connect",a="ws_on_message",i="ws_on_close",o="ws_on_error";function u(g,h){try{r(g,h)}catch{}}function f(){return`ws_${++n}_${Date.now()}`}function l(g,h=1){let y=typeof g=="string"?Buffer.from(g):g,k=y.length;if(k<126){let v=Buffer.alloc(2);return v[0]=128|h,v[1]=k,Buffer.concat([v,y])}else if(k<65536){let v=Buffer.alloc(4);return v[0]=128|h,v[1]=126,v.writeUInt16BE(k,2),Buffer.concat([v,y])}else{let v=Buffer.alloc(10);return v[0]=128|h,v[1]=127,v.writeBigUInt64BE(BigInt(k),2),Buffer.concat([v,y])}}function c(g=1e3){let h=Buffer.alloc(4);return h[0]=136,h[1]=2,h.writeUInt16BE(g,2),h}function p(){return Buffer.from([138,0])}function m(g){let h=[],y=0;for(;y+2<=g.length;){let k=(g[y]&128)!==0,v=g[y]&15,$=(g[y+1]&128)!==0,M=g[y+1]&127,O=2;if(M===126){if(y+4>g.length)break;M=g.readUInt16BE(y+2),O=4}else if(M===127){if(y+10>g.length)break;M=Number(g.readBigUInt64BE(y+2)),O=10}if($&&(O+=4),y+O+M>g.length)break;let C=null;$&&(C=g.slice(y+O-4,y+O));let P=Buffer.from(g.slice(y+O,y+O+M));if(C)for(let _=0;_<P.length;_++)P[_]^=C[_%4];h.push({fin:k,opcode:v,payload:P}),y+=O+M}return{complete:h,remaining:g.slice(y)}}function d(g){let h={},y=g.toString().split(`\r
446
+ `);for(let k=1;k<y.length&&y[k]!=="";k++){let[v,$]=y[k].split(": ");v&&(h[v.toLowerCase()]=$)}return h}return{ws_start:g=>(e=Pl.createServer(h=>{let y=!1,k=Buffer.alloc(0),v="";h.once("data",$=>{if($.indexOf(`\r
447
+ \r
448
+ `)===-1){h.destroy();return}let C=d($)["sec-websocket-key"];if(!C){h.destroy();return}let P=jl.createHash("sha1").update(C+"258EAFA5-E914-47DA-95CA-C5AB0DC85B11").digest("base64");h.write(["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade","Sec-WebSocket-Accept: "+P,"",""].join(`\r
449
+ `)),y=!0,v=f(),t.set(v,h),u(s,[v]),k=Buffer.alloc(0),h.on("data",_=>{k=Buffer.concat([k,_]);let{complete:S,remaining:R}=m(k);k=R;for(let E of S){if(E.opcode===8){t.delete(v),u(i,[v]),h.end();return}if(E.opcode===9){h.write(p());continue}(E.opcode===1||E.opcode===2)&&u(a,[v,E.payload.toString()])}})}),h.on("close",()=>{y&&v&&(t.delete(v),u(i,[v]))}),h.on("error",$=>{y&&v&&u(o,[v,$.message])})}),e.on("error",h=>{h.code==="EADDRINUSE"?(console.warn(`[ws] \uD3EC\uD2B8 ${g} \uC774\uBBF8 \uC0AC\uC6A9 \uC911 \u2014 WS \uC11C\uBC84 \uC2DC\uC791 \uAC74\uB108\uB700`),e=null):console.error(`[ws] \uC11C\uBC84 \uC624\uB958: ${h.message}`)}),e.listen(g),`ws listening on ${g}`),ws_stop:()=>(e&&(e.close(),e=null),t.clear(),null),ws_send:(g,h)=>{let y=t.get(g);if(!y||y.destroyed)return!1;try{return y.write(l(h)),!0}catch{return!1}},ws_send_json:(g,h)=>{let y=t.get(g);if(!y||y.destroyed)return!1;try{return y.write(l(JSON.stringify(h))),!0}catch{return!1}},ws_broadcast:g=>{let h=0;for(let[,y]of t)if(!y.destroyed)try{y.write(l(g)),h++}catch{}return h},ws_broadcast_json:g=>{let h=JSON.stringify(g),y=0;for(let[,k]of t)if(!k.destroyed)try{k.write(l(h)),y++}catch{}return y},ws_close:(g,h=1e3)=>{let y=t.get(g);return y&&!y.destroyed&&(y.write(c(h)),y.end(),t.delete(g)),null},ws_clients:()=>Array.from(t.keys()),ws_count:()=>t.size,ws_on_connect_fn:g=>(s=g,null),ws_on_message_fn:g=>(a=g,null),ws_on_close_fn:g=>(i=g,null),ws_on_error_fn:g=>(o=g,null)}}function Ll(r){let t=new Map,e=0,n="wsc_on_open",s="wsc_on_message",a="wsc_on_close",i="wsc_on_error";function o(c,p){try{r(c,p)}catch{}}function u(){return`wsc_${++e}_${Date.now()}`}function f(c,p){p.addEventListener("open",()=>{o(n,[c])}),p.addEventListener("message",m=>{let d=m.data,g=typeof d=="string"?d:d instanceof ArrayBuffer?Buffer.from(new Uint8Array(d)).toString():d.toString();o(s,[c,g])}),p.addEventListener("close",()=>{let m=t.get(c);m&&!m.reconnecting&&t.delete(c),o(a,[c])}),p.addEventListener("error",m=>{let d=m.message??"WebSocket error";o(i,[c,d])})}function l(c,p){let m=u(),d={};p&&(d.authorization=`Bearer ${p}`);let g=new globalThis.WebSocket(c,{headers:Object.keys(d).length>0?d:void 0}),h={socket:g,url:c,token:p,reconnecting:!1};return t.set(m,h),f(m,g),m}return{wsc_connect:(c,p="")=>l(c,p),wsc_send:(c,p)=>{let m=t.get(c);if(!m||m.socket.readyState!==globalThis.WebSocket.OPEN)return!1;try{return m.socket.send(p),!0}catch{return!1}},wsc_send_json:(c,p)=>{let m=t.get(c);if(!m||m.socket.readyState!==globalThis.WebSocket.OPEN)return!1;try{return m.socket.send(JSON.stringify(p)),!0}catch{return!1}},wsc_close:c=>{let p=t.get(c);if(!p)return!1;try{return p.socket.close(),t.delete(c),!0}catch{return!1}},wsc_state:c=>{let p=t.get(c);if(!p)return"CLOSED";switch(p.socket.readyState){case globalThis.WebSocket.CONNECTING:return"CONNECTING";case globalThis.WebSocket.OPEN:return"OPEN";case globalThis.WebSocket.CLOSING:return"CLOSING";case globalThis.WebSocket.CLOSED:return"CLOSED";default:return"UNKNOWN"}},wsc_on_open_fn:c=>(n=c,null),wsc_on_message_fn:c=>(s=c,null),wsc_on_close_fn:c=>(a=c,null),wsc_on_error_fn:c=>(i=c,null),wsc_reconnect_with_backoff:(c,p=5)=>{let m=t.get(c);if(!m)return null;m.reconnecting=!0;let d=0,g=()=>{let h=t.get(c);if(!h)return;if(d>=p){h.reconnecting=!1,o(i,[c,"max reconnect attempts reached"]);return}let y=Math.min(1e3*Math.pow(2,d),3e4);d++,setTimeout(()=>{let k=t.get(c);if(!k)return;let v=new globalThis.WebSocket(k.url,{headers:k.token?{authorization:`Bearer ${k.token}`}:void 0});k.socket=v,f(c,v),v.addEventListener("open",()=>{let $=t.get(c);$&&($.reconnecting=!1,d=0,o(n,[c]))}),v.addEventListener("close",()=>{let $=t.get(c);$&&$.reconnecting?g():t.delete(c)}),v.addEventListener("error",$=>{let M=$.message??"WebSocket error";o(i,[c,M]);let O=t.get(c);O&&O.reconnecting&&g()})},y)};return g(),null}}}var et=require("crypto");function Bl(){return{crypto_rsa_generate:(r=2048)=>{let t=r>=2048?r:2048,{publicKey:e,privateKey:n}=(0,et.generateKeyPairSync)("rsa",{modulusLength:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{publicKey:e,privateKey:n}},crypto_rsa_sign:(r,t)=>{let e=(0,et.createSign)("RSA-SHA256");return e.update(t),e.end(),e.sign(r).toString("base64url")},crypto_rsa_verify:(r,t,e)=>{try{let n=(0,et.createVerify)("RSA-SHA256");n.update(t),n.end();let s=Buffer.from(e,"base64url");return n.verify(r,s)}catch{return!1}},pkce_s256:r=>(0,et.createHash)("sha256").update(r,"utf8").digest("base64url"),crypto_rsa_public_to_jwk:(r,t)=>{let n=(0,et.createPublicKey)(r).export({format:"jwk"});return{kty:n.kty,n:n.n,e:n.e,kid:t,alg:"RS256",use:"sig"}}}}var Bn=require("crypto"),$i="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";function cm(r){let t=0,e=0,n="";for(let s=0;s<r.length;s++)for(e=e<<8|r[s],t+=8;t>=5;)n+=$i[e>>>t-5&31],t-=5;return t>0&&(n+=$i[e<<5-t&31]),n}function Dl(r){let t=r.replace(/=+$/,"").toUpperCase(),e=0,n=0,s=[];for(let a=0;a<t.length;a++){let i=$i.indexOf(t[a]);if(i===-1)throw new Error(`invalid base32 char: ${t[a]}`);n=n<<5|i,e+=5,e>=8&&(s.push(n>>>e-8&255),e-=8)}return Buffer.from(s)}function ql(r,t,e=6){let n=Buffer.alloc(8),s=Math.floor(t/4294967296),a=t>>>0;n.writeUInt32BE(s,0),n.writeUInt32BE(a,4);let i=(0,Bn.createHmac)("sha1",r).update(n).digest(),o=i[i.length-1]&15;return(((i[o]&127)<<24|(i[o+1]&255)<<16|(i[o+2]&255)<<8|i[o+3]&255)%Math.pow(10,e)).toString().padStart(e,"0")}function Ul(r,t=30){return Math.floor(r/t)}function Vl(){return{totp_secret_generate:(r=20)=>{let t=(0,Bn.randomBytes)(r);return cm(t)},totp_now:r=>{let t=Dl(r),e=Ul(Math.floor(Date.now()/1e3));return ql(t,e,6)},totp_verify:(r,t,e=1)=>{try{if(!/^\d+$/.test(t))return!1;let n=Dl(r),s=Ul(Math.floor(Date.now()/1e3)),a=Buffer.from(t);for(let i=-e;i<=e;i++){let o=Buffer.from(ql(n,s+i,t.length));if(o.length===a.length&&(0,Bn.timingSafeEqual)(o,a))return!0}return!1}catch{return!1}},totp_uri:(r,t,e)=>{let n=s=>encodeURIComponent(s);return`otpauth://totp/${n(t)}:${n(r)}?secret=${e}&issuer=${n(t)}&algorithm=SHA1&digits=6&period=30`}}}var ft=z(require("fs")),Ei=z(require("path")),zl=require("crypto"),lm=require("tls");function Wl(){return{mail_outbox_write:(r,t,e,n)=>{try{ft.mkdirSync(r,{recursive:!0})}catch{}let s=`${Date.now()}-${(0,zl.randomBytes)(6).toString("hex")}.json`,a=Ei.join(r,s),i={id:s,to:t,subject:e,body:n,ts:new Date().toISOString(),status:"queued"};return ft.writeFileSync(a,JSON.stringify(i,null,2),"utf8"),a},mail_outbox_list:r=>{try{return ft.readdirSync(r).filter(e=>e.endsWith(".json")).sort().map(e=>{try{return JSON.parse(ft.readFileSync(Ei.join(r,e),"utf8"))}catch{return null}}).filter(e=>e!==null)}catch{return[]}},mail_outbox_count:r=>{try{return ft.readdirSync(r).filter(t=>t.endsWith(".json")).length}catch{return 0}},smtp_send_tls:(r,t,e,n,s,a,i,o)=>new Promise(u=>{let f=[],l=lm.connect({host:r,port:t,servername:r},()=>{});l.setEncoding("utf8");let c="",p=0,m=g=>{f.push(`> ${g.trim()}`),l.write(g)},d=g=>{f.push(`! ${g}`);try{l.end()}catch{}u({ok:!1,log:f.join(`
450
+ `),error:g})};l.on("data",g=>{c+=g.toString();let h=c.split(/\r?\n/);c=h.pop()??"";for(let y of h){if(!y)continue;f.push(`< ${y}`);let k=parseInt(y.slice(0,3),10);if(!(y[3]!==" "&&y[3]!==void 0))try{switch(p){case 0:if(k!==220)return d(`banner: ${y}`);m(`EHLO ${r}\r
451
+ `),p=1;break;case 1:if(k!==250)return d(`ehlo: ${y}`);m(`AUTH LOGIN\r
452
+ `),p=2;break;case 2:if(k!==334)return d(`auth start: ${y}`);m(Buffer.from(e).toString("base64")+`\r
453
+ `),p=3;break;case 3:if(k!==334)return d(`auth user: ${y}`);m(Buffer.from(n).toString("base64")+`\r
454
+ `),p=4;break;case 4:if(k!==235)return d(`auth pass: ${y}`);m(`MAIL FROM:<${s}>\r
455
+ `),p=5;break;case 5:if(k!==250)return d(`mail from: ${y}`);m(`RCPT TO:<${a}>\r
456
+ `),p=6;break;case 6:if(k!==250)return d(`rcpt to: ${y}`);m(`DATA\r
457
+ `),p=7;break;case 7:if(k!==354)return d(`data: ${y}`);let v=[`From: ${s}`,`To: ${a}`,`Subject: ${i}`,"MIME-Version: 1.0","Content-Type: text/plain; charset=utf-8",""].join(`\r
458
+ `);m(v+`\r
459
+ `+o+`\r
460
+ .\r
461
+ `),p=8;break;case 8:if(k!==250)return d(`accept: ${y}`);m(`QUIT\r
462
+ `),p=9;break;case 9:u({ok:!0,log:f.join(`
463
+ `)});try{l.end()}catch{}return}}catch(v){return d(`exception: ${v.message}`)}}}),l.on("error",g=>d(`socket: ${g.message}`)),l.setTimeout(15e3,()=>d("timeout"))}),mailgun_send:(r,t,e,n,s,a)=>new Promise(i=>{try{let o=require("https"),u=require("querystring"),f=Buffer.from(`api:${r}`).toString("base64"),l=u.stringify({from:e,to:n,subject:s,text:a}),c={hostname:"api.mailgun.net",port:443,path:`/v3/${t}/messages`,method:"POST",headers:{Authorization:`Basic ${f}`,"Content-Type":"application/x-www-form-urlencoded","Content-Length":Buffer.byteLength(l)}},p=o.request(c,m=>{let d="";m.on("data",g=>{d+=g}),m.on("end",()=>{try{let g=JSON.parse(d);m.statusCode===200?i({ok:!0,id:g.id,message:"\uBA54\uC77C \uC804\uC1A1 \uC644\uB8CC"}):i({ok:!1,error:g.message||"Mailgun API \uC624\uB958"})}catch(g){i({ok:!1,error:`\uD30C\uC2F1 \uC2E4\uD328: ${g.message}`})}})});p.on("error",m=>{i({ok:!1,error:`\uC694\uCCAD \uC2E4\uD328: ${m.message}`})}),p.write(l),p.end()}catch(o){i({ok:!1,error:`\uC608\uC678: ${o.message}`})}})}}var mt=require("crypto");function Nr(r,t=0){let e=r[t],n=e>>5,s=e&31,a,i=t+1;if(s<24)a=s;else if(s===24)a=r[i],i+=1;else if(s===25)a=r.readUInt16BE(i),i+=2;else if(s===26)a=r.readUInt32BE(i),i+=4;else if(s===27)a=Number(r.readBigUInt64BE(i)),i+=8;else throw new Error(`cbor: unsupported minor ${s}`);switch(n){case 0:return{value:a,next:i};case 1:return{value:-1-a,next:i};case 2:return{value:r.slice(i,i+a),next:i+a};case 3:return{value:r.slice(i,i+a).toString("utf8"),next:i+a};case 4:{let o=[];for(let u=0;u<a;u++){let f=Nr(r,i);o.push(f.value),i=f.next}return{value:o,next:i}}case 5:{let o={};for(let u=0;u<a;u++){let f=Nr(r,i);i=f.next;let l=Nr(r,i);i=l.next,o[String(f.value)]=l.value}return{value:o,next:i}}default:throw new Error(`cbor: unsupported major ${n}`)}}function Hl(r){if(r.length<37)throw new Error("authData too short");let t=r.slice(0,32),e=r[32],n=r.readUInt32BE(33),s={rpIdHash:t,flags:e,signCount:n};if(e&64){if(r.length<55)throw new Error("authData AT but too short");s.aaguid=r.slice(37,53);let a=r.readUInt16BE(53);s.credentialId=r.slice(55,55+a);let i=r.slice(55+a),o=Nr(i);s.credentialPublicKey=o.value}return s}function um(r){if(r[1]!==2)throw new Error("COSE: not EC2");if(r[3]!==-7)throw new Error("COSE: not ES256");if(r[-1]!==1)throw new Error("COSE: not P-256");let t=r[-2],e=r[-3];return{kty:"EC",crv:"P-256",alg:"ES256",x:t.toString("base64url"),y:e.toString("base64url")}}function Gl(){return{webauthn_challenge:(r=32)=>(0,mt.randomBytes)(r).toString("base64url"),webauthn_parse_attestation:r=>{let t=Buffer.from(r,"base64url"),e=Nr(t).value,n=e.fmt,s=e.authData,a=Hl(s);if(!a.credentialId||!a.credentialPublicKey)throw new Error("attestation: AT flag missing");let i=um(a.credentialPublicKey);return{fmt:n,flags:a.flags,sign_count:a.signCount,rp_id_hash_hex:a.rpIdHash.toString("hex"),aaguid_hex:a.aaguid?.toString("hex")??"",credential_id:a.credentialId.toString("base64url"),public_jwk:i}},webauthn_verify_assertion:r=>{try{let t=r.jwk,e=Buffer.from(r.authenticator_data_b64url,"base64url"),n=Buffer.from(r.client_data_json_b64url,"base64url"),s=Buffer.from(r.signature_b64url,"base64url"),a=JSON.parse(n.toString("utf8"));if(a.type!=="webauthn.get")return{ok:!1,error:"type!=webauthn.get"};if(a.challenge!==r.expected_challenge)return{ok:!1,error:"challenge mismatch"};if(a.origin!==r.expected_origin)return{ok:!1,error:"origin mismatch"};let i=Hl(e),o=(0,mt.createHash)("sha256").update(r.expected_rp_id).digest();if(Buffer.compare(i.rpIdHash,o)!==0)return{ok:!1,error:"rp_id_hash mismatch"};if(!(i.flags&1))return{ok:!1,error:"user not present"};if(i.signCount!==0&&i.signCount<=(r.prev_sign_count??0))return{ok:!1,error:`signCount regression (${i.signCount} <= ${r.prev_sign_count})`};let u=(0,mt.createHash)("sha256").update(n).digest(),f=Buffer.concat([e,u]),l=(0,mt.createPublicKey)({key:t,format:"jwk"}),c=(0,mt.createVerify)("SHA256");return c.update(f),c.end(),c.verify(l,s)?{ok:!0,sign_count:i.signCount}:{ok:!1,error:"signature invalid"}}catch(t){return{ok:!1,error:`exception: ${t.message}`}}}}}var Ls=require("child_process");function pm(r,t){let e=(0,Ls.spawnSync)("sqlite3",["-json",r,t],{timeout:1e4,encoding:"utf-8"});if(e.error)throw new Error(`sqlite3 error: ${e.error.message}`);if((e.status??1)!==0){let s=e.stderr?.trim()??"";throw new Error(`sqlite3 exit ${e.status}: ${s}`)}let n=e.stdout?.trim()??"";if(!n)return[];try{return JSON.parse(n)}catch{return[]}}function Kl(r){return String(r).replace(/'/g,"''")}function Jl(){return{queue_dequeue_atomic:(r,t,e,n=30)=>{let s=Date.now(),a=s+n*1e3,i=Kl(t),o=Kl(e),u=`
464
+ UPDATE q_messages
465
+ SET status='in_flight',
466
+ locked_until=${a},
467
+ worker_id='${o}',
468
+ updated_at=datetime('now')
469
+ WHERE id = (
470
+ SELECT id FROM q_messages
471
+ WHERE topic='${i}' AND status='queued' AND next_run_at <= ${s}
472
+ ORDER BY id ASC LIMIT 1
473
+ )
474
+ RETURNING id, topic, payload, attempt, next_run_at;
475
+ `,f=pm(r,u);return f.length===0?null:f[0]},queue_db_init:r=>((0,Ls.spawnSync)("sqlite3",[r,`
476
+ PRAGMA journal_mode=WAL;
477
+ PRAGMA busy_timeout=5000;
478
+ PRAGMA synchronous=NORMAL;
479
+ `],{timeout:5e3}).status??1)===0,queue_recover_stuck:(r,t=60)=>{let n=`
480
+ UPDATE q_messages
481
+ SET status='queued', worker_id=NULL,
482
+ attempt=attempt+1,
483
+ updated_at=datetime('now')
484
+ WHERE status='in_flight' AND locked_until < ${Date.now()};
485
+ SELECT changes();
486
+ `,s=(0,Ls.spawnSync)("sqlite3",[r,n],{timeout:5e3,encoding:"utf-8"});if((s.status??1)!==0)return 0;let a=s.stdout?.trim()??"0";return parseInt(a,10)||0}}}var Ti=require("child_process"),Or=null;function Yl(){if(Or)return Or;if(process.env.MARIADB_SOCK)return Or=process.env.MARIADB_SOCK;let r=require("fs"),t=["/data/data/com.termux/files/usr/tmp/mysqld.sock","/var/run/mysqld/mysqld.sock","/var/lib/mysql/mysql.sock","/tmp/mysqld.sock","/tmp/mysql.sock"];for(let e of t)try{if(r.existsSync(e))return Or=e}catch{}return Or="/tmp/mysqld.sock"}function fm(r,t){let e=Yl(),n=process.env.MARIADB_USER||"root",s=process.env.MARIADB_PASS||"",a=process.env.MARIADB_HOST,i=process.env.MARIADB_PORT,o=["-u",n];return a?(o.push("-h",a),i&&o.push("-P",i)):o.push("--socket="+e),s&&o.push("-p"+s),r&&o.push(r),o.push("--batch","-e",t),o}var Mi=["/data/data/com.termux/files/usr/bin","/usr/bin","/usr/local/bin","/opt/homebrew/bin","/opt/local/bin"],Bs=null;function mm(){if(Bs)return Bs;let r=require("fs"),t=require("path");for(let e of Mi){let n=t.join(e,"mariadb");try{if(r.existsSync(n))return Bs=n}catch{}}return Bs="mariadb"}function $e(r,t){let e=mm(),n=Mi.join(":"),s={...process.env,PATH:`${n}:${process.env.PATH??""}`},a=(0,Ti.spawnSync)(e,fm(r,t),{timeout:15e3,encoding:"utf-8",env:s});if(a.error){let i=a.error.message.includes("ENOENT")?`
487
+ \uD78C\uD2B8: mariadb CLI\uB97C \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4. \uD655\uC778\uD55C \uACBD\uB85C: ${Mi.join(", ")}`:"";throw new Error(`mariadb CLI \uC2E4\uD328: ${a.error.message}${i}
488
+ DB: ${r}
489
+ SQL: ${t.slice(0,200)}`)}if((a.status??1)!==0){let i=a.stderr?.trim()??`mariadb exit ${a.status}`;throw new Error(`MariaDB \uC624\uB958: ${i}
490
+ DB: ${r}
491
+ SQL: ${t.slice(0,200)}`)}return a.stdout?.toString()??""}function Ft(r){let t=r.split(`
492
+ `).filter(n=>n.length>0);if(t.length<1)return[];let e=t[0].split(" ");return t.slice(1).map(n=>{let s=n.split(" "),a={};return e.forEach((i,o)=>{let u=s[o];u===void 0||u==="NULL"?a[i]=null:/^-?\d+$/.test(u)?a[i]=parseInt(u,10):/^-?\d+\.\d+$/.test(u)?a[i]=parseFloat(u):a[i]=u}),a})}function Xl(r){return r.replace(/\\/g,"\\\\").replace(/\0/g,"\\0").replace(/'/g,"''").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\x1a/g,"\\Z")}function Pt(r,t){return!t||t.length===0?r:t.reduce((e,n)=>{if(n==null)return e.replace("?","NULL");if(typeof n=="boolean")return e.replace("?",n?"1":"0");if(typeof n=="number"){if(!isFinite(n)||isNaN(n))throw new Error(`SQL \uD30C\uB77C\uBBF8\uD130 \uC624\uB958: \uC720\uD6A8\uD558\uC9C0 \uC54A\uC740 \uC22B\uC790 (${n})`);return e.replace("?",String(n))}if(Array.isArray(n)){let s=n.map(a=>a==null?"NULL":typeof a=="number"?String(a):typeof a=="boolean"?a?"1":"0":`'${Xl(String(a))}'`);return e.replace("?",s.join(", "))}if(n instanceof Date)return e.replace("?",`'${n.toISOString()}'`);if(typeof n=="object")throw new Error(`SQL \uD30C\uB77C\uBBF8\uD130 \uC624\uB958: \uAC1D\uCCB4\uB294 \uD30C\uB77C\uBBF8\uD130\uB85C \uC0AC\uC6A9 \uBD88\uAC00 (\uBC1B\uC740 \uAC12: ${JSON.stringify(n).slice(0,80)})
493
+ \uD78C\uD2B8: (json-stringify \uAC12) \uC73C\uB85C \uBB38\uC790\uC5F4 \uBCC0\uD658 \uD6C4 \uC0BD\uC785\uD558\uC138\uC694`);return e.replace("?",`'${Xl(String(n))}'`)},r)}var Ql=4*1024*1024,dm=`
494
+ const { workerData } = require('worker_threads');
495
+ const mysql2 = require('mysql2/promise');
496
+ const control = new Int32Array(workerData.controlBuf);
497
+ const data = Buffer.from(workerData.dataBuf);
498
+ const pools = new Map();
499
+
500
+ async function handle(req) {
501
+ if (req.type === 'connect') {
502
+ if (pools.has(req.poolId)) return { ok: true };
503
+ const pool = await mysql2.createPool({
504
+ host: req.config.host || '127.0.0.1',
505
+ port: req.config.port || 3306,
506
+ user: req.config.user || 'root',
507
+ password: req.config.password || '',
508
+ database: req.config.database || '',
509
+ connectionLimit: req.config.poolSize || 5,
510
+ socketPath: req.config.socketPath,
511
+ });
512
+ pools.set(req.poolId, pool);
513
+ return { ok: true };
514
+ }
515
+ if (req.type === 'close') {
516
+ const pool = pools.get(req.poolId);
517
+ if (pool) { await pool.end(); pools.delete(req.poolId); }
518
+ return { ok: true };
519
+ }
520
+ const pool = pools.get(req.poolId);
521
+ if (!pool) return { ok: false, error: 'pool ' + req.poolId + ' not found' };
522
+
523
+ if (req.type === 'query') {
524
+ const [rows] = await pool.query(req.sql, req.params || []);
525
+ return { ok: true, rows: Array.from(rows).map(r => Object.assign({}, r)) };
526
+ }
527
+ if (req.type === 'exec') {
528
+ const [result] = await pool.query(req.sql, req.params || []);
529
+ return { ok: true, affectedRows: result.affectedRows || 0, insertId: result.insertId || 0 };
530
+ }
531
+ if (req.type === 'one') {
532
+ const [rows] = await pool.query(req.sql, req.params || []);
533
+ return { ok: true, row: rows[0] ? Object.assign({}, rows[0]) : null };
534
+ }
535
+ if (req.type === 'transaction') {
536
+ const conn = await pool.getConnection();
537
+ try {
538
+ await conn.beginTransaction();
539
+ const results = [];
540
+ for (const stmt of req.stmts) {
541
+ const [r] = await conn.query(stmt.sql, stmt.params || []);
542
+ results.push({ ok: true, affectedRows: r.affectedRows || 0, insertId: r.insertId || 0 });
543
+ }
544
+ await conn.commit();
545
+ return { ok: true, results };
546
+ } catch (e) {
547
+ await conn.rollback();
548
+ return { ok: false, error: e.message };
549
+ } finally {
550
+ conn.release();
551
+ }
552
+ }
553
+ return { ok: false, error: 'unknown type: ' + req.type };
554
+ }
555
+
556
+ async function loop() {
557
+ while (true) {
558
+ Atomics.wait(control, 0, 0);
559
+ const flag = Atomics.load(control, 0);
560
+ if (flag === -1) break;
561
+ const reqLen = data.readInt32LE(0);
562
+ const reqStr = data.toString('utf8', 4, 4 + reqLen);
563
+ let resp;
564
+ try {
565
+ const req = JSON.parse(reqStr);
566
+ resp = await handle(req);
567
+ } catch(e) {
568
+ resp = { ok: false, error: e.message };
569
+ }
570
+ const respStr = JSON.stringify(resp);
571
+ data.writeInt32LE(respStr.length, 0);
572
+ data.write(respStr, 4, 'utf8');
573
+ Atomics.store(control, 0, 2);
574
+ Atomics.notify(control, 0);
575
+ Atomics.wait(control, 0, 2); // wait for main thread to acknowledge (reset to 0)
576
+ }
577
+ }
578
+ loop().catch(e => {
579
+ console.error('[MariaDB Worker]', e.message);
580
+ Atomics.store(control, 0, -2);
581
+ Atomics.notify(control, 0);
582
+ });
583
+ `,Ds=null,qs=null,Ri=null;function gm(){if(Ds)return;let{Worker:r}=require("worker_threads");qs=new SharedArrayBuffer(4),Ri=new SharedArrayBuffer(Ql),Atomics.store(new Int32Array(qs),0,0),Ds=new r(dm,{eval:!0,workerData:{controlBuf:qs,dataBuf:Ri}}),Ds.on("error",t=>{console.error("[MariaDB Pool Worker Error]",t.message),Ds=null})}function Fe(r){gm();let t=new Int32Array(qs),e=Buffer.from(Ri),n=JSON.stringify(r);if(n.length+4>Ql)throw new Error("MariaDB pool: request too large");if(e.writeInt32LE(n.length,0),e.write(n,4,"utf8"),Atomics.store(t,0,1),Atomics.notify(t,0),Atomics.wait(t,0,1,15e3)==="timed-out")throw new Error("MariaDB pool timeout");let a=e.readInt32LE(0),i=JSON.parse(e.toString("utf8",4,4+a));if(Atomics.store(t,0,0),!i.ok)throw new Error(i.error||"MariaDB pool error");return i}function Zl(){return{mariadb_exec:(r,t,e=[])=>{if(typeof r=="string"&&r.startsWith("pool_")){let n=Fe({type:"exec",poolId:r,sql:t,params:e});return{affectedRows:n.affectedRows,insertId:n.insertId}}return $e(r,Pt(t,e))},mariadb_query:(r,t,e=[])=>typeof r=="string"&&r.startsWith("pool_")?Fe({type:"query",poolId:r,sql:t,params:e}).rows??[]:Ft($e(r,Pt(t,e))),mariadb_one:(r,t,e=[])=>{if(typeof r=="string"&&r.startsWith("pool_"))return Fe({type:"one",poolId:r,sql:t,params:e}).row??null;let s=Ft($e(r,Pt(t,e)))[0];return s??null},db_query_one:(r,t,e=[])=>typeof r=="number"?Fe({type:"one",poolId:r,sql:t,params:e}).row??null:Ft($e(String(r),Pt(t,e)))[0]??null,"db-query-one":(r,t,e=[])=>typeof r=="number"?Fe({type:"one",poolId:r,sql:t,params:e}).row??null:Ft($e(String(r),Pt(t,e)))[0]??null,mariadb_transaction:(r,t)=>{if(!Array.isArray(t)||t.length===0)return{ok:!1,error:"empty statements"};let n=`SET autocommit=0;
584
+ BEGIN;
585
+ `+t.map(s=>Pt(s.sql,s.params??[])).join(`;
586
+ `)+`;
587
+ COMMIT;`;try{return $e(r,n),{ok:!0,count:t.length}}catch(s){try{$e(r,"ROLLBACK")}catch{}return{ok:!1,error:s.message}}},mariadb_batch:(r,t)=>{if(!Array.isArray(t)||t.length===0)return[];if(t.every(n=>n.type==="exec"||!n.type)&&t.length>1){let s=`SET autocommit=0;
588
+ BEGIN;
589
+ `+t.map(a=>Pt(a.sql,a.params??[])).join(`;
590
+ `)+`;
591
+ COMMIT;`;try{return $e(r,s),t.map(()=>({ok:!0}))}catch(a){try{$e(r,"ROLLBACK")}catch{}return t.map(()=>({ok:!1,error:a.message}))}}return t.map(n=>{let s=Pt(n.sql,n.params??[]);try{return n.type==="exec"?{ok:!0,result:$e(r,s)}:n.type==="one"?{ok:!0,result:Ft($e(r,s))[0]??null}:{ok:!0,result:Ft($e(r,s))}}catch(a){return{ok:!1,error:a.message}}})},mariadb_connect:(...r)=>{let t=r[0];typeof t=="string"&&(t={host:r[0]??"localhost",user:r[1]??"",password:r[2]??"",database:r[3]??"",port:typeof r[4]=="number"?r[4]:3306});let e=`pool_${Date.now()}_${Math.random().toString(36).slice(2)}`;return Fe({type:"connect",poolId:e,config:t}),e},"mariadb-connect":(...r)=>{let t=r[0];typeof t=="string"&&(t={host:r[0]??"localhost",user:r[1]??"",password:r[2]??"",database:r[3]??"",port:typeof r[4]=="number"?r[4]:3306});let e=`pool_${Date.now()}_${Math.random().toString(36).slice(2)}`;return Fe({type:"connect",poolId:e,config:t}),e},mariadb_pool_connect:r=>{let t=`pool_${Date.now()}_${Math.random().toString(36).slice(2)}`;return Fe({type:"connect",poolId:t,config:r}),t},mariadb_pool_query:(r,t,e=[])=>Fe({type:"query",poolId:r,sql:t,params:e}).rows??[],mariadb_pool_one:(r,t,e=[])=>Fe({type:"one",poolId:r,sql:t,params:e}).row,mariadb_pool_exec:(r,t,e=[])=>{let n=Fe({type:"exec",poolId:r,sql:t,params:e});return{affectedRows:n.affectedRows,insertId:n.insertId}},mariadb_pool_transaction:(r,t)=>Fe({type:"transaction",poolId:r,stmts:t}),mariadb_pool_close:r=>(Fe({type:"close",poolId:r}),null),mariadb_health:()=>{let r=["-u",process.env.MARIADB_USER||"root","--socket="+Yl(),"ping"];return((0,Ti.spawnSync)("mariadb-admin",r,{timeout:3e3,encoding:"utf-8"}).status??1)===0},mariadb_databases:()=>Ft($e("","SHOW DATABASES")).map(r=>r.Database),mariadb_tables:r=>Ft($e(r,"SHOW TABLES")).map(t=>Object.values(t)[0])}}var eu=require("child_process"),tu=z(require("path"));function Us(){let r=tu.join(__dirname,"_mongodb_helper.js");function t(n){try{let s=i=>{if(i instanceof Map)return Object.fromEntries(i);if(Array.isArray(i))return i.map(s);if(typeof i=="object"&&i!==null){let o={};for(let[u,f]of Object.entries(i))o[u]=s(f);return o}return i},a=(0,eu.execFileSync)("node",[r,JSON.stringify(s(n))],{timeout:n.timeout?n.timeout+2e3:15e3,encoding:"utf-8"});return JSON.parse(a)}catch(s){return{ok:!1,error:s.message||"Helper execution failed"}}}function e(n){if(!n)return{host:"localhost",port:27017};let s=n.indexOf("@");if(s!==-1){let[o,u]=[n.slice(0,s),n.slice(s+1)],f=o.indexOf(":"),l=o.slice(0,f),c=o.slice(f+1),p=u.indexOf("/"),m=p!==-1?u.slice(0,p):u,d=p!==-1?u.slice(p+1):"admin",[g,h]=m.split(":");return{host:g,port:parseInt(h||"27017",10),user:l,pass:c,authDb:d}}let[a,i]=n.split(":");return{host:a,port:parseInt(i||"27017",10)}}return{mongo_connect:(n,s=27017)=>t({method:"ping",host:n,port:s}).ok?`${n}:${s}`:null,mongo_connect_auth:(n,s,a,i,o="admin")=>t({method:"ping",host:n,port:s,user:a,pass:i,authDb:o}).ok?`${a}:${i}@${n}:${s}/${o}`:null,mongo_find_one:(n,s,a,i={})=>{let o=t({method:"find_one",...e(n),db:s,collection:a,filter:i});return o.ok?o.doc??null:null},mongo_find:(n,s,a,i={},o={})=>{let u=t({method:"find_many",...e(n),db:s,collection:a,filter:i,limit:o.limit,skip:o.skip,sort:o.sort,projection:o.projection});return u.ok?u.docs??[]:[]},mongo_count:(n,s,a,i={})=>{let o=t({method:"count",...e(n),db:s,collection:a,filter:i});return o.ok?o.count??0:0},mongo_insert_one:(n,s,a,i)=>{let o=t({method:"insert_one",...e(n),db:s,collection:a,doc:i});return o.ok?o.inserted_id??null:null},mongo_insert_many:(n,s,a,i)=>{let o=t({method:"insert_many",...e(n),db:s,collection:a,docs:i});return o.ok?{count:o.inserted_count,ids:o.inserted_ids}:null},mongo_update_one:(n,s,a,i,o,u={})=>{let f=t({method:"update_one",...e(n),db:s,collection:a,filter:i,update:o,options:u});return f.ok?{matched:f.matched,modified:f.modified}:null},mongo_update_many:(n,s,a,i,o,u={})=>{let f=t({method:"update_many",...e(n),db:s,collection:a,filter:i,update:o,options:u});return f.ok?{matched:f.matched,modified:f.modified}:null},mongo_delete_one:(n,s,a,i)=>{let o=t({method:"delete_one",...e(n),db:s,collection:a,filter:i});return o.ok?o.deleted??0:0},mongo_delete_many:(n,s,a,i)=>{let o=t({method:"delete_many",...e(n),db:s,collection:a,filter:i});return o.ok?o.deleted??0:0},mongo_aggregate:(n,s,a,i)=>{let o=t({method:"aggregate",...e(n),db:s,collection:a,pipeline:i});return o.ok?o.docs??[]:[]},mongo_transaction:(n,s,a)=>t({method:"transaction",...e(n),db:s,ops:a}),mongo_create_index:(n,s,a,i,o={})=>{let u=t({method:"create_index",...e(n),db:s,collection:a,filter:i,options:o});return u.ok?u.name??null:null},mongo_collections:(n,s)=>{let a=t({method:"list_collections",...e(n),db:s});return a.ok?a.collections??[]:[]},mongodb_connect:(n,s=27017)=>t({method:"ping",host:n,port:s}).ok?`${n}:${s}`:null,mongodb_close:n=>!0,mongodb_is_connected:n=>{let{host:s,port:a}=e(n);return t({method:"ping",host:s,port:a,timeout:1e3}).ok===!0}}}function nu(r){return{async_call:(t,e=[])=>new ae((n,s)=>{setImmediate(()=>{try{let a=r(t,e);n(a)}catch(a){s(new Error(`async_call error: ${a.message}`))}})}),await_result:t=>{let e=t.getState();if(e==="resolved")return t.getValue();throw e==="rejected"?t.getError()||new Error("Promise rejected"):new Error("Promise still pending - use proper async handling")},promise_all:t=>new ae((e,n)=>{if(!Array.isArray(t)||t.length===0){e([]);return}let s=[],a=0;t.forEach((i,o)=>{if(!(i instanceof ae)){n(new Error(`promise_all: element ${o} is not a promise`));return}let u=i.getState();u==="resolved"?(s[o]=i.getValue(),a++,a===t.length&&e(s)):n(u==="rejected"?i.getError()||new Error(`promise_all: promise ${o} rejected`):new Error(`promise_all: promise ${o} still pending`))})}),promise_race:t=>new ae((e,n)=>{if(!Array.isArray(t)||t.length===0){n(new Error("promise_race: empty promise array"));return}for(let s=0;s<t.length;s++){let a=t[s];if(!(a instanceof ae)){n(new Error(`promise_race: element ${s} is not a promise`));return}let i=a.getState();if(i==="resolved"){e(a.getValue());return}else if(i==="rejected"){n(a.getError()||new Error(`promise_race: promise ${s} rejected`));return}}n(new Error("promise_race: all promises still pending"))}),promise_delay:t=>new ae(e=>{setTimeout(()=>e(null),t)}),promise_timeout:(t,e,n=[])=>new ae((s,a)=>{let i=!1,o=setTimeout(()=>{i||(i=!0,a(new Error(`promise_timeout: timed out after ${t}ms`)))},t);try{let u=r(e,n);i=!0,clearTimeout(o),s(u)}catch(u){i=!0,clearTimeout(o),a(new Error(`promise_timeout: ${u.message}`))}}),promise_resolve:t=>Wo(t),promise_reject:t=>{let e=t instanceof Error?t:new Error(String(t));return $a(e)},promise_state:t=>t instanceof ae?t.getState():"unknown",promise_then:(t,e)=>t instanceof ae?t.then(n=>{try{return r(e,[n])}catch(s){throw new Error(`promise_then handler error: ${s.message}`)}}):$a(new Error("promise_then: first arg is not a promise"))}}var hm=0;function ym(){return`ch_${++hm}_${Date.now()}`}var Ci=class{constructor(t=100){this.queue=[];this.maxSize=t}send(t){return this.queue.length>=this.maxSize?!1:(this.queue.push(t),!0)}recv(){return this.queue.shift()??null}size(){return this.queue.length}isEmpty(){return this.queue.length===0}isFull(){return this.queue.length>=this.maxSize}},Qt=new Map;function ru(){return{chan:r=>{let t=ym();return Qt.set(t,new Ci(typeof r=="number"?r:100)),t},"chan-send":(r,t)=>{let e=Qt.get(r);return e?e.send(t):!1},"chan-recv":r=>{let t=Qt.get(r);return t?t.recv():null},"chan-size":r=>{let t=Qt.get(r);return t?t.size():0},"chan-empty?":r=>{let t=Qt.get(r);return t?t.isEmpty():!0},"chan-full?":r=>{let t=Qt.get(r);return t?t.isFull():!0},"chan-close":r=>Qt.delete(r)}}function Vs(r){return typeof r=="string"&&r.startsWith(":")?r.slice(1):r}function su(){return{"imm-map":r=>{if(!r||typeof r!="object"||Array.isArray(r))return Object.freeze({});let t={};for(let e of Object.keys(r))t[Vs(e)]=r[e];return Object.freeze(t)},"imm-assoc":(r,t,e)=>{let n=r&&typeof r=="object"&&!Array.isArray(r)?r:{};return Object.freeze({...n,[Vs(t)]:e})},"imm-dissoc":(r,t)=>{if(!r||typeof r!="object")return Object.freeze({});let e=Vs(t),{[e]:n,...s}=r;return Object.freeze(s)},"imm-get":(r,t,e)=>{if(!r||typeof r!="object")return e??null;let n=Vs(t),s=r[n];return s!==void 0?s:e??null},"imm-keys":r=>!r||typeof r!="object"||Array.isArray(r)?Object.freeze([]):Object.freeze(Object.keys(r)),"imm-vals":r=>!r||typeof r!="object"||Array.isArray(r)?Object.freeze([]):Object.freeze(Object.values(r)),"imm-merge":(r,t)=>{let e=r&&typeof r=="object"&&!Array.isArray(r)?r:{},n=t&&typeof t=="object"&&!Array.isArray(t)?t:{};return Object.freeze({...e,...n})},"imm-vec":r=>Array.isArray(r)?Object.freeze([...r]):Object.freeze([]),"imm-conj":(r,t)=>Array.isArray(r)?Object.freeze([...r,t]):Object.freeze([t]),"imm-nth":(r,t)=>{if(!Array.isArray(r))return null;let e=r[t];return e!==void 0?e:null},"imm-slice":(r,t,e)=>Array.isArray(r)?Object.freeze(r.slice(t,e)):Object.freeze([]),"imm-update":(r,t,e)=>{if(!Array.isArray(r))return Object.freeze([]);let n=[...r];return n[t]=e,Object.freeze(n)},"imm-pop":r=>!Array.isArray(r)||r.length===0?Object.freeze([]):Object.freeze(r.slice(0,-1)),"imm-count":r=>Array.isArray(r)?r.length:r&&typeof r=="object"?Object.keys(r).length:0,"imm?":r=>Object.isFrozen(r),"imm-empty?":r=>Array.isArray(r)?r.length===0:r&&typeof r=="object"?Object.keys(r).length===0:!0,"imm-into":(r,t)=>{if(Array.isArray(r)){let s=Array.isArray(t)?t:t&&typeof t=="object"?Object.values(t):[];return Object.freeze([...r,...s])}let e=r&&typeof r=="object"?r:{},n=t&&typeof t=="object"&&!Array.isArray(t)?t:{};return Object.freeze({...e,...n})}}}var Fr=r=>{if(r instanceof Map)return Object.fromEntries(r);if(Array.isArray(r))return r.map(Fr);if(typeof r=="object"&&r!==null){let t={};for(let[e,n]of Object.entries(r))t[e]=Fr(n);return t}return r};function au(){return{"ai-call":async(r,t)=>{let e=process.env.ANTHROPIC_API_KEY,n=process.env.OPENAI_API_KEY,s=e||n,a=typeof t=="string"?t:String(typeof t=="object"&&t!==null?t.prompt||JSON.stringify(t):t);if(!s)return`[AI Mock Response] Model: ${r}, Prompt: ${a.slice(0,50)}...`;if(e&&(r.startsWith("claude")||r.startsWith("anthropic")))try{let i=typeof t=="object"&&t!==null&&t.context?`
592
+
593
+ Context:
594
+ ${JSON.stringify(t.context)}`:"",o=typeof t=="object"&&t!==null?Number(t["max-tokens"]||t.maxTokens||1024):1024,u=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"Content-Type":"application/json","x-api-key":e,"anthropic-version":"2023-06-01"},body:JSON.stringify(Fr({model:r==="claude-3"?"claude-3-haiku-20240307":r,max_tokens:o,messages:[{role:"user",content:a+i}]}))});if(u.ok)return(await u.json())?.content?.[0]?.text??"[AI: empty response]"}catch(i){return`[AI Error] ${String(i)}`}if(n&&(r.startsWith("gpt")||r.startsWith("openai")))try{let i=await fetch("https://api.openai.com/v1/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify(Fr({model:r==="gpt-4"?"gpt-4-turbo-preview":r,messages:[{role:"user",content:a}]}))});if(i.ok)return(await i.json())?.choices?.[0]?.message?.content??"[AI: empty response]"}catch(i){return`[AI Error] ${String(i)}`}return`[AI Mock Response] Model: ${r}, Prompt: ${a.slice(0,50)}...`},"rag-search":(r,t)=>{let e=t?.kb??t?.kb??"default",n=Number(t?.limit??t?.limit??5);return[{content:`Mock RAG result for: ${r}`,score:.95,source:String(e)},{content:`Related: ${r} \u2014 context from ${e}`,score:.82,source:String(e)},{content:`Additional info about ${r}`,score:.74,source:String(e)},{content:`Background: ${r} overview`,score:.61,source:String(e)},{content:`Reference: ${r} documentation`,score:.53,source:String(e)}].slice(0,n)},embed:async r=>{let t=process.env.FREELANG_GPT_PORT??"30113";try{let e=await fetch(`http://localhost:${t}/api/embed`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Fr({text:r})),signal:AbortSignal.timeout?AbortSignal.timeout(3e3):void 0});if(e.ok){let n=await e.json();if(Array.isArray(n?.embedding))return n.embedding}}catch{}return Array.from({length:10},(e,n)=>Math.sin((r.charCodeAt(n%r.length)+n*7)*.1))},similarity:(r,t)=>{if(!Array.isArray(r)||!Array.isArray(t))return 0;let e=Math.min(r.length,t.length);if(e===0)return 0;let n=0,s=0,a=0;for(let o=0;o<e;o++)n+=r[o]*t[o],s+=r[o]**2,a+=t[o]**2;let i=Math.sqrt(s)*Math.sqrt(a);return i===0?0:n/i},"chunk-text":(r,t=512,e=50)=>{if(typeof r!="string"||r.length===0)return[];let n=Math.max(1,t-e),s=[];for(let a=0;a<r.length&&(s.push(r.slice(a,a+t)),!(a+t>=r.length));a+=n);return s},"prompt-template":(r,t)=>typeof r!="string"?String(r):r.replace(/\{(\w+)\}/g,(e,n)=>String(t?.[n]??""))}}var Me=z(require("fs")),Ie=z(require("path"));be();ke();function iu(){return`
595
+ // \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
596
+ // FreeLang v11 Runtime Helpers (Enhanced 2026-04-30)
597
+ // \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
598
+
599
+ // \u2500 \uC0B0\uC220 \uBC0F \uB17C\uB9AC \uC5F0\uC0B0\uC790 (stdlib) \u2500
600
+ function _plus(...args) { if (args.length === 0) return 0; if (args.length === 1) return args[0]; return args.reduce((a, b) => a + b); }
601
+ function _minus(...args) { if (args.length === 0) return 0; if (args.length === 1) return -args[0]; return args.reduce((a, b) => a - b); }
602
+ function _star(...args) { if (args.length === 0) return 1; if (args.length === 1) return args[0]; return args.reduce((a, b) => a * b); }
603
+ function _slash(...args) { if (args.length === 0) return 1; if (args.length === 1) return 1/args[0]; return args.reduce((a, b) => a / b); }
604
+ function _gt(a, b) { return a > b; }
605
+ function _lt(a, b) { return a < b; }
606
+ function _eq(a, b) { return a === b; }
607
+ function _gt_eq(a, b) { return a >= b; }
608
+ function _lt_eq(a, b) { return a <= b; }
609
+ function _not(a) { return !a; }
610
+ function _and(...args) { for(let a of args) if(!a) return false; return args.length > 0 ? args[args.length-1] : true; }
611
+ function _or(...args) { for(let a of args) if(a) return a; return false; }
612
+ function _concat(...args) {
613
+ if (args.length === 0) return "";
614
+ if (Array.isArray(args[0])) return [].concat(...args);
615
+ return args.join("");
616
+ }
617
+
618
+ // \u2500 \uD0C0\uC785 \uCCB4\uD06C \u2500
619
+ function _fl_null_q(v) { return v === null || v === undefined; }
620
+ function _fl_true_q(v) { return v === true; }
621
+ function _fl_false_q(v) { return v === false; }
622
+ function _fl_number_q(v) { return typeof v === 'number'; }
623
+ function _fl_string_q(v) { return typeof v === 'string'; }
624
+ function _fl_list_q(v) { return Array.isArray(v); }
625
+ function _fl_array_q(v) { return Array.isArray(v); }
626
+ function _fl_map_q(v) { return v !== null && typeof v === 'object' && !Array.isArray(v); }
627
+ function _fl_fn_q(v) { return typeof v === 'function'; }
628
+
629
+ // \u2500 \uB370\uC774\uD130 \uC811\uADFC \uBC0F \uC870\uC791 \u2500
630
+ function _fl_length(v) { if(v==null) return 0; return v.length !== undefined ? v.length : 0; }
631
+ function _fl_get(obj, key, dflt) {
632
+ if (obj === null || obj === undefined) return dflt || null;
633
+ if (obj instanceof Map) return obj.has(key) ? obj.get(key) : (dflt || null);
634
+
635
+ let k = (typeof key === "object" && key !== null) ? (key.name || key.value || String(key)) : String(key);
636
+ if (k.startsWith(":")) k = k.slice(1);
637
+
638
+ if (Array.isArray(obj)) {
639
+ if (typeof key === "number") return obj[key] !== undefined ? obj[key] : (dflt || null);
640
+ if (k === "length") return obj.length;
641
+ let idx = parseInt(k);
642
+ if (!isNaN(idx)) return obj[idx] !== undefined ? obj[idx] : (dflt || null);
643
+ }
644
+
645
+ if (typeof obj === "object") {
646
+ if (obj[k] !== undefined) return obj[k];
647
+ if (obj[":" + k] !== undefined) return obj[":" + k];
648
+ }
649
+ return dflt || null;
650
+ }
651
+ function _fl_first(l) { return (l && l.length > 0) ? l[0] : null; }
652
+ function _fl_last(l) { return (l && l.length > 0) ? l[l.length - 1] : null; }
653
+ function _fl_rest(l) { return (l && l.length > 0) ? l.slice(1) : []; }
654
+ function _fl_append(l, x) { return [...(l || []), x]; }
655
+ function _fl_concat(a, b) { return Array.isArray(a) && Array.isArray(b) ? [...a, ...b] : String(a || "") + String(b || ""); }
656
+ function _fl_keys(o) { return o ? Object.keys(o) : []; }
657
+ function _fl_values(o) { return o ? Object.values(o) : []; }
658
+ var _fl_entries = (o) => o ? Object.entries(o).map(([k,v]) => [k,v]) : [];
659
+ function _fl_map_set(o, ...args) { const result = {...(o || {})}; for (let i = 0; i + 1 < args.length; i += 2) { result[args[i]] = args[i + 1]; } return result; }
660
+ function _fl_has_key_q(o, k) { return o ? (String(k) in o) : false; }
661
+
662
+ // \u2500 \uBB38\uC790\uC5F4 \uC870\uC791 \u2500
663
+ function _fl_str(...xs) { return xs.map(x => x === null || x === undefined ? "" : (typeof x === "object" ? JSON.stringify(x) : String(x))).join(""); }
664
+ function _fl_char_at(s, i) { return (s && s[i]) || null; }
665
+ function _fl_substring(s, a, b) { return s ? (b === undefined ? s.slice(a) : s.slice(a, b)) : ""; }
666
+ function _fl_lower(s) { return String(s || "").toLowerCase(); }
667
+ function _fl_upper(s) { return String(s || "").toUpperCase(); }
668
+ function _fl_trim(s) { return String(s || "").trim(); }
669
+ function _fl_replace(s, a, b) { return String(s || "").split(a).join(b); }
670
+ function _fl_str_index_of(s, sub) { return (s || "").indexOf(sub); }
671
+ function _fl_contains_q(s, sub) { return (s || "").includes(sub); }
672
+ function _fl_str_to_num(s) { const n = Number(s); return isNaN(n) ? null : n; }
673
+ function _fl_join(arr, sep) { return (arr || []).join(sep !== undefined ? sep : ""); }
674
+ function _fl_split(s, sep) { return (s || "").split(sep !== undefined ? sep : ""); }
675
+ function _fl_repeat(s, n) { return (s || "").repeat(n || 0); }
676
+ function _fl_range(a, b, s) { let r = []; let start = b === undefined ? 0 : a; let end = b === undefined ? a : b; let step = s || 1; if (step > 0) { for (let i = start; i < end; i += step) r.push(i); } else { for (let i = start; i > end; i += step) r.push(i); } return r; }
677
+
678
+ // \u2500 \uACE0\uCC28 \uD568\uC218 (Null-safe & Spread) \u2500
679
+ function _fl_map(arr, fn) { return (arr || []).map(x => fn(x)); }
680
+ function _fl_filter(arr, fn) { return (arr || []).filter(x => { const r = fn(x); return r !== false && r !== null; }); }
681
+ function _fl_reduce(arr, fn, init) { return (arr || []).reduce((a, x) => fn(a, x), init); }
682
+
683
+ // \u2500 \uB370\uC774\uD130 \uC811\uADFC \uBC0F \uC870\uC791 \uBCF4\uC870 \u2500
684
+ function _fl_slice(l, a, b) { return (l || []).slice(a, b); }
685
+
686
+ // \u2500 \uC2DC\uC2A4\uD15C \uBC0F I/O \u2500
687
+ function _fl_print(v) { console.log(v); return v; }
688
+ function _fl_get_argv() { return (typeof process !== "undefined" ? process.argv.slice(2) : []); }
689
+ function _fl_file_read(p) { return require("fs").readFileSync(p, "utf8"); }
690
+ function _fl_file_write(p, c) { return require("fs").writeFileSync(p, c); }
691
+ function _fl_file_exists(p) { return require("fs").existsSync(p); }
692
+ function _fl_file_delete(p) { try { require("fs").unlinkSync(p); } catch(e) {} }
693
+ function _fl_file_append(p, c) { require("fs").appendFileSync(p, String(c)); }
694
+ function _fl_file_copy(s, d) { require("fs").copyFileSync(s, d); }
695
+ function _fl_file_rename(o, n) { require("fs").renameSync(o, n); }
696
+ function _fl_file_size(p) { try { return require("fs").statSync(p).size; } catch(e) { return 0; } }
697
+ function _fl_file_modified(p) { try { return require("fs").statSync(p).mtimeMs; } catch(e) { return 0; } }
698
+ function _fl_file_mkdir(p) { try { require("fs").mkdirSync(p, { recursive: true }); } catch(e) {} }
699
+ function _fl_file_rmdir(p) { try { require("fs").rmSync(p, { recursive: true, force: true }); } catch(e) {} }
700
+ function _fl_file_list(p) { try { return require("fs").readdirSync(p); } catch(e) { return []; } }
701
+ function _fl_process_run(cmd) { try { const {execSync}=require("child_process"); return execSync(cmd,{encoding:"utf8"}); } catch(e) { return ""; } }
702
+ function _fl_process_run_args(cmd, args) { try { const {execSync}=require("child_process"); return execSync(cmd+" "+(args||[]).join(" "),{encoding:"utf8"}); } catch(e) { return ""; } }
703
+ function _fl_process_exec(cmd) { try { const {execSync}=require("child_process"); return execSync(cmd,{encoding:"utf8"}); } catch(e) { return ""; } }
704
+ function _fl_process_exec_args(cmd, args) { try { const {execSync}=require("child_process"); return execSync(cmd+" "+(args||[]).join(" "),{encoding:"utf8"}); } catch(e) { return ""; } }
705
+ function _fl_process_spawn(cmd, args) { try { const {spawnSync}=require("child_process"); const r=spawnSync(cmd,args||[],{encoding:"utf8"}); return r.stdout||""; } catch(e) { return ""; } }
706
+ function _fl_run_inherit(cmd) { require("child_process").spawnSync(cmd,{shell:true,stdio:"inherit"}); }
707
+ function _fl_process_kill(pid) { try { process.kill(pid); } catch(e) {} }
708
+ function _fl_process_wait(pid) { return null; }
709
+ function _fl_env_get(k) { return process.env[k] || null; }
710
+ function _fl_env_set(k, v) { process.env[k] = String(v); }
711
+ function _fl_env_all() { return process.env; }
712
+ function _fl_file_is_file(p) { try { return require("fs").statSync(p).isFile(); } catch(e) { return false; } }
713
+ function _fl_file_is_dir(p) { try { return require("fs").statSync(p).isDirectory(); } catch(e) { return false; } }
714
+ function _fl_process_exists(pid) { try { process.kill(pid, 0); return true; } catch(e) { return false; } }
715
+ function _fl_process_getcwd() { return process.cwd(); }
716
+ function _fl_process_chdir(p) { try { process.chdir(p); } catch(e) {} }
717
+ function _fl_process_pid() { return process.pid; }
718
+ function _fl_process_ppid() { return process.ppid || null; }
719
+ function _fl_readline(prompt) {
720
+ if (prompt) process.stdout.write(prompt);
721
+ try {
722
+ const fs = require("fs");
723
+ const parts = [];
724
+ const b = Buffer.alloc(1);
725
+ while (true) {
726
+ const n = fs.readSync(process.stdin.fd, b, 0, 1);
727
+ if (n === 0) return parts.length === 0 ? null : parts.join("");
728
+ const c = b[0];
729
+ if (c === 10) break;
730
+ if (c !== 13) parts.push(String.fromCharCode(c));
731
+ }
732
+ return parts.join("");
733
+ } catch(e) { return null; }
734
+ }
735
+ function _fl_shell_capture(cmd) {
736
+ try {
737
+ const {execSync} = require("child_process");
738
+ return {stdout: execSync(cmd, {encoding: "utf8"}), stderr: "", code: 0, ok: true};
739
+ } catch(e) {
740
+ return {stdout: "", stderr: String(e), code: 1, ok: false};
741
+ }
742
+ }
743
+
744
+ // \u2500 \uD0C0\uC785 \u2500
745
+ function _fl_type_of(v) { if (v === null || v === undefined) return "nil"; if (Array.isArray(v)) return "list"; return typeof v; }
746
+
747
+ // \u2500 \uAE30\uD0C0 \u2500
748
+ function _while(condFn, bodyFn) { while(condFn()) { bodyFn(); } }
749
+
750
+ // \u2500 \uC2DC\uAC04 \u2500
751
+ const now_ms = () => Date.now();
752
+ const now_iso = () => new Date().toISOString();
753
+ const now_unix = () => Math.floor(Date.now() / 1000);
754
+
755
+ // \u2500 \uC178 \uC2E4\uD589 \u2500
756
+ const shell_exec = (cmd, inp) => { try { const {execSync} = require("child_process"); const opts = {encoding: "utf8"}; if (inp) opts["input"] = inp; return execSync(cmd, opts); } catch(e) { return ""; } };
757
+
758
+ // \u2500 \uC218\uD559 \u2500
759
+ var math_sqrt = (n) => Math.sqrt(n);
760
+ var math_pow = (a, b) => Math.pow(a, b);
761
+ var math_pi = Math.PI;
762
+ var round = (n) => Math.round(n);
763
+ var floor = (n) => Math.floor(n);
764
+ var ceil = (n) => Math.ceil(n);
765
+ var abs = (n) => Math.abs(n);
766
+ var min = (...args) => Math.min(...args);
767
+ var max = (...args) => Math.max(...args);
768
+
769
+ // \u2500 \uCEEC\uB809\uC158 \uD655\uC7A5 \u2500
770
+ function _fl_take(n, arr) { return (arr || []).slice(0, n); }
771
+ function _fl_drop(n, arr) { return (arr || []).slice(n); }
772
+ function _fl_zip(a, b) { const r = []; const l = Math.min((a || []).length, (b || []).length); for (let i = 0; i < l; i++) r.push([a[i], b[i]]); return r; }
773
+ function _fl_flatten(arr) { return (arr || []).flat(); }
774
+ function _fl_reverse(arr) { return Array.isArray(arr) ? [...arr].reverse() : arr; }
775
+ function _fl_sort(arr, fn) { return fn ? [...(arr || [])].sort((a, b) => fn(a, b) ? -1 : 1) : [...(arr || [])].sort(); }
776
+
777
+ // \u2500 \uBB38\uC790\uC5F4 \uACF5\uAC1C \uBCC4\uCE6D \u2500
778
+ var str_upper = (s) => String(s || "").toUpperCase();
779
+ var str_lower = (s) => String(s || "").toLowerCase();
780
+ var str_contains = (s, sub) => String(s || "").includes(String(sub || ""));
781
+ var str_replace = (s, a, b) => { if (s == null) return ""; return String(s).split(String(a || "")).join(String(b || "")); };
782
+ var str_starts_with = (s, p) => String(s || "").startsWith(String(p || ""));
783
+ var str_ends_with = (s, sf) => String(s || "").endsWith(String(sf || ""));
784
+ var str_trim = (s) => String(s || "").trim();
785
+ var str_length = (s) => String(s || "").length;
786
+ var str_split = (s, sep) => String(s || "").split(sep);
787
+
788
+ // \u2500 \uD0C0\uC785 \uD655\uC7A5 \u2500
789
+ var list_q = (v) => Array.isArray(v);
790
+ var map_q = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
791
+ var fn_q = (v) => typeof v === "function";
792
+
793
+ // \u2500 IIFE \uD3F4\uBC31 \u2500
794
+ var unknown = (...a) => a[a.length - 1];
795
+
796
+ // \u2500 \uAE00\uB85C\uBC8C \uBC14\uC778\uB529 \u2500
797
+ let __argv__ = _fl_get_argv();
798
+
799
+ // \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
800
+ `.trim()}var bm=["_plus","_minus","_star","_slash","_gt","_lt","_eq","_gt_eq","_lt_eq","_not","_and","_or","_concat","_fl_null_q","_fl_true_q","_fl_false_q","_fl_number_q","_fl_string_q","_fl_list_q","_fl_array_q","_fl_map_q","_fl_fn_q","_fl_length","_fl_get","_fl_first","_fl_last","_fl_rest","_fl_append","_fl_concat","_fl_keys","_fl_values","_fl_entries","_fl_map_set","_fl_has_key_q","_fl_str","_fl_char_at","_fl_substring","_fl_lower","_fl_upper","_fl_trim","_fl_replace","_fl_str_index_of","_fl_contains_q","_fl_str_to_num","_fl_join","_fl_split","_fl_repeat","_fl_range","_fl_map","_fl_filter","_fl_reduce","_fl_slice","_fl_print","_fl_get_argv","_fl_file_read","_fl_file_write","_fl_file_exists","_fl_shell_capture","_fl_take","_fl_drop","_fl_zip","_fl_flatten","_fl_reverse","_fl_sort"],E1=bm.length;var ou={module:"commonjs",runtime:!1,minify:!1,target:"node"},km=`
801
+ function _fl_map(arr, fn) { return (arr || []).map(fn); }
802
+ function _fl_filter(arr, fn) { return (arr || []).filter(fn); }
803
+ function _fl_reduce(arr, fn, init) { return (arr || []).reduce(fn, init); }
804
+ function _fl_print(v) { console.log(v); return v; }
805
+ `.trim();var cu={"null?":"_fl_null_q","nil?":"_fl_null_q","cli-args":"_fl_get_argv",file_read:"_fl_file_read","file-read":"_fl_file_read",file_write:"_fl_file_write","file-write":"_fl_file_write","file-exists":"_fl_file_exists",file_exists:"_fl_file_exists",readline:"_fl_readline","read-line":"_fl_readline",char_at:"_fl_char_at","char-at":"_fl_char_at",substring:"_fl_substring","str-slice":"_fl_substring","true?":"_fl_true_q","false?":"_fl_false_q","string?":"_fl_string_q","number?":"_fl_number_q","list?":"_fl_list_q","array?":"_fl_array_q","map?":"_fl_map_q","fn?":"_fl_fn_q","boolean?":"_fl_boolean_q","type-of":"_fl_type_of","empty?":"_fl_empty_q","is-digit?":"_fl_is_digit_q","is-alpha?":"_fl_is_alpha_q","is-alnum?":"_fl_is_alnum_q","is-space?":"_fl_is_space_q","is-symbol-char?":"_fl_is_symbol_char_q",map:"_fl_map",filter:"_fl_filter",reduce:"_fl_reduce",first:"_fl_first",last:"_fl_last",rest:"_fl_rest",append:"_fl_append",concat:"_fl_concat",slice:"_fl_slice",take:"_fl_take",drop:"_fl_drop",zip:"_fl_zip",flatten:"_fl_flatten",reverse:"_fl_reverse",sort:"_fl_sort",length:"_fl_length",range:"_fl_range",str:"_fl_str","contains?":"_fl_contains_q","str-contains":"_fl_contains_q","str-includes":"_fl_contains_q","str-to-num":"_fl_str_to_num","parse-num":"_fl_str_to_num",assoc:"_fl_map_set",upper:"_fl_upper","str-upper":"_fl_upper",lower:"_fl_lower","str-lower":"_fl_lower",trim:"_fl_trim",replace:"_fl_replace","str-replace":"_fl_replace","str-index-of":"_fl_str_index_of",str_index_of:"_fl_str_index_of",join:"_fl_join","str-join":"_fl_join",split:"_fl_split","str-split":"_fl_split",repeat:"_fl_repeat","str-repeat":"_fl_repeat",get:"_fl_get","json-parse":"JSON.parse","json-stringify":"JSON.stringify",json_parse:"JSON.parse",json_stringify:"JSON.stringify",keys:"_fl_keys",json_keys:"_fl_keys",values:"_fl_values","map-keys":"_fl_keys","map-values":"_fl_values","map-set":"_fl_map_set","json-set":"_fl_map_set",json_set:"_fl_map_set","has-key?":"_fl_has_key_q"},vm=new Set(["abstract","arguments","await","boolean","break","byte","case","catch","char","class","const","continue","debugger","default","delete","do","double","else","enum","eval","export","extends","false","final","finally","float","for","function","goto","if","implements","import","in","instanceof","int","interface","let","long","native","new","null","package","private","protected","public","return","short","static","super","switch","synchronized","this","throw","throws","transient","true","try","typeof","var","void","volatile","while","with","yield"]);function Ee(r){if(cu[r])return cu[r];let e=r.replace(/^\$/,"").replace(/\?$/g,"_q").replace(/!/g,"_bang").replace(/>/g,"_gt").replace(/</g,"_lt").replace(/=/g,"_eq").replace(/\+/g,"_plus").replace(/\*/g,"_star").replace(/\//g,"_slash").replace(/-/g,"_");return vm.has(e)?`_${e}`:e}var Zt=class{constructor(){this.exportedNames=[];this.opts={...ou}}generate(t,e){this.opts={...ou,...e},this.exportedNames=[];let n=[];n.push(iu()),n.push(""),this.opts.runtime&&(n.push(km),n.push(""));let s=[];for(let i of t){let o=this.genNode(i);o!==""&&s.push(o.endsWith(";")?o:o+";")}if(n.push(...s),this.exportedNames.length>0){if(this.opts.module==="commonjs"){let i=this.exportedNames.map(o=>` ${o}: ${o}`).join(`,
806
+ `);n.push(`module.exports = {
807
+ ${i}
808
+ };`)}else if(this.opts.module==="esm"){let i=this.exportedNames.join(", ");n.push(`export { ${i} };`)}}else if(this.opts.module==="commonjs"&&s.some(i=>i.startsWith("function "))){let i=s.filter(o=>o.startsWith("function ")).map(o=>{let u=o.match(/^function\s+(\w+)/);return u?u[1]:null}).filter(Boolean);if(i.length>0){let o=i.map(u=>` ${u}: ${u}`).join(`,
809
+ `);n.push(`module.exports = {
810
+ ${o}
811
+ };`)}}let a=n.join(`
812
+ `);return this.opts.minify?this.minify(a):a}genNode(t){switch(t.kind){case"literal":return this.genLiteral(t);case"template-string":return this.genTemplateString(t);case"variable":return this.genVariable(t);case"sexpr":return this.genSExpr(t);case"block":return this.genBlock(t);case"keyword":return this.genKeyword(t);case"try-block":return this.genTryBlock(t);default:return`/* unsupported: ${t.kind} */`}}genLiteral(t){if(t.type==="string")return JSON.stringify(t.value);if(t.type==="boolean")return t.value?"true":"false";if(t.type==="null")return"null";if(t.type==="symbol"){if(t.value==="nil"||t.value==="null")return"null";let e=String(t.value).replace(/^\$/,"");return Ee(e)}else return String(t.value)}genTemplateString(t){let e=t.value,n="`",s=0;for(;s<e.length;){if(e[s]==="$"&&e[s+1]==="{"){let a=s+2,i=e.indexOf("}",a);if(i>a){let o=e.slice(a,i).trim(),u=this.genNode({kind:"variable",name:o});n+="${"+u+"}",s=i+1;continue}}e[s]==="`"?n+="\\`":e[s]==="\\"?n+="\\\\":n+=e[s],s++}return n+="`",n}genVariable(t){let e=t.name.replace(/^\$/,"");return Ee(e)}genKeyword(t){return JSON.stringify(t.name)}genSExpr(t){let{op:e,args:n}=t;if(e==="and")return n.length===0?"true":"("+n.map(a=>this.genNode(a)).join(" && ")+")";if(e==="or")return n.length===0?"false":"("+n.map(a=>this.genNode(a)).join(" || ")+")";if(e==="cond")return this.genCond(n);if(e==="while")return this.genWhile(n);if(e==="->"){if(n.length===0)return"null";let a=this.genNode(n[0]);for(let i=1;i<n.length;i++){let o=n[i];if(o.kind==="sexpr"){let{op:u,args:f}=o,l=Ee(u),c=f.map(p=>this.genNode(p));a=`${l}(${[a,...c].join(", ")})`}else a=`${this.genNode(o)}(${a})`}return a}if(e==="->>"){if(n.length===0)return"null";let a=this.genNode(n[0]);for(let i=1;i<n.length;i++){let o=n[i];if(o.kind==="sexpr"){let{op:u,args:f}=o,l=Ee(u),c=f.map(p=>this.genNode(p));a=`${l}(${[...c,a].join(", ")})`}else a=`${this.genNode(o)}(${a})`}return a}if(e==="recur")return`{ __recur: true, a: [${n.map(i=>this.genNode(i)).join(", ")}] }`;if(e==="loop"){let a=n[0],i=n.slice(1),o=[];a.kind==="block"&&a.type==="Array"&&(o=a.fields.get("items")||[]);let u=[],f=[];for(let p=0;p<o.length;p+=2){let m=o[p],d=o[p+1];if(!m)continue;let g=this.extractVarName(m),h=d?this.genNode(d):"null";u.push(`let ${g} = ${h};`),f.push(g)}let l=i.map(p=>this.genNode(p).trim()).filter(p=>p!==""),c="";return l.length===0?c="return null;":l.length===1?c=`return ${l[0]};`:c=`${l.slice(0,-1).map(m=>m.endsWith(";")?m:m+";").join(" ")} return ${l[l.length-1]};`,`((() => { ${u.join(" ")} while (true) { const __r = (() => { ${c} })(); if (__r && __r.__recur) { [${f.join(", ")}] = __r.a; continue; } return __r; } })())`}if(e==="let"){if(n.length>=2){let a=n[0],i=[];a.kind==="block"&&a.type==="Array"?i=a.fields.get("items")||[]:a.kind==="sexpr"&&(i=a.args);let o=[];if(i.length>0&&i[0].kind==="block"&&i[0].type==="Array"){for(let c of i)if(c.kind==="block"&&c.type==="Array"){let p=c.fields.get("items")||[];if(p.length>=2){let m=this.extractVarName(p[0]),d=this.genNode(p[1]);o.push(`let ${m} = ${d};`)}}}else for(let c=0;c<i.length;c+=2){if(!i[c])continue;let p=this.extractVarName(i[c]),m=i[c+1]?this.genNode(i[c+1]):"null";o.push(`let ${p} = ${m};`)}let f=n.slice(1).map(c=>this.genNode(c).trim()).filter(c=>c!==""),l="";return f.length===0?l="return null;":f.length===1?l=`return ${f[0]};`:l=`${f.slice(0,-1).map(p=>p.endsWith(";")?p:p+";").join(" ")} return ${f[f.length-1]};`,`((() => { ${o.join(" ")} ${l} })())`}return"(() => null)()"}if(e==="do")return this.genDo(n);let s={"+":"+","-":"-","*":"*","/":"/","%":"%","<":"<",">":">","<=":"<=",">=":">=","==":"===","!=":"!==","=":"==="};if(e in s&&n.length===2){let a=this.genNode(n[0]),i=this.genNode(n[1]);return`(${a} ${s[e]} ${i})`}if(e==="-"&&n.length===1)return`(-${this.genNode(n[0])})`;if(e==="not"&&n.length===1)return`(!${this.genNode(n[0])})`;if(e==="if"){let a=this.genNode(n[0]),i=this.genNode(n[1]),o=n[2]?this.genNode(n[2]):"undefined";return`(${a} ? ${i} : ${o})`}if(e==="define"){let a=this.extractVarName(n[0]),i=this.genNode(n[1]);return`const ${a} = ${i};`}if(e==="set!"){let a=this.extractVarName(n[0]),i=this.genNode(n[1]);return`(${a} = ${i})`}if(e==="defn"||e==="defun"){let a=this.extractVarName(n[0]),{params:i,preamble:o}=this.extractParamListWithDestructuring(n[1]),u=n[2],f=u?this.genNode(u):"null",l=o?`((() => { ${o} return ${f}; })())`:f;return`const ${a} = (${i.join(", ")}) => ${l}`}if(e==="fn")return this.genFn(n);if(e==="list")return`[${n.map(i=>this.genNode(i)).join(", ")}]`;if(e==="str-concat")return`('' + ${n.map(i=>this.genNode(i)).join(" + ")})`;if(e==="print"||e==="println")return`_fl_print(${n.length>0?this.genNode(n[0]):'""'})`;if(e==="map")return`_fl_map(${this.genNode(n[1])}, ${this.genNode(n[0])})`;if(e==="filter")return`_fl_filter(${this.genNode(n[1])}, ${this.genNode(n[0])})`;if(e==="reduce")return`_fl_reduce(${this.genNode(n[2])}, ${this.genNode(n[0])}, ${this.genNode(n[1])})`;if(e==="export"){for(let a of n)a.kind==="variable"?this.exportedNames.push(a.name):a.kind==="literal"&&typeof a.value=="string"&&this.exportedNames.push(a.value);return""}if(e==="let"){if(n.length>=2){let o=n[0],u=[];o.kind==="block"&&o.type==="Array"?u=o.fields.get("items")||[]:o.kind==="sexpr"&&(u=o.args);let f=[];if(u.length>0&&!(u[0].kind==="block"&&u[0].type==="Array"))for(let p=0;p<u.length-1;p+=2){let m=this.extractVarName(u[p]),d=this.genNode(u[p+1]);f.push(`let ${m} = ${d};`)}else for(let p of u)if(p.kind==="block"&&p.type==="Array"){let m=p.fields.get("items")||[];if(m.length>=2){let d=this.extractVarName(m[0]),g=this.genNode(m[1]);f.push(`let ${d} = ${g};`)}}let c=n.slice(1).map(p=>this.genNode(p)).join("; ");return`(() => { ${f.join(" ")} return ${c}; })()`}let a=this.extractVarName(n[0]),i=n[1]?this.genNode(n[1]):"undefined";return`(() => { let ${a} = ${i}; return ${a}; })()`}return this.genFuncCall(e,n)}genDo(t){if(t.length===0)return"(() => undefined)()";if(t.length===1)return`(() => ${this.genNode(t[0])})()`;let e=t.slice(0,-1).map(s=>{let a=this.genNode(s).trim();return a===""||a.endsWith(";")?a:a+";"}).filter(s=>s!==""),n=this.genNode(t[t.length-1]);return`(() => { ${e.join(" ")} return ${n}; })()`}genCond(t){if(t.length===0)return"null";let e=!1;if(t[0].kind==="block"&&t[0].type==="Array"){let a=t[0].fields.get("items");Array.isArray(a)&&a.length>=1&&(e=!0)}let n;if(e)n=t.map(a=>{if(a.kind==="block"&&a.type==="Array"){let i=a.fields.get("items")||[];return[i[0],i[1]]}return[a,null]});else{n=[];for(let a=0;a<t.length-1;a+=2)n.push([t[a],t[a+1]]);t.length%2===1&&n.push([{kind:"literal",type:"boolean",value:!0},t[t.length-1]])}let s="null";for(let a=n.length-1;a>=0;a--){let[i,o]=n[a];if(!i)continue;let u=this.genNode(i),f=o?this.genNode(o):"null";s="("+u+" ? "+f+" : "+s+")"}return s}genWhile(t){let e=this.genNode(t[0]),s=t.slice(1).map(a=>this.genNode(a).trim()).filter(a=>a!=="").map(a=>a.endsWith(";")?a:a+";").join(" ");return"(() => { while("+e+") { "+s+" } })()"}genFn(t){let{params:e,preamble:n}=this.extractParamListWithDestructuring(t[0]),s;if(t.length<=1)s="undefined";else if(t.length===2)s=this.genNode(t[1]);else{let i=t.slice(1),o=i.slice(0,-1).map(f=>this.genNode(f)+";").join(" "),u=this.genNode(i[i.length-1]);s=`((() => { ${o} return ${u}; })())`}let a=n?`((() => { ${n} return ${s}; })())`:s;return`((${e.join(", ")}) => ${a})`}extractParamListWithDestructuring(t){if(!t)return{params:[],preamble:""};let e=t.kind==="block"&&t.type==="Array"?t.fields.get("items"):t.kind==="sexpr"?t.args:[t],n=[],s=[],a=0;for(let i of e||[])if(i.kind==="variable")n.push(Ee(i.name.replace(/^\$/,"")));else if(i.kind==="literal"&&(i.type==="symbol"||typeof i.value=="string"))n.push(Ee(String(i.value).replace(/^\$/,"")));else if(i.kind==="block"&&i.type==="Array"){let o=`_arg${a++}`;n.push(o);let u=i.fields.get("items")||[];for(let f=0;f<u.length;f++){let l=u[f];if(l.kind==="variable"){let c=Ee(l.name.replace(/^\$/,""));s.push(`let ${c} = ${o}[${f}];`)}else if(l.kind==="literal"&&(l.type==="symbol"||typeof l.value=="string")){let c=Ee(String(l.value).replace(/^\$/,""));s.push(`let ${c} = ${o}[${f}];`)}}}else n.push("p");return{params:n,preamble:s.join(" ")}}extractVarName(t){return t.kind==="variable"?Ee(t.name.replace(/^\$/,"")):t.kind==="literal"&&typeof t.value=="string"?Ee(t.value):"unknown"}extractParamList(t){return t?((t.kind==="block"&&t.type==="Array"?t.fields.get("items"):t.kind==="sexpr"?t.args:[t])||[]).map(n=>(n.name||String(n.value||"p")).replace(/^\\$/,"")).map(n=>Ee(n)):[]}extractBlockParams(t){let e=t.fields.get("params");return e?((Array.isArray(e)?e:e.kind==="block"&&e.type==="Array"?e.fields.get("items"):[e])||[]).map(s=>(s.name||String(s.value||"p")).replace(/^\\$/,"")).map(s=>Ee(s)):[]}genFuncCall(t,e){let n=e.map(a=>this.genNode(a));return`${Ee(t)}(${n.join(", ")})`}genBlock(t){switch(t.type){case"FUNC":return this.genFuncBlock(t);case"MODULE":return this.genModuleBlock(t);case"SERVICE":return this.genServiceBlock(t);case"MODEL":return this.genModelBlock(t);case"CONTROLLER":return this.genControllerBlock(t);case"MAP":case"Map":return this.genMapBlock(t);case"ARRAY":case"Array":return this.genArrayBlock(t);default:return`/* unsupported block: ${t.type} */`}}genMapBlock(t){let e=[];return t.fields.forEach((n,s)=>{let a=s.match(/^[a-zA-Z_$][a-zA-Z0-9_$]*$/)?s:JSON.stringify(s);e.push(a+": "+this.genNode(n))}),"({ "+e.join(", ")+" })"}genArrayBlock(t){let e=t.fields.get("items");return"["+((Array.isArray(e)?e:e&&e.kind==="block"?e.fields.get("items"):[])||[]).map(a=>this.genNode(a)).join(", ")+"]"}genFuncBlock(t){let e=this.extractBlockParams(t),n=t.fields.get("body"),s=n?this.genNode(n):"undefined";return`function ${this.flNameToJs(t.name)}(${e.join(", ")}) { return ${s}; }`}flNameToJs(t){return Ee(t)}genModuleBlock(t){let e=t.fields.get("body");return e?Array.isArray(e)?e.map(n=>this.genNode(n)).join(`
813
+ `):this.genNode(e):""}genServiceBlock(t){let e=t.name,n=t.fields.get("methods"),s=t.fields.get("inject"),a=s&&Array.isArray(s)?s.map(o=>`private ${o.name||o}: ${o.name||o}`).join(", "):"",i="";return n&&n.kind==="sexpr"&&(i=n.args.map(o=>{if(o.kind==="sexpr"&&o.op==="fn"){let u=o,f=u.args[0].name||u.args[0].value||"method",l=this.extractParamList(u.args[1]).map(p=>p.replace(/^\$/,"")).join(", "),c=u.args[2]?this.genNode(u.args[2]):"undefined";return` ${f}(${l}) { return ${c}; }`}return""}).filter(Boolean).join(`
814
+ `)),[`export class ${e} {`,a?` constructor(${a}) {}`:" constructor() {}",i,"}"].join(`
815
+ `)}genModelBlock(t){let e=t.name,n=t.fields.get("table")||e.toLowerCase()+"s",s=t.fields.get("fields"),a=" id SERIAL PRIMARY KEY";if(s&&s.kind==="sexpr"){for(let i of s.args)if(i.kind==="sexpr"){let o=i.op.replace(/^[\$:]/,"").replace(/-/g,"_");a+=`,
816
+ ${o} VARCHAR(255)`}}return[`CREATE TABLE IF NOT EXISTS ${n} (`,a,`,
817
+ created_at TIMESTAMP DEFAULT NOW(),
818
+ updated_at TIMESTAMP DEFAULT NOW()
819
+ );`].join(`
820
+ `)}genControllerBlock(t){let e=t.fields.get("prefix")||"/",n=t.fields.get("routes"),s="";if(n&&n.kind==="sexpr"){let a=n;for(let i=0;i<a.args.length;i+=3){let o=String(a.args[i].value||"GET").toLowerCase(),u=String(a.args[i+1].value||"/");s+=`router.${o}("${e==="/"?u:e+u}", async (req, res) => { res.json({ status: 200 }); });
821
+ `}}return['import { Router } from "express";',"export const router = Router();",s].join(`
822
+ `)}genTryBlock(t){let n=[`(()=>{try{return ${this.genNode(t.body)};}`];if(t.catchClauses)for(let s of t.catchClauses)n.push(`catch(${s.variable||"err"}){return ${this.genNode(s.handler)};}`);return t.finallyBlock&&n.push(`finally{${this.genNode(t.finallyBlock)};}`),n.join("")+"})()"}minify(t){return t.replace(/\/\/[^\n]*/g,"").replace(/\s+/g," ").trim()}};function lu(){let r=new Zt;return{fl_compile_file:(t,e)=>{try{let n=Me.readFileSync(t,"utf-8"),s=W(n),a=H(s),i=r.generate(a,{module:"commonjs",runtime:!1,minify:!1,target:"node"}),o=Ie.dirname(e);return o!=="."&&!Me.existsSync(o)&&Me.mkdirSync(o,{recursive:!0}),Me.writeFileSync(e,i,"utf-8"),!0}catch(n){throw new Error(`fl_compile_file failed for '${t}': ${n.message}`)}},fl_compile:(t,e)=>{try{let n=Ie.resolve(t),s=Ie.resolve(e),a=Me.readdirSync(n).filter(f=>f.endsWith(".fl")).map(f=>Ie.join(n,f)),i=0,o=0,u=[];for(let f of a){let l=Ie.join(s,Ie.basename(f,".fl")+".js");try{let c=Me.readFileSync(f,"utf-8"),p=W(c),m=H(p),d=r.generate(m,{module:"commonjs",runtime:!1,minify:!1,target:"node"}),g=Ie.dirname(l);g!=="."&&!Me.existsSync(g)&&Me.mkdirSync(g,{recursive:!0}),Me.writeFileSync(l,d,"utf-8"),i++}catch(c){o++,u.push(`${Ie.basename(f)}: ${c.message}`)}}return{compiled:i,failed:o,errors:u}}catch(n){throw new Error(`fl_compile failed for '${t}': ${n.message}`)}},fl_compile_result_ok:t=>t.failed===0}}function uu(){let r=process.env.REGISTRY_URL||"http://localhost:4873";return{registry_publish:(t,e,n)=>{try{let s=JSON.stringify(n);return zs("PUT",`${r}/${t}/${e}`,s)}catch(s){throw new Error(`registry_publish failed: ${s.message}`)}},registry_search:t=>{try{let e=zs("GET",`${r}/search?q=${encodeURIComponent(t)}`,"");return typeof e=="string"?JSON.parse(e):e}catch(e){throw new Error(`registry_search failed: ${e.message}`)}},registry_info:t=>{try{let e=zs("GET",`${r}/${t}`,"");return typeof e=="string"?JSON.parse(e):e}catch(e){throw new Error(`registry_info failed: ${e.message}`)}},registry_delete:(t,e)=>{try{return zs("DELETE",`${r}/${t}/${e}`,"")}catch(n){throw new Error(`registry_delete failed: ${n.message}`)}},registry_start:(t=4873)=>{try{return{port:t,running:!0,message:"Registry started"}}catch(e){throw new Error(`registry_start failed: ${e.message}`)}}}}function zs(r,t,e){try{let{execSync:n}=require("child_process"),s=`curl -s -X ${r} ${e?`-d '${e}'`:""} "${t}"`,a=n(s,{encoding:"utf-8"});try{return JSON.parse(a)}catch{return a}}catch(n){throw new Error(`HTTP ${r} ${t} failed: ${n.message}`)}}function mu(){let r=new Map,t=js();return{orm_define_model:(e,n,s,a)=>{try{let i={name:e,table:n,fields:s||[],indexes:a||[]};r.set(e,i);let o=pu(e,n,s);return{name:e,table:n,fields:s.length,indexes:(a||[]).length,sql:o}}catch(i){throw new Error(`orm_define_model failed: ${i.message}`)}},orm_migrate:e=>{try{let n=r.get(e);if(!n)throw new Error(`Model not found: ${e}`);let s=pu(e,n.table,n.fields);return!0}catch(n){throw new Error(`orm_migrate failed: ${n.message}`)}},orm_create:(e,n)=>{try{let s=r.get(e);if(!s)throw new Error(`Model not found: ${e}`);return fu(s,n),{id:Math.floor(Math.random()*1e6),...n,created_at:new Date().toISOString()}}catch(s){throw new Error(`orm_create failed: ${s.message}`)}},orm_find:(e,n)=>{try{if(!r.get(e))throw new Error(`Model not found: ${e}`);return{id:n,model:e}}catch(s){throw new Error(`orm_find failed: ${s.message}`)}},orm_find_by:(e,n,s)=>{try{if(!r.get(e))throw new Error(`Model not found: ${e}`);return{[n]:s,model:e}}catch(a){throw new Error(`orm_find_by failed: ${a.message}`)}},orm_where:(e,n)=>{try{if(!r.get(e))throw new Error(`Model not found: ${e}`);return[{...n,model:e}]}catch(s){throw new Error(`orm_where failed: ${s.message}`)}},orm_update:(e,n,s)=>{try{let a=r.get(e);if(!a)throw new Error(`Model not found: ${e}`);return fu(a,s),{id:n,...s,updated_at:new Date().toISOString()}}catch(a){throw new Error(`orm_update failed: ${a.message}`)}},orm_delete:(e,n)=>{try{if(!r.get(e))throw new Error(`Model not found: ${e}`);return!0}catch(s){throw new Error(`orm_delete failed: ${s.message}`)}},orm_all:e=>{try{if(!r.get(e))throw new Error(`Model not found: ${e}`);return[]}catch(n){throw new Error(`orm_all failed: ${n.message}`)}},orm_count:e=>{try{if(!r.get(e))throw new Error(`Model not found: ${e}`);return 0}catch(n){throw new Error(`orm_count failed: ${n.message}`)}},orm_get_model:e=>{try{let n=r.get(e);return n||null}catch(n){throw new Error(`orm_get_model failed: ${n.message}`)}}}}function pu(r,t,e){let n=e.map(s=>{let a=`${s.name} `;return s.type==="integer"?a+="INTEGER":s.type==="string"?a+="TEXT":s.type==="datetime"?a+="DATETIME DEFAULT CURRENT_TIMESTAMP":a+="TEXT",s.primaryKey&&(a+=" PRIMARY KEY AUTOINCREMENT"),s.unique&&(a+=" UNIQUE"),s.required&&(a+=" NOT NULL"),a});return`CREATE TABLE IF NOT EXISTS ${t} (
823
+ ${n.join(`,
824
+ `)}
825
+ );`}function fu(r,t){for(let e of r.fields){if(e.required&&t[e.name]===void 0)throw new Error(`Field '${e.name}' is required`);if(e.type==="integer"&&t[e.name]!==void 0&&typeof t[e.name]!="number")throw new Error(`Field '${e.name}' must be integer`)}}function du(){let r=new Map;return{schema_define:(t,e)=>{try{let n={name:t,fields:e};return r.set(t,n),n}catch(n){throw new Error(`schema_define failed: ${n.message}`)}},schema_validate:(t,e)=>{try{let n=r.get(t);if(!n)throw new Error(`Schema not found: ${t}`);let s=[];for(let[a,i]of Object.entries(n.fields)){let o=e[a],u=Ws(a,o,i);s.push(...u)}return{valid:s.length===0,errors:s,data:s.length===0?e:null}}catch(n){throw new Error(`schema_validate failed: ${n.message}`)}},schema_is_valid:(t,e)=>{try{let n=r.get(t);if(!n)return!1;for(let[s,a]of Object.entries(n.fields)){let i=e[s];if(Ws(s,i,a).length>0)return!1}return!0}catch{return!1}},schema_validate_or_throw:(t,e)=>{try{let n=r.get(t);if(!n)throw new Error(`Schema not found: ${t}`);let s=[];for(let[a,i]of Object.entries(n.fields)){let o=e[a],u=Ws(a,o,i);s.push(...u)}if(s.length>0)throw new Error(`Validation failed: ${s.join(", ")}`);return e}catch(n){throw new Error(`schema_validate_or_throw failed: ${n.message}`)}},schema_get_errors:(t,e)=>{try{let n=r.get(t);if(!n)throw new Error(`Schema not found: ${t}`);let s=[];for(let[a,i]of Object.entries(n.fields)){let o=e[a],u=Ws(a,o,i);s.push(...u)}return s}catch(n){throw new Error(`schema_get_errors failed: ${n.message}`)}},schema_get:t=>{try{return r.get(t)||null}catch(e){throw new Error(`schema_get failed: ${e.message}`)}},validate_email:t=>{try{return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}catch{return!1}},validate_string:(t,e,n)=>{try{return!(typeof t!="string"||e!==void 0&&t.length<e||n!==void 0&&t.length>n)}catch{return!1}},validate_number:(t,e,n)=>{try{return!(typeof t!="number"||e!==void 0&&t<e||n!==void 0&&t>n)}catch{return!1}},validate_regex:(t,e)=>{try{return new RegExp(e).test(String(t))}catch{return!1}}}}function Ws(r,t,e){let n=[];if(e.required&&(t==null||t===""))return n.push(`${r} is required`),n;if(t==null)return n;if(e.type==="string"&&typeof t!="string"?n.push(`${r} must be string`):e.type==="number"&&typeof t!="number"?n.push(`${r} must be number`):e.type==="integer"&&!Number.isInteger(t)?n.push(`${r} must be integer`):e.type==="boolean"&&typeof t!="boolean"?n.push(`${r} must be boolean`):e.type==="email"&&(/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)||n.push(`${r} must be valid email`)),typeof t=="string"&&(e.min!==void 0&&t.length<e.min&&n.push(`${r} minimum length is ${e.min}`),e.max!==void 0&&t.length>e.max&&n.push(`${r} maximum length is ${e.max}`)),typeof t=="number"&&(e.min!==void 0&&t<e.min&&n.push(`${r} minimum value is ${e.min}`),e.max!==void 0&&t>e.max&&n.push(`${r} maximum value is ${e.max}`)),e.pattern)try{new RegExp(e.pattern).test(String(t))||n.push(`${r} does not match pattern`)}catch{n.push(`${r} pattern is invalid`)}return n}function gu(){let r=new Map,t=[];return{middleware_define:(e,n,s,a)=>{try{let i={name:e,condition:typeof n=="function"?n:void 0,handler:typeof s=="function"?s:()=>s,onFail:typeof a=="function"?a:void 0};return r.set(e,i),{name:e,defined:!0,hasCondition:!!i.condition,hasOnFail:!!i.onFail}}catch(i){throw new Error(`middleware_define failed: ${i.message}`)}},middleware_create_chain:e=>{try{let n=e.filter(s=>r.has(s));return t.push(n),n}catch(n){throw new Error(`middleware_create_chain failed: ${n.message}`)}},middleware_apply_chain:(e,n)=>{try{let s=t[e];if(!s)throw new Error(`Chain not found: ${e}`);let a=[],i=n,o=!0;for(let u of s){let f=r.get(u);if(f)if(f.condition&&!f.condition(i))if(f.onFail){let l=f.onFail(i);if(l&&typeof l=="object"&&"error"in l){a.push(`${u}: condition failed`),o=!1;break}}else{a.push(`${u}: condition not met`),o=!1;break}else try{i=f.handler(i)}catch(l){a.push(`${u}: ${l.message}`),o=!1,f.onFail&&f.onFail(i);break}}return{passed:o,request:i,errors:a,chainLength:s.length,executedMiddlewares:s.length-(a.length>0?1:0)}}catch(s){throw new Error(`middleware_apply_chain failed: ${s.message}`)}},middleware_add_to_chain:(e,n)=>{try{let s=t[e];if(!s)throw new Error(`Chain not found: ${e}`);return r.has(n)&&s.push(n),s}catch(s){throw new Error(`middleware_add_to_chain failed: ${s.message}`)}},middleware_get:e=>{try{let n=r.get(e);return n?{name:n.name,hasCondition:!!n.condition,hasOnFail:!!n.onFail}:null}catch(n){throw new Error(`middleware_get failed: ${n.message}`)}},middleware_auth_check:e=>({name:"auth-check",condition:n=>{let s=n.headers?.authorization||n.auth;return!!s&&s.startsWith("Bearer ")},handler:n=>{let a=(n.headers?.authorization||n.auth).replace("Bearer ","");return{...n,user:{token:a}}},onFail:n=>({error:"UNAUTHORIZED",statusCode:401})}),middleware_logging:()=>({name:"logging",handler:e=>{let n=new Date().toISOString();return console.log(`[${n}] ${e.method||"GET"} ${e.path||"/"}`),e}}),middleware_rate_limit:(e=100,n=6e4)=>{let s=new Map;return{name:"rate-limit",handler:a=>{let i=a.ip||a.headers?.["x-forwarded-for"]||"unknown",o=Date.now(),u=o-n;s.has(i)||s.set(i,[]);let l=s.get(i).filter(c=>c>u);if(l.length>=e)throw new Error(`Rate limit exceeded: ${e} requests per ${n}ms`);return l.push(o),s.set(i,l),{...a,rateLimit:{remaining:e-l.length}}},onFail:a=>({error:"TOO_MANY_REQUESTS",statusCode:429})}},middleware_cors:e=>({name:"cors",handler:n=>({...n,headers:{...n.headers,"Access-Control-Allow-Origin":e||"*","Access-Control-Allow-Methods":"GET,POST,PUT,DELETE,OPTIONS","Access-Control-Allow-Headers":"Content-Type,Authorization"}})})}}var Pr=z(require("fs"));function hu(){return{table_load_csv:r=>{try{let e=Pr.readFileSync(r,"utf-8").split(`
826
+ `).filter(a=>a.trim()),n=e[0].split(",").map(a=>a.trim()),s=e.slice(1).map(a=>{let i=a.split(",").map(u=>u.trim()),o={};return n.forEach((u,f)=>{let l=i[f];o[u]=isNaN(Number(l))?l:Number(l)}),o});return{headers:n,rows:s}}catch(t){throw new Error(`table_load_csv failed: ${t.message}`)}},table_load_json:r=>{try{let t=Pr.readFileSync(r,"utf-8"),e=JSON.parse(t);if(!Array.isArray(e))throw new Error("JSON must be array of objects");return{headers:e.length>0?Object.keys(e[0]):[],rows:e}}catch(t){throw new Error(`table_load_json failed: ${t.message}`)}},table_save_csv:(r,t)=>{try{let e=[r.headers.join(","),...r.rows.map(n=>r.headers.map(s=>n[s]??"").join(","))].join(`
827
+ `);return Pr.writeFileSync(t,e,"utf-8"),!0}catch(e){throw new Error(`table_save_csv failed: ${e.message}`)}},table_select:(r,t)=>{try{let e=t.filter(s=>r.headers.includes(s)),n=r.rows.map(s=>{let a={};return e.forEach(i=>a[i]=s[i]),a});return{headers:e,rows:n}}catch(e){throw new Error(`table_select failed: ${e.message}`)}},table_filter:(r,t)=>{try{let e=r.rows.filter(t);return{headers:r.headers,rows:e}}catch(e){throw new Error(`table_filter failed: ${e.message}`)}},table_map:(r,t)=>{try{let e=r.rows.map(t);return{headers:r.headers,rows:e}}catch(e){throw new Error(`table_map failed: ${e.message}`)}},table_sort:(r,t,e="asc")=>{try{let n=[...r.rows].sort((s,a)=>{let i=s[t],o=a[t],u=i<o?-1:i>o?1:0;return e==="desc"?-u:u});return{headers:r.headers,rows:n}}catch(n){throw new Error(`table_sort failed: ${n.message}`)}},table_group_by:(r,t)=>{try{let e={};return r.rows.forEach(n=>{let s=String(n[t]);e[s]||(e[s]=[]),e[s].push(n)}),e}catch(e){throw new Error(`table_group_by failed: ${e.message}`)}},table_aggregate:(r,t,e)=>{try{let n=r.rows.map(s=>s[t]).filter(s=>s!=null);return e==="count"?n.length:n.length===0?0:e==="sum"?n.reduce((s,a)=>s+a,0):e==="mean"?n.reduce((s,a)=>s+a,0)/n.length:e==="min"?Math.min(...n):e==="max"?Math.max(...n):0}catch(n){throw new Error(`table_aggregate failed: ${n.message}`)}},table_join:(r,t,e)=>{try{let n=new Map;t.rows.forEach(i=>n.set(i[e],i));let s=r.rows.map(i=>{let o=n.get(i[e]);return o?{...i,...o}:i});return{headers:[...new Set([...r.headers,...t.headers])],rows:s}}catch(n){throw new Error(`table_join failed: ${n.message}`)}},table_head:(r,t=5)=>{try{return{headers:r.headers,rows:r.rows.slice(0,t)}}catch(e){throw new Error(`table_head failed: ${e.message}`)}},table_tail:(r,t=5)=>{try{return{headers:r.headers,rows:r.rows.slice(-t)}}catch(e){throw new Error(`table_tail failed: ${e.message}`)}},table_shape:r=>{try{return{rows:r.rows.length,cols:r.headers.length}}catch(t){throw new Error(`table_shape failed: ${t.message}`)}}}}function yu(){let r=new Map,t=new Map,e=new Map,n={requests:0,errors:0};return{service_define:(s,a,i)=>{try{let o={name:s,port:a,routes:i||[],running:!1};return r.set(s,o),o}catch(o){throw new Error(`service_define failed: ${o.message}`)}},service_start:s=>{try{let a=r.get(s);if(!a)throw new Error(`Service not found: ${s}`);return a.running=!0,{service:s,running:!0,port:a.port}}catch(a){throw new Error(`service_start failed: ${a.message}`)}},service_stop:s=>{try{let a=r.get(s);if(!a)throw new Error(`Service not found: ${s}`);return a.running=!1,!0}catch(a){throw new Error(`service_stop failed: ${a.message}`)}},service_health:s=>{try{let a=r.get(s);if(!a)throw new Error(`Service not found: ${s}`);return{service:s,status:a.running?"healthy":"down",uptime:a.running?Math.random()*3600:0,requests:n.requests}}catch(a){throw new Error(`service_health failed: ${a.message}`)}},queue_create:(s,a)=>{try{let i={name:s,type:a||"memory",messages:[]};return t.set(s,i.messages),i}catch(i){throw new Error(`queue_create failed: ${i.message}`)}},queue_publish:(s,a,i)=>{try{let o=t.get(s);if(!o)throw new Error(`Queue not found: ${s}`);return o.push({event:a,data:i,timestamp:Date.now()}),!0}catch(o){throw new Error(`queue_publish failed: ${o.message}`)}},queue_subscribe:(s,a,i)=>{try{return`sub-${Math.random().toString(36).substr(2,9)}`}catch(o){throw new Error(`queue_subscribe failed: ${o.message}`)}},circuit_breaker_define:(s,a,i,o)=>{try{let u={name:s,state:"CLOSED",threshold:a||5,timeout:i||3e4,failures:0,lastFailure:null,fallback:o};return e.set(s,u),u}catch(u){throw new Error(`circuit_breaker_define failed: ${u.message}`)}},circuit_call:(s,a)=>{try{let i=e.get(s);if(!i)return a();if(i.state==="OPEN")return i.fallback?i.fallback():{error:"Circuit open"};try{let o=a();return i.failures=0,i.state="CLOSED",o}catch(o){throw i.failures++,i.lastFailure=Date.now(),i.failures>=i.threshold&&(i.state="OPEN"),o}}catch(i){throw new Error(`circuit_call failed: ${i.message}`)}},observe_metric:(s,a,i)=>{try{return n[s]||(n[s]=0),i==="gauge"?n[s]=a:n[s]+=a,!0}catch(o){throw new Error(`observe_metric failed: ${o.message}`)}},observe_log:(s,a,i)=>{try{let o=new Date().toISOString();return console.log(`[${o}] [${s.toUpperCase()}] ${a}`,i||""),!0}catch(o){throw new Error(`observe_log failed: ${o.message}`)}},observe_report:()=>{try{return{timestamp:new Date().toISOString(),metrics:n,services:Array.from(r.values()).map(s=>({name:s.name,port:s.port,running:s.running})),queues:Array.from(t.keys())}}catch(s){throw new Error(`observe_report failed: ${s.message}`)}}}}function jr(r){return r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Ni(r){let t={};if(!r.startsWith(`---
828
+ `)&&!r.startsWith(`---\r
829
+ `))return{fm:t,body:r};let e=r.replace(/^---\r?\n/,""),n=e.match(/\n---[ \t]*(\r?\n|$)/),s=n?e.indexOf(n[0]):-1;if(s<0)return{fm:t,body:r};let a=e.slice(0,s),i=e.slice(s).replace(/^\n---\r?\n?/,"");for(let o of a.split(/\r?\n/)){let u=o.match(/^([A-Za-z_][A-Za-z0-9_-]*)\s*:\s*(.*)$/);if(!u)continue;let f=u[2].trim();/^(true|false)$/i.test(String(f))?f=String(f).toLowerCase()==="true":/^-?\d+(\.\d+)?$/.test(String(f))?f=Number(f):(f.startsWith('"')&&f.endsWith('"')||f.startsWith("'")&&f.endsWith("'"))&&(f=f.slice(1,-1)),t[u[1]]=f}return{fm:t,body:i}}function Oi(r){let t=[];return r=r.replace(/`([^`\n]+)`/g,(e,n)=>(t.push(`<code>${jr(n)}</code>`),`\0C${t.length-1}\0`)),r=jr(r),r=r.replace(/!\[([^\]]*)\]\(([^)\s]+)(?:\s+&quot;([^&]*)&quot;)?\)/g,(e,n,s,a)=>a?`<img src="${s}" alt="${n}" title="${a}" loading="lazy" decoding="async">`:`<img src="${s}" alt="${n}" loading="lazy" decoding="async">`),r=r.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+&quot;([^&]*)&quot;)?\)/g,(e,n,s,a)=>a?`<a href="${s}" title="${a}">${n}</a>`:`<a href="${s}">${n}</a>`),r=r.replace(/\*\*([^*\n]+)\*\*/g,"<strong>$1</strong>"),r=r.replace(/(^|[^*])\*([^*\n]+)\*(?!\*)/g,"$1<em>$2</em>"),r=r.replace(/\x00C(\d+)\x00/g,(e,n)=>t[Number(n)]||""),r}function Fi(r){let t=r.replace(/\r\n/g,`
830
+ `).split(`
831
+ `),e=[],n=0;for(;n<t.length;){let s=t[n];if(/^\s*$/.test(s)){n++;continue}let a=s.match(/^```\s*([A-Za-z0-9_+-]*)\s*$/);if(a){let l=a[1]||"";n++;let c=[];for(;n<t.length&&!/^```\s*$/.test(t[n]);)c.push(t[n]),n++;n<t.length&&n++,e.push({kind:"code",lang:l,text:c.join(`
832
+ `)});continue}if(/^\s*([-*_])(\s*\1){2,}\s*$/.test(s)){e.push({kind:"hr"}),n++;continue}let i=s.match(/^(#{1,6})\s+(.+?)\s*#*\s*$/);if(i){e.push({kind:"heading",level:i[1].length,text:i[2]}),n++;continue}if(/^>\s?/.test(s)){let l=[];for(;n<t.length&&/^>\s?/.test(t[n]);)l.push(t[n].replace(/^>\s?/,"")),n++;e.push({kind:"quote",lines:l});continue}let o=s.match(/^\s*[-*+]\s+(.+)$/),u=s.match(/^\s*\d+\.\s+(.+)$/);if(o||u){let l=!!u,c=[],p=l?/^\s*\d+\.\s+(.+)$/:/^\s*[-*+]\s+(.+)$/;for(;n<t.length;){let m=t[n].match(p);if(!m)break;c.push(m[1]),n++}e.push({kind:"list",ordered:l,items:c});continue}let f=[s];for(n++;n<t.length;){let l=t[n];if(/^\s*$/.test(l)||/^#{1,6}\s/.test(l)||/^```/.test(l)||/^>\s?/.test(l)||/^\s*[-*+]\s+/.test(l)||/^\s*\d+\.\s+/.test(l)||/^\s*([-*_])(\s*\1){2,}\s*$/.test(l))break;f.push(l),n++}e.push({kind:"paragraph",text:f.join(" ")})}return e}function Pi(r){switch(r.kind){case"heading":return`<h${r.level}>${Oi(r.text)}</h${r.level}>`;case"paragraph":return`<p>${Oi(r.text)}</p>`;case"code":return r.lang?`<pre><code class="language-${jr(r.lang)}">${jr(r.text)}</code></pre>`:`<pre><code>${jr(r.text)}</code></pre>`;case"quote":return`<blockquote>${Fi(r.lines.join(`
833
+ `)).map(Pi).join("")}</blockquote>`;case"list":{let t=r.ordered?"ol":"ul",e=r.items.map(n=>`<li>${Oi(n)}</li>`).join("");return`<${t}>${e}</${t}>`}case"hr":return"<hr>"}}function bu(){return{markdown_to_html:r=>{if(typeof r!="string")return"";let{body:t}=Ni(r);return Fi(t).map(Pi).join("")},markdown_frontmatter:r=>typeof r!="string"?{fm:{},body:""}:Ni(r),markdown_render_full:r=>{if(typeof r!="string")return{fm:{},html:""};let{fm:t,body:e}=Ni(r),n=Fi(e).map(Pi).join("");return{fm:t,html:n}}}}function ku(r){return String(r||"").toLowerCase().replace(/[^a-z0-9가-힣\s]/g," ").replace(/\s+/g," ").trim()}function vu(){return{blog_all_tags:r=>{let t=new Map;for(let e of r||[])for(let n of e.tags||[])t.set(n,(t.get(n)||0)+1);return[...t.entries()].sort((e,n)=>n[1]-e[1]||e[0].localeCompare(n[0])).map(e=>e[0])},blog_posts_by_tag:(r,t)=>(r||[]).filter(n=>(n.tags||[]).includes(t)).sort((n,s)=>(s.date||"").localeCompare(n.date||"")),blog_tag_counts:r=>{let t={};for(let e of r||[])for(let n of e.tags||[])t[n]=(t[n]||0)+1;return t},blog_related:(r,t,e=5)=>{let n=(r||[]).find(i=>i.slug===t);if(!n)return[];let s=new Set(n.tags||[]);return(r||[]).filter(i=>i.slug!==t).map(i=>({post:i,score:(i.tags||[]).filter(o=>s.has(o)).length,date:i.date||""})).filter(i=>i.score>0).sort((i,o)=>o.score-i.score||o.date.localeCompare(i.date)).slice(0,Math.max(0,e)).map(i=>i.post)},blog_search_index:r=>(r||[]).map(t=>({slug:t.slug,title:t.title,url:t.url||`/blog/${t.slug}`,terms:ku(`${t.title} ${t.summary||""} ${t.body||""}`).slice(0,500)})),blog_search:(r,t,e=10)=>{let n=ku(t);if(!n)return[];let s=n.split(" ").filter(Boolean);return(r||[]).map(i=>{let o=0;for(let u of s)i.title.toLowerCase().includes(u)&&(o+=3),i.terms.includes(u)&&(o+=1);return{entry:i,score:o}}).filter(i=>i.score>0).sort((i,o)=>o.score-i.score).slice(0,Math.max(0,e)).map(i=>({slug:i.entry.slug,title:i.entry.title,url:i.entry.url,score:i.score}))},blog_posts_sorted:r=>[...r||[]].sort((t,e)=>(e.date||"").localeCompare(t.date||"")),blog_paginate:(r,t=1,e=10)=>{let n=r||[],s=Math.max(1,e),a=Math.max(1,Math.ceil(n.length/s)),i=Math.min(Math.max(1,t),a),o=(i-1)*s;return{items:n.slice(o,o+s),total:n.length,page:i,pages:a,perPage:s,hasPrev:i>1,hasNext:i<a}}}}var _u=require("child_process");function wu(r,t,e){let n=["-s","-o","/dev/null","-w","%{http_code}","-X","POST","-H","Content-Type: application/json",...e?["-H",`X-Service-Key: ${e}`]:[],"-d",t,r];try{let s=(0,_u.spawnSync)("curl",n,{timeout:3e3}),a=parseInt(s.stdout?.toString().trim()??"0",10);return{ok:a>=200&&a<300,status:a}}catch{return{ok:!1,status:0}}}function Su(){return{audit_log:(r,t,e,n,s)=>{let a=process.env.AUDIT_URL??"",i=process.env.AUDIT_SERVICE_KEY??"";if(!a)return null;let o=JSON.stringify({service_id:r,actor_id:t??r,action:e,resource:n,detail:s,timestamp:new Date().toISOString()});try{return wu(a,o,i)}catch{return null}},audit_log_custom:(r,t,e,n,s,a)=>{let i=process.env.AUDIT_URL??"",o=process.env.AUDIT_SERVICE_KEY??"";if(!i)return null;let u=JSON.stringify({service_id:r,actor_id:t??r,action:e,resource:n,detail:s,timestamp:new Date().toISOString(),...a&&typeof a=="object"?a:{}});try{return wu(i,u,o)}catch{return null}},"audit_log_ok?":r=>r!=null&&r.ok===!0}}var ji={ws:r=>Il(r?(t,e)=>r.callUserFunction(t,e):()=>null),wsc:r=>Ll(r?(t,e)=>r.callUserFunction(t,e):()=>null),"crypto-rsa":()=>Bl(),totp:()=>Vl(),mail:()=>Wl(),webauthn:()=>Gl(),queue:()=>Jl(),workflow:()=>Ns(),resource:()=>Os(),mariadb:()=>Zl(),mongodb:()=>Us(),async:r=>nu(r?(t,e)=>r.callUserFunction(t,e):()=>null),channel:()=>ru(),immutable:()=>su(),ai:()=>au(),compile:()=>lu(),registry:()=>uu(),oci:()=>{throw new Error("oci \uBAA8\uB4C8\uC740 \uBCC4\uB3C4 \uD328\uD0A4\uC9C0\uAC00 \uD544\uC694\uD569\uB2C8\uB2E4. \uD45C\uC900 \uBC30\uD3EC\uC5D0 \uD3EC\uD568\uB418\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.")},orm:()=>mu(),validation:()=>du(),middleware:()=>gu(),table:()=>hu(),stats:()=>{throw new Error("stats \uBAA8\uB4C8\uC740 \uBCC4\uB3C4 \uD328\uD0A4\uC9C0\uAC00 \uD544\uC694\uD569\uB2C8\uB2E4. \uD45C\uC900 \uBC30\uD3EC\uC5D0 \uD3EC\uD568\uB418\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.")},plot:()=>{throw new Error("plot \uBAA8\uB4C8\uC740 \uBCC4\uB3C4 \uD328\uD0A4\uC9C0\uAC00 \uD544\uC694\uD569\uB2C8\uB2E4. \uD45C\uC900 \uBC30\uD3EC\uC5D0 \uD3EC\uD568\uB418\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.")},service:()=>yu(),markdown:()=>bu(),feed:()=>{throw new Error("feed \uBAA8\uB4C8\uC740 \uBCC4\uB3C4 \uD328\uD0A4\uC9C0\uAC00 \uD544\uC694\uD569\uB2C8\uB2E4. \uD45C\uC900 \uBC30\uD3EC\uC5D0 \uD3EC\uD568\uB418\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.")},blog:()=>vu(),cloud:()=>{throw new Error("cloud \uBAA8\uB4C8\uC740 \uBCC4\uB3C4 \uD328\uD0A4\uC9C0\uAC00 \uD544\uC694\uD569\uB2C8\uB2E4. \uD45C\uC900 \uBC30\uD3EC\uC5D0 \uD3EC\uD568\uB418\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.")},matrix:()=>{throw new Error("matrix \uBAA8\uB4C8\uC740 \uBCC4\uB3C4 \uD328\uD0A4\uC9C0\uAC00 \uD544\uC694\uD569\uB2C8\uB2E4. \uD45C\uC900 \uBC30\uD3EC\uC5D0 \uD3EC\uD568\uB418\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.")},audit:()=>Su()},Ii=new Set;function xu(){return Object.keys(ji)}function Au(r){return Ii.has(r)}function $u(r,t){let e=r.replace(/_/g,"-");if(Ii.has(e))return!0;let n=ji[e];if(!n)return console.warn(`\u26A0\uFE0F [FreeLang] require: \uC54C \uC218 \uC5C6\uB294 \uBAA8\uB4C8 "${r}". \uC0AC\uC6A9 \uAC00\uB2A5: ${Object.keys(ji).join(", ")}`),!1;try{let s=n(t);return t.registerModule(s),Ii.add(e),!0}catch(s){return console.error(`\u274C [FreeLang] require "${r}" \uB85C\uB4DC \uC2E4\uD328:`,s),!1}}var tn=z(require("fs")),en=z(require("path")),Eu=z(require("os")),Mu=z(require("crypto")),Li=require("child_process");function Ir(r){let t=en.join(Eu.tmpdir(),"fl-images");return tn.existsSync(t)||tn.mkdirSync(t,{recursive:!0}),en.join(t,Mu.randomBytes(8).toString("hex")+r)}function Lr(r){let t=(0,Li.spawnSync)("convert",r,{timeout:3e4});if(t.error)throw new Error("ImageMagick not found: "+t.error.message);let e=t.stderr?.toString()??"";if(t.status!==0)throw new Error("ImageMagick error: "+e);return{ok:!0,stderr:e}}function wm(r){let t=(0,Li.spawnSync)("identify",["-format","%wx%h %m %b",r],{timeout:1e4}),e=new Map;if(t.status!==0)return e.set("width",0),e.set("height",0),e.set("format","unknown"),e.set("size",0),e.set("channels",3),e.set("has_alpha",!1),e;let s=(t.stdout?.toString().trim()??"").match(/^(\d+)x(\d+)\s+(\S+)\s+(.+)$/),a=tn.existsSync(r)?tn.statSync(r).size:0;return e.set("width",s?parseInt(s[1]):0),e.set("height",s?parseInt(s[2]):0),e.set("format",s?s[3].toLowerCase():"unknown"),e.set("size",a),e.set("channels",3),e.set("has_alpha",!1),e}function Ru(){return{image_info:r=>wm(r),image_resize:(r,t,e)=>{let n=en.extname(r)||".jpg",s=Ir(n);return Lr([r,"-resize",`${Math.floor(t)}x${Math.floor(e)}>`,s]),s},image_thumbnail:(r,t)=>{let e=Math.floor(t),n=Ir(".jpg");return Lr([r,"-thumbnail",`${e}x${e}^`,"-gravity","center","-extent",`${e}x${e}`,"-quality","85",n]),n},image_convert:(r,t)=>{let e=(t||"jpg").toLowerCase().replace("jpeg","jpg"),n=Ir("."+e);return Lr([r,"-quality","85",n]),n},image_watermark:(r,t)=>{let e=en.extname(r)||".jpg",n=Ir(e);return Lr([r,"-gravity","SouthEast","-fill","rgba(255,255,255,0.6)","-pointsize","24","-annotate","+10+10",t,n]),n},image_crop:(r,t,e,n,s)=>{let a=en.extname(r)||".jpg",i=Ir(a);return Lr([r,"-crop",`${Math.floor(n)}x${Math.floor(s)}+${Math.floor(t)}+${Math.floor(e)}`,"+repage",i]),i}}}var Bi={};on(Bi,{"Date.now":()=>_m,"JSON.parse":()=>Sm,"JSON.stringify":()=>xm,_comment:()=>Am,agent_broadcast:()=>$m,agent_history:()=>Em,agent_inbox_size:()=>Mm,agent_list:()=>Rm,agent_process:()=>Tm,agent_recv:()=>Cm,agent_send:()=>Nm,agent_spawn:()=>Om,array_length:()=>Fm,array_push:()=>Pm,assert_type:()=>jm,block_items:()=>Im,bson_decode_native:()=>Lm,bson_encode_native:()=>Bm,char_at:()=>Dm,char_code:()=>qm,cli_args:()=>Um,"console.log":()=>Vm,console_log:()=>zm,cosine_sim:()=>Wm,count:()=>Hm,ctx_add:()=>Gm,ctx_all:()=>Km,ctx_get:()=>Jm,ctx_new:()=>Xm,ctx_remove:()=>Ym,ctx_stats:()=>Qm,ctx_trim:()=>Zm,current_time_ms:()=>ed,db_query:()=>td,default:()=>Cy,dict:()=>nd,dir_list:()=>rd,dot_product:()=>sd,"ends-with?":()=>ad,env:()=>id,env_get:()=>od,euclidean_dist:()=>cd,fetch:()=>ld,file_append:()=>ud,file_mkdir:()=>pd,filter_lazy:()=>fd,first:()=>md,first_or:()=>dd,fl_concepts:()=>gd,fl_env_get:()=>hd,fl_example_count:()=>yd,fl_examples:()=>bd,fl_exec_op:()=>kd,fl_fix_env:()=>vd,fl_interp:()=>wd,fl_learn:()=>_d,fl_parse:()=>Sd,flat_map:()=>xd,"get-env":()=>Ad,get_env:()=>$d,get_or:()=>Ed,head:()=>Md,html_response:()=>Rd,http_get:()=>Td,http_post:()=>Cd,includes:()=>Nd,index_of:()=>Od,is_array:()=>Fd,is_nil:()=>Pd,is_null:()=>jd,is_number:()=>Id,is_string:()=>Ld,json_keys:()=>Bd,json_response:()=>Dd,last_or:()=>qd,lazy_head:()=>Ud,lazy_seq:()=>Vd,lazy_tail:()=>zd,list_append:()=>Wd,list_tools:()=>Hd,listen:()=>Gd,log:()=>Kd,lower_case:()=>Jd,map_entries:()=>Xd,map_err:()=>Yd,map_lazy:()=>Qd,map_ok:()=>Zd,map_set:()=>eg,"mariadb-batch":()=>wy,"mariadb-databases":()=>Ry,"mariadb-exec":()=>yy,"mariadb-health":()=>My,"mariadb-one":()=>ky,"mariadb-pool-close":()=>Ey,"mariadb-pool-connect":()=>_y,"mariadb-pool-exec":()=>Ay,"mariadb-pool-one":()=>xy,"mariadb-pool-query":()=>Sy,"mariadb-pool-transaction":()=>$y,"mariadb-query":()=>by,"mariadb-tables":()=>Ty,"mariadb-transaction":()=>vy,mariadb_all:()=>tg,math_abs:()=>ng,math_pow:()=>rg,math_sqrt:()=>sg,maybe_bind:()=>ag,maybe_chain:()=>ig,maybe_combine:()=>og,maybe_filter:()=>cg,maybe_map:()=>lg,maybe_select:()=>ug,mem_episode:()=>pg,mem_forget:()=>fg,mem_keys:()=>mg,mem_purge:()=>dg,mem_recall:()=>gg,mem_remember:()=>hg,mem_remember_short:()=>yg,mem_search_episodes:()=>bg,mem_search_tag:()=>kg,mem_stats:()=>vg,mem_working_clear:()=>wg,mem_working_get:()=>_g,mem_working_set:()=>Sg,merge:()=>xg,net_connect:()=>Ag,net_sendrecv:()=>$g,net_sendrecv_pool:()=>Eg,"now-ms":()=>Mg,now_iso:()=>Rg,"null?":()=>Tg,num_to_str:()=>Cg,obj_merge:()=>Ng,obj_omit:()=>Og,obj_pick:()=>Fg,object_keys:()=>Pg,omit:()=>jg,panic:()=>Ig,parseInt:()=>Lg,parse_int:()=>Bg,parse_json:()=>Dg,print:()=>qg,print_err:()=>Ug,prompt_compile:()=>Vg,prompt_from_code:()=>zg,prompt_target:()=>Wg,prompt_tokens:()=>Hg,pure_writer:()=>Gg,push:()=>Kg,quality_check:()=>Jg,quality_feedback:()=>Xg,rag_add:()=>Yg,rag_query:()=>Qg,rag_remove:()=>Zg,rag_retrieve:()=>eh,rag_size:()=>th,raise:()=>nh,read_file:()=>rh,result_classify:()=>sh,result_explain:()=>ah,return_writer:()=>ih,sdk_features:()=>oh,sdk_snippet:()=>ch,sdk_supports:()=>lh,sdk_validate:()=>uh,sdk_version:()=>ph,server_listen:()=>fh,server_run:()=>mh,server_uptime:()=>dh,set_timeout:()=>gh,shell_exec:()=>hh,shell_exec_result:()=>yh,size:()=>bh,sort_by:()=>kh,split:()=>vh,"starts-with?":()=>wh,str_char_at:()=>_h,str_concat:()=>Sh,str_join:()=>xh,str_length:()=>Ah,str_split:()=>$h,str_to_int:()=>Eh,str_to_num:()=>Mh,stream_chunk_count:()=>Rh,stream_chunks:()=>Th,stream_collect:()=>Ch,stream_create:()=>Nh,stream_delete:()=>Oh,stream_end:()=>Fh,stream_text:()=>Ph,stream_write:()=>jh,string_length:()=>Ih,stringify:()=>Lh,take_while:()=>Bh,throw:()=>Dh,"to-lower":()=>qh,"to-upper":()=>Uh,toString:()=>Vh,to_hex:()=>zh,to_str:()=>Wh,to_string:()=>Hh,trace_add:()=>Gh,trace_create:()=>Kh,trace_enter:()=>Jh,trace_exit:()=>Xh,trace_markdown:()=>Yh,trace_node_count:()=>Qh,trace_tree:()=>Zh,trim:()=>ey,try_reason:()=>ty,try_with_fallback:()=>ny,type_of:()=>ry,unwrap_or:()=>sy,upper_case:()=>ay,use_tool:()=>iy,vec_add:()=>oy,vec_dist:()=>cy,vec_dot:()=>ly,vec_magnitude:()=>uy,vec_norm:()=>py,vec_normalize:()=>fy,vec_scale:()=>my,vec_top_k:()=>dy,write_file:()=>gy,zip_with:()=>hy});var _m={correct:"now-ms",usage:"(now-ms)",mistake:"#37"},Sm={correct:"json_parse",usage:"(json_parse s)",mistake:"#44"},xm={correct:"json_stringify",usage:"(json_stringify x)",mistake:"#45"},Am="FreeLang v11 \uD568\uC218\uBA85 \uBCC4\uCE6D \u2014 wrapper(bin/freelang-smart)\uC640 stdlib-helpers\uAC00 \uACF5\uC720. MISTAKES-100 \uB9E4\uD551 \uBA85\uC2DC.",$m={correct:"agent-broadcast",usage:"(agent-broadcast ...)",mistake:"Phase X-2"},Em={correct:"agent-history",usage:"(agent-history ...)",mistake:"Phase X-2"},Mm={correct:"agent-inbox-size",usage:"(agent-inbox-size ...)",mistake:"Phase X-2"},Rm={correct:"agent-list",usage:"(agent-list ...)",mistake:"Phase X-2"},Tm={correct:"agent-process",usage:"(agent-process ...)",mistake:"Phase X-2"},Cm={correct:"agent-recv",usage:"(agent-recv ...)",mistake:"Phase X-2"},Nm={correct:"agent-send",usage:"(agent-send ...)",mistake:"Phase X-2"},Om={correct:"agent-spawn",usage:"(agent-spawn ...)",mistake:"Phase X-2"},Fm={correct:"length",usage:"(length arr)",mistake:"#42"},Pm={correct:"append",usage:"(append arr item)",mistake:null},jm={correct:"assert-type",usage:"(assert-type ...)",mistake:"Phase X-2"},Im={correct:"block-items",usage:"(block-items ...)",mistake:"Phase X-2"},Lm={correct:"bson-decode-native",usage:"(bson-decode-native ...)",mistake:"Phase X-2"},Bm={correct:"bson-encode-native",usage:"(bson-encode-native ...)",mistake:"Phase X-2"},Dm={correct:"char-at",usage:"(char-at ...)",mistake:"Phase X-2"},qm={correct:"char-code",usage:"(char-code ...)",mistake:"Phase X-2"},Um={correct:"cli-args",usage:"(cli-args ...)",mistake:"Phase X-2"},Vm={correct:"println",usage:"(println value)",mistake:"#35"},zm={correct:"println",usage:"(println value)",mistake:"#35"},Wm={correct:"cosine-sim",usage:"(cosine-sim ...)",mistake:"Phase X-2"},Hm={correct:"length",usage:"(length arr)",mistake:"#42"},Gm={correct:"ctx-add",usage:"(ctx-add ...)",mistake:"Phase X-2"},Km={correct:"ctx-all",usage:"(ctx-all ...)",mistake:"Phase X-2"},Jm={correct:"ctx-get",usage:"(ctx-get ...)",mistake:"Phase X-2"},Xm={correct:"ctx-new",usage:"(ctx-new ...)",mistake:"Phase X-2"},Ym={correct:"ctx-remove",usage:"(ctx-remove ...)",mistake:"Phase X-2"},Qm={correct:"ctx-stats",usage:"(ctx-stats ...)",mistake:"Phase X-2"},Zm={correct:"ctx-trim",usage:"(ctx-trim ...)",mistake:"Phase X-2"},ed={correct:"now-ms",usage:"(now-ms)",mistake:"#37"},td={correct:"mariadb_query",usage:"(mariadb_query db sql params)",mistake:"#38"},nd={correct:"map-set",usage:'(map-set {} "k" v)',mistake:null},rd={correct:"dir-list",usage:"(dir-list ...)",mistake:"Phase X-2"},sd={correct:"dot-product",usage:"(dot-product ...)",mistake:"Phase X-2"},ad={correct:"str-ends-with",usage:"(str-ends-with s suffix)",mistake:"#79"},id={correct:"shell_env",usage:'(shell_env "KEY")',mistake:"#32"},od={correct:"shell_env",usage:'(shell_env "KEY")',mistake:"#32"},cd={correct:"euclidean-dist",usage:"(euclidean-dist ...)",mistake:"Phase X-2"},ld={correct:"http_get",usage:"(http_get url)",mistake:null},ud={correct:"file-append",usage:"(file-append ...)",mistake:"Phase X-2"},pd={correct:"file-mkdir",usage:"(file-mkdir ...)",mistake:"Phase X-2"},fd={correct:"filter-lazy",usage:"(filter-lazy ...)",mistake:"Phase X-2"},md={correct:"get",usage:"(get arr 0)",mistake:null},dd={correct:"first-or",usage:"(first-or ...)",mistake:"Phase X-2"},gd={correct:"fl-concepts",usage:"(fl-concepts ...)",mistake:"Phase X-2"},hd={correct:"fl-env-get",usage:"(fl-env-get ...)",mistake:"Phase X-2"},yd={correct:"fl-example-count",usage:"(fl-example-count ...)",mistake:"Phase X-2"},bd={correct:"fl-examples",usage:"(fl-examples ...)",mistake:"Phase X-2"},kd={correct:"fl-exec-op",usage:"(fl-exec-op ...)",mistake:"Phase X-2"},vd={correct:"fl-fix-env",usage:"(fl-fix-env ...)",mistake:"Phase X-2"},wd={correct:"fl-interp",usage:"(fl-interp ...)",mistake:"Phase X-2"},_d={correct:"fl-learn",usage:"(fl-learn ...)",mistake:"Phase X-2"},Sd={correct:"fl-parse",usage:"(fl-parse ...)",mistake:"Phase X-2"},xd={correct:"flat-map",usage:"(flat-map ...)",mistake:"Phase X-2"},Ad={correct:"shell_env",usage:'(shell_env "KEY")',mistake:"#32"},$d={correct:"shell_env",usage:'(shell_env "KEY")',mistake:"#32"},Ed={correct:"get-or",usage:"(get-or ...)",mistake:"Phase X-2"},Md={correct:"get",usage:"(get arr 0)",mistake:null},Rd={correct:"html-response",usage:"(html-response ...)",mistake:"Phase X-2"},Td={correct:"http-get",usage:"(http-get ...)",mistake:"Phase X-2"},Cd={correct:"http_get",usage:'(http_get url {:method "POST"})',mistake:null},Nd={correct:"str-contains",usage:"(str-contains s pattern)",mistake:"#80"},Od={correct:"index-of",usage:"(index-of ...)",mistake:"Phase X-2"},Fd={correct:"array?",usage:"(array? value)",mistake:null},Pd={correct:"nil?",usage:"(nil? value)",mistake:"#55"},jd={correct:"nil?",usage:"(nil? value)",mistake:"#55"},Id={correct:"number?",usage:"(number? value)",mistake:null},Ld={correct:"string?",usage:"(string? value)",mistake:null},Bd={correct:"keys",usage:"(keys m)",mistake:"#36"},Dd={correct:"json-response",usage:"(json-response ...)",mistake:"Phase X-2"},qd={correct:"last-or",usage:"(last-or ...)",mistake:"Phase X-2"},Ud={correct:"lazy-head",usage:"(lazy-head ...)",mistake:"Phase X-2"},Vd={correct:"lazy-seq",usage:"(lazy-seq ...)",mistake:"Phase X-2"},zd={correct:"lazy-tail",usage:"(lazy-tail ...)",mistake:"Phase X-2"},Wd={correct:"append",usage:"(append arr item)",mistake:null},Hd={correct:"list-tools",usage:"(list-tools ...)",mistake:"Phase X-2"},Gd={correct:"server_start",usage:"(server_start 40000)",mistake:"#33"},Kd={correct:"println",usage:"(println value)",mistake:"#35"},Jd={correct:"lower-case",usage:"(lower-case ...)",mistake:"Phase X-2"},Xd={correct:"map-entries",usage:"(map-entries ...)",mistake:"Phase X-2"},Yd={correct:"map-err",usage:"(map-err ...)",mistake:"Phase X-2"},Qd={correct:"map-lazy",usage:"(map-lazy ...)",mistake:"Phase X-2"},Zd={correct:"map-ok",usage:"(map-ok ...)",mistake:"Phase X-2"},eg={correct:"map-set",usage:"(map-set ...)",mistake:"Phase X-2"},tg={correct:"mariadb_query",usage:"(mariadb_query db sql params)",mistake:"#38"},ng={correct:"math-abs",usage:"(math-abs ...)",mistake:"Phase X-2"},rg={correct:"math-pow",usage:"(math-pow ...)",mistake:"Phase X-2"},sg={correct:"math-sqrt",usage:"(math-sqrt ...)",mistake:"Phase X-2"},ag={correct:"maybe-bind",usage:"(maybe-bind ...)",mistake:"Phase X-2"},ig={correct:"maybe-chain",usage:"(maybe-chain ...)",mistake:"Phase X-2"},og={correct:"maybe-combine",usage:"(maybe-combine ...)",mistake:"Phase X-2"},cg={correct:"maybe-filter",usage:"(maybe-filter ...)",mistake:"Phase X-2"},lg={correct:"maybe-map",usage:"(maybe-map ...)",mistake:"Phase X-2"},ug={correct:"maybe-select",usage:"(maybe-select ...)",mistake:"Phase X-2"},pg={correct:"mem-episode",usage:"(mem-episode ...)",mistake:"Phase X-2"},fg={correct:"mem-forget",usage:"(mem-forget ...)",mistake:"Phase X-2"},mg={correct:"mem-keys",usage:"(mem-keys ...)",mistake:"Phase X-2"},dg={correct:"mem-purge",usage:"(mem-purge ...)",mistake:"Phase X-2"},gg={correct:"mem-recall",usage:"(mem-recall ...)",mistake:"Phase X-2"},hg={correct:"mem-remember",usage:"(mem-remember ...)",mistake:"Phase X-2"},yg={correct:"mem-remember-short",usage:"(mem-remember-short ...)",mistake:"Phase X-2"},bg={correct:"mem-search-episodes",usage:"(mem-search-episodes ...)",mistake:"Phase X-2"},kg={correct:"mem-search-tag",usage:"(mem-search-tag ...)",mistake:"Phase X-2"},vg={correct:"mem-stats",usage:"(mem-stats ...)",mistake:"Phase X-2"},wg={correct:"mem-working-clear",usage:"(mem-working-clear ...)",mistake:"Phase X-2"},_g={correct:"mem-working-get",usage:"(mem-working-get ...)",mistake:"Phase X-2"},Sg={correct:"mem-working-set",usage:"(mem-working-set ...)",mistake:"Phase X-2"},xg={correct:"assoc",usage:'(assoc m "k" v) ;; \uD0A4\uBCC4\uB85C',mistake:"#39"},Ag={correct:"net-connect",usage:"(net-connect ...)",mistake:"Phase X-2"},$g={correct:"net-sendrecv",usage:"(net-sendrecv ...)",mistake:"Phase X-2"},Eg={correct:"net-sendrecv-pool",usage:"(net-sendrecv-pool ...)",mistake:"Phase X-2"},Mg={correct:"now-ms",usage:"(now-ms)",mistake:"#37"},Rg={correct:"now-iso",usage:"(now-iso ...)",mistake:"Phase X-2"},Tg={correct:"nil?",usage:"(nil? value)",mistake:"#55"},Cg={correct:"str",usage:"(str 42)",mistake:"#57"},Ng={correct:"assoc",usage:'(assoc m "k" v) ;; \uD0A4\uBCC4\uB85C',mistake:"#39"},Og={correct:"dissoc",usage:'(dissoc m "k")',mistake:"#40"},Fg={correct:"get",usage:'(get m "k") ;; \uAC1C\uBCC4 \uD0A4 \uC811\uADFC',mistake:"#41"},Pg={correct:"keys",usage:"(keys m)",mistake:"#36"},jg={correct:"dissoc",usage:'(dissoc m "k")',mistake:"#40"},Ig={correct:"error",usage:'(error "msg")',mistake:"#90"},Lg={correct:"str_to_num",usage:'(str_to_num "42")',mistake:"#34"},Bg={correct:"str_to_num",usage:'(str_to_num "42")',mistake:"#34"},Dg={correct:"json_parse",usage:"(json_parse s)",mistake:"#44"},qg={correct:"println",usage:"(println value)",mistake:"#35"},Ug={correct:"print-err",usage:"(print-err ...)",mistake:"Phase X-2"},Vg={correct:"prompt-compile",usage:"(prompt-compile ...)",mistake:"Phase X-2"},zg={correct:"prompt-from-code",usage:"(prompt-from-code ...)",mistake:"Phase X-2"},Wg={correct:"prompt-target",usage:"(prompt-target ...)",mistake:"Phase X-2"},Hg={correct:"prompt-tokens",usage:"(prompt-tokens ...)",mistake:"Phase X-2"},Gg={correct:"pure-writer",usage:"(pure-writer ...)",mistake:"Phase X-2"},Kg={correct:"append",usage:"(append arr item)",mistake:null},Jg={correct:"quality-check",usage:"(quality-check ...)",mistake:"Phase X-2"},Xg={correct:"quality-feedback",usage:"(quality-feedback ...)",mistake:"Phase X-2"},Yg={correct:"rag-add",usage:"(rag-add ...)",mistake:"Phase X-2"},Qg={correct:"rag-query",usage:"(rag-query ...)",mistake:"Phase X-2"},Zg={correct:"rag-remove",usage:"(rag-remove ...)",mistake:"Phase X-2"},eh={correct:"rag-retrieve",usage:"(rag-retrieve ...)",mistake:"Phase X-2"},th={correct:"rag-size",usage:"(rag-size ...)",mistake:"Phase X-2"},nh={correct:"error",usage:'(error "msg")',mistake:"#90"},rh={correct:"read-file",usage:"(read-file ...)",mistake:"Phase X-2"},sh={correct:"result-classify",usage:"(result-classify ...)",mistake:"Phase X-2"},ah={correct:"result-explain",usage:"(result-explain ...)",mistake:"Phase X-2"},ih={correct:"return-writer",usage:"(return-writer ...)",mistake:"Phase X-2"},oh={correct:"sdk-features",usage:"(sdk-features ...)",mistake:"Phase X-2"},ch={correct:"sdk-snippet",usage:"(sdk-snippet ...)",mistake:"Phase X-2"},lh={correct:"sdk-supports",usage:"(sdk-supports ...)",mistake:"Phase X-2"},uh={correct:"sdk-validate",usage:"(sdk-validate ...)",mistake:"Phase X-2"},ph={correct:"sdk-version",usage:"(sdk-version ...)",mistake:"Phase X-2"},fh={correct:"server_start",usage:"(server_start 40000)",mistake:"#33"},mh={correct:"server_start",usage:"(server_start 40000)",mistake:"#33"},dh={correct:"server-uptime",usage:"(server-uptime ...)",mistake:"Phase X-2"},gh={correct:"set-timeout",usage:"(set-timeout ...)",mistake:"Phase X-2"},hh={correct:"shell-exec",usage:"(shell-exec ...)",mistake:"Phase X-2"},yh={correct:"shell-exec-result",usage:"(shell-exec-result ...)",mistake:"Phase X-2"},bh={correct:"length",usage:"(length arr)",mistake:"#42"},kh={correct:"sort-by",usage:"(sort-by ...)",mistake:"Phase X-2"},vh={correct:"str-split",usage:'(str-split s ",")',mistake:"#43"},wh={correct:"str-starts-with",usage:"(str-starts-with s prefix)",mistake:"#79"},_h={correct:"str-char-at",usage:"(str-char-at ...)",mistake:"Phase X-2"},Sh={correct:"str",usage:'(str "a" "b")',mistake:null},xh={correct:"str-join",usage:"(str-join ...)",mistake:"Phase X-2"},Ah={correct:"str-length",usage:'(str-length "hello")',mistake:"#77"},$h={correct:"str-split",usage:'(str-split s ",")',mistake:"#43"},Eh={correct:"str_to_num",usage:'(str_to_num "42")',mistake:"#34"},Mh={correct:"str-to-num",usage:"(str-to-num ...)",mistake:"Phase X-2"},Rh={correct:"stream-chunk-count",usage:"(stream-chunk-count ...)",mistake:"Phase X-2"},Th={correct:"stream-chunks",usage:"(stream-chunks ...)",mistake:"Phase X-2"},Ch={correct:"stream-collect",usage:"(stream-collect ...)",mistake:"Phase X-2"},Nh={correct:"stream-create",usage:"(stream-create ...)",mistake:"Phase X-2"},Oh={correct:"stream-delete",usage:"(stream-delete ...)",mistake:"Phase X-2"},Fh={correct:"stream-end",usage:"(stream-end ...)",mistake:"Phase X-2"},Ph={correct:"stream-text",usage:"(stream-text ...)",mistake:"Phase X-2"},jh={correct:"stream-write",usage:"(stream-write ...)",mistake:"Phase X-2"},Ih={correct:"str-length",usage:'(str-length "hello")',mistake:"#77"},Lh={correct:"json_stringify",usage:"(json_stringify x)",mistake:"#45"},Bh={correct:"take-while",usage:"(take-while ...)",mistake:"Phase X-2"},Dh={correct:"error",usage:'(error "msg")',mistake:"#90"},qh={correct:"str-lower",usage:"(str-lower s)",mistake:"#81"},Uh={correct:"str-upper",usage:"(str-upper s)",mistake:"#81"},Vh={correct:"str",usage:"(str value)",mistake:"#82"},zh={correct:"to-hex",usage:"(to-hex ...)",mistake:"Phase X-2"},Wh={correct:"str",usage:"(str value)",mistake:"#82"},Hh={correct:"str",usage:"(str value)",mistake:"#82"},Gh={correct:"trace-add",usage:"(trace-add ...)",mistake:"Phase X-2"},Kh={correct:"trace-create",usage:"(trace-create ...)",mistake:"Phase X-2"},Jh={correct:"trace-enter",usage:"(trace-enter ...)",mistake:"Phase X-2"},Xh={correct:"trace-exit",usage:"(trace-exit ...)",mistake:"Phase X-2"},Yh={correct:"trace-markdown",usage:"(trace-markdown ...)",mistake:"Phase X-2"},Qh={correct:"trace-node-count",usage:"(trace-node-count ...)",mistake:"Phase X-2"},Zh={correct:"trace-tree",usage:"(trace-tree ...)",mistake:"Phase X-2"},ey={correct:"str-trim",usage:'(str-trim " x ")',mistake:"#78"},ty={correct:"try-reason",usage:"(try-reason ...)",mistake:"Phase X-2"},ny={correct:"try-with-fallback",usage:"(try-with-fallback ...)",mistake:"Phase X-2"},ry={correct:"type-of",usage:"(type-of ...)",mistake:"Phase X-2"},sy={correct:"unwrap-or",usage:"(unwrap-or ...)",mistake:"Phase X-2"},ay={correct:"upper-case",usage:"(upper-case ...)",mistake:"Phase X-2"},iy={correct:"use-tool",usage:"(use-tool ...)",mistake:"Phase X-2"},oy={correct:"vec-add",usage:"(vec-add ...)",mistake:"Phase X-2"},cy={correct:"vec-dist",usage:"(vec-dist ...)",mistake:"Phase X-2"},ly={correct:"vec-dot",usage:"(vec-dot ...)",mistake:"Phase X-2"},uy={correct:"vec-magnitude",usage:"(vec-magnitude ...)",mistake:"Phase X-2"},py={correct:"vec-norm",usage:"(vec-norm ...)",mistake:"Phase X-2"},fy={correct:"vec-normalize",usage:"(vec-normalize ...)",mistake:"Phase X-2"},my={correct:"vec-scale",usage:"(vec-scale ...)",mistake:"Phase X-2"},dy={correct:"vec-top-k",usage:"(vec-top-k ...)",mistake:"Phase X-2"},gy={correct:"write-file",usage:"(write-file ...)",mistake:"Phase X-2"},hy={correct:"zip-with",usage:"(zip-with ...)",mistake:"Phase X-2"},yy={correct:"mariadb_exec",usage:"(mariadb_exec db sql params)",mistake:"P6"},by={correct:"mariadb_query",usage:"(mariadb_query db sql params)",mistake:"P6"},ky={correct:"mariadb_one",usage:"(mariadb_one db sql params)",mistake:"P6"},vy={correct:"mariadb_transaction",usage:"(mariadb_transaction db stmts)",mistake:"P6"},wy={correct:"mariadb_batch",usage:"(mariadb_batch db queries)",mistake:"P6"},_y={correct:"mariadb_pool_connect",usage:"(mariadb_pool_connect config)",mistake:"P6"},Sy={correct:"mariadb_pool_query",usage:"(mariadb_pool_query poolId sql params)",mistake:"P6"},xy={correct:"mariadb_pool_one",usage:"(mariadb_pool_one poolId sql params)",mistake:"P6"},Ay={correct:"mariadb_pool_exec",usage:"(mariadb_pool_exec poolId sql params)",mistake:"P6"},$y={correct:"mariadb_pool_transaction",usage:"(mariadb_pool_transaction poolId stmts)",mistake:"P6"},Ey={correct:"mariadb_pool_close",usage:"(mariadb_pool_close poolId)",mistake:"P6"},My={correct:"mariadb_health",usage:"(mariadb_health)",mistake:"P6"},Ry={correct:"mariadb_databases",usage:"(mariadb_databases)",mistake:"P6"},Ty={correct:"mariadb_tables",usage:"(mariadb_tables db)",mistake:"P6"},Cy={"Date.now":_m,"JSON.parse":Sm,"JSON.stringify":xm,_comment:Am,agent_broadcast:$m,agent_history:Em,agent_inbox_size:Mm,agent_list:Rm,agent_process:Tm,agent_recv:Cm,agent_send:Nm,agent_spawn:Om,array_length:Fm,array_push:Pm,assert_type:jm,block_items:Im,bson_decode_native:Lm,bson_encode_native:Bm,char_at:Dm,char_code:qm,cli_args:Um,"console.log":Vm,console_log:zm,cosine_sim:Wm,count:Hm,ctx_add:Gm,ctx_all:Km,ctx_get:Jm,ctx_new:Xm,ctx_remove:Ym,ctx_stats:Qm,ctx_trim:Zm,current_time_ms:ed,db_query:td,dict:nd,dir_list:rd,dot_product:sd,"ends-with?":ad,env:id,env_get:od,euclidean_dist:cd,fetch:ld,file_append:ud,file_mkdir:pd,filter_lazy:fd,first:md,first_or:dd,fl_concepts:gd,fl_env_get:hd,fl_example_count:yd,fl_examples:bd,fl_exec_op:kd,fl_fix_env:vd,fl_interp:wd,fl_learn:_d,fl_parse:Sd,flat_map:xd,"get-env":Ad,get_env:$d,get_or:Ed,head:Md,html_response:Rd,http_get:Td,http_post:Cd,includes:Nd,index_of:Od,is_array:Fd,is_nil:Pd,is_null:jd,is_number:Id,is_string:Ld,json_keys:Bd,json_response:Dd,last_or:qd,lazy_head:Ud,lazy_seq:Vd,lazy_tail:zd,list_append:Wd,list_tools:Hd,listen:Gd,log:Kd,lower_case:Jd,map_entries:Xd,map_err:Yd,map_lazy:Qd,map_ok:Zd,map_set:eg,mariadb_all:tg,math_abs:ng,math_pow:rg,math_sqrt:sg,maybe_bind:ag,maybe_chain:ig,maybe_combine:og,maybe_filter:cg,maybe_map:lg,maybe_select:ug,mem_episode:pg,mem_forget:fg,mem_keys:mg,mem_purge:dg,mem_recall:gg,mem_remember:hg,mem_remember_short:yg,mem_search_episodes:bg,mem_search_tag:kg,mem_stats:vg,mem_working_clear:wg,mem_working_get:_g,mem_working_set:Sg,merge:xg,net_connect:Ag,net_sendrecv:$g,net_sendrecv_pool:Eg,"now-ms":Mg,now_iso:Rg,"null?":Tg,num_to_str:Cg,obj_merge:Ng,obj_omit:Og,obj_pick:Fg,object_keys:Pg,omit:jg,panic:Ig,parseInt:Lg,parse_int:Bg,parse_json:Dg,print:qg,print_err:Ug,prompt_compile:Vg,prompt_from_code:zg,prompt_target:Wg,prompt_tokens:Hg,pure_writer:Gg,push:Kg,quality_check:Jg,quality_feedback:Xg,rag_add:Yg,rag_query:Qg,rag_remove:Zg,rag_retrieve:eh,rag_size:th,raise:nh,read_file:rh,result_classify:sh,result_explain:ah,return_writer:ih,sdk_features:oh,sdk_snippet:ch,sdk_supports:lh,sdk_validate:uh,sdk_version:ph,server_listen:fh,server_run:mh,server_uptime:dh,set_timeout:gh,shell_exec:hh,shell_exec_result:yh,size:bh,sort_by:kh,split:vh,"starts-with?":wh,str_char_at:_h,str_concat:Sh,str_join:xh,str_length:Ah,str_split:$h,str_to_int:Eh,str_to_num:Mh,stream_chunk_count:Rh,stream_chunks:Th,stream_collect:Ch,stream_create:Nh,stream_delete:Oh,stream_end:Fh,stream_text:Ph,stream_write:jh,string_length:Ih,stringify:Lh,take_while:Bh,throw:Dh,"to-lower":qh,"to-upper":Uh,toString:Vh,to_hex:zh,to_str:Wh,to_string:Hh,trace_add:Gh,trace_create:Kh,trace_enter:Jh,trace_exit:Xh,trace_markdown:Yh,trace_node_count:Qh,trace_tree:Zh,trim:ey,try_reason:ty,try_with_fallback:ny,type_of:ry,unwrap_or:sy,upper_case:ay,use_tool:iy,vec_add:oy,vec_dist:cy,vec_dot:ly,vec_magnitude:uy,vec_norm:py,vec_normalize:fy,vec_scale:my,vec_top_k:dy,write_file:gy,zip_with:hy,"mariadb-exec":yy,"mariadb-query":by,"mariadb-one":ky,"mariadb-transaction":vy,"mariadb-batch":wy,"mariadb-pool-connect":_y,"mariadb-pool-query":Sy,"mariadb-pool-one":xy,"mariadb-pool-exec":Ay,"mariadb-pool-transaction":$y,"mariadb-pool-close":Ey,"mariadb-health":My,"mariadb-databases":Ry,"mariadb-tables":Ty};var Gs={};for(let[r,t]of Object.entries(Bi))r.startsWith("_")||(Gs[r]=t);function Ny(r,t){let e=r.length,n=t.length;if(e===0)return n;if(n===0)return e;let s=Array.from({length:e+1},(a,i)=>Array.from({length:n+1},(o,u)=>i===0?u:u===0?i:0));for(let a=1;a<=e;a++)for(let i=1;i<=n;i++)s[a][i]=r[a-1]===t[i-1]?s[a-1][i-1]:1+Math.min(s[a-1][i],s[a][i-1],s[a-1][i-1]);return s[e][n]}var Oy=["println","print","map","filter","reduce","append","get","assoc","dissoc","str","length","nil?","if","cond","let","do","defn","fn","define","server_start","server_get","server_post","server_put","server_delete","server_json","server_html","server_text","server_status","server_redirect","mariadb_connect","mariadb_query","mariadb_one","mariadb_exec","http_get","json_parse","json_stringify","file_read","file_write","file_exists","auth_jwt_sign","auth_jwt_verify","auth_hash_password"];function Tu(r,t=Oy,e=3){return t.map(s=>({name:s,dist:Ny(r,s)})).filter(s=>s.dist<=Math.max(2,Math.floor(r.length/3))).sort((s,a)=>s.dist-a.dist).slice(0,e).map(s=>s.name)}var Dn=r=>typeof r=="function"||r!==null&&typeof r=="object"&&r.kind==="function-value",Hs=r=>Array.isArray(r),Cu=r=>r instanceof Map||r!==null&&typeof r=="object"&&!Array.isArray(r)&&r.kind!=="function-value",Nu=r=>Array.isArray(r)||r instanceof Map||r!==null&&typeof r=="object"&&r.kind!=="function-value",Ou=r=>r!==!1&&r!==null&&r!==void 0&&r!==0&&r!=="";function qn(r,t,e){if(typeof r=="function")return r(...t);if(e)return e(r,t);throw new Error("\uD638\uCD9C \uAC00\uB2A5\uD55C \uD568\uC218\uAC00 \uC544\uB2D9\uB2C8\uB2E4")}function Di(r){return r==null?null:r instanceof Map?r.get("body"):typeof r=="object"?r.body:r}function qi(r){return r==null?0:r instanceof Map?Number(r.get("status")||0):typeof r=="object"?Number(r.status||0):0}function Ui(r){if(typeof r!="string")return r;try{return JSON.parse(r)}catch{return r}}function Fu(r){return{_tag:"Ok",value:r}}function Pu(r,t="E_TRY_CALL",e="runtime-error"){return{_tag:"Err",code:t,message:r,category:e,recoverable:!0}}function ju(r,t,e){let n=r,s=h=>{let y=Gs[h];return y?[y.correct]:Tu(h)},a=h=>{let y=Gs[h];if(!y)return null;let k=new Map;return k.set("correct",y.correct),k.set("usage",y.usage),k},i=h=>{let y=Gs[h];if(y)return`'${h}'\uC740(\uB294) \uC5C6\uC2B5\uB2C8\uB2E4. \uB300\uC2E0 ${y.correct} \uC0AC\uC6A9: ${y.usage}`;let k=Tu(h);return k.length>0?`'${h}'\uC744 \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4. \uD639\uC2DC: ${k.join(", ")} ?`:`'${h}'\uC5D0 \uB300\uD55C \uC815\uBCF4\uAC00 \uC5C6\uC2B5\uB2C8\uB2E4.`},o=(h,y)=>{if(Dn(h)&&Hs(y))return y.map(k=>qn(h,[k],n));if(Hs(h)&&Dn(y))return h.map(k=>qn(y,[k],n));throw new Error("smart-map: [fn, arr] \uB610\uB294 [arr, fn]")},u=(h,y)=>{if(Dn(h)&&Hs(y))return y.filter(k=>Ou(qn(h,[k],n)));if(Hs(h)&&Dn(y))return h.filter(k=>Ou(qn(y,[k],n)));throw new Error("smart-filter: [fn, arr] \uB610\uB294 [arr, fn]")},f=(h,y)=>{if(Nu(h)&&!Dn(h))return h instanceof Map?h.get(y):(Array.isArray(h),h[y]);if(Nu(y)&&!Dn(y))return y instanceof Map?y.get(h):(Array.isArray(y),y[h]);throw new Error("smart-get: \uCEEC\uB809\uC158\uACFC \uD0A4\uAC00 \uD544\uC694\uD569\uB2C8\uB2E4")},l=(h,y,k)=>{if(Cu(h)){if(h instanceof Map){let v=new Map(h);return v.set(y,k),v}return{...h,[y]:k}}if(Cu(k)){if(k instanceof Map){let v=new Map(k);return v.set(h,y),v}return{...k,[h]:y}}throw new Error("smart-assoc: map + key + value")},c=(h,y)=>{if(!t)throw new Error("http-get-json: http_get \uBBF8\uC5F0\uACB0");let k=t(h,y);return Ui(Di(k))},p=(h,y)=>{let k=typeof y=="string"?y:JSON.stringify(y);if(e){let M=e(h,k);return{status:qi(M),data:Ui(Di(M))}}if(!t)throw new Error("http-post-json: http_post/http_get \uBBF8\uC5F0\uACB0");let $=t(h,{method:"POST",headers:{"Content-Type":"application/json"},body:k});return{status:qi($),data:Ui(Di($))}},m=(h,y)=>{if(!t)throw new Error("http-status: http_get \uBBF8\uC5F0\uACB0");let k=t(h,y);return qi(k)},d=h=>{try{return Fu(qn(h,[],n))}catch(y){return Pu(y?.message||String(y))}},g=(h,y)=>{try{return Fu(qn(h,[y],n))}catch(k){return Pu(k?.message||String(k))}};return{"suggest-fn":s,suggest_fn:s,"alias-of":a,alias_of:a,"help-text":i,help_text:i,"smart-map":o,smart_map:o,"smart-filter":u,smart_filter:u,"smart-get":f,smart_get:f,"smart-assoc":l,smart_assoc:l,"http-status":m,http_status:m,"try-call":d,try_call:d,"try-call-1":g,try_call_1:g}}var Fy=new Set(["define","fn","defn","if","cond","let","do","match","try","catch","finally","throw","loop","recur","set!","swap!","reset!","deref","atom","and","or","not","+","-","*","/","<",">","<=",">=","=","!="]),Py=new Set(["file_exists","file_is_dir","fl_require"]);function jy(r,t){if(Fy.has(r)||!r.includes("_"))return!1;let e=Iu(r);return!(e===r||t.has(e))}function Iu(r){return r.replace(/_/g,"-")}function Lu(r){let t={},e=new Set;for(let s of r)if(s)for(let a of Object.keys(s))e.add(a);let n=0;for(let s of r)if(s)for(let[a,i]of Object.entries(s)){if(typeof i!="function"||!jy(a,e))continue;let o=Iu(a);if(t[o]||(t[o]=i,e.add(o),n++),Py.has(a)){let u=o+"?";!t[u]&&!e.has(u)&&(t[u]=i,e.add(u),n++)}}return process.env.FL_DEBUG_KEBAB&&console.error(`[kebab-aliases] +${n} (\uC608: ${Object.keys(t).slice(0,5).join(", ")} ...)`),t}function Bu(r){let t=Zc(),e=el(),n=tl(),s=sl(),a=ol();r.registerModule(t),r.registerModule(e),r.registerModule(n),r.registerModule(rl(r)),r.registerModule(s),r.registerModule(a);let i=cl(),o=ll(),u=ul(),f=_s(),l=Ss();r.registerModule(i),r.registerModule(o),r.registerModule(u),r.registerModule(f),r.registerModule(l),r.registerModule(pl((b,w)=>r.callFunctionValue(b,w)));let c=fl(),p=ml(),m=dl(),d=hl(),g=yl();r.registerModule(c),r.registerModule(p),r.registerModule(m),r.registerModule(d),r.registerModule(g),r.registerModule(kl((b,w)=>r.callFunctionValue(b,w)));let h=Ts(),y=Ns(),k=Os();r.registerModule(h),r.registerModule(y),r.registerModule(k),r.registerModule(Sl((b,w)=>r.callUserFunction(b,w),(b,w)=>r.callFunctionValue(b,w)));let v=js(),$=$l(),M=El();r.registerModule(v),r.registerModule($),r.registerModule(M),r.registerModule(Rl((b,w)=>r.callUserFunction(b,w)));let O=Cl(),C=Nl();r.registerModule(O),r.registerModule(C),r.registerModule(Ol((b,w)=>r.callFunctionValue(b,w))),r.registerModule(lc((b,w)=>r.callFunctionValue(b,w),(b,w)=>r.callUserFunction(b,w))),r.registerModule(Fl());let P=Ru(),_=Us();r.registerModule(P),r.registerModule(_);let S=ju((b,w)=>r.callFunctionValue(b,w),a.http_get,a.http_post);r.registerModule(S);let R=[t,e,n,s,a,i,o,u,f,l,c,p,m,d,g,h,y,k,v,$,M,O,C,P,_,S];r.registerModule(Lu(R)),r.registerModule({fl_require:b=>$u(b,r),"fl_require?":b=>Au(b),fl_modules:()=>xu(),fl_load:b=>{let w=require("fs"),x=require("path"),{lex:N}=(be(),_e(cn)),{parse:F}=(ke(),_e(fn)),I=x.isAbsolute(b)?b:x.resolve(process.cwd(),b);if(!w.existsSync(I))return console.error(`\u274C [fl_load] \uD30C\uC77C \uC5C6\uC74C: ${I}`),!1;let V=r.importedFiles??new Set;if(V.has(I))return!0;V.add(I),r.importedFiles=V;try{let q=w.readFileSync(I,"utf-8");return r.interpret(F(N(q))),!0}catch(q){return V.delete(I),console.error(`\u274C [fl_load] "${I}" \uB85C\uB4DC \uC2E4\uD328:`,q.message),!1}}});let E={"get-in":(b,w)=>{let x=b;for(let N of w){if(x==null)return null;x=x instanceof Map?x.get(N)??x.get(String(N))??null:x?.[N]??null}return x??null},"assoc-in":(b,w,x)=>{if(!w||w.length===0)return x;let N=w[0],F=w.slice(1),I=b instanceof Map?b.get(N)??b.get(String(N)):b?.[N],V=F.length>0?E["assoc-in"](I??new Map,F,x):x;if(b instanceof Map){let q=new Map(b);return q.set(N,V),q}return Object.assign({},b??{},{[String(N)]:V})},"update-in":(b,w,x,...N)=>{let F=E["get-in"](b,w),I;return typeof x=="function"?I=x(F,...N):x?.kind==="function-value"||x?.kind==="async-function-value"?I=r.callFunctionValue(x,[F,...N]):typeof x?.body=="function"?I=x.body(F,...N):typeof x=="string"?I=r.callUserFunction(x,[F,...N]):I=F,E["assoc-in"](b,w,I)},format:(b,...w)=>{let x=0;return String(b).replace(/%([-+]?\d*\.?\d*)?([dfsoxXbeE%])/g,(N,F,I)=>{if(I==="%")return"%";let V=w[x++],q=(F??"").match(/\.(\d+)/),L=q?parseInt(q[1]):6,X=parseInt((F??"").replace(/\.\d+/,""))||0,G=Q=>X>0?Q.padStart(X):X<0?Q.padEnd(-X):Q;switch(I){case"d":return G(String(Math.trunc(Number(V))));case"f":return G(Number(V).toFixed(L));case"e":return G(Number(V).toExponential(L));case"E":return G(Number(V).toExponential(L).toUpperCase());case"s":return G(String(V??""));case"o":return G(Number(V).toString(8));case"x":return G(Number(V).toString(16));case"X":return G(Number(V).toString(16).toUpperCase());case"b":return G(Number(V).toString(2));default:return G(String(V))}})},"date-format":(b,w)=>{let x=new Date(Number(b));return String(w).replace("yyyy",String(x.getFullYear())).replace("MM",String(x.getMonth()+1).padStart(2,"0")).replace("dd",String(x.getDate()).padStart(2,"0")).replace("HH",String(x.getHours()).padStart(2,"0")).replace("mm",String(x.getMinutes()).padStart(2,"0")).replace("ss",String(x.getSeconds()).padStart(2,"0")).replace("SSS",String(x.getMilliseconds()).padStart(3,"0"))},"date-add":(b,w,x)=>{let N=new Date(Number(b)),F=String(w).replace(/^:/,"");return F==="days"||F==="day"?N.setDate(N.getDate()+Number(x)):F==="hours"||F==="hour"?N.setHours(N.getHours()+Number(x)):F==="minutes"||F==="minute"?N.setMinutes(N.getMinutes()+Number(x)):F==="months"||F==="month"?N.setMonth(N.getMonth()+Number(x)):F==="years"||F==="year"?N.setFullYear(N.getFullYear()+Number(x)):F==="seconds"||F==="second"?N.setSeconds(N.getSeconds()+Number(x)):(F==="weeks"||F==="week")&&N.setDate(N.getDate()+Number(x)*7),N.getTime()},"date-diff":(b,w,x)=>{let N=Number(w)-Number(b),F=String(x).replace(/^:/,"");return F==="days"?Math.floor(N/864e5):F==="hours"?Math.floor(N/36e5):F==="minutes"?Math.floor(N/6e4):F==="seconds"?Math.floor(N/1e3):F==="weeks"?Math.floor(N/6048e5):N},"date-parse":b=>{let w=Date.parse(String(b));return isNaN(w)?0:w},"re-match":(b,w)=>{try{let x=String(w).match(new RegExp(b));return x?x[0]:null}catch{return null}},"re-test":(b,w)=>{try{return new RegExp(b).test(String(w))}catch{return!1}},"re-find":(b,w)=>{try{let x=String(w).match(new RegExp(b));return x?x[0]:null}catch{return null}},"re-find-all":(b,w)=>{try{return[...String(w).matchAll(new RegExp(b,"g"))].map(x=>x[0])}catch{return[]}},"re-replace":(b,w,x)=>{try{return String(x).replace(new RegExp(b,"g"),w)}catch{return String(x)}},"re-split":(b,w)=>{try{return String(w).split(new RegExp(b))}catch{return[String(w)]}},"re-groups":(b,w)=>{try{let x=String(w).match(new RegExp(b));return x?[...x]:null}catch{return null}},"log/info":(b,w)=>{let x=new Date().toISOString(),N=w?" "+JSON.stringify(w instanceof Map?Object.fromEntries(w):w):"";return process.stdout.write(`\x1B[32m[INFO]\x1B[0m ${x} ${b}${N}
834
+ `),null},"log/warn":(b,w)=>{let x=new Date().toISOString(),N=w?" "+JSON.stringify(w instanceof Map?Object.fromEntries(w):w):"";return process.stderr.write(`\x1B[33m[WARN]\x1B[0m ${x} ${b}${N}
835
+ `),null},"log/error":(b,w)=>{let x=new Date().toISOString(),N=w instanceof Map?Object.fromEntries(w):w,F=N?.raw instanceof Error?{...N,raw:N.raw.message}:N,I=F?" "+JSON.stringify(F):"";return process.stderr.write(`\x1B[31m[ERROR]\x1B[0m ${x} ${b}${I}
836
+ `),null},"log/debug":(b,w)=>{if(!process.env.FL_DEBUG&&!process.env.FL_LOG_DEBUG)return null;let x=new Date().toISOString(),N=w?" "+JSON.stringify(w instanceof Map?Object.fromEntries(w):w):"";return process.stderr.write(`\x1B[2m[DEBUG]\x1B[0m ${x} ${b}${N}
837
+ `),null},"fn-meta":b=>{let w=ks.get(b);if(!w)return null;let x=new Map;return w.doc&&x.set("doc",w.doc),w.returns&&x.set("returns",w.returns),w.context&&x.set("context",w.context),w.effects&&x.set("effects",w.effects),w.examples&&x.set("examples",w.examples),x},fn_meta:b=>E["fn-meta"](b),"check-arg-type":(b,w)=>{let x=typeof b=="number"?"number":typeof b=="string"?"string":typeof b=="boolean"?"boolean":b===null?"nil":Array.isArray(b)?"array":typeof b=="function"?"function":"map";if(x!==w){let N=new Error(`Expected ${w}, got ${x}`);throw N.code="TYPE_MISMATCH",N.context={expectedType:w,actualType:x,value:b},N}return b},check_arg_type:function(b,w){return this["check-arg-type"](b,w)},"validate-args":(b,w)=>{let x=Array.isArray(b)?b:[b],N=Array.isArray(w)?w:[w];for(let F=0;F<Math.min(x.length,N.length);F++){let I=typeof x[F]=="number"?"number":typeof x[F]=="string"?"string":typeof x[F]=="boolean"?"boolean":x[F]===null?"nil":Array.isArray(x[F])?"array":typeof x[F]=="function"?"function":"map";if(I!==N[F]){let V=new Error(`Argument ${F}: expected ${N[F]}, got ${I}`);throw V.code="TYPE_MISMATCH",V.context={argIndex:F,expectedType:N[F],actualType:I},V}}return x},validate_args:function(b,w){return this["validate-args"](b,w)},"run-props":()=>{let b=[],w=0,x=0;for(let[,N]of Ne){let F=bs(N,(L,X)=>{let G=r.context?.variables?.get(L)??r.context?.variables?.get("$"+L);if(!G)throw new Error(`\uD568\uC218 \uC5C6\uC74C: ${L}`);return r.callFunctionValue(G,X)},(L,X)=>L?r.callFunctionValue(L,X):!0);w+=F.passed,x+=F.failed;let I=F.failed===0,V=I?"\x1B[32m\u2713\x1B[0m":"\x1B[31m\u2716\x1B[0m";if(process.stdout.write(` ${V} ${F.name} \x1B[2m(${F.fn}, ${F.passed}/${F.samples} passed, ${F.durationMs}ms)\x1B[0m
838
+ `),!I&&F.firstFailure){let L=F.firstFailure;process.stdout.write(` \x1B[31m\uBC18\uB840\x1B[0m: args=${JSON.stringify(L.args)}`+(L.error?` error=${L.error}`:` result=${JSON.stringify(L.result)}`)+`
839
+ `)}let q=new Map;q.set("name",F.name),q.set("fn",F.fn),q.set("passed",F.passed),q.set("failed",F.failed),q.set("ok",F.failed===0),b.push(q)}if(Ne.size>0){let N=x===0;process.stdout.write(`
840
+ ${N?"\x1B[32m[PROPS PASS]\x1B[0m":"\x1B[31m[PROPS FAIL]\x1B[0m"} ${Ne.size}\uAC1C property, ${w} passed, ${x} failed
841
+ `)}return b},run_props:()=>E["run-props"](),"props-list":()=>[...Ne.keys()],mod:(b,w)=>b%w,number:b=>{let w=Number(b);return isNaN(w)?null:w},"to-number":b=>{let w=Number(b);return isNaN(w)?null:w},to_number:b=>{let w=Number(b);return isNaN(w)?null:w},"parse-int":(b,w)=>{let x=parseInt(b,w??10);return isNaN(x)?null:x},parse_int:(b,w)=>{let x=parseInt(b,w??10);return isNaN(x)?null:x},"parse-float":b=>{let w=parseFloat(b);return isNaN(w)?null:w},parse_float:b=>{let w=parseFloat(b);return isNaN(w)?null:w},"number?":b=>typeof b=="number"&&!isNaN(b),"log-info":(...b)=>{if(b.length===2&&b[0]&&Array.isArray(b[0].entries)){let w=b[0],x=String(b[1]);return{...w,entries:[...w.entries,{ts:Date.now(),level:"info",msg:x}]}}return console.log(`[INFO] ${b.map(String).join(" ")}`),null},log_info:(...b)=>{if(b.length===2&&b[0]&&Array.isArray(b[0].entries)){let w=b[0],x=String(b[1]);return{...w,entries:[...w.entries,{ts:Date.now(),level:"info",msg:x}]}}return console.log(`[INFO] ${b.map(String).join(" ")}`),null},"log-warn":(...b)=>{if(b.length===2&&b[0]&&Array.isArray(b[0].entries)){let w=b[0],x=String(b[1]);return{...w,entries:[...w.entries,{ts:Date.now(),level:"warn",msg:x}]}}return console.warn(`[WARN] ${b.map(String).join(" ")}`),null},log_warn:(...b)=>{if(b.length===2&&b[0]&&Array.isArray(b[0].entries)){let w=b[0],x=String(b[1]);return{...w,entries:[...w.entries,{ts:Date.now(),level:"warn",msg:x}]}}return console.warn(`[WARN] ${b.map(String).join(" ")}`),null},"log-error":(...b)=>{if(b.length===2&&b[0]&&Array.isArray(b[0].entries)){let w=b[0],x=String(b[1]);return{...w,entries:[...w.entries,{ts:Date.now(),level:"error",msg:x}]}}return console.error(`[ERROR] ${b.map(String).join(" ")}`),null},log_error:(...b)=>{if(b.length===2&&b[0]&&Array.isArray(b[0].entries)){let w=b[0],x=String(b[1]);return{...w,entries:[...w.entries,{ts:Date.now(),level:"error",msg:x}]}}return console.error(`[ERROR] ${b.map(String).join(" ")}`),null},validate:(b,w)=>{let x=[],N=w instanceof Map?[...w.entries()]:Object.entries(w??{}),F=b instanceof Map?I=>b.get(I)??b.get(":"+I):I=>(b??{})[I];for(let[I,V]of N){let q=String(I).replace(/^:/,""),L=F(q),X=Array.isArray(V)?V:[V];for(let G of X){let Q=String(G??"").replace(/^:/,"");if(Q==="required"&&(L==null||L===""))x.push(`${q}: required`);else if(Q==="number"&&L!==null&&L!==void 0&&typeof L!="number"&&isNaN(Number(L)))x.push(`${q}: must be number`);else if(Q==="string"&&L!==null&&L!==void 0&&typeof L!="string")x.push(`${q}: must be string`);else if(Q==="boolean"&&L!==null&&L!==void 0&&typeof L!="boolean")x.push(`${q}: must be boolean`);else if(Q==="email"&&L&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(L)))x.push(`${q}: must be valid email`);else if(Q.startsWith("min-")){let Z=Number(Q.slice(4));typeof L=="string"&&L.length<Z?x.push(`${q}: min length ${Z}`):typeof L=="number"&&L<Z&&x.push(`${q}: min value ${Z}`)}else if(Q.startsWith("max-")){let Z=Number(Q.slice(4));typeof L=="string"&&L.length>Z?x.push(`${q}: max length ${Z}`):typeof L=="number"&&L>Z&&x.push(`${q}: max value ${Z}`)}}}return x.length>0?x:null},"list-min":b=>Array.isArray(b)&&b.length>0?Math.min(...b.map(Number)):null,list_min:b=>Array.isArray(b)&&b.length>0?Math.min(...b.map(Number)):null,"list-max":b=>Array.isArray(b)&&b.length>0?Math.max(...b.map(Number)):null,list_max:b=>Array.isArray(b)&&b.length>0?Math.max(...b.map(Number)):null,"str-contains?":(b,w)=>typeof b=="string"&&typeof w=="string"?b.includes(w):!1,"str-contains":(b,w)=>typeof b=="string"&&typeof w=="string"?b.includes(w):!1,str_contains:(b,w)=>typeof b=="string"&&typeof w=="string"?b.includes(w):!1,"includes?":(b,w)=>typeof b=="string"?b.includes(String(w)):Array.isArray(b)?b.includes(w):!1,"includes-item":(b,w)=>Array.isArray(b)?b.includes(w):!1,"str-pad":(b,w,x,N)=>{let F=String(b??""),I=Number(w),V=String(x??" ")[0]??" ";if(F.length>=I)return F;let q=V.repeat(I-F.length);return N==="left"||N===":left"?q+F:F+q},str_pad:(b,w,x,N)=>{let F=String(b??""),I=Number(w),V=String(x??" ")[0]??" ";if(F.length>=I)return F;let q=V.repeat(I-F.length);return N==="left"||N===":left"?q+F:F+q},"str-repeat":(b,w)=>String(b??"").repeat(Math.max(0,Math.trunc(Number(w)))),str_repeat:(b,w)=>String(b??"").repeat(Math.max(0,Math.trunc(Number(w)))),flatten:b=>Array.isArray(b)?b.reduce((w,x)=>Array.isArray(x)?w.concat(x):(w.push(x),w),[]):[b],distinct:b=>{if(!Array.isArray(b))return[];let w=new Set,x=[];for(let N of b){let F=N!==null&&typeof N=="object"?JSON.stringify(N):N;w.has(F)||(w.add(F),x.push(N))}return x},zip:(b,w)=>{let x=new Map,N=Array.isArray(b)?b:[],F=Array.isArray(w)?w:[];for(let I=0;I<N.length;I++)x.set(N[I],F[I]??null);return x},"nil-or":(b,w)=>b??w,nil_or:(b,w)=>b??w,"or-default":(b,w)=>b??w,or_default:(b,w)=>b??w,coalesce:(...b)=>b.find(w=>w!=null)??null,inc:b=>typeof b=="number"?b+1:Number(b)+1,dec:b=>typeof b=="number"?b-1:Number(b)-1,"dissoc-nil":b=>{if(b instanceof Map){let w=new Map(b);return w.forEach((x,N)=>{x==null&&w.delete(N)}),w}return b&&typeof b=="object"&&!Array.isArray(b)?Object.fromEntries(Object.entries(b).filter(([,w])=>w!=null)):b??new Map},dissoc_nil:b=>{if(b instanceof Map){let w=new Map(b);return w.forEach((x,N)=>{x==null&&w.delete(N)}),w}return b&&typeof b=="object"&&!Array.isArray(b)?Object.fromEntries(Object.entries(b).filter(([,w])=>w!=null)):b??new Map},merge:(...b)=>{let w=new Map;for(let x of b)if(x instanceof Map)x.forEach((N,F)=>{N!=null&&w.set(F,N)});else if(x&&typeof x=="object"&&!Array.isArray(x))for(let[N,F]of Object.entries(x))F!=null&&w.set(N,F);return w},"merge-all":(...b)=>{let w=new Map;for(let x of b)if(x instanceof Map)x.forEach((N,F)=>w.set(F,N));else if(x&&typeof x=="object"&&!Array.isArray(x))for(let[N,F]of Object.entries(x))w.set(N,F);return w},"hash-sha256":b=>(0,Un.createHash)("sha256").update(b,"utf8").digest("hex"),"hmac-sha256":(b,w)=>(0,Un.createHmac)("sha256",b).update(w,"utf8").digest("hex"),hash_md5:b=>(0,Un.createHash)("md5").update(b,"utf8").digest("hex"),"hash-md5":b=>(0,Un.createHash)("md5").update(b,"utf8").digest("hex")},T={"bcrypt-hash":"auth_hash_password",bcrypt_hash:"auth_hash_password","bcrypt-verify":"auth_verify_password",bcrypt_verify:"auth_verify_password","jwt-sign":"auth_jwt_sign",jwt_sign:"auth_jwt_sign","jwt-verify":"auth_jwt_verify",jwt_verify:"auth_jwt_verify","jwt-decode":"auth_jwt_decode",jwt_decode:"auth_jwt_decode","password-hash":"auth_hash_password",password_hash:"auth_hash_password","password-verify":"auth_verify_password",password_verify:"auth_verify_password"};for(let[b,w]of Object.entries(E))r.context.functions.has(b)||r.context.functions.set(b,{name:b,params:[],body:w});let B={"on-shutdown":"on_sigterm",on_shutdown:"on_sigterm","on-exit":"on_exit"};for(let[b,w]of Object.entries(B))if(!r.context.functions.has(b)&&r.context.functions.has(w)){let x=r.context.functions.get(w);r.context.functions.set(b,{...x,name:b})}for(let[b,w]of Object.entries(T))if(!r.context.functions.has(b)&&r.context.functions.has(w)){let x=r.context.functions.get(w);r.context.functions.set(b,{...x,name:b})}let U={"log-info":(...b)=>b.length===2&&b[0]&&Array.isArray(b[0].entries)?{...b[0],entries:[...b[0].entries,{ts:Date.now(),level:"info",msg:String(b[1])}]}:(console.log(`[INFO] ${b.map(String).join(" ")}`),null),log_info:(...b)=>b.length===2&&b[0]&&Array.isArray(b[0].entries)?{...b[0],entries:[...b[0].entries,{ts:Date.now(),level:"info",msg:String(b[1])}]}:(console.log(`[INFO] ${b.map(String).join(" ")}`),null),"log-warn":(...b)=>b.length===2&&b[0]&&Array.isArray(b[0].entries)?{...b[0],entries:[...b[0].entries,{ts:Date.now(),level:"warn",msg:String(b[1])}]}:(console.warn(`[WARN] ${b.map(String).join(" ")}`),null),log_warn:(...b)=>b.length===2&&b[0]&&Array.isArray(b[0].entries)?{...b[0],entries:[...b[0].entries,{ts:Date.now(),level:"warn",msg:String(b[1])}]}:(console.warn(`[WARN] ${b.map(String).join(" ")}`),null),"log-error":(...b)=>b.length===2&&b[0]&&Array.isArray(b[0].entries)?{...b[0],entries:[...b[0].entries,{ts:Date.now(),level:"error",msg:String(b[1])}]}:(console.error(`[ERROR] ${b.map(String).join(" ")}`),null),log_error:(...b)=>b.length===2&&b[0]&&Array.isArray(b[0].entries)?{...b[0],entries:[...b[0].entries,{ts:Date.now(),level:"error",msg:String(b[1])}]}:(console.error(`[ERROR] ${b.map(String).join(" ")}`),null),"stdlib-list":()=>[...r.context.functions.keys()].sort(),stdlib_list:()=>[...r.context.functions.keys()].sort(),"fn-where":b=>{let w=String(b).replace(/-/g,"_"),x=String(b).replace(/_/g,"-"),N=r.context.functions.has(String(b))?String(b):r.context.functions.has(w)?w:r.context.functions.has(x)?x:null;return N?typeof r.context.functions.get(N)?.body=="function"?`native:${N}`:`fl-defined:${N}`:`not-found: ${b}`},fn_where:b=>{let w=String(b).replace(/-/g,"_"),x=String(b).replace(/_/g,"-"),N=r.context.functions.has(String(b))?String(b):r.context.functions.has(w)?w:r.context.functions.has(x)?x:null;return N?typeof r.context.functions.get(N)?.body=="function"?`native:${N}`:`fl-defined:${N}`:`not-found: ${b}`},"fn-exists?":b=>{let w=String(b);if(r.context.functions.has(w)||r.context.functions.has(w.replace(/-/g,"_"))||r.context.functions.has(w.replace(/_/g,"-")))return!0;let x=new Set(["abs","agent-broadcast","agent-history","agent-inbox-size","agent-list","agent-process","agent-recv","agent-send","agent-spawn","and","append","array?","assert-type","assoc","atom","begin","bind","block-items","bool","bool?","boolean?","bson-decode-native","bson-encode-native","call","ceil","char-at","char-code","clamp","cli-args","closure?","comp","complement","concat","cons","constantly","contains?","cos","cosine-sim","cosine_sim","ctx-add","ctx-all","ctx-get","ctx-has-room?","ctx-new","ctx-remove","ctx-stats","ctx-trim","define","deref","dir-exists?","dir-list","dissoc","distinct","do","dot-product","drop","echo","empty?","ends-with?","err","err?","error","euclidean-dist","even?","exp","export","failure","false?","file-append","file-exists?","file-mkdir","file_append","file_mkdir","filter","filter-lazy","find","first","first-or","first_or","fl-concepts","fl-env-get","fl-example-count","fl-examples","fl-exec-op","fl-fix-env","fl-interp","fl-learn","fl-parse","fl-special-op?","flat-map","flatten","float?","floor","fn","fn?","function?","get","get-or","has-key?","help","html-escape","html-response","http-get","http_get","identity","if","if-let","includes?","index-of","inspect","int?","is-digit?","is-symbol?","is-whitespace?","iterate","join","js-escape","json-response","juxt","keys","last","last-or","last_or","lazy-head","lazy-seq","lazy-tail","lazy?","left","length","let","lex","list","list-tools","list?","load","log","lower","lower-case","lowercase","map","map-entries","map-err","map-lazy","map-ok","map-set","map?","map_entries","match","math-abs","math-pow","math-sqrt","math_abs","math_sqrt","max","maybe-bind","maybe-chain","maybe-combine","maybe-filter","maybe-map","maybe-select","mem-episode","mem-forget","mem-keys","mem-purge","mem-recall","mem-remember","mem-remember-short","mem-search-episodes","mem-search-tag","mem-stats","mem-working-clear","mem-working-get","mem-working-set","merge","min","mod","nan?","neg?","negative?","net-connect","net-sendrecv","net-sendrecv-pool","nil-or-empty?","nil?","none","not","not-nil?","now","now-iso","now_iso","null?","num","num-to-str","number?","obj-entries","obj-keys","obj-merge","obj-omit","obj-pick","obj-values","obj_entries","obj_keys","obj_merge","obj_omit","obj_pick","obj_values","odd?","ok","ok?","omit","or","parse","pick","pop","pos?","positive?","pow","print","print-err","println","promise","prompt-compile","prompt-from-code","prompt-target","prompt-tokens","pure","pure-writer","push","quality-check","quality-feedback","quality-passed?","rag-add","rag-query","rag-remove","rag-retrieve","rag-size","random","range","read-file","recover","reduce","repeat","replace","repr","require","reset!","rest","result-classify","result-explain","return-writer","reverse","right","round","sdk-features","sdk-snippet","sdk-supports","sdk-validate","sdk-version","server-uptime","set!","set-timeout","shell-exec","shell-exec-result","shift","sin","slice","sleep","some","some?","sort","sort-by","sort_by","split","sqrt","starts-with?","str","str-char-at","str-ends-with?","str-join","str-split","str-starts-with?","str-to-num","str_trim","stream-chunk-count","stream-chunks","stream-collect","stream-create","stream-delete","stream-done?","stream-end","stream-text","stream-write","string?","string_trim","strlen","substring","success","swap!","take","take-while","tan","tell","to-hex","trace-add","trace-create","trace-enter","trace-exit","trace-markdown","trace-node-count","trace-tree","trim","true?","try","try-reason","try-with-fallback","type-of","typeof","unique","unshift","unwrap","unwrap-or","upper","upper-case","uppercase","use-tool","uuid","uuid4","vals","values","vec-add","vec-dist","vec-dot","vec-magnitude","vec-norm","vec-normalize","vec-scale","vec-top-k","when","write-file","zero?","zip","zip-with","cond","catch","includes-item","flatten"]);return x.has(w)||x.has(w.replace(/_/g,"-"))},fn_exists:b=>{let w=String(b);if(r.context.functions.has(w)||r.context.functions.has(w.replace(/-/g,"_"))||r.context.functions.has(w.replace(/_/g,"-")))return!0;let x=new Set(["abs","agent-broadcast","agent-history","agent-inbox-size","agent-list","agent-process","agent-recv","agent-send","agent-spawn","and","append","array?","assert-type","assoc","atom","begin","bind","block-items","bool","bool?","boolean?","bson-decode-native","bson-encode-native","call","ceil","char-at","char-code","clamp","cli-args","closure?","comp","complement","concat","cons","constantly","contains?","cos","cosine-sim","cosine_sim","ctx-add","ctx-all","ctx-get","ctx-has-room?","ctx-new","ctx-remove","ctx-stats","ctx-trim","define","deref","dir-exists?","dir-list","dissoc","distinct","do","dot-product","drop","echo","empty?","ends-with?","err","err?","error","euclidean-dist","even?","exp","export","failure","false?","file-append","file-exists?","file-mkdir","file_append","file_mkdir","filter","filter-lazy","find","first","first-or","first_or","fl-concepts","fl-env-get","fl-example-count","fl-examples","fl-exec-op","fl-fix-env","fl-interp","fl-learn","fl-parse","fl-special-op?","flat-map","flatten","float?","floor","fn","fn?","function?","get","get-or","has-key?","help","html-escape","html-response","http-get","http_get","identity","if","if-let","includes?","index-of","inspect","int?","is-digit?","is-symbol?","is-whitespace?","iterate","join","js-escape","json-response","juxt","keys","last","last-or","last_or","lazy-head","lazy-seq","lazy-tail","lazy?","left","length","let","lex","list","list-tools","list?","load","log","lower","lower-case","lowercase","map","map-entries","map-err","map-lazy","map-ok","map-set","map?","map_entries","match","math-abs","math-pow","math-sqrt","math_abs","math_sqrt","max","maybe-bind","maybe-chain","maybe-combine","maybe-filter","maybe-map","maybe-select","mem-episode","mem-forget","mem-keys","mem-purge","mem-recall","mem-remember","mem-remember-short","mem-search-episodes","mem-search-tag","mem-stats","mem-working-clear","mem-working-get","mem-working-set","merge","min","mod","nan?","neg?","negative?","net-connect","net-sendrecv","net-sendrecv-pool","nil-or-empty?","nil?","none","not","not-nil?","now","now-iso","now_iso","null?","num","num-to-str","number?","obj-entries","obj-keys","obj-merge","obj-omit","obj-pick","obj-values","obj_entries","obj_keys","obj_merge","obj_omit","obj_pick","obj_values","odd?","ok","ok?","omit","or","parse","pick","pop","pos?","positive?","pow","print","print-err","println","promise","prompt-compile","prompt-from-code","prompt-target","prompt-tokens","pure","pure-writer","push","quality-check","quality-feedback","quality-passed?","rag-add","rag-query","rag-remove","rag-retrieve","rag-size","random","range","read-file","recover","reduce","repeat","replace","repr","require","reset!","rest","result-classify","result-explain","return-writer","reverse","right","round","sdk-features","sdk-snippet","sdk-supports","sdk-validate","sdk-version","server-uptime","set!","set-timeout","shell-exec","shell-exec-result","shift","sin","slice","sleep","some","some?","sort","sort-by","sort_by","split","sqrt","starts-with?","str","str-char-at","str-ends-with?","str-join","str-split","str-starts-with?","str-to-num","str_trim","stream-chunk-count","stream-chunks","stream-collect","stream-create","stream-delete","stream-done?","stream-end","stream-text","stream-write","string?","string_trim","strlen","substring","success","swap!","take","take-while","tan","tell","to-hex","trace-add","trace-create","trace-enter","trace-exit","trace-markdown","trace-node-count","trace-tree","trim","true?","try","try-reason","try-with-fallback","type-of","typeof","unique","unshift","unwrap","unwrap-or","upper","upper-case","uppercase","use-tool","uuid","uuid4","vals","values","vec-add","vec-dist","vec-dot","vec-magnitude","vec-norm","vec-normalize","vec-scale","vec-top-k","when","write-file","zero?","zip","zip-with","cond","catch","includes-item","flatten"]);return x.has(w)||x.has(w.replace(/_/g,"-"))}};for(let[b,w]of Object.entries(U))r.context.functions.set(b,{name:b,params:[],body:w})}function Du(r,t){let e=r.eval(t.value);for(let n of t.cases){let s=Vn(r,n.pattern,e);if(s.matched){r.context.variables.push();for(let[a]of s.bindings)r.context.variables.set("$"+a,s.bindings.get(a));if(s.asBinding&&r.context.variables.set("$"+s.asBinding,e),n.guard&&!r.eval(n.guard)){r.context.variables.pop();continue}try{return r.eval(n.body)}finally{r.context.variables.pop()}}}if(t.defaultCase)return r.eval(t.defaultCase);throw new Error("Pattern match exhausted without matching case")}function qu(r,t){let e;try{e=r.eval(t.body)}catch(n){if(Rt(n))throw n;let s=!1;if(t.catchClauses&&t.catchClauses.length>0)for(let a of t.catchClauses){if(r.context.variables.push(),a.variable){let i={};if(typeof n=="string")i.message=n,i.type="RuntimeError";else if(n instanceof Error){let o=n.message,u=o.match(/^FreeLang line \d+:\s*/);u&&(o=o.slice(u[0].length));let f=o.match(/^\[[^\]]+\]\s*(.*?)(?:\s*\(at line \d+.*)?$/s);if(f)o=f[1].trim();else{let g=o.match(/^(.*?)\s*\(at line \d+/s);g&&(o=g[1].trim())}i.message=o||n.message;let l=n.constructor?.name??"RuntimeError";i.type=l==="Error"?"RuntimeError":l;let c=n.message.match(/\(at line (\d+)/);c&&(i.line=parseInt(c[1],10));let p=n;p.file&&(i.file=p.file);let m=p.code??null;if(m&&(i.code=m),p.hint&&(i.hint=p.hint),n.stack){let g=n.stack.split(`
842
+ `).filter(y=>!y.includes("bootstrap.js")&&!y.includes("node:internal")).join(`
843
+ `).trim(),h=i.line!=null?`FreeLang line ${i.line}`:null;i.stack=g||h||i.message}let d={E_TYPE_NIL:"TypeError",E_TYPE_MISMATCH:"TypeError",E_ARG_COUNT:"ArityError",E_FN_NOT_FOUND:"ReferenceError",E_UNDEFINED_VAR:"ReferenceError",E_UNRESOLVED_SYMBOL:"ReferenceError",E_DIV_BY_ZERO:"RuntimeError",E_INDEX_OOB:"RuntimeError",E_INVALID_FORM:"RuntimeError",E_PURE_VIOLATION:"RuntimeError",E_STACK_OVERFLOW:"RuntimeError",E_RUNTIME:"RuntimeError"};(p.category||m)&&(i.type=(m?d[m]:null)??p.category??"RuntimeError")}else n&&typeof n=="object"?(i.message=n.message??String(n),i.type=n.type??"RuntimeError",n.stack&&(i.stack=n.stack)):(i.message=String(n),i.type="RuntimeError");i.raw=n,r.context.variables.set("$"+a.variable,i)}try{e=r.eval(a.handler),s=!0;break}catch(i){throw i}finally{r.context.variables.pop()}}if(!s)throw n}finally{t.finallyBlock&&r.eval(t.finallyBlock)}return e}function Uu(r,t){let e=r.eval(t.argument);throw e instanceof Error?e:typeof e=="string"?new Error(e):e&&typeof e=="object"&&e.message?new Error(e.message):new Error(String(e))}function Vn(r,t,e){let n=new Map;if(t.kind==="literal-pattern")return{matched:t.value===e,bindings:n};if(t.kind==="variable-pattern"){let s=t;return n.set(s.name,e),{matched:!0,bindings:n}}if(t.kind==="wildcard-pattern")return{matched:!0,bindings:n};if(t.kind==="list-pattern"){let s=t;if(!Array.isArray(e))return{matched:!1,bindings:n};let a=s.elements,i=0;for(let o=0;o<a.length;o++){if(o>=e.length)return{matched:!1,bindings:n};let u=Vn(r,a[o],e[o]);if(!u.matched)return{matched:!1,bindings:n};for(let[f,l]of u.bindings)n.set(f,l);i++}if(s.restElement){let o=e.slice(i);n.set(s.restElement,o)}else if(i<e.length)return{matched:!1,bindings:n};return{matched:!0,bindings:n}}if(t.kind==="struct-pattern"){let s=t;if(typeof e!="object"||e===null)return{matched:!1,bindings:n};for(let[a,i]of s.fields){let o=a.startsWith(":")?a.slice(1):a,u=e[o]!==void 0?e[o]:e[a],f=Vn(r,i,u);if(!f.matched)return{matched:!1,bindings:n};for(let[l,c]of f.bindings)n.set(l,c)}return{matched:!0,bindings:n,asBinding:s.asBinding}}if(t.kind==="or-pattern"){let s=t;for(let a of s.alternatives){let i=Vn(r,a,e);if(i.matched)return i}return{matched:!1,bindings:n}}if(t.kind==="range-pattern"){let s=t;return{matched:typeof e=="number"&&e>=s.min&&e<s.max,bindings:n}}return{matched:!1,bindings:n}}function Vu(r){if(!r.context.typeClasses||!r.context.typeClassInstances)return;let t=(i,o)=>i?.kind==="Result"?i.tag==="Ok"?r.callFunction(o,[i.value]):i:i?.kind==="Option"&&i.tag==="Some"?r.callFunction(o,[i.value]):i,e=(i,o)=>{let u=[];for(let f of i){let l=r.callFunction(o,[f]);u=u.concat(Array.isArray(l)?l:[l])}return u},n=(i,o)=>i?.tag==="Ok"?{tag:"Ok",value:r.callFunction(o,[i.value]),kind:"Result"}:i,s=(i,o)=>i?.tag==="Some"?{tag:"Some",value:r.callFunction(o,[i.value]),kind:"Option"}:i,a=(i,o)=>i.map(u=>r.callFunction(o,[u]));r.context.typeClasses.set("Monad",{name:"Monad",typeParams:["M"],methods:new Map([["pure","fn [a] (M a)"],["bind","fn [m f] (M b)"],["map","fn [m f] (M b)"]])}),r.context.typeClasses.set("Functor",{name:"Functor",typeParams:["F"],methods:new Map([["fmap","fn [f a] (F a)"]])}),r.context.typeClassInstances.set("Monad[Result]",{className:"Monad",concreteType:"Result",implementations:new Map([["pure",i=>({tag:"Ok",value:i,kind:"Result"})],["bind",t],["map",n]])}),r.context.typeClassInstances.set("Monad[Option]",{className:"Monad",concreteType:"Option",implementations:new Map([["pure",i=>({tag:"Some",value:i,kind:"Option"})],["bind",t],["map",s]])}),r.context.typeClassInstances.set("Monad[List]",{className:"Monad",concreteType:"List",implementations:new Map([["pure",i=>[i]],["bind",e],["map",a]])}),r.context.typeClassInstances.set("Functor[Result]",{className:"Functor",concreteType:"Result",implementations:new Map([["fmap",n]])}),r.context.typeClassInstances.set("Functor[Option]",{className:"Functor",concreteType:"Option",implementations:new Map([["fmap",s]])}),r.context.typeClassInstances.set("Functor[List]",{className:"Functor",concreteType:"List",implementations:new Map([["fmap",a]])})}function zu(r,t){let e={name:t.name,typeParams:t.typeParams,methods:new Map};t.methods&&t.methods.forEach((n,s)=>{e.methods.set(s,s)}),r.context.typeClasses.set(t.name,e),r.logger.info(`\u2705 Registered TYPECLASS "${t.name}" with type params [${t.typeParams.join(", ")}] and ${e.methods.size} method(s)`)}function Wu(r,t){let e=`${t.className}[${t.concreteType}]`,n=new Map;t.implementations&&t.implementations.forEach((a,i)=>{n.set(i,r.eval(a))});let s={className:t.className,concreteType:t.concreteType,implementations:n};r.context.typeClassInstances.set(e,s),r.logger.info(`\u2705 Registered INSTANCE of "${t.className}" for type "${t.concreteType}" with ${n.size} method(s)`)}nt();var Vi=class{constructor(){this.enabled=!1;this.entries=new Map;this.callStack=[]}enter(t){if(!this.enabled)return()=>{};let e=performance.now(),n={name:t,startMs:e,childMs:0};return this.callStack.push(n),()=>{let a=performance.now()-e,i=a-n.childMs,o=this.callStack.lastIndexOf(n);o!==-1&&this.callStack.splice(o,1),this.callStack.length>0&&(this.callStack[this.callStack.length-1].childMs+=a),this._addEntry(t,a,i)}}record(t,e){this.enabled&&this._addEntry(t,e,e)}_addEntry(t,e,n){let s=this.entries.get(t);s?(s.callCount++,s.totalMs+=e,s.selfMs+=n,e>s.maxMs&&(s.maxMs=e),e<s.minMs&&(s.minMs=e)):this.entries.set(t,{callCount:1,totalMs:e,selfMs:n,maxMs:e,minMs:e})}getReport(){let t=[];for(let[e,n]of this.entries)t.push({name:e,callCount:n.callCount,totalMs:n.totalMs,selfMs:n.selfMs,avgMs:n.totalMs/n.callCount,maxMs:n.maxMs,minMs:n.minMs});return t.sort((e,n)=>n.callCount-e.callCount),t}getTop(t){return this.getReport().slice(0,t)}reset(){this.entries.clear(),this.callStack=[]}toMarkdown(){let t=this.getReport();if(t.length===0)return`| name | calls | totalMs | selfMs | avgMs | maxMs | minMs |
844
+ |------|-------|---------|--------|-------|-------|-------|
845
+ `;let e="| name | calls | totalMs | selfMs | avgMs | maxMs | minMs |",n="|------|-------|---------|--------|-------|-------|-------|",s=t.map(a=>`| ${a.name} | ${a.callCount} | ${a.totalMs.toFixed(3)} | ${a.selfMs.toFixed(3)} | ${a.avgMs.toFixed(3)} | ${a.maxMs.toFixed(3)} | ${a.minMs.toFixed(3)} |`);return[e,n,...s].join(`
846
+ `)}toJSON(){return this.getReport()}},Hu=new Vi;var zn=class{constructor(){this.stack=[];this.vars=new Map;this.ip=0}run(t){for(this.stack=[],this.vars=new Map,this.ip=0;this.ip<t.instructions.length;){let e=t.instructions[this.ip];switch(this.ip++,e.op){case 0:{let n=e.arg;this.push(t.constants[n]);break}case 1:{let n=e.arg;if(!this.vars.has(n))throw new Error(`VM: \uC815\uC758\uB418\uC9C0 \uC54A\uC740 \uBCC0\uC218: ${n}`);this.push(this.vars.get(n));break}case 2:{let n=e.arg,s=this.pop();this.vars.set(n,s);break}case 7:{this.pop();break}case 8:{if(this.stack.length===0)throw new Error("VM: \uC2A4\uD0DD \uC5B8\uB354\uD50C\uB85C (DUP)");this.push(this.stack[this.stack.length-1]);break}case 9:{let n=this.pop(),s=this.pop();this.push(s+n);break}case 10:{let n=this.pop(),s=this.pop();this.push(s-n);break}case 11:{let n=this.pop(),s=this.pop();this.push(s*n);break}case 12:{let n=this.pop(),s=this.pop();if(n===0)throw new Error("VM: 0\uC73C\uB85C \uB098\uB204\uAE30");this.push(s/n);break}case 13:{let n=this.pop(),s=this.pop();this.push(s%n);break}case 14:{let n=this.pop(),s=this.pop();this.push(s===n);break}case 19:{let n=this.pop(),s=this.pop();this.push(s!==n);break}case 15:{let n=this.pop(),s=this.pop();this.push(s<n);break}case 16:{let n=this.pop(),s=this.pop();this.push(s>n);break}case 17:{let n=this.pop(),s=this.pop();this.push(s<=n);break}case 18:{let n=this.pop(),s=this.pop();this.push(s>=n);break}case 20:{let n=this.pop(),s=this.pop();this.push(!!s&&!!n);break}case 21:{let n=this.pop(),s=this.pop();this.push(!!s||!!n);break}case 22:{let n=this.pop();this.push(!n);break}case 5:{this.ip=e.arg;break}case 6:{this.pop()||(this.ip=e.arg);break}case 23:{let n=e.arg;if(this.stack.length<n)throw new Error(`VM: \uC2A4\uD0DD \uC5B8\uB354\uD50C\uB85C (MAKE_LIST: need ${n}, have ${this.stack.length})`);let s=this.stack.splice(this.stack.length-n,n);this.push(s);break}case 24:{let n=this.pop(),s=e.arg;if(n!==null&&typeof n=="object")this.push(n[s]);else throw new Error("VM: GET_FIELD \uB300\uC0C1\uC774 \uAC1D\uCCB4\uAC00 \uC544\uB2D8");break}case 3:throw new Error("VM: CALL \uBBF8\uAD6C\uD604");case 4:return this.stack.length>0?this.stack[this.stack.length-1]:null;case 25:return this.stack.length>0?this.stack[this.stack.length-1]:null;default:throw new Error(`VM: \uC54C \uC218 \uC5C6\uB294 OpCode: ${e.op}`)}}return this.stack.length>0?this.stack[this.stack.length-1]:null}push(t){this.stack.push(t)}pop(){if(this.stack.length===0)throw new Error("VM: \uC2A4\uD0DD \uC5B8\uB354\uD50C\uB85C");return this.stack.pop()}};var Iy=new zn;function Gu(r,t,e,n){let s=r.context.variables.snapshot();for(let[a,i]of s){if(e.has(a)||!t.has(a))continue;let o=t.get(a);if(i!==o){t.set(a,i);for(let u=n.length-1;u>=0;u--)if(n[u].has(a)){n[u].set(a,i);break}}}}var Ks=5e3;function nn(r,t,e){if(typeof t=="string"){r.context.variables.set(t,e);return}if(t?.kind==="block"&&t?.type==="Map"){let s=t.fields?.get("keys");if(s?.kind==="block"&&s?.type==="Array"){let a=s.fields.get("items")??[];for(let i of a){let o=i?.kind==="literal"&&i?.type==="symbol"?i.value:i?.kind==="variable"?i.name.replace(/^\$/,""):null;if(o!==null){let u=o.startsWith("$")?o:"$"+o,f=e!==null&&typeof e=="object"?e[o]??null:null;r.context.variables.set(u,f)}}}}}function zi(r,t,e){if(r.tcoMode)return Ys(r,t,e);if(process.env.FL_VM==="1"&&xr.has(t))try{let d=xr.get(t),g=new Map;if(d._closure&&Array.isArray(d._closure)&&d._closure.length>0)for(let[h,y]of d._closure)g.set(h,y);else{let h=r.context.variables.snapshot();for(let[y,k]of h)g.set(y,k)}for(let[h,y]of xr)g.set("$"+h,y),g.set(h,y);for(let h=0;h<d._params.length;h++)g.set(d._params[h],e[h]??null);return Iy.run(d._chunk,g)}catch{}let n=t,s=null,a=t.match(/^([\w\-]+)\[([^\]]+)\]$/);a&&(n=a[1],s=a[2].split(",").map(g=>({kind:"type",name:g.trim()})));let i=r.context.functions.get(n);if(!i){let d=n.includes("_")?n.replace(/_/g,"-"):n.replace(/-/g,"_");d!==n&&(i=r.context.functions.get(d))}if(!i){let d=r.context.variables.get(n)??r.context.variables.get("$"+n);if(d&&(d.kind==="function-value"||d.kind==="async-function-value"||typeof d=="function"||d.params&&d.body)){if(d.kind==="function-value")return Js(r,d,e);if(d.kind==="async-function-value")return Xs(r,d,e);if(typeof d=="function")return d(...e);i=d}}if(!i){let d=[...r.context.functions.keys()],g=Xr[n]??Xr[n.replace(/-/g,"_")]??Xr[n.replace(/_/g,"-")],h;if(g)h=`'${n}'\uB294 \uC5C6\uC2B5\uB2C8\uB2E4. \uB300\uC2E0 '${g.correct}'\uB97C \uC0AC\uC6A9\uD558\uC138\uC694.
847
+ \uC0AC\uC6A9\uBC95: ${g.usage}`;else{let y=dn(n,d);h=y?`'${n}'\uB97C \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4. \uD639\uC2DC '${y}'\uB97C \uB9D0\uC500\uD558\uC2E0 \uAC74\uAC00\uC694?`:`'${n}'\uB97C \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4. \uD568\uC218\uAC00 \uC815\uC758\uB418\uC5B4 \uC788\uB294\uC9C0 \uD655\uC778\uD558\uC138\uC694.`}throw new Bt(n,r.currentFilePath,r.currentLine>0?r.currentLine:void 0,void 0,h)}if(i._call)return i._call(...e);let o=!1;if(i.generics&&i.generics.length>0){if(!s)throw new Error(`Generic function '${n}' requires type arguments, e.g., ${n}[int] or ${n}[int string]`);if(r.context.typeChecker){let d=r.context.typeChecker.instantiateGenericFunction(n,s);if(!d.valid)throw new Error(`Cannot instantiate generic function '${n}': ${d.message}`)}o=!0}if(!o&&r.context.runtimeTypeChecker&&r.context.runtimeTypeChecker.checkCall(n,e),typeof i.body=="function")return i.body(...e);if(i.paramDefaults)for(;e.length<i.params.length;){let d=i.paramDefaults[e.length];if(d!==void 0)e=[...e,r.eval(d)];else break}if(i.params.length>e.length){let d=i.params.map(g=>typeof g=="string"?g.replace(/^\$/,""):g?.kind==="variable"?g.name.replace(/^\$/,""):"\u2026");throw new Error(`Function '${n}' expects ${i.params.length} args (${d.join(", ")}), got ${e.length}`)}if(r.callDepth>=Ks){let d=r.callStack??[],g=d.slice(-10).map((h,y)=>` #${d.length-10+y}: ${h.fn} (line ${h.line})`).join(`
848
+ `);throw new Error(`[E_STACK_OVERFLOW] line ${r.currentLine}: Maximum call depth exceeded (${Ks}) \u2014 possible infinite recursion in '${n}'
849
+ `+(g?`\uCD5C\uADFC \uD638\uCD9C \uCCB4\uC778:
850
+ ${g}`:""))}let u=n.match(/^([^:]+):/),f=[];if(u){let d=u[1]+":";for(let[g,h]of r.context.functions)if(g.startsWith(d)){let y=g.slice(d.length);r.context.functions.has(y)||(r.context.functions.set(y,h),f.push(y))}}let l=Hu.enter(n),c=r.context.callStack,p=e.slice(0,5).map(d=>d===null?"nil":Array.isArray(d)?`[${d.length}]`:typeof d=="object"?"{obj}":typeof d=="function"?"<fn>":typeof d=="string"?d.length>20?`"${d.slice(0,17)}..."`:`"${d}"`:String(d)),m={name:n,line:r.currentLine,args:p};if(process.env.FL_TRACE==="1"&&console.error(`[trace] ${" ".repeat(Math.min(r.callDepth,20))}\u2192 ${n}(${p.join(", ")}) (line ${r.currentLine})`),i.capturedEnv){let d=r.context.variables.saveStack(),g=new Set(i.params);r.callDepth++,c.push(m),c.length>100&&c.shift();let h;try{r.context.variables.fromSnapshot(i.capturedEnv);for(let y=0;y<i.params.length;y++)nn(r,i.params[y],e[y]);h=r.eval(i.body),Gu(r,i.capturedEnv,g,d)}catch(y){if(Rt(y))h=y.value;else throw y instanceof Error&&!y.__flCallStack&&(y.__flCallStack=[...c]),y}finally{r.callDepth--,c.pop(),r.context.variables.restoreStack(d);for(let y of f)r.context.functions.delete(y);l()}return h}r.context.variables.push(),r.callDepth++,c.push(m),c.length>100&&c.shift();try{for(let d=0;d<2e6;d++){for(let h=0;h<i.params.length;h++)nn(r,i.params[h],e[h]);let g;try{g=r.eval(i.body)}catch(h){if(Rt(h))return h.value;throw h instanceof Error&&!h.__flCallStack&&(h.__flCallStack=[...c]),h}if(g&&typeof g=="object"&&g.__FL_RECUR__){e=g.__args;continue}return g}throw new Error(`recur: max iterations exceeded in '${n}'`)}finally{r.callDepth--,c.pop(),r.context.variables.pop();for(let d of f)r.context.functions.delete(d);l()}}function Js(r,t,e){if(r.tcoMode)return Qs(r,t,e);if(t._call)return t._call(...e);if(t.kind!=="function-value")throw new Error(`Expected function-value, got ${t.kind}`);if(t.paramDefaults)for(;e.length<t.params.length;){let i=t.paramDefaults[e.length];if(i!==void 0)e=[...e,i];else break}if(r.callDepth>=Ks)throw new Error(`FreeLang line ${r.currentLine}: Maximum call depth exceeded (${Ks}) \u2014 possible infinite recursion`);let n=r.context.variables.saveStack(),s=new Set(t.params);r.callDepth++;let a;try{r.context.variables.fromSnapshot(t.capturedEnv);for(let i=0;i<t.params.length;i++)nn(r,t.params[i],e[i]);a=r.eval(t.body),Gu(r,t.capturedEnv,s,n)}catch(i){if(Rt(i))a=i.value;else{if(i instanceof Error&&!i.__flCallStack){let o=r.context?.callStack;o?.length&&(i.__flCallStack=[...o])}throw i}}finally{r.callDepth--,r.context.variables.restoreStack(n)}return a}function Xs(r,t,e){if(t.kind!=="async-function-value")throw new Error(`Expected async-function-value, got ${t.kind}`);return new ae((n,s)=>{let a=r.context.variables.saveStack();try{r.context.variables.fromSnapshot(t.capturedEnv);for(let o=0;o<t.params.length;o++)nn(r,t.params[o],e[o]);let i=r.eval(t.body);i instanceof ae?i.then(o=>n(o)).catch(o=>s(o)):n(i)}catch(i){s(i)}finally{r.context.variables.restoreStack(a)}})}function Ku(r,t,e){if(t.kind==="builtin-function")return t.fn(e.map(n=>r.eval(n)));if(t.kind==="function-value")return Js(r,t,e);if(t.kind==="async-function-value")return Xs(r,t,e);if(typeof t=="function")return t(...e);if(typeof t=="string"){let n=e.map(s=>({kind:"literal",value:s,type:s===null?"any":Array.isArray(s)?"list":typeof s}));return r.eval({kind:"sexpr",op:t,args:n})}else{if(t&&t.params&&t.body)return zi(r,t.name||"anonymous",e);throw new Error(`Cannot call ${typeof t}: ${JSON.stringify(t).slice(0,100)}`)}}function Ys(r,t,e){let n=t,s=e,a=r.tcoMode;r.tcoMode=!0;try{for(let i=0;i<2e6;i++){let o=n,u=n.match(/^([\w\-]+)\[([^\]]+)\]$/);u&&(o=u[1]);let f=r.context.functions.get(o);if(!f){let m=o.includes("_")?o.replace(/_/g,"-"):o.replace(/-/g,"_");m!==o&&(f=r.context.functions.get(m))}if(!f){let m=[...r.context.functions.keys()],d=dn(o,m),g=d?`'${o}'\uB97C \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4. \uD639\uC2DC '${d}'\uB97C \uB9D0\uC500\uD558\uC2E0 \uAC74\uAC00\uC694?`:`'${o}'\uB97C \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4. \uD568\uC218\uAC00 \uC815\uC758\uB418\uC5B4 \uC788\uB294\uC9C0 \uD655\uC778\uD558\uC138\uC694.`;throw new Bt(o,r.currentFilePath,r.currentLine>0?r.currentLine:void 0,void 0,g)}if(f._call)return f._call(...s);if(typeof f.body=="function")return f.body(...s);let l=o.match(/^([^:]+):/),c=[];if(l){let m=l[1]+":";for(let[d,g]of r.context.functions)if(d.startsWith(m)){let h=d.slice(m.length);r.context.functions.has(h)||(r.context.functions.set(h,g),c.push(h))}}let p;try{if(f.capturedEnv){let m=r.context.variables.saveStack();try{r.context.variables.fromSnapshot(f.capturedEnv);for(let d=0;d<f.params.length;d++)nn(r,f.params[d],s[d]);p=r.eval(f.body)}catch(d){if(Rt(d))p=d.value;else throw d}finally{r.context.variables.restoreStack(m)}}else{r.context.variables.push();try{for(let m=0;m<f.params.length;m++)nn(r,f.params[m],s[m]);p=r.eval(f.body)}catch(m){if(Rt(m))p=m.value;else throw m}finally{r.context.variables.pop()}}}finally{for(let m of c)r.context.functions.delete(m)}if(oi(p))if(typeof p.fn=="string"){n=p.fn,s=p.args;continue}else return Qs(r,p.fn,p.args);return p}throw new Error(`TCO: \uCD5C\uB300 \uBC18\uBCF5(2,000,000) \uCD08\uACFC \u2014 '${n}'\uC5D0\uC11C \uBB34\uD55C \uC7AC\uADC0 \uAC00\uB2A5\uC131`)}finally{r.tcoMode=a}}function Qs(r,t,e){let n=r.tcoMode;r.tcoMode=!0;try{let s=t,a=e;for(let i=0;i<1e6;i++){if(s.kind!=="function-value")throw new Error(`Expected function-value, got ${s.kind}`);let o=r.context.variables.saveStack(),u;try{r.context.variables.fromSnapshot(s.capturedEnv);for(let f=0;f<s.params.length;f++)nn(r,s.params[f],a[f]);u=r.eval(s.body)}finally{r.context.variables.restoreStack(o)}if(oi(u)){if(typeof u.fn=="string")return Ys(r,u.fn,u.args);s=u.fn,a=u.args;continue}return u}throw new Error("TCO: \uCD5C\uB300 \uBC18\uBCF5(1,000,000) \uCD08\uACFC \u2014 function-value\uC5D0\uC11C \uBB34\uD55C \uC7AC\uADC0 \uAC00\uB2A5\uC131")}finally{r.tcoMode=n}}function Ju(r,t,e){let n=r.context.functions.get(t);if(!n)throw new Bt(t,r.currentFilePath,r.currentLine>0?r.currentLine:void 0);if(typeof n.body=="function")return n.body(...e);let s;if(n.capturedEnv){let a=r.context.variables.saveStack();try{r.context.variables.fromSnapshot(n.capturedEnv);for(let i=0;i<n.params.length;i++)r.context.variables.set(n.params[i],e[i]);s=r.eval(n.body)}finally{r.context.variables.restoreStack(a)}}else{r.context.variables.push();try{for(let a=0;a<n.params.length;a++)r.context.variables.set(n.params[a],e[a]);s=r.eval(n.body)}finally{r.context.variables.pop()}}return s}function Xu(r,t,e){if(t.kind!=="function-value")throw new Error(`Expected function-value, got ${t.kind}`);let n=r.context.variables.saveStack();try{r.context.variables.fromSnapshot(t.capturedEnv);for(let s=0;s<t.params.length;s++)r.context.variables.set(t.params[s],e[s]);return r.eval(t.body)}finally{r.context.variables.restoreStack(n)}}var Zs=class{constructor(){this.macros=new Map}define(t,e,n){this.macros.set(t,{name:t,params:e,body:n})}has(t){return this.macros.has(t)}getMacro(t){return this.macros.get(t)}expand(t){if(t.kind==="sexpr"){let e=t,n=e.op;if(this.macros.has(n)){let s=this.macros.get(n),a=e.args.map(l=>this.expand(l)),i=new Map;for(let l=0;l<s.params.length;l++){let c=s.params[l],p=c.startsWith("$")?c:"$"+c;i.set(p,a[l]??{kind:"literal",type:"null",value:null})}let o=new Map,u=this.renameLocals(s.body,i,o),f=this.substitute(u,i);return this.expand(f)}return{...e,args:e.args.map(s=>this.expand(s))}}return t}renameLocals(t,e,n){if(t.kind==="variable"){let s=t,a=s.name.startsWith("$")?s.name:"$"+s.name;return e.has(a)?t:n.has(a)?{kind:"variable",name:n.get(a)}:t}if(t.kind==="sexpr"){let s=t;if(s.op==="let"||s.op==="set"){let a=new Map(n),i=s.args.map((o,u)=>this.renameLocals(o,e,a));return{...s,args:i}}return{...s,args:s.args.map(a=>this.renameLocals(a,e,n))}}return t}substitute(t,e){if(t.kind==="variable"){let n=t,s=n.name.startsWith("$")?n.name:"$"+n.name;return e.has(s)?e.get(s):t}if(t.kind==="literal"){let n=t;if(n.type==="symbol"){let s="$"+n.value;if(e.has(s))return e.get(s)}return t}if(t.kind==="sexpr"){let n=t;return{...n,args:n.args.map(s=>this.substitute(s,e))}}if(t.kind==="block"){let n=t,s=new Map;for(let[a,i]of n.fields.entries())Array.isArray(i)?s.set(a,i.map(o=>this.substitute(o,e))):s.set(a,this.substitute(i,e));return{...n,fields:s}}return t}astToString(t){if(t.kind==="sexpr"){let e=t,n=e.args.map(s=>this.astToString(s)).join(" ");return`(${e.op}${n?" "+n:""})`}if(t.kind==="literal"){let e=t;return e.type==="string"?`"${e.value}"`:e.type==="null"?"nil":String(e.value)}return t.kind==="variable"?t.name:t.kind==="keyword"?":"+t.name:JSON.stringify(t)}};var ea=class{constructor(){this.protocols=new Map;this.impls=new Map;this.methodIndex=new Map}defineProtocol(t){this.protocols.set(t.name,t);for(let e of t.methods)this.methodIndex.has(e.name)||this.methodIndex.set(e.name,new Set),this.methodIndex.get(e.name).add(t.name)}defineImpl(t){let e=`${t.protocolName}:${t.typeName}`;this.impls.set(e,t)}resolveMethod(t,e){let n=this.extractTypeName(e);if(!n)return null;let s=this.methodIndex.get(t);if(!s)return null;for(let a of s){let i=`${a}:${n}`,o=this.impls.get(i);if(o&&o.methods.has(t))return o}return null}resolveMethodForType(t,e){let n=this.methodIndex.get(t);if(!n)return null;for(let s of n){let a=`${s}:${e}`,i=this.impls.get(a);if(i&&i.methods.has(t))return i}return null}hasMethod(t){return this.methodIndex.has(t)}getProtocol(t){return this.protocols.get(t)}getImpl(t,e){return this.impls.get(`${t}:${e}`)}extractTypeName(t){return t==null?null:typeof t=="object"&&!Array.isArray(t)&&t.__type?String(t.__type):Array.isArray(t)?"List":typeof t=="string"?"String":typeof t=="number"?"Number":typeof t=="boolean"?"Boolean":null}};var ta=class{constructor(){this.structs=new Map}define(t){this.structs.set(t.name,t)}get(t){return this.structs.get(t)}names(){return Array.from(this.structs.keys())}makeConstructor(t){let e=this.structs.get(t);if(!e)throw new Error(`StructRegistry: unknown struct "${t}"`);return(...n)=>{if(n.length!==e.fields.length)throw new Error(`${t} constructor: expected ${e.fields.length} arguments, got ${n.length}`);let s={__type:t};for(let a=0;a<e.fields.length;a++)s[e.fields[a].name]=n[a];return s}}makePredicate(t){return e=>e==null||typeof e!="object"?!1:e.__type===t}makeAccessor(t,e){return n=>{if(n==null)throw new Error(`${t}.${e}: cannot access field on null/undefined`);if(typeof n!="object")throw new Error(`${t}.${e}: expected struct, got ${typeof n}`);if(n.__type!==t)throw new Error(`${t}.${e}: expected ${t}, got ${n.__type??typeof n}`);if(!(e in n))throw new Error(`${t}.${e}: field "${e}" not found`);return n[e]}}isStruct(t){return t!==null&&typeof t=="object"&&t.__type!==void 0}getFields(t){let e=this.structs.get(t);return e?e.fields.map(n=>n.name):[]}};Br();var Ji=class{constructor(){this.steps=[]}step(t,e,n){let s=`step-${this.steps.length+1}`,a=this.steps.length>0?this.steps[this.steps.length-1].result:void 0,i=Date.now(),o,u;try{o=e(a)}catch(c){u=c,o={kind:"cot-error",error:c instanceof Error?c.message:String(c)}}let f=Date.now()-i,l={id:s,thought:t,result:o,durationMs:f};if(n!==void 0&&(l.confidence=n),this.steps.push(l),u!==void 0)throw u;return this}conclude(t){let e=t(this.steps),n=this.steps.filter(a=>a.confidence!==void 0).map(a=>a.confidence),s=n.length>0?n.reduce((a,i)=>a+i,0)/n.length:void 0;return{steps:[...this.steps],conclusion:e,totalSteps:this.steps.length,confidence:s}}getSteps(){return[...this.steps]}toMarkdown(){let t=[`# Chain-of-Thought \uCD94\uB860
851
+ `];for(let e=0;e<this.steps.length;e++){let n=this.steps[e];t.push(`## Step ${e+1}: ${n.thought}`),t.push(`- **\uACB0\uACFC**: ${JSON.stringify(n.result)}`),n.confidence!==void 0&&t.push(`- **\uD655\uC2E0\uB3C4**: ${(n.confidence*100).toFixed(0)}%`),n.durationMs!==void 0&&t.push(`- **\uC18C\uC694\uC2DC\uAC04**: ${n.durationMs}ms`),t.push("")}return t.join(`
852
+ `)}toJSON(){return{kind:"chain-of-thought",totalSteps:this.steps.length,steps:this.steps.map(t=>({id:t.id,thought:t.thought,result:t.result,confidence:t.confidence,durationMs:t.durationMs}))}}reset(){return this.steps=[],this}};function Yu(r,t,e,n){let s=new Ji,a=null;function i(f,l){return f?f.kind==="keyword"&&f.name===l||f.kind==="literal"&&f.type==="string"&&f.value===l:!1}let o=0;for(;o<r.length;){let f=r[o];if(i(f,"step")){if(o++,o>=r.length)throw new Error("COT :step requires a description string");let l=r[o],c;if(l?.kind==="literal"&&typeof l.value=="string"?c=l.value:c=String(t(l)),o++,o>=r.length)throw new Error(`COT :step "${c}" requires an expression`);let p=r[o];o++;let m;o<r.length&&i(r[o],"confidence")&&(o++,o<r.length&&(m=Number(t(r[o])),o++)),s.step(c,d=>(e("$prev",d!==void 0?d:null),t(p)),m);continue}if(i(f,"conclude")){if(o++,o>=r.length)throw new Error("COT :conclude requires a function");a=t(r[o]),o++;continue}o++}let u=f=>a===null?f.length>0?f[f.length-1].result:null:typeof a=="function"?a(f):(a?.kind==="function-value"&&e("$__cot_steps__",f),a);return s.conclude(u)}var ra=class{constructor(){this._branches=[];this._scoreFn=null;this._pruneThreshold=0;this._executed=[]}branch(t,e){return this._branches.push({hypothesis:t,fn:e}),this}evaluate(t){return this._scoreFn=t,this}prune(t){return this._pruneThreshold=t,this}select(t="best",e=1){this._executed=this._branches.map((u,f)=>{let l;try{l=u.fn()}catch(p){l={error:String(p.message??p)}}at(l)?l={maybeValue:l.value,confidence:l.confidence}:Se(l)&&(l=null);let c=this._scoreFn?Ly(this._scoreFn(l),0,1):.5;return{id:`branch-${f}`,hypothesis:u.hypothesis,result:l,score:c,pruned:!1}});let n=this._executed.length,s=0;for(let u of this._executed)u.score<this._pruneThreshold&&(u.pruned=!0,s++);let a=this._executed.filter(u=>!u.pruned);if(a.length===0&&this._executed.length>0){let u=[...this._executed].sort((f,l)=>l.score-f.score)[0];u.pruned=!1,a.push(u),s--}a.sort((u,f)=>f.score-u.score);let i,o;return t==="top-k"?(o=a.slice(0,e),i=o[0]):(i=a[0],o=this._executed),{branches:o,best:i,explored:n,pruned:s}}toMarkdown(){if(this._executed.length===0)return`# Tree-of-Thought
853
+
854
+ \uBD84\uAE30 \uC5C6\uC74C. \`select()\` \uBA3C\uC800 \uD638\uCD9C\uD558\uC138\uC694.
855
+ `;let t=[`# Tree-of-Thought \uD0D0\uC0C9 \uACB0\uACFC
856
+ `],e=[...this._executed].sort((s,a)=>a.score-s.score);for(let s of e){let a=s.pruned?"\u2702\uFE0F PRUNED":"\u2705 ALIVE";t.push(`## [${s.id}] ${s.hypothesis}`),t.push(`- \uC0C1\uD0DC: ${a}`),t.push(`- \uC810\uC218: ${s.score.toFixed(4)}`),t.push(`- \uACB0\uACFC: ${JSON.stringify(s.result)}`),t.push("")}let n=e.filter(s=>!s.pruned);return n.length>0&&(t.push(`## \uCD5C\uC120 \uC120\uD0DD: ${n[0].hypothesis}`),t.push(`\uC810\uC218: ${n[0].score.toFixed(4)}`)),t.join(`
857
+ `)}};function Ly(r,t,e){return Math.max(t,Math.min(e,r))}var Xi=class{constructor(){this.criteriaList=[]}addCriteria(t){return this.criteriaList.push(t),this}reflect(t,e=.7){let n={},s=[];if(this.criteriaList.length===0)return{output:t,scores:{},totalScore:1,passed:!0,feedback:[]};let a=0,i=0;for(let f of this.criteriaList){let l;try{l=f.check(t),l=Math.max(0,Math.min(1,l))}catch{l=0}n[f.name]=l;let c=f.weight??1;a+=c,i+=l*c,l<e&&s.push(`[${f.name}] score=${l.toFixed(2)} \u2014 \uAE30\uC900 \uBBF8\uB2EC (threshold=${e})`)}let o=a>0?i/a:0,u=o>=e;return{output:t,scores:n,totalScore:o,passed:u,feedback:s}}revise(t,e){let n=e(t);return{...t,revised:n}}toMarkdown(){let t=[];if(t.push("# Reflector \uD3C9\uAC00 \uAE30\uC900"),t.push(""),this.criteriaList.length===0)t.push("- (\uAE30\uC900 \uC5C6\uC74C)");else for(let e of this.criteriaList)t.push(`- **${e.name}** (weight=${e.weight??1})`);return t.join(`
858
+ `)}getCriteriaList(){return this.criteriaList}};function Qu(r){let{output:t,criteria:e,threshold:n=.7,onFail:s,revise:a}=r,i=new Xi;e.forEach((u,f)=>{i.addCriteria({name:`criteria-${f}`,check:u,weight:1})});let o=i.reflect(t,n);if(!o.passed&&s){let u=s(o);o={...o,revised:u}}return a&&(o=i.revise(o,a)),o}var sa=class{constructor(t){this.stepFunctions=[];this.stepCursor=0;this.options=t,this.state={goal:t.goal,step:0,maxSteps:t.maxSteps??10,memory:{},history:[],done:!1}}step(t,e){return this.stepFunctions.push({thought:t,fn:e}),this}run(t){for(;!this.state.done&&this.state.step<this.state.maxSteps&&!(this.options.stopWhen&&this.options.stopWhen(this.state));){let e=null;if(t){if(e=t(this.state),e===null)break}else if(this.stepCursor<this.stepFunctions.length){let{thought:n,fn:s}=this.stepFunctions[this.stepCursor],a=s(this.state);e={step:this.state.step,thought:n,action:n,observation:a},this.stepCursor++}else break;if(this.state.step++,this.state.history.push(e),this.options.onStep&&this.options.onStep({...this.state}),this.options.stopWhen&&this.options.stopWhen(this.state))break}return this.state.step>=this.state.maxSteps&&!this.state.done&&(this.state.done=!0),this.state}getState(){return this.state}isDone(){return this.state.done}setResult(t){this.state.result=t,this.state.done=!0}toMarkdown(){let t=[`# Agent: ${this.state.goal}
859
+ `];t.push(`- **\uBAA9\uD45C**: ${this.state.goal}`),t.push(`- **\uC644\uB8CC**: ${this.state.done}`),t.push(`- **\uCD1D \uB2E8\uACC4**: ${this.state.step}`),this.state.result!==void 0&&t.push(`- **\uACB0\uACFC**: ${JSON.stringify(this.state.result)}`),t.push("");for(let e of this.state.history)t.push(`## Step ${e.step+1}: ${e.thought}`),t.push(`- **\uC561\uC158**: ${e.action}`),t.push(`- **\uAD00\uCC30**: ${JSON.stringify(e.observation)}`),t.push("");return t.join(`
860
+ `)}};function By(r,t,e=null){return t in r.memory?r.memory[t]:e}function Dy(r,t,e){r.memory[t]=e}function qy(r,t){return r.done=!0,r.result=t,r}function Zu(r,t,e){let n=r.get("goal"),s=n!=null?String(t(n)):"unknown",a=r.get("max-steps"),i=a!=null?Number(t(a)):10,o=r.get("step"),u=null;o!=null&&(u=t(o));let f=r.get("stop-when"),l=null;f!=null&&(l=t(f));let c=r.get("on-step"),p=null;c!=null&&(p=t(c));let m={goal:s,maxSteps:i};l!=null&&(m.stopWhen=h=>{let y=e(l,[h]);return y===!0||y===1}),p!=null&&(m.onStep=h=>{e(p,[h])});let d=new sa(m),g=u!=null?h=>{let y=e(u,[h]);return h.done?null:{step:h.step,thought:`step-${h.step}`,action:"fl-step",observation:y}}:void 0;return d.run(g)}function ep(r){return{"agent-new":(...t)=>{let e={goal:"unnamed"};for(let n=0;n<t.length;n+=2){let s=String(t[n]).replace(/^:/,""),a=t[n+1];s==="goal"?e.goal=String(a):s==="max-steps"?e.maxSteps=Number(a):s==="tools"&&(e.tools=Array.isArray(a)?a.map(String):[])}return new sa(e)},"agent-run":(t,e)=>{if(!e)return t.run();let n=s=>{let a=r.callFunctionValue(e,[s]);return s.done||a==null?null:typeof a=="object"&&"thought"in a?a:{step:s.step,thought:`step-${s.step}`,action:"fl-step",observation:a}};return t.run(n)},"agent-done?":t=>t.isDone(),"agent-result":t=>t.getState().result??null,"agent-history":t=>t.getState().history,"agent-state":t=>t.getState(),"agent-markdown":t=>t.toMarkdown(),"get-memory":(t,e,n=null)=>By(t,e,n),"set-memory":(t,e,n)=>(Dy(t,e,n),null),"agent-done":(t,e)=>qy(t,e),"agent-continue":t=>t}}function aa(r){return{instructions:r.instructions.map(t=>({...t})),constants:[...r.constants],name:r.name}}var Uy=new Set([9,10,11,12,13,14,19,15,16,17,18,20,21]);function Vy(r,t,e){switch(r){case 9:return t+e;case 10:return t-e;case 11:return t*e;case 12:return e===0?null:t/e;case 13:return t%e;case 14:return t===e;case 19:return t!==e;case 15:return t<e;case 16:return t>e;case 17:return t<=e;case 18:return t>=e;case 20:return!!t&&!!e;case 21:return!!t||!!e;default:return null}}var zy={name:"constant-folding",run(r){let t=aa(r),e=!0;for(;e;){e=!1;let n=t.instructions;for(let s=0;s+2<n.length;s++){let a=n[s],i=n[s+1],o=n[s+2];if(a.op===0&&i.op===0&&Uy.has(o.op)){let u=t.constants[a.arg],f=t.constants[i.arg];if(o.op===12&&f===0)continue;let l=Vy(o.op,u,f),c=t.constants.indexOf(l);c===-1&&(c=t.constants.length,t.constants.push(l)),n.splice(s,3,{op:0,arg:c});for(let p=0;p<n.length;p++){let m=n[p];(m.op===5||m.op===6)&&typeof m.arg=="number"&&(m.arg>s+2?m.arg-=2:m.arg>s&&(m.arg=s))}e=!0;break}}}return t}},Wy={name:"dead-code-elimination",run(r){let t=aa(r),e=t.instructions,n=e.findIndex(s=>s.op===25);return n!==-1&&n<e.length-1&&(t.instructions=e.slice(0,n+1)),t}},Hy={name:"push-pop-elimination",run(r){let t=aa(r),e=!0;for(;e;){e=!1;let n=t.instructions;for(let s=0;s+1<n.length;s++){let a=n[s],i=n[s+1];if(a.op===0&&i.op===7){n.splice(s,2);for(let o=0;o<n.length;o++){let u=n[o];(u.op===5||u.op===6)&&typeof u.arg=="number"&&(u.arg>s+1?u.arg-=2:u.arg>s&&(u.arg=s))}e=!0;break}}}return t}},Gy={name:"jump-optimization",run(r){let t=aa(r),e=!0;for(;e;){e=!1;let n=t.instructions;for(let s=0;s<n.length;s++){let a=n[s];if(a.op===5&&a.arg===s+1){n.splice(s,1);for(let i=0;i<n.length;i++){let o=n[i];(o.op===5||o.op===6)&&typeof o.arg=="number"&&o.arg>s&&(o.arg-=1)}e=!0;break}}}return t}},Yi=class{constructor(){this.passes=[];this.stats=[]}addPass(t){return this.passes.push(t),this}optimize(t){this.stats=[];let e=t;for(let n of this.passes){let s=e.instructions.length,a=n.run(e),i=s-a.instructions.length;this.stats.push({passName:n.name,reduced:i}),e=a}return e}getStats(){return this.stats}};function tp(){return new Yi().addPass(zy).addPass(Wy).addPass(Hy).addPass(Gy)}var we=class r{constructor(t,e){this.currentLine=0;this.callDepth=0;this.callStack=[];this.tcoMode=!1;this.importedFiles=new Set;this.currentFilePath=process.cwd();this.debugSession=Wi();this.serverConfig=null;this.logger=t||Vo();let n=e?.strict??process.env.FREELANG_STRICT==="1";this.context={functions:new Map,routes:new Map,intents:new Map,variables:new Yr,middleware:[],errorHandlers:{handlers:new Map},startTime:Date.now(),typeChecker:Lo(),runtimeTypeChecker:new Jr(n),typeClasses:new Map,typeClassInstances:new Map,modules:new Map,macroExpander:new Zs,protocols:new ea,structs:new ta,callStack:[],lastError:void 0};let s=process.env.BRAVE_SEARCH_KEY||process.env.SERPER_API_KEY,a=process.env.BRAVE_SEARCH_KEY?"brave":process.env.SERPER_API_KEY?"serper":"mock";if(this.searchAdapter=new Qr(s,a),this.learnedFactsStore=new Zr("./data/learned-facts.json",30),Bu(this),!process.env.FL_NO_AUTO_ENV)try{let i=require("fs"),u=require("path").resolve(process.cwd(),".env");if(i.existsSync(u)){let f=i.readFileSync(u,"utf-8");for(let l of f.split(`
861
+ `)){let c=l.trim();if(!c||c.startsWith("#"))continue;let p=c.indexOf("=");if(p===-1)continue;let m=c.slice(0,p).trim(),d=c.slice(p+1).trim();(d.startsWith('"')&&d.endsWith('"')||d.startsWith("'")&&d.endsWith("'"))&&(d=d.slice(1,-1)),m&&process.env[m]===void 0&&(process.env[m]=d)}}}catch{}this.loadFlStdlib(),this.registerBuiltinTypeClasses(),this.registerStandardMacros(),this.registerAgentBuiltins()}get globals(){return this.context.functions}static{this.CALL_STACK_LIMIT=100}static{this.MAX_CALL_DEPTH=5e3}static{this._vmCompiler=new jn}static{this._vmOptimizer=tp()}static{this._vm=new zn}static{this._vmEnabled=process.env.FL_VM==="1"}registerAgentBuiltins(){let t=ep(this);for(let[e,n]of Object.entries(t))this.context.functions.set(e,{name:e,params:[],body:n})}registerStandardMacros(){this.context.macroExpander.define("and2",["$a","$b"],{kind:"sexpr",op:"if",args:[{kind:"variable",name:"$a"},{kind:"variable",name:"$b"},{kind:"literal",type:"boolean",value:!1}]})}loadFlStdlib(){try{let a=np.join(__dirname,"freelang-stdlib.fl");if(!ia.existsSync(a))return;let i=ia.readFileSync(a,"utf-8");this.interpret(H(W(i)))}catch{}let t=a=>Array.isArray(a)?a[0]==="some":a?.tag==="Some",e=a=>Array.isArray(a)?a[1]:a?.value,n=(a,i)=>typeof a=="string"?this.callUserFunction(a,[i]):a(i),s={"ok?":a=>a?.tag==="Ok","err?":a=>a?.tag==="Err","some?":a=>t(a),"none?":a=>Array.isArray(a)?a[0]==="none":a?.tag==="None","maybe-or":(a,i)=>t(a)?e(a):i,"maybe-map":(a,i)=>t(a)?{tag:"Some",kind:"Option",value:n(i,e(a))}:a,"maybe-chain":(a,i)=>t(a)?n(i,e(a)):a,"result-or":(a,i)=>a?._tag==="Ok"||a?.tag==="Ok"?a.value:i,"result-map":(a,i)=>a?._tag==="Ok"||a?.tag==="Ok"?{_tag:"Ok",tag:"Ok",kind:"Result",value:n(i,a.value)}:a,"result-chain":(a,i)=>a?._tag==="Ok"||a?.tag==="Ok"?n(i,a.value):a};for(let[a,i]of Object.entries(s))this.context.functions.set(a,{name:a,params:[],body:i})}registerModule(t){for(let[e,n]of Object.entries(t))if(this.context.functions.set(e,{name:e,params:[],body:n}),this.context.typeChecker){let s=Array(n.length).fill({kind:"type",name:"any"});this.context.typeChecker.registerFunction(e,s,{kind:"type",name:"any"})}}interpret(t){try{for(let e of t)e.kind==="sexpr"&&e.op==="defmacro"&&this.evalDefmacro(e);t=t.map(e=>e.kind==="sexpr"&&e.op==="defmacro"?e:this.context.macroExpander.expand(e));for(let e of t)e.kind==="sexpr"&&e.op==="defmacro"||(Co(e)?this.evalImportBlock(e):No(e)?this.evalOpenBlock(e):Oo(e)?this.context.lastValue=this.handleSearchBlock(e):Fo(e)?this.context.lastValue=this.handleLearnBlock(e):Po(e)?this.context.lastValue=this.handleReasoningBlock(e):jo(e)?this.context.lastValue=this.handleReasoningSequence(e):To(e)?this.evalModuleBlock(e):Lt(e)?this.evalBlock(e):this.context.lastValue=this.eval(e))}catch(e){throw e&&e.constructor&&e.constructor.name==="ReturnSignal"||(e instanceof Error&&this.currentLine>0&&!e.message.includes("FreeLang line")&&(e.message=`FreeLang line ${this.currentLine}: ${e.message}`),e instanceof Error&&!e.__flCallStack&&this.context.callStack.length>0&&(e.__flCallStack=[...this.context.callStack])),e}return this.context}run(t){return this.interpret(H(W(t)))}evalBlock(t){switch(t.type){case"PAGE":this.context.lastValue=this.handlePageBlock(t);break;case"API":this.context.lastValue=this.handleApiBlock(t);break;case"COMPONENT":this.context.lastValue=this.handleComponentBlock(t);break;case"FORM":this.context.lastValue=this.handleFormBlock(t);break;case"SERVICE":this.context.lastValue=this.handleServiceBlock(t);break;case"CONTROLLER":this.context.lastValue=this.handleControllerBlock(t);break;case"GUARD":this.context.lastValue=this.handleGuardBlock(t);break;case"MODEL":this.context.lastValue=this.handleModelBlock(t);break;case"QUERY":this.context.lastValue=this.handleQueryBlock(t);break;case"MIGRATION":this.context.lastValue=this.handleMigrationBlock(t);break;case"REPOSITORY":this.context.lastValue=this.handleRepositoryBlock(t);break;case"DATABASE":this.context.lastValue=this.handleDatabaseBlock(t);break;case"CACHE":this.context.lastValue=this.handleCacheBlock(t);break;case"CACHED":this.context.lastValue=this.handleCachedBlock(t);break;case"KAFKA":this.context.lastValue=this.handleKafkaBlock(t);break;case"PRODUCER":this.context.lastValue=this.handleProducerBlock(t);break;case"CONSUMER":this.context.lastValue=this.handleConsumerBlock(t);break;case"QUEUE":this.context.lastValue=this.handleQueueBlock(t);break;case"RABBITMQ":this.context.lastValue=this.handleRabbitMQBlock(t);break;case"JWT":this.context.lastValue=this.handleJWTBlock(t);break;case"OAUTH":this.context.lastValue=this.handleOAuthBlock(t);break;case"DOCKERFILE":this.context.lastValue=this.handleDockerfileBlock(t);break;case"DOCKER-COMPOSE":this.context.lastValue=this.handleDockerComposeBlock(t);break;case"K8S-DEPLOYMENT":this.context.lastValue=this.handleK8sDeploymentBlock(t);break;case"K8S-SERVICE":this.context.lastValue=this.handleK8sServiceBlock(t);break;case"K8S-INGRESS":this.context.lastValue=this.handleK8sIngressBlock(t);break;case"AWS":case"AWS-S3":case"AWS-LAMBDA":case"AWS-RDS":case"AWS-SQS":this.context.lastValue=this.handleAwsBlock(t);break;case"GCP":case"GCP-CLOUD-RUN":case"GCP-BIGQUERY":this.context.lastValue=this.handleGcpBlock(t);break;case"AZURE":case"AZURE-FUNCTION":case"AZURE-COSMOS":this.context.lastValue=this.handleAzureBlock(t);break;case"SERVER":this.handleServerBlock(t);break;case"ROUTE":this.handleRouteBlock(t);break;case"FUNC":this.handleFuncBlock(t);break;case"INTENT":this.handleIntentBlock(t);break;case"MIDDLEWARE":this.handleMiddlewareBlock(t);break;case"WEBSOCKET":this.handleWebSocketBlock(t);break;case"ERROR-HANDLER":this.handleErrorHandlerBlock(t);break;case"TOOL":this.context.lastValue=this.handleToolBlock(t);break;case"USE-TOOL":this.context.lastValue=this.handleUseToolBlock(t);break;case"AGENT":this.handleAgentBlock(t);break;default:break}}handleAgentBlock(t){let e=this,n=i=>e.eval(i),s=(i,o)=>e.callFunctionValue(i,o),a=Zu(t.fields,n,s);this.context.lastValue=a}handlePageBlock(t){let e=t.fields.get("render");if(!e)return null;let n=this.context.__params||{};this.context.variables.push();for(let[s,a]of Object.entries(n))this.context.variables.set(`$${s}`,a);try{let s;if(e.kind==="block"?(this.evalBlock(e),s=this.context.lastValue):s=this.eval(e),typeof s=="string"){let a=s;for(let[o,u]of Object.entries(n))a=a.replace(new RegExp(`{{\\s*${o}\\s*}}`,"g"),String(u));let i=t.fields.get("state");if(i){let o=this.eval(i),u=JSON.stringify(o);a=a+`
862
+ <script>window.__state = ${u};</script>`}return a}return s}finally{this.context.variables.pop()}}handleApiBlock(t){let e=t.fields.get("do");if(!e)return{status:400,json:{error:"missing :do"}};this.context.variables.push();try{let n=this.eval(e);return n&&typeof n=="object"?n.status!==void 0&&n.json!==void 0?n:{status:200,json:n}:{status:200,json:n}}finally{this.context.variables.pop()}}handleComponentBlock(t){let e=t.fields.get("render");if(!e)return null;let n=t.fields.get("state");if(n&&n.kind==="block"&&n.type==="Map"){let i=n.fields.get("entries")||[];this.context.variables.push();for(let o=0;o<i.length-1;o+=2){let u=i[o]?.kind==="keyword"?i[o].name:String(i[o]),f=this.eval(i[o+1]);this.context.variables.set(`$${u}`,f)}}let s=t.fields.get("methods"),a=this.eval(e);return n&&this.context.variables.pop(),a}handleFormBlock(t){let e=t.fields.get("fields");if(!e)return null;let n=Array.isArray(e)?e:[e],s=`<form>
863
+ `;for(let a of n)if(a?.kind==="block"&&a?.type==="Map"){let i=a.fields.get("name")||"field",o=a.fields.get("type")||"text";s+=` <input type="${o}" name="${i}" />
864
+ `}return s+="</form>",s}handleServiceBlock(t){let e=t.name,n=t.fields.get("inject"),s=t.fields.get("methods"),a={name:e,methods:{}};if(s&&s.kind==="block"&&s.type==="Map"){let i=s.fields.get("entries")||[];for(let o=0;o<i.length-1;o+=2){let u=i[o]?.kind==="keyword"?i[o].name:String(i[o]),f=this.eval(i[o+1]);a.methods[u]=f}}return this.context.services=this.context.services||new Map,this.context.services.set(e,a),{status:"registered",service:e}}handleControllerBlock(t){let e=t.name,n=this.eval(t.fields.get("prefix"))||"",s=t.fields.get("routes"),a={name:e,prefix:n,routes:[]};if(s&&s.kind==="block"&&s.type==="Map"){let i=s.fields.get("entries")||[];for(let o=0;o<i.length-1;o+=2){let u=i[o]?.kind==="keyword"?i[o].name:String(i[o]),f=this.eval(i[o+1]);a.routes.push({method:"GET",path:u,handler:f})}}return this.context.controllers=this.context.controllers||new Map,this.context.controllers.set(e,a),{status:"registered",controller:e}}handleGuardBlock(t){let e=t.name,n=this.eval(t.fields.get("strategy"))||"none",s=this.eval(t.fields.get("check")),a={name:e,strategy:n,check:s};return this.context.guards=this.context.guards||new Map,this.context.guards.set(e,a),{status:"registered",guard:e}}handleModelBlock(t){let e=t.name,n=this.eval(t.fields.get("table"))||e.toLowerCase(),s=this.eval(t.fields.get("db"))||"postgresql",a=t.fields.get("fields"),i={name:e,tableName:n,dbType:s,fields:{}};if(a&&a.kind==="block"&&a.type==="Map"){let o=a.fields.get("entries")||[];for(let u=0;u<o.length-1;u+=2){let f=o[u]?.kind==="keyword"?o[u].name:String(o[u]),l=this.eval(o[u+1]);i.fields[f]=l}}return this.context.models=this.context.models||new Map,this.context.models.set(e,i),{status:"registered",model:e}}handleQueryBlock(t){let e=t.name,n=this.eval(t.fields.get("model")),s=t.fields.get("where"),a={name:e,model:n,where:{}};if(s&&s.kind==="block"&&s.type==="Map"){let i=s.fields.get("entries")||[];for(let o=0;o<i.length-1;o+=2){let u=i[o]?.kind==="keyword"?i[o].name:String(i[o]),f=this.eval(i[o+1]);a.where[u]=f}}return this.context.queries=this.context.queries||new Map,this.context.queries.set(e,a),{status:"registered",query:e}}handleMigrationBlock(t){let e=t.name,n=this.eval(t.fields.get("version"))||"001",s=this.eval(t.fields.get("up")),a=this.eval(t.fields.get("down")),i={name:e,version:n,up:s,down:a};return this.context.migrations=this.context.migrations||new Map,this.context.migrations.set(e,i),{status:"registered",migration:e}}handleRepositoryBlock(t){let e=t.name,n=this.eval(t.fields.get("model")),s=t.fields.get("methods"),a={name:e,model:n,methods:{}};if(s&&s.kind==="block"&&s.type==="Map"){let i=s.fields.get("entries")||[];for(let o=0;o<i.length-1;o+=2){let u=i[o]?.kind==="keyword"?i[o].name:String(i[o]),f=this.eval(i[o+1]);a.methods[u]=f}}return this.context.repositories=this.context.repositories||new Map,this.context.repositories.set(e,a),{status:"registered",repository:e}}handleDatabaseBlock(t){let e=t.name,n=this.eval(t.fields.get("type"))||"postgresql",s=this.eval(t.fields.get("host"))||"localhost",a=this.eval(t.fields.get("port"))||5432,i=this.eval(t.fields.get("name"))||"freelang_db",o={name:e,type:n,host:s,port:a,database:i};return this.context.databases=this.context.databases||new Map,this.context.databases.set(e,o),{status:"registered",database:e}}handleCacheBlock(t){let e=t.name,n=this.eval(t.fields.get("host"))||"localhost",s=this.eval(t.fields.get("port"))||6379,a=this.eval(t.fields.get("ttl"))||3600,i={name:e,host:n,port:s,ttl:a};return this.context.caches=this.context.caches||new Map,this.context.caches.set(e,i),{status:"registered",cache:e}}handleCachedBlock(t){let e=t.name,n=this.eval(t.fields.get("cache")),s=this.eval(t.fields.get("key")),a=this.eval(t.fields.get("fn")),i=this.eval(t.fields.get("ttl"))||300,o={name:e,cache:n,key:s,fn:a,ttl:i};return this.context.cacheds=this.context.cacheds||new Map,this.context.cacheds.set(e,o),{status:"registered",cached:e}}handleKafkaBlock(t){let e=t.name,n=t.fields.get("brokers"),s=Array.isArray(n)?n.map(o=>this.eval(o)):["localhost:9092"],a=this.eval(t.fields.get("client-id"))||"freelang-app",i={name:e,brokers:s,clientId:a};return this.context.kafkas=this.context.kafkas||new Map,this.context.kafkas.set(e,i),{status:"registered",kafka:e}}handleProducerBlock(t){let e=t.name,n=this.eval(t.fields.get("kafka")),s=this.eval(t.fields.get("topic"))||"events",a={name:e,kafka:n,topic:s};return this.context.producers=this.context.producers||new Map,this.context.producers.set(e,a),{status:"registered",producer:e}}handleConsumerBlock(t){let e=t.name,n=this.eval(t.fields.get("kafka")),s=this.eval(t.fields.get("topic"))||"events",a=this.eval(t.fields.get("group"))||"default",i=this.eval(t.fields.get("handler")),o={name:e,kafka:n,topic:s,groupId:a,handler:i};return this.context.consumers=this.context.consumers||new Map,this.context.consumers.set(e,o),{status:"registered",consumer:e}}handleQueueBlock(t){let e=t.name,n=this.eval(t.fields.get("rabbitmq")),s=this.eval(t.fields.get("exchange"))||"app",a=this.eval(t.fields.get("routing-key"))||"",i=this.eval(t.fields.get("handler")),o={name:e,rabbitmq:n,exchange:s,routingKey:a,handler:i};return this.context.queues=this.context.queues||new Map,this.context.queues.set(e,o),{status:"registered",queue:e}}handleRabbitMQBlock(t){let e=t.name,n=this.eval(t.fields.get("url"))||"amqp://localhost:5672",s={name:e,url:n};return this.context.rabbitmqs=this.context.rabbitmqs||new Map,this.context.rabbitmqs.set(e,s),{status:"registered",rabbitmq:e}}handleJWTBlock(t){let e=t.name,n=this.eval(t.fields.get("secret"))||"change-me",s=this.eval(t.fields.get("expires-in"))||"7d",a=this.eval(t.fields.get("algorithm"))||"HS256",i={name:e,secret:n,expiresIn:s,algorithm:a};return this.context.jwts=this.context.jwts||new Map,this.context.jwts.set(e,i),{status:"registered",jwt:e}}handleOAuthBlock(t){let e=t.name,n=this.eval(t.fields.get("provider"))||"google",s=this.eval(t.fields.get("client-id"))||"",a=this.eval(t.fields.get("client-secret"))||"",i=this.eval(t.fields.get("callback-url"))||"/auth/callback",o=this.eval(t.fields.get("scope"))||["email","profile"],u=this.eval(t.fields.get("on-success")),f={name:e,provider:n,clientId:s,clientSecret:a,callbackUrl:i,scope:o,onSuccess:u};return this.context.oauths=this.context.oauths||new Map,this.context.oauths.set(e,f),{status:"registered",oauth:e}}handleDockerfileBlock(t){let e=t.name,n=this.eval(t.fields.get("base"))||"node:20-alpine",s=this.eval(t.fields.get("workdir"))||"/app",a=this.eval(t.fields.get("expose"))||3e3,i=this.eval(t.fields.get("cmd"))||"npm start",o={name:e,base:n,workdir:s,expose:a,cmd:i};return this.context.dockerfiles=this.context.dockerfiles||new Map,this.context.dockerfiles.set(e,o),{status:"registered",dockerfile:e}}handleDockerComposeBlock(t){let e=t.name,n=t.fields.get("services"),s=t.fields.get("volumes"),a={name:e,services:{},volumes:{}};if(n&&n.kind==="block"&&n.type==="Map"){let i=n.fields.get("entries")||[];for(let o=0;o<i.length-1;o+=2){let u=i[o]?.kind==="keyword"?i[o].name:String(i[o]),f=this.eval(i[o+1]);a.services[u]=f}}return this.context.composes=this.context.composes||new Map,this.context.composes.set(e,a),{status:"registered","docker-compose":e}}handleK8sDeploymentBlock(t){let e=t.name,n=this.eval(t.fields.get("replicas"))||1,s=this.eval(t.fields.get("image"))||"app:latest",a=this.eval(t.fields.get("namespace"))||"default",i={name:e,replicas:n,image:s,namespace:a};return this.context.k8sDeployments=this.context.k8sDeployments||new Map,this.context.k8sDeployments.set(e,i),{status:"registered","k8s-deployment":e}}handleK8sServiceBlock(t){let e=t.name,n=t.fields.get("selector"),s=t.fields.get("ports"),a=this.eval(t.fields.get("type"))||"ClusterIP",i={name:e,selector:{},ports:[],type:a};if(n&&n.kind==="block"&&n.type==="Map"){let o=n.fields.get("entries")||[];for(let u=0;u<o.length-1;u+=2){let f=o[u]?.kind==="keyword"?o[u].name:String(o[u]),l=this.eval(o[u+1]);i.selector[f]=l}}return this.context.k8sServices=this.context.k8sServices||new Map,this.context.k8sServices.set(e,i),{status:"registered","k8s-service":e}}handleK8sIngressBlock(t){let e=t.name,n=t.fields.get("rules"),s=this.eval(t.fields.get("annotations"))||{},a={name:e,rules:[],annotations:s};return this.context.k8sIngresses=this.context.k8sIngresses||new Map,this.context.k8sIngresses.set(e,a),{status:"registered","k8s-ingress":e}}handleAwsBlock(t){let e=t.name,n=t.type,s=this.eval(t.fields.get("region"))||"ap-northeast-2",a=this.eval(t.fields.get("endpoint"))||"",i={name:e,type:n,region:s,endpoint:a};return this.context.aws=this.context.aws||new Map,this.context.aws.set(e,i),{status:"registered",aws:e}}handleGcpBlock(t){let e=t.name,n=t.type,s=this.eval(t.fields.get("project-id"))||"project",a=this.eval(t.fields.get("region"))||"asia-northeast3",i={name:e,type:n,projectId:s,region:a};return this.context.gcp=this.context.gcp||new Map,this.context.gcp.set(e,i),{status:"registered",gcp:e}}handleAzureBlock(t){let e=t.name,n=t.type,s=this.eval(t.fields.get("subscription-id"))||"",a=this.eval(t.fields.get("resource-group"))||"default",i={name:e,type:n,subscriptionId:s,resourceGroup:a};return this.context.azure=this.context.azure||new Map,this.context.azure.set(e,i),{status:"registered",azure:e}}handleToolBlock(t){let e=t.name,n=t.fields.has("desc")?this.eval(t.fields.get("desc")):"",s=t.fields.get("body"),a={};if(t.fields.has("input")){let f=t.fields.get("input");if(f?.kind==="block"&&f?.type==="Map"){let l=f.fields.get("entries");if(Array.isArray(l))for(let c=0;c<l.length-1;c+=2){let p=l[c]?.kind==="keyword"?l[c].name:l[c]?.kind==="literal"?String(l[c].value):String(l[c]),m=l[c+1],d=m?.kind==="keyword"?m.name:m?.kind==="literal"?String(m.value):"any";a[p]=d}}}let i="any";if(t.fields.has("output")){let f=t.fields.get("output");i=f?.kind==="keyword"?f.name:f?.kind==="literal"?String(f.value):"any"}let o=this,u={name:e,description:String(n||""),inputSchema:a,outputSchema:i,execute:f=>{o.context.variables.push();try{for(let[l,c]of Object.entries(f))o.context.variables.set(`$${l}`,c);return o.eval(s)}finally{o.context.variables.pop()}}};return Te.register(u),u}handleUseToolBlock(t){let e=t.name,n={};if(t.fields.has("args")){let a=t.fields.get("args");if(a?.kind==="block"&&a?.type==="Map"){let i=a.fields.get("entries");if(Array.isArray(i))for(let o=0;o<i.length-1;o+=2){let u=i[o]?.kind==="keyword"?i[o].name:i[o]?.kind==="literal"?String(i[o].value):String(i[o]);n[u]=this.eval(i[o+1])}}}let s=Te.executeSync(e,n);return s.success?s.output:(()=>{throw new Error(s.error||`Tool failed: ${e}`)})()}handleServerBlock(t){let e=Number(this.getFieldValue(t,"port")||3009),n=String(this.getFieldValue(t,"host")||"0.0.0.0");this.serverConfig={port:e,host:n}}handleRouteBlock(t){let e=this.getFieldValue(t,"method","GET"),n=this.getFieldValue(t,"path","/"),s=t.fields.get("handler");if(!s)throw new Error(`[ROUTE ${t.name}] Missing :handler`);this.context.routes.set(t.name,{name:t.name,method:e.toLowerCase(),path:n,handler:s})}handleFuncBlock(t){let e=t.fields.get("params"),n=[];if(e&&e.kind==="variable")n.push(e.name);else if(e?.kind==="block"&&e.type==="Array"){let u=e.fields.get("items");Array.isArray(u)&&n.push(...u.map(f=>{if(f.kind==="block"&&f.type==="Array"){let l=f.fields.get("items");if(Array.isArray(l)&&l.length>0){let c=l[0];if(c.kind==="variable")return c.name;if(c.kind==="literal"&&c.type==="symbol")return"$"+c.value}}return f.kind==="variable"||f.name?f.name.startsWith("$")?f.name:"$"+f.name:"$unknown"}))}let s=t.fields.get("body");if(!s)throw new Error(`[FUNC ${t.name}] Missing :body`);let a=[],i={kind:"type",name:"any"};if(t.typeAnnotations&&this.context.typeChecker){let u=t.typeAnnotations.get("params");Array.isArray(u)?a=u:a=n.map(()=>({kind:"type",name:"any"}));let f=t.typeAnnotations.get("return");f&&(i=f)}let o=t.generics&&t.generics.length>0;if(this.context.functions.set(t.name,{name:t.name,params:n,body:s,generics:t.generics,paramTypes:a,returnType:i}),this.context.typeChecker&&(o&&t.generics?this.context.typeChecker.registerGenericFunction(t.name,t.generics,a,i):this.context.typeChecker.registerFunction(t.name,a,i)),this.context.runtimeTypeChecker&&t.typeAnnotations){let u=a.map(l=>l.name||"any"),f=i.name||"any";this.context.runtimeTypeChecker.registerFunc(t.name,u,f)}}handleIntentBlock(t){let e=new Map;for(let[n,s]of t.fields)n.startsWith(":")&&e.set(n,s);this.context.intents.set(t.name,{name:t.name,fields:e})}handleMiddlewareBlock(t){let e=new Map;for(let[n,s]of t.fields)n.startsWith(":")&&e.set(n,this.eval(s));this.context.middleware.push({name:t.name,config:e})}handleWebSocketBlock(t){}handleErrorHandlerBlock(t){let e=t.fields.get("on-404"),n=t.fields.get("on-500");e&&this.context.errorHandlers.handlers.set(404,e),n&&this.context.errorHandlers.handlers.set(500,n)}eval(t){if(!t)return null;if(t.kind==="literal"){let e=t;if(e.type==="string"&&typeof e.value=="string"&&(e.value.includes("{$")||e.value.includes("{(")))return this.interpolateString(e.value);if(e.type==="symbol"&&typeof e.value=="string"){if(e.value==="true")return!0;if(e.value==="false")return!1;if(e.value==="null"||e.value==="nil")return null;let n=e.value,s="$"+n;if(this.context.variables.has(s))return this.context.variables.get(s);if(this.context.variables.has(n))return this.context.variables.get(n);if(process.env.FL_STRICT==="1"&&!this.context.functions.has(n)){let a=e.line;throw new Error(`[E_UNRESOLVED_SYMBOL] '${n}' at line ${a||this.currentLine}, col 0 \u2014 set FL_STRICT=0 to silence`)}}return e.value}if(t.kind==="variable"){let e=t.name,n=t.line,s=this.currentFilePath?this.currentFilePath.replace(/^.*\//,""):"",a=n?` (${s?s+":":"at line "}${n})`:"";if(e.includes(".")){let f=e.split("."),l=this.context.variables.has("$"+f[0])?this.context.variables.get("$"+f[0]):this.context.variables.get(f[0]);if(l===void 0&&!this.context.variables.has("$"+f[0])&&!this.context.variables.has(f[0])){let c=this.context.variables.getAllVars(),p=dn(f[0],c),m=new Dt(f[0],c.filter(d=>!d.startsWith("__")),p,s,n||this.currentLine,0);throw m.__flCallStack=this.context.callStack.slice(),this.context.lastError={message:m.message,code:m.code,file:m.file,line:m.line,col:m.col,callStack:this.context.callStack.slice(),variables:Object.fromEntries(this.context.variables.getAllVars().slice(0,10).map(d=>[d,this.context.variables.get(d)])),hint:m.hint},m}for(let c=1;c<f.length;c++){if(l==null)return null;l=typeof l=="object"?l[f[c]]:null}return l??null}if(this.context.variables.has("$"+e))return this.context.variables.get("$"+e);if(this.context.variables.has(e))return this.context.variables.get(e);if(this.context.functions.has(e)||this.context.functions.has("$"+e))return{kind:"builtin-fn",name:e};let i=this.context.variables.getAllVars(),o=dn(e,i),u=new Dt(e,i.filter(f=>!f.startsWith("__")),o,s,n||this.currentLine,0);throw u.__flCallStack=this.context.callStack.slice(),this.context.lastError={message:u.message,code:u.code,file:u.file,line:u.line,col:u.col,callStack:this.context.callStack.slice(),variables:Object.fromEntries(i.slice(0,10).map(f=>[f,this.context.variables.get(f)])),hint:u.hint},u}if(t.kind==="keyword")return t.name;if(t.kind==="sexpr")return this.evalSExpr(t);if(t.kind==="block"){let e=t;if(Lt(e)&&Yn(e))throw new Error(`Control block [${e.type}] should not be eval'd directly. This block must be processed by interpret() or evalBlock().`);if(e.type==="Array"){let n=e.fields.get("items");if(Array.isArray(n))return n.map(s=>this.eval(s))}if(e.type==="Map"){let n={};for(let[s,a]of e.fields)n[s]=Array.isArray(a)?a.map(i=>this.eval(i)):this.eval(a);return n}throw new Error(`Unknown block type: ${e.type}`)}if(t.kind==="pattern-match")return this.evalPatternMatch(t);if(t.kind==="function-value")return t;if(t.kind==="type-class")return this.evalTypeClass(t);if(t.kind==="type-class-instance")return this.evalInstance(t);if(t.kind==="template-string"){let e=t;return this.interpolateString(e.value)}return t.kind==="try-block"?this.evalTryBlock(t):t.kind==="throw"?this.evalThrow(t):t.kind==="loop"?this.evalLoop(t):null}evalSExpr(t){t.line!==void 0&&(this.currentLine=t.line);let e=t.op;if(typeof e!="string"&&(e=e?.name?e.name:String(e)),e=String(e).trim(),e.includes(":")){let[f,l]=e.split(":");if(t.args.length>0){let c=this.eval(t.args[0]),p=this.getConcreteType(c);if(p){let m=this.resolveMethod(f,p,l);if(m){let d=t.args.slice(1).map(g=>this.eval(g));if(m.kind==="function-value")return this.callFunctionValue(m,[c,...d]);if(typeof m=="function")return m(c,...d)}}}}let n=new Set(["search","fetch","learn","recall","remember","forget","observe","analyze","decide","act","verify","await"]),s=new Set(["DOCKERFILE","dockerfile","DOCKER-COMPOSE","docker-compose","K8S-DEPLOYMENT","deployment","K8S-SERVICE","service","K8S-INGRESS","ingress","GITHUB-ACTIONS","github-actions","ci","AWS-S3","aws-s3","AWS-LAMBDA","aws-lambda","AWS-RDS","aws-rds","GCP-RUN","gcp-run","AZURE-FUNCTION","azure-function"]),a=new Set(["STYLE","style","THEME","theme"]),i=new Set(["fn","defn","defun","async","set!","define","func-ref","call","compose","comp","pipe","->","->>","as->","?.","?.","|>","??","let","set","if","if-let","when","when-not","when-let","unless","cond","case","for","do","begin","progn","loop","recur","while","doseq","dotimes","and","or","defmacro","macroexpand","defstruct","defprotocol","impl","parallel","race","with-timeout","fl-try","use","defprop","map-keys","map_keys","map-vals","map_vals","return","group-by","group_by","partial","memoize","deftest","describe","it","is","is=","run-tests","test-summary","import","migrate"]);if(n.has(e))return Pc(this,e,t);if(s.has(e))return jc(this,e,t);if(a.has(e))return Ic(this,e,t);if(i.has(e))return fi(this,e,t);if(e==="REFLECT"){let f=this,l=C=>f.eval(C),c=(C,P)=>f.callFunctionValue(C,P),p=null,m=null,d=null,g=null,h=null,y=C=>C?.kind==="keyword"?C.name:C?.kind==="literal"&&C?.type==="string"?C.value:null;for(let C=0;C<t.args.length;C++){let P=t.args[C],_=y(P);if(_!==null&&C+1<t.args.length){let S=t.args[C+1];_==="output"?(p=S,C++):_==="criteria"?(m=S,C++):_==="threshold"?(d=S,C++):_==="on-fail"?(g=S,C++):_==="revise"&&(h=S,C++)}}let k=p!=null?l(p):null,v=[];if(m!=null){let C=l(m);if(Array.isArray(C)){for(let P of C)if(typeof P=="function")v.push(P);else if(P?.kind==="function-value")v.push(_=>{let S=c(P,[_]);return typeof S=="number"?S:S?1:0});else if(typeof P=="number"){let _=P;v.push(()=>_)}}}let $=d!=null?Number(l(d)):.7,M;if(g!=null){let C=l(g);C?.kind==="function-value"?M=P=>c(C,[P]):typeof C=="function"&&(M=C)}let O;if(h!=null){let C=l(h);C?.kind==="function-value"?O=P=>c(C,[P]):typeof C=="function"&&(O=C)}return Qu({output:k,criteria:v,threshold:$,onFail:M,revise:O})}if(e==="COT"){let f=this,l=Yu(t.args,c=>f.eval(c),(c,p)=>f.context.variables.set(c,p),c=>f.context.variables.get(c));if(l.conclusion?.kind==="function-value"){let c=f.context.variables.get("$__cot_steps__");l.conclusion=f.callFunctionValue(l.conclusion,[c])}return l}if(e==="TOT"){let c=function(k,v){return k?k.kind==="keyword"&&k.name===v||k.kind==="literal"&&k.type==="string"&&k.value===v:!1},f=this,l=new ra,p=t.args,m=0,d=null,g=null,h="best",y=1;for(;m<p.length;){let k=p[m];if(c(k,"branch")){m++;let v=p[m];m++;let $=p[m];m++;let M=String(f.eval(v)),O=$;l.branch(M,()=>f.eval(O))}else if(c(k,"eval"))m++,d=p[m],m++;else if(c(k,"prune"))m++,g=Number(f.eval(p[m])),m++;else if(c(k,"select")){m++;let v=f.eval(p[m]);m++,v==="top-k"?h="top-k":h="best"}else c(k,"k")&&(m++,y=Number(f.eval(p[m]))),m++}if(d!=null){let k=f.eval(d);l.evaluate(v=>typeof k=="function"?Number(k(v))||0:k?.kind==="function-value"?Number(f.callFunctionValue(k,[v]))||0:.5)}return g!==null&&!isNaN(g)&&l.prune(g),l.select(h,y)}if(e==="break!"){let f={file:this.currentFilePath||"<unknown>",line:t.line??this.currentLine,col:0},l={};try{let c=this.context.variables.snapshot();for(let[p,m]of Object.entries(c))l[p]=m}catch{}return Gi(this.debugSession,f,l),null}if(e==="map"&&t.args.length===3){let f=fi(this,e,t);if(f!==void 0)return f}if(r._vmEnabled&&li(t))try{let f=r._vmCompiler.compile(t),l=r._vmOptimizer.optimize(f),c=this.context.variables.snapshot();return r._vm.run(l,c)}catch{}let o=t.args.map(f=>this.eval(f));if(o.length>=1&&typeof o[0]=="string"){let f=`${e}:${o[0]}`;if(this.context.functions.has(f))return this.callUserFunction(f,o.slice(1))}if(this.context.protocols.hasMethod(e)&&o.length>=1){let f=o[0],l=this.context.protocols.resolveMethod(e,f);if(l){let c=l.methods.get(e);return this.callProtocolMethod(c,f,o.slice(1))}}let u=`__native_${e}`;if(this.context[u]!==void 0){let f=this.context[u];return f(...o)}try{return Fn(this,e,o,t)}catch(f){if(f&&f.constructor&&f.constructor.name==="ReturnSignal")throw f;let l=t.line??this.currentLine,c=t.col??0,p=f.message??String(f),m=p.startsWith(`[${e}]`)||p.startsWith(`(${e})`)?p:`[${e}] ${p}`,d=m.includes("(at line ")?m:`${m} (at line ${l}, col ${c})`;if(f.code||f.name==="FLRuntimeError")throw f.message=d,f;{let g=new Error(d);throw g.__flCallStack=f.__flCallStack??(this.callStack.length>0?[...this.callStack]:void 0),g}}}callProtocolMethod(t,e,n){let s=t.params;this.context.variables.push();try{s.length>0&&this.context.variables.set(s[0],e);for(let a=1;a<s.length;a++)this.context.variables.set(s[a],n[a-1]??null);return this.eval(t.body)}finally{this.context.variables.pop()}}interpolateString(t){let e="",n=0;for(;n<t.length;){if(t[n]==="$"&&n+1<t.length&&t[n+1]==="{"){let s=n+2,a=t.indexOf("}",s);if(a>s){let i=t.slice(s,a).trim(),o;if(i.includes("("))try{let u=W("("+i+")"),f=H(u);o=f.length>0?this.eval(f[0]):null}catch(u){let f=u?.message??String(u);throw new ue(de.E_INVALID_FORM,`\uBB38\uC790\uC5F4 \uBCF4\uAC04 \uC2E4\uD328 \u2014 \${(${i})}
865
+ \uC6D0\uC778: ${f}`,void 0,void 0,void 0,'\uC62C\uBC14\uB978 \uD45C\uD604\uC2DD\uC778\uC9C0 \uD655\uC778\uD558\uC138\uC694. \uC608: "${(+ 1 2)}" \uB610\uB294 "${varName}"')}else if(i.includes(".")){let u=i.split(".");o=this.context.variables.has("$"+u[0])?this.context.variables.get("$"+u[0]):this.context.variables.get(u[0]);for(let f=1;f<u.length;f++){if(o==null){o=null;break}o=typeof o=="object"?o[u[f]]:null}}else o=this.context.variables.has("$"+i)?this.context.variables.get("$"+i):this.context.variables.get(i);e+=o==null?"":String(o),n=a+1;continue}}if(t[n]==="{"&&n+1<t.length){let s=t[n+1];if(s==="$"){let a=t.indexOf("}",n);if(a>n){let i=t.slice(n+2,a),o;if(i.includes(".")){let u=i.split(".");o=this.context.variables.has("$"+u[0])?this.context.variables.get("$"+u[0]):this.context.variables.get(u[0]);for(let f=1;f<u.length;f++){if(o==null){o=null;break}o=typeof o=="object"?o[u[f]]:null}}else o=this.context.variables.has("$"+i)?this.context.variables.get("$"+i):this.context.variables.get(i);e+=o==null?"":String(o),n=a+1;continue}}else if(s==="("){let a=0,i=n+1;for(;i<t.length;){if(t[i]==="(")a++;else if(t[i]===")"&&(a--,a===0))break;i++}if(i<t.length&&i+1<t.length&&t[i+1]==="}"){let o=t.slice(n+1,i+1);try{let u=W(o),f=H(u),l=f.length>0?this.eval(f[0]):null;e+=l==null?"":String(l)}catch(u){let f=u?.message??String(u);throw new ue(de.E_INVALID_FORM,`\uBB38\uC790\uC5F4 \uBCF4\uAC04 \uC2E4\uD328 \u2014 {(${o})}
866
+ \uC6D0\uC778: ${f}`,void 0,void 0,void 0,"\uC62C\uBC14\uB978 \uD45C\uD604\uC2DD\uC778\uC9C0 \uD655\uC778\uD558\uC138\uC694.")}n=i+2;continue}}}e+=t[n],n++}return e}toDisplayString(t,e=!1){if(t==null)return"null";if(typeof t=="string")return e?`"${t}"`:t;if(typeof t=="number"||typeof t=="boolean")return String(t);if(Array.isArray(t))return"["+t.map(n=>this.toDisplayString(n,!0)).join(", ")+"]";if(Re(t))return`<lazy-seq: ${es(3,t).map(s=>this.toDisplayString(s)).join(", ")}...>`;if(t instanceof Map){if(t.has("message")&&t.has("raw")){let s=t.get("message")??"",a=t.get("line");return a?`[line ${a}] ${s}`:String(s)}let n=[];return t.forEach((s,a)=>n.push(`${a}: ${this.toDisplayString(s,!0)}`)),"{"+n.join(", ")+"}"}return typeof t=="object"?t.kind==="function-value"?`<fn:${t.name||"\u03BB"}>`:"{"+Object.entries(t).filter(([s])=>!s.startsWith("__")).map(([s,a])=>`"${s}": ${this.toDisplayString(a,!0)}`).join(", ")+"}":String(t)}callUserFunction(t,e){return zi(this,t,e)}callFunctionValue(t,e){return Js(this,t,e)}callAsyncFunctionValue(t,e){return Xs(this,t,e)}callFunction(t,e){return Ku(this,t,e)}callUserFunctionTCO(t,e){return Ys(this,t,e)}callFunctionValueTCO(t,e){return Qs(this,t,e)}callUserFunctionRaw(t,e){return Ju(this,t,e)}callFunctionValueRaw(t,e){return Xu(this,t,e)}getFieldValue(t,e,n=null){let s=t.fields.get(e);return s===void 0?n:this.eval(s)}evalPatternMatch(t){return Du(this,t)}evalTryBlock(t){return qu(this,t)}evalThrow(t){return Uu(this,t)}evalLoop(t){if(!t)throw new Error("Loop node is null");let e=t.init,n=t.condition,s=t.update,a=t.body;if(!e||!n||!s||!a)throw new Error(`Loop parts missing: init=${!!e} condition=${!!n} update=${!!s} body=${!!a}`);if(e.kind!=="sexpr")throw new Error(`Loop init must be sexpr, got: ${e.kind}`);let i=e.op,o=e.args||[];if(!i||o.length<1)throw new Error("Loop init must be ($var val)");let u=String(i),f=this.eval(o[0]),l=new Map;l.set(u,f),this.scopes.push(l);try{let c=null;for(;this.isTruthy(this.eval(n));){c=this.eval(a);let p=this.eval(s);l.set(u,p)}return c}finally{this.scopes.pop()}}matchPattern(t,e){return Vn(this,t,e)}getContext(){return this.context}setVariable(t,e){this.context.variables.set(t,e)}evalDefmacro(t){if(t.args.length<3)throw new Error("defmacro requires name, params, and body");let e=t.args[0],n=e.kind==="literal"?String(e.value):e.kind==="variable"?e.name:String(e.value??e.name??""),s=t.args[1],a=[];if(s.kind==="block"&&s.type==="Array"){let o=s.fields.get("items");if(Array.isArray(o))for(let u of o)u.kind==="variable"?a.push(u.name.startsWith("$")?u.name:"$"+u.name):u.kind==="literal"&&a.push("$"+u.value)}let i=t.args[2];this.context.macroExpander.define(n,a,i)}registerBuiltinTypeClasses(){Vu(this)}evalTypeClass(t){zu(this,t)}evalInstance(t){Wu(this,t)}getTypeClass(t){return this.context.typeClasses?.get(t)}getTypeClassInstance(t,e){return this.context.typeClassInstances?.get(`${t}[${e}]`)}satisfiesConstraint(t,e){return!!this.getTypeClassInstance(e,t)}getConcreteType(t){if(!(!t||typeof t!="object")){if(t.tag==="Ok"||t.tag==="Err")return"Result";if(t.tag==="Some"||t.tag==="None")return"Option";if(Array.isArray(t))return"List";if(t.kind==="Result")return"Result";if(t.kind==="Option")return"Option";if(t.kind==="List")return"List"}}resolveMethod(t,e,n){return this.getTypeClassInstance(t,e)?.implementations.get(n)}getModules(){return this.context.modules||(this.context.modules=new Map),this.context.modules}evalModuleBlock(t){Jc(this,t)}evalImportBlock(t){Xc(this,t)}evalImportFromFile(t,e,n,s){Yc(this,t,e,n,s)}evalOpenBlock(t){Qc(this,t)}handleSearchBlock(t){return zc(this,t)}handleLearnBlock(t){return Wc(this,t)}handleReasoningBlock(t){return Hc(this,t)}handleReasoningSequence(t){return Vc(this,t)}destroy(){this.learnedFactsStore.destroy(),this.context.server&&this.context.server.close(),this.logger.info("Interpreter cleanup completed")}};be();ke();function Ky(r){let t=[],e=r.split(`
867
+ `);for(let n=0;n<e.length;n++){let s=e[n].trim();if(s.startsWith(";"))t.push({line:n+1,text:s});else{let a=e[n].indexOf(";");a>=0&&(e[n].slice(0,a).match(/(?<!\\)"/g)||[]).length%2===0&&t.push({line:n+1,text:e[n].slice(a).trim()})}}return t}var Qi=class{constructor(){this.indentStr=" ";this.maxWidth=80}format(t){if(!t.trim())return"";let n=Ky(t),s=W(t),a=H(s),i=[];for(let u of a)i.push(this.formatNode(u,0));let o=[];for(let u=0;u<i.length;u++){let f=i[u],l=a[u];u>0&&(l.kind==="block"||l.kind==="module")&&o.push(""),o.push(f)}return o.join(`
868
+ `)+`
869
+ `}formatNode(t,e){switch(t.kind){case"literal":return this.formatLiteral(t);case"variable":return`$${t.name}`;case"keyword":return`:${t.name}`;case"sexpr":return this.formatSExpr(t,e);case"block":return this.formatBlock(t,e);case"pattern-match":return this.formatPatternMatch(t,e);case"function-value":return this.formatFunctionValue(t,e);case"type-class":return this.formatTypeClass(t,e);case"type-class-instance":return this.formatTypeClassInstance(t,e);case"module":return this.formatModuleBlock(t,e);case"import":return this.formatImportBlock(t);case"open":return this.formatOpenBlock(t);case"search-block":return this.formatSearchBlock(t,e);case"learn-block":return this.formatLearnBlock(t,e);case"reasoning-block":return this.formatReasoningBlock(t,e);case"reasoning-sequence":return this.formatReasoningSequence(t,e);case"async-function":return this.formatAsyncFunction(t,e);case"await":return this.formatAwait(t,e);case"try-block":return this.formatTryBlock(t,e);case"catch-clause":return this.formatCatchClause(t,e);case"throw":return this.formatThrow(t,e);case"type-variable":return t.name;default:return String(t.value??"")}}formatLiteral(t){return t.type==="string"?`"${String(t.value).replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:t.type==="null"?"null":(t.type==="boolean"||t.type==="symbol",String(t.value))}formatSExpr(t,e){let n=t.op,s=t.args;if(s.length===0)return`(${n})`;if(n==="fn"||n==="lambda")return this.formatFn(n,s,e);if(n==="define"||n==="def")return this.formatDefine(n,s,e);if(n==="let")return this.formatLet(s,e);if(n==="if")return this.formatIf(s,e);if(n==="do"||n==="begin")return this.formatDo(n,s,e);if(n==="cond")return this.formatCond(s,e);if(n==="match")return this.formatMatch(s,e);let a=s.map(l=>this.formatNode(l,e)),i=`(${n} ${a.join(" ")})`,o=this.ind(e);if(i.length<=this.maxWidth-e*2)return i;let u=this.ind(e+1),f=s.map(l=>u+this.formatNode(l,e+1));return`(${n}
870
+ ${f.join(`
871
+ `)})`}formatFn(t,e,n){if(e.length<2)return`(${t} ${e.map(u=>this.formatNode(u,n)).join(" ")})`;let s=this.formatNode(e[0],n),a=e.slice(1).map(u=>this.formatNode(u,n+1)),i=this.ind(n+1),o=`(${t} ${s} ${a.join(" ")})`;return o.length<=this.maxWidth-n*2?o:`(${t} ${s}
872
+ ${a.map(u=>i+u).join(`
873
+ `)})`}formatDefine(t,e,n){if(e.length===0)return`(${t})`;let s=e[0],a=this.formatNode(s,n);if(e.length===1)return`(${t} ${a})`;let i=e.slice(1).map(f=>this.formatNode(f,n+1)),o=`(${t} ${a} ${i.join(" ")})`;if(o.length<=this.maxWidth-n*2)return o;let u=this.ind(n+1);return`(${t} ${a}
874
+ ${i.map(f=>u+f).join(`
875
+ `)})`}formatLet(t,e){if(t.length===0)return"(let)";let n=t[0],s=t.slice(1).map(u=>this.formatNode(u,e+1)),a=this.formatNode(n,e+1),i=`(let ${a} ${s.join(" ")})`;if(i.length<=this.maxWidth-e*2)return i;let o=this.ind(e+1);return`(let ${a}
876
+ ${s.map(u=>o+u).join(`
877
+ `)})`}formatIf(t,e){let n=t.map(i=>this.formatNode(i,e+1)),s=`(if ${n.join(" ")})`;if(s.length<=this.maxWidth-e*2)return s;let a=this.ind(e+1);return`(if ${n[0]}
878
+ ${n.slice(1).map(i=>a+i).join(`
879
+ `)})`}formatDo(t,e,n){let s=this.ind(n+1),a=e.map(i=>s+this.formatNode(i,n+1));return`(${t}
880
+ ${a.join(`
881
+ `)})`}formatCond(t,e){let n=this.ind(e+1);return`(cond
882
+ ${t.map(a=>n+this.formatNode(a,e+1)).join(`
883
+ `)})`}formatMatch(t,e){if(t.length===0)return"(match)";let n=this.formatNode(t[0],e),s=this.ind(e+1),a=t.slice(1).map(i=>s+this.formatNode(i,e+1));return`(match ${n}
884
+ ${a.join(`
885
+ `)})`}formatBlock(t,e){if(t.type==="Array"){let f=t.fields.get("items");return f?this.formatNodeArray(f,e):"[]"}if(t.type==="Map"){let f=[];for(let[m,d]of t.fields){let g=Array.isArray(d)?this.formatNodeArray(d,e+1):this.formatNode(d,e+1);f.push(`:${m} ${g}`)}if(f.length===0)return"{}";let l=`{${f.join(" ")}}`,c=this.maxWidth-e*2;if(l.length<=c)return l;let p=this.ind(e+1);return`{
886
+ ${f.map(m=>p+m).join(`
887
+ `)}
888
+ ${this.ind(e)}}`}let n=this.ind(e+1),s=[],a=`[${t.type} ${t.name}`,i=[];for(let[f,l]of t.fields){let c=Array.isArray(l)?this.formatNodeArray(l,e+1):this.formatNode(l,e+1);i.push(`:${f}`,c)}let o=i.length>0?`${a} ${i.join(" ")}]`:`${a}]`,u=this.maxWidth-e*2;if(o.length<=u)return o;s.push(a);for(let f=0;f<i.length;f+=2){let l=i[f],c=i[f+1];s.push(`${n}${l} ${c}`)}return s.join(`
889
+ `)+"]"}formatNodeArray(t,e){if(t.length===0)return"[]";let n=t.map(i=>this.formatNode(i,e)),s=`[${n.join(" ")}]`;if(s.length<=this.maxWidth-e*2)return s;let a=this.ind(e+1);return`[
890
+ ${n.map(i=>a+i).join(`
891
+ `)}
892
+ ${this.ind(e)}]`}formatPatternMatch(t,e){let n=this.formatNode(t.value,e+1),s=this.ind(e+1),a=t.cases.map(o=>s+this.formatMatchCase(o,e+1)),i=`(match ${n}
893
+ ${a.join(`
894
+ `)}`;return t.defaultCase&&(i+=`
895
+ ${s}(_ ${this.formatNode(t.defaultCase,e+1)})`),i+")"}formatMatchCase(t,e){let n=this.formatPattern(t.pattern),s=this.formatNode(t.body,e);if(t.guard){let a=this.formatNode(t.guard,e);return`(${n} :when ${a} ${s})`}return`(${n} ${s})`}formatPattern(t){switch(t.kind){case"literal-pattern":return String(t.value);case"variable-pattern":return`$${t.name}`;case"wildcard-pattern":return"_";case"list-pattern":{let e=t.elements.map(n=>this.formatPattern(n));return t.restElement&&e.push(`& $${t.restElement}`),`[${e.join(" ")}]`}case"struct-pattern":{let e=[];for(let[s,a]of t.fields)e.push(`:${s} ${this.formatPattern(a)}`);let n=`{${e.join(" ")}}`;return t.asBinding&&(n+=` :as $${t.asBinding}`),n}case"or-pattern":return t.alternatives.map(e=>this.formatPattern(e)).join(" | ");case"range-pattern":return`(range ${t.min} ${t.max})`;default:return"_"}}formatFunctionValue(t,e){let n=t.params.map(o=>`$${o}`).join(" "),s=this.formatNode(t.body,e+1),a=`(fn [${n}] ${s})`;if(a.length<=this.maxWidth-e*2)return a;let i=this.ind(e+1);return`(fn [${n}]
896
+ ${i}${s})`}formatTypeClass(t,e){let n=this.ind(e+1),s=t.typeParams.join(" "),a=[];for(let[i,o]of t.methods)a.push(`${n}:${i} ${this.formatNode(o.type,e+1)}`);return`[TYPECLASS ${t.name} [${s}]
897
+ ${n}:methods [
898
+ ${a.join(`
899
+ `)}
900
+ ${n}]
901
+ ${this.ind(e)}]`}formatTypeClassInstance(t,e){let n=this.ind(e+1),s=[];for(let[a,i]of t.implementations)s.push(`${n}:${a} ${this.formatNode(i,e+1)}`);return`[INSTANCE (${t.className} ${t.concreteType})
902
+ ${s.join(`
903
+ `)}
904
+ ${this.ind(e)}]`}formatModuleBlock(t,e){let n=this.ind(e+1),s=`[${t.exports.join(" ")}]`,a=t.body.map(i=>n+this.formatNode(i,e+1)).join(`
905
+ `);return`[MODULE ${t.name}
906
+ ${n}:exports ${s}
907
+ ${n}:body [
908
+ ${a}
909
+ ${n}]
910
+ ${this.ind(e)}]`}formatImportBlock(t){let e=`(import ${t.moduleName}`;return t.source&&(e+=` :from "${t.source}"`),t.selective&&(e+=` :only [${t.selective.join(" ")}]`),t.alias&&(e+=` :as ${t.alias}`),e+")"}formatOpenBlock(t){let e=`(open ${t.moduleName}`;return t.source&&(e+=` :from "${t.source}"`),e+")"}formatSearchBlock(t,e){let n=`[search "${t.query}" :source "${t.source}"`;return t.cache!==void 0&&(n+=` :cache ${t.cache}`),t.limit!==void 0&&(n+=` :limit ${t.limit}`),t.name&&(n+=` :name "${t.name}"`),n+"]"}formatLearnBlock(t,e){let n=`(learn "${t.key}" ${JSON.stringify(t.data)}`;return t.source&&(n+=` :source "${t.source}"`),t.confidence!==void 0&&(n+=` :confidence ${t.confidence}`),n+")"}formatReasoningBlock(t,e){let n=this.ind(e+1),s=[];for(let[a,i]of t.data)s.push(`${n}:${a} ${JSON.stringify(i)}`);return s.length===0?`(${t.stage})`:`(${t.stage}
911
+ ${s.join(`
912
+ `)})`}formatReasoningSequence(t,e){let n=this.ind(e+1);return`(reasoning-sequence
913
+ ${t.stages.map(a=>n+this.formatNode(a,e+1)).join(`
914
+ `)})`}formatAsyncFunction(t,e){let n=t.params.map(o=>`$${o.name}`).join(" "),s=this.formatNode(t.body,e+1),a=this.ind(e+1),i=`[async ${t.name} [${n}] ${s}]`;return i.length<=this.maxWidth-e*2?i:`[async ${t.name} [${n}]
915
+ ${a}${s}]`}formatAwait(t,e){return`(await ${this.formatNode(t.argument,e)})`}formatTryBlock(t,e){let n=this.ind(e+1),s=this.formatNode(t.body,e+1),a=`(try
916
+ ${n}${s}`;if(t.catchClauses)for(let i of t.catchClauses)a+=`
917
+ ${n}${this.formatCatchClause(i,e+1)}`;return t.finallyBlock&&(a+=`
918
+ ${n}(finally ${this.formatNode(t.finallyBlock,e+1)})`),a+")"}formatCatchClause(t,e){let n=this.formatNode(t.handler,e);return t.pattern?`(catch [${this.formatPattern(t.pattern)}${t.variable?` $${t.variable}`:""}] ${n})`:t.variable?`(catch [$${t.variable}] ${n})`:`(catch ${n})`}formatThrow(t,e){return`(throw ${this.formatNode(t.argument,e)})`}ind(t){return this.indentStr.repeat(t)}};function Dr(r){return new Qi().format(r)}be();ke();function rp(r){let t=r.replace(/^\^/,"").toLowerCase();return t==="string"||t==="str"?"string":t==="number"||t==="num"||t==="int"||t==="float"?"number":t==="bool"||t==="boolean"?"bool":t==="array"||t==="list"||t==="vec"?"array":t==="map"||t==="object"||t==="obj"?"map":t==="nil"||t==="null"?"nil":t==="fn"||t==="function"?"fn":"any"}function oa(r){if(!r)return null;if(r.kind==="literal"){if(r.type==="string")return"string";if(r.type==="number")return"number";if(r.type==="boolean")return"bool";if(r.type==="nil")return"nil"}if(r.kind==="block"){if(r.type==="Array")return"array";if(r.type==="Map")return"map"}return r.kind==="keyword"?"string":null}function Jy(r,t){let e=oa(r);if(e!==null)return e;if(r?.kind==="variable"&&t.has(r.name))return t.get(r.name);if(r?.kind==="literal"&&r?.type==="symbol"){let n=String(r.value??"");if(t.has(n))return t.get(n)}return null}function sp(r,t){return r==="any"||t==="any"?!0:r===t}var Xy=new Map([["str",{min:0,max:1/0}],["println",{min:0,max:1/0}],["print",{min:0,max:1/0}],["get",{min:2,max:3}],["assoc",{min:3,max:1/0}],["dissoc",{min:2,max:2}],["keys",{min:1,max:1}],["values",{min:1,max:1}],["length",{min:1,max:1}],["map",{min:2,max:2}],["filter",{min:2,max:2}],["reduce",{min:3,max:3}],["append",{min:2,max:2}],["slice",{min:2,max:3}],["str-slice",{min:2,max:3}],["str-substr",{min:3,max:3}],["str-split",{min:2,max:2}],["json-parse",{min:1,max:1}],["json-stringify",{min:1,max:2}],["now-ms",{min:0,max:0}],["now-iso",{min:0,max:0}],["nil?",{min:1,max:1}],["not",{min:1,max:1}],["if",{min:2,max:3}],["let",{min:2,max:1/0}],["do",{min:1,max:1/0}],["or",{min:2,max:1/0}],["and",{min:2,max:1/0}],["contains?",{min:2,max:2}],["has-key?",{min:2,max:2}],["http-get-bearer",{min:2,max:2}],["http-post-bearer",{min:3,max:3}],["http-parallel",{min:1,max:1}],["http-retry",{min:2,max:3}],["http-retry-post",{min:3,max:4}],["frequencies",{min:1,max:1}],["auth-sha256",{min:1,max:1}],["auth-hmac",{min:2,max:2}],["math-round-dec",{min:2,max:2}],["server-get",{min:2,max:2}],["server-post",{min:2,max:2}],["server-put",{min:2,max:2}],["server-json",{min:1,max:2}]]),Yy=new Set(["define","defn","defun","fn","lambda","if","cond","let","let*","when","unless","do","begin","and","or","not","match","try","catch","throw","load","fl-require","server-get","server-post","server-put","server-delete","server-start","server-json","server-html","server-text","server-status","db-create","db-query","db-exec","db-insert"]);function Qy(r){let t=new Map,e=new Map;function n(s){if(!s||typeof s!="object")return;if(s.kind!=="sexpr"){Array.isArray(s.body)&&s.body.forEach(n);return}let a=s.op;if(a!=="defn"&&a!=="defun"){if(a==="define"&&(s.args?.length??0)>=2){let h=s.args[0],y=s.args[1],k="";h?.kind==="variable"?k=h.name:h?.kind==="literal"&&h?.type==="symbol"&&(k=String(h.value??""));let v=oa(y);k&&v!==null&&e.set(k,v)}if((a==="let"||a==="let*")&&(s.args?.length??0)>=1){let h=s.args[0];if(h?.kind==="block"&&h?.type==="Array"){let y=h.fields?.get?.("items")??[];for(let k of y)if(k?.kind==="block"&&k?.type==="Array"){let v=k.fields?.get?.("items")??[];if(v.length>=2){let $=v[0],M=v[1],O="";$?.kind==="variable"?O=$.name:$?.kind==="literal"&&$?.type==="symbol"&&(O=String($.value??""));let C=oa(M);O&&C!==null&&e.set(O,C)}}}}s.args?.forEach(n);return}let i=0,o=s.args||[],u="any";if(o[i]?.kind==="literal"&&String(o[i]?.value??"").startsWith("^")){let h=String(o[i].value);h!=="^pure"&&(u=rp(h)),i++}let f=o[i++],l="";if(f?.kind==="variable"?l=f.name:f?.kind==="literal"&&f?.type==="symbol"&&(l=String(f.value)),!l)return;let c=o[i],p=[],m=!1;if(c?.kind==="block"&&c?.type==="Array"){let h=c.fields?.get?.("items")??[],y=0;for(;y<h.length;){let k=h[y];if(k?.kind==="literal"&&String(k?.value??"").startsWith("^")){let v=rp(String(k.value));y++;let $=h[y];$?.kind==="variable"&&p.push({name:$.name,type:v})}else if(k?.kind==="variable"){let v=k.name;(v.startsWith("...")||v.startsWith("rest"))&&(m=!0),p.push({name:v,type:"any"})}y++}}let d=o.slice(i+1),g=d.length>0?d[d.length-1]:void 0;t.set(l,{name:l,params:p,returnType:u,line:s.line??0,variadic:m,lastExprNode:g}),d.forEach(n)}return Array.isArray(r)&&r.forEach(n),{defs:t,varTypes:e}}function Zy(r,t,e){let n=[];function s(a,i){if(!a||typeof a!="object")return;if(a.kind!=="sexpr"){Array.isArray(a.body)&&a.body.forEach(p=>s(p,i));return}let o=String(a.op??""),u=a.args??[],f=a.line??0;if(o==="defn"||o==="defun"){let p=0;u[p]?.kind==="literal"&&String(u[p]?.value??"").startsWith("^")&&p++;let m=u[p++],d="";m?.kind==="variable"?d=m.name:m?.kind==="literal"&&(d=String(m.value));let g=d?t.get(d):void 0;if(g&&g.returnType!=="any"&&g.lastExprNode){let h=oa(g.lastExprNode);h!==null&&!sp(g.returnType,h)&&n.push({kind:"warning",code:"return-type",line:g.line,message:`(${d}) \u2014 \uC120\uC5B8 \uBC18\uD658 \uD0C0\uC785 ^${g.returnType}\uC774\uB098 ${h} \uB9AC\uD130\uB7F4 \uBC18\uD658`})}u.slice(p+1).forEach(h=>s(h,d));return}if(Yy.has(o)){u.forEach(p=>s(p,i));return}let l=t.get(o);if(l&&!l.variadic){let p=u.length,m=l.params.length;if(p!==m)n.push({kind:"error",code:"arity",line:f,message:`(${o}) \u2014 \uC778\uC790 ${p}\uAC1C \uC804\uB2EC, ${m}\uAC1C \uD544\uC694 (${l.params.map(d=>"$"+d.name).join(" ")})`});else for(let d=0;d<l.params.length;d++){let g=l.params[d];if(g.type==="any")continue;let h=Jy(u[d],e);h!==null&&(sp(g.type,h)||n.push({kind:"warning",code:"type-mismatch",line:f,message:`(${o}) \u2014 $${g.name}: ^${g.type} \uD30C\uB77C\uBBF8\uD130\uC5D0 ${h} \uC804\uB2EC`}))}}let c=Xy.get(o);if(c&&!l){let p=u.length;if(p<c.min||p>c.max){let m=c.max===1/0?`${c.min}\uAC1C \uC774\uC0C1`:c.min===c.max?`${c.min}\uAC1C`:`${c.min}~${c.max}\uAC1C`;n.push({kind:"error",code:"arity",line:f,message:`(${o}) \u2014 \uC778\uC790 ${p}\uAC1C \uC804\uB2EC, ${m} \uD544\uC694`})}}u.forEach(p=>s(p,i))}return Array.isArray(r)&&r.forEach(a=>s(a)),n}function ap(r){try{let t=W(r),e=H(t),{defs:n,varTypes:s}=Qy(e),a=Zy(e,n,s);return{errors:a.filter(i=>i.kind==="error"),warnings:a.filter(i=>i.kind==="warning"),fnCount:n.size,checkedCalls:a.length}}catch{return{errors:[],warnings:[],fnCount:0,checkedCalls:0}}}function ip(r,t){if(r.length===0)return"";let n=[`
919
+ \x1B[36m[type-check]\x1B[0m ${require("path").basename(t)} \u2014 ${r.length}\uAC74`];for(let s of r){let a=s.kind==="error"?"\x1B[31m\u2716\x1B[0m":"\x1B[33m\u26A0\x1B[0m",i=s.kind==="error"?"\x1B[31m":"\x1B[33m";n.push(` ${a} line ${s.line}: ${i}${s.code}\x1B[0m \u2014 ${s.message}`)}return n.join(`
920
+ `)}Br();var rn=z(require("fs")),jt=z(require("path"));be();ke();function op(r){let t=null;return function(n){t&&(clearTimeout(t),t=null),t=setTimeout(()=>{t=null,n()},r)}}var Zi=class{constructor(){this.watchers=[]}watch(t,e){let n=e?.debounceMs??300,s=e?.clearConsole??!0,a=e?.onReload,i=e?.onError,o=op(n),u=jt.basename(t),f=()=>{o(()=>{if(s&&process.stdout.write("\x1B[2J\x1B[0f"),console.log(`\x1B[36m[RELOAD]\x1B[0m ${u} changed`),a)try{a(t)}catch(d){i?i(t,d instanceof Error?d:new Error(String(d))):console.error(`\x1B[31m[ERROR]\x1B[0m ${u}: ${d.message??d}`)}})},l=0,c=-1;try{let d=rn.statSync(t);l=d.mtimeMs,c=d.size}catch{}let p=setInterval(()=>{try{let d=rn.statSync(t);(d.mtimeMs!==l||d.size!==c)&&(l=d.mtimeMs,c=d.size,f())}catch{}},500);p.unref?.();let m=!1;return()=>{m||(m=!0,clearInterval(p))}}watchDir(t,e,n){let s=n?.debounceMs??300,a=n?.clearConsole??!0,i=n?.onReload,o=n?.onError,u=op(s),f=e.replace(/^\*/,""),l=new RegExp(f.replace(".","\\.")+"$"),c=null;try{c=rn.watch(t,(m,d)=>{d&&l.test(d)&&u(()=>{a&&process.stdout.write("\x1B[2J\x1B[0f"),console.log(`\x1B[36m[RELOAD]\x1B[0m ${d} changed`);let g=jt.join(t,d);if(i)try{i(g)}catch(h){o?o(g,h instanceof Error?h:new Error(String(h))):console.error(`\x1B[31m[ERROR]\x1B[0m ${d}: ${h.message??h}`)}})}),this.watchers.push(c)}catch{}let p=!1;return()=>{if(!p&&c){p=!0;try{c.close()}catch{}let m=this.watchers.indexOf(c);m!==-1&&this.watchers.splice(m,1)}}}stopAll(){for(let t of this.watchers)try{t.close()}catch{}this.watchers=[]}};function cp(r,t){let e=jt.resolve(r);function n(){try{let i=rn.readFileSync(e,"utf-8"),o=W(i),u=H(o),f=new we;f.currentFilePath=e;let c=f.interpret(u).lastValue;c!=null&&console.log(typeof c=="object"?JSON.stringify(c,null,2):String(c)),t?.onReload&&t.onReload(r)}catch(i){let o=i instanceof Error?i:new Error(String(i));t?.onError?t.onError(r,o):console.error(`\x1B[31m[ERROR]\x1B[0m ${jt.basename(e)}: ${o.message}`)}}n();let s=new Zi,a={...t,onReload:i=>{n()}};console.log(`\x1B[2m watching ${jt.basename(e)}...\x1B[0m`),s.watch(e,a)}function ca(r){let t=[],e=[],n=!1,s=[];for(let a of r){let i=a.replace(/^;;;\s?/,"");if(i.startsWith("@example")){s.length>0&&(e.push(s.join(`
921
+ `).trim()),s=[]),n=!0;let o=i.replace(/^@example\s*/,"");o&&s.push(o)}else n?s.push(i):t.push(i)}return s.length>0&&e.push(s.join(`
922
+ `).trim()),{doc:t.join(`
923
+ `).trim(),examples:e}}function eb(r){let t=r.match(/:params\s*\[([^\]]*)\]/);return t?t[1].split(/\s+/).map(e=>e.trim()).filter(e=>e.startsWith("$")).map(e=>e.slice(1)):[]}function qr(r,t){let e=0,n=t,s=!1,a=r[t],i=a==="["?"]":")";for(;n<r.length;){let o=r[n];if(o==='"')for(n++;n<r.length&&r[n]!=='"';)r[n]==="\\"&&n++,n++;else if(o===a)e++,s=!0;else if(o===i&&(e--,s&&e===0))return r.slice(t,n+1);n++}return r.slice(t,n)}function ua(r){let t=[],e=r.split(`
924
+ `),n=[],s=0;for(let i of e)n.push(s),s+=i.length+1;let a=0;for(;a<e.length;){let i=e[a],o=i.trim(),u=o.match(/^\[FUNC\s+(\S+)/);if(u){let m=u[1],d=la(e,a),{doc:g,examples:h}=ca(d),y=n[a],k=qr(r,y+i.indexOf("[FUNC")),v=eb(k);t.push({name:m,kind:"function",params:v,doc:g,examples:h,source:k}),a++;continue}let f=o.match(/^\(defmacro\s+(\S+)/);if(f){let m=f[1],d=la(e,a),{doc:g,examples:h}=ca(d),y=n[a],k=i.indexOf("(defmacro"),v=qr(r,y+k),$=v.match(/\(defmacro\s+\S+\s+\[([^\]]*)\]/),M=$?$[1].split(/\s+/).map(O=>O.trim()).filter(O=>O.startsWith("$")).map(O=>O.slice(1)):[];t.push({name:m,kind:"macro",params:M,doc:g,examples:h,source:v}),a++;continue}let l=o.match(/^\(defstruct\s+(\S+)/);if(l){let m=l[1],d=la(e,a),{doc:g,examples:h}=ca(d),y=n[a],k=i.indexOf("(defstruct"),v=qr(r,y+k),$=v.match(/\(defstruct\s+\S+\s+\[([^\]]*)\]/),M=$?$[1].split(/\s+/).map(O=>O.trim()).filter(O=>O.startsWith(":")).map(O=>O.slice(1)):[];t.push({name:m,kind:"struct",params:M,doc:g,examples:h,source:v}),a++;continue}let c=o.match(/^\(defprotocol\s+(\S+)/);if(c){let m=c[1],d=la(e,a),{doc:g,examples:h}=ca(d),y=n[a],k=i.indexOf("(defprotocol"),v=qr(r,y+k);t.push({name:m,kind:"protocol",params:[],doc:g,examples:h,source:v}),a++;continue}if(o.match(/^\[MODULE\s+(\S+)/)){let m=n[a],d=i.indexOf("[MODULE"),g=qr(r,m+d),h=ua(g.replace(/^\[MODULE[^\n]*\n/,""));t.push(...h),a++;continue}a++}return t}function la(r,t){let e=[],n=t-1;for(;n>=0;){let s=r[n].trim();if(s.startsWith(";;;"))e.unshift(r[n].trim()),n--;else{if(s==="")break;break}}return e}function eo(r,t){let e=[],n=t??"FreeLang API \uBB38\uC11C";if(e.push(`# ${n}`),e.push(""),r.length===0)return e.push("(\uBB38\uC11C\uD654\uB41C \uD56D\uBAA9 \uC5C6\uC74C)"),e.join(`
925
+ `);e.push("## \uBAA9\uCC28"),e.push("");for(let s of r){let a=tb(s.kind),i=rb(s.name);e.push(`- [${a} \`${s.name}\`](#${i})`)}e.push("");for(let s of r){if(e.push(`## ${s.name}`),e.push(""),e.push(`**\uC885\uB958**: ${nb(s.kind)}`),e.push(""),s.doc&&(e.push(s.doc),e.push("")),s.params.length>0){e.push("### \uD30C\uB77C\uBBF8\uD130"),e.push(""),e.push("| \uC774\uB984 | \uC124\uBA85 |"),e.push("|------|------|");for(let a of s.params)e.push(`| \`${a}\` | |`);e.push("")}else(s.kind==="function"||s.kind==="macro")&&(e.push("*\uD30C\uB77C\uBBF8\uD130 \uC5C6\uC74C*"),e.push(""));if(s.examples.length>0){e.push("### \uC608\uC81C"),e.push("");for(let a of s.examples)e.push("```freelang"),e.push(a),e.push("```"),e.push("")}e.push("### \uC18C\uC2A4"),e.push(""),e.push("```freelang"),e.push(s.source),e.push("```"),e.push(""),e.push("---"),e.push("")}return e.join(`
926
+ `)}function tb(r){switch(r){case"function":return"fn";case"macro":return"macro";case"struct":return"struct";case"protocol":return"protocol"}}function nb(r){switch(r){case"function":return"\uD568\uC218 (FUNC)";case"macro":return"\uB9E4\uD06C\uB85C (defmacro)";case"struct":return"\uAD6C\uC870\uCCB4 (defstruct)";case"protocol":return"\uD504\uB85C\uD1A0\uCF5C (defprotocol)"}}function rb(r){return r.toLowerCase().replace(/[^a-z0-9가-힣]/g,"-")}var Hn=z(require("fs"));no();var so=class{constructor(t={}){this.steps=[];this.failFast=!0;t.failFast!==void 0&&(this.failFast=t.failFast)}setFailFast(t){return this.failFast=t,this}addStep(t){return this.steps.push(t),this}async run(){let t=[],e=!0,n=0,s=!1;for(let a of this.steps){if(s){t.push({name:a.name,passed:!1,output:"(skipped)",durationMs:0,skipped:!0});continue}let i;try{i=await a.run()}catch(u){i={passed:!1,output:`Exception: ${u.message??String(u)}`,durationMs:0}}let o=i.passed?"\u2705":"\u274C";if(console.log(`${o} ${a.name} (${i.durationMs}ms)`),!i.passed&&i.output&&i.output!=="(skipped)"){let u=i.output.split(`
927
+ `).map(f=>" "+f).join(`
928
+ `);console.log(u)}t.push({name:a.name,passed:i.passed,output:i.output,durationMs:i.durationMs,skipped:!1}),n+=i.durationMs,i.passed||(e=!1,this.failFast&&(s=!0))}return{passed:e,steps:t,totalMs:n}}};async function ao(r){let t=Date.now(),{passed:e,output:n}=await r(),s=Date.now()-t;return{passed:e,output:n,durationMs:s}}function ob(r){return{name:"fmt-check",run:()=>ao(async()=>{if(r.length===0)return{passed:!0,output:"\uAC80\uC0AC\uD560 \uD30C\uC77C \uC5C6\uC74C"};let t=[];for(let e of r){if(!Hn.existsSync(e))continue;let n=Hn.readFileSync(e,"utf-8");try{let s=Dr(n);n!==s&&t.push(e)}catch(s){return{passed:!1,output:`\uD3EC\uB9F7 \uC624\uB958 ${e}: ${s.message}`}}}return t.length>0?{passed:!1,output:`\uD3EC\uB9F7 \uD544\uC694 \uD30C\uC77C:
929
+ ${t.map(e=>` - ${e}`).join(`
930
+ `)}`}:{passed:!0,output:`${r.length}\uAC1C \uD30C\uC77C \uD3EC\uB9F7 OK`}})}}function cb(r){return{name:"lint",run:()=>ao(async()=>{if(r.length===0)return{passed:!0,output:"\uAC80\uC0AC\uD560 \uD30C\uC77C \uC5C6\uC74C"};let t=vp(),e=[];for(let n of r){if(!Hn.existsSync(n))continue;let s=Hn.readFileSync(n,"utf-8"),i=t.lint(s).filter(o=>o.severity==="error");for(let o of i)e.push(` ${n}:${o.line??"?"}:${o.col??"?"} [${o.rule}] ${o.message}`)}return e.length>0?{passed:!1,output:`Lint \uC624\uB958 ${e.length}\uAC1C:
931
+ ${e.join(`
932
+ `)}`}:{passed:!0,output:`${r.length}\uAC1C \uD30C\uC77C lint OK`}})}}function lb(){return{name:"type-check",run:()=>ao(async()=>{let{execSync:r}=require("child_process");try{let t=process.cwd();return r("npx tsc --noEmit",{cwd:t,stdio:"pipe"}),{passed:!0,output:"TypeScript \uD0C0\uC785 \uCCB4\uD06C OK"}}catch(t){return{passed:!1,output:(t.stdout?.toString()??t.stderr?.toString()??String(t)).trim()}}})}}function wp(r,t={}){let e=new so(t);return e.addStep(ob(r)),e.addStep(cb(r)),e.addStep(lb()),e}var Ur=z(require("fs")),io=z(require("path")),Vr=class{constructor(t="app"){this.routes=[];this.layoutChain={};this.middlewares=new Map;this.errorHandlers=new Map;this.notFoundHandler=null;this.appDir=t,this.scan()}scanNotFound(t){try{let e=io.join(t,"not-found.fl");Ur.existsSync(e)&&(this.notFoundHandler=e,console.log(`approuter.not-found file=${e}`))}catch{}}scan(){if(!Ur.existsSync(this.appDir)){console.log(`approuter.warn event=app_dir_missing path=${this.appDir}`);return}this.scanDirectory(this.appDir,"","layout"),this.scanDirectory(this.appDir,"","middleware"),this.scanDirectory(this.appDir,"","error"),this.scanNotFound(this.appDir),this.scanDirectory(this.appDir,"","page"),this.scanDirectory(this.appDir,"","route"),this.buildLayoutChain()}scanDirectory(t,e="",n="page"){try{let s=Ur.readdirSync(t,{withFileTypes:!0});for(let a of s){let i=io.join(t,a.name),o=e===""?"/"+a.name:e+"/"+a.name;if(a.isDirectory()){let f=a.name.startsWith("(")&&a.name.endsWith(")")?e:o;this.scanDirectory(i,f,n)}else if(n==="page"&&a.name==="page.fl"){let u=e===""?"/":e;this.registerRoute(u,i,"page")}else if(n==="route"&&a.name==="route.fl"){let u=e===""?"/":e;this.registerRoute(u,i,"route")}else if(n==="layout"&&a.name==="layout.fl"){let u=e===""?"/":e;this.layoutChain[u]||(this.layoutChain[u]=[]),this.layoutChain[u].push(i),console.log(`approuter.layout scope=${u} file=${i}`)}else if(n==="middleware"&&a.name==="middleware.fl"){let u=e===""?"/":e;this.middlewares.set(u,i),console.log(`approuter.middleware scope=${u} file=${i}`)}else if(n==="error"&&a.name==="error.fl"){let u=e===""?"/":e;this.errorHandlers.set(u,i),console.log(`approuter.error scope=${u} file=${i}`)}}}catch(s){console.error(`Error scanning directory ${t}:`,s.message)}}registerRoute(t,e,n="page"){let s=this.buildPattern(t),a=this.extractParams(t),i=t.includes("["),o={path:t,pattern:s,filePath:e,params:a,isDynamic:i,layouts:n==="route"?[]:this.getLayoutsForPath(t),kind:n};this.routes.push(o),console.log(`approuter.${n} path=${t} file=${e} dynamic=${i}`)}buildPattern(t){let e=t.split("/").map(n=>n.startsWith("[")&&n.endsWith("]")?"([^/]+)":n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("\\/");return new RegExp(`^${e}$`)}extractParams(t){let e=t.match(/\[([^\]]+)\]/g);return e?e.map(n=>n.slice(1,-1)):[]}getLayoutsForPath(t){let e=[],n=t.split("/").filter(Boolean);(this.layoutChain["/"]||this.layoutChain[""])&&e.push(...this.layoutChain["/"]||this.layoutChain[""]||[]);let s="";for(let a of n)s+="/"+a,this.layoutChain[s]&&e.push(...this.layoutChain[s]);return e}buildLayoutChain(){}match(t){for(let e of this.routes){let n=t.match(e.pattern);if(n){let s={};return e.params.forEach((a,i)=>{s[a]=n[i+1]}),{route:e,params:s}}}return null}getRoutes(){return this.routes}getMiddlewareForPath(t){return this.middlewares.get(t)||null}getErrorHandlerForPath(t){return this.errorHandlers.has(t)?this.errorHandlers.get(t)||null:this.errorHandlers.get("/")||null}getNotFoundHandler(){return this.notFoundHandler}getLayoutsForRoute(t){return this.layoutChain[t]||[]}};var zr=z(require("fs")),Wr=z(require("crypto"));be();ke();var pa=class{constructor(t){this.cache=new Map;this.cacheTimeout=5*60*1e3;this._helpersInjected=!1;this.interpreter=t}ensureHelpers(){this._helpersInjected||(this.injectJWTFunctions(),this.injectAuthHelpers(),this.injectDBHelpers(),this.injectMetaHelpers(),this.injectFetchHelpers(),this.injectHTTPServerHelpers(),this._helpersInjected=!0)}parseFile(t){let e=Date.now(),n=this.cache.get(t);if(n&&e-n.timestamp<this.cacheTimeout)return n.ast;let s=zr.readFileSync(t,"utf-8"),a=W(s),i=H(a);return this.cache.set(t,{ast:i,timestamp:e}),i}initializeDataStore(){let t=this.interpreter.context;t.__db||(t.__db={users:new Map,projects:new Map,todos:new Map,sessions:new Map,messages:new Map,boards:new Map,documents:[],boardMembers:new Map,_nextId:{users:1,projects:1,todos:1,messages:1,boards:1}})}async executePage(t,e){try{if(!zr.existsSync(t))return{success:!1,status:404,error:`Page not found: ${t}`};let n=this.parseFile(t),s=this.createFlRequest(e);this.initializeDataStore();let a=this.interpreter.context,i=a.__db;a.__params=e.params||{},a.__body=e.body||{},a.__method=e.method||"GET",a.__headers=e.headers||{},a.__query=e.query||{},this.interpreter.context.variables.set("$__params",e.params||{}),this.interpreter.context.variables.set("$__query",e.query||{}),a.__page_meta={},a.__db_users=i.users,a.__db_projects=i.projects,a.__db_todos=i.todos,a.__db_sessions=i.sessions,a.__db_messages=i.messages,a.__db_boards=i.boards,a.__db_members=i.boardMembers,this.ensureHelpers();let u=this.interpreter.interpret(n).lastValue,f=a.__page_meta&&Object.keys(a.__page_meta).length>0?a.__page_meta:void 0,l=this.processResult(u);return f&&(l.meta=f),l}catch(n){return{success:!1,status:500,error:n.message,stack:n.stack}}}async executeRoute(t,e){try{if(!zr.existsSync(t))return{success:!1,status:404,error:`Route not found: ${t}`};let n=this.parseFile(t),s=this.createFlRequest(e);this.ensureHelpers(),this.interpreter.globals=this.interpreter.globals||{},this.interpreter.globals.__request=s,this.interpreter.globals.__params=e.params||{},this.interpreter.context.variables.set("$__request",s),this.interpreter.context.variables.set("$__params",e.params||{});let a=null;for(let f of n)a=this.interpreter.eval(f);let i=(e.method||e.req?.method||"GET").toUpperCase(),o=this.interpreter.context.variables,u=o.has(i)?o.get(i):o.has("$"+i)?o.get("$"+i):null;if(u&&typeof u=="object"&&u.kind==="function-value")try{a=this.interpreter.callFunctionValue(u,[s])}catch(f){return console.error(`[executeRoute] \uD578\uB4E4\uB7EC \uC2E4\uD589 \uC624\uB958 (${i}): ${f.message}`,f.stack),{success:!1,status:500,error:f.message,stack:f.stack}}return this.processResult(a)}catch(n){return console.error(`[executeRoute] \uD30C\uC77C \uC2E4\uD589 \uC624\uB958: ${n.message}`,n.stack),{success:!1,status:500,error:n.message,stack:n.stack}}}createFlRequest(t){return{__fl_request:!0,method:t.req?.method||"GET",path:t.req?.path||"/",query:t.query||{},params:t.params||{},headers:t.headers||{},body:t.body||"",timestamp:Date.now()}}processResult(t){return t&&typeof t=="object"?t.__fl_response===!0?{success:!0,status:t.status||200,body:t.body,contentType:t.contentType||"application/json"}:{success:!0,status:200,body:t,contentType:"application/json"}:typeof t=="string"?{success:!0,status:200,body:t,contentType:t.includes("<")?"text/html; charset=utf-8":"text/plain"}:{success:!0,status:204,body:"",contentType:"text/plain"}}clearCache(t){t?this.cache.delete(t):this.cache.clear()}getCacheStats(){return{size:this.cache.size,files:Array.from(this.cache.keys())}}injectJWTFunctions(){let t=this.interpreter.context,e=process.env.JWT_SECRET||"freelang-v11-default-secret";t["jwt-sign"]=n=>{let s={alg:"HS256",typ:"JWT"},a=Math.floor(Date.now()/1e3),i={...n,iat:a,exp:a+24*60*60},o=Buffer.from(JSON.stringify(s)).toString("base64url"),u=Buffer.from(JSON.stringify(i)).toString("base64url"),f=`${o}.${u}`,l=Wr.createHmac("sha256",e).update(f).digest("base64url");return`${o}.${u}.${l}`},t["jwt-verify"]=n=>{try{let s=n.split(".");if(s.length!==3)return null;let a=`${s[0]}.${s[1]}`,i=Wr.createHmac("sha256",e).update(a).digest("base64url"),o=Buffer.from(s[2]),u=Buffer.from(i);if(o.length!==u.length||!Wr.timingSafeEqual(o,u))return null;let f=JSON.parse(Buffer.from(s[1],"base64url").toString()),l=Math.floor(Date.now()/1e3);return f.exp&&f.exp<l?null:f}catch{return null}}}injectFetchHelpers(){let t=this.interpreter.context,e=(s,a)=>{try{let i=(a?.method||"GET").toUpperCase(),o=a?.headers||{},u=a?.body||null,f=new URL(s),l=f.protocol==="https:"?require("https"):require("http"),c="",p=null,m=l.request(f,{method:i,headers:o},d=>{d.on("data",g=>{c+=g}),d.on("end",()=>{})});return m.on("error",d=>{p=d}),u&&m.write(u),m.end(),p?null:c||null}catch{return null}},n=(s,a)=>{try{let i=e(s,a);return i?JSON.parse(i):null}catch{return null}};t["server-fetch"]=e,t["server-fetch-json"]=n,this.interpreter.context.variables.set("$server-fetch",e),this.interpreter.context.variables.set("server-fetch",e),this.interpreter.context.variables.set("$server-fetch-json",n),this.interpreter.context.variables.set("server-fetch-json",n)}injectAuthHelpers(){let t=this.interpreter.context;t["auth-user"]=e=>{if(!e)return null;let n=e.replace("Bearer ",""),s=t["jwt-verify"](n);if(!s)return null;let a=t.__db;return a&&a.users?Array.from(a.users.values()).find(o=>o.id===s.userId)||null:s}}injectDBHelpers(){let t=this.interpreter.context;t.create=(e,n)=>{let s=t.__db,a=Object.keys(s).find(u=>s[u]===e),i=s._nextId[a]||1;s._nextId[a]=i+1;let o={id:i,...n,created_at:new Date};return e.set(i,o),o},t.get=(e,n)=>e.get(n),t.list=e=>Array.from(e.values()),t.update=(e,n,s)=>{let a=e.get(n);if(a){let i={...a,...s,updated_at:new Date};return e.set(n,i),i}return null},t.delete=(e,n)=>e.delete(n),t["get-member"]=(e,n,s)=>{let a=`${n}:${s}`;return e.get(a)},t["add-member"]=(e,n,s,a="member")=>{let i=`${n}:${s}`,o={boardId:n,userId:s,role:a,joined_at:new Date};return e.set(i,o),o},t["str-to-int"]=e=>parseInt(String(e),10),t.merge=(e,n)=>({...e,...n}),t.count=e=>e instanceof Map?e.size:Array.isArray(e)?e.length:typeof e=="object"&&e!==null?Object.keys(e).length:0}injectMetaHelpers(){let t=this.interpreter.context,e=n=>(t.__page_meta||(t.__page_meta={}),n&&typeof n=="object"&&Object.assign(t.__page_meta,n),n);t["set-meta!"]=e,this.interpreter.context.variables.set("$set-meta!",e),this.interpreter.context.variables.set("set-meta!",e)}injectHTTPServerHelpers(){let t=this.interpreter.context;t.server_json=e=>({__fl_response:!0,status:200,contentType:"application/json",body:e}),t.server_html=e=>({__fl_response:!0,status:200,contentType:"text/html; charset=utf-8",body:e}),t.server_text=e=>({__fl_response:!0,status:200,contentType:"text/plain",body:e}),t.server_status=(e,n)=>({__fl_response:!0,status:e,contentType:"application/json",body:n}),this.interpreter.context.variables.set("$server_json",t.server_json),this.interpreter.context.variables.set("server_json",t.server_json),this.interpreter.context.variables.set("$server_html",t.server_html),this.interpreter.context.variables.set("server_html",t.server_html),this.interpreter.context.variables.set("$server_text",t.server_text),this.interpreter.context.variables.set("server_text",t.server_text),this.interpreter.context.variables.set("$server_status",t.server_status),this.interpreter.context.variables.set("server_status",t.server_status)}},_p=pa;var ze=z(require("fs")),Sp=z(require("path")),fa=class{constructor(t,e){this.ssrCache=new Map;this.buildOutputDir=".next";this.executor=t,e&&(this.buildOutputDir=e)}async render(t){switch(t.mode){case"ssr":return this.renderSSR(t);case"isr":return this.renderISR(t);case"ssg":return this.renderSSG(t);default:throw new Error(`Unknown render mode: ${t.mode}`)}}async renderSSR(t){let e=Date.now(),n=await this.executor.executePage(t.filePath,{req:{method:"GET",path:"/"},params:t.params,query:t.query,headers:t.headers,body:t.body});if(!n.success)throw new Error(`Failed to render page: ${n.error}`);return{html:typeof n.body=="string"?n.body:JSON.stringify(n.body),timestamp:Date.now(),cached:!1,cacheAge:Date.now()-e}}async renderISR(t){let e=this.getCacheKey(t.filePath,t.params),n=t.revalidateAfter||60,s=this.ssrCache.get(e);if(s&&Date.now()-s.timestamp<n*1e3)return{html:s.html,timestamp:s.timestamp,cached:!0,cacheAge:Date.now()-s.timestamp};let a=await this.renderSSR(t);return this.ssrCache.set(e,{html:a.html,timestamp:a.timestamp,revalidate:n}),{...a,cached:!1}}async renderSSG(t){let e=this.getCacheKey(t.filePath,t.params),n=Sp.join(this.buildOutputDir,e.replace(/\//g,"_")+".html");if(ze.existsSync(n)){let a=ze.readFileSync(n,"utf-8"),i=ze.statSync(n);return{html:a,timestamp:i.mtime.getTime(),cached:!0,cacheAge:Date.now()-i.mtime.getTime()}}let s=await this.renderSSR(t);return ze.existsSync(this.buildOutputDir)||ze.mkdirSync(this.buildOutputDir,{recursive:!0}),ze.writeFileSync(n,s.html,"utf-8"),s}async renderWithLayout(t,e){let n=t;for(let s of[...e].reverse()){let a=await this.executor.executePage(s,{req:{method:"GET",path:"/"}});if(!a.success)continue;let i=typeof a.body=="string"?a.body:typeof a.body=="object"&&a.body!==null&&typeof a.body.html=="string"?a.body.html:"";if(!i)continue;let o=/\{\{\s*children\s*\}\}|\{\{\{\s*children\s*\}\}\}|<Outlet\s*\/?>/i;o.test(i)&&(n=i.replace(o,n))}return n}getCacheKey(t,e){let n=t;if(e&&Object.keys(e).length>0){let s=Object.entries(e).sort().map(([a,i])=>`${a}=${i}`).join("&");n+=`?${s}`}return n}invalidateISRCache(){this.ssrCache.clear()}invalidateISRPath(t,e){let n=this.getCacheKey(t,e);this.ssrCache.delete(n)}async buildSSG(t){let e=0;for(let n of t){let s=n.params||[{}];for(let a of s)try{await this.renderSSG({filePath:n.filePath,mode:"ssg",params:a}),e++}catch(i){console.error(`Failed to build ${n.filePath}:`,i.message)}}return e}getCacheStats(){return{isrCacheSize:this.ssrCache.size,isrCachedPaths:Array.from(this.ssrCache.keys())}}},xp=fa;var Ap=z(require("http"));function It(r){return r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function ub(r,t={}){let e=r.filePath||"Page",n=`<h1>${e}</h1>`;if(Object.keys(t).length>0){n+="<p><strong>Route Parameters:</strong></p><ul>";for(let[s,a]of Object.entries(t))n+=`<li>${s}: ${a}</li>`;n+="</ul>"}return ma(e,n)}function ma(r,t,e=""){return`<!DOCTYPE html>
933
+ <html>
934
+ <head>
935
+ <meta charset="UTF-8">
936
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
937
+ <title>FreeLang v11 - ${r}</title>
938
+ <style>
939
+
940
+ * { margin: 0; padding: 0; box-sizing: border-box; }
941
+ body {
942
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto;
943
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
944
+ min-height: 100vh;
945
+ display: flex;
946
+ align-items: center;
947
+ justify-content: center;
948
+ padding: 20px;
949
+ }
950
+ .container {
951
+ background: white;
952
+ border-radius: 12px;
953
+ box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
954
+ padding: 40px;
955
+ max-width: 600px;
956
+ width: 100%;
957
+ }
958
+ h1 { color: #667eea; margin-bottom: 20px; }
959
+ p { color: #666; margin-bottom: 15px; }
960
+ ul { margin-left: 20px; }
961
+ li { margin-bottom: 10px; }
962
+ a { color: #667eea; text-decoration: none; }
963
+ a:hover { text-decoration: underline; }
964
+ ${e?`
965
+ `+e:""}
966
+ </style>
967
+ </head>
968
+ <body>
969
+ <div class="container">
970
+ ${t}
971
+ <hr style="margin: 30px 0; border: none; border-top: 1px solid #eee;">
972
+ <p><small>Powered by FreeLang v11 App Router</small></p>
973
+ <p><a href="/">\u2190 Back to Home</a></p>
974
+ </div>
975
+ </body>
976
+ </html>`}function pb(){return`<!DOCTYPE html>
977
+ <html>
978
+ <head>
979
+ <meta charset="UTF-8">
980
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
981
+ <title>FreeLang v11</title>
982
+ <style>
983
+ * { margin: 0; padding: 0; box-sizing: border-box; }
984
+ body {
985
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto;
986
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
987
+ min-height: 100vh;
988
+ display: flex;
989
+ align-items: center;
990
+ justify-content: center;
991
+ padding: 20px;
992
+ }
993
+ .hero {
994
+ text-align: center;
995
+ color: white;
996
+ max-width: 800px;
997
+ }
998
+ h1 { font-size: 3em; margin-bottom: 10px; }
999
+ p { font-size: 1.2em; margin-bottom: 30px; opacity: 0.9; }
1000
+ .features {
1001
+ display: grid;
1002
+ grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
1003
+ gap: 20px;
1004
+ margin: 40px 0;
1005
+ }
1006
+ .feature {
1007
+ background: rgba(255,255,255,0.1);
1008
+ backdrop-filter: blur(10px);
1009
+ padding: 20px;
1010
+ border-radius: 10px;
1011
+ border: 1px solid rgba(255,255,255,0.2);
1012
+ }
1013
+ .feature h3 { margin-bottom: 10px; }
1014
+ .links {
1015
+ display: flex;
1016
+ gap: 15px;
1017
+ justify-content: center;
1018
+ flex-wrap: wrap;
1019
+ margin-top: 30px;
1020
+ }
1021
+ a {
1022
+ background: white;
1023
+ color: #667eea;
1024
+ padding: 12px 24px;
1025
+ border-radius: 6px;
1026
+ text-decoration: none;
1027
+ font-weight: bold;
1028
+ transition: all 0.2s;
1029
+ }
1030
+ a:hover { transform: translateY(-2px); box-shadow: 0 10px 20px rgba(0,0,0,0.2); }
1031
+ </style>
1032
+ </head>
1033
+ <body>
1034
+ <div class="hero">
1035
+ <h1>FreeLang v11</h1>
1036
+ <p>AI-Native Language with App Router</p>
1037
+
1038
+ <div class="features">
1039
+ <div class="feature">
1040
+ <h3>Pure v11</h3>
1041
+ <p>100% FreeLang v11</p>
1042
+ </div>
1043
+ <div class="feature">
1044
+ <h3>Zero Deps</h3>
1045
+ <p>No npm dependencies</p>
1046
+ </div>
1047
+ <div class="feature">
1048
+ <h3>App Router</h3>
1049
+ <p>Filesystem-based routing</p>
1050
+ </div>
1051
+ <div class="feature">
1052
+ <h3>AGENT</h3>
1053
+ <p>Native AI blocks</p>
1054
+ </div>
1055
+ </div>
1056
+
1057
+ <div class="links">
1058
+ <a href="/demo">Demo</a>
1059
+ <a href="/api/status">Status API</a>
1060
+ </div>
1061
+ </div>
1062
+ </body>
1063
+ </html>`}var Hr=class{constructor(t={}){this.executor=null;this.renderer=null;this.server=null;this.config={appDir:t.appDir||"app",port:t.port||3e3,renderMode:t.renderMode||"ssr"},this.router=new Vr(this.config.appDir)}setInterpreter(t){this.executor=new _p(t),this.renderer=new xp(this.executor)}async start(){return this.server=Ap.createServer(async(t,e)=>{await this.handleRequest(t,e)}),new Promise(t=>{this.server.listen(this.config.port,()=>{let e=this.config.port,n=this.router.getRoutes(),s=`server.listening port=${e}`;console.log(`server.start port=${e} app_routes=${n.length}`);for(let a of n)console.log(`server.route path=${a.path} file=${a.filePath}`);t(s)})})}stop(){this.server&&(this.server.close(),this.server=null)}async handleRequest(t,e){let n=(t.url||"/").split("?")[0],s=this.parseQuery(t.url||"/"),a={};if(t.method!=="GET"&&t.method!=="HEAD")try{let u=[];for await(let l of t)u.push(l);let f=Buffer.concat(u).toString("utf-8");f&&t.headers["content-type"]?.includes("application/json")&&(a=JSON.parse(f))}catch{}if(e.setHeader("Access-Control-Allow-Origin","*"),e.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, PATCH, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type"),t.method==="OPTIONS"){e.writeHead(200),e.end();return}let i=this.router.match(n);if(i){if(this.executor)try{let u=i.route.kind||"page",f=u==="route"||n.startsWith("/api/"),l={req:{method:t.method,path:n,headers:t.headers},params:i.params,query:s,body:a,method:t.method,isApiPath:f},c=u==="route"?await this.executor.executeRoute(i.route.filePath,l):await this.executor.executePage(i.route.filePath,l);if(f){e.setHeader("Content-Type","application/json"),e.writeHead(c.status||200),typeof c.body=="string"?e.end(c.body):c.body!==null&&typeof c.body=="object"?e.end(JSON.stringify(c.body)):e.end(JSON.stringify({success:c.success,body:c.body}));return}if(c.success&&typeof c.body=="string"){let p=c.body,m=i.route.layouts;if(this.renderer&&m&&m.length>0)try{p=await this.renderer.renderWithLayout(p,m)}catch{}c.meta&&Object.keys(c.meta).length>0&&(p=this.injectMetaIntoHead(p,c.meta)),e.setHeader("Content-Type",c.contentType||"text/html; charset=utf-8"),e.writeHead(c.status||200),e.end(p)}else e.setHeader("Content-Type","text/html; charset=utf-8"),e.writeHead(c.status||500),e.end(c.error||"Internal Server Error");return}catch(u){n.startsWith("/api/")?(e.setHeader("Content-Type","application/json"),e.writeHead(500),e.end(JSON.stringify({error:u.message}))):(e.setHeader("Content-Type","text/html; charset=utf-8"),e.writeHead(500),e.end(ma("Error",`<h1>Error</h1><p>${u.message}</p>`)));return}e.setHeader("Content-Type","text/html; charset=utf-8"),e.writeHead(200),e.end(ub(i.route,i.params));return}if(n==="/demo"){e.setHeader("Content-Type","text/html; charset=utf-8"),e.writeHead(200),e.end(ma("Demo","<h1>Demo Page</h1><p>App Router demo</p>"));return}if(n==="/api/status"){e.setHeader("Content-Type","application/json"),e.writeHead(200),e.end(JSON.stringify({status:"ok",framework:"FreeLang v11",router:"App Router v1.0",routes:this.router.getRoutes().length,message:"Pure v11 web framework with filesystem routing"}));return}if(n==="/"||n===""){e.setHeader("Content-Type","text/html; charset=utf-8"),e.writeHead(200),e.end(pb());return}let o=this.router.getNotFoundHandler();if(o&&this.executor&&this.renderer)try{let u=await this.executor.executePage(o,{req:{method:t.method,path:n}});if(u.success&&typeof u.body=="string"){let f=u.body,l=this.router.getLayoutsForRoute("/");if(l&&l.length>0)try{f=await this.renderer.renderWithLayout(f,l)}catch{}u.meta&&(f=this.injectMetaIntoHead(f,u.meta)),e.setHeader("Content-Type","text/html; charset=utf-8"),e.writeHead(404),e.end(f);return}}catch{}e.setHeader("Content-Type","text/html; charset=utf-8"),e.writeHead(404),e.end(ma("404",`<h1>404 Not Found</h1><p>Route not found: ${It(n)}</p>`))}injectMetaIntoHead(t,e){let n=t.match(/<head[^>]*>/i);if(!n)return t;let s=n[0],a=t.indexOf(s),i=a+s.length,o=t.substring(a,t.indexOf("</head>",a)),u=[];e.title&&!o.includes("<title>")&&u.push(`<title>${It(e.title)}</title>`),e.description&&!o.includes('name="description"')&&u.push(`<meta name="description" content="${It(e.description)}">`),e["og-image"]&&!o.includes('property="og:image"')&&u.push(`<meta property="og:image" content="${It(e["og-image"])}">`),e["og-url"]&&!o.includes('property="og:url"')&&u.push(`<meta property="og:url" content="${It(e["og-url"])}">`),e.canonical&&!o.includes('rel="canonical"')&&u.push(`<link rel="canonical" href="${It(e.canonical)}">`),e["og-title"]&&!o.includes('property="og:title"')&&u.push(`<meta property="og:title" content="${It(e["og-title"])}">`),e["og-description"]&&!o.includes('property="og:description"')&&u.push(`<meta property="og:description" content="${It(e["og-description"])}">`);let f=u.join(`
1064
+ `);return t.substring(0,i)+`
1065
+ `+f+t.substring(i)}parseQuery(t){let e=t.split("?")[1];if(!e)return{};let n={};for(let s of e.split("&")){let[a,i]=s.split("=");a&&(n[decodeURIComponent(a)]=decodeURIComponent(i||""))}return n}getRouter(){return this.router}getRenderer(){return this.renderer}getExecutor(){return this.executor}};function fb(r){return!r||r.length===0?"":`
1066
+ \x1B[2m\uCF5C \uC2A4\uD0DD:\x1B[0m
1067
+ `+r.slice().reverse().slice(0,10).map((e,n)=>` \x1B[2m${n===0?"\u2192":" "} ${e.name??e.fn??"?"} (line ${e.line})\x1B[0m`).join(`
1068
+ `)}function Kn(r,t,e,n){let s=e?D.basename(e):"<stdin>",a=[];if(r instanceof pn){if(a.push(`
1069
+ \x1B[31m\uD30C\uC2F1 \uC624\uB958\x1B[0m ${s}:${r.line}:${r.col}`),t){let i=t.split(`
1070
+ `),o=r.line-1;if(o>=0&&o<i.length){let u=String(r.line).padStart(4," ");a.push(` ${u} \u2502 ${i[o]}`),a.push(` ${"\u2500".repeat(r.col-1)}^`)}}a.push(` ${r.message}`)}else if(r instanceof Error){let i=r.message.match(/^FreeLang line (\d+):\s*/),o=i?parseInt(i[1]):0,u=i?r.message.slice(i[0].length):r.message;if(a.push(`
1071
+ \x1B[31m\uC2E4\uD589 \uC624\uB958\x1B[0m ${s}${o?`:${o}`:""}`),t&&o>0){let l=t.split(`
1072
+ `),c=Math.max(0,o-2),p=Math.min(l.length-1,o);for(let m=c;m<=p;m++){let d=String(m+1).padStart(4," "),g=m+1===o?"\x1B[31m\u2192\x1B[0m":" ",h=m+1===o?`\x1B[31m${l[m]}\x1B[0m`:`\x1B[2m${l[m]}\x1B[0m`;a.push(` ${g} ${d} \u2502 ${h}`)}a.push("")}a.push(` \x1B[31m\u2716\x1B[0m ${u}`);let f=n??r.__flCallStack;f&&f.length>0&&a.push(fb(f))}else a.push(`
1073
+ \x1B[31m\uC624\uB958\x1B[0m ${String(r)}`);return a.join(`
1074
+ `)}function mb(r,t){try{let e=W(r);H(e);let n=t?D.basename(t):"<stdin>";return console.log(`\x1B[32m\u2713\x1B[0m ${n} \uBB38\uBC95 \uC774\uC0C1 \uC5C6\uC74C`),!0}catch(e){return console.error(Kn(e,r,t)),!1}}function Ep(r){return`/tmp/fl_${r.replace(/[^a-zA-Z0-9]/g,"_")}.pid`}function db(r,t,e=[]){let n=D.resolve(r),s=e.includes("--vm-bench");j.existsSync(n)||(console.error(`\x1B[31m\uC624\uB958\x1B[0m \uD30C\uC77C\uC744 \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4: ${r}`),process.exit(1));let a=Ep(n);try{j.writeFileSync(a,`${process.pid}
1075
+ ${n}`)}catch{}process.on("exit",()=>{try{j.unlinkSync(a)}catch{}});function i(){let o=j.readFileSync(n,"utf-8"),u;try{let l=W(o),c=H(l),p=new we;p.currentFilePath=n,e.length>0&&p.context.variables.set("$__argv__",e),u=p.interpret(c)}catch(l){console.error(Kn(l,o,n)),t||process.exit(1);return}let f=u?.lastValue;f!=null&&console.log(typeof f=="object"?JSON.stringify(f,null,2):String(f))}if(t&&(process.env.FL_DEV="1"),s){console.log(`
1076
+ \x1B[36m[vm-bench] \uC131\uB2A5 \uCE21\uC815 \uC2DC\uC791...\x1B[0m`);let o=100,u=j.readFileSync(n,"utf-8"),f=performance.now();for(let d=0;d<o;d++){delete process.env.FL_VM;try{let g=W(u),h=H(g),y=new we;y.currentFilePath=n,e.length>0&&y.context.variables.set("$__argv__",e.filter(k=>k!=="--vm-bench")),y.interpret(h)}catch{}}let l=performance.now()-f,c=performance.now();for(let d=0;d<o;d++){process.env.FL_VM="1";try{let g=W(u),h=H(g),y=new we;y.currentFilePath=n,e.length>0&&y.context.variables.set("$__argv__",e.filter(k=>k!=="--vm-bench")),y.interpret(h)}catch{}}let p=performance.now()-c;delete process.env.FL_VM;let m=l/p;if(console.log(`\x1B[36m[vm-bench]\x1B[0m interpreter: ${l.toFixed(1)}ms (${o} iter)`),console.log(`\x1B[36m[vm-bench]\x1B[0m vm: ${p.toFixed(1)}ms (${o} iter)`),console.log(`\x1B[36m[vm-bench]\x1B[0m speedup: ${m.toFixed(2)}x`),m<1?console.log("\x1B[33m\u26A0\uFE0F VM\uC774 \uB290\uB9BC (\uC0B0\uC220 \uC9D1\uC57D \uCF54\uB4DC\uAC00 \uC544\uB2D0 \uC218 \uC788\uC74C)\x1B[0m"):m>=1.5?console.log("\x1B[32m\u2713 \uBAA9\uD45C \uB2EC\uC131 (1.5\uBC30 \uC774\uC0C1)\x1B[0m"):console.log("\x1B[2m\u25CB 1.0x ~ 1.5x \uBC94\uC704\x1B[0m"),console.log(""),!t)return}if(!t&&!s&&!process.env.FL_NO_HINT&&j.readFileSync(n,"utf-8").includes("server_start")&&process.stderr.write(`\x1B[2m\u{1F4A1} \uAC1C\uBC1C \uC911\uC5D0\uB294: freelang watch ${D.basename(n)}\x1B[0m
1077
+ `),i(),t){console.log(`\x1B[2m watching ${D.basename(n)}... (dev mode: browser auto-reload enabled)\x1B[0m`);let o=0,u=-1;try{let l=j.statSync(n);o=l.mtimeMs,u=l.size}catch{}let f=null;setInterval(()=>{try{let l=j.statSync(n);(l.mtimeMs!==o||l.size!==u)&&(o=l.mtimeMs,u=l.size,f&&clearTimeout(f),f=setTimeout(()=>{console.log(`
1078
+ \x1B[2m\u2500\u2500\u2500 \uBCC0\uACBD \uAC10\uC9C0, \uC7AC\uC2E4\uD589 \u2500\u2500\u2500\x1B[0m`),i()},100))}catch{}},500)}}function gb(r,t){let e=D.resolve(r);j.existsSync(e)||(console.error(`\x1B[31m\uC624\uB958\x1B[0m \uD30C\uC77C\uC744 \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4: ${r}`),process.exit(1));let n=t.indexOf("--samples"),s=n>=0?parseInt(t[n+1],10):void 0,a=j.readFileSync(e,"utf-8");try{let c=W(a),p=H(c),m=new we;m.currentFilePath=e,m.interpret(p)}catch{}if(Ne.size===0){console.log(`\x1B[33m[props]\x1B[0m ${D.basename(e)} \u2014 defprop \uC5C6\uC74C`),console.log('\x1B[2m \uD301: (defprop my-prop {:fn "add" :args [:int :int] :check (fn [$a $b] (= (add $a $b) (add $b $a)))})\x1B[0m');return}console.log(`\x1B[36m[props]\x1B[0m ${D.basename(e)} \u2014 ${Ne.size}\uAC1C property \uC2E4\uD589
1079
+ `);let i;try{let c=W(a),p=H(c);i=new we,i.currentFilePath=e,i.interpret(p)}catch{}let o=0,u=0,f=0;for(let[,c]of Ne){let p=s?{...c,samples:s}:c,m=bs(p,(h,y)=>{let k=i?.context?.variables?.get(h)??i?.context?.variables?.get("$"+h);if(!k)throw new Error(`\uD568\uC218 \uC5C6\uC74C: ${h}`);return i.callFunctionValue(k,y)},(h,y)=>h?i.callFunctionValue(h,y):!0);o+=m.passed,u+=m.failed;let d=m.failed===0,g=d?"\x1B[32m\u2713\x1B[0m":"\x1B[31m\u2716\x1B[0m";if(process.stdout.write(` ${g} \x1B[1m${m.name}\x1B[0m \x1B[2m${m.fn} ${m.passed}/${m.samples} ${m.durationMs}ms\x1B[0m
1080
+ `),!d&&m.firstFailure){let h=m.firstFailure;process.stdout.write(` \x1B[31m\uBC18\uB840\x1B[0m: args=${JSON.stringify(h.args)}`+(h.error?` error=${h.error}`:` result=${JSON.stringify(h.result)}`)+`
1081
+ `),f=1}}let l=u===0;process.stdout.write(`
1082
+ ${l?"\x1B[32m[PROPS PASS]\x1B[0m":"\x1B[31m[PROPS FAIL]\x1B[0m"} ${Ne.size}\uAC1C property \u2014 ${o} passed / ${u} failed
1083
+ `),f&&process.exit(f)}function hb(r){let t=D.resolve(r);j.existsSync(t)||(console.error(`\x1B[31m\uC624\uB958\x1B[0m \uD30C\uC77C\uC744 \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4: ${r}`),process.exit(1));let e=j.readFileSync(t,"utf-8");mb(e,t)||process.exit(1);let{metaMissing:s,effectsWarn:a}=yb(e,t),i=!1;if(s.length>0){i=!0,process.stderr.write(`
1084
+ \x1B[33m[meta-check]\x1B[0m ${D.basename(t)} \u2014 ${s.length}\uAC1C \uD568\uC218\uC5D0 \uBA54\uD0C0 \uC5C6\uC74C
1085
+ `);for(let p of s)process.stderr.write(` \x1B[33m\u26A0\x1B[0m line ${p.line}: \x1B[1m${p.name}\x1B[0m \u2014 :context/:returns \uC5C6\uC74C
1086
+ `);process.stderr.write(`\x1B[2m \uD301: (defn ${s[0].name} [...] {:context "..." :returns "..."} ...)\x1B[0m
1087
+ `)}let o=a.filter(p=>p.isPure),u=a.filter(p=>!p.isPure);if(o.length>0){i=!0,process.stderr.write(`
1088
+ \x1B[31m[pure-violation]\x1B[0m ${D.basename(t)} \u2014 ${o.length}\uAC1C ^pure \uD568\uC218\uC5D0\uC11C side effect \uBC1C\uACAC
1089
+ `);for(let p of o){let m=p.undeclared.map(d=>`:${d}`).join(" ");process.stderr.write(` \x1B[31m\u2716\x1B[0m line ${p.line}: \x1B[1m${p.name}\x1B[0m \u2014 \x1B[31m${m}\x1B[0m (\uC21C\uC218 \uD568\uC218 \uC704\uBC18)
1090
+ `)}process.stderr.write(`\x1B[2m :effects [] \uB610\uB294 ^pure \uC120\uC5B8 \uC2DC side effect \uD638\uCD9C \uBD88\uAC00\x1B[0m
1091
+ `)}if(u.length>0){i=!0,process.stderr.write(`
1092
+ \x1B[33m[effects-check]\x1B[0m ${D.basename(t)} \u2014 ${u.length}\uAC1C \uD568\uC218\uC5D0 \uBBF8\uC120\uC5B8 effect
1093
+ `);for(let p of u){let m=p.undeclared.map(d=>`:${d}`).join(" ");process.stderr.write(` \x1B[33m\u26A0\x1B[0m line ${p.line}: \x1B[1m${p.name}\x1B[0m \u2014 \uBBF8\uC120\uC5B8 effect: \x1B[33m${m}\x1B[0m
1094
+ `)}}i&&process.stderr.write(`
1095
+ `);let{errors:f,warnings:l,fnCount:c}=ap(e);f.length>0||l.length>0?(process.stderr.write(ip([...f,...l],t)+`
1096
+
1097
+ `),f.length>0&&process.exit(1)):c>0&&console.log(`\x1B[36m[type-check]\x1B[0m ${D.basename(t)} \uD0C0\uC785 \uC774\uC0C1 \uC5C6\uC74C (\uD568\uC218 ${c}\uAC1C \uBD84\uC11D)`)}function yb(r,t){let e=[],n=[];try{let o=function(f,l){f&&(f.kind==="sexpr"?(f.op&&l.add(f.op),Array.isArray(f.args)&&f.args.forEach(c=>o(c,l))):f.kind==="block"&&f.fields instanceof Map&&f.fields.forEach(c=>o(c,l)))},u=function(f){for(let l of f)if(l)if(l.kind==="sexpr"&&(l.op==="defn"||l.op==="defun")){let c=0,p=l.args??[],m=!1;p[c]?.kind==="literal"&&String(p[c].value??"").startsWith("^")&&(String(p[c].value)==="^pure"&&(m=!0),c++);let d=p[c],g=d?.kind==="variable"?d.name:d?.kind==="literal"?String(d.value):"?",h=p.slice(c+2),y=h[0],k=null;if(y?.kind==="block"&&y?.type==="Map"&&y.fields instanceof Map&&[...y.fields.keys()].some($=>i.has($))&&(k=y.fields,h=h.slice(1)),!k&&h.length>0&&e.push({name:g,line:l.line??0}),k?.has("effects")||m){let $=[];if(!m&&k?.has("effects")){let _=k.get("effects");if(_?.kind==="block"&&_?.type==="Array"){let S=_.fields?.get("items");Array.isArray(S)&&($=S.map(R=>R?.kind==="literal"?String(R.value).replace(/^:/,""):"?"))}}let M=m||$.length===0,O=new Set($),C=new Set;h.forEach(_=>o(_,C));let P=[];C.forEach(_=>{let S=pi.get(_);S&&!O.has(S)&&P.push(S)}),P.length>0&&n.push({name:g,line:l.line??0,undeclared:[...new Set(P)],isPure:M})}u(h)}else l.kind==="sexpr"&&l.args?u(l.args):l.kind==="block"&&l.fields instanceof Map&&u([...l.fields.values()])},s=W(r),a=H(s),i=new Set(["returns","context","effects","examples"]);u(a)}catch{}return{metaMissing:e,effectsWarn:n}}function bb(r){let t=r.find(s=>!s.startsWith("-")&&s.endsWith(".fl")),e=r.includes("--target")?r[r.indexOf("--target")+1]:"all";t||(console.error("\x1B[31m\uC624\uB958\x1B[0m \uC785\uB825 \uD30C\uC77C\uC744 \uC9C0\uC815\uD558\uC138\uC694: codegen <file.fl>"),process.exit(1));let n=D.resolve(t);j.existsSync(n)||(console.error(`\x1B[31m\uC624\uB958\x1B[0m \uD30C\uC77C\uC744 \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4: ${t}`),process.exit(1));try{let s=j.readFileSync(n,"utf-8"),a=W(s),i=H(a),o=new Zt;for(let u of i)if(u.kind==="block"){let f=u.type;if(["SERVICE","MODEL","CONTROLLER"].includes(f)&&(e==="all"||e==="typescript"&&f!=="MODEL"||e==="sql"&&f==="MODEL")){let l=o.generate([u]);console.log(l),console.log(`
1098
+ `+"\u2500".repeat(80)+`
1099
+ `)}}}catch(s){console.error(`\x1B[31m\uC624\uB958\x1B[0m ${Kn(s,j.readFileSync(n,"utf-8"),n)}`),process.exit(1)}}function kb(r){let t=r.indexOf("-o"),e=r.find(o=>!o.startsWith("-")&&o!==r[t+1]),n=t!==-1?r[t+1]:null,s=r.includes("--esm"),a=r.includes("--runtime");e||(console.error("\x1B[31m\uC624\uB958\x1B[0m \uC785\uB825 \uD30C\uC77C\uC744 \uC9C0\uC815\uD558\uC138\uC694: compile <file.fl> [-o <out.js>]"),process.exit(1));let i=D.resolve(e);j.existsSync(i)||(console.error(`\x1B[31m\uC624\uB958\x1B[0m \uD30C\uC77C\uC744 \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4: ${e}`),process.exit(1));try{let o=j.readFileSync(i,"utf-8"),u=W(o),f=H(u),c=new Zt().generate(f,{module:s?"esm":"commonjs",runtime:a,minify:!1,target:"node"});if(n){let p=D.resolve(n),m=D.dirname(p);m!=="."&&!j.existsSync(m)&&j.mkdirSync(m,{recursive:!0}),j.writeFileSync(p,c,"utf-8"),console.log(`\x1B[32m\u2713\x1B[0m \uCEF4\uD30C\uC77C \uC644\uB8CC ${D.basename(e)} \u2192 ${n}`)}else process.stdout.write(c)}catch(o){console.error(Kn(o,j.readFileSync(i,"utf-8"),i)),process.exit(1)}}function vb(){console.log("FreeLang v11 REPL (\x1B[2m:q / (exit) / (quit) \uC885\uB8CC :help \uB3C4\uC6C0\uB9D0 :reset \uC138\uC158 \uCD08\uAE30\uD654\x1B[0m)"),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");let r=(()=>{try{let i=require("os");return require("path").join(i.homedir(),".fl_history")}catch{return null}})(),t=[];if(r)try{let i=require("fs");i.existsSync(r)&&(t=i.readFileSync(r,"utf8").split(`
1100
+ `).filter(o=>o.trim()).slice(-500).reverse())}catch{}let e=$p.createInterface({input:process.stdin,output:process.stdout,prompt:"\x1B[36mfl>\x1B[0m ",terminal:!0,history:t,historySize:500}),n="",s=new we;function a(i){let o=0,u=!1;for(let f=0;f<i.length;f++){let l=i[f];if(l==='"'){let c=0,p=f-1;for(;p>=0&&i[p]==="\\";)c++,p--;c%2===0&&(u=!u)}u||((l==="("||l==="["||l==="{")&&o++,(l===")"||l==="]"||l==="}")&&o--)}return o}e.prompt(),e.on("line",i=>{let o=i.trim();if((o===":q"||o===":quit"||o===":exit"||o==="(exit)"||o==="(quit)"||o==="exit"||o==="quit")&&(console.log("bye."),e.close(),process.exit(0)),o==="(exit"||o==="(quit"){console.log("\x1B[33m\u{1F4A1} \uC885\uB8CC\uD558\uB824\uBA74: :q \uB610\uB294 (exit) \uC785\uB825\x1B[0m");return}if(o===":help"){console.log([" :q / :quit \uC885\uB8CC"," :clear \uBC84\uD37C \uCD08\uAE30\uD654"," :help \uC774 \uB3C4\uC6C0\uB9D0"," :ls \uC815\uC758\uB41C \uD568\uC218 \uBAA9\uB85D"," :stack callStack \uCD9C\uB825 (\uCD5C\uADFC 20\uAC1C)"," :locals \uD604\uC7AC \uBCC0\uC218 dump"," :debug debugger ON/OFF toggle"," :step step \uBAA8\uB4DC toggle",""," \uC608\uC81C:"," (+ 1 2)",' (println "Hello, World!")',' (let [[$x 42]] (println "x = {$x}"))'," [FUNC add :params [$a $b] :body (+ $a $b)]"," (add 3 5)"].join(`
1101
+ `)),e.prompt();return}if(o===":clear"){n="",console.log(" \uBC84\uD37C \uCD08\uAE30\uD654\uB428."),e.prompt();return}if(o===":reset"){n="",s=new we,console.log(" \uC138\uC158 \uCD08\uAE30\uD654\uB428 (\uBAA8\uB4E0 \uBCC0\uC218/\uD568\uC218 \uC81C\uAC70)."),e.prompt();return}if(o===":ls"){let l=[...s.context.functions.keys()];console.log(l.length===0?"(\uD568\uC218 \uC5C6\uC74C)":l.slice(0,50).join(" ")),l.length>50&&console.log(` ... \uC678 ${l.length-50}\uAC1C`),e.prompt();return}if(o===":stack"){let l=s.callStack??[];if(l.length===0)console.log(" (callStack \uBE44\uC5B4\uC788\uC74C \u2014 \uD638\uCD9C \uC911\uC77C \uB54C\uB9CC \uD45C\uC2DC)");else{let c=l.slice(-20);for(let p=0;p<c.length;p++){let m=c[p].args?`(${c[p].args.join(", ")})`:"";console.log(` #${l.length-c.length+p}: ${c[p].fn}${m} (line ${c[p].line})`)}}e.prompt();return}if(o===":locals"){let l=s.context.variables.snapshot?.()??new Map;if(l.size===0)console.log(" (\uBCC0\uC218 \uC5C6\uC74C)");else{let c=0;for(let[p,m]of l){if(c++>=30){console.log(` ... ${l.size-30}\uAC1C \uB354`);break}let d=typeof m=="function"?"<function>":m?.kind==="function-value"?"<fn-value>":(()=>{try{return JSON.stringify(m)?.slice(0,60)}catch{return"<unserializable>"}})();console.log(` ${p} = ${d}`)}}e.prompt();return}if(o===":debug"){try{let{getGlobalDebugSession:l}=(Br(),_e(Ki)),c=l();c.enabled=!c.enabled,console.log(` debugger: ${c.enabled?"ON":"OFF"}`)}catch(l){console.log(` debug \uBAA8\uB4C8 \uB85C\uB4DC \uC2E4\uD328: ${l.message}`)}e.prompt();return}if(o===":step"){try{let{getGlobalDebugSession:l}=(Br(),_e(Ki)),c=l();c.enabled=!0,c.stepMode=!c.stepMode,console.log(` step \uBAA8\uB4DC: ${c.stepMode?"ON (\uBAA8\uB4E0 \uC904\uC5D0\uC11C break)":"OFF"}`)}catch(l){console.log(` debug \uBAA8\uB4C8 \uB85C\uB4DC \uC2E4\uD328: ${l.message}`)}e.prompt();return}if(o.startsWith(";")){e.prompt();return}if(n+=(n?`
1102
+ `:"")+i,a(n)>0){process.stdout.write("\x1B[2m \u2026\x1B[0m ");return}let f=n.trim();if(n="",!f){e.prompt();return}try{let l=W(f),c=H(l),m=s.interpret(c).lastValue;m!=null&&(typeof m=="object"?console.log("\x1B[33m=>\x1B[0m",JSON.stringify(m,null,2)):console.log("\x1B[33m=>\x1B[0m",String(m)))}catch(l){console.error(Kn(l,f))}if(r&&f)try{require("fs").appendFileSync(r,f.replace(/\n/g," ")+`
1103
+ `)}catch{}e.prompt()}),e.on("close",()=>{process.exit(0)})}function Mp(){try{return ri()}catch{return[]}}function wb(r){let e=Mp().map(o=>({module:o.module,name:o.name,params:o.params,ret:o.returns}));e.length===0&&(console.error(JSON.stringify({error:"stdlib_signatures_missing",hint:"run `npm run build` to regenerate"})),process.exit(2));let n=r.toLowerCase(),s=e.filter(o=>o.name===r),a=e.filter(o=>o.name.toLowerCase().includes(n)&&o.name!==r);if(s.length===0&&a.length===0){let o=e.map(u=>({e:u,d:_b(u.name.toLowerCase(),n)})).filter(u=>u.d<=3).sort((u,f)=>u.d-f.d).slice(0,5);console.log(JSON.stringify({query:r,found:!1,suggestions:o.map(({e:u})=>({name:u.name,module:u.module}))})),process.exit(1)}let i=a.slice(0,20);console.log(JSON.stringify({query:r,found:!0,exact:s.map(o=>({name:o.name,module:o.module,params:o.params,returns:o.ret})),partial:i.map(o=>({name:o.name,module:o.module,params:o.params,returns:o.ret})),partial_truncated:a.length>20?a.length-20:0}))}function _b(r,t){if(r===t)return 0;if(!r.length)return t.length;if(!t.length)return r.length;let e=new Array(t.length+1).fill(0).map((n,s)=>s);for(let n=1;n<=r.length;n++){let s=[n];for(let a=1;a<=t.length;a++)s[a]=r[n-1]===t[a-1]?e[a-1]:Math.min(e[a-1],e[a],s[a-1])+1;for(let a=0;a<=t.length;a++)e[a]=s[a]}return e[t.length]}function Sb(r){if(r.includes("--stdin")){let s="";process.stdin.setEncoding("utf-8"),process.stdin.on("data",a=>{s+=a}),process.stdin.on("end",()=>{try{let a=Dr(s);process.stdout.write(a)}catch(a){console.error(`\x1B[31m\uD3EC\uB9F7 \uC624\uB958\x1B[0m ${a.message}`),process.exit(1)}});return}let t=r.includes("--check"),e=r.filter(s=>!s.startsWith("--"));e.length===0&&(console.error("\x1B[31m\uC624\uB958\x1B[0m \uD30C\uC77C \uACBD\uB85C\uB97C \uC9C0\uC815\uD558\uC138\uC694"),process.exit(1));let n=!1;for(let s of e){let a=D.resolve(s);j.existsSync(a)||(console.error(`\x1B[31m\uC624\uB958\x1B[0m \uD30C\uC77C\uC744 \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4: ${s}`),process.exit(1));let i=j.readFileSync(a,"utf-8"),o;try{o=Dr(i)}catch(u){console.error(`\x1B[31m\uD3EC\uB9F7 \uC624\uB958\x1B[0m ${D.basename(a)}: ${u.message}`),process.exit(1)}t?i!==o?(console.log(`\x1B[33m\uBCC0\uACBD \uD544\uC694\x1B[0m ${D.basename(a)}`),n=!0):console.log(`\x1B[32m\uC774\uBBF8 \uD3EC\uB9F7\uB428\x1B[0m ${D.basename(a)}`):i!==o?(j.writeFileSync(a,o,"utf-8"),console.log(`\x1B[32m\uD3EC\uB9F7 \uC644\uB8CC\x1B[0m ${D.basename(a)}`)):console.log(`\x1B[2m\uBCC0\uACBD \uC5C6\uC74C\x1B[0m ${D.basename(a)}`)}t&&n&&process.exit(1)}function xb(r,t){let e=D.resolve(r);j.existsSync(e)||(console.error(`\x1B[31m\uC624\uB958\x1B[0m \uD30C\uC77C\uC744 \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4: ${r}`),process.exit(1));let n=new Wn;n.enabled=!0,n.stepMode=t,Hi(n),console.log(`\x1B[35m[FreeLang Debugger]\x1B[0m ${D.basename(e)}${t?" (step mode)":""}`),console.log("\x1B[2m (break!) \uC704\uCE58\uC5D0\uC11C \uC911\uB2E8\uC810 \uBC1C\uC0DD\x1B[0m"),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");try{let s=j.readFileSync(e,"utf-8"),a=W(s),i=H(a),o=new we;o.currentFilePath=e,o.debugSession=n;let u=o.interpret(i);u.lastValue!==null&&u.lastValue!==void 0&&(typeof u.lastValue=="object"?console.log(JSON.stringify(u.lastValue,null,2)):console.log(String(u.lastValue))),console.log(`
1104
+ \x1B[35m[\uB514\uBC84\uADF8 \uC644\uB8CC]\x1B[0m \uC911\uB2E8\uC810 ${n.breakLog.length}\uD68C \uB3C4\uB2EC`)}catch(s){console.error(Kn(s,void 0,e)),process.exit(1)}}async function Ab(r){let t=r.includes("--no-fail-fast"),e=r.filter(f=>!f.startsWith("--")),n;if(e.length>0)n=e.map(f=>D.resolve(f)).filter(f=>j.existsSync(f)),n.length===0&&(console.error("\x1B[31m\uC624\uB958\x1B[0m \uC9C0\uC815\uD55C \uD30C\uC77C\uC744 \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4"),process.exit(1));else{let f=process.cwd();n=j.readdirSync(f).filter(l=>l.endsWith(".fl")).map(l=>D.join(f,l))}console.log(`\x1B[36m[FreeLang CI]\x1B[0m \uD30C\uC77C ${n.length}\uAC1C fail-fast=${!t}`),console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");let a=await wp(n,{failFast:!t}).run();console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");let i=a.steps.length,o=a.steps.filter(f=>f.passed&&!f.skipped).length,u=a.steps.filter(f=>f.skipped).length;a.passed?console.log(`\x1B[32m[CI PASS]\x1B[0m ${o}/${i} steps (${a.totalMs}ms)`):(console.log(`\x1B[31m[CI FAIL]\x1B[0m ${o}/${i} steps (${a.totalMs}ms, ${u} skipped)`),process.exit(1))}function $b(r){let t=r.indexOf("--dir");if(t!==-1){let l=r[t+1];l||(console.error("\x1B[31m\uC624\uB958\x1B[0m --dir \uB4A4\uC5D0 \uB514\uB809\uD1A0\uB9AC \uACBD\uB85C\uB97C \uC9C0\uC815\uD558\uC138\uC694"),process.exit(1));let c=D.resolve(l);(!j.existsSync(c)||!j.statSync(c).isDirectory())&&(console.error(`\x1B[31m\uC624\uB958\x1B[0m \uB514\uB809\uD1A0\uB9AC\uB97C \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4: ${l}`),process.exit(1));let p=j.readdirSync(c).filter(y=>y.endsWith(".fl")).map(y=>D.join(c,y));if(p.length===0){console.error(`\x1B[33m\uACBD\uACE0\x1B[0m .fl \uD30C\uC77C\uC774 \uC5C6\uC2B5\uB2C8\uB2E4: ${l}`);return}let m=[];for(let y of p){let k=j.readFileSync(y,"utf-8");m.push(...ua(k))}let d=D.basename(c)+" API \uBB38\uC11C",g=eo(m,d),h=r.indexOf("-o");if(h!==-1&&r[h+1]){let y=D.resolve(r[h+1]);j.writeFileSync(y,g,"utf-8"),console.log(`\x1B[32m\uBB38\uC11C \uC800\uC7A5\uB428\x1B[0m ${y} (${m.length}\uAC1C \uD56D\uBAA9)`)}else process.stdout.write(g);return}let e=r.filter(l=>!l.startsWith("-"));e.length===0&&(console.error("\x1B[31m\uC624\uB958\x1B[0m \uD30C\uC77C \uACBD\uB85C\uB97C \uC9C0\uC815\uD558\uC138\uC694"),process.exit(1));let n=e[0],s=D.resolve(n);j.existsSync(s)||(console.error(`\x1B[31m\uC624\uB958\x1B[0m \uD30C\uC77C\uC744 \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4: ${n}`),process.exit(1));let a=j.readFileSync(s,"utf-8"),i=ua(a),o=D.basename(s,".fl")+" API \uBB38\uC11C",u=eo(i,o),f=r.indexOf("-o");if(f!==-1&&r[f+1]){let l=D.resolve(r[f+1]);j.writeFileSync(l,u,"utf-8"),console.log(`\x1B[32m\uBB38\uC11C \uC800\uC7A5\uB428\x1B[0m ${l} (${i.length}\uAC1C \uD56D\uBAA9)`)}else process.stdout.write(u)}function Eb(r){let t=r.includes("--oci");if(r.includes("--static")){let p=function(S,R){let E=D.join(S,"generate-static-params.fl");if(!j.existsSync(E))return[];try{let T=D.resolve(process.cwd(),"bootstrap.js"),B=j.existsSync(T)?T:D.resolve(__dirname,"bootstrap.js"),{execSync:U}=require("child_process"),w=U(`node "${B}" run "${E}"`,{encoding:"utf-8",stdio:["ignore","pipe","pipe"]}).match(/\[[\s\S]*\]/);if(!w)return[];let x=JSON.parse(w[0]);return Array.isArray(x)?x:[]}catch(T){return console.log(`build.params_error dir=${S} err=${(T.message||String(T)).split(`
1105
+ `)[0]}`),[]}},m=function(S,R){let E=j.readdirSync(S,{withFileTypes:!0});for(let T of E){let B=D.join(S,T.name);if(T.isDirectory()){if(T.name.startsWith("[")&&T.name.endsWith("]")){let U=T.name.slice(1,-1),b=p(B,U),w=D.join(B,"page.fl");if(b.length===0){console.log(`build.skip reason=dynamic_no_params path=/${D.relative(f,B)} param=${U}`);continue}if(!j.existsSync(w)){console.log(`build.skip reason=dynamic_no_page path=/${D.relative(f,B)}`);continue}for(let x of b){let N=x&&typeof x=="object"?x[U]:null;N&&c.push({filePath:w,route:R+"/"+String(N)})}continue}if(T.name==="api")continue;m(B,R+"/"+T.name)}else T.name==="page.fl"&&c.push({filePath:B,route:R||"/"})}},n=r.indexOf("--app"),s=r.indexOf("--out"),a=r.indexOf("--port"),i=n!==-1?r[n+1]:"app",o=s!==-1?r[s+1]:"dist",u=a!==-1?parseInt(r[a+1],10):43099,f=D.resolve(i),l=D.resolve(o);j.existsSync(f)||(console.error(`build.error event=app_not_found path=${i}`),process.exit(1)),console.log(`build.start app=${i} out=${o} port=${u}`),j.mkdirSync(l,{recursive:!0});let c=[];m(f,"");let d=D.join(f,"not-found.fl");if(j.existsSync(d)&&c.push({filePath:d,route:"/__404__"}),c.length===0){console.log(`build.error event=no_pages app=${i}`);return}let{spawn:g}=require("child_process"),h=require("http"),y=D.resolve(process.cwd(),"bootstrap.js"),k=j.existsSync(y)?y:D.resolve(__dirname,"bootstrap.js"),v=g("node",[k,"serve","--app",f,"--port",String(u)],{stdio:["ignore","pipe","pipe"]}),$=async()=>{for(let S=0;S<30;S++){if(await new Promise(E=>{let T=h.get({host:"localhost",port:u,path:"/",timeout:500},B=>{B.destroy(),E(!0)});T.on("error",()=>E(!1)),T.on("timeout",()=>{T.destroy(),E(!1)})}))return!0;await new Promise(E=>setTimeout(E,200))}return!1},M=S=>new Promise((R,E)=>{let T=h.get({host:"localhost",port:u,path:S,timeout:5e3},B=>{let U="";B.on("data",b=>{U+=b.toString()}),B.on("end",()=>{B.statusCode&&B.statusCode>=400?E(new Error(`HTTP ${B.statusCode}`)):R(U)})});T.on("error",E),T.on("timeout",()=>{T.destroy(),E(new Error("timeout"))})}),O=S=>{try{let{execSync:R}=require("child_process"),E=R(`node "${k}" run "${S.filePath}"`,{encoding:"utf-8",stdio:["ignore","pipe","pipe"]}),T=E.match(/<!DOCTYPE html[\s\S]*?<\/html>/i)||E.match(/<html[\s\S]*?<\/html>/i);return T?T[0]:null}catch{return null}},C=S=>{if(!S)return!1;let R=S.trim();return!(R.length<50||R.startsWith("Internal Server Error"))},P=r.indexOf("--concurrency"),_=Math.max(1,P!==-1?parseInt(r[P+1]||"8",10):8);(async()=>{let S=await $(),R=Date.now(),E=0,T=0,B=async b=>{let w=null;if(S)try{let x=await M(b.route);C(x)&&(w=x)}catch{}if(!w){let x=O(b);C(x)&&(w=x)}if(w){let x=b.route==="/__404__"?D.join(l,"404.html"):D.join(l,b.route==="/"?"index.html":b.route.slice(1)+"/index.html");j.mkdirSync(D.dirname(x),{recursive:!0}),j.writeFileSync(x,w),console.log(`build.page route=${b.route==="/__404__"?"/404":b.route} ok=true file=${D.relative(process.cwd(),x)} bytes=${w.length}`),E++}else console.log(`build.page route=${b.route} ok=false`),T++};for(let b=0;b<c.length;b+=_){let w=c.slice(b,b+_);await Promise.all(w.map(B))}v.kill();let U=Date.now()-R;console.log(`build.done ok=${E} fail=${T} out=${o} ms=${U} concurrency=${_}`),T>0&&process.exit(1),process.exit(0)})();return}if(t){let n=r.indexOf("--oci")+1,s=r[n],a=r.indexOf("--tag"),i=a!==-1?r[a+1]:"my-app:latest",o=r.indexOf("--registry"),u=o!==-1?r[o+1]:void 0;s||(console.error("\x1B[31m\uC624\uB958\x1B[0m app \uD30C\uC77C\uC744 \uC9C0\uC815\uD558\uC138\uC694: fl build --oci <app.fl> --tag <tag>"),process.exit(1));let f=D.resolve(s);j.existsSync(f)||(console.error(`\x1B[31m\uC624\uB958\x1B[0m \uD30C\uC77C\uC744 \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4: ${s}`),process.exit(1)),console.log(`\x1B[36m[OCI Build]\x1B[0m ${D.basename(s)} \u2192 ${i}`);let l=D.resolve(__dirname,"../vpm/v9-oci.fl");j.existsSync(l)||(console.error("\x1B[31m\uC624\uB958\x1B[0m v9-oci.fl\uC744 \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4"),process.exit(1));let{execSync:c}=require("child_process");try{let p=u?`node ${D.resolve(__dirname,"../src/cli.js")} run ${l} build ${s} ${i} ${u}`:`node ${D.resolve(__dirname,"../src/cli.js")} run ${l} build ${s} ${i}`;console.log(`\x1B[2m Command: ${p}\x1B[0m`),c(p,{stdio:"inherit"}),console.log(`\x1B[32m[OK]\x1B[0m OCI \uBE4C\uB4DC \uC644\uB8CC: ${i}`)}catch(p){console.error(`\x1B[31m[Error]\x1B[0m OCI \uBE4C\uB4DC \uC2E4\uD328: ${p.message}`),process.exit(1)}}else console.error("\x1B[31m\uC624\uB958\x1B[0m --oci \uD50C\uB798\uADF8\uB97C \uC9C0\uC815\uD558\uC138\uC694"),console.log(`
1106
+ \uC0AC\uC6A9\uBC95:
1107
+ fl build --oci <app.fl> --tag <tag> [--registry <url>]`),process.exit(1)}function Mb(r){let t=r[0];if(t==="start"){let e=r.indexOf("--port"),n=e!==-1&&r[e+1]?parseInt(r[e+1],10):4873;(isNaN(n)||n<1024||n>65535)&&(console.error(`\x1B[31m\uC624\uB958\x1B[0m \uC720\uD6A8\uD558\uC9C0 \uC54A\uC740 \uD3EC\uD2B8: ${n}`),process.exit(1)),console.log(`\x1B[36m[Registry]\x1B[0m v9 \uD328\uD0A4\uC9C0 \uB808\uC9C0\uC2A4\uD2B8\uB9AC \uC2DC\uC791 (\uD3EC\uD2B8 ${n})`),console.log(`\x1B[36m[Registry]\x1B[0m http://localhost:${n}/`);let s=D.resolve(__dirname,"../vpm/registry-server.fl");j.existsSync(s)||(console.error(`\x1B[31m\uC624\uB958\x1B[0m registry-server.fl\uC744 \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4: ${s}`),process.exit(1));let{execSync:a}=require("child_process");try{process.env.REGISTRY_PORT=String(n),a(`node ${D.resolve(__dirname,"../src/cli.js")} run ${s}`,{stdio:"inherit",env:{...process.env,REGISTRY_PORT:String(n)}})}catch(i){console.error(`\x1B[31m\uB808\uC9C0\uC2A4\uD2B8\uB9AC \uC2DC\uC791 \uC624\uB958:\x1B[0m ${i.message}`),process.exit(1)}}else if(t==="status"){let e=r.indexOf("--port"),n=e!==-1&&r[e+1]?parseInt(r[e+1],10):4873;try{let a=require("http").get(`http://localhost:${n}/-/all`,i=>{i.statusCode===200?(console.log(`\x1B[32m[OK]\x1B[0m \uB808\uC9C0\uC2A4\uD2B8\uB9AC \uC815\uC0C1 \uC6B4\uC601 \uC911 (\uD3EC\uD2B8 ${n})`),process.exit(0)):(console.error(`\x1B[31m\uC624\uB958\x1B[0m \uB808\uC9C0\uC2A4\uD2B8\uB9AC \uC751\uB2F5 \uC774\uC0C1 (\uC0C1\uD0DC: ${i.statusCode})`),process.exit(1))});a.on("error",i=>{console.error(`\x1B[31m\uC624\uB958\x1B[0m \uB808\uC9C0\uC2A4\uD2B8\uB9AC \uC5F0\uACB0 \uC2E4\uD328: ${i.message}`),process.exit(1)}),a.setTimeout(5e3,()=>{a.destroy(),console.error("\x1B[31m\uC624\uB958\x1B[0m \uB808\uC9C0\uC2A4\uD2B8\uB9AC \uD0C0\uC784\uC544\uC6C3"),process.exit(1)})}catch(s){console.error(`\x1B[31m\uC624\uB958\x1B[0m ${s.message}`),process.exit(1)}}else console.error(`\x1B[31m\uC54C \uC218 \uC5C6\uB294 \uC11C\uBE0C\uCEE4\uB9E8\uB4DC:\x1B[0m registry ${t}`),console.log(`
1108
+ \uC0AC\uC6A9\uBC95:
1109
+ fl registry start [--port 4873]
1110
+ fl registry status [--port 4873]`),process.exit(1)}function Rb(r){let t=r[0];t||(console.error("\x1B[31m\uC624\uB958\x1B[0m \uD50C\uB7EC\uADF8\uC778 \uC774\uB984\uC744 \uC9C0\uC815\uD558\uC138\uC694: install <plugin-name>"),process.exit(1));let e=require("os").homedir(),n=D.resolve(e,".fl","plugins");j.existsSync(n)||(j.mkdirSync(n,{recursive:!0}),console.log(`\x1B[36m[Y5]\x1B[0m \uD50C\uB7EC\uADF8\uC778 \uB514\uB809\uD1A0\uB9AC \uC0DD\uC131: ${n}`));let s=D.resolve(process.cwd(),"plugins",t+".fl"),a=D.resolve(process.cwd(),"self/stdlib",t+".fl"),i=D.resolve(n,t+".fl"),o=null;j.existsSync(s)?(o=s,console.log(`\x1B[36m[Y5]\x1B[0m \uB85C\uCEEC \uD50C\uB7EC\uADF8\uC778 \uCC3E\uC74C: ${s}`)):j.existsSync(a)?(o=a,console.log(`\x1B[36m[Y5]\x1B[0m \uB0B4\uC7A5 stdlib \uD50C\uB7EC\uADF8\uC778 \uCC3E\uC74C: ${a}`)):(console.error(`\x1B[31m\uC624\uB958\x1B[0m \uD50C\uB7EC\uADF8\uC778\uC744 \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4: ${t}`),console.log(" \uC2DC\uB3C4\uD55C \uACBD\uB85C:"),console.log(` - ${s}`),console.log(` - ${a}`),process.exit(1));try{let u=j.readFileSync(o,"utf-8");j.writeFileSync(i,u,"utf-8"),console.log(`\x1B[32m\u2713\x1B[0m \uD50C\uB7EC\uADF8\uC778 \uC124\uCE58 \uC644\uB8CC: ${i}`),console.log(`\x1B[2m \uC0AC\uC6A9: (use ${t})\x1B[0m`)}catch(u){console.error(`\x1B[31m\uC624\uB958\x1B[0m \uC124\uCE58 \uC2E4\uD328: ${u.message}`),process.exit(1)}}function Tb(r){let t=r[0];t||(console.error("\x1B[31m\uC624\uB958\x1B[0m \uD50C\uB7EC\uADF8\uC778 \uD30C\uC77C\uC744 \uC9C0\uC815\uD558\uC138\uC694: publish <plugin-file.fl>"),process.exit(1)),j.existsSync(t)||(console.error(`\x1B[31m\uC624\uB958\x1B[0m \uD30C\uC77C\uC744 \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4: ${t}`),process.exit(1));let e=j.readFileSync(t,"utf-8"),n=e.match(/^;; plugin:\s*(.+)$/m),s=e.match(/^;; version:\s*(.+)$/m);n||(console.error("\x1B[31m\uC624\uB958\x1B[0m \uD50C\uB7EC\uADF8\uC778 \uBA54\uD0C0 \uBE14\uB85D\uC774 \uC5C6\uC2B5\uB2C8\uB2E4. \uD30C\uC77C \uC0C1\uB2E8\uC5D0 \uB2E4\uC74C\uC744 \uCD94\uAC00\uD558\uC138\uC694:"),console.log(" ;; plugin: <name>"),console.log(" ;; version: 1.0.0"),console.log(" ;; depends:"),process.exit(1));let a=n[1].trim(),i=s?s[1].trim():"1.0.0";console.log(`\x1B[36m[Y5]\x1B[0m \uBC30\uD3EC \uC911: ${a} (v${i})`);try{let{execSync:o}=require("child_process"),u=D.resolve("/tmp",`fl-publish-${Date.now()}`);j.mkdirSync(u,{recursive:!0}),o("git clone https://gogs.dclub.kr/kim/fl-plugins.git .",{cwd:u,stdio:"pipe"}),j.copyFileSync(t,D.resolve(u,`${a}.fl`)),o(`git add ${a}.fl`,{cwd:u,stdio:"pipe"}),o(`git -c user.name="FreeLang CLI" -c user.email="cli@freelang.dev" commit -m "Add plugin: ${a} v${i}"`,{cwd:u,stdio:"pipe"}),o("git push origin master",{cwd:u,stdio:"pipe"}),console.log(`\x1B[32m\u2713\x1B[0m \uD50C\uB7EC\uADF8\uC778 '${a}' \uAC8C\uC2DC \uC644\uB8CC`),console.log("\x1B[2m \uC800\uC7A5\uC18C: https://gogs.dclub.kr/kim/fl-plugins\x1B[0m"),j.rmSync(u,{recursive:!0,force:!0})}catch(o){console.error(`\x1B[31m\uC624\uB958\x1B[0m \uBC30\uD3EC \uC2E4\uD328: ${o.message}`),process.exit(1)}}function Cb(r){let t="app",e=null,n="ssr",s=0;for(let o=0;o<r.length;o++)if(r[o]==="--app"&&r[o+1])t=r[++o];else if(r[o]==="--port"&&r[o+1])e=parseInt(r[++o],10);else if(r[o]==="--mode"&&r[o+1]){let u=r[++o];["ssr","isr","ssg"].includes(u)&&(n=u)}else r[o].startsWith("--")||(s===0&&(t=r[o]),s++);if(e===null)if(process.env.PORT)e=parseInt(process.env.PORT,10);else{try{let o=require("fs"),f=require("path").join(process.cwd(),"fl.config.json");if(o.existsSync(f)){let l=JSON.parse(o.readFileSync(f,"utf-8"));l.port&&(e=l.port)}}catch{}e===null&&(e=3e3)}let a=new Hr({appDir:t,port:e,renderMode:n}),i=new we;a.setInterpreter(i),a.start().then(o=>{console.log(o),setInterval(()=>{},1e4).unref()}).catch(o=>{console.error(`\x1B[31m\uC11C\uBC84 \uC624\uB958\x1B[0m ${o.message}`),process.exit(1)})}var tt={bold:r=>`\x1B[1m${r}\x1B[0m`,cyan:r=>`\x1B[36m${r}\x1B[0m`,green:r=>`\x1B[32m${r}\x1B[0m`,dim:r=>`\x1B[2m${r}\x1B[0m`,red:r=>`\x1B[31m${r}\x1B[0m`,yellow:r=>`\x1B[33m${r}\x1B[0m`},Rp="11.1.1-dev";function sn(r){let t=tt.bold,e=tt.cyan,n=tt.green,s=tt.dim;if(console.log(["",`${t("FreeLang")} ${e("v"+Rp)} ${s("AI-Native Lisp \xB7 Self-Hosting \xB7 500+ stdlib")}`,"",`${t("\uC0AC\uC6A9\uBC95:")} freelang <\uCEE4\uB9E8\uB4DC> [\uC635\uC158]`,"",`${e("\u2500\u2500 \uC2E4\uD589 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")}`,` ${n("run")} <file.fl> [-- args...] \uD30C\uC77C \uC2E4\uD589`,` ${n("run")} <file.fl> --watch \uC800\uC7A5 \uC2DC \uC790\uB3D9 \uC7AC\uC2E4\uD589`,` ${n("repl")} \uB300\uD654\uD615 REPL`,` ${n("check")} <file.fl> \uBB38\uBC95 \uAC80\uC0AC (\uC2E4\uD589 \uC5C6\uC74C)`,"",`${e("\u2500\u2500 \uAC1C\uBC1C \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")}`,` ${n("watch")} <file.fl> \uD30C\uC77C \uBCC0\uACBD \uAC10\uC9C0 \uC7AC\uC2E4\uD589`,` ${n("debug")} <file.fl> \uB514\uBC84\uADF8 \uBAA8\uB4DC (break! \uC9C0\uC6D0)`,` ${n("debug")} <file.fl> --step \uC2A4\uD15D \uBAA8\uB4DC`,` ${n("fmt")} <file.fl> \uCF54\uB4DC \uD3EC\uB9F7 (\uC778\uD50C\uB808\uC774\uC2A4)`,` ${n("fmt")} --check <file.fl> \uD3EC\uB9F7 \uAC80\uC0AC (exit 1 if dirty)`,` ${n("fmt")} --stdin stdin \u2192 stdout \uD3EC\uB9F7`,"",`${e("\u2500\u2500 \uBB38\uC11C / \uD0D0\uC0C9 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")}`,` ${n("ls-fns")} [\uD0A4\uC6CC\uB4DC] stdlib \uD568\uC218 \uBAA9\uB85D (\uD0A4\uC6CC\uB4DC \uD544\uD130)`,` ${n("fn-doc")} <\uC774\uB984> \uD568\uC218 \uC2DC\uADF8\uB2C8\uCC98 + \uC124\uBA85`,` ${n("doc")} <file.fl> [-o out.md] Markdown \uBB38\uC11C \uC0DD\uC131`,` ${n("doc")} --dir <dir> \uB514\uB809\uD1A0\uB9AC \uD1B5\uD569 \uBB38\uC11C\uD654`,"",`${e("\u2500\u2500 \uBE4C\uB4DC / \uBC30\uD3EC \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")}`,` ${n("compile")} <file.fl> [-o out.js] JS\uB85C \uCEF4\uD30C\uC77C (AOT)`,` ${n("build")} --oci <app.fl> --tag <tag> OCI \uC774\uBBF8\uC9C0 \uBE4C\uB4DC`,` ${n("serve")} [--port 3000] \uC6F9 \uC11C\uBC84 \uC2DC\uC791`,` ${n("ci")} [file.fl] CI \uAC80\uC0AC \uC2E4\uD589`,"",`${e("\u2500\u2500 \uD504\uB85C\uC138\uC2A4 \uAD00\uB9AC \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")}`,` ${n("ps")} \uC2E4\uD589 \uC911\uC778 fl \uD504\uB85C\uC138\uC2A4 \uBAA9\uB85D`,` ${n("stop")} [file.fl] \uD504\uB85C\uC138\uC2A4 \uC885\uB8CC (\uC5C6\uC73C\uBA74 \uC804\uCCB4)`,"",`${e("\u2500\u2500 \uC5D0\uB7EC \uBD84\uC11D \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")}`,` ${n("errors")} [N] \uBBF8\uBC1C\uACAC \uD568\uC218 TOP N \uBD84\uC11D (\uAE30\uBCF8 20)`,` ${n("errors-clear")} \uC5D0\uB7EC \uB85C\uADF8 \uCD08\uAE30\uD654`,"",`${e("\u2500\u2500 \uAE30\uD0C0 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500")}`,` ${n("--version")} / ${n("-v")} \uBC84\uC804 \uCD9C\uB825`,` ${n("--help")} / ${n("-h")} \uC774 \uB3C4\uC6C0\uB9D0`,"",`${t("\uC608\uC81C:")}`," freelang run app.fl"," freelang run app.fl --watch"," freelang run app.fl -- arg1 arg2"," freelang repl"," freelang check app.fl"," freelang ls-fns http"," freelang fn-doc json_parse"," freelang compile app.fl -o app.js"," freelang ps"," freelang stop app.fl"," freelang errors",""].join(`
1111
+ `)),r){let i=["run","repl","check","watch","debug","fmt","ls-fns","fn-doc","doc","compile","build","serve","ci","version","help"].find(o=>o.startsWith(r[0])||Math.abs(o.length-r.length)<=2&&[...r].filter((u,f)=>o[f]===u).length>=Math.min(o.length,r.length)-2);console.error(`${tt.red("\uC624\uB958")} \uC54C \uC218 \uC5C6\uB294 \uCEE4\uB9E8\uB4DC: ${tt.bold(r)}${i?`
1112
+ \uD639\uC2DC ${tt.green("freelang "+i)} ?`:""}`),process.exit(1)}}function Gn(r){let t=tt.green,e=tt.dim,n=tt.bold,a={run:[`${n("freelang run")} \u2014 \uD30C\uC77C \uC2E4\uD589`,""," freelang run <file.fl> \uC2E4\uD589"," freelang run <file.fl> --watch \uC800\uC7A5 \uC2DC \uC790\uB3D9 \uC7AC\uC2E4\uD589"," freelang run <file.fl> -- a b \uC2A4\uD06C\uB9BD\uD2B8\uC5D0 \uC778\uC790 \uC804\uB2EC ($__argv__)","",`${e("\uC608\uC81C:")}`," freelang run app.fl"," freelang run server.fl --watch"," freelang run cli.fl -- input.txt"],repl:[`${n("freelang repl")} \u2014 \uB300\uD654\uD615 REPL`,""," (+ 1 2) \uD45C\uD604\uC2DD \uD3C9\uAC00"," (defn f [x] ...) \uD568\uC218 \uC815\uC758 (\uC138\uC158 \uC720\uC9C0)"," :stack \uCF5C \uC2A4\uD0DD \uCD9C\uB825"," :env \uBC14\uC778\uB529 \uBAA9\uB85D"," :exit / Ctrl+D \uC885\uB8CC"],check:[`${n("freelang check")} \u2014 \uBB38\uBC95 \uAC80\uC0AC (\uC2E4\uD589 \uC5C6\uC74C)`,""," freelang check <file.fl>",""," \uD30C\uC2F1 \uC624\uB958 \uBC1C\uC0DD \uC2DC \uB77C\uC778:\uCEEC\uB7FC + \uAD04\uD638 \uD78C\uD2B8 \uD45C\uC2DC"],fmt:[`${n("freelang fmt")} \u2014 \uCF54\uB4DC \uD3EC\uB9F7`,""," freelang fmt <file.fl> \uC778\uD50C\uB808\uC774\uC2A4 \uD3EC\uB9F7"," freelang fmt --check <file.fl> \uD3EC\uB9F7 \uD544\uC694 \uC5EC\uBD80 \uAC80\uC0AC (exit 1)"," freelang fmt --stdin stdin \u2192 stdout","",`${e("CI \uD65C\uC6A9:")}`," freelang fmt --check src/*.fl"],compile:[`${n("freelang compile")} \u2014 JS\uB85C AOT \uCEF4\uD30C\uC77C`,""," freelang compile <file.fl> \u2192 file.fl.out.js"," freelang compile <file.fl> -o app.js \u2192 app.js",""," \uC0DD\uC131\uB41C .js\uB294 Node.js / Bun\uC73C\uB85C \uC9C1\uC811 \uC2E4\uD589 \uAC00\uB2A5"," \uC2E4\uD589 \uC2DC FreeLang \uBD88\uD544\uC694 (\uB3C5\uB9BD \uBC30\uD3EC)"],"ls-fns":[`${n("freelang ls-fns")} \u2014 stdlib \uD568\uC218 \uD0D0\uC0C9`,""," freelang ls-fns \uC804\uCCB4 \uBAA9\uB85D (500+)",' freelang ls-fns http "http" \uD3EC\uD568 \uD568\uC218\uB9CC'," freelang ls-fns json json \uAD00\uB828"],"fn-doc":[`${n("freelang fn-doc")} \u2014 \uD568\uC218 \uC0C1\uC138 \uBB38\uC11C`,""," freelang fn-doc json_parse"," freelang fn-doc str_split"]}[r];a?console.log(`
1113
+ `+a.join(`
1114
+ `)+`
1115
+ `):sn()}var J=process.argv.slice(2),oo=J[0];switch(oo){case"run":{if(J[1]==="--help"||J[1]==="-h"){Gn("run");break}let r=J[1];r||(Gn("run"),process.exit(1));let t=J.includes("--watch")||J.includes("-w"),e=J.indexOf("--"),n=e>=0?J.slice(e+1):J.slice(2).filter(s=>s!=="--watch"&&s!=="-w");db(r,t,n);break}case"check":{if(J[1]==="--help"||J[1]==="-h"){Gn("check");break}let r=J[1];r||(Gn("check"),process.exit(1)),hb(r);break}case"compile":{if(J[1]==="--help"||J[1]==="-h"){Gn("compile");break}J.length<2&&(Gn("compile"),process.exit(1)),kb(J.slice(1));break}case"codegen":{J.length<2&&(sn(),process.exit(1)),bb(J.slice(1));break}case"fmt":{Sb(J.slice(1));break}case"repl":vb();break;case"fn-doc":case"fl-doc":{let r=J[1];r||(console.error("Usage: freelang fn-doc <name>"),console.error(" (name can be exact or partial)"),process.exit(1)),wb(r);break}case"ls-fns":case"ls-fn":{let r=J[1]??"",t=Mp();t.length===0&&(console.error("\uD568\uC218 \uBAA9\uB85D\uC744 \uBD88\uB7EC\uC62C \uC218 \uC5C6\uC2B5\uB2C8\uB2E4. npm run build \uC2E4\uD589 \uD6C4 \uC7AC\uC2DC\uB3C4\uD558\uC138\uC694."),process.exit(1));let e=r.toLowerCase(),n=e?t.filter(o=>o.name.toLowerCase().includes(e)||o.module.toLowerCase().includes(e)):t,s=new Map;for(let o of n)s.has(o.module)||s.set(o.module,[]),s.get(o.module).push(o);let a=n.length,i=e?`\x1B[36m[ls-fns]\x1B[0m "${e}" \uD3EC\uD568 \u2014 ${a}\uAC1C
1116
+ `:`\x1B[36m[ls-fns]\x1B[0m \uC804\uCCB4 ${a}\uAC1C \uD568\uC218
1117
+ `;process.stdout.write(i),s.forEach((o,u)=>{process.stdout.write(`
1118
+ \x1B[33m${u}\x1B[0m (${o.length})
1119
+ `);for(let f of o){let l=f.params?` \x1B[2m${f.params}\x1B[0m`:"",c=f.returns?` \u2192 \x1B[2m${f.returns}\x1B[0m`:"";process.stdout.write(` ${f.name}${l}${c}
1120
+ `)}}),process.stdout.write(`
1121
+ \x1B[2m\u{1F4A1} freelang fn-doc <\uC774\uB984> \uC73C\uB85C \uC790\uC138\uD55C \uC124\uBA85\uC744 \uBCFC \uC218 \uC788\uC2B5\uB2C8\uB2E4\x1B[0m
1122
+ `);break}case"debug":{let r=J[1];r||(sn(),process.exit(1));let t=J.includes("--step");xb(r,t);break}case"watch":{let r=J[1];r||(sn(),process.exit(1));let t=J.includes("--no-clear");console.log(`\x1B[36m[Watch Mode]\x1B[0m ${D.basename(r)} \u2014 \uBCC0\uACBD \uAC10\uC9C0 \uC2DC \uC790\uB3D9 \uC7AC\uC2E4\uD589`),cp(r,{clearConsole:!t,debounceMs:300,onError:(e,n)=>{console.error(`\x1B[31m[ERROR]\x1B[0m ${D.basename(e)}: ${n.message}`)}});break}case"props":case"prop":{let r=J[1];r||(console.error("Usage: freelang props <file.fl> [--samples N]"),process.exit(1)),gb(r,J.slice(2));break}case"ci":{Ab(J.slice(1)).catch(r=>{console.error(`\x1B[31m[CI \uC624\uB958]\x1B[0m ${r.message}`),process.exit(1)});break}case"doc":{$b(J.slice(1));break}case"build":{Eb(J.slice(1));break}case"registry":{Mb(J.slice(1));break}case"install":{Rb(J.slice(1));break}case"publish":{Tb(J.slice(1));break}case"serve":{Cb(J.slice(1));break}case"errors":{let r=process.env.FL_ERROR_LOG??"/tmp/fl-unknown-functions.jsonl",t=parseInt(J[1]??"20",10);try{let e=j.readFileSync(r,"utf-8").trim();if(!e){console.log("(\uAE30\uB85D\uB41C \uC5D0\uB7EC \uC5C6\uC74C)");break}let n={},s={};for(let i of e.split(`
1123
+ `))try{let o=JSON.parse(i);n[o.name]=(n[o.name]??0)+1,!s[o.name]&&o.file&&(s[o.name]=`${o.file}:${o.line??"?"}`)}catch{}let a=Object.entries(n).sort((i,o)=>o[1]-i[1]).slice(0,t);console.log(`
1124
+ \u{1F4CA} FreeLang \uBBF8\uBC1C\uACAC \uD568\uC218 TOP ${t} (\uB85C\uADF8: ${r})
1125
+ `),a.forEach(([i,o],u)=>{let f=s[i]?` \u2190 ${s[i]}`:"";console.log(` ${String(u+1).padStart(2)}. ${i.padEnd(30)} ${String(o).padStart(4)}\uD68C${f}`)}),console.log(`
1126
+ \uCD1D ${Object.keys(n).length}\uC885\uB958 / ${e.split(`
1127
+ `).length}\uAC74
1128
+ `)}catch(e){e.code==="ENOENT"?console.log(`(\uC544\uC9C1 \uAE30\uB85D \uC5C6\uC74C \u2014 ${r})`):console.error(e.message)}break}case"errors-clear":{let r=process.env.FL_ERROR_LOG??"/tmp/fl-unknown-functions.jsonl";try{j.unlinkSync(r),console.log(`\u2713 \uB85C\uADF8 \uC0AD\uC81C: ${r}`)}catch{console.log("(\uB85C\uADF8 \uC5C6\uC74C)")}break}case"stop":{let r=J[1];if(r){let t=D.resolve(r),e=Ep(t);try{let n=j.readFileSync(e,"utf-8").trim(),s=parseInt(n.split(`
1129
+ `)[0],10);process.kill(s,"SIGTERM");try{j.unlinkSync(e)}catch{}console.log(`\u2713 \uC885\uB8CC: ${r} (PID ${s})`)}catch(n){if(n.code==="ENOENT")console.log(`(PID \uD30C\uC77C \uC5C6\uC74C \u2014 ${r} \uC774 \uC2E4\uD589 \uC911\uC774\uC9C0 \uC54A\uAC70\uB098 \uC774\uBBF8 \uC885\uB8CC\uB428)`);else if(n.code==="ESRCH"){try{j.unlinkSync(e)}catch{}console.log("(\uC774\uBBF8 \uC885\uB8CC\uB428)")}else console.error(n.message)}}else{let t=j.readdirSync("/tmp").filter(n=>n.startsWith("fl_")&&n.endsWith(".pid"));if(t.length===0){console.log("(\uC2E4\uD589 \uC911\uC778 fl \uD504\uB85C\uC138\uC2A4 \uC5C6\uC74C)");break}let e=0;for(let n of t)try{let s=j.readFileSync(`/tmp/${n}`,"utf-8").trim(),[a,i]=s.split(`
1130
+ `),o=parseInt(a,10);process.kill(o,"SIGTERM"),j.unlinkSync(`/tmp/${n}`),console.log(`\u2713 \uC885\uB8CC: PID ${o} ${i??n}`),e++}catch(s){if(s.code==="ESRCH"){try{j.unlinkSync(`/tmp/${n}`)}catch{}console.log(`\u2713 \uC774\uBBF8 \uC885\uB8CC\uB428: ${n}`)}else console.error(`\u2717 \uC2E4\uD328: ${n} \u2014 ${s.message}`)}console.log(`
1131
+ \uCD1D ${e}\uAC1C \uC885\uB8CC`)}break}case"ps":{let r=j.readdirSync("/tmp").filter(t=>t.startsWith("fl_")&&t.endsWith(".pid"));if(r.length===0){console.log("(\uC2E4\uD589 \uC911\uC778 fl \uD504\uB85C\uC138\uC2A4 \uC5C6\uC74C)");break}console.log(`
1132
+ \uC2E4\uD589 \uC911\uC778 FreeLang \uD504\uB85C\uC138\uC2A4:
1133
+ `);for(let t of r)try{let e=j.readFileSync(`/tmp/${t}`,"utf-8").trim(),[n,s]=e.split(`
1134
+ `),a=parseInt(n,10);process.kill(a,0);let i=s??t;console.log(` PID ${String(a).padEnd(8)} ${i}`)}catch(e){if(e.code==="ESRCH")try{j.unlinkSync(`/tmp/${t}`)}catch{}}console.log();break}case"version":case"-v":case"--version":console.log(`FreeLang v${Rp}`);break;case"help":case"-h":case"--help":sn();break;default:oo?sn(oo):sn();break}