sera-code 0.0.0-stage → 0.1.0

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 (456) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE-SERA.md +25 -0
  3. package/README.md +27 -2
  4. package/THIRD_PARTY_NOTICES.md +68 -0
  5. package/bin/sera.mjs +137 -0
  6. package/dist/bundle/chunks/anthropic-messages-RD7GXOQL.js +6 -0
  7. package/dist/bundle/chunks/anthropic.js +75 -0
  8. package/dist/bundle/chunks/azure-openai-responses-CJT3KTVK.js +2 -0
  9. package/dist/bundle/chunks/bedrock-converse-stream.js +89 -0
  10. package/dist/bundle/chunks/chunk-46WGNYIE.js +82 -0
  11. package/dist/bundle/chunks/chunk-4UNN5OGR.js +4 -0
  12. package/dist/bundle/chunks/chunk-53H5DPHA.js +16 -0
  13. package/dist/bundle/chunks/chunk-5AGIVGSV.js +6 -0
  14. package/dist/bundle/chunks/chunk-6JXVX6Q2.js +2 -0
  15. package/dist/bundle/chunks/chunk-6QGV3IWD.js +6 -0
  16. package/dist/bundle/chunks/chunk-7CBJINYJ.js +20 -0
  17. package/dist/bundle/chunks/chunk-7DDKXS2Q.js +2 -0
  18. package/dist/bundle/chunks/chunk-7RZ5BS7U.js +2 -0
  19. package/dist/bundle/chunks/chunk-7ZC4UXSL.js +2 -0
  20. package/dist/bundle/chunks/chunk-BPHHHEET.js +9 -0
  21. package/dist/bundle/chunks/chunk-BSS6T6KQ.js +2 -0
  22. package/dist/bundle/chunks/chunk-CF5GWZHW.js +31 -0
  23. package/dist/bundle/chunks/chunk-EDSQGWII.js +44 -0
  24. package/dist/bundle/chunks/chunk-FFMDRXC4.js +10 -0
  25. package/dist/bundle/chunks/chunk-GUGC72EB.js +1222 -0
  26. package/dist/bundle/chunks/chunk-HODJBMOY.js +9 -0
  27. package/dist/bundle/chunks/chunk-HQBQWHLD.js +7 -0
  28. package/dist/bundle/chunks/chunk-HQJBN2MC.js +2 -0
  29. package/dist/bundle/chunks/chunk-JXWJOIH4.js +2 -0
  30. package/dist/bundle/chunks/chunk-KXU77PUU.js +4 -0
  31. package/dist/bundle/chunks/chunk-L2ZPNLYD.js +2 -0
  32. package/dist/bundle/chunks/chunk-LPXNMA2W.js +2 -0
  33. package/dist/bundle/chunks/chunk-LVVZS2NO.js +12 -0
  34. package/dist/bundle/chunks/chunk-M3LEVT3X.js +2 -0
  35. package/dist/bundle/chunks/chunk-P7FPUEYA.js +2 -0
  36. package/dist/bundle/chunks/chunk-PGXDEOVV.js +2 -0
  37. package/dist/bundle/chunks/chunk-PJACZCIR.js +2 -0
  38. package/dist/bundle/chunks/chunk-PMRZO46Y.js +2 -0
  39. package/dist/bundle/chunks/chunk-PRRNXB7S.js +2 -0
  40. package/dist/bundle/chunks/chunk-QTM7S6TH.js +2 -0
  41. package/dist/bundle/chunks/chunk-RDZVAGPR.js +2 -0
  42. package/dist/bundle/chunks/chunk-TLNP2BSO.js +2 -0
  43. package/dist/bundle/chunks/chunk-TMKHGABX.js +2 -0
  44. package/dist/bundle/chunks/chunk-TMTOQ7H7.js +2 -0
  45. package/dist/bundle/chunks/chunk-UKVNB6C4.js +2 -0
  46. package/dist/bundle/chunks/chunk-USJZMAIR.js +2 -0
  47. package/dist/bundle/chunks/chunk-UTB4DTYQ.js +2 -0
  48. package/dist/bundle/chunks/chunk-ZLAHUYDW.js +131 -0
  49. package/dist/bundle/chunks/chunk-ZNCN2NGY.js +60 -0
  50. package/dist/bundle/chunks/cli-MML2DU4A.js +51 -0
  51. package/dist/bundle/chunks/cloudflare-workers-ai-system-one-QPZQRBK5.js +2 -0
  52. package/dist/bundle/chunks/codemode-worker.js +478 -0
  53. package/dist/bundle/chunks/dist-ZNZCJI7B.js +7 -0
  54. package/dist/bundle/chunks/easter-egg-3d-VOETWRJO.js +2 -0
  55. package/dist/bundle/chunks/execute-HXDNZ26B.js +505 -0
  56. package/dist/bundle/chunks/github-copilot.js +2 -0
  57. package/dist/bundle/chunks/google-generative-ai-SJXMIEPZ.js +2 -0
  58. package/dist/bundle/chunks/google-vertex-VSXQ3BDH.js +2 -0
  59. package/dist/bundle/chunks/https-proxy-agent-LVOO5TPL.js +13 -0
  60. package/dist/bundle/chunks/image-resize-worker.js +2 -0
  61. package/dist/bundle/chunks/jiti-loader-GL4HJFAD.js +21 -0
  62. package/dist/bundle/chunks/jiti-static-loader-2RCDI6B4.js +2 -0
  63. package/dist/bundle/chunks/kimi-coding.js +2 -0
  64. package/dist/bundle/chunks/lib-4AVRLBHM.js +9 -0
  65. package/dist/bundle/chunks/llama-cpp-classify-4KFSGAMH.js +22 -0
  66. package/dist/bundle/chunks/meta.js +2 -0
  67. package/dist/bundle/chunks/mistral-conversations-JYWDZV2K.js +5 -0
  68. package/dist/bundle/chunks/multipart-parser-FMGQ7342.js +3 -0
  69. package/dist/bundle/chunks/node-AUOGOBCN.js +2 -0
  70. package/dist/bundle/chunks/node-KCMANYC2.js +16 -0
  71. package/dist/bundle/chunks/openai-chatgpt.js +75 -0
  72. package/dist/bundle/chunks/openai-codex-responses-OQV5DCFA.js +10 -0
  73. package/dist/bundle/chunks/openai-codex.js +75 -0
  74. package/dist/bundle/chunks/openai-completions-RFDJM2W5.js +7 -0
  75. package/dist/bundle/chunks/openai-decisions-O6PHBSCB.js +5 -0
  76. package/dist/bundle/chunks/openai-responses-LVNAPALQ.js +4 -0
  77. package/dist/bundle/chunks/openrouter-images-4WG6OOLH.js +2 -0
  78. package/dist/bundle/chunks/openrouter.js +75 -0
  79. package/dist/bundle/chunks/pdfjs-BETXZQ7A.js +108 -0
  80. package/dist/bundle/chunks/pdfjs-decoders-37HBPYHX.js +2 -0
  81. package/dist/bundle/chunks/pdfjs-jbig2-MH7WRXUP.js +2 -0
  82. package/dist/bundle/chunks/pdfjs-jbig2_nowasm_fallback-UVK7AQLA.js +2 -0
  83. package/dist/bundle/chunks/pdfjs-openjpeg-TC2QHC4G.js +2 -0
  84. package/dist/bundle/chunks/pdfjs-openjpeg_nowasm_fallback-ZC2FTHCZ.js +3 -0
  85. package/dist/bundle/chunks/pi-messages-EZXKVRR6.js +8 -0
  86. package/dist/bundle/chunks/radius.js +75 -0
  87. package/dist/bundle/chunks/runtime-JAH75CB5.js +2 -0
  88. package/dist/bundle/chunks/src-QKGKDFSU.js +4 -0
  89. package/dist/bundle/chunks/typesafe-system-one-X3JT6ECA.js +2 -0
  90. package/dist/bundle/chunks/virtual-modules-I5QRIHN6.js +2 -0
  91. package/dist/bundle/chunks/xai.js +2 -0
  92. package/dist/bundle/cli-runtime.js +3 -0
  93. package/dist/bundle/cli.js +5 -0
  94. package/dist/bundle/index.js +2 -0
  95. package/dist/bundle/rpc-entry.js +3 -0
  96. package/dist/core/export-html/ansi-to-html.d.ts +22 -0
  97. package/dist/core/export-html/ansi-to-html.d.ts.map +1 -0
  98. package/dist/core/export-html/ansi-to-html.js +249 -0
  99. package/dist/core/export-html/ansi-to-html.js.map +1 -0
  100. package/dist/core/export-html/index.d.ts +37 -0
  101. package/dist/core/export-html/index.d.ts.map +1 -0
  102. package/dist/core/export-html/index.js +228 -0
  103. package/dist/core/export-html/index.js.map +1 -0
  104. package/dist/core/export-html/template.css +1085 -0
  105. package/dist/core/export-html/template.html +56 -0
  106. package/dist/core/export-html/template.js +2044 -0
  107. package/dist/core/export-html/tool-renderer.d.ts +34 -0
  108. package/dist/core/export-html/tool-renderer.d.ts.map +1 -0
  109. package/dist/core/export-html/tool-renderer.js +110 -0
  110. package/dist/core/export-html/tool-renderer.js.map +1 -0
  111. package/dist/core/export-html/vendor/highlight.min.js +1213 -0
  112. package/dist/core/export-html/vendor/marked-cjk-friendly.min.js +6 -0
  113. package/dist/core/export-html/vendor/marked.min.js +79 -0
  114. package/dist/modes/interactive/assets/clankolas.png +0 -0
  115. package/dist/modes/interactive/theme/dark.json +81 -0
  116. package/dist/modes/interactive/theme/light.json +81 -0
  117. package/dist/modes/interactive/theme/system-theme.d.ts +55 -0
  118. package/dist/modes/interactive/theme/system-theme.d.ts.map +1 -0
  119. package/dist/modes/interactive/theme/system-theme.js +546 -0
  120. package/dist/modes/interactive/theme/system-theme.js.map +1 -0
  121. package/dist/modes/interactive/theme/theme-controller.d.ts +81 -0
  122. package/dist/modes/interactive/theme/theme-controller.d.ts.map +1 -0
  123. package/dist/modes/interactive/theme/theme-controller.js +210 -0
  124. package/dist/modes/interactive/theme/theme-controller.js.map +1 -0
  125. package/dist/modes/interactive/theme/theme-schema.d.ts +28 -0
  126. package/dist/modes/interactive/theme/theme-schema.d.ts.map +1 -0
  127. package/dist/modes/interactive/theme/theme-schema.js +105 -0
  128. package/dist/modes/interactive/theme/theme-schema.js.map +1 -0
  129. package/dist/modes/interactive/theme/theme-tokens.d.ts +257 -0
  130. package/dist/modes/interactive/theme/theme-tokens.d.ts.map +1 -0
  131. package/dist/modes/interactive/theme/theme-tokens.js +94 -0
  132. package/dist/modes/interactive/theme/theme-tokens.js.map +1 -0
  133. package/dist/modes/interactive/theme/theme.d.ts +155 -0
  134. package/dist/modes/interactive/theme/theme.d.ts.map +1 -0
  135. package/dist/modes/interactive/theme/theme.js +905 -0
  136. package/dist/modes/interactive/theme/theme.js.map +1 -0
  137. package/docs/cli-integration.md +106 -0
  138. package/docs/cli.md +333 -0
  139. package/docs/codemode.md +230 -0
  140. package/docs/compaction.md +463 -0
  141. package/docs/configuration.md +47 -0
  142. package/docs/containerization.md +183 -0
  143. package/docs/custom-provider.md +227 -0
  144. package/docs/docs.json +220 -0
  145. package/docs/environment-variables.md +102 -0
  146. package/docs/extensions.md +400 -0
  147. package/docs/how-pi-works.md +49 -0
  148. package/docs/index.md +39 -0
  149. package/docs/json.md +226 -0
  150. package/docs/keybindings.md +195 -0
  151. package/docs/llama-cpp.md +121 -0
  152. package/docs/mcp.md +272 -0
  153. package/docs/message-types.md +279 -0
  154. package/docs/models-configuration.md +196 -0
  155. package/docs/models.md +225 -0
  156. package/docs/nvidia-rtx-llama-cpp.md +96 -0
  157. package/docs/packages.md +131 -0
  158. package/docs/prompt-templates.md +59 -0
  159. package/docs/providers.md +247 -0
  160. package/docs/quickstart.md +136 -0
  161. package/docs/rpc-commands.md +860 -0
  162. package/docs/rpc-extension-ui.md +200 -0
  163. package/docs/rpc.md +193 -0
  164. package/docs/sdk.md +147 -0
  165. package/docs/security.md +99 -0
  166. package/docs/session-format.md +293 -0
  167. package/docs/sessions.md +66 -0
  168. package/docs/settings.md +172 -0
  169. package/docs/shell-aliases.md +93 -0
  170. package/docs/skills.md +93 -0
  171. package/docs/slash-commands.md +61 -0
  172. package/docs/terminal-setup.md +233 -0
  173. package/docs/termux.md +117 -0
  174. package/docs/themes.md +138 -0
  175. package/docs/tmux.md +55 -0
  176. package/docs/tui.md +195 -0
  177. package/docs/usage.md +94 -0
  178. package/docs/virtual-models.md +114 -0
  179. package/docs/windows.md +81 -0
  180. package/lib/auth.js +190 -0
  181. package/lib/provider.js +52 -0
  182. package/package.json +43 -5
  183. package/sera-core/skills/apple-tasarim/SKILL.md +48 -0
  184. package/sera-core/skills/apple-tasarim/referanslar/apple-hig.md +55 -0
  185. package/sera-core/skills/belge-yarat/SKILL.md +64 -0
  186. package/sera-core/skills/belge-yarat/referanslar/belge-yazim.md +60 -0
  187. package/sera-core/skills/derin-arastirma/SKILL.md +52 -0
  188. package/sera-core/skills/derin-arastirma/referanslar/arastirma-yontem.md +50 -0
  189. package/sera-core/skills/dusunme-dogrulama/SKILL.md +59 -0
  190. package/sera-core/skills/dusunme-dogrulama/referanslar/dusunme-kontrol.md +54 -0
  191. package/sera-core/skills/film-stilleri/SKILL.md +51 -0
  192. package/sera-core/skills/hyperframes/LICENSE-UPSTREAM +190 -0
  193. package/sera-core/skills/hyperframes/SKILL.md +79 -0
  194. package/sera-core/skills/hyperframes/assets/frame-presets/biennale-yellow/FRAME.md +289 -0
  195. package/sera-core/skills/hyperframes/assets/frame-presets/blockframe/FRAME.md +275 -0
  196. package/sera-core/skills/hyperframes/assets/frame-presets/blue-professional/FRAME.md +307 -0
  197. package/sera-core/skills/hyperframes/assets/frame-presets/bold-poster/FRAME.md +275 -0
  198. package/sera-core/skills/hyperframes/assets/frame-presets/broadside/FRAME.md +284 -0
  199. package/sera-core/skills/hyperframes/assets/frame-presets/capsule/FRAME.md +284 -0
  200. package/sera-core/skills/hyperframes/assets/frame-presets/cartesian/FRAME.md +278 -0
  201. package/sera-core/skills/hyperframes/assets/frame-presets/cobalt-grid/FRAME.md +265 -0
  202. package/sera-core/skills/hyperframes/assets/frame-presets/code-editorial/FRAME.md +277 -0
  203. package/sera-core/skills/hyperframes/assets/frame-presets/coral/FRAME.md +314 -0
  204. package/sera-core/skills/hyperframes/assets/frame-presets/creative-mode/FRAME.md +333 -0
  205. package/sera-core/skills/hyperframes/assets/frame-presets/daisy-days/FRAME.md +274 -0
  206. package/sera-core/skills/hyperframes/assets/frame-presets/editorial-forest/FRAME.md +265 -0
  207. package/sera-core/skills/hyperframes/references/captions.md +46 -0
  208. package/sera-core/skills/hyperframes/references/film.md +48 -0
  209. package/sera-core/skills/hyperframes/references/format.md +159 -0
  210. package/sera-core/skills/hyperframes/references/look.md +69 -0
  211. package/sera-core/skills/hyperframes/references/motion.md +95 -0
  212. package/sera-core/skills/hyperframes/references/overlays.md +39 -0
  213. package/sera-core/skills/hyperframes/references/path-tracing.md +36 -0
  214. package/sera-core/skills/hyperframes/references/plugin-installation.md +42 -0
  215. package/sera-core/skills/hyperframes/references/review.md +51 -0
  216. package/sera-core/skills/hyperframes/references/runtimes.md +69 -0
  217. package/sera-core/skills/hyperframes/references/skill-lifecycle.md +54 -0
  218. package/sera-core/skills/hyperframes/references/sound.md +43 -0
  219. package/sera-core/skills/hyperframes/references/spec.md +76 -0
  220. package/sera-core/skills/hyperframes/references/story.md +103 -0
  221. package/sera-core/skills/hyperframes/references/storyboard-format.md +107 -0
  222. package/sera-core/skills/hyperframes/references/storyboard.md +36 -0
  223. package/sera-core/skills/hyperframes/references/types/3d.md +25 -0
  224. package/sera-core/skills/hyperframes/references/types/character.md +20 -0
  225. package/sera-core/skills/hyperframes/references/types/data.md +19 -0
  226. package/sera-core/skills/hyperframes/references/types/explainer.md +34 -0
  227. package/sera-core/skills/hyperframes/references/types/launch.md +41 -0
  228. package/sera-core/skills/hyperframes/references/types/music.md +24 -0
  229. package/sera-core/skills/hyperframes/references/types/vertical.md +23 -0
  230. package/sera-core/skills/hyperframes-cli/LICENSE-UPSTREAM +190 -0
  231. package/sera-core/skills/hyperframes-cli/SKILL.md +99 -0
  232. package/sera-core/skills/hyperframes-cli/references/beats.md +17 -0
  233. package/sera-core/skills/hyperframes-cli/references/compare-and-batch.md +105 -0
  234. package/sera-core/skills/hyperframes-cli/references/conventions.md +16 -0
  235. package/sera-core/skills/hyperframes-cli/references/doctor-browser.md +80 -0
  236. package/sera-core/skills/hyperframes-cli/references/feedback.md +14 -0
  237. package/sera-core/skills/hyperframes-cli/references/init-and-scaffold.md +75 -0
  238. package/sera-core/skills/hyperframes-cli/references/lint-validate-inspect.md +164 -0
  239. package/sera-core/skills/hyperframes-cli/references/preview-render.md +204 -0
  240. package/sera-core/skills/hyperframes-cli/references/upgrade-info-misc.md +134 -0
  241. package/sera-core/skills/impeccable/LICENSE-UPSTREAM +191 -0
  242. package/sera-core/skills/impeccable/NOTICE-UPSTREAM.md +11 -0
  243. package/sera-core/skills/impeccable/SKILL.md +89 -0
  244. package/sera-core/skills/impeccable/reference/adapt.md +318 -0
  245. package/sera-core/skills/impeccable/reference/adapt.native.md +58 -0
  246. package/sera-core/skills/impeccable/reference/android.md +46 -0
  247. package/sera-core/skills/impeccable/reference/animate.md +89 -0
  248. package/sera-core/skills/impeccable/reference/audit.md +139 -0
  249. package/sera-core/skills/impeccable/reference/audit.native.md +139 -0
  250. package/sera-core/skills/impeccable/reference/bolder.md +33 -0
  251. package/sera-core/skills/impeccable/reference/clarify.md +94 -0
  252. package/sera-core/skills/impeccable/reference/colorize.md +86 -0
  253. package/sera-core/skills/impeccable/reference/component-review.md +63 -0
  254. package/sera-core/skills/impeccable/reference/craft-floor.md +44 -0
  255. package/sera-core/skills/impeccable/reference/craft.md +5 -0
  256. package/sera-core/skills/impeccable/reference/critique.md +819 -0
  257. package/sera-core/skills/impeccable/reference/degraded/asset-producer.md +42 -0
  258. package/sera-core/skills/impeccable/reference/degraded/documenter.md +24 -0
  259. package/sera-core/skills/impeccable/reference/degraded/finish-reviewer.md +38 -0
  260. package/sera-core/skills/impeccable/reference/degraded/manual-edit-applier.md +93 -0
  261. package/sera-core/skills/impeccable/reference/delight.md +70 -0
  262. package/sera-core/skills/impeccable/reference/distill.md +111 -0
  263. package/sera-core/skills/impeccable/reference/doctor.md +54 -0
  264. package/sera-core/skills/impeccable/reference/document.md +416 -0
  265. package/sera-core/skills/impeccable/reference/extract.md +69 -0
  266. package/sera-core/skills/impeccable/reference/generate.md +101 -0
  267. package/sera-core/skills/impeccable/reference/harden.md +362 -0
  268. package/sera-core/skills/impeccable/reference/hooks.md +120 -0
  269. package/sera-core/skills/impeccable/reference/init.md +133 -0
  270. package/sera-core/skills/impeccable/reference/ios.md +51 -0
  271. package/sera-core/skills/impeccable/reference/layout.md +84 -0
  272. package/sera-core/skills/impeccable/reference/live-setup.md +104 -0
  273. package/sera-core/skills/impeccable/reference/live.md +327 -0
  274. package/sera-core/skills/impeccable/reference/mode-operate.md +21 -0
  275. package/sera-core/skills/impeccable/reference/mode-persuade.md +19 -0
  276. package/sera-core/skills/impeccable/reference/mode-read.md +21 -0
  277. package/sera-core/skills/impeccable/reference/new-work.md +152 -0
  278. package/sera-core/skills/impeccable/reference/onboard.md +234 -0
  279. package/sera-core/skills/impeccable/reference/operate.md +61 -0
  280. package/sera-core/skills/impeccable/reference/optimize.md +257 -0
  281. package/sera-core/skills/impeccable/reference/overdrive.md +127 -0
  282. package/sera-core/skills/impeccable/reference/polish.md +105 -0
  283. package/sera-core/skills/impeccable/reference/quieter.md +99 -0
  284. package/sera-core/skills/impeccable/reference/region-map.md +26 -0
  285. package/sera-core/skills/impeccable/reference/routing.md +24 -0
  286. package/sera-core/skills/impeccable/reference/shape.md +59 -0
  287. package/sera-core/skills/impeccable/reference/typeset.md +90 -0
  288. package/sera-core/skills/impeccable/reference/visualize.md +47 -0
  289. package/sera-core/skills/oyun-yarat/SKILL.md +106 -0
  290. package/sera-core/skills/oyun-yarat/referanslar/3b-yaris.md +74 -0
  291. package/sera-core/skills/oyun-yarat/referanslar/kaplay.md +99 -0
  292. package/sera-core/skills/oyun-yarat/referanslar/oyun-desenleri.md +73 -0
  293. package/sera-core/skills/oyun-yarat/sablonlar/kaplay-2d.html +164 -0
  294. package/sera-core/skills/oyun-yarat/sablonlar/three-yaris.html +149 -0
  295. package/sera-core/skills/oyun-yarat/sablonlar/tuval-minimal.html +77 -0
  296. package/sera-core/skills/receiving-code-review/LICENSE-UPSTREAM +21 -0
  297. package/sera-core/skills/receiving-code-review/SKILL.md +205 -0
  298. package/sera-core/skills/refero-design/LICENSE-UPSTREAM +21 -0
  299. package/sera-core/skills/refero-design/SKILL.md +534 -0
  300. package/sera-core/skills/refero-design/references/anti-ai-slop.md +292 -0
  301. package/sera-core/skills/refero-design/references/color.md +563 -0
  302. package/sera-core/skills/refero-design/references/copywriting.md +222 -0
  303. package/sera-core/skills/refero-design/references/craft-details.md +525 -0
  304. package/sera-core/skills/refero-design/references/example-workflow.md +264 -0
  305. package/sera-core/skills/refero-design/references/icons.md +166 -0
  306. package/sera-core/skills/refero-design/references/mcp-tools.md +258 -0
  307. package/sera-core/skills/refero-design/references/motion.md +504 -0
  308. package/sera-core/skills/refero-design/references/typography.md +737 -0
  309. package/sera-core/skills/refero-design/references/visual-workflow.md +105 -0
  310. package/sera-core/skills/requesting-code-review/LICENSE-UPSTREAM +21 -0
  311. package/sera-core/skills/requesting-code-review/SKILL.md +95 -0
  312. package/sera-core/skills/requesting-code-review/code-reviewer.md +198 -0
  313. package/sera-core/skills/reverse-engineer-anything/DISCLAIMER.md +136 -0
  314. package/sera-core/skills/reverse-engineer-anything/LICENSE-REA-MIT +21 -0
  315. package/sera-core/skills/reverse-engineer-anything/SKILL.md +363 -0
  316. package/sera-core/skills/reverse-engineer-anything/THIRD_PARTY_NOTICES.md +135 -0
  317. package/sera-core/skills/reverse-engineer-anything/references/android-applications.md +36 -0
  318. package/sera-core/skills/reverse-engineer-anything/references/connection-and-recovery.md +127 -0
  319. package/sera-core/skills/reverse-engineer-anything/references/evidence-workflows.md +71 -0
  320. package/sera-core/skills/reverse-engineer-anything/references/javascript-applications.md +218 -0
  321. package/sera-core/skills/reverse-engineer-anything/references/native-and-artifacts.md +297 -0
  322. package/sera-core/skills/reverse-engineer-anything/references/runtime-observation.md +78 -0
  323. package/sera-core/skills/seo-audit/LICENSE-UPSTREAM +21 -0
  324. package/sera-core/skills/seo-audit/SKILL.md +210 -0
  325. package/sera-core/skills/sera-guvenlik-denetim/SKILL.md +44 -0
  326. package/sera-core/skills/sera-guvenlik-denetim/referanslar/guvenlik-listesi.md +33 -0
  327. package/sera-core/skills/sera-hata-ayikla/SKILL.md +27 -0
  328. package/sera-core/skills/sera-hata-ayikla/referanslar/hata-ayiklama.md +37 -0
  329. package/sera-core/skills/sera-kod-inceleme/SKILL.md +44 -0
  330. package/sera-core/skills/sera-kod-inceleme/referanslar/inceleme-listesi.md +62 -0
  331. package/sera-core/skills/sera-ofis-dosya/SKILL.md +27 -0
  332. package/sera-core/skills/sera-ofis-dosya/referanslar/ofis-dosya.md +93 -0
  333. package/sera-core/skills/sera-research/SKILL.md +90 -0
  334. package/sera-core/skills/sera-tasarim/SKILL.md +149 -0
  335. package/sera-core/skills/sera-teslim-sozlesmesi/SKILL.md +592 -0
  336. package/sera-core/skills/sera-test-yaz/SKILL.md +26 -0
  337. package/sera-core/skills/sera-test-yaz/referanslar/test-yazimi.md +35 -0
  338. package/sera-core/skills/sera-veri-gorsel/SKILL.md +65 -0
  339. package/sera-core/skills/sera-web-test/SKILL.md +26 -0
  340. package/sera-core/skills/sera-web-test/referanslar/web-test.md +44 -0
  341. package/sera-core/skills/sera-zamanli-gorev/SKILL.md +22 -0
  342. package/sera-core/skills/sera-zamanli-gorev/referanslar/zamanli-gorev.md +58 -0
  343. package/sera-core/skills/systematic-debugging/LICENSE-UPSTREAM +21 -0
  344. package/sera-core/skills/systematic-debugging/SKILL.md +283 -0
  345. package/sera-core/skills/systematic-debugging/condition-based-waiting.md +115 -0
  346. package/sera-core/skills/systematic-debugging/defense-in-depth.md +122 -0
  347. package/sera-core/skills/systematic-debugging/root-cause-tracing.md +169 -0
  348. package/sera-core/skills/test-driven-development/LICENSE-UPSTREAM +21 -0
  349. package/sera-core/skills/test-driven-development/SKILL.md +330 -0
  350. package/sera-core/skills/test-driven-development/writing-good-tests.md +198 -0
  351. package/sera-core/skills/ticaret-icerik/SKILL.md +49 -0
  352. package/sera-core/skills/ticaret-icerik/referanslar/ticaret-icerik.md +54 -0
  353. package/sera-core/skills/uygulama-yarat/SKILL.md +95 -0
  354. package/sera-core/skills/uygulama-yarat/referanslar/uygulama-desenleri.md +63 -0
  355. package/sera-core/skills/uygulama-yarat/sablonlar/uygulama-tek-dosya.html +121 -0
  356. package/sera-core/skills/uyumluluk-denetim/SKILL.md +56 -0
  357. package/sera-core/skills/uyumluluk-denetim/referanslar/mevzuat-tablosu.md +65 -0
  358. package/sera-core/skills/veri-analizi/SKILL.md +54 -0
  359. package/sera-core/skills/veri-analizi/referanslar/veri-analizi-yontem.md +49 -0
  360. package/sera-core/skills/veri-analizi/sablonlar/profil.mjs +79 -0
  361. package/sera-core/skills/video-duzen/SKILL.md +50 -0
  362. package/sera-core/skills/video-duzen/referanslar/video-duzen.md +100 -0
  363. package/sera-core/skills/web-yayin-listesi/SKILL.md +115 -0
  364. package/sera-core/skills/writing-plans/LICENSE-UPSTREAM +21 -0
  365. package/sera-core/skills/writing-plans/SKILL.md +204 -0
  366. package/sera-core/src/action-nudge.ts +200 -0
  367. package/sera-core/src/agent-mode.ts +143 -0
  368. package/sera-core/src/agents.ts +185 -0
  369. package/sera-core/src/app-master.ts +275 -0
  370. package/sera-core/src/app-verify.ts +551 -0
  371. package/sera-core/src/approval.ts +131 -0
  372. package/sera-core/src/budget.ts +136 -0
  373. package/sera-core/src/command-policy.ts +808 -0
  374. package/sera-core/src/config.ts +135 -0
  375. package/sera-core/src/context-diet.ts +272 -0
  376. package/sera-core/src/device-id.ts +48 -0
  377. package/sera-core/src/dogal-arac.ts +203 -0
  378. package/sera-core/src/dogal-niyet.ts +173 -0
  379. package/sera-core/src/egress-allow.ts +52 -0
  380. package/sera-core/src/export.ts +124 -0
  381. package/sera-core/src/exposure.ts +8 -0
  382. package/sera-core/src/extension.ts +2416 -0
  383. package/sera-core/src/fs-tools.ts +444 -0
  384. package/sera-core/src/generated/build-rules.ts +26 -0
  385. package/sera-core/src/generated/zero-knowledge.ts +170 -0
  386. package/sera-core/src/github-agent-command.ts +133 -0
  387. package/sera-core/src/github-agent-engine.ts +198 -0
  388. package/sera-core/src/github-agent-schedule.ts +180 -0
  389. package/sera-core/src/github-agent.ts +669 -0
  390. package/sera-core/src/github-ajan-akis.ts +193 -0
  391. package/sera-core/src/github-ajan-gercek.ts +102 -0
  392. package/sera-core/src/github-tick.ts +78 -0
  393. package/sera-core/src/github-yedek.ts +269 -0
  394. package/sera-core/src/goal.ts +119 -0
  395. package/sera-core/src/handoff.ts +132 -0
  396. package/sera-core/src/hooks.ts +284 -0
  397. package/sera-core/src/image-tool.ts +118 -0
  398. package/sera-core/src/intake-brief.ts +82 -0
  399. package/sera-core/src/intake-core.ts +1152 -0
  400. package/sera-core/src/intake-hook.ts +88 -0
  401. package/sera-core/src/ios-build-tool.ts +134 -0
  402. package/sera-core/src/lazy-capability.ts +125 -0
  403. package/sera-core/src/lazy-mcp.ts +300 -0
  404. package/sera-core/src/limit-command.ts +51 -0
  405. package/sera-core/src/loop-brake.ts +129 -0
  406. package/sera-core/src/lsp.ts +618 -0
  407. package/sera-core/src/mcp-bridge.ts +159 -0
  408. package/sera-core/src/mcp-pin.ts +105 -0
  409. package/sera-core/src/mcp-ssrf.ts +124 -0
  410. package/sera-core/src/message-cap.ts +45 -0
  411. package/sera-core/src/no-progress.ts +177 -0
  412. package/sera-core/src/notebook-tool.ts +179 -0
  413. package/sera-core/src/ofis.ts +473 -0
  414. package/sera-core/src/path-guard.ts +139 -0
  415. package/sera-core/src/permission-bridge.ts +228 -0
  416. package/sera-core/src/policy-chain.ts +122 -0
  417. package/sera-core/src/pricing.ts +71 -0
  418. package/sera-core/src/proc.ts +149 -0
  419. package/sera-core/src/rea.ts +188 -0
  420. package/sera-core/src/repo-map.ts +230 -0
  421. package/sera-core/src/research.ts +347 -0
  422. package/sera-core/src/rules-memory.ts +227 -0
  423. package/sera-core/src/sandbox.ts +445 -0
  424. package/sera-core/src/server-error.ts +78 -0
  425. package/sera-core/src/skills.ts +268 -0
  426. package/sera-core/src/snapshot.ts +143 -0
  427. package/sera-core/src/spec-gate.ts +112 -0
  428. package/sera-core/src/subagent.ts +261 -0
  429. package/sera-core/src/teslim.ts +120 -0
  430. package/sera-core/src/test-fix.ts +184 -0
  431. package/sera-core/src/todo-question.ts +163 -0
  432. package/sera-core/src/turn-snapshots.ts +126 -0
  433. package/sera-core/src/tuval/arac.ts +338 -0
  434. package/sera-core/src/tuval/arsiv.ts +106 -0
  435. package/sera-core/src/tuval/belge.ts +216 -0
  436. package/sera-core/src/tuval/birlestir.ts +282 -0
  437. package/sera-core/src/tuval/disa.ts +235 -0
  438. package/sera-core/src/tuval/editor.ts +583 -0
  439. package/sera-core/src/tuval/film-cekirdek.ts +170 -0
  440. package/sera-core/src/tuval/film-disa.ts +188 -0
  441. package/sera-core/src/tuval/film-oynatici.ts +307 -0
  442. package/sera-core/src/tuval/kimlik.ts +156 -0
  443. package/sera-core/src/tuval/pano.ts +763 -0
  444. package/sera-core/src/tuval/proje.ts +728 -0
  445. package/sera-core/src/tuval/sistem-cekirdek.ts +167 -0
  446. package/sera-core/src/tuval/sistem.ts +328 -0
  447. package/sera-core/src/tuval/sunucu.ts +413 -0
  448. package/sera-core/src/tuval/uretim.ts +24 -0
  449. package/sera-core/src/tuval/veri-cekirdek.ts +477 -0
  450. package/sera-core/src/tuval/xlsx.ts +215 -0
  451. package/sera-core/src/tuval/zip.ts +163 -0
  452. package/sera-core/src/untrusted.ts +201 -0
  453. package/sera-core/src/video-edit-tool.ts +411 -0
  454. package/sera-core/src/video-tool.ts +217 -0
  455. package/sera-core/src/web-tools.ts +257 -0
  456. package/sera-core/src/zk.ts +104 -0
@@ -0,0 +1,2416 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { dirname, join, resolve as resolvePath } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import {
7
+ type ExtensionAPI,
8
+ type ExtensionContext,
9
+ setSeraCompactionPolicy,
10
+ type ToolCallEvent,
11
+ type ToolResultEvent,
12
+ } from "@earendil-works/pi-coding-agent";
13
+ import { Type } from "typebox";
14
+ import {
15
+ actionNudgeFromEnv,
16
+ classifyEnd,
17
+ exhaustedMessage,
18
+ IDLE_NUDGE,
19
+ IdleWatch,
20
+ NudgeState,
21
+ nudgeText,
22
+ } from "./action-nudge.ts";
23
+ import { AGENT_COMMAND, AgentMode, EXIT_PLAN_TOOL, parseAgentName, registerExitPlan } from "./agent-mode.ts";
24
+ import {
25
+ AGENT_TOOLS_ENV,
26
+ type AgentDef,
27
+ agentsSystemText,
28
+ findAgent,
29
+ framePrompt,
30
+ loadAgents,
31
+ restrictTools,
32
+ } from "./agents.ts";
33
+ import { registerAppTools } from "./app-master.ts";
34
+ import {
35
+ type ApprovalPolicy,
36
+ approvalBlock,
37
+ callKind,
38
+ isDefaultPolicy,
39
+ MODE_USAGE,
40
+ parseModeCommand,
41
+ policyFromEnv,
42
+ policyLabel,
43
+ } from "./approval.ts";
44
+ import { BudgetGovernor } from "./budget.ts";
45
+ import { classifyToolCall } from "./command-policy.ts";
46
+ import { loadConfig, type SeraConfig } from "./config.ts";
47
+ import { ContextDiet, capOutput, contentText, type MsgLike, makeFileSpill } from "./context-diet.ts";
48
+ import { type Handler as DogalHandler, registerDogalTools } from "./dogal-arac.ts";
49
+ import { loadEgressAllow } from "./egress-allow.ts";
50
+ import { buildExport, EXPORT_COMMAND } from "./export.ts";
51
+ import { rareExposure } from "./exposure.ts";
52
+ import { registerFsTools } from "./fs-tools.ts";
53
+ import { registerGithubCommand } from "./github-agent-command.ts";
54
+ import { realAkisDeps } from "./github-ajan-gercek.ts";
55
+ import { githubYedek } from "./github-yedek.ts";
56
+ import { GOAL_USAGE, type GoalState, goalNudge, newGoal, parseGoalCommand, shouldContinue } from "./goal.ts";
57
+ import { buildForkPrompt, buildHandoff, HANDOFF_COMMAND, HANDOFF_NOTIFY_PREFIX, type HandoffEntry } from "./handoff.ts";
58
+ import { HookRunner, loadHooks, TrustStore } from "./hooks.ts";
59
+ import { registerImageTool } from "./image-tool.ts";
60
+ import { briefEnabledFromEnv, makeBriefRuntime } from "./intake-brief.ts";
61
+ import { runIntakeBriefed } from "./intake-hook.ts";
62
+ import { registerIosBuildTool } from "./ios-build-tool.ts";
63
+ import { idleFromEnv } from "./lazy-capability.ts";
64
+ import { type LazyMcpRuntime, makeLazyMcp } from "./lazy-mcp.ts";
65
+ import { registerLimitCommand } from "./limit-command.ts";
66
+ import { brakeMessage, LoopBrake, UserTurnGate } from "./loop-brake.ts";
67
+ import { formatDiagnostics, LspManager, runFormatter } from "./lsp.ts";
68
+ import {
69
+ isRemoteMcp,
70
+ lazyMcpStatus,
71
+ MCP_LAZY_MIN_TOKENS,
72
+ MCP_STATUS_KEY,
73
+ MCP_STATUS_PREFIX,
74
+ mcpAutoActive,
75
+ mcpStatus,
76
+ parseMcpServers,
77
+ partitionMcp,
78
+ type SeraMcpServer,
79
+ } from "./mcp-bridge.ts";
80
+ import { checkRemoteMcpUrl } from "./mcp-ssrf.ts";
81
+ import { capMessages, capNoteText, maxMessagesFromEnv } from "./message-cap.ts";
82
+ import { NoProgress, noProgressNote, noProgressStop, type TurnInfo } from "./no-progress.ts";
83
+ import { registerNotebookTool } from "./notebook-tool.ts";
84
+ import {
85
+ OFIS_KOMUT_ENV,
86
+ OFIS_ROL_ENV,
87
+ OFIS_YAZ_ENV,
88
+ type OfisPlan,
89
+ ofisKabukEngeli,
90
+ ofisYazmaEngeli,
91
+ ofisYurut,
92
+ panoMetni,
93
+ planHatasi,
94
+ rolAraclari,
95
+ rolModeli,
96
+ } from "./ofis.ts";
97
+ import { checkOutside, extraRootsFromEnv } from "./path-guard.ts";
98
+ import { PERMISSION_TITLE_PREFIX, PermissionGate, parsePermissionTools } from "./permission-bridge.ts";
99
+ import { type CallStep, callChain, type ResultStep, resultChain } from "./policy-chain.ts";
100
+ import { resolvePrice, UNPRICED_WARNING } from "./pricing.ts";
101
+ import { ProcManager } from "./proc.ts";
102
+ import {
103
+ externalTools,
104
+ findRea,
105
+ installRea,
106
+ NOT_INSTALLED_MSG,
107
+ REA_STATUS_KEY,
108
+ REA_STATUS_PREFIX,
109
+ REA_VERSION,
110
+ reaDef,
111
+ reaEnabled,
112
+ reaGreeting,
113
+ } from "./rea.ts";
114
+ import { buildRepoMap } from "./repo-map.ts";
115
+ import {
116
+ clipSummary,
117
+ RESEARCH_SKILL,
118
+ ResearchLedger,
119
+ ResearchMode,
120
+ registerResearchTools,
121
+ registerResearchWorkflowTools,
122
+ } from "./research.ts";
123
+ import {
124
+ applyRulesMemory,
125
+ type ContextFile,
126
+ isShowIntent,
127
+ MEMORY_COMMAND,
128
+ MemoryStore,
129
+ memoryListText,
130
+ memoryPaths,
131
+ } from "./rules-memory.ts";
132
+ import { looksSandboxDenied, parseUnsandboxed, SANDBOX_HINT, SandboxRunner } from "./sandbox.ts";
133
+ import {
134
+ compactSkillsSection,
135
+ DEFAULT_SKILLS_COLLAPSE_OVER,
136
+ DEFAULT_SKILLS_MAX_TOKENS,
137
+ SkillGuard,
138
+ type SkillLike,
139
+ skillDirs,
140
+ } from "./skills.ts";
141
+ import { restoreSummary, SnapshotStore } from "./snapshot.ts";
142
+ import { type SpecGateState, onAgentEnd as specOnAgentEnd, startGate } from "./spec-gate.ts";
143
+ import { childBudget, newChildId, runChild, SUBAGENT_DEPTH_ENV, slimEvent } from "./subagent.ts";
144
+ import { loadTeslimBody, TESLIM_CUSTOM_TYPE, TeslimGate } from "./teslim.ts";
145
+ import {
146
+ commitPaths,
147
+ detectTestCommand,
148
+ editedPath,
149
+ fixPrompt,
150
+ runTests,
151
+ TEST_COMMAND,
152
+ TEST_ENTRY,
153
+ type TestEntry,
154
+ testAttempts,
155
+ testTimeoutMs,
156
+ } from "./test-fix.ts";
157
+ import { registerTodoQuestion } from "./todo-question.ts";
158
+ import {
159
+ REVERT_ALIAS,
160
+ REVERT_COMMAND,
161
+ SNAPSHOT_ENTRY,
162
+ SNAPSHOT_NOTIFY_PREFIX,
163
+ type TurnSnapshot,
164
+ TurnSnapshots,
165
+ UNDO_HINT,
166
+ UNREVERT_COMMAND,
167
+ } from "./turn-snapshots.ts";
168
+ import { registerTuvalTool } from "./tuval/arac.ts";
169
+ import {
170
+ injectionWarning,
171
+ isUntrustedSource,
172
+ riskAfterTaint,
173
+ scanInjection,
174
+ TaintTracker,
175
+ UNTRUSTED_RULE,
176
+ wrapUntrusted,
177
+ } from "./untrusted.ts";
178
+ import { registerVideoEditTool } from "./video-edit-tool.ts";
179
+ import { registerVideoTool } from "./video-tool.ts";
180
+ import { registerWebTools } from "./web-tools.ts";
181
+ import { registerZeroKnowledge } from "./zk.ts";
182
+
183
+ /** Güvenilmez-çıktı sınırlayıcıları: ilerleme-yok özetinde gösterilmez. */
184
+ const UNTRUSTED_TAGS = /<<<(SON_)?GUVENILMEZ_ARAC_CIKTISI[^>\n]*(>>>)?/g;
185
+
186
+ /**
187
+ * Sera core extension: D1 Budget Governor, D2 Context Diet, D3 Loop Brake.
188
+ * Lives entirely in the extension API - no changes to Pi core.
189
+ * Load: pi -e packages/sera-core/src/extension.ts (or via the "pi" manifest in package.json)
190
+ */
191
+ const SERA_MODEL_LABELS: Record<string, string> = {
192
+ // Sahip 2026-11-15: web/mobil seçicisiyle birebir (Mini, Zen, Sensei; Core kaldırıldı).
193
+ "sera-mini": "Mini",
194
+ "sera-zen": "Zen",
195
+ "sera-max": "Sensei",
196
+ };
197
+
198
+ export default async function seraCore(pi: ExtensionAPI) {
199
+ // Motor ic degiskenleri (PI_*) kullanici komutlarina gitmez (coding-agent bash.ts SERA_HIDE_SESSION_ENV).
200
+ process.env.SERA_HIDE_SESSION_ENV ??= "1";
201
+ const cfg: SeraConfig = loadConfig();
202
+ let governor: BudgetGovernor | undefined;
203
+ let haltReported = false;
204
+ const brake = new LoopBrake(cfg.loop);
205
+ const userTurn = new UserTurnGate();
206
+ const diet = new ContextDiet({
207
+ keepRecentTurns: cfg.diet.keepRecentTurns,
208
+ minChars: cfg.diet.minChars,
209
+ pruneAtTokens: cfg.diet.pruneAtTokens,
210
+ pruneStepTokens: cfg.diet.pruneStepTokens,
211
+ spill: makeFileSpill(cfg.diet.spillDir),
212
+ });
213
+ const brakeStops = new Set<string>();
214
+ const actionCfg = actionNudgeFromEnv();
215
+ const actionNudge = new NudgeState(actionCfg);
216
+ // E5 ile ortak sinyal: bu turda loop-brake konustu mu (cift ses yok).
217
+ let brakeSpoke = false;
218
+ // /goal açıkken hedef modu kendi takibini gönderir: eylem-hatırlatması çift ses çıkarmaz.
219
+ let goalRunning: () => boolean = () => false;
220
+
221
+ // D2: early compaction. Pi's auto-compaction (which resumes the run afterwards) now triggers at
222
+ // min(window * ratio, 200K) instead of window - 16K. One small core hook, see settings-manager.ts.
223
+ setSeraCompactionPolicy({ ratio: cfg.diet.compactRatio, maxTokens: cfg.diet.compactAbsMaxTokens });
224
+
225
+ // Komut isleyicileri: dogal-dil araci (sera_islem) ayni mantigi cagirir (slash komut yazmadan).
226
+ const cmdHandlers = new Map<string, DogalHandler>();
227
+ const regCmd: typeof pi.registerCommand = (name, c) => {
228
+ cmdHandlers.set(name, c.handler as DogalHandler);
229
+ pi.registerCommand(name, c);
230
+ };
231
+ const say = (ctx: ExtensionContext, msg: string, level: "info" | "warning" | "error" = "warning") => {
232
+ process.stderr.write(`${msg}\n`);
233
+ try {
234
+ if (ctx.hasUI) ctx.ui.notify(msg, level);
235
+ } catch {
236
+ // UI may be unavailable
237
+ }
238
+ };
239
+
240
+ // Derin Arastirma Modu: ayri `research/` butce hatti (aylik tavan) + arama siniri + A19 (research.ts).
241
+ const research = new ResearchMode({
242
+ ledger: new ResearchLedger(
243
+ join(process.env.SERA_MEMORY_DIR || join(homedir(), ".sera"), "research-budget.json"),
244
+ Number(process.env.SERA_RESEARCH_CAP_USD) > 0 ? Number(process.env.SERA_RESEARCH_CAP_USD) : undefined,
245
+ ),
246
+ activeTools: () => pi.getActiveTools(),
247
+ searchUsd: Number(process.env.SERA_RESEARCH_SEARCH_USD) > 0 ? Number(process.env.SERA_RESEARCH_SEARCH_USD) : 0,
248
+ });
249
+
250
+ const getGovernor = (ctx: ExtensionContext): BudgetGovernor => {
251
+ if (!governor) {
252
+ const mc = (ctx.model as { cost?: { input?: unknown; output?: unknown } } | undefined)?.cost;
253
+ const catalogKnown = typeof mc?.input === "number" && typeof mc?.output === "number";
254
+ governor = new BudgetGovernor(cfg.budget, resolvePrice(ctx.model?.id, cfg.priceModel), catalogKnown);
255
+ }
256
+ return governor;
257
+ };
258
+
259
+ // Durum satirindaki butce cubugu (yalniz tavan tanimliysa): her model cagrisindan once ve cevaptan sonra.
260
+ // session_start'ta CAGRILMAZ: getGovernor fiyati ilk cagrida ctx.model'den sabitler.
261
+ const showMeter = (ctx: ExtensionContext) => {
262
+ const m = getGovernor(ctx).meter();
263
+ if (!m) return;
264
+ // Varsayilan (kullanicinin koymadigi) guvenlik tavani yalniz yaklasinca gorunur; aksi halde alt cubuk gurultu olur.
265
+ if (cfg.budgetDefaulted && !m.warn) return;
266
+ try {
267
+ if (ctx.hasUI) ctx.ui.setStatus("sera-budget", m.text);
268
+ } catch {
269
+ // UI may be unavailable
270
+ }
271
+ };
272
+
273
+ const enforce = (ctx: ExtensionContext): boolean => {
274
+ const g = getGovernor(ctx);
275
+ const st = g.check();
276
+ showMeter(ctx);
277
+ for (const d of st.warnings) say(ctx, `[Sera BUTCE] butce dolmak uzere (${d}).`);
278
+ if (st.halted) {
279
+ if (!haltReported) {
280
+ haltReported = true;
281
+ say(ctx, `[Sera BUTCE] ${st.message}`, "error");
282
+ pi.appendEntry("sera-budget-halt", {
283
+ message: st.message,
284
+ usd: g.usd,
285
+ turns: g.turns,
286
+ uncachedInput: g.uncachedInputTokens,
287
+ });
288
+ }
289
+ ctx.abort();
290
+ return true;
291
+ }
292
+ return false;
293
+ };
294
+
295
+ // --- D1: record usage from each finished assistant response (provider-reported, cached separate)
296
+ pi.on("message_end", (event, ctx) => {
297
+ const m = event.message as { role?: string; usage?: Parameters<BudgetGovernor["record"]>[0] };
298
+ if (m.role !== "assistant" || !m.usage) return;
299
+ const g = getGovernor(ctx);
300
+ const hadFallback = g.usedFallbackPrice;
301
+ const usdBefore = g.usd;
302
+ g.record(m.usage);
303
+ research.recordUsd(g.usd - usdBefore);
304
+ if (research.capReached()) {
305
+ say(ctx, research.capMessage(), "error");
306
+ ctx.abort();
307
+ }
308
+ if (g.usedFallbackPrice && !hadFallback) say(ctx, `[Sera BUTCE] ${UNPRICED_WARNING}.`);
309
+ showMeter(ctx);
310
+ });
311
+
312
+ // Loop-brake: yalniz GERCEK kullanici isteminde sifirla (sinyal aciklamasi: UserTurnGate).
313
+ pi.on("input", (e) => {
314
+ userTurn.onInput(e.source, e.streamingBehavior);
315
+ return { action: "continue" as const };
316
+ });
317
+
318
+ // --- Tarif kapsama kapısı (spec-gate.ts): kullanıcı tarif dosyası / uzun madde listesi verdiyse, ajan bitirdiğinde
319
+ // her madde için koddan kanıt istenir; eksik madde o turda uygulatılır (en çok MAX_ROUNDS tur). SERA_SPEC_GATE=0 kapatır.
320
+ if (process.env.SERA_SPEC_GATE !== "0" && process.env[SUBAGENT_DEPTH_ENV] !== "1") {
321
+ let spec: SpecGateState | undefined;
322
+ pi.on("input", (e, ctx) => {
323
+ if (e.source === "extension" || e.streamingBehavior) return { action: "continue" as const };
324
+ const read = (ref: string): string | undefined => {
325
+ try {
326
+ const p = resolvePath(ctx.cwd, ref);
327
+ if (!existsSync(p) || statSync(p).size > 400_000) return undefined;
328
+ return readFileSync(p, "utf8");
329
+ } catch {
330
+ return undefined;
331
+ }
332
+ };
333
+ const next = startGate(e.text, read);
334
+ // Yeni bir tarif verildiyse kapı yeniden kurulur; tarifsiz kısa takip mesajı açık kapıyı kapatmaz.
335
+ if (next) spec = next;
336
+ return { action: "continue" as const };
337
+ });
338
+ pi.on("agent_end", (e, ctx) => {
339
+ if (!spec || haltReported || goalRunning()) return;
340
+ const last = [...e.messages].reverse().find((m) => (m as { role?: string }).role === "assistant") as
341
+ | { content?: unknown }
342
+ | undefined;
343
+ const text = Array.isArray(last?.content)
344
+ ? (last.content as { type?: string; text?: string }[])
345
+ .filter((c) => c.type === "text")
346
+ .map((c) => c.text ?? "")
347
+ .join("\n")
348
+ : String(last?.content ?? "");
349
+ const d = specOnAgentEnd(spec, text);
350
+ if (d.note) say(ctx, d.note, d.level ?? "info");
351
+ if (!d.followUp) return;
352
+ pi.appendEntry("sera-spec-gate", { source: spec.source, round: spec.rounds, items: spec.items.length });
353
+ try {
354
+ pi.sendMessage(
355
+ { customType: "sera-spec-gate", content: d.followUp, display: false, details: { round: spec.rounds } },
356
+ { deliverAs: "followUp", triggerTurn: true },
357
+ );
358
+ } catch {
359
+ // oturum kapanmış
360
+ }
361
+ });
362
+ }
363
+ pi.on("before_agent_start", (e) => {
364
+ if (userTurn.onAgentStart(e.messageType)) {
365
+ brake.reset();
366
+ actionNudge.reset();
367
+ }
368
+ return undefined;
369
+ });
370
+
371
+ // --- D1: guard BEFORE every model call (transformContext runs right before the request) + D2 prune
372
+ const maxMessages = maxMessagesFromEnv();
373
+ let msgCapWarned = false;
374
+ pi.on("context", (event, ctx) => {
375
+ if (enforce(ctx)) return undefined;
376
+ let msgs = event.messages as unknown as MsgLike[];
377
+ if (cfg.diet.enabled) msgs = diet.prune(msgs);
378
+ // Sunucu tek istekte >400 mesajı reddeder (araç sonuçları da mesaj): token eşiğinden bağımsız sayı tavanı.
379
+ const capped = capMessages(msgs as unknown as { role?: string }[], maxMessages, (n) => ({
380
+ role: "user",
381
+ content: [{ type: "text", text: capNoteText(n) }],
382
+ timestamp: Date.now(),
383
+ }));
384
+ if (capped.dropped > 0) {
385
+ msgs = capped.messages as unknown as MsgLike[];
386
+ if (!msgCapWarned) {
387
+ msgCapWarned = true;
388
+ say(
389
+ ctx,
390
+ `[Sera] Konuşma ${maxMessages} mesajı aştı; en eski ${capped.dropped} mesaj isteklerden çıkarılıyor (sunucu sınırı).`,
391
+ "info",
392
+ );
393
+ }
394
+ }
395
+ if (msgs === (event.messages as unknown)) return undefined;
396
+ return { messages: msgs as unknown as typeof event.messages };
397
+ });
398
+
399
+ // Sera Giris Alani (Katman A): uzun/yapistirilmis mesaj modele gitmeden once deterministik temizlenir (ANSI, tekrar,
400
+ // yigin izi dongusu); hala cok uzunsa orijinal ~/.sera/intake altina BIREBIR yazilir, modele referans + bas/son gider.
401
+ // Kisa mesaj ve ``` kod bloklari dokunulmaz. Kapatmak icin SERA_INTAKE=0.
402
+ // Katman B: uzun duz yazi icin en ucuz YAPILANDIRILMIS model (zincir degismez) brif cikarir; kapsam kontrolu + 8 sn zaman asimi,
403
+ // her hatada sessizce Katman A. Kapatmak icin SERA_BRIEF=0 (veya SERA_INTAKE=0).
404
+ pi.on("input", async (event, ctx) => {
405
+ // Dogal "neleri hatirliyorsun" istegi: model cagrilmadan (token harcamadan) /bellek listesi (web ile ayni kural).
406
+ if (isShowIntent(event.text) && !event.images?.length) {
407
+ const paths = memoryPaths(seraHome, ctx.cwd);
408
+ say(
409
+ ctx,
410
+ `[Sera] ${memoryListText(new MemoryStore(paths.project).lines(), new MemoryStore(paths.user).lines())}`,
411
+ "info",
412
+ );
413
+ return { action: "handled" as const };
414
+ }
415
+ let deps: Parameters<typeof runIntakeBriefed>[2];
416
+ if (briefEnabledFromEnv() && event.text.length > 4000) {
417
+ try {
418
+ const rt = makeBriefRuntime(ctx.modelRegistry as never, ctx.scopedModels as never, ctx.model as never);
419
+ if (rt) deps = { call: rt.call, opts: { prices: rt.prices } };
420
+ } catch {
421
+ deps = undefined;
422
+ }
423
+ }
424
+ const d = await runIntakeBriefed(
425
+ event,
426
+ join(dirname(cfg.diet.spillDir), "intake"),
427
+ deps,
428
+ undefined,
429
+ process.env.SERA_INTAKE !== "0",
430
+ );
431
+ if (d.action !== "transform") return { action: "continue" as const };
432
+ say(ctx, `[Sera] ${d.notice}`, "info");
433
+ return { action: "transform" as const, text: d.text };
434
+ });
435
+
436
+ pi.on("turn_end", (_event, ctx) => {
437
+ enforce(ctx);
438
+ });
439
+
440
+ // tool_call / tool_result politikalari TEK zincirde (sira policy-chain.ts'te sabit, kayit sirasindan bagimsiz).
441
+ const callSteps: CallStep<ToolCallEvent, ExtensionContext>[] = [];
442
+ const resultSteps: ResultStep<ToolResultEvent, ExtensionContext>[] = [];
443
+
444
+ // --- D3: loop brake
445
+ callSteps.push({
446
+ name: "loop-brake",
447
+ run: (event, ctx) => {
448
+ const r = brake.onCall(event.toolCallId, event.toolName, event.input);
449
+ if (r.level === "stop") {
450
+ brakeStops.add(event.toolCallId);
451
+ brakeSpoke = true;
452
+ const reason = brakeMessage("stop", event.toolName, r.count);
453
+ say(ctx, reason, "error");
454
+ pi.appendEntry("sera-loop-stop", { tool: event.toolName, count: r.count });
455
+ ctx.abort();
456
+ return { block: true, reason, terminate: true };
457
+ }
458
+ return undefined;
459
+ },
460
+ });
461
+
462
+ // --- Ajan modu (plan = yazma/calistirma kapali): yalnizca SERA_AGENTS=1 iken (Sera Code Pi adaptoru verir)
463
+ const agent = process.env.SERA_AGENTS === "1" ? new AgentMode() : undefined;
464
+ if (agent) {
465
+ regCmd(AGENT_COMMAND, {
466
+ description: "Sera ajan modu: plan (salt okunur) | build",
467
+ handler: async (args) => {
468
+ const next = parseAgentName(args);
469
+ if (!next) return;
470
+ pi.setActiveTools(agent.set(next, pi.getActiveTools()));
471
+ },
472
+ });
473
+ callSteps.push({ name: "agent-mode", run: (event) => agent.check(event.toolName, event.input) });
474
+ // exit_plan (ExitPlanMode karsiligi): yalniz ust ajan; build modunda aktif listeden cikarilir.
475
+ if (process.env[SUBAGENT_DEPTH_ENV] !== "1") {
476
+ registerExitPlan(pi, agent);
477
+ pi.on("session_start", () => {
478
+ if (agent.current === "build") pi.setActiveTools(pi.getActiveTools().filter((t) => t !== EXIT_PLAN_TOOL));
479
+ });
480
+ }
481
+ }
482
+
483
+ // --- Korumali yol / geri donussuz komut: HER ZAMAN acik (izin koprusu kapali ya da arayuz yokken de).
484
+ callSteps.push({
485
+ name: "protected-paths",
486
+ run: (event) => {
487
+ const d = classifyToolCall(event.toolName, event.input);
488
+ return d?.verdict === "deny" ? { block: true, reason: d.reason } : undefined;
489
+ },
490
+ });
491
+ // --- Sera Ofis çalışanı: dosya sınırı kodla zorlanır (yalnız istem yetmedi). Yalnız alt ajanda ve liste verildiyse.
492
+ // O11 (2026-11-16): rol de aktarılır → şef/danışman kabuğu salt-okunur, çalışanın kabukla yazması da listeye bağlı.
493
+ const ofisRol = process.env[OFIS_ROL_ENV];
494
+ if (process.env[SUBAGENT_DEPTH_ENV] === "1" && (process.env[OFIS_YAZ_ENV] || ofisRol)) {
495
+ const liste = (k: string): string[] => {
496
+ try {
497
+ const v = JSON.parse(process.env[k] ?? "[]");
498
+ return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : [];
499
+ } catch {
500
+ return []; // bozuk liste: güvenli taraf — hiçbir yazma izinli değil
501
+ }
502
+ };
503
+ const izinli = liste(OFIS_YAZ_ENV);
504
+ const izinliKomut = liste(OFIS_KOMUT_ENV);
505
+ callSteps.push({
506
+ name: "ofis-dosya",
507
+ run: (event, ctx) => {
508
+ const i = (event.input ?? {}) as Record<string, unknown>;
509
+ const kabuk = event.toolName === "bash" || event.toolName === "powershell";
510
+ const r = kabuk
511
+ ? ofisKabukEngeli(String(i.command ?? ""), ofisRol ?? "calisan", izinli, ctx.cwd, izinliKomut)
512
+ : process.env[OFIS_YAZ_ENV]
513
+ ? ofisYazmaEngeli(event.toolName, event.input, izinli, ctx.cwd)
514
+ : undefined;
515
+ return r ? { block: true, reason: r } : undefined;
516
+ },
517
+ });
518
+ }
519
+
520
+ // --- D2-6: onay modları matrisi (/sera-mode). Yalnız DARALTIR; chain'de permission'dan ÖNCE (ilk engelleyen kazanır).
521
+ // Varsayılan (tam + ağ=sor) hiçbir şeyi değiştirmez (regresyon yok). SERA_MODE/SERA_NET ile başlangıç ayarlanır.
522
+ let approval: ApprovalPolicy = policyFromEnv(process.env);
523
+ regCmd("sera-mode", {
524
+ description: "Sera onay modu: /sera-mode oku|düzenle|tam · ağ için: /sera-mode ağ kapat|aç",
525
+ handler: async (args, ctx) => {
526
+ const p = parseModeCommand(args);
527
+ if (p.show) {
528
+ say(ctx, `[Sera onay modu] ${policyLabel(approval)}. ${MODE_USAGE}`, "info");
529
+ return;
530
+ }
531
+ if (p.invalid) {
532
+ say(ctx, `[Sera] ${MODE_USAGE}`, "warning");
533
+ return;
534
+ }
535
+ if (p.mode) approval = { ...approval, mode: p.mode };
536
+ if (p.net) approval = { ...approval, net: p.net };
537
+ say(ctx, `[Sera onay modu] ${policyLabel(approval)}.`, "info");
538
+ },
539
+ });
540
+ callSteps.push({
541
+ name: "approval",
542
+ run: (event) => {
543
+ if (isDefaultPolicy(approval)) return undefined; // hızlı yol: varsayılanda hiçbir ek engel yok
544
+ const d = classifyToolCall(event.toolName, event.input);
545
+ const ci = event.input as { command?: unknown; serve_command?: unknown } | undefined;
546
+ const cmd = String(ci?.command ?? ci?.serve_command ?? "").trim();
547
+ const kind = callKind(event.toolName, { hasCommand: cmd.length > 0, egress: d?.egress === true });
548
+ const reason = approvalBlock(approval, kind);
549
+ return reason ? { block: true, reason: `[Sera onay modu] ${reason}.` } : undefined;
550
+ },
551
+ });
552
+
553
+ // --- D1-3 kancalar: ~/.sera/hooks.json (her zaman) + <proje>/.sera/hooks.json (yalniz kullanici /guven dediyse)
554
+ const trust = new TrustStore(process.env.SERA_TRUST_FILE || join(homedir(), ".sera", "trusted-projects.json"));
555
+ let hooks: HookRunner | undefined;
556
+ const hooksFor = (ctx: ExtensionContext): HookRunner => {
557
+ if (hooks) return hooks;
558
+ const userFile = process.env.SERA_HOOKS_FILE || join(homedir(), ".sera", "hooks.json");
559
+ const projectFile = join(ctx.cwd, ".sera", "hooks.json");
560
+ const files = [userFile];
561
+ if (projectFile !== userFile && existsSync(projectFile)) {
562
+ if (trust.has(ctx.cwd)) files.push(projectFile);
563
+ else
564
+ say(
565
+ ctx,
566
+ "[Sera KANCA] Bu projenin .sera/hooks.json kancalari calistirilmadi (proje guvenilir degil). Projeye guveniyorsan /guven yaz.",
567
+ "warning",
568
+ );
569
+ }
570
+ const { config, errors } = loadHooks(files);
571
+ for (const e of errors) say(ctx, `[Sera KANCA] ${e}`, "warning");
572
+ hooks = new HookRunner(config, ctx.cwd, (m) => say(ctx, m, "warning"));
573
+ return hooks;
574
+ };
575
+ // --- D1-5: devir notu (model cagrisi yok). Sera Code adaptoru yeni oturumu acar ve notu taslak olarak koyar.
576
+ regCmd(HANDOFF_COMMAND, {
577
+ description: "Sera: oturumu yeni oturuma devretmek icin devir notu uret (arguman: yeni gorev)",
578
+ handler: async (args, ctx) => {
579
+ const h = buildHandoff(ctx.sessionManager.getBranch() as unknown as HandoffEntry[], args);
580
+ const data = h ? { ok: true, ...h } : { ok: false, message: "Devredilecek bir konusma yok (oturum bos)." };
581
+ const text = HANDOFF_NOTIFY_PREFIX + JSON.stringify(data);
582
+ if (ctx.hasUI) ctx.ui.notify(text, data.ok ? "info" : "error");
583
+ else process.stderr.write(`${text}\n`);
584
+ },
585
+ });
586
+ // --- D2-9: oturumu paylaşılabilir Markdown'a aktar (model çağrısı yok; sırlar maskelenir). Dosya cwd'ye yazılır.
587
+ regCmd(EXPORT_COMMAND, {
588
+ description: "Sera: oturumu paylaşılabilir Markdown dökümüne aktar (sırlar maskelenir, model çağrısı yok)",
589
+ handler: async (_args, ctx) => {
590
+ const ex = buildExport(ctx.sessionManager.getBranch() as unknown as HandoffEntry[]);
591
+ if (!ex) {
592
+ say(ctx, "[Sera] Dışa aktarılacak konuşma yok (oturum boş).", "error");
593
+ return;
594
+ }
595
+ const stamp = new Date().toISOString().slice(0, 19).replace(/[:T]/g, "-");
596
+ const out = join(ctx.cwd, `sera-export-${stamp}.md`);
597
+ try {
598
+ writeFileSync(out, ex.markdown, "utf8");
599
+ say(ctx, `[Sera] Oturum dışa aktarıldı (${ex.turns} mesaj, sırlar maskeli): ${out}`, "info");
600
+ } catch (e) {
601
+ say(ctx, `[Sera] Dışa aktarım yazılamadı: ${e instanceof Error ? e.message : String(e)}`, "error");
602
+ }
603
+ },
604
+ });
605
+ // --- GitHub deposunda yaşayan ajan (/sera-github): issue'da @sera -> izole worktree -> PR. Yalnız üst ajan; varsayılan observe.
606
+ if (process.env[SUBAGENT_DEPTH_ENV] !== "1") registerGithubCommand(pi, say);
607
+ // --- D2-2: hedef modu (/goal). Hedefe ya da BÜTÇE/YİNELEME tavanına kadar otonom devam eder. Yalnız üst ajan.
608
+ if (process.env[SUBAGENT_DEPTH_ENV] !== "1") {
609
+ let goal: GoalState | undefined;
610
+ goalRunning = () => !!goal && !goal.done;
611
+ regCmd("goal", {
612
+ description: "Sera: hedef modu — /goal <hedef> [--turns N] [--usd X]; durdurmak: /goal dur",
613
+ handler: async (args, ctx) => {
614
+ const p = parseGoalCommand(args);
615
+ if (p.stop) {
616
+ goal = undefined;
617
+ say(ctx, "[Sera hedef modu] Kapatıldı.", "info");
618
+ return;
619
+ }
620
+ if (!p.text) {
621
+ say(ctx, `[Sera] ${GOAL_USAGE}`, "warning");
622
+ return;
623
+ }
624
+ const g = getGovernor(ctx);
625
+ goal = newGoal(p, { usd: g.usd, turns: g.turns });
626
+ say(
627
+ ctx,
628
+ `[Sera hedef modu] Aktif: "${goal.text}" (tur bütçesi ${goal.maxTurns}${goal.maxUsd ? `, $${goal.maxUsd}` : ""}, en çok ${goal.maxIterations} yineleme). Bitince goal_done aracı. Durdurmak: /goal dur.`,
629
+ "info",
630
+ );
631
+ },
632
+ });
633
+ pi.registerTool({
634
+ name: "goal_done",
635
+ label: "Goal done",
636
+ description: "Aktif /goal hedefi tamamlandığında çağır: kısa bir özet ver; hedef modu kapanır.",
637
+ promptSnippet: "Mark the active /goal as achieved",
638
+ parameters: Type.Object({
639
+ summary: Type.String({ description: "Hedefin nasıl karşılandığının kısa özeti" }),
640
+ }),
641
+ async execute(_id, params, _signal, _onUpdate, ctx) {
642
+ if (!goal) return { content: [{ type: "text" as const, text: "Aktif hedef yok." }], details: {} };
643
+ goal.done = true;
644
+ const text = `[Sera hedef modu] Hedefe ulaşıldı: "${goal.text}". ${params.summary}`;
645
+ goal = undefined;
646
+ say(ctx, text, "info");
647
+ return { content: [{ type: "text" as const, text }], details: {} };
648
+ },
649
+ });
650
+ pi.on("agent_end", (_e, ctx) => {
651
+ if (!goal || goal.done) return;
652
+ goal.iterations += 1;
653
+ const g = getGovernor(ctx);
654
+ const d = shouldContinue(goal, { usd: g.usd, turns: g.turns });
655
+ if (!d.cont) {
656
+ say(ctx, `[Sera hedef modu] Durdu: ${d.reason}. Hedef: "${goal.text}".`, "info");
657
+ goal = undefined;
658
+ return;
659
+ }
660
+ try {
661
+ pi.sendMessage(
662
+ {
663
+ customType: "sera-goal",
664
+ content: goalNudge(goal),
665
+ display: false,
666
+ details: { iterations: goal.iterations },
667
+ },
668
+ { deliverAs: "followUp", triggerTurn: true },
669
+ );
670
+ } catch {
671
+ goal = undefined; // oturum kapanmış: modu bırak
672
+ }
673
+ });
674
+ // goal_done yalnız /goal etkinken modele gider (soğuk başlangıçta şema yükü yok).
675
+ const syncGoalTool = () => {
676
+ const active = pi.getActiveTools();
677
+ const want = !!goal && !goal.done;
678
+ const has = active.includes("goal_done");
679
+ if (want && !has) pi.setActiveTools([...active, "goal_done"]);
680
+ else if (!want && has) pi.setActiveTools(active.filter((t) => t !== "goal_done"));
681
+ };
682
+ pi.on("session_start", () => syncGoalTool());
683
+ pi.on("before_agent_start", () => {
684
+ syncGoalTool();
685
+ return undefined;
686
+ });
687
+ }
688
+
689
+ regCmd("guven", {
690
+ description: "Sera: bu projeye guven (proje kancalari calisir) | /guven kapat",
691
+ handler: async (args, ctx) => {
692
+ const on = !/^\s*(kapat|hayir|off)\s*$/i.test(args);
693
+ trust.set(ctx.cwd, on);
694
+ hooks = undefined; // bir sonraki cagrida kancalar yeniden yuklenir
695
+ say(
696
+ ctx,
697
+ on
698
+ ? "[Sera] Bu projeye guveniliyor: .sera/hooks.json kancalari calisacak."
699
+ : "[Sera] Bu projeye guven kaldirildi: proje kancalari calismayacak.",
700
+ "info",
701
+ );
702
+ },
703
+ });
704
+ // --- Video araci (web /api/video-studio ile ayni kapi; web=CLI esitligi). Alt ajanda kapali (maliyet/kota ust ajanda).
705
+ if (process.env[SUBAGENT_DEPTH_ENV] !== "1") registerVideoTool(pi);
706
+ if (process.env[SUBAGENT_DEPTH_ENV] !== "1") registerVideoEditTool(pi);
707
+ if (process.env[SUBAGENT_DEPTH_ENV] !== "1") registerImageTool(pi);
708
+ if (process.env[SUBAGENT_DEPTH_ENV] !== "1") registerIosBuildTool(pi);
709
+ // --- Arac esitligi: glob/grep/ls (saf Node, dogrudan) + web_fetch/web_search (tembel). Alt ajanda da gerekli (Explore/Plan).
710
+ registerFsTools(pi);
711
+ registerWebTools(pi);
712
+ // --- Uygulama Ustasi: app_verify (gercek calistirip dogrula) + open_app (varsayilan tarayicida ac). SERA_USTA=0 kapatir.
713
+ if (process.env[SUBAGENT_DEPTH_ENV] !== "1" && process.env.SERA_USTA !== "0")
714
+ registerAppTools(pi, {
715
+ offer: async (cwd) => {
716
+ const r = await githubYedek(
717
+ "durum",
718
+ cwd,
719
+ realAkisDeps(cwd, { entry: process.env.SERA_PI_ENTRY ?? process.argv[1] ?? "", args: [] }),
720
+ );
721
+ return r.status === "ask" ? r.text : undefined;
722
+ },
723
+ });
724
+ if (process.env[SUBAGENT_DEPTH_ENV] !== "1") registerNotebookTool(pi);
725
+ registerResearchTools(pi); // alt ajan da kendi scratchpad'ine yazar
726
+ if (process.env[SUBAGENT_DEPTH_ENV] !== "1") registerResearchWorkflowTools(pi);
727
+ if (process.env[SUBAGENT_DEPTH_ENV] !== "1") registerTuvalTool(pi);
728
+ // --- Dogal-dil yol: "GitHub projemi takip et", "bitene kadar uğraş" gibi istekler komutsuz (sera_islem + github_ajan).
729
+ if (process.env[SUBAGENT_DEPTH_ENV] !== "1") registerDogalTools(pi, { handlers: cmdHandlers });
730
+ // --- D1-8: yapilacaklar listesi + kullaniciya soru (yalniz ust ajan)
731
+ if (process.env[SUBAGENT_DEPTH_ENV] !== "1") registerTodoQuestion(pi);
732
+ if (process.env[SUBAGENT_DEPTH_ENV] !== "1")
733
+ registerZeroKnowledge(pi, { blocked: () => haltReported || goalRunning() });
734
+
735
+ const PARALLEL_GUIDELINE = "Batch independent tool calls (esp. read-only) in one response; they run in parallel.";
736
+ // --- D1-6: kural zinciri siniri + kalici bellek (her calistirmada sistem istemine; motorun zinciri korunur)
737
+ const seraHome = process.env.SERA_MEMORY_DIR || join(homedir(), ".sera");
738
+ const tokenEnv = (name: string, d: number) => {
739
+ const n = Number(process.env[name]);
740
+ return Number.isFinite(n) && n > 0 ? n : d;
741
+ };
742
+ // 0 gecerli deger (kapali): tokenEnv gibi ama 0'i korur
743
+ const tokenEnvOr = (name: string, d: number) => {
744
+ const raw = process.env[name];
745
+ if (raw === undefined || raw === "") return d;
746
+ const n = Number(raw);
747
+ return Number.isFinite(n) && n >= 0 ? n : d;
748
+ };
749
+ const builtinSkillsDir = join(dirname(fileURLToPath(import.meta.url)), "..", "skills");
750
+ let capWarned = false;
751
+ const repoMapCache = new Map<string, ContextFile | null>();
752
+ // Fable #14: şüpheli (enjeksiyon) durumu alt ajana taşınır; E2 bloğu açıksa gerçek izleyiciye bağlanır.
753
+ let taintActiveNow = (): boolean => process.env.SERA_TAINTED === "1";
754
+ // --- D2-1: özel alt ajan .md tanımları (cwd başına bir kez yüklenir). Alt ajanın kendisinde (depth=1) tanıtım yok.
755
+ const agentsCache = new Map<string, AgentDef[]>();
756
+ const getAgents = (cwd: string): AgentDef[] => {
757
+ let a = agentsCache.get(cwd);
758
+ if (!a) {
759
+ a = loadAgents(cwd, seraHome, { projectTrusted: trust.has(cwd) });
760
+ agentsCache.set(cwd, a);
761
+ }
762
+ return a;
763
+ };
764
+ let agentToolsApplied = false;
765
+ pi.on("before_agent_start", (event, ctx) => {
766
+ const opts = event.systemPromptOptions as {
767
+ contextFiles?: { path: string; content: string }[];
768
+ promptGuidelines?: string[];
769
+ };
770
+ // D1-9 paralel okuma: motor ayni yanittaki araclari eszamanli calistirir; model bunu kullansin
771
+ if (!opts.promptGuidelines?.includes(PARALLEL_GUIDELINE))
772
+ opts.promptGuidelines = [...(opts.promptGuidelines ?? []), PARALLEL_GUIDELINE];
773
+ const r = applyRulesMemory(opts.contextFiles ?? [], {
774
+ home: seraHome,
775
+ cwd: ctx.cwd,
776
+ maxRuleTokens: tokenEnv("SERA_RULES_MAX_TOKENS", 6000),
777
+ maxMemoryTokens: tokenEnv("SERA_MEMORY_MAX_TOKENS", 1500),
778
+ });
779
+ opts.contextFiles = r.files;
780
+ // --- D2-7: depo haritası (opt-in; oturum/cwd başına bir kez üretilir, sonra önbellekten)
781
+ if (cfg.repoMap.enabled) {
782
+ let rm = repoMapCache.get(ctx.cwd);
783
+ if (rm === undefined) {
784
+ rm = buildRepoMap(ctx.cwd, { maxTokens: cfg.repoMap.maxTokens }) ?? null;
785
+ repoMapCache.set(ctx.cwd, rm);
786
+ }
787
+ if (rm) opts.contextFiles = [...opts.contextFiles, rm];
788
+ }
789
+ // --- D2-1: alt ajan ise ve 'tools' allowlist'i verildiyse aktif araçları bir kez DARALT (güvenlik)
790
+ if (process.env[SUBAGENT_DEPTH_ENV] === "1" && process.env[AGENT_TOOLS_ENV] && !agentToolsApplied) {
791
+ agentToolsApplied = true;
792
+ const allow = process.env[AGENT_TOOLS_ENV]!.split(",")
793
+ .map((s) => s.trim())
794
+ .filter(Boolean);
795
+ const keep = restrictTools(
796
+ allow,
797
+ (pi.getAllTools() as { name: string }[]).map((t) => t.name),
798
+ );
799
+ if (keep) pi.setActiveTools(keep);
800
+ } else if (process.env[SUBAGENT_DEPTH_ENV] !== "1") {
801
+ // --- D2-1: üst ajana özel ajanları tanıt (yalnız ad + açıklama; içerik task seçince enjekte edilir)
802
+ const adv = agentsSystemText(getAgents(ctx.cwd));
803
+ if (adv) opts.contextFiles = [...opts.contextFiles, { path: "(Sera özel ajanlar)", content: adv }];
804
+ }
805
+ // Kimlik (sahip 2026-11-12): "hangi modelsin" sorusu icin modelin Sera adi istemin SONUNDA (onbellek dostu); model env dokmez.
806
+ {
807
+ const id = String((ctx as { model?: { id?: string } }).model?.id ?? "");
808
+ const label = SERA_MODEL_LABELS[id.replace(/^sera\//, "")];
809
+ if (label) {
810
+ const o = opts as { sections?: Record<string, string> };
811
+ o.sections = { ...(o.sections ?? {}), kimlik: `Sera model: ${label}` };
812
+ }
813
+ }
814
+ // Beceri dizini butcesi (SERA_SKILLS_MAX_TOKENS, vars. 1500; 0 = motorun tam XML dizini): adlar hep var, aciklamalar kisalir.
815
+ const skills = (opts as { skills?: SkillLike[]; sections?: Record<string, string> }).skills;
816
+ if (skills?.length) {
817
+ const text = compactSkillsSection(skills, {
818
+ maxTokens: tokenEnvOr("SERA_SKILLS_MAX_TOKENS", DEFAULT_SKILLS_MAX_TOKENS),
819
+ priorityDirs: [join(seraHome, "skills"), join(ctx.cwd, ".sera", "skills"), builtinSkillsDir],
820
+ builtinDir: builtinSkillsDir,
821
+ collapseOver: tokenEnvOr("SERA_SKILLS_COLLAPSE_OVER", DEFAULT_SKILLS_COLLAPSE_OVER),
822
+ });
823
+ if (text !== undefined) {
824
+ const o = opts as { skills: SkillLike[]; sections?: Record<string, string> };
825
+ o.sections = { ...(o.sections ?? {}), skills: text };
826
+ o.skills = [];
827
+ }
828
+ }
829
+ if (!capWarned && (r.truncated.length || r.dropped.length)) {
830
+ capWarned = true;
831
+ say(
832
+ ctx,
833
+ `[Sera KURAL] Kural dosyalari bagalam sinirini asti; kisaltilan: ${r.truncated.length}, atlanan: ${r.dropped.length} (en uzak klasordekiler once).`,
834
+ "warning",
835
+ );
836
+ }
837
+ return undefined;
838
+ });
839
+ regCmd(MEMORY_COMMAND, {
840
+ description: "Sera: kalici not ekle (bu proje) | /hatirla genel <metin> (tum projeler)",
841
+ handler: async (args, ctx) => {
842
+ const m = /^\s*(genel|kullanici|kullanıcı)\s+([\s\S]*)$/i.exec(args);
843
+ const paths = memoryPaths(seraHome, ctx.cwd);
844
+ const store = new MemoryStore(m ? paths.user : paths.project, process.env.SERA_MEMORY_WRITE !== "0");
845
+ try {
846
+ const line = store.add(m ? m[2]! : args);
847
+ say(ctx, `[Sera] Hatirlandi (${m ? "tum projeler" : "bu proje"}): ${line.replace(/^- /, "")}`, "info");
848
+ } catch (e) {
849
+ say(ctx, `[Sera] ${e instanceof Error ? e.message : String(e)}`, "error");
850
+ }
851
+ },
852
+ });
853
+
854
+ // /limit, /kullanim: kullanim sayfasiyla ayni bilgi (sunucu /api/usage); modele gitmez.
855
+ registerLimitCommand(pi, regCmd, say);
856
+ regCmd("bellek", {
857
+ description: "Sera: kalici notlari listele (bu proje + tum projeler)",
858
+ handler: async (args, ctx) => {
859
+ const paths = memoryPaths(seraHome, ctx.cwd);
860
+ const ed = /^\s*(?:duzenle|düzenle)\s+(?:(genel|kullanici|kullanıcı)\s+)?(\S+)\s+([\s\S]*)$/i.exec(args);
861
+ if (/^\s*(?:duzenle|düzenle)(?:\s|$)/i.test(args)) {
862
+ if (!ed) {
863
+ say(ctx, "[Sera] Kullanım: /bellek duzenle <no> <metin> | /bellek duzenle genel <no> <metin>", "error");
864
+ return;
865
+ }
866
+ try {
867
+ const store = new MemoryStore(ed[1] ? paths.user : paths.project, process.env.SERA_MEMORY_WRITE !== "0");
868
+ const line = store.update(ed[2]!, ed[3]!);
869
+ say(ctx, `[Sera] Güncellendi (${ed[1] ? "tum projeler" : "bu proje"}): ${line}`, "info");
870
+ } catch (e) {
871
+ say(ctx, `[Sera] ${e instanceof Error ? e.message : String(e)}`, "error");
872
+ }
873
+ return;
874
+ }
875
+ say(
876
+ ctx,
877
+ `[Sera] ${memoryListText(new MemoryStore(paths.project).lines(), new MemoryStore(paths.user).lines())}`,
878
+ "info",
879
+ );
880
+ },
881
+ });
882
+ regCmd("unut", {
883
+ description: "Sera: kalici notu sil — /unut <no> | /unut hepsi | /unut genel <no>",
884
+ handler: async (args, ctx) => {
885
+ const m = /^\s*(genel|kullanici|kullanıcı)\s+([\s\S]*)$/i.exec(args);
886
+ const paths = memoryPaths(seraHome, ctx.cwd);
887
+ const store = new MemoryStore(m ? paths.user : paths.project, process.env.SERA_MEMORY_WRITE !== "0");
888
+ try {
889
+ const removed = store.forget(m ? m[2]! : args);
890
+ say(ctx, `[Sera] Silindi (${m ? "tum projeler" : "bu proje"}): ${removed.length} not`, "info");
891
+ } catch (e) {
892
+ say(ctx, `[Sera] ${e instanceof Error ? e.message : String(e)}`, "error");
893
+ }
894
+ },
895
+ });
896
+
897
+ // --- D1-7: beceri klasorleri (~/.sera/skills, <proje>/.sera/skills) + disallowed-tools kisiti
898
+ // Yerlesik beceriler (packages/sera-core/skills: reverse-engineer-anything ...): baglamda yalniz ad+aciklama, icerik gerekince.
899
+ const builtinSkills = join(dirname(fileURLToPath(import.meta.url)), "..", "skills");
900
+ pi.on("resources_discover", (event) => ({
901
+ skillPaths: [...(existsSync(builtinSkills) ? [builtinSkills] : []), ...skillDirs(seraHome, event.cwd)],
902
+ }));
903
+ const skillGuard = new SkillGuard();
904
+ pi.on("before_agent_start", (event) => {
905
+ skillGuard.reset();
906
+ research.reset();
907
+ if (event.messageType === "user") {
908
+ skillGuard.fromPrompt(event.prompt);
909
+ if (event.prompt.includes(`<skill name="${RESEARCH_SKILL}"`)) research.activate();
910
+ }
911
+ return undefined;
912
+ });
913
+ // --- Teslim sozlesmesi (dahili test): program/proje isteginde SKILL govdesi bu isteme tembel eklenir (her turda degil).
914
+ const teslimGate = new TeslimGate();
915
+ pi.on("session_start", () => {
916
+ teslimGate.reset();
917
+ });
918
+ pi.on("before_agent_start", (event) => {
919
+ if (event.messageType !== "user" || process.env.SERA_TESLIM === "0") return undefined;
920
+ if (process.env[SUBAGENT_DEPTH_ENV] === "1") return undefined;
921
+ const text = teslimGate.onUserTurn(event.prompt, () => loadTeslimBody());
922
+ return text ? { message: { customType: TESLIM_CUSTOM_TYPE, content: text, display: false } } : undefined;
923
+ });
924
+ callSteps.push({
925
+ name: "skill",
926
+ run: (event, ctx) => {
927
+ const reason = skillGuard.check(event.toolName, event.input, ctx.cwd);
928
+ return reason ? { block: true, reason } : undefined;
929
+ },
930
+ });
931
+
932
+ callSteps.push({
933
+ name: "research",
934
+ run: (event) => {
935
+ const reason = research.onToolCall(event.toolName, event.input);
936
+ return reason ? { block: true, reason } : undefined;
937
+ },
938
+ });
939
+
940
+ callSteps.push({ name: "hooks", run: (event, ctx) => hooksFor(ctx).pre(event.toolName, event.input) });
941
+ pi.on("agent_end", async (_e, ctx) => {
942
+ await hooksFor(ctx).stop();
943
+ });
944
+
945
+ // --- Izin koprusu. SERA_PERMISSIONS=1 iken tam kapi (Sera Code Pi adaptoru verir). Degilse yine de
946
+ // DISARI GONDERIM kapisi HER ZAMAN calisir (sera run / -p, alt ajan, yolo, test-duzelt dahil): bu soru atlanamaz.
947
+ {
948
+ const full = process.env.SERA_PERMISSIONS === "1";
949
+ const _pt = process.env.SERA_PERMISSION_TIMEOUT_MS;
950
+ const permAskTimeoutMs =
951
+ _pt !== undefined && _pt.trim() !== "" && Number.isFinite(Number(_pt)) ? Number(_pt) : 600_000;
952
+ const gate = new PermissionGate(full ? parsePermissionTools(process.env.SERA_PERMISSION_TOOLS) : new Set(), {
953
+ egressOnly: !full,
954
+ egressAllow: loadEgressAllow(),
955
+ askTimeoutMs: permAskTimeoutMs, // donma önleme: izin sorusu yanıtsız kalırsa 10 dk sonra güvenli reddet
956
+
957
+ resolveRemote: (name, cwd) => {
958
+ try {
959
+ const r = execFileSync("git", ["remote", "get-url", name || "origin"], {
960
+ cwd,
961
+ timeout: 2000,
962
+ windowsHide: true,
963
+ stdio: ["ignore", "pipe", "ignore"],
964
+ });
965
+ return r.toString().trim() || undefined;
966
+ } catch {
967
+ return undefined;
968
+ }
969
+ },
970
+ });
971
+ callSteps.push({
972
+ name: "permission",
973
+ run: (event, ctx) =>
974
+ gate.check(
975
+ event.toolName,
976
+ event.toolCallId,
977
+ event.input,
978
+ ctx.hasUI ? { select: (t, o) => ctx.ui.select(t, o) } : undefined,
979
+ { cwd: ctx.cwd },
980
+ ),
981
+ });
982
+
983
+ // --- E1: OS sandbox (varsayılan AÇIK; SERA_SANDBOX=0 kapatır). Kabuk komutu (bash/proc start) sandbox içinde çalışır.
984
+ // Tembel: modül yalnız İLK kabuk komutunda yüklenir. Kaçış: komutun başına `SERA_UNSANDBOXED=1 ` -> kullanıcıya
985
+ // mevcut izin penceresiyle sorulur (onay yoksa/arayüz yoksa ÇALIŞMAZ).
986
+ if (cfg.sandbox.enabled) {
987
+ let runner: SandboxRunner | undefined;
988
+ let noticed = false;
989
+ const unsandboxedIds = new Set<string>();
990
+ const sandboxedIds = new Set<string>();
991
+ // Fable #15: app_verify'in command / serve_command alanlari da kabukta calisir → ayni sandbox'a girer.
992
+ type ShellSlot = { command: string; set: (c: string) => void };
993
+ const shellCommands = (event: ToolCallEvent): ShellSlot[] => {
994
+ const input = event.input as Record<string, unknown> | undefined;
995
+ if (!input) return [];
996
+ const slot = (key: string): ShellSlot[] =>
997
+ typeof input[key] === "string" && (input[key] as string).trim()
998
+ ? [
999
+ {
1000
+ command: input[key] as string,
1001
+ set: (c) => {
1002
+ input[key] = c;
1003
+ },
1004
+ },
1005
+ ]
1006
+ : [];
1007
+ if (event.toolName === "bash" || event.toolName === "powershell") return slot("command");
1008
+ if (event.toolName === "proc" && input.action === "start") return slot("command");
1009
+ if (event.toolName === "app_verify") return [...slot("command"), ...slot("serve_command")];
1010
+ return [];
1011
+ };
1012
+ callSteps.push({
1013
+ name: "sandbox-mark",
1014
+ run: (event) => {
1015
+ for (const sc of shellCommands(event)) {
1016
+ const p = parseUnsandboxed(sc.command);
1017
+ if (p.unsandboxed) {
1018
+ unsandboxedIds.add(event.toolCallId);
1019
+ sc.set(p.command); // sonraki politikalar TEMİZ komutu görür
1020
+ }
1021
+ }
1022
+ return undefined;
1023
+ },
1024
+ });
1025
+ callSteps.push({
1026
+ name: "sandbox",
1027
+ run: async (event, ctx) => {
1028
+ const scs = shellCommands(event);
1029
+ if (!scs.length) return undefined;
1030
+ if (unsandboxedIds.delete(event.toolCallId)) {
1031
+ const denied = await gate.askUnsandboxed(
1032
+ event.toolName,
1033
+ event.toolCallId,
1034
+ event.input,
1035
+ ctx.hasUI ? { select: (t, o) => ctx.ui.select(t, o) } : undefined,
1036
+ );
1037
+ return denied; // onaylandıysa komut olduğu gibi (sandbox'sız) çalışır
1038
+ }
1039
+ runner ??= new SandboxRunner(cfg.sandbox, { cwd: ctx.cwd });
1040
+ const wraps: Awaited<ReturnType<SandboxRunner["wrap"]>>[] = [];
1041
+ for (const sc of scs)
1042
+ wraps.push(await runner.wrap(sc.command, event.toolName === "powershell" ? "powershell" : "bash"));
1043
+ const r = wraps.find((w) => !w.sandboxed) ?? wraps[0]!;
1044
+ if (!r.sandboxed) {
1045
+ if (!noticed) {
1046
+ noticed = true;
1047
+ say(
1048
+ ctx,
1049
+ `[Sera sandbox] Sandbox kullanılamıyor (${r.reason ?? "bilinmeyen neden"}); kabuk komutları KISITSIZ çalışıyor: dosya yazma/okuma ve ağ sandbox tarafından sınırlanmıyor. Hâlâ geçerli: izin penceresi (SERA_PERMISSIONS=1), tehlikeli komut/korumalı yol engeli, dışarı-gönderim sorusu, onay modları. Sandbox'ı bilerek kapatmak için SERA_SANDBOX=0.`,
1050
+ "warning",
1051
+ );
1052
+ }
1053
+ return undefined;
1054
+ }
1055
+ for (const [i, sc] of scs.entries()) sc.set(wraps[i]!.wrapped);
1056
+ sandboxedIds.add(event.toolCallId);
1057
+ return undefined;
1058
+ },
1059
+ });
1060
+ resultSteps.push({
1061
+ name: "sandbox",
1062
+ run: (event) => {
1063
+ if (!sandboxedIds.delete(event.toolCallId) || !event.isError) return undefined;
1064
+ const text = contentText(event.content);
1065
+ if (!looksSandboxDenied(text)) return undefined;
1066
+ return { content: [...event.content, { type: "text" as const, text: SANDBOX_HINT }] };
1067
+ },
1068
+ });
1069
+ pi.on("session_shutdown", async () => {
1070
+ await runner?.shutdown();
1071
+ });
1072
+ }
1073
+
1074
+ const uiOf = (ctx: ExtensionContext) =>
1075
+ ctx.hasUI ? { select: (t: string, o: string[]) => ctx.ui.select(t, o) } : undefined;
1076
+
1077
+ // --- E4: proje disi dosya onayi (SERA_WORKSPACE_GUARD=0 kapatir; SERA_ALLOW_PATHS ek izinli klasorler)
1078
+ callSteps.push({
1079
+ name: "workspace-guard",
1080
+ run: (event, ctx) => {
1081
+ if (process.env.SERA_WORKSPACE_GUARD === "0") return undefined;
1082
+ const f = checkOutside(ctx.cwd, event.toolName, event.input, { extraRoots: extraRootsFromEnv() });
1083
+ if (!f) return undefined;
1084
+ return gate.confirm(event.toolName, event.toolCallId, event.input, uiOf(ctx), "edit", f.reason, {
1085
+ sticky: f.sensitive,
1086
+ key: f.sensitive ? undefined : `outside:${dirname(f.path)}`,
1087
+ });
1088
+ },
1089
+ });
1090
+
1091
+ // --- E2: guvenilmez arac ciktisi isaretleme + enjeksiyon tarama + supheli icerik sonrasi riskli eylem onayi
1092
+ const untrustedOn = process.env.SERA_UNTRUSTED !== "0";
1093
+ const taintTurns = Number(process.env.SERA_TAINT_TURNS);
1094
+ const taint = new TaintTracker(Number.isFinite(taintTurns) && taintTurns > 0 ? taintTurns : undefined);
1095
+ // Fable #14: şüpheli üst ajandan başlatılan alt ajan şüpheli başlar; işaret sıkıştırmada söner; task'a taşınır.
1096
+ if (process.env.SERA_TAINTED === "1") taint.mark(["ust-ajan-supheli"], "ust ajan");
1097
+ taintActiveNow = () => taint.active;
1098
+ pi.on("session_compact", () => taint.clear());
1099
+ pi.on("before_agent_start", (event) => {
1100
+ if (!untrustedOn) return undefined;
1101
+ const opts = event.systemPromptOptions as { promptGuidelines?: string[] };
1102
+ if (!opts.promptGuidelines?.includes(UNTRUSTED_RULE))
1103
+ opts.promptGuidelines = [...(opts.promptGuidelines ?? []), UNTRUSTED_RULE];
1104
+ return undefined;
1105
+ });
1106
+ resultSteps.push({
1107
+ name: "untrusted",
1108
+ run: (event, ctx) => {
1109
+ if (!untrustedOn || !isUntrustedSource(event.toolName, event.input, ctx.cwd)) return undefined;
1110
+ const parts = event.content as { type: string; text?: string }[];
1111
+ const ids = scanInjection(contentText(event.content));
1112
+ const wrapped = wrapUntrusted(event.toolName, parts);
1113
+ if (ids.length) {
1114
+ taint.mark(ids, event.toolName);
1115
+ say(
1116
+ ctx,
1117
+ `[Sera GUVENLIK] '${event.toolName}' ciktisinda prompt-injection belirtisi: ${ids.join(", ")}`,
1118
+ "warning",
1119
+ );
1120
+ pi.appendEntry("sera-injection-flag", { tool: event.toolName, patterns: ids });
1121
+ wrapped.push({ type: "text", text: injectionWarning(ids, event.toolName) });
1122
+ }
1123
+ if (wrapped === parts) return undefined;
1124
+ return { content: wrapped as unknown as ToolResultEvent["content"] };
1125
+ },
1126
+ });
1127
+ callSteps.push({
1128
+ name: "taint-guard",
1129
+ run: (event, ctx) => {
1130
+ if (!taint.active) return undefined;
1131
+ const r = riskAfterTaint(event.toolName, event.input, ctx.cwd);
1132
+ if (!r) return undefined;
1133
+ const why = `${r.reason} (kaynak: ${taint.source}, kalıp: ${taint.patterns.join(", ")})`;
1134
+ return gate.confirm(event.toolName, event.toolCallId, event.input, uiOf(ctx), r.kind, why, {
1135
+ sticky: true,
1136
+ egress: r.kind !== "edit",
1137
+ });
1138
+ },
1139
+ });
1140
+ pi.on("turn_end", () => taint.tick());
1141
+ }
1142
+
1143
+ // --- E5: "ilerleme yok" tespiti (SERA_NOPROGRESS_TURNS, 0 = kapali)
1144
+ {
1145
+ const np = new NoProgress();
1146
+ let pendingNote: string | undefined;
1147
+ pi.on("turn_end", (event, ctx) => {
1148
+ const msg = event.message as { content?: unknown };
1149
+ const parts = Array.isArray(msg.content) ? (msg.content as Record<string, unknown>[]) : [];
1150
+ const info: TurnInfo = {
1151
+ text: parts
1152
+ .filter((c) => c.type === "text")
1153
+ .map((c) => String(c.text ?? ""))
1154
+ .join(" "),
1155
+ calls: parts
1156
+ .filter((c) => c.type === "toolCall")
1157
+ .map((c) => ({ id: String(c.id), name: String(c.name), input: c.arguments })),
1158
+ results: event.toolResults.map((r) => ({
1159
+ id: r.toolCallId,
1160
+ name: r.toolName,
1161
+ isError: r.isError,
1162
+ text: contentText(r.content).replace(UNTRUSTED_TAGS, ""),
1163
+ })),
1164
+ };
1165
+ const spoke = brakeSpoke;
1166
+ brakeSpoke = false;
1167
+ if (info.calls.length === 0) return;
1168
+ const r = np.endTurn(info, spoke);
1169
+ if (r.level === "note") pendingNote = noProgressNote(r.stalled);
1170
+ else if (r.level === "stop") {
1171
+ const text = noProgressStop(r.stalled, r.summary);
1172
+ say(ctx, text, "error");
1173
+ pi.appendEntry("sera-noprogress-stop", { stalled: r.stalled, summary: r.summary });
1174
+ ctx.abort();
1175
+ }
1176
+ });
1177
+ resultSteps.push({
1178
+ name: "no-progress",
1179
+ run: (event) => {
1180
+ if (!pendingNote) return undefined;
1181
+ const note = pendingNote;
1182
+ pendingNote = undefined;
1183
+ return {
1184
+ content: [
1185
+ ...event.content,
1186
+ {
1187
+ type: "text" as const,
1188
+ text: `
1189
+ ${note}`,
1190
+ },
1191
+ ],
1192
+ };
1193
+ },
1194
+ });
1195
+ }
1196
+
1197
+ // --- Eylem hatırlatması + akış bekçisi (sahip şikâyeti: "devam ediyorum" deyip durma; kök neden raporu: action-nudge.ts).
1198
+ // (a) tur araç çağrısı olmadan "şimdi yapıyorum/yapacağım" diyerek bittiyse: kullanıcı istemi başına en fazla N (2) otomatik takip;
1199
+ // (c) yanıt uzunluk sınırında kesildiyse (stopReason=length) aynı takip, kod dökmeden araçla yazdırır;
1200
+ // (b) akıştan SERA_STREAM_IDLE_S sn (90) hiç veri gelmezse istek iptal edilir, bir kez yeniden denenir, sonra düz Türkçe söylenir.
1201
+ // Döngü freni / ilerleme-yok / bütçe durdurmaları abort verir (stopReason=aborted): burada dürtülmez. SERA_ACTION_NUDGE=0 kapatır.
1202
+ {
1203
+ const idle = new IdleWatch(actionCfg.idleSeconds * 1000);
1204
+ let idleAborted = false;
1205
+ // abort sonrası motor kuyruktaki takibi işlemez (_agentRunAbortRequested): yeniden deneme agent_settled'da yeni koşu olarak başlar.
1206
+ let idleRetryPending = false;
1207
+ let timer: ReturnType<typeof setInterval> | undefined;
1208
+ const stopTimer = () => {
1209
+ if (timer) clearInterval(timer);
1210
+ timer = undefined;
1211
+ idle.disarm();
1212
+ };
1213
+ pi.on("context", () => {
1214
+ idle.arm();
1215
+ return undefined;
1216
+ });
1217
+ pi.on("message_start", () => idle.touch());
1218
+ pi.on("message_update", () => idle.touch());
1219
+ pi.on("message_end", (event) => {
1220
+ if ((event.message as { role?: string }).role === "assistant") idle.disarm();
1221
+ });
1222
+ pi.on("agent_start", (_e, ctx) => {
1223
+ idleAborted = false;
1224
+ if (actionCfg.idleSeconds <= 0 || timer) return;
1225
+ timer = setInterval(
1226
+ () => {
1227
+ if (!idle.expired()) return;
1228
+ idle.disarm();
1229
+ idleAborted = true;
1230
+ try {
1231
+ say(
1232
+ ctx,
1233
+ `[Sera] Sağlayıcıdan ${actionCfg.idleSeconds} sn veri gelmedi; takılan istek iptal ediliyor, yeniden denenecek.`,
1234
+ "warning",
1235
+ );
1236
+ pi.appendEntry("sera-stream-idle", { seconds: actionCfg.idleSeconds });
1237
+ ctx.abort();
1238
+ } catch {
1239
+ // Oturum degisti/yenilendi: ctx/pi bayat (assertActive firlatir); zamanlayicida yakalanmayan istisna motoru dusurur.
1240
+ stopTimer();
1241
+ }
1242
+ },
1243
+ Math.max(200, Math.min(2000, Math.floor((actionCfg.idleSeconds * 1000) / 3))),
1244
+ );
1245
+ timer.unref?.();
1246
+ });
1247
+ pi.on("session_shutdown", () => stopTimer());
1248
+ pi.on("agent_settled", () => {
1249
+ if (!idleRetryPending) return;
1250
+ idleRetryPending = false;
1251
+ pi.appendEntry("sera-action-nudge", { kind: "idle", n: actionNudge.idleRetriesUsed });
1252
+ try {
1253
+ pi.sendMessage(
1254
+ { customType: "sera-action-nudge", content: IDLE_NUDGE, display: false, details: { kind: "idle" } },
1255
+ { triggerTurn: true },
1256
+ );
1257
+ } catch {
1258
+ // oturum kapanmış
1259
+ }
1260
+ });
1261
+ pi.on("agent_end", (e, ctx) => {
1262
+ stopTimer();
1263
+ if (process.env[SUBAGENT_DEPTH_ENV] === "1" || haltReported || goalRunning()) return;
1264
+ const last = [...e.messages].reverse().find((m) => (m as { role?: string }).role === "assistant");
1265
+ const send = (text: string, kind: string, n: number) => {
1266
+ pi.appendEntry("sera-action-nudge", { kind, n });
1267
+ try {
1268
+ pi.sendMessage(
1269
+ { customType: "sera-action-nudge", content: text, display: false, details: { kind, n } },
1270
+ { deliverAs: "followUp", triggerTurn: true },
1271
+ );
1272
+ } catch {
1273
+ // oturum kapanmış
1274
+ }
1275
+ };
1276
+ if (idleAborted) {
1277
+ idleAborted = false;
1278
+ if (actionNudge.takeIdle()) idleRetryPending = true;
1279
+ else say(ctx, exhaustedMessage("idle", actionNudge.idleRetriesUsed + 1), "error");
1280
+ return;
1281
+ }
1282
+ if (!actionCfg.enabled) return;
1283
+ const end = classifyEnd(last);
1284
+ if (end.kind === "none") return;
1285
+ if (actionNudge.take()) {
1286
+ const what =
1287
+ end.kind === "truncated" ? "yanıtı ortada kesildi" : "'devam ediyorum' dedi ama araç çağırmadı";
1288
+ say(ctx, `[Sera] Model ${what}; otomatik hatırlatma (${actionNudge.nudges}/${actionCfg.max}).`, "info");
1289
+ send(nudgeText(end.kind), end.kind, actionNudge.nudges);
1290
+ } else {
1291
+ say(ctx, exhaustedMessage(end.kind, actionNudge.nudges), "error");
1292
+ }
1293
+ });
1294
+ }
1295
+
1296
+ // --- D1-2 anlik kopya / geri al: her turun ilk degistiren cagrisindan once kopya (SERA_SNAPSHOTS=0 kapatir)
1297
+ if (process.env.SERA_SNAPSHOTS !== "0" && process.env[SUBAGENT_DEPTH_ENV] !== "1") {
1298
+ let turns: TurnSnapshots | undefined;
1299
+ const turnsFor = (ctx: ExtensionContext) => {
1300
+ turns ??= new TurnSnapshots(new SnapshotStore(ctx.cwd, process.env.SERA_SNAPSHOT_DIR || undefined));
1301
+ return turns;
1302
+ };
1303
+ type Entry = { id: string; type: string; customType?: string; data?: unknown; message?: { role?: string } };
1304
+ const userIds = (ctx: ExtensionContext): string[] =>
1305
+ (ctx.sessionManager.getBranch() as Entry[])
1306
+ .filter((e) => e.type === "message" && e.message?.role === "user")
1307
+ .map((e) => e.id);
1308
+ const reply = (ctx: ExtensionContext, data: Record<string, unknown>) => {
1309
+ const text = SNAPSHOT_NOTIFY_PREFIX + JSON.stringify(data);
1310
+ if (ctx.hasUI) ctx.ui.notify(text, data.ok ? "info" : "error");
1311
+ else
1312
+ process.stderr.write(`${text}
1313
+ `);
1314
+ };
1315
+ callSteps.push({
1316
+ name: "checkpoint",
1317
+ run: async (event, ctx) => {
1318
+ await turnsFor(ctx).beforeCall(userIds(ctx).at(-1), event.toolName, event.input);
1319
+ return undefined;
1320
+ },
1321
+ });
1322
+ pi.on("agent_start", (_e, ctx) => turnsFor(ctx).onStart());
1323
+ pi.on("agent_end", async (_e, ctx) => {
1324
+ const t = await turnsFor(ctx).onEnd();
1325
+ if (!t) return;
1326
+ pi.appendEntry(SNAPSHOT_ENTRY, t);
1327
+ // Yalniz dosya degistiren turda (onEnd yalniz o zaman kayit doner): tek satir geri-al ipucu.
1328
+ if (ctx.hasUI) ctx.ui.notify(UNDO_HINT, "info");
1329
+ });
1330
+ const revertCommand: Parameters<typeof pi.registerCommand>[1] = {
1331
+ description:
1332
+ "Sera: secilen mesajdan itibaren turlari ve dosya degisikliklerini geri al (arguman: mesaj sirasi)",
1333
+ handler: async (args, ctx) => {
1334
+ try {
1335
+ const ids = userIds(ctx);
1336
+ const k = Number.parseInt(args.trim(), 10);
1337
+ const target = Number.isInteger(k) ? ids[k] : ids.at(-1);
1338
+ if (!target) throw new Error("Geri alinacak mesaj bulunamadi.");
1339
+ const snaps = (ctx.sessionManager.getEntries() as Entry[])
1340
+ .filter((e) => e.type === "custom" && e.customType === SNAPSHOT_ENTRY)
1341
+ .map((e) => e.data as TurnSnapshot);
1342
+ const report = await turnsFor(ctx).revert(target, ids, snaps, ctx.sessionManager.getLeafId());
1343
+ await ctx.navigateTree(target);
1344
+ reply(ctx, { op: "revert", ok: true, message: restoreSummary(report, "geri alindi"), report });
1345
+ } catch (e) {
1346
+ reply(ctx, { op: "revert", ok: false, message: e instanceof Error ? e.message : String(e) });
1347
+ }
1348
+ },
1349
+ };
1350
+ regCmd(REVERT_COMMAND, revertCommand);
1351
+ regCmd(REVERT_ALIAS, revertCommand);
1352
+ regCmd(UNREVERT_COMMAND, {
1353
+ description: "Sera: son geri almayi yeniden uygula",
1354
+ handler: async (_args, ctx) => {
1355
+ try {
1356
+ const r = await turnsFor(ctx).unrevert();
1357
+ if (!r) throw new Error("Yeniden yapilacak bir geri alma yok.");
1358
+ if (r.leaf) await ctx.navigateTree(r.leaf);
1359
+ reply(ctx, {
1360
+ op: "unrevert",
1361
+ ok: true,
1362
+ message: restoreSummary(r.report, "yeniden uygulandi"),
1363
+ report: r.report,
1364
+ });
1365
+ } catch (e) {
1366
+ reply(ctx, { op: "unrevert", ok: false, message: e instanceof Error ? e.message : String(e) });
1367
+ }
1368
+ },
1369
+ });
1370
+ }
1371
+
1372
+ // --- Tembel yetenekler (SAHIP ILKESI: yalniz ihtiyac olani yukle, is bitince kapat; lazy-capability.ts):
1373
+ // kullanicinin MCP sunuculari + REA acilista surec/sema OLMADAN, tek kucuk giris noktasiyla (mcp__<ad>__lazy) gelir.
1374
+ const lazyIdle = idleFromEnv();
1375
+ const lazyRuntimes = new Map<string, LazyMcpRuntime>();
1376
+ const lazyTools = new Map<string, number>();
1377
+ let statusCtx: ExtensionContext | undefined;
1378
+ let publishMcp: (() => void) | undefined;
1379
+ let reaOpened = false;
1380
+ const reaInstalled = () => !!findRea();
1381
+ const publishRea = () => {
1382
+ const rt = lazyRuntimes.get("rea")?.rt;
1383
+ if (!rt || !statusCtx?.hasUI) return;
1384
+ const running = rt.state === "on" || rt.state === "starting";
1385
+ const state = running ? "running" : reaOpened ? "open" : "off";
1386
+ try {
1387
+ statusCtx.ui.setStatus(
1388
+ REA_STATUS_KEY,
1389
+ REA_STATUS_PREFIX + JSON.stringify({ state, installed: reaInstalled() }),
1390
+ );
1391
+ } catch {
1392
+ // UI yok
1393
+ }
1394
+ };
1395
+ const addLazy = (def: Parameters<typeof makeLazyMcp>[0]) => {
1396
+ const r = makeLazyMcp(def, {
1397
+ idleMs: lazyIdle,
1398
+ onState: (s) => {
1399
+ if (s === "off") lazyTools.delete(def.name);
1400
+ publishRea();
1401
+ publishMcp?.();
1402
+ },
1403
+ });
1404
+ lazyRuntimes.set(def.name, r);
1405
+ pi.registerTool({
1406
+ name: r.toolName,
1407
+ label: def.name,
1408
+ description: r.description,
1409
+ promptSnippet: def.summary ?? `MCP ${def.name} (tembel)`,
1410
+ parameters: Type.Object({
1411
+ action: Type.Optional(Type.String({ description: "groups|tools|schema|call|stop" })),
1412
+ group: Type.Optional(Type.String()),
1413
+ tool: Type.Optional(Type.String()),
1414
+ args: Type.Optional(Type.Any()),
1415
+ }),
1416
+ async execute(_id, params) {
1417
+ const out = await r.execute(params);
1418
+ const n = (r.rt as unknown as { handle?: { tools: unknown[] } }).handle?.tools.length;
1419
+ if (n !== undefined) lazyTools.set(def.name, n);
1420
+ return out;
1421
+ },
1422
+ });
1423
+ return r;
1424
+ };
1425
+ pi.on("session_shutdown", async () => {
1426
+ await Promise.all([...lazyRuntimes.values()].map((r) => r.rt.stop()));
1427
+ });
1428
+ if (reaEnabled()) {
1429
+ addLazy({ ...reaDef(), pin: false });
1430
+ regCmd("rea", {
1431
+ description: "REA (tersine muhendislik) ac | /rea kapat",
1432
+ handler: async (args, ctx) => {
1433
+ statusCtx = ctx;
1434
+ const rt = lazyRuntimes.get("rea")!.rt;
1435
+ if (/^\s*(kapat|off|hayir)\s*$/i.test(args)) {
1436
+ reaOpened = false;
1437
+ await rt.stop();
1438
+ publishRea();
1439
+ if (ctx.hasUI) ctx.ui.notify("◆ REA kapatıldı; araç şemaları bellekten çıktı.", "info");
1440
+ return;
1441
+ }
1442
+ if (!findRea()) {
1443
+ let yes = false;
1444
+ try {
1445
+ yes =
1446
+ ctx.hasUI &&
1447
+ (await ctx.ui.confirm(
1448
+ "REA kurulsun mu?",
1449
+ `rea-agents ${REA_VERSION} (sabit sürüm, kurulum betikleri çalıştırılmaz) genel olarak kurulacak.`,
1450
+ ));
1451
+ } catch {
1452
+ yes = false;
1453
+ }
1454
+ if (!yes) {
1455
+ say(ctx, NOT_INSTALLED_MSG, "warning");
1456
+ return;
1457
+ }
1458
+ const r = installRea();
1459
+ if (!r.ok) {
1460
+ say(ctx, r.message, "error");
1461
+ return;
1462
+ }
1463
+ }
1464
+ reaOpened = true;
1465
+ publishRea();
1466
+ if (ctx.hasUI) ctx.ui.notify(reaGreeting(findRea(), externalTools()), "info");
1467
+ },
1468
+ });
1469
+ }
1470
+
1471
+ // --- MCP koprusu: SERA_MCP_SERVERS (Sera Code adaptoru verir). Varsayilan TEMBEL; `eager:true` ya da SERA_MCP_EXPOSURE ile
1472
+ // acilista Pi'nin yerlesik MCP destegine kayit (asagidaki eski yol).
1473
+ if (process.env.SERA_MCP_SERVERS) {
1474
+ const { servers: all, skipped } = parseMcpServers(process.env.SERA_MCP_SERVERS);
1475
+ // SSRF korumasi: uzak URL'ler DNS cozumlemesinden sonra denetlenir; ozel/loopback/metadata hedefler atlanir.
1476
+ for (const [n, s] of Object.entries(all)) {
1477
+ if (!isRemoteMcp(s)) continue;
1478
+ const v = await checkRemoteMcpUrl(s.url);
1479
+ if (!v.ok) {
1480
+ delete all[n];
1481
+ process.stderr.write(
1482
+ `[Sera MCP] '${n}' engellendi (SSRF korumasi: ${v.reason}). Bilerek kullanacaksan SERA_MCP_ALLOW_HOSTS=<host> ile izin ver.
1483
+ `,
1484
+ );
1485
+ }
1486
+ }
1487
+ const part = partitionMcp(all, process.env.SERA_MCP_EXPOSURE);
1488
+ for (const n of part.lazy) {
1489
+ const s = all[n]! as SeraMcpServer;
1490
+ addLazy({ name: n, spec: s, summary: `MCP sunucusu ${n} (kullanici eklemesi).` });
1491
+ }
1492
+ const servers = Object.fromEntries(part.eager.map((n) => [n, all[n]!]));
1493
+ // Eager yol (D1-9 tembel sema "auto"): araclar deferred kaydedilir; toplam sema esik altindaysa dogrudan bildirilir,
1494
+ // ustundeyse model tool_search ile yukler. SERA_MCP_EXPOSURE=direct|deferred sabitler.
1495
+ const mode = process.env.SERA_MCP_EXPOSURE;
1496
+ const mcpExposure = mode === "direct" ? "direct" : "deferred";
1497
+ if (part.eager.length && mode !== "direct" && mode !== "deferred") {
1498
+ const min = Number(process.env.SERA_MCP_LAZY_MIN_TOKENS) || MCP_LAZY_MIN_TOKENS;
1499
+ const names = Object.keys(servers);
1500
+ const waitMs = Number(process.env.SERA_MCP_WAIT_MS ?? 5000);
1501
+ pi.on("before_agent_start", async () => {
1502
+ // sunucular baglanmadan araclari gorunmez: dogrudan moddaki gibi kisa sure bekle (her sunucudan bir arac)
1503
+ const ready = () => {
1504
+ const tools = pi.getAllTools().map((t) => t.name);
1505
+ return names.every((n) => tools.some((t) => t.startsWith(`mcp__${n}__`)));
1506
+ };
1507
+ for (let t = 0; t < waitMs && !ready(); t += 100) await new Promise((r) => setTimeout(r, 100));
1508
+ const next = mcpAutoActive(pi.getAllTools() as never, pi.getActiveTools(), min);
1509
+ if (next) pi.setActiveTools(next);
1510
+ return undefined;
1511
+ });
1512
+ }
1513
+ for (const [name, s] of Object.entries(servers)) {
1514
+ try {
1515
+ if (isRemoteMcp(s)) {
1516
+ const { oauth, ...rest } = s;
1517
+ pi.registerMcpServer(name, { exposure: mcpExposure, ...rest, ...(oauth ? { oauth } : {}) });
1518
+ } else pi.registerMcpServer(name, { type: "stdio", exposure: mcpExposure, ...s });
1519
+ } catch (e) {
1520
+ process.stderr.write(`[Sera MCP] '${name}' kaydedilemedi: ${e instanceof Error ? e.message : String(e)}\n`);
1521
+ }
1522
+ }
1523
+ for (const name of skipped) process.stderr.write(`[Sera MCP] '${name}' gecersiz yapilandirma, atlandi\n`);
1524
+
1525
+ // Sunucu durumu -> Sera Code /mcp (ui.setStatus, on ek + JSON). Oturum basinda baglanana ya da sure dolana kadar izlenir.
1526
+ const statusWaitMs = Number(process.env.SERA_MCP_STATUS_WAIT_MS ?? 20_000);
1527
+ let lastStatus = "";
1528
+ let watch: ReturnType<typeof setInterval> | undefined;
1529
+ const stopWatch = () => {
1530
+ if (watch) clearInterval(watch);
1531
+ watch = undefined;
1532
+ };
1533
+ const publish = (ctx: ExtensionContext, expired: boolean) => {
1534
+ const st = {
1535
+ ...mcpStatus(
1536
+ Object.keys(servers),
1537
+ skipped,
1538
+ pi.getAllTools().map((t) => t.name),
1539
+ expired,
1540
+ ),
1541
+ ...lazyMcpStatus(
1542
+ part.lazy.map((n) => ({ name: n, state: lazyRuntimes.get(n)!.rt.state, tools: lazyTools.get(n) })),
1543
+ ),
1544
+ };
1545
+ const text = MCP_STATUS_PREFIX + JSON.stringify(st);
1546
+ if (text !== lastStatus && ctx.hasUI) ctx.ui.setStatus(MCP_STATUS_KEY, text);
1547
+ lastStatus = text;
1548
+ return Object.keys(st).length === allCount + skipped.length;
1549
+ };
1550
+ const allCount = Object.keys(all).length;
1551
+ publishMcp = () => {
1552
+ if (statusCtx) publish(statusCtx, !watch);
1553
+ };
1554
+ pi.on("session_start", (_e, ctx) => {
1555
+ statusCtx = ctx;
1556
+ stopWatch();
1557
+ const t0 = Date.now();
1558
+ lastStatus = "";
1559
+ watch = setInterval(() => {
1560
+ const expired = Date.now() - t0 >= statusWaitMs;
1561
+ try {
1562
+ if (publish(ctx, expired) || expired) stopWatch();
1563
+ } catch {
1564
+ // Oturum degisti/yenilendi: eski pi/ctx bayat (assertActive firlatir). Yakalanmayan istisna tum motoru
1565
+ // ("Pi sureci kapandi (kod 1)") dusururdu; izlemeyi birak.
1566
+ stopWatch();
1567
+ }
1568
+ }, 250);
1569
+ watch.unref?.();
1570
+ });
1571
+ // Oturum kapanirken (switch_session/new/fork/reload) izleme zamanlayicisi ve bayat ctx birakilmaz.
1572
+ pi.on("session_shutdown", () => {
1573
+ stopWatch();
1574
+ statusCtx = undefined;
1575
+ });
1576
+ pi.on("before_agent_start", (_e, ctx) => {
1577
+ statusCtx = ctx;
1578
+ publish(ctx, !watch);
1579
+ return undefined;
1580
+ });
1581
+ }
1582
+ pi.on("session_start", (_e, ctx) => {
1583
+ statusCtx = ctx;
1584
+ publishRea();
1585
+ });
1586
+
1587
+ // --- Alt ajan ("task" araci): yalnizca SERA_SUBAGENTS=1 iken ve alt ajanin kendisinde degil
1588
+ if (process.env.SERA_SUBAGENTS === "1" && process.env[SUBAGENT_DEPTH_ENV] !== "1") {
1589
+ const selfPath = fileURLToPath(import.meta.url);
1590
+ type TaskParams = {
1591
+ description: string;
1592
+ prompt: string;
1593
+ subagent_type?: string;
1594
+ fork?: boolean;
1595
+ /** Sera Ofis: rol modeli (yalnız aynı sağlayıcıda; ör. sera-core) ve araç allowlist'i (yalnız daraltır) */
1596
+ model?: string;
1597
+ tools?: string[];
1598
+ /** Sera Ofis çalışanı: yalnız bu dosyalara yazabilir (kodla zorlanır) */
1599
+ yazilabilir?: string[];
1600
+ /** Sera Ofis rolü (şef/danışman kabuğu salt-okunur) ve şefin çalıştırabileceği doğrulama komutu (O11) */
1601
+ ofisRol?: string;
1602
+ ofisKomut?: string[];
1603
+ };
1604
+ type TaskUsage = {
1605
+ input: number;
1606
+ output: number;
1607
+ cacheRead: number;
1608
+ cacheWrite: number;
1609
+ totalTokens: number;
1610
+ cost: { input: number; output: number; cacheRead: number; cacheWrite: number; total: number };
1611
+ };
1612
+ type TaskResult = {
1613
+ content: Array<{ type: "text"; text: string }>;
1614
+ details: unknown;
1615
+ usage: TaskUsage;
1616
+ isError?: boolean;
1617
+ };
1618
+ // Calisan alt ajanlar (on plan + arka plan): her biri baslarken kalan butceden PAY rezerve eder
1619
+ // (cap), harcadikca rezerv erir. Yeni cocuk (kalan - rezerv) / bos yuva alir -> toplam tavan asilmaz.
1620
+ const childSlots = Number(process.env.SERA_BG_MAX) || 3;
1621
+ const reservations = new Set<{ cap: Record<string, number>; used: Record<string, number> }>();
1622
+ const shareOpts = () => {
1623
+ const reserved: Record<string, number> = { usd: 0, turns: 0, uncachedInputTokens: 0 };
1624
+ for (const r of reservations)
1625
+ for (const k of Object.keys(reserved)) reserved[k] += Math.max(0, (r.cap[k] ?? 0) - (r.used[k] ?? 0));
1626
+ return { reserved, slots: childSlots - reservations.size };
1627
+ };
1628
+ const runTask = async (
1629
+ params: TaskParams,
1630
+ signal: AbortSignal | undefined,
1631
+ onUpdate: ((u: { content: Array<{ type: "text"; text: string }>; details: unknown }) => void) | undefined,
1632
+ ctx: ExtensionContext,
1633
+ ): Promise<TaskResult> => {
1634
+ const g = getGovernor(ctx);
1635
+ const budget = childBudget(cfg.budget, g, shareOpts());
1636
+ if (budget.exhausted) {
1637
+ throw new Error(`Butce tavani doldu (${budget.exhausted}); alt ajan baslatilmadi.`);
1638
+ }
1639
+ const id = newChildId();
1640
+ let queue: unknown[] = [];
1641
+ let timer: ReturnType<typeof setTimeout> | undefined;
1642
+ // Alt ajanin toplam harcamasi arac sonucunun `usage`ina yazilir: motorun oturum toplami (get_session_stats)
1643
+ // toolResult usage'ini sayar, boylece ust oturumun harcama gostergesi alt ajani da icerir ve dosyada kalir.
1644
+ const childUsage = {
1645
+ input: 0,
1646
+ output: 0,
1647
+ cacheRead: 0,
1648
+ cacheWrite: 0,
1649
+ totalTokens: 0,
1650
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
1651
+ };
1652
+ const addChildUsage = (u: Partial<typeof childUsage> & { cost?: Partial<typeof childUsage.cost> }) => {
1653
+ for (const k of ["input", "output", "cacheRead", "cacheWrite", "totalTokens"] as const)
1654
+ childUsage[k] += Number(u[k]) || 0;
1655
+ for (const k of ["input", "output", "cacheRead", "cacheWrite", "total"] as const)
1656
+ childUsage.cost[k] += Number(u.cost?.[k]) || 0;
1657
+ };
1658
+ const flush = () => {
1659
+ timer = undefined;
1660
+ const events = queue;
1661
+ queue = [];
1662
+ onUpdate?.({
1663
+ content: [{ type: "text", text: "Alt ajan calisiyor..." }],
1664
+ details: { sera_child: { id, prompt: params.prompt, events } },
1665
+ });
1666
+ };
1667
+ // --- D2-1: subagent_type bir özel ajana karşılıksa rol yönergesini enjekte et, araç allowlist'ini aktar.
1668
+ // NOT: def.model UYGULANMAZ — model zinciri sahibin kararı (agents.ts). Çocuk üst ajanın modelini kullanır.
1669
+ const def = findAgent(getAgents(ctx.cwd), params.subagent_type);
1670
+ const childEnv: Record<string, string | undefined> = {
1671
+ ...budget.env,
1672
+ [SUBAGENT_DEPTH_ENV]: "1",
1673
+ // Fable #14: üst ajan şüpheliyken çocuk da şüpheli başlar.
1674
+ ...(taintActiveNow() ? { SERA_TAINTED: "1" } : {}),
1675
+ // Oturumda verilen /sera-mode durumu alt ajana aynen geçer (salt-okunur/ağ-kapalı delinmez; Fable YÜKSEK 3).
1676
+ SERA_MODE: approval.mode,
1677
+ SERA_NET: approval.net === "block" ? "block" : "ask",
1678
+ };
1679
+ if (def?.tools?.length) childEnv[AGENT_TOOLS_ENV] = def.tools.join(",");
1680
+ if (params.yazilabilir?.length) childEnv[OFIS_YAZ_ENV] = JSON.stringify(params.yazilabilir);
1681
+ if (params.ofisRol) childEnv[OFIS_ROL_ENV] = params.ofisRol;
1682
+ if (params.ofisKomut?.length) childEnv[OFIS_KOMUT_ENV] = JSON.stringify(params.ofisKomut);
1683
+ if (params.tools?.length)
1684
+ childEnv[AGENT_TOOLS_ENV] = (
1685
+ def?.tools?.length ? params.tools.filter((t) => def.tools!.includes(t)) : params.tools
1686
+ ).join(",");
1687
+ const _subT = process.env.SERA_SUBAGENT_TIMEOUT_MS;
1688
+ const subTimeoutMs =
1689
+ _subT !== undefined && _subT.trim() !== "" && Number.isFinite(Number(_subT)) ? Number(_subT) : 1_200_000;
1690
+ const resv = {
1691
+ cap: {
1692
+ usd: Number(budget.env.SERA_BUDGET_USD) || 0,
1693
+ turns: Number(budget.env.SERA_BUDGET_TURNS) || 0,
1694
+ uncachedInputTokens: Number(budget.env.SERA_BUDGET_INPUT_TOKENS) || 0,
1695
+ } as Record<string, number>,
1696
+ used: { usd: 0, turns: 0, uncachedInputTokens: 0 } as Record<string, number>,
1697
+ };
1698
+ reservations.add(resv);
1699
+ const result = await runChild({
1700
+ node: process.execPath,
1701
+ entry: process.env.SERA_PI_ENTRY ?? process.argv[1] ?? "",
1702
+ extensions: [selfPath],
1703
+ cwd: ctx.cwd,
1704
+ args: ctx.model
1705
+ ? [
1706
+ "--provider",
1707
+ ctx.model.provider,
1708
+ "--model",
1709
+ params.model ||
1710
+ (research.active ? process.env.SERA_RESEARCH_SUBAGENT_MODEL : undefined) ||
1711
+ ctx.model.id,
1712
+ ]
1713
+ : [],
1714
+ env: childEnv,
1715
+ // --- D2-1 /fork: fork alt ajanı ebeveyn bağlam özetiyle tohumlanır; özel ajan varsa çerçeve onun üstüne uygulanır
1716
+ prompt: (() => {
1717
+ const base = params.fork
1718
+ ? buildForkPrompt(ctx.sessionManager.getBranch() as unknown as HandoffEntry[], params.prompt)
1719
+ : params.prompt;
1720
+ return def ? framePrompt(def, base) : base;
1721
+ })(),
1722
+ preamble: agent?.current === "plan" ? [`/${AGENT_COMMAND} plan`] : undefined,
1723
+ timeoutMs: subTimeoutMs, // donma önleme: alt ajan en çok bu kadar sürer (SERA_SUBAGENT_TIMEOUT_MS, vars. 20 dk)
1724
+ signal,
1725
+ onEvent: (ev) => {
1726
+ // Alt ajanin her model cagrisi HEMEN ust butceye sayilir (butce kacagi olmasin).
1727
+ if (ev?.type === "message_end" && ev.message?.role === "assistant" && ev.message.usage) {
1728
+ const before = { usd: g.usd, turns: g.turns, uncachedInputTokens: g.uncachedInputTokens };
1729
+ g.record(ev.message.usage);
1730
+ research.recordUsd(g.usd - before.usd);
1731
+ if (research.capReached()) {
1732
+ say(ctx, research.capMessage(), "error");
1733
+ ctx.abort();
1734
+ }
1735
+ resv.used.usd += g.usd - before.usd;
1736
+ resv.used.turns += g.turns - before.turns;
1737
+ resv.used.uncachedInputTokens += g.uncachedInputTokens - before.uncachedInputTokens;
1738
+ addChildUsage(ev.message.usage);
1739
+ // Her cocuk olayinda ust tavan kontrolu: asilirsa ust abort (cocuk signal'i da kesilir), bitisi beklenmez.
1740
+ enforce(ctx);
1741
+ }
1742
+ const slim = slimEvent(ev);
1743
+ if (slim) queue.push(slim);
1744
+ timer ??= setTimeout(flush, 30);
1745
+ },
1746
+ onPermission: async (title, options) => {
1747
+ if (!ctx.hasUI) return undefined;
1748
+ let t = title;
1749
+ try {
1750
+ t =
1751
+ PERMISSION_TITLE_PREFIX +
1752
+ JSON.stringify({ ...JSON.parse(title.slice(PERMISSION_TITLE_PREFIX.length)), child: id });
1753
+ } catch {
1754
+ // bozuk baslik: oldugu gibi
1755
+ }
1756
+ return ctx.ui.select(t, options);
1757
+ },
1758
+ }).finally(() => {
1759
+ reservations.delete(resv);
1760
+ });
1761
+ if (timer) {
1762
+ clearTimeout(timer);
1763
+ flush();
1764
+ }
1765
+ // Ust butce: alt ajan harcamasi sayildi; tavan asildiysa ust ajan da durur.
1766
+ enforce(ctx);
1767
+ const details = { sera_child: { id, done: true, events: [] as unknown[] } };
1768
+ // Hata yollarinda da firlatmak yerine isError: harcama (usage) sonucta kalsin.
1769
+ const fail = (text: string) => ({
1770
+ content: [{ type: "text" as const, text }],
1771
+ details,
1772
+ usage: childUsage,
1773
+ isError: true,
1774
+ });
1775
+ if (result.halted)
1776
+ return fail(
1777
+ `Alt ajan butce tavanina ulasti ve durdu. ${result.text ? `Kismi sonuc: ${result.text}` : ""}`.trim(),
1778
+ );
1779
+ if (result.stopReason === "aborted") return fail("Alt ajan durduruldu.");
1780
+ if (result.stopReason === "error" || result.errorMessage) return fail("Alt ajan hata verdi, sonuc alinamadi.");
1781
+ return {
1782
+ content: [
1783
+ {
1784
+ type: "text",
1785
+ text: research.active
1786
+ ? clipSummary(result.text || "(Alt ajan metin dondurmedi)")
1787
+ : result.text || "(Alt ajan metin dondurmedi)",
1788
+ },
1789
+ ],
1790
+ details,
1791
+ usage: childUsage,
1792
+ };
1793
+ };
1794
+ // --- Arka plan alt ajani: task({background:true}) hemen doner; bitince sonuc modele followUp mesaj olarak gelir.
1795
+ const bg = new Map<
1796
+ string,
1797
+ {
1798
+ description: string;
1799
+ status: "running" | "done" | "error" | "cancelled";
1800
+ started: number;
1801
+ text?: string;
1802
+ ctrl: AbortController;
1803
+ }
1804
+ >();
1805
+ const bgMax = Number(process.env.SERA_BG_MAX) || 3;
1806
+ let bgSeq = 0;
1807
+ pi.on("session_shutdown", () => {
1808
+ for (const t of bg.values()) if (t.status === "running") t.ctrl.abort();
1809
+ });
1810
+ pi.registerTool({
1811
+ name: "task",
1812
+ label: "Task",
1813
+ description:
1814
+ "Launch a subagent in a separate context to do a self-contained subtask. It has the same tools and its own context window; you only receive its final answer. Give it a complete, standalone prompt.",
1815
+ promptSnippet: "Delegate a self-contained subtask to a subagent (separate context) and get its final answer",
1816
+ parameters: Type.Object({
1817
+ description: Type.String({ description: "Short (3-7 words) description of the subtask" }),
1818
+ prompt: Type.String({ description: "Complete standalone instructions for the subagent" }),
1819
+ subagent_type: Type.Optional(Type.String({ description: "Kind of subagent (default: general)" })),
1820
+ fork: Type.Optional(
1821
+ Type.Boolean({
1822
+ description:
1823
+ "true: fork — the subagent is seeded with a digest of THIS session's context (summary, recent requests, open todos, files) so it continues aware of the conversation, unlike a fresh separate-context task",
1824
+ }),
1825
+ ),
1826
+ background: Type.Optional(
1827
+ Type.Boolean({
1828
+ description: "true: run in the background, return immediately; the result arrives later as a message",
1829
+ }),
1830
+ ),
1831
+ }),
1832
+ async execute(_toolCallId, params, signal, onUpdate, ctx) {
1833
+ if (!params.background) return runTask(params, signal, onUpdate, ctx);
1834
+ const running = [...bg.values()].filter((t) => t.status === "running").length;
1835
+ if (running >= bgMax)
1836
+ throw new Error(
1837
+ `Arka planda zaten ${running} alt ajan calisiyor (en fazla ${bgMax}); birini bekle ya da task_status ile iptal et.`,
1838
+ );
1839
+ const g = getGovernor(ctx);
1840
+ const pre = childBudget(cfg.budget, g, shareOpts());
1841
+ if (pre.exhausted) throw new Error(`Butce tavani doldu (${pre.exhausted}); alt ajan baslatilmadi.`);
1842
+ const id = `bg${++bgSeq}`;
1843
+ const rec = {
1844
+ description: params.description,
1845
+ status: "running" as const,
1846
+ started: Date.now(),
1847
+ ctrl: new AbortController(),
1848
+ };
1849
+ const entry: {
1850
+ description: string;
1851
+ status: "running" | "done" | "error" | "cancelled";
1852
+ started: number;
1853
+ text?: string;
1854
+ ctrl: AbortController;
1855
+ } = rec;
1856
+ bg.set(id, entry);
1857
+ void runTask(params, entry.ctrl.signal, undefined, ctx)
1858
+ .then((r) => {
1859
+ const text = r.content.map((c) => c.text).join("\n");
1860
+ if (entry.status === "cancelled") return;
1861
+ entry.status = r.isError ? "error" : "done";
1862
+ entry.text = text;
1863
+ })
1864
+ .catch((e) => {
1865
+ if (entry.status === "cancelled") return;
1866
+ entry.status = "error";
1867
+ entry.text = `Alt ajan hata verdi: ${(e as Error).message}`;
1868
+ })
1869
+ .finally(() => {
1870
+ if (entry.status === "cancelled") return;
1871
+ try {
1872
+ pi.sendMessage(
1873
+ {
1874
+ customType: "sera-bg-task",
1875
+ content: `[Arka plan alt ajani ${id} "${entry.description}" ${entry.status === "done" ? "bitti" : "hata verdi"}]
1876
+ ${entry.text ?? ""}`,
1877
+ display: true,
1878
+ details: { id, status: entry.status },
1879
+ },
1880
+ { deliverAs: "followUp", triggerTurn: true },
1881
+ );
1882
+ } catch {
1883
+ // oturum kapanmis: sonuc task_status ile okunamaz, sessizce birakilir
1884
+ }
1885
+ });
1886
+ return {
1887
+ content: [
1888
+ {
1889
+ type: "text",
1890
+ text: `Arka plan alt ajani baslatildi: ${id} ("${params.description}"). Bitince sonucu bir mesaj olarak alacaksin; beklerken baska is yapabilirsin. Durum/iptal: task_status.`,
1891
+ },
1892
+ ],
1893
+ details: { sera_bg: { id } },
1894
+ };
1895
+ },
1896
+ });
1897
+ // --- Sera Ofis (sahip onayı 2026-11-10): müdür (bu ajan) planı panoya yazar; çalışanlar paralel yapar,
1898
+ // şef GERÇEK komutla doğrular, iki retten sonra danışman (Max) yol gösterir. Tüm harcama aynı bütçeye sayılır.
1899
+ // Ölçümle tek ajanı geçtiği kanıtlanana kadar AÇIKÇA açılır (SERA_OFIS=1); varsayılan kapalı (sahip 2026-11-10).
1900
+ if (process.env.SERA_OFIS === "1")
1901
+ pi.registerTool({
1902
+ name: "ofis",
1903
+ label: "Sera Ofis",
1904
+ description:
1905
+ "Sera Ofis takımını çalıştır: BÜYÜK ve parçalara bölünebilen işi (ör. oyun: mantık + çizim + ses + test; çok dosyalı program) 2-8 göreve ayırıp çalışanlara dağıtır. Her görev bitince şef doğrulama komutunu GERÇEKTEN çalıştırıp onaylar ya da geri çevirir; iki kez başarısız olan görev için teknik danışman yol gösterir. KÜÇÜK işlerde KULLANMA (tek ajan daha ucuz ve hızlı). Her görevin dokunacağı dosyaları yaz; aynı dosyaya iki görev aynı anda dokunamaz. Görev talimatları eksiksiz ve kendi başına anlaşılır olmalı.",
1906
+ promptSnippet: "Büyük, bölünebilen işi rol tabanlı ajan takımına (çalışan/şef/danışman) dağıt",
1907
+ parameters: Type.Object({
1908
+ hedef: Type.String({ description: "Ekibin ortak hedefi (1-3 cümle)" }),
1909
+ dogrulama: Type.Optional(
1910
+ Type.String({ description: "Genel doğrulama komutu (ör. 'npm test', 'pytest -q')" }),
1911
+ ),
1912
+ gorevler: Type.Array(
1913
+ Type.Object({
1914
+ id: Type.String({ description: "Kısa kimlik (harf/rakam/-/_)" }),
1915
+ baslik: Type.String(),
1916
+ is: Type.String({ description: "Çalışana eksiksiz talimat" }),
1917
+ dosyalar: Type.Array(Type.String(), {
1918
+ minItems: 1,
1919
+ description: "Görevin yazacağı dosyalar (ZORUNLU: çalışan yalnız bunlara yazabilir)",
1920
+ }),
1921
+ bagimli: Type.Optional(
1922
+ Type.Array(Type.String(), { description: "Önce bitmesi gereken görev id'leri" }),
1923
+ ),
1924
+ dogrulama: Type.Optional(Type.String({ description: "Bu göreve özel doğrulama komutu" })),
1925
+ }),
1926
+ ),
1927
+ }),
1928
+ async execute(_toolCallId, params, signal, onUpdate, ctx) {
1929
+ const plan = params as OfisPlan;
1930
+ const hata = planHatasi(plan);
1931
+ if (hata) throw new Error(hata);
1932
+ const seraModel = ctx.model?.provider === "sera";
1933
+ const mevcut = ctx.model?.id;
1934
+ const toplam = {
1935
+ input: 0,
1936
+ output: 0,
1937
+ cacheRead: 0,
1938
+ cacheWrite: 0,
1939
+ totalTokens: 0,
1940
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
1941
+ };
1942
+ const ekle = (u: TaskUsage) => {
1943
+ for (const k of ["input", "output", "cacheRead", "cacheWrite", "totalTokens"] as const)
1944
+ toplam[k] += u[k];
1945
+ for (const k of ["input", "output", "cacheRead", "cacheWrite", "total"] as const)
1946
+ toplam.cost[k] += u.cost[k];
1947
+ };
1948
+ const ROL_AD = { calisan: "çalışan", sef: "şef", danisman: "danışman" } as const;
1949
+ // Alt ajan olayları (sera_child) panoyla BİRLİKTE yayınlanır: arayüz alt ajanı tanır, izin sorularını
1950
+ // kullanıcıya iletir (tanınmayan alt ajanın izni güvenlik gereği reddedilir) ve alt oturumunu gösterir.
1951
+ let panoYayin: { content: Array<{ type: "text"; text: string }>; details: Record<string, unknown> } = {
1952
+ content: [{ type: "text", text: "Sera Ofis" }],
1953
+ details: {},
1954
+ };
1955
+ const cocukYayin = (u: { content: Array<{ type: "text"; text: string }>; details: unknown }) =>
1956
+ onUpdate?.({
1957
+ content: panoYayin.content,
1958
+ details: { ...panoYayin.details, ...((u.details as Record<string, unknown>) ?? {}) },
1959
+ });
1960
+ const rapor = await ofisYurut(plan, {
1961
+ danismanVar: seraModel && process.env.SERA_OFIS_DANISMAN !== "0",
1962
+ signal,
1963
+ guncelle: (pano) => {
1964
+ panoYayin = {
1965
+ content: [
1966
+ {
1967
+ type: "text",
1968
+ text: `Sera Ofis
1969
+ ${panoMetni(pano)}`,
1970
+ },
1971
+ ],
1972
+ details: {
1973
+ sera_ofis: {
1974
+ pano: pano.map(({ id, baslik, durum, deneme }) => ({ id, baslik, durum, deneme })),
1975
+ },
1976
+ },
1977
+ };
1978
+ onUpdate?.(panoYayin);
1979
+ },
1980
+ calistir: async (rol, istem, gorev) => {
1981
+ try {
1982
+ const r = await runTask(
1983
+ {
1984
+ description: `${ROL_AD[rol]}: ${gorev.baslik}`.slice(0, 80),
1985
+ prompt: istem,
1986
+ model: seraModel ? rolModeli(rol, process.env, mevcut) : undefined,
1987
+ tools: rolAraclari(rol),
1988
+ yazilabilir: rol === "calisan" ? gorev.dosyalar : undefined,
1989
+ ofisRol: rol,
1990
+ ofisKomut: rol === "sef" && gorev.dogrulama ? [gorev.dogrulama] : undefined,
1991
+ },
1992
+ signal,
1993
+ onUpdate ? cocukYayin : undefined,
1994
+ ctx,
1995
+ );
1996
+ ekle(r.usage);
1997
+ const text = r.content.map((c) => c.text).join("\n");
1998
+ return { ok: !r.isError, text, butceBitti: /butce tavan/i.test(text) && !!r.isError };
1999
+ } catch (e) {
2000
+ const m = (e as Error)?.message ?? String(e);
2001
+ return { ok: false, text: m, butceBitti: /butce tavan/i.test(m) };
2002
+ }
2003
+ },
2004
+ });
2005
+ const bitti = rapor.pano.filter((t) => t.durum === "bitti").length;
2006
+ const ozet = `Sera Ofis: ${bitti}/${rapor.pano.length} görev tamamlandı${rapor.durdu ? ` (durdu: ${rapor.durdu})` : ""}.`;
2007
+ return {
2008
+ content: [
2009
+ {
2010
+ type: "text" as const,
2011
+ text: `${ozet}
2012
+ ${panoMetni(rapor.pano, true)}`,
2013
+ },
2014
+ ],
2015
+ details: {
2016
+ sera_ofis: {
2017
+ pano: rapor.pano.map(({ id, baslik, durum, deneme }) => ({ id, baslik, durum, deneme })),
2018
+ done: true,
2019
+ },
2020
+ },
2021
+ usage: toplam,
2022
+ isError: bitti === 0,
2023
+ };
2024
+ },
2025
+ });
2026
+ pi.registerTool({
2027
+ name: "task_status",
2028
+ exposure: rareExposure(),
2029
+ label: "Task status",
2030
+ description:
2031
+ "Arka plan alt ajanlarini listele (action=list), birinin durumunu/sonucunu al (get) ya da iptal et (cancel).",
2032
+ promptSnippet: "Background subagent status/cancel",
2033
+ parameters: Type.Object({
2034
+ action: Type.Optional(Type.String({ description: "list|get|cancel" })),
2035
+ id: Type.Optional(Type.String()),
2036
+ }),
2037
+ async execute(_id, params) {
2038
+ const out = (t: string) => ({ content: [{ type: "text" as const, text: t }], details: {} });
2039
+ const action = params.action ?? "list";
2040
+ if (action === "list") {
2041
+ if (!bg.size) return out("Arka plan alt ajani yok.");
2042
+ return out(
2043
+ [...bg.entries()]
2044
+ .map(
2045
+ ([id, t]) =>
2046
+ `${id} [${t.status}] ${t.description} (${Math.round((Date.now() - t.started) / 1000)} sn)`,
2047
+ )
2048
+ .join("\n"),
2049
+ );
2050
+ }
2051
+ const t = params.id ? bg.get(params.id) : undefined;
2052
+ if (!t) return out(`Bilinmeyen alt ajan: ${params.id ?? "(id yok)"}`);
2053
+ if (action === "cancel") {
2054
+ if (t.status !== "running") return out(`${params.id} zaten ${t.status}.`);
2055
+ t.status = "cancelled";
2056
+ t.ctrl.abort();
2057
+ return out(`${params.id} iptal edildi.`);
2058
+ }
2059
+ return out(
2060
+ `${params.id} [${t.status}] ${t.description}${
2061
+ t.text
2062
+ ? `
2063
+ ${t.text}`
2064
+ : ""
2065
+ }`,
2066
+ );
2067
+ },
2068
+ });
2069
+ }
2070
+
2071
+ resultSteps.push({
2072
+ name: "loop-brake",
2073
+ run: (event, ctx) => {
2074
+ if (brakeStops.has(event.toolCallId)) return undefined;
2075
+ const text = contentText(event.content);
2076
+ const r = brake.onResult(event.toolCallId, event.toolName, event.isError, text);
2077
+ if (r.level === "none") return undefined;
2078
+ brakeSpoke = true;
2079
+ const note = brakeMessage(r.level, event.toolName, r.count);
2080
+ if (r.level === "stop") {
2081
+ say(ctx, note, "error");
2082
+ pi.appendEntry("sera-loop-stop", { tool: event.toolName, count: r.count });
2083
+ ctx.abort();
2084
+ }
2085
+ return { content: [...event.content, { type: "text" as const, text: `\n${note}` }] };
2086
+ },
2087
+ });
2088
+
2089
+ const spillFull = makeFileSpill(cfg.diet.spillDir);
2090
+ resultSteps.push({
2091
+ name: "output-cap",
2092
+ run: (event) => {
2093
+ if (!(cfg.diet.outputCapChars > 0)) return undefined;
2094
+ let changed = false;
2095
+ const content = event.content.map((c) => {
2096
+ if (c.type !== "text") return c;
2097
+ const cut = capOutput(event.toolName, event.toolCallId, c.text, cfg.diet.outputCapChars, spillFull);
2098
+ if (cut === undefined) return c;
2099
+ changed = true;
2100
+ return { ...c, text: cut };
2101
+ });
2102
+ return changed ? { content } : undefined;
2103
+ },
2104
+ });
2105
+
2106
+ resultSteps.push({
2107
+ name: "hooks",
2108
+ run: async (event, ctx) => {
2109
+ const notes = await hooksFor(ctx).post(event.toolName, event.input, contentText(event.content));
2110
+ if (!notes.length) return undefined;
2111
+ const text = notes.map((n) => `\n[Kanca] ${n}`).join("");
2112
+ return { content: [...event.content, { type: "text" as const, text }] };
2113
+ },
2114
+ });
2115
+
2116
+ // --- D1-10: test-duzelt dongusu (/test). Yalniz ust ajanda (alt ajan kullanici komutu almaz).
2117
+ if (process.env[SUBAGENT_DEPTH_ENV] !== "1") {
2118
+ type Loop = { paths: Set<string>; started: boolean; ended?: (aborted: boolean) => void };
2119
+ let loop: Loop | undefined;
2120
+ let stopFix: (() => void) | undefined;
2121
+ type Entry = { type: string; customType?: string; data?: unknown };
2122
+ const customs = (ctx: ExtensionContext, type: string) =>
2123
+ (ctx.sessionManager.getEntries() as Entry[]).filter((e) => e.type === "custom" && e.customType === type);
2124
+ resultSteps.push({
2125
+ name: "test-fix",
2126
+ run: (event, ctx) => {
2127
+ if (!loop || event.isError) return undefined;
2128
+ const p = editedPath(ctx.cwd, event.toolName, event.input);
2129
+ if (p) loop.paths.add(p);
2130
+ return undefined;
2131
+ },
2132
+ });
2133
+ pi.on("agent_start", () => {
2134
+ if (loop) loop.started = true;
2135
+ });
2136
+ pi.on("agent_end", (e) => {
2137
+ const end = loop?.ended;
2138
+ if (!end || !loop) return;
2139
+ loop.ended = undefined;
2140
+ const last = [...e.messages].reverse().find((m) => (m as { role?: string }).role === "assistant") as
2141
+ | { stopReason?: string }
2142
+ | undefined;
2143
+ end(last?.stopReason === "aborted" || last?.stopReason === "error");
2144
+ });
2145
+ /** Duzeltme turunu baslatir ve bitmesini bekler; tur hic baslamazsa (model yok vb.) false. */
2146
+ const fixTurn = (ctx: ExtensionContext, l: Loop, text: string) =>
2147
+ new Promise<"done" | "aborted" | "nostart">((done) => {
2148
+ l.started = false;
2149
+ const t0 = Date.now();
2150
+ const watch = setInterval(() => {
2151
+ try {
2152
+ if (!l.started && ctx.isIdle() && Date.now() - t0 > 10_000) {
2153
+ clearInterval(watch);
2154
+ stopFix = undefined;
2155
+ l.ended = undefined;
2156
+ done("nostart");
2157
+ }
2158
+ } catch {
2159
+ // Oturum degisti/yenilendi: ctx bayat (assertActive firlatir); yakalanmayan istisna motoru dusururdu.
2160
+ stopFix?.();
2161
+ }
2162
+ }, 500);
2163
+ watch.unref?.();
2164
+ // Oturum kapaninca zamanlayici temizlenir; bekleyen soz bilerek cozulmez (bayat ctx ile devam edilmesin).
2165
+ stopFix = () => {
2166
+ clearInterval(watch);
2167
+ l.ended = undefined;
2168
+ stopFix = undefined;
2169
+ };
2170
+ l.ended = (aborted) => {
2171
+ clearInterval(watch);
2172
+ stopFix = undefined;
2173
+ done(aborted ? "aborted" : "done");
2174
+ };
2175
+ pi.sendUserMessage(text);
2176
+ });
2177
+ pi.on("session_shutdown", () => stopFix?.());
2178
+
2179
+ regCmd(TEST_COMMAND, {
2180
+ description: "Sera: testleri calistir, kirilirsa modele duzelttir (en fazla N deneme) — /test [komut]",
2181
+ handler: async (args, ctx) => {
2182
+ if (loop) return say(ctx, "[Sera TEST] Test-duzelt dongusu zaten calisiyor.", "warning");
2183
+ const cmd = args.trim() || detectTestCommand(ctx.cwd);
2184
+ if (!cmd)
2185
+ return say(
2186
+ ctx,
2187
+ "[Sera TEST] Test komutu bulunamadi. /test <komut> yaz ya da SERA_TEST_CMD ayarla (ornek: /test npm test).",
2188
+ "error",
2189
+ );
2190
+ const max = testAttempts();
2191
+ const stopsAtStart = customs(ctx, "sera-loop-stop").length;
2192
+ const l: Loop = { paths: new Set(), started: false };
2193
+ loop = l;
2194
+ try {
2195
+ for (let attempt = 0; ; attempt++) {
2196
+ say(
2197
+ ctx,
2198
+ `[Sera TEST] Calisiyor: ${cmd}${attempt ? ` (duzeltme ${attempt}/${max} sonrasi)` : ""}`,
2199
+ "info",
2200
+ );
2201
+ const r = await runTests(cmd, ctx.cwd, testTimeoutMs());
2202
+ const snap = customs(ctx, SNAPSHOT_ENTRY).at(-1)?.data as TurnSnapshot | undefined;
2203
+ const entry: TestEntry = { cmd, attempt, ok: r.ok, code: r.code, ms: r.ms, snapshot: snap?.after };
2204
+ pi.appendEntry(TEST_ENTRY, entry);
2205
+ if (r.ok) {
2206
+ let extra = "";
2207
+ if (attempt > 0 && process.env.SERA_TEST_AUTOCOMMIT === "1") {
2208
+ try {
2209
+ const sha = await commitPaths(ctx.cwd, [...l.paths], `Sera /test duzeltmesi: ${cmd}`);
2210
+ if (sha) extra = ` Otomatik commit: ${sha} (${l.paths.size} dosya).`;
2211
+ } catch (e) {
2212
+ extra = ` ${e instanceof Error ? e.message : String(e)}`;
2213
+ }
2214
+ }
2215
+ return say(
2216
+ ctx,
2217
+ `[Sera TEST] Testler gecti${attempt ? ` (${attempt} duzeltme turundan sonra)` : ""}.${extra}`,
2218
+ "info",
2219
+ );
2220
+ }
2221
+ const why = r.timedOut ? "zaman asimi" : `cikis ${r.code ?? "?"}`;
2222
+ if (attempt >= max)
2223
+ return say(
2224
+ ctx,
2225
+ `[Sera TEST] Testler ${max} duzeltme denemesinde gecmedi (${why}); dongu durdu. Hata ozeti son mesajda.`,
2226
+ "error",
2227
+ );
2228
+ if (customs(ctx, "sera-loop-stop").length > stopsAtStart)
2229
+ return say(ctx, "[Sera TEST] Dongu freni ajani durdurdu; test-duzelt dongusu de durdu.", "error");
2230
+ say(
2231
+ ctx,
2232
+ `[Sera TEST] Testler kirik (${why}); Sera duzeltiyor (deneme ${attempt + 1}/${max}).`,
2233
+ "warning",
2234
+ );
2235
+ const t = await fixTurn(ctx, l, fixPrompt(cmd, r, attempt + 1, max));
2236
+ await ctx.waitForIdle(); // tur sonu kayitlari (anlik kopya vb.) yazilsin
2237
+ if (t === "aborted") return say(ctx, "[Sera TEST] Duzeltme turu durduruldu; dongu bitti.", "warning");
2238
+ if (t === "nostart")
2239
+ return say(ctx, "[Sera TEST] Duzeltme turu baslatilamadi; dongu bitti.", "error");
2240
+ if (customs(ctx, "sera-loop-stop").length > stopsAtStart)
2241
+ return say(ctx, "[Sera TEST] Dongu freni ajani durdurdu; test-duzelt dongusu de durdu.", "error");
2242
+ }
2243
+ } finally {
2244
+ loop = undefined;
2245
+ }
2246
+ },
2247
+ });
2248
+ }
2249
+
2250
+ // --- LSP tanilari + bicimlendirici (SERA_LSP=0 / SERA_FORMAT=0 kapatir). Sunucular tembel baslar, bosta kapanir.
2251
+ if (process.env.SERA_LSP !== "0" || process.env.SERA_FORMAT !== "0") {
2252
+ let lsp: LspManager | undefined;
2253
+ const lspFor = (cwd: string, ctx?: ExtensionContext) => {
2254
+ if (!lsp) {
2255
+ lsp = new LspManager(cwd);
2256
+ const m = lsp;
2257
+ lsp.onChange = () => {
2258
+ // Sera Code arayuzu: /lsp durum listesi (adaptor "sera-lsp:" onekli durum satirini okur)
2259
+ if (ctx?.hasUI) ctx.ui.setStatus("sera-lsp", `sera-lsp:${JSON.stringify(m.status())}`);
2260
+ };
2261
+ }
2262
+ return lsp;
2263
+ };
2264
+ resultSteps.push({
2265
+ name: "lsp",
2266
+ run: async (event, ctx) => {
2267
+ if (event.isError) return undefined;
2268
+ const rel = editedPath(ctx.cwd, event.toolName, event.input);
2269
+ if (!rel) return undefined;
2270
+ const file = resolvePath(ctx.cwd, rel);
2271
+ const notes: string[] = [];
2272
+ try {
2273
+ const f = await runFormatter(file, ctx.cwd);
2274
+ if (f?.changed)
2275
+ notes.push(
2276
+ `[Bicimlendirici] ${f.formatter}: ${rel} bicimlendirildi (dosya degisti; sonraki duzenlemeden once yeniden oku).`,
2277
+ );
2278
+ } catch {
2279
+ // bicimlendirici hatasi sonucu bozmaz
2280
+ }
2281
+ if (process.env.SERA_LSP !== "0") {
2282
+ try {
2283
+ const ds = await lspFor(ctx.cwd, ctx).diagnostics(file, Number(process.env.SERA_LSP_WAIT_MS) || 4000);
2284
+ const t = formatDiagnostics(rel, ds);
2285
+ if (t) notes.push(t);
2286
+ } catch {
2287
+ // dil sunucusu yok / cevap vermedi: sessiz
2288
+ }
2289
+ }
2290
+ if (!notes.length) return undefined;
2291
+ return { content: [...event.content, { type: "text" as const, text: `\n${notes.join("\n")}` }] };
2292
+ },
2293
+ });
2294
+ if (process.env.SERA_LSP !== "0") {
2295
+ pi.registerTool({
2296
+ name: "lsp",
2297
+ exposure: rareExposure(),
2298
+ label: "lsp",
2299
+ description:
2300
+ "Dil sunucusu (LSP): action=diagnostics (dosyadaki hatalar) | hover | definition | references. line/character 1 tabanli. Dil sunucusu kurulu degilse bunu soyler.",
2301
+ promptSnippet: "LSP: diagnostics/hover/definition/references",
2302
+ parameters: Type.Object({
2303
+ action: Type.String({ description: "diagnostics|hover|definition|references" }),
2304
+ path: Type.String(),
2305
+ line: Type.Optional(Type.Number()),
2306
+ character: Type.Optional(Type.Number()),
2307
+ }),
2308
+ async execute(_id, params, _signal, _update, ctx) {
2309
+ const file = resolvePath(ctx.cwd, params.path);
2310
+ const text = (t: string) => ({ content: [{ type: "text" as const, text: t }], details: {} });
2311
+ if (!existsSync(file)) return text(`Dosya yok: ${params.path}`);
2312
+ const m = lspFor(ctx.cwd, ctx);
2313
+ if (!m.candidates(file).length) return text("Bu dosya turu icin kurulu/uygun dil sunucusu bulunamadi.");
2314
+ try {
2315
+ if (params.action === "diagnostics") {
2316
+ const ds = await m.diagnostics(file, Number(process.env.SERA_LSP_WAIT_MS) || 4000);
2317
+ return text(
2318
+ formatDiagnostics(params.path, ds) ?? `[LSP] ${params.path}: hata yok (${ds.length} tani)`,
2319
+ );
2320
+ }
2321
+ if (params.action === "hover" || params.action === "definition" || params.action === "references") {
2322
+ const r = await m.query(file, params.action, (params.line ?? 1) - 1, (params.character ?? 1) - 1);
2323
+ return text(JSON.stringify(r ?? null).slice(0, 6000));
2324
+ }
2325
+ return text("Bilinmeyen action: diagnostics|hover|definition|references");
2326
+ } catch (e) {
2327
+ return text(`[LSP] hata: ${(e as Error).message}`);
2328
+ }
2329
+ },
2330
+ });
2331
+ }
2332
+ pi.on("session_shutdown", async () => {
2333
+ await lsp?.stopAll();
2334
+ });
2335
+ }
2336
+
2337
+ // --- Arka plan surec araci "proc" (SERA_PROC=0 kapatir). Komutlar bash ile AYNI izin politikasindan gecer.
2338
+ if (process.env.SERA_PROC !== "0") {
2339
+ const procs = new ProcManager(Number(process.env.SERA_PROC_MAX) || 5);
2340
+ pi.registerTool({
2341
+ name: "proc",
2342
+ exposure: rareExposure(),
2343
+ label: "proc",
2344
+ description:
2345
+ "Arka plan sureci yonet (bloke etmez): action=start (command ile baslat), read (id, since=onceki next), write (id, command=stdin satiri), kill (id), list. Dev sunucusu/izleyici/uzun test icin. PTY degil: boru tabanli.",
2346
+ promptSnippet: "Run/read/stop background processes (dev servers, watchers) without blocking",
2347
+ parameters: Type.Object({
2348
+ action: Type.String({ description: "start|read|write|kill|list" }),
2349
+ command: Type.Optional(
2350
+ Type.String({ description: "start: calistirilacak komut; write: stdin'e gonderilecek satir" }),
2351
+ ),
2352
+ id: Type.Optional(Type.String()),
2353
+ since: Type.Optional(Type.Number()),
2354
+ }),
2355
+ async execute(_id, params, _signal, _update, ctx) {
2356
+ const out = (t: string) => ({ content: [{ type: "text" as const, text: t }], details: {} });
2357
+ try {
2358
+ switch (params.action) {
2359
+ case "start": {
2360
+ if (!params.command?.trim()) return out("start icin command gerekli.");
2361
+ const i = procs.start(params.command, ctx.cwd);
2362
+ return out(
2363
+ `Surec baslatildi: ${i.id} (${i.command}). Cikti: proc read id=${i.id}; kapat: proc kill id=${i.id}.`,
2364
+ );
2365
+ }
2366
+ case "read": {
2367
+ const r = procs.read(params.id ?? "", params.since ?? 0);
2368
+ return out(
2369
+ `[${r.info.id} ${r.info.status}${r.info.exitCode !== null ? ` kod=${r.info.exitCode}` : ""}] next=${r.next}\n${r.text}`,
2370
+ );
2371
+ }
2372
+ case "write":
2373
+ procs.write(params.id ?? "", params.command ?? "");
2374
+ return out(`${params.id} stdin'e yazildi.`);
2375
+ case "kill": {
2376
+ const i = procs.kill(params.id ?? "");
2377
+ return out(`${i.id} durduruldu (${i.status}).`);
2378
+ }
2379
+ case "list": {
2380
+ const l = procs.list();
2381
+ return out(
2382
+ l.length
2383
+ ? l.map((p) => `${p.id} [${p.status}] ${p.command}`).join("\n")
2384
+ : "Arka plan sureci yok.",
2385
+ );
2386
+ }
2387
+ default:
2388
+ return out("Bilinmeyen action: start|read|write|kill|list");
2389
+ }
2390
+ } catch (e) {
2391
+ return { ...out(`[proc] hata: ${(e as Error).message}`), isError: true };
2392
+ }
2393
+ },
2394
+ });
2395
+ pi.on("session_shutdown", () => procs.killAll());
2396
+ }
2397
+
2398
+ // --- Tembel yerlesik araclar: seyrek araclar `deferred` kayitli (exposure.ts); bulunabilsinler diye tool_search etkin tutulur.
2399
+ if (rareExposure() === "deferred") {
2400
+ const ensureToolSearch = () => {
2401
+ const active = pi.getActiveTools();
2402
+ if (active.includes("tool_search")) return;
2403
+ const reaches = pi.getAllTools().some((t) => t.name === "tool_search" && t.reachesTools);
2404
+ if (reaches) pi.setActiveTools([...active, "tool_search"]);
2405
+ };
2406
+ pi.on("session_start", () => ensureToolSearch());
2407
+ pi.on("before_agent_start", () => {
2408
+ ensureToolSearch();
2409
+ return undefined;
2410
+ });
2411
+ }
2412
+
2413
+ // TEK kayit: Pi'de Sera'nin baska tool_call/tool_result isleyicisi yok (grep ile denetlenir, test var).
2414
+ pi.on("tool_call", callChain(callSteps));
2415
+ pi.on("tool_result", resultChain(resultSteps));
2416
+ }