alran 0.0.0-stage → 0.9.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 (506) hide show
  1. package/ALRAN_TOOLS_NOTICES.md +64 -0
  2. package/LICENSE +27 -0
  3. package/LICENSE-STATUS.md +21 -0
  4. package/NOTICE +6 -0
  5. package/README.md +289 -2
  6. package/THIRD_PARTY_NOTICES.md +113 -0
  7. package/alran-tools.js +3 -0
  8. package/assets/agents/_default/prompt-auto_classifier.md +185 -0
  9. package/assets/agents/_default/prompt-auto_classifier_extras.md +17 -0
  10. package/assets/agents/_default/prompt-base-all.md +133 -0
  11. package/assets/agents/_default/prompt-base-all.md.hbs +228 -0
  12. package/assets/agents/_default/prompt-base-windows.md +5 -0
  13. package/assets/agents/_default/prompt-base-windows.md.hbs +5 -0
  14. package/assets/agents/_default/prompt-base-worker.md +10 -0
  15. package/assets/agents/_default/prompt-base-worker.md.hbs +27 -0
  16. package/assets/agents/_default/prompt-compact.md +76 -0
  17. package/assets/agents/_default/prompt-compact_continue.md +9 -0
  18. package/assets/agents/_default/prompt-git.md +8 -0
  19. package/assets/agents/_default/prompt-goal.md +13 -0
  20. package/assets/agents/_default/prompt-session-branch.md +3 -0
  21. package/assets/agents/_default/prompt-session-branch.md.hbs +30 -0
  22. package/assets/agents/_default/prompt-session-root.md +3 -0
  23. package/assets/agents/_default/prompt-session-root.md.hbs +32 -0
  24. package/assets/agents/_default/prompt-title.md +11 -0
  25. package/assets/agents/_default/prompt-tool_agent.md +22 -0
  26. package/assets/agents/_migration/README.md +20 -0
  27. package/assets/agents/_migration/coder/PERSONA.md +11 -0
  28. package/assets/agents/_migration/coder/system-prompt.md.hbs +42 -0
  29. package/assets/agents/_migration/general/PERSONA.md +11 -0
  30. package/assets/agents/_migration/general/system-prompt.md.hbs +49 -0
  31. package/assets/agents/_v2/AGENT_CONTEXT.md.hbs +245 -0
  32. package/assets/agents/_v2/PTC_TOOL_CALLS.md.hbs +35 -0
  33. package/assets/agents/_v2/coding/SYSTEM.md.hbs +173 -0
  34. package/assets/agents/_v2/explore.md.hbs +38 -0
  35. package/assets/agents/_v2/tui/SYSTEM.md.hbs +211 -0
  36. package/assets/agents/_v2/verifier.md.hbs +32 -0
  37. package/assets/agents/_v2/work/SYSTEM.md.hbs +186 -0
  38. package/assets/agents/_v2/worker.md.hbs +27 -0
  39. package/assets/agents/alran/PERSONA.md +7 -0
  40. package/assets/agents/alran/features/cron.md.hbs +0 -0
  41. package/assets/agents/alran/features/delegation.md.hbs +56 -0
  42. package/assets/agents/alran/features/memory.md.hbs +61 -0
  43. package/assets/agents/alran/features/recoverable-deletion.md.hbs +10 -0
  44. package/assets/agents/alran/features/task-management.md.hbs +11 -0
  45. package/assets/agents/alran/features/web-search.md.hbs +11 -0
  46. package/assets/agents/alran/modes/coding/online/PERSONA.md.hbs +20 -0
  47. package/assets/agents/alran/modes/coding/online/SYSTEM.md.hbs +158 -0
  48. package/assets/agents/alran/modes/work/online/PERSONA.md.hbs +20 -0
  49. package/assets/agents/alran/modes/work/online/SYSTEM.md.hbs +160 -0
  50. package/assets/agents/alran/prompt-session-root.md +4 -0
  51. package/assets/agents/alran/prompt-session-root.md.hbs +4 -0
  52. package/assets/agents/alran/skills/alran-code-product/SKILL.md +72 -0
  53. package/assets/agents/alran/skills/alran-code-product/references/account-models.md +61 -0
  54. package/assets/agents/alran/skills/alran-code-product/references/agents.md +34 -0
  55. package/assets/agents/alran/skills/alran-code-product/references/extensions.md +46 -0
  56. package/assets/agents/alran/skills/alran-code-product/references/workflows.md +56 -0
  57. package/assets/agents/alran/skills/control-in-app-browser/SKILL.md +590 -0
  58. package/assets/agents/alran/system-prompt.md.hbs +97 -0
  59. package/assets/agents/builtin-agents.json +1 -0
  60. package/assets/agents/desktop-task/archive-title/system-en.md +1 -0
  61. package/assets/agents/desktop-task/checkpoint/system.md +19 -0
  62. package/assets/agents/desktop-task/output-revision/system.md +1 -0
  63. package/assets/agents/desktop-task/retry/continuation.md +4 -0
  64. package/assets/agents/desktop-task/session-title/system.md +41 -0
  65. package/assets/agents/explore/PERSONA.md +8 -0
  66. package/assets/agents/explore/agent.md +14 -0
  67. package/assets/agents/explore/system-prompt.md.hbs +35 -0
  68. package/assets/agents/greeting.md +61 -0
  69. package/assets/agents/managed-prompts.json +47 -0
  70. package/assets/agents/prompt-exemptions.json +36 -0
  71. package/assets/agents/verifier/PERSONA.md +8 -0
  72. package/assets/agents/verifier/agent.md +17 -0
  73. package/assets/agents/verifier/system-prompt.md.hbs +28 -0
  74. package/assets/agents/worker/PERSONA.md +8 -0
  75. package/assets/agents/worker/agent.md +18 -0
  76. package/assets/agents/worker/system-prompt.md.hbs +22 -0
  77. package/assets/agents/workflow/code-review/review-candidates.md +120 -0
  78. package/assets/agents/workflow/code-review/reviewer-system.md +75 -0
  79. package/assets/agents/workflow/goal/budget-limit.md +16 -0
  80. package/assets/agents/workflow/goal/continuation.md +62 -0
  81. package/assets/agents/workflow/goal/objective-updated.md +16 -0
  82. package/assets/agents/workflow/goal/recovery-terminal-audit.md +13 -0
  83. package/assets/agents/workflow/goal/recovery.md +11 -0
  84. package/assets/agents/workflow/goal/terminal-audit.md +10 -0
  85. package/assets/agents/workflow/plan-mode/agent-entry.md +72 -0
  86. package/assets/agents/workflow/prompt-hook/system.md +0 -0
  87. package/assets/models-dev-catalog.json.gz +0 -0
  88. package/assets/prompts/code-review/review-candidates.md +120 -0
  89. package/assets/prompts/code-review/reviewer-system.md +75 -0
  90. package/assets/skills/alran-tools-master/SKILL.md +127 -0
  91. package/assets/skills/code-review/SKILL.md +51 -0
  92. package/assets/skills/cu-desktop/SKILL.md +255 -0
  93. package/assets/skills/deep-research/SKILL.md +30 -0
  94. package/assets/skills/deploy-website/SKILL.md +52 -0
  95. package/assets/skills/docx/LICENSE +21 -0
  96. package/assets/skills/docx/SKILL.md +259 -0
  97. package/assets/skills/docx/assets/styles/academic_styles.xml +250 -0
  98. package/assets/skills/docx/assets/styles/corporate_styles.xml +284 -0
  99. package/assets/skills/docx/assets/styles/default_styles.xml +449 -0
  100. package/assets/skills/docx/assets/xsd/aesthetic-rules.xsd +470 -0
  101. package/assets/skills/docx/assets/xsd/business-rules.xsd +130 -0
  102. package/assets/skills/docx/assets/xsd/common-types.xsd +159 -0
  103. package/assets/skills/docx/assets/xsd/wml-subset.xsd +589 -0
  104. package/assets/skills/docx/docs/acceptance-checklists/create.md +7 -0
  105. package/assets/skills/docx/docs/acceptance-checklists/edit.md +6 -0
  106. package/assets/skills/docx/docs/acceptance-checklists/layout-repair.md +7 -0
  107. package/assets/skills/docx/docs/acceptance-checklists/template.md +6 -0
  108. package/assets/skills/docx/docs/acceptance.md +139 -0
  109. package/assets/skills/docx/docs/anti-patterns.md +14 -0
  110. package/assets/skills/docx/docs/backends.md +116 -0
  111. package/assets/skills/docx/docs/evidence.md +73 -0
  112. package/assets/skills/docx/docs/failure-taxonomy.md +71 -0
  113. package/assets/skills/docx/docs/index.md +50 -0
  114. package/assets/skills/docx/docs/rendered-delivery.md +125 -0
  115. package/assets/skills/docx/docs/router.md +122 -0
  116. package/assets/skills/docx/docs/tables-and-numbering.md +27 -0
  117. package/assets/skills/docx/docs/task-apply-template.md +141 -0
  118. package/assets/skills/docx/docs/task-compare-two-docx.md +48 -0
  119. package/assets/skills/docx/docs/task-create.md +124 -0
  120. package/assets/skills/docx/docs/task-edit-fill.md +69 -0
  121. package/assets/skills/docx/docs/task-read-content.md +148 -0
  122. package/assets/skills/docx/docs/task-read-rendered.md +78 -0
  123. package/assets/skills/docx/docs/task-read-structure.md +93 -0
  124. package/assets/skills/docx/docs/task-repair-layout.md +70 -0
  125. package/assets/skills/docx/docs/template-dsl.md +32 -0
  126. package/assets/skills/docx/docs/track-changes.md +15 -0
  127. package/assets/skills/docx/docs/xml-patch-dsl.md +33 -0
  128. package/assets/skills/docx/references/cjk_typography.md +357 -0
  129. package/assets/skills/docx/references/cjk_university_template_guide.md +184 -0
  130. package/assets/skills/docx/references/comments_guide.md +191 -0
  131. package/assets/skills/docx/references/design_good_bad_examples.md +829 -0
  132. package/assets/skills/docx/references/design_principles.md +819 -0
  133. package/assets/skills/docx/references/openxml_element_order.md +308 -0
  134. package/assets/skills/docx/references/openxml_encyclopedia_part1.md +4061 -0
  135. package/assets/skills/docx/references/openxml_encyclopedia_part2.md +2820 -0
  136. package/assets/skills/docx/references/openxml_encyclopedia_part3.md +3381 -0
  137. package/assets/skills/docx/references/openxml_namespaces.md +82 -0
  138. package/assets/skills/docx/references/openxml_units.md +72 -0
  139. package/assets/skills/docx/references/sample-patch-plans.json +22 -0
  140. package/assets/skills/docx/references/sample-task-intents.json +5 -0
  141. package/assets/skills/docx/references/sample-template-manifests.json +21 -0
  142. package/assets/skills/docx/references/scenario_a_create.md +284 -0
  143. package/assets/skills/docx/references/scenario_b_edit_content.md +295 -0
  144. package/assets/skills/docx/references/scenario_c_apply_template.md +456 -0
  145. package/assets/skills/docx/references/track_changes_guide.md +200 -0
  146. package/assets/skills/docx/references/troubleshooting.md +506 -0
  147. package/assets/skills/docx/references/typography_guide.md +294 -0
  148. package/assets/skills/docx/references/xsd_validation_guide.md +158 -0
  149. package/assets/skills/docx/scripts/build_patch_plan.py +29 -0
  150. package/assets/skills/docx/scripts/diff_docx_structure.py +61 -0
  151. package/assets/skills/docx/scripts/doc_to_docx.ps1 +85 -0
  152. package/assets/skills/docx/scripts/doc_to_docx.sh +40 -0
  153. package/assets/skills/docx/scripts/docx_preview.ps1 +76 -0
  154. package/assets/skills/docx/scripts/docx_preview.sh +37 -0
  155. package/assets/skills/docx/scripts/docx_to_pdf.py +87 -0
  156. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Cli/AlranAIDocx.Cli.csproj +19 -0
  157. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Cli/Program.cs +18 -0
  158. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/AlranAIDocx.Core.csproj +15 -0
  159. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Commands/AnalyzeCommand.cs +147 -0
  160. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Commands/ApplyTemplateCommand.cs +322 -0
  161. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Commands/CreateCommand.cs +324 -0
  162. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Commands/DiffCommand.cs +155 -0
  163. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Commands/EditContentCommand.cs +487 -0
  164. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Commands/FixOrderCommand.cs +108 -0
  165. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Commands/MergeRunsCommand.cs +122 -0
  166. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Commands/ValidateCommand.cs +107 -0
  167. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/OpenXml/CommentSynchronizer.cs +169 -0
  168. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/OpenXml/ElementOrder.cs +80 -0
  169. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/OpenXml/NamespaceConstants.cs +42 -0
  170. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/OpenXml/RunMerger.cs +81 -0
  171. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/OpenXml/StyleAnalyzer.cs +81 -0
  172. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/OpenXml/TrackChangesHelper.cs +99 -0
  173. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/OpenXml/UnitConverter.cs +23 -0
  174. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/AestheticRecipeSamples.cs +1832 -0
  175. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/AestheticRecipeSamples_Batch1.cs +910 -0
  176. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/AestheticRecipeSamples_Batch2.cs +999 -0
  177. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/AestheticRecipeSamples_Batch3.cs +1048 -0
  178. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/AestheticRecipeSamples_Batch4.cs +1038 -0
  179. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/CharacterFormattingSamples.cs +1020 -0
  180. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/DocumentCreationSamples.cs +1121 -0
  181. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/FieldAndTocSamples.cs +624 -0
  182. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/FootnoteAndCommentSamples.cs +675 -0
  183. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/HeaderFooterSamples.cs +838 -0
  184. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/ImageSamples.cs +917 -0
  185. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/ListAndNumberingSamples.cs +826 -0
  186. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/ParagraphFormattingSamples.cs +1199 -0
  187. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/StyleSystemSamples.cs +1487 -0
  188. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/TableSamples.cs +1163 -0
  189. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Samples/TrackChangesSamples.cs +595 -0
  190. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Typography/CjkHelper.cs +39 -0
  191. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Typography/FontDefaults.cs +24 -0
  192. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Typography/PageSizes.cs +20 -0
  193. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Validation/BusinessRuleValidator.cs +224 -0
  194. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Validation/GateCheckValidator.cs +148 -0
  195. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Validation/ValidationResult.cs +23 -0
  196. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.Core/Validation/XsdValidator.cs +69 -0
  197. package/assets/skills/docx/scripts/dotnet/AlranAIDocx.slnx +4 -0
  198. package/assets/skills/docx/scripts/env_check.ps1 +327 -0
  199. package/assets/skills/docx/scripts/env_check.sh +340 -0
  200. package/assets/skills/docx/scripts/extract_docx_text.py +1075 -0
  201. package/assets/skills/docx/scripts/pack_docx.py +31 -0
  202. package/assets/skills/docx/scripts/read_docx_structure.py +1032 -0
  203. package/assets/skills/docx/scripts/render_docx_pages.py +147 -0
  204. package/assets/skills/docx/scripts/rendered_report.py +609 -0
  205. package/assets/skills/docx/scripts/setup.ps1 +542 -0
  206. package/assets/skills/docx/scripts/setup.sh +537 -0
  207. package/assets/skills/docx/scripts/unpack_docx.py +29 -0
  208. package/assets/skills/docx/scripts/validate_template_manifest.py +60 -0
  209. package/assets/skills/docx/scripts/verify_anchor_atomicity.py +87 -0
  210. package/assets/skills/edit-deployed-website/SKILL.md +27 -0
  211. package/assets/skills/init/SKILL.md +135 -0
  212. package/assets/skills/llm-call/SKILL.md +48 -0
  213. package/assets/skills/llm-call/scripts/llm_call.py +458 -0
  214. package/assets/skills/pdf/SKILL.md +280 -0
  215. package/assets/skills/pdf/docs/advanced-reference.md +711 -0
  216. package/assets/skills/pdf/docs/create-guide.md +437 -0
  217. package/assets/skills/pdf/docs/design-guide.md +204 -0
  218. package/assets/skills/pdf/docs/forms-guide.md +462 -0
  219. package/assets/skills/pdf/docs/html-pdf-spec.md +500 -0
  220. package/assets/skills/pdf/docs/latex-academic-thesis-guide.md +233 -0
  221. package/assets/skills/pdf/docs/latex-technical-book-guide.md +112 -0
  222. package/assets/skills/pdf/docs/pitfalls-index.md +792 -0
  223. package/assets/skills/pdf/docs/read-guide.md +358 -0
  224. package/assets/skills/pdf/docs/reformat-guide.md +238 -0
  225. package/assets/skills/pdf/docs/skill-readme-archive.md +151 -0
  226. package/assets/skills/pdf/docs/troubleshooting.md +86 -0
  227. package/assets/skills/pdf/docs/vision-guide.md +188 -0
  228. package/assets/skills/pdf/scripts/__init__.py +0 -0
  229. package/assets/skills/pdf/scripts/_pdf_read_lib.py +284 -0
  230. package/assets/skills/pdf/scripts/fill/__init__.py +0 -0
  231. package/assets/skills/pdf/scripts/fill/acroform_apply.py +153 -0
  232. package/assets/skills/pdf/scripts/fill/overlay_apply.py +109 -0
  233. package/assets/skills/pdf/scripts/lib/__init__.py +0 -0
  234. package/assets/skills/pdf/scripts/lib/acroform_io.py +170 -0
  235. package/assets/skills/pdf/scripts/lib/cli_utils.py +41 -0
  236. package/assets/skills/pdf/scripts/lib/geometry.py +79 -0
  237. package/assets/skills/pdf/scripts/make.sh +388 -0
  238. package/assets/skills/pdf/scripts/merge.py +112 -0
  239. package/assets/skills/pdf/scripts/pdf_inspect/__init__.py +0 -0
  240. package/assets/skills/pdf/scripts/pdf_inspect/acroform_inspect.py +52 -0
  241. package/assets/skills/pdf/scripts/pdf_inspect/acroform_probe.py +57 -0
  242. package/assets/skills/pdf/scripts/pdf_inspect/layout_scan.py +164 -0
  243. package/assets/skills/pdf/scripts/read_pdf_vision.py +473 -0
  244. package/assets/skills/pdf/scripts/reformat_parse.py +181 -0
  245. package/assets/skills/pdf/scripts/render/__init__.py +0 -0
  246. package/assets/skills/pdf/scripts/render/overlay_preview.py +86 -0
  247. package/assets/skills/pdf/scripts/render/page_rasterize.py +85 -0
  248. package/assets/skills/pdf/scripts/render_html.cjs +205 -0
  249. package/assets/skills/pdf/scripts/validate/__init__.py +0 -0
  250. package/assets/skills/pdf/scripts/validate/geometry_lint.py +124 -0
  251. package/assets/skills/pdf/templates/INDEX.md +90 -0
  252. package/assets/skills/pdf/templates/bilingual-menu-premium/README.md +175 -0
  253. package/assets/skills/pdf/templates/bilingual-menu-premium/skeleton.html +343 -0
  254. package/assets/skills/pdf/templates/brand-guide-2page/README.md +140 -0
  255. package/assets/skills/pdf/templates/brand-guide-2page/skeleton.html +264 -0
  256. package/assets/skills/pdf/templates/data-viz-report/README.md +234 -0
  257. package/assets/skills/pdf/templates/data-viz-report/skeleton.html +835 -0
  258. package/assets/skills/pdf/templates/form-fill-acroform/README.md +195 -0
  259. package/assets/skills/pdf/templates/form-fill-acroform/field_values.template.json +118 -0
  260. package/assets/skills/pdf/templates/latex-academic-thesis/README.md +146 -0
  261. package/assets/skills/pdf/templates/latex-academic-thesis/source.tex +334 -0
  262. package/assets/skills/pdf/templates/latex-technical-book/README.md +130 -0
  263. package/assets/skills/pdf/templates/latex-technical-book/README.template-source.md +62 -0
  264. package/assets/skills/pdf/templates/latex-technical-book/source.tex +439 -0
  265. package/assets/skills/pdf/templates/multi-article-aggregator/README.md +148 -0
  266. package/assets/skills/pdf/templates/multi-article-aggregator/pipeline.md +223 -0
  267. package/assets/skills/pdf/templates/multilang-research-report/README.md +136 -0
  268. package/assets/skills/pdf/templates/multilang-research-report/skeleton.html +242 -0
  269. package/assets/skills/pdf/templates/reformat-default/README.md +136 -0
  270. package/assets/skills/pdf/templates/reformat-default/skeleton.html +204 -0
  271. package/assets/skills/pdf/templates/translate-preserve-layout/README.md +136 -0
  272. package/assets/skills/pdf/templates/translate-preserve-layout/skeleton.html +96 -0
  273. package/assets/skills/pdf/templates/translate-preserve-layout/terminology.template.json +66 -0
  274. package/assets/skills/pptx/SKILL.md +283 -0
  275. package/assets/skills/pptx/references/design-system.md +424 -0
  276. package/assets/skills/pptx/references/editing.md +162 -0
  277. package/assets/skills/pptx/references/element-map.md +229 -0
  278. package/assets/skills/pptx/references/pitfalls.md +205 -0
  279. package/assets/skills/pptx/references/pptxgenjs.md +420 -0
  280. package/assets/skills/pptx/references/preview-selection-writeback.md +65 -0
  281. package/assets/skills/pptx/references/python-pptx-recipes.md +63 -0
  282. package/assets/skills/pptx/references/slide-types.md +413 -0
  283. package/assets/skills/pptx/scripts/alran-ppt-map.cjs +280 -0
  284. package/assets/skills/pptx/scripts/audit_pptx.py +708 -0
  285. package/assets/skills/pptx/scripts/extract_comments.py +468 -0
  286. package/assets/skills/pptx/scripts/extract_images.py +226 -0
  287. package/assets/skills/pptx/scripts/extract_pptx.py +285 -0
  288. package/assets/skills/pptx/scripts/pdf2png.swift +203 -0
  289. package/assets/skills/pptx/scripts/pptx-screenshot.sh +105 -0
  290. package/assets/skills/resume-codex/SKILL.md +53 -0
  291. package/assets/skills/resume-codex/scripts/session-reader.mjs +445 -0
  292. package/assets/skills/skill-creator/SKILL.md +188 -0
  293. package/assets/skills/skill-creator/references/anti-patterns.md +149 -0
  294. package/assets/skills/skill-creator/references/commands-macos-linux.md +38 -0
  295. package/assets/skills/skill-creator/references/commands-windows-powershell.md +48 -0
  296. package/assets/skills/skill-creator/references/description-rubric.md +83 -0
  297. package/assets/skills/skill-creator/references/skill-template.md +101 -0
  298. package/assets/skills/skill-creator/references/when-to-bundle-scripts.md +139 -0
  299. package/assets/skills/skill-creator/scripts/lint-skill.js +226 -0
  300. package/assets/skills/skill-refiner/SKILL.md +137 -0
  301. package/assets/skills/visual-page/SKILL.md +194 -0
  302. package/assets/skills/x-link-reader/SKILL.md +108 -0
  303. package/assets/skills/xlsx/SKILL.md +498 -0
  304. package/assets/skills/xlsx/docs/advanced-reference.md +410 -0
  305. package/assets/skills/xlsx/docs/conventions-guide.md +217 -0
  306. package/assets/skills/xlsx/docs/create-edit-guide.md +410 -0
  307. package/assets/skills/xlsx/docs/pitfalls-index.md +759 -0
  308. package/assets/skills/xlsx/docs/raw-xml-escape-hatch.md +201 -0
  309. package/assets/skills/xlsx/docs/recalc-guide.md +295 -0
  310. package/assets/skills/xlsx/scripts/office/helpers/__init__.py +0 -0
  311. package/assets/skills/xlsx/scripts/office/helpers/merge_runs.py +199 -0
  312. package/assets/skills/xlsx/scripts/office/helpers/simplify_redlines.py +197 -0
  313. package/assets/skills/xlsx/scripts/office/pack.py +159 -0
  314. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-chart.xsd +1499 -0
  315. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-chartDrawing.xsd +146 -0
  316. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-diagram.xsd +1085 -0
  317. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-lockedCanvas.xsd +11 -0
  318. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-main.xsd +3081 -0
  319. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-picture.xsd +23 -0
  320. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-spreadsheetDrawing.xsd +185 -0
  321. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/dml-wordprocessingDrawing.xsd +287 -0
  322. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/pml.xsd +1676 -0
  323. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-additionalCharacteristics.xsd +28 -0
  324. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-bibliography.xsd +144 -0
  325. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-commonSimpleTypes.xsd +174 -0
  326. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-customXmlDataProperties.xsd +25 -0
  327. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-customXmlSchemaProperties.xsd +18 -0
  328. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesCustom.xsd +59 -0
  329. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesExtended.xsd +56 -0
  330. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesVariantTypes.xsd +195 -0
  331. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-math.xsd +582 -0
  332. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/shared-relationshipReference.xsd +25 -0
  333. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/sml.xsd +4439 -0
  334. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-main.xsd +570 -0
  335. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-officeDrawing.xsd +509 -0
  336. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-presentationDrawing.xsd +12 -0
  337. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-spreadsheetDrawing.xsd +108 -0
  338. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/vml-wordprocessingDrawing.xsd +96 -0
  339. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/wml.xsd +3646 -0
  340. package/assets/skills/xlsx/scripts/office/schemas/ISO-IEC29500-4_2016/xml.xsd +116 -0
  341. package/assets/skills/xlsx/scripts/office/schemas/ecma/fouth-edition/opc-contentTypes.xsd +42 -0
  342. package/assets/skills/xlsx/scripts/office/schemas/ecma/fouth-edition/opc-coreProperties.xsd +50 -0
  343. package/assets/skills/xlsx/scripts/office/schemas/ecma/fouth-edition/opc-digSig.xsd +49 -0
  344. package/assets/skills/xlsx/scripts/office/schemas/ecma/fouth-edition/opc-relationships.xsd +33 -0
  345. package/assets/skills/xlsx/scripts/office/schemas/mce/mc.xsd +75 -0
  346. package/assets/skills/xlsx/scripts/office/schemas/microsoft/wml-2010.xsd +560 -0
  347. package/assets/skills/xlsx/scripts/office/schemas/microsoft/wml-2012.xsd +67 -0
  348. package/assets/skills/xlsx/scripts/office/schemas/microsoft/wml-2018.xsd +14 -0
  349. package/assets/skills/xlsx/scripts/office/schemas/microsoft/wml-cex-2018.xsd +20 -0
  350. package/assets/skills/xlsx/scripts/office/schemas/microsoft/wml-cid-2016.xsd +13 -0
  351. package/assets/skills/xlsx/scripts/office/schemas/microsoft/wml-sdtdatahash-2020.xsd +4 -0
  352. package/assets/skills/xlsx/scripts/office/schemas/microsoft/wml-symex-2015.xsd +8 -0
  353. package/assets/skills/xlsx/scripts/office/soffice.py +191 -0
  354. package/assets/skills/xlsx/scripts/office/unpack.py +132 -0
  355. package/assets/skills/xlsx/scripts/office/validate.py +117 -0
  356. package/assets/skills/xlsx/scripts/office/validators/__init__.py +15 -0
  357. package/assets/skills/xlsx/scripts/office/validators/base.py +851 -0
  358. package/assets/skills/xlsx/scripts/office/validators/docx.py +446 -0
  359. package/assets/skills/xlsx/scripts/office/validators/pptx.py +275 -0
  360. package/assets/skills/xlsx/scripts/office/validators/redlining.py +247 -0
  361. package/assets/skills/xlsx/scripts/recalc.py +450 -0
  362. package/chunks/account-commands-JZ6NXTTK.js +2 -0
  363. package/chunks/anthropic-MN33DP4E.js +2 -0
  364. package/chunks/application-ITGAJ4HC.js +2 -0
  365. package/chunks/auth-command-V3RVPLZO.js +2 -0
  366. package/chunks/azure-openai-responses-OWHMUNKC.js +2 -0
  367. package/chunks/chunk-2TF6JAQM.js +2 -0
  368. package/chunks/chunk-33CNY6GP.js +2 -0
  369. package/chunks/chunk-3AODGLMF.js +2 -0
  370. package/chunks/chunk-44VPC5LA.js +38 -0
  371. package/chunks/chunk-4CN3IJFH.js +2 -0
  372. package/chunks/chunk-4PDIO3M6.js +2 -0
  373. package/chunks/chunk-4X22UJQH.js +164 -0
  374. package/chunks/chunk-6255CZPL.js +2 -0
  375. package/chunks/chunk-6P4UKHGR.js +2 -0
  376. package/chunks/chunk-7QLAXRD2.js +1085 -0
  377. package/chunks/chunk-7XYOYZX2.js +2 -0
  378. package/chunks/chunk-A7GMJNA2.js +29 -0
  379. package/chunks/chunk-AGUSPIUP.js +2 -0
  380. package/chunks/chunk-BQ3CF3KE.js +2 -0
  381. package/chunks/chunk-C3CMJAAV.js +3 -0
  382. package/chunks/chunk-CJM7ZJ6W.js +7 -0
  383. package/chunks/chunk-CSOUJVKM.js +2 -0
  384. package/chunks/chunk-D66ZSHXR.js +2 -0
  385. package/chunks/chunk-D7MGU75P.js +2 -0
  386. package/chunks/chunk-E3GLGDGC.js +5 -0
  387. package/chunks/chunk-ENHOPPS7.js +16 -0
  388. package/chunks/chunk-EOR6EDNR.js +2 -0
  389. package/chunks/chunk-EYK25HWR.js +2 -0
  390. package/chunks/chunk-F46IELF5.js +2 -0
  391. package/chunks/chunk-FC4M2B7E.js +2 -0
  392. package/chunks/chunk-FSNYOJPJ.js +2 -0
  393. package/chunks/chunk-FUERW2DW.js +3 -0
  394. package/chunks/chunk-FXOH6TEQ.js +21 -0
  395. package/chunks/chunk-GP52JZMY.js +2 -0
  396. package/chunks/chunk-GRXX6I72.js +2 -0
  397. package/chunks/chunk-GSYHBK5Q.js +6 -0
  398. package/chunks/chunk-HNWBFJNO.js +2 -0
  399. package/chunks/chunk-IIE366LR.js +6706 -0
  400. package/chunks/chunk-IWK7PZP7.js +207 -0
  401. package/chunks/chunk-J3KCPYZT.js +2 -0
  402. package/chunks/chunk-KCLRJQ53.js +59 -0
  403. package/chunks/chunk-LU4RPLJ3.js +2 -0
  404. package/chunks/chunk-LZJYNT32.js +2 -0
  405. package/chunks/chunk-M7GW4VMR.js +27 -0
  406. package/chunks/chunk-MACBL5HF.js +2 -0
  407. package/chunks/chunk-N5NTXCJI.js +2 -0
  408. package/chunks/chunk-N5SVBCUB.js +7 -0
  409. package/chunks/chunk-N6W7ZL26.js +2 -0
  410. package/chunks/chunk-NWB7LFOK.js +131 -0
  411. package/chunks/chunk-OIQ336YE.js +16 -0
  412. package/chunks/chunk-OQNU3VPS.js +30 -0
  413. package/chunks/chunk-OTDNOWXG.js +16 -0
  414. package/chunks/chunk-PNXZWSWT.js +3 -0
  415. package/chunks/chunk-QFUV5PX6.js +2 -0
  416. package/chunks/chunk-QIN5ZBE2.js +2 -0
  417. package/chunks/chunk-QKBN5CGI.js +2 -0
  418. package/chunks/chunk-QPGTKSIQ.js +2 -0
  419. package/chunks/chunk-SIOLUFGG.js +2 -0
  420. package/chunks/chunk-TW23QKAD.js +3 -0
  421. package/chunks/chunk-U3RMPDXU.js +2 -0
  422. package/chunks/chunk-U7U3DJHF.js +2 -0
  423. package/chunks/chunk-VLXX22YO.js +2 -0
  424. package/chunks/chunk-WHD2XVT2.js +2 -0
  425. package/chunks/chunk-WTAJMYF2.js +249 -0
  426. package/chunks/chunk-WWNUAU4P.js +29 -0
  427. package/chunks/chunk-WYANV3IX.js +4 -0
  428. package/chunks/chunk-XAGZ6ZEU.js +9 -0
  429. package/chunks/chunk-XFCC2CI2.js +24 -0
  430. package/chunks/chunk-XQK7JM66.js +2 -0
  431. package/chunks/chunk-YLQXZBEL.js +2 -0
  432. package/chunks/chunk-YPV2X2RG.js +2 -0
  433. package/chunks/chunk-Z6BHCXKT.js +25 -0
  434. package/chunks/chunk-Z6HBNJCA.js +8 -0
  435. package/chunks/chunk-ZQKVUPKA.js +2 -0
  436. package/chunks/chunk-ZQOALVGL.js +2 -0
  437. package/chunks/clipboard-image-PQPC4EHR.js +2 -0
  438. package/chunks/data-dir-LDVKDCJ2.js +2 -0
  439. package/chunks/dist-2BRD4JFU.js +11 -0
  440. package/chunks/dist-EXKHRFQO.js +5 -0
  441. package/chunks/emscripten-module-RD6P2XH5.js +2 -0
  442. package/chunks/emscripten-module-WYNDFH3N.js +2 -0
  443. package/chunks/emscripten-module-XPTEOIWW.js +2 -0
  444. package/chunks/emscripten-module-ZS3PMSDF.js +2 -0
  445. package/chunks/ffi-IO7WZQNG.js +2 -0
  446. package/chunks/ffi-M5UP5J6C.js +2 -0
  447. package/chunks/ffi-ORLOPBB3.js +2 -0
  448. package/chunks/ffi-OUPK6AY6.js +2 -0
  449. package/chunks/google-UJAPMFAB.js +2 -0
  450. package/chunks/google-vertex-VLSF55PW.js +2 -0
  451. package/chunks/install-source-JTIUC4G4.js +2 -0
  452. package/chunks/launcher-FCZ3EDBF.js +61 -0
  453. package/chunks/lifecycle-GY435YMF.js +2 -0
  454. package/chunks/main-TQGGRHTS.js +13 -0
  455. package/chunks/mistral-ZJZUEF2X.js +3 -0
  456. package/chunks/module-6F3E5H7Y-BN7QWGYB.js +2 -0
  457. package/chunks/module-asyncify-R6PWJ6ZV-P4FWSBAY.js +2 -0
  458. package/chunks/multipart-parser-L6M455MS.js +2 -0
  459. package/chunks/network-proxy-U72JCK2I.js +2 -0
  460. package/chunks/openai-codex-responses-FPCDNRL5.js +2 -0
  461. package/chunks/openai-completions-D32YW6KL.js +2 -0
  462. package/chunks/openai-responses-ZCGSENM4.js +2 -0
  463. package/chunks/openrouter-G2EHY5BD.js +2 -0
  464. package/chunks/otel-OHXIZ666.js +2 -0
  465. package/chunks/package-contract-GVXTMJ3N.js +2 -0
  466. package/chunks/pdfjs-SHZAF7PF.js +107 -0
  467. package/chunks/photon_rs-C52RL4CI.js +3 -0
  468. package/chunks/plugin-command-OSAFHS7C.js +2 -0
  469. package/chunks/provider-command-SKTCHD4E.js +2 -0
  470. package/chunks/questionnaire-bridge-ISQOCYWY.js +2 -0
  471. package/chunks/run-acp-command-SG2BDMFJ.js +2 -0
  472. package/chunks/run-exec-command-5ADSQR2Z.js +15 -0
  473. package/chunks/skills-command-XXXEZAG6.js +2 -0
  474. package/chunks/src-DNIDEMVV.js +2 -0
  475. package/chunks/src-IBHIRTD7.js +2 -0
  476. package/chunks/telemetry-J7ZLGF5X.js +2 -0
  477. package/chunks/telemetry-command-COQG2AKK.js +5 -0
  478. package/chunks/tools-WDBB2JKV.js +2 -0
  479. package/chunks/undici-TUGHZJSA.js +2 -0
  480. package/chunks/update-NB6OD572.js +14 -0
  481. package/chunks/update-hint-ED7O67WU.js +3 -0
  482. package/chunks/wechat-onboard-UWXQW2HT.js +2 -0
  483. package/cli.js +5 -0
  484. package/configs/data-minimal.yaml +50 -0
  485. package/embedded/alran-tools/cli.mjs +4961 -0
  486. package/embedded/alran-tools/manifest.json +25 -0
  487. package/emscripten-module.wasm +0 -0
  488. package/image-preview-worker.js +2 -0
  489. package/internal-bin/alran-tools +9 -0
  490. package/internal-bin/alran-tools.cmd +8 -0
  491. package/matrix-mcp-stdio.js +4 -0
  492. package/native/darwin/prebuilds/darwin-arm64/darwin-modifiers.node +0 -0
  493. package/native/darwin/prebuilds/darwin-x64/darwin-modifiers.node +0 -0
  494. package/native/win32/prebuilds/win32-arm64/win32-console-mode.node +0 -0
  495. package/native/win32/prebuilds/win32-x64/win32-console-mode.node +0 -0
  496. package/package.json +38 -4
  497. package/photon_rs_bg.wasm +0 -0
  498. package/quickjs-worker.js +152 -0
  499. package/vendor/java-proxy-agent/build.ts +97 -0
  500. package/vendor/java-proxy-agent/srt-proxy-agent.jar +0 -0
  501. package/vendor/seccomp/arm64/apply-seccomp +0 -0
  502. package/vendor/seccomp/build.ts +74 -0
  503. package/vendor/seccomp/x64/apply-seccomp +0 -0
  504. package/vendor/srt-win/arm64/srt-win.exe +0 -0
  505. package/vendor/srt-win/build.ts +40 -0
  506. package/vendor/srt-win/x64/srt-win.exe +0 -0
@@ -0,0 +1,29 @@
1
+ import { createRequire as __alran_cR } from "module"; import { basename as __alran_basename, dirname as __alran_dirname, join as __alran_join } from "path"; import { fileURLToPath as __alran_fileURLToPath, pathToFileURL as __alran_pathToFileURL } from "url"; const __alran_tuiCurrentModuleDir = __alran_dirname(__alran_fileURLToPath(import.meta.url)); const __alran_tuiPackageRoot = __alran_basename(__alran_tuiCurrentModuleDir) === "chunks" ? __alran_dirname(__alran_tuiCurrentModuleDir) : __alran_tuiCurrentModuleDir; const __alran_tuiPackageEntryUrl = __alran_pathToFileURL(__alran_join(__alran_tuiPackageRoot, "cli.js")).href; const require = __alran_cR(__alran_tuiPackageEntryUrl); const __dirname = __alran_tuiPackageRoot;
2
+ import{b as Or,c as Br,d as Lr}from"./chunk-N6W7ZL26.js";import{a as Ir,b as zt}from"./chunk-J3KCPYZT.js";import{a as Mr}from"./chunk-3AODGLMF.js";import{d as Gt,f as Tr,h as Cr,i as $r,j as Nr,k as Fr,l as jr}from"./chunk-VLXX22YO.js";import{a as q}from"./chunk-7XYOYZX2.js";function p(n,e,t,r,s){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e==="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?s.call(n,t):s?s.value=t:e.set(n,t),t}function i(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e==="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)}var Qt=function(){const{crypto:n}=globalThis;if(n?.randomUUID){Qt=n.randomUUID.bind(n);return n.randomUUID()}const e=new Uint8Array(1);const t=n?()=>n.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^t()&15>>+r/4).toString(16))};function H(n){return typeof n==="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}var We=n=>{if(n instanceof Error)return n;if(typeof n==="object"&&n!==null){try{if(Object.prototype.toString.call(n)==="[object Error]"){const e=new Error(n.message,n.cause?{cause:n.cause}:{});if(n.stack)e.stack=n.stack;if(n.cause&&!e.cause)e.cause=n.cause;if(n.name)e.name=n.name;return e}}catch{}try{return new Error(JSON.stringify(n))}catch{}}return new Error(n)};var g=class extends Error{};var R=class n extends g{constructor(e,t,r,s,o){super(`${n.makeMessage(e,t,r)}`);this.status=e;this.headers=s;this.requestID=s?.get("request-id");this.error=t;this.type=o??null}static makeMessage(e,t,r){const s=t?.message?typeof t.message==="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;if(e&&s){return`${e} ${s}`}if(e){return`${e} status code (no body)`}if(s){return s}return"(no status code or body)"}static generate(e,t,r,s){if(!e||!s){return new G({message:r,cause:We(t)})}const o=t;const a=o?.["error"]?.["type"];if(e===400){return new me(e,o,r,s,a)}if(e===401){return new ge(e,o,r,s,a)}if(e===403){return new _e(e,o,r,s,a)}if(e===404){return new be(e,o,r,s,a)}if(e===409){return new ye(e,o,r,s,a)}if(e===422){return new we(e,o,r,s,a)}if(e===429){return new xe(e,o,r,s,a)}if(e>=500){return new Se(e,o,r,s,a)}return new n(e,o,r,s,a)}};var T=class extends R{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}};var G=class extends R{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0);if(t)this.cause=t}};var fe=class extends G{constructor({message:e}={}){super({message:e??"Request timed out."})}};var me=class extends R{};var ge=class extends R{};var _e=class extends R{};var be=class extends R{};var ye=class extends R{};var we=class extends R{};var xe=class extends R{};var Se=class extends R{};var qs=/^[a-z][a-z0-9+.-]*:/i;var qr=n=>{return qs.test(n)};var Yt=n=>(Yt=Array.isArray,Yt(n));var Zt=Yt;function gt(n){if(typeof n!=="object"){return{}}return n??{}}function er(n){if(!n)return true;for(const e in n)return false;return true}function Ur(n,e){return Object.prototype.hasOwnProperty.call(n,e)}var Hr=(n,e)=>{if(typeof e!=="number"||!Number.isInteger(e)){throw new g(`${n} must be an integer`)}if(e<0){throw new g(`${n} must be a positive integer`)}return e};var _t=n=>{try{return JSON.parse(n)}catch(e){return void 0}};var Dr=n=>new Promise(e=>setTimeout(e,n));var z="0.91.1";var Xr=()=>{return typeof window!=="undefined"&&typeof window.document!=="undefined"&&typeof navigator!=="undefined"};function Us(){if(typeof Deno!=="undefined"&&Deno.build!=null){return"deno"}if(typeof EdgeRuntime!=="undefined"){return"edge"}if(Object.prototype.toString.call(typeof globalThis.process!=="undefined"?globalThis.process:0)==="[object process]"){return"node"}return"unknown"}var Hs=()=>{const n=Us();if(n==="deno"){return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z,"X-Stainless-OS":Jr(Deno.build.os),"X-Stainless-Arch":Wr(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"}}if(typeof EdgeRuntime!=="undefined"){return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version}}if(n==="node"){return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z,"X-Stainless-OS":Jr(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Wr(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"}}const e=Ds();if(e){return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}}return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":z,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Ds(){if(typeof navigator==="undefined"||!navigator){return null}const n=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:t}of n){const r=t.exec(navigator.userAgent);if(r){const s=r[1]||0;const o=r[2]||0;const a=r[3]||0;return{browser:e,version:`${s}.${o}.${a}`}}}return null}var Wr=n=>{if(n==="x32")return"x32";if(n==="x86_64"||n==="x64")return"x64";if(n==="arm")return"arm";if(n==="aarch64"||n==="arm64")return"arm64";if(n)return`other:${n}`;return"unknown"};var Jr=n=>{n=n.toLowerCase();if(n.includes("ios"))return"iOS";if(n==="android")return"Android";if(n==="darwin")return"MacOS";if(n==="win32")return"Windows";if(n==="freebsd")return"FreeBSD";if(n==="openbsd")return"OpenBSD";if(n==="linux")return"Linux";if(n)return`Other:${n}`;return"Unknown"};var Vr;var Kr=()=>{return Vr??(Vr=Hs())};function Gr(){if(typeof fetch!=="undefined"){return fetch}throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function tr(...n){const e=globalThis.ReadableStream;if(typeof e==="undefined"){throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`")}return new e(...n)}function bt(n){let e=Symbol.asyncIterator in n?n[Symbol.asyncIterator]():n[Symbol.iterator]();return tr({start(){},async pull(t){const{done:r,value:s}=await e.next();if(r){t.close()}else{t.enqueue(s)}},async cancel(){await e.return?.()}})}function Je(n){if(n[Symbol.asyncIterator])return n;const e=n.getReader();return{async next(){try{const t=await e.read();if(t?.done)e.releaseLock();return t}catch(t){e.releaseLock();throw t}},async return(){const t=e.cancel();e.releaseLock();await t;return{done:true,value:void 0}},[Symbol.asyncIterator](){return this}}}async function zr(n){if(n===null||typeof n!=="object")return;if(n[Symbol.asyncIterator]){await n[Symbol.asyncIterator]().return?.();return}const e=n.getReader();const t=e.cancel();e.releaseLock();await t}var Qr=({headers:n,body:e})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}};function Yr(n){return Object.entries(n).filter(([e,t])=>typeof t!=="undefined").map(([e,t])=>{if(typeof t==="string"||typeof t==="number"||typeof t==="boolean"){return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`}if(t===null){return`${encodeURIComponent(e)}=`}throw new g(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}function ts(n){let e=0;for(const s of n){e+=s.length}const t=new Uint8Array(e);let r=0;for(const s of n){t.set(s,r);r+=s.length}return t}var Zr;function Ve(n){let e;return(Zr??(e=new globalThis.TextEncoder,Zr=e.encode.bind(e)))(n)}var es;function rr(n){let e;return(es??(e=new globalThis.TextDecoder,es=e.decode.bind(e)))(n)}var $;var O;var D=class{constructor(){$.set(this,void 0);O.set(this,void 0);p(this,$,new Uint8Array,"f");p(this,O,null,"f")}decode(e){if(e==null){return[]}const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==="string"?Ve(e):e;p(this,$,ts([i(this,$,"f"),t]),"f");const r=[];let s;while((s=Vs(i(this,$,"f"),i(this,O,"f")))!=null){if(s.carriage&&i(this,O,"f")==null){p(this,O,s.index,"f");continue}if(i(this,O,"f")!=null&&(s.index!==i(this,O,"f")+1||s.carriage)){r.push(rr(i(this,$,"f").subarray(0,i(this,O,"f")-1)));p(this,$,i(this,$,"f").subarray(i(this,O,"f")),"f");p(this,O,null,"f");continue}const o=i(this,O,"f")!==null?s.preceding-1:s.preceding;const a=rr(i(this,$,"f").subarray(0,o));r.push(a);p(this,$,i(this,$,"f").subarray(s.index),"f");p(this,O,null,"f")}return r}flush(){if(!i(this,$,"f").length){return[]}return this.decode("\n")}};$=new WeakMap,O=new WeakMap;D.NEWLINE_CHARS=new Set(["\n","\r"]);D.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Vs(n,e){const t=10;const r=13;for(let s=e??0;s<n.length;s++){if(n[s]===t){return{preceding:s,index:s+1,carriage:false}}if(n[s]===r){return{preceding:s,index:s+1,carriage:true}}}return null}function rs(n){const e=10;const t=13;for(let r=0;r<n.length-1;r++){if(n[r]===e&&n[r+1]===e){return r+2}if(n[r]===t&&n[r+1]===t){return r+2}if(n[r]===t&&n[r+1]===e&&r+3<n.length&&n[r+2]===t&&n[r+3]===e){return r+4}}return-1}var wt={off:0,error:200,warn:300,info:400,debug:500};var sr=(n,e,t)=>{if(!n){return void 0}if(Ur(wt,n)){return n}M(t).warn(`${e} was set to ${JSON.stringify(n)}, expected one of ${JSON.stringify(Object.keys(wt))}`);return void 0};function Xe(){}function yt(n,e,t){if(!e||wt[n]>wt[t]){return Xe}else{return e[n].bind(e)}}var Xs={error:Xe,warn:Xe,info:Xe,debug:Xe};var ss=new WeakMap;function M(n){const e=n.logger;const t=n.logLevel??"off";if(!e){return Xs}const r=ss.get(e);if(r&&r[0]===t){return r[1]}const s={error:yt("error",e,t),warn:yt("warn",e,t),info:yt("info",e,t),debug:yt("debug",e,t)};ss.set(e,[t,s]);return s}var W=n=>{if(n.options){n.options={...n.options};delete n.options["headers"]}if(n.headers){n.headers=Object.fromEntries((n.headers instanceof Headers?[...n.headers]:Object.entries(n.headers)).map(([e,t])=>[e,e.toLowerCase()==="x-api-key"||e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))}if("retryOfRequestLogID"in n){if(n.retryOfRequestLogID){n.retryOf=n.retryOfRequestLogID}delete n.retryOfRequestLogID}return n};var Ke;var U=class n{constructor(e,t,r){this.iterator=e;Ke.set(this,void 0);this.controller=t;p(this,Ke,r,"f")}static fromSSEResponse(e,t,r){let s=false;const o=r?M(r):console;async function*a(){if(s){throw new g("Cannot iterate over a consumed stream, use `.tee()` to split the stream.")}s=true;let c=false;try{for await(const l of Ks(e,t)){if(l.event==="completion"){try{yield JSON.parse(l.data)}catch(h){o.error(`Could not parse message into JSON:`,l.data);o.error(`From chunk:`,l.raw);throw h}}if(l.event==="message_start"||l.event==="message_delta"||l.event==="message_stop"||l.event==="content_block_start"||l.event==="content_block_delta"||l.event==="content_block_stop"||l.event==="message"||l.event==="user.message"||l.event==="user.interrupt"||l.event==="user.tool_confirmation"||l.event==="user.custom_tool_result"||l.event==="agent.message"||l.event==="agent.thinking"||l.event==="agent.tool_use"||l.event==="agent.tool_result"||l.event==="agent.mcp_tool_use"||l.event==="agent.mcp_tool_result"||l.event==="agent.custom_tool_use"||l.event==="agent.thread_context_compacted"||l.event==="session.status_running"||l.event==="session.status_idle"||l.event==="session.status_rescheduled"||l.event==="session.status_terminated"||l.event==="session.error"||l.event==="session.deleted"||l.event==="span.model_request_start"||l.event==="span.model_request_end"){try{yield JSON.parse(l.data)}catch(h){o.error(`Could not parse message into JSON:`,l.data);o.error(`From chunk:`,l.raw);throw h}}if(l.event==="ping"){continue}if(l.event==="error"){const h=_t(l.data)??l.data;const f=h?.error?.type;throw new R(void 0,h,void 0,e.headers,f)}}c=true}catch(l){if(H(l))return;throw l}finally{if(!c)t.abort()}}return new n(a,t,r)}static fromReadableStream(e,t,r){let s=false;async function*o(){const c=new D;const l=Je(e);for await(const h of l){for(const f of c.decode(h)){yield f}}for(const h of c.flush()){yield h}}async function*a(){if(s){throw new g("Cannot iterate over a consumed stream, use `.tee()` to split the stream.")}s=true;let c=false;try{for await(const l of o()){if(c)continue;if(l)yield JSON.parse(l)}c=true}catch(l){if(H(l))return;throw l}finally{if(!c)t.abort()}}return new n(a,t,r)}[(Ke=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[];const t=[];const r=this.iterator();const s=o=>{return{next:()=>{if(o.length===0){const a=r.next();e.push(a);t.push(a)}return o.shift()}}};return[new n(()=>s(e),this.controller,i(this,Ke,"f")),new n(()=>s(t),this.controller,i(this,Ke,"f"))]}toReadableStream(){const e=this;let t;return tr({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{const{value:s,done:o}=await t.next();if(o)return r.close();const a=Ve(JSON.stringify(s)+"\n");r.enqueue(a)}catch(s){r.error(s)}},async cancel(){await t.return?.()}})}};async function*Ks(n,e){if(!n.body){e.abort();if(typeof globalThis.navigator!=="undefined"&&globalThis.navigator.product==="ReactNative"){throw new g(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`)}throw new g(`Attempted to iterate over a response with no body`)}const t=new nr;const r=new D;const s=Je(n.body);for await(const o of Gs(s)){for(const a of r.decode(o)){const c=t.decode(a);if(c)yield c}}for(const o of r.flush()){const a=t.decode(o);if(a)yield a}}async function*Gs(n){let e=new Uint8Array;for await(const t of n){if(t==null){continue}const r=t instanceof ArrayBuffer?new Uint8Array(t):typeof t==="string"?Ve(t):t;let s=new Uint8Array(e.length+r.length);s.set(e);s.set(r,e.length);e=s;let o;while((o=rs(e))!==-1){yield e.slice(0,o);e=e.slice(o)}}if(e.length>0){yield e}}var nr=class{constructor(){this.event=null;this.data=[];this.chunks=[]}decode(e){if(e.endsWith("\r")){e=e.substring(0,e.length-1)}if(!e){if(!this.event&&!this.data.length)return null;const o={event:this.event,data:this.data.join("\n"),raw:this.chunks};this.event=null;this.data=[];this.chunks=[];return o}this.chunks.push(e);if(e.startsWith(":")){return null}let[t,r,s]=zs(e,":");if(s.startsWith(" ")){s=s.substring(1)}if(t==="event"){this.event=s}else if(t==="data"){this.data.push(s)}return null}};function zs(n,e){const t=n.indexOf(e);if(t!==-1){return[n.substring(0,t),e,n.substring(t+e.length)]}return[n,"",""]}async function xt(n,e){const{response:t,requestLogID:r,retryOfRequestLogID:s,startTime:o}=e;const a=await(async()=>{if(e.options.stream){M(n).debug("response",t.status,t.url,t.headers,t.body);if(e.options.__streamClass){return e.options.__streamClass.fromSSEResponse(t,e.controller)}return U.fromSSEResponse(t,e.controller)}if(t.status===204){return null}if(e.options.__binaryResponse){return t}const c=t.headers.get("content-type");const l=c?.split(";")[0]?.trim();const h=l?.includes("application/json")||l?.endsWith("+json");if(h){const m=t.headers.get("content-length");if(m==="0"){return void 0}const x=await t.json();return or(x,t)}const f=await t.text();return f})();M(n).debug(`[${r}] response parsed`,W({retryOfRequestLogID:s,url:t.url,status:t.status,body:a,durationMs:Date.now()-o}));return a}function or(n,e){if(!n||typeof n!=="object"||Array.isArray(n)){return n}return Object.defineProperty(n,"_request_id",{value:e.headers.get("request-id"),enumerable:false})}var Ge;var se=class n extends Promise{constructor(e,t,r=xt){super(s=>{s(null)});this.responsePromise=t;this.parseResponse=r;Ge.set(this,void 0);p(this,Ge,e,"f")}_thenUnwrap(e){return new n(i(this,Ge,"f"),this.responsePromise,async(t,r)=>or(e(await this.parseResponse(t,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("request-id")}}parse(){if(!this.parsedPromise){this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(i(this,Ge,"f"),e))}return this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};Ge=new WeakMap;var St;var kt=class{constructor(e,t,r,s){St.set(this,void 0);p(this,St,e,"f");this.options=s;this.response=t;this.body=r}hasNextPage(){const e=this.getPaginatedItems();if(!e.length)return false;return this.nextPageRequestOptions()!=null}async getNextPage(){const e=this.nextPageRequestOptions();if(!e){throw new g("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.")}return await i(this,St,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;yield e;while(e.hasNextPage()){e=await e.getNextPage();yield e}}async*[(St=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages()){for(const t of e.getPaginatedItems()){yield t}}}};var ze=class extends se{constructor(e,t,r){super(e,t,async(s,o)=>new r(s,o.response,await xt(s,o),o.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e){yield t}}};var N=class extends kt{constructor(e,t,r,s){super(e,t,r,s);this.data=r.data||[];this.has_more=r.has_more||false;this.first_id=r.first_id||null;this.last_id=r.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===false){return false}return super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.["before_id"]){const t=this.first_id;if(!t){return null}return{...this.options,query:{...gt(this.options.query),before_id:t}}}const e=this.last_id;if(!e){return null}return{...this.options,query:{...gt(this.options.query),after_id:e}}}};var k=class extends kt{constructor(e,t,r,s){super(e,t,r,s);this.data=r.data||[];this.next_page=r.next_page||null}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){const e=this.next_page;if(!e){return null}return{...this.options,query:{...gt(this.options.query),page:e}}}};var ir=()=>{if(typeof File==="undefined"){const{process:n}=globalThis;const e=typeof n?.versions?.node==="string"&&parseInt(n.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function ne(n,e,t){ir();return new File(n,e??"unknown_file",t)}function Qe(n,e){const t=typeof n==="object"&&n!==null&&("name"in n&&n.name&&String(n.name)||"url"in n&&n.url&&String(n.url)||"filename"in n&&n.filename&&String(n.filename)||"path"in n&&n.path&&String(n.path))||"";return e?t.split(/[\\/]/).pop()||void 0:t}var cr=n=>n!=null&&typeof n==="object"&&typeof n[Symbol.asyncIterator]==="function";var ke=async(n,e,t=true)=>{return{...n,body:await Zs(n.body,e,t)}};var ns=new WeakMap;function Ys(n){const e=typeof n==="function"?n:n.fetch;const t=ns.get(e);if(t)return t;const r=(async()=>{try{const s="Response"in e?e.Response:(await e("data:,")).constructor;const o=new FormData;if(o.toString()===await new s(o).text()){return false}return true}catch{return true}})();ns.set(e,r);return r}var Zs=async(n,e,t=true)=>{if(!await Ys(e)){throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.")}const r=new FormData;await Promise.all(Object.entries(n||{}).map(([s,o])=>ar(r,s,o,t)));return r};var en=n=>n instanceof Blob&&"name"in n;var ar=async(n,e,t,r)=>{if(t===void 0)return;if(t==null){throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`)}if(typeof t==="string"||typeof t==="number"||typeof t==="boolean"){n.append(e,String(t))}else if(t instanceof Response){let s={};const o=t.headers.get("Content-Type");if(o){s={type:o}}n.append(e,ne([await t.blob()],Qe(t,r),s))}else if(cr(t)){n.append(e,ne([await new Response(bt(t)).blob()],Qe(t,r)))}else if(en(t)){n.append(e,ne([t],Qe(t,r),{type:t.type}))}else if(Array.isArray(t)){await Promise.all(t.map(s=>ar(n,e+"[]",s,r)))}else if(typeof t==="object"){await Promise.all(Object.entries(t).map(([s,o])=>ar(n,`${e}[${s}]`,o,r)))}else{throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}};var os=n=>n!=null&&typeof n==="object"&&typeof n.size==="number"&&typeof n.type==="string"&&typeof n.text==="function"&&typeof n.slice==="function"&&typeof n.arrayBuffer==="function";var tn=n=>n!=null&&typeof n==="object"&&typeof n.name==="string"&&typeof n.lastModified==="number"&&os(n);var rn=n=>n!=null&&typeof n==="object"&&typeof n.url==="string"&&typeof n.blob==="function";async function vt(n,e,t){ir();n=await n;e||(e=Qe(n,true));if(tn(n)){if(n instanceof File&&e==null&&t==null){return n}return ne([await n.arrayBuffer()],e??n.name,{type:n.type,lastModified:n.lastModified,...t})}if(rn(n)){const s=await n.blob();e||(e=new URL(n.url).pathname.split(/[\\/]/).pop());return ne(await lr(s),e,t)}const r=await lr(n);if(!t?.type){const s=r.find(o=>typeof o==="object"&&"type"in o&&o.type);if(typeof s==="string"){t={...t,type:s}}}return ne(r,e,t)}async function lr(n){let e=[];if(typeof n==="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer){e.push(n)}else if(os(n)){e.push(n instanceof Blob?n:await n.arrayBuffer())}else if(cr(n)){for await(const t of n){e.push(...await lr(t))}}else{const t=n?.constructor?.name;throw new Error(`Unexpected data type: ${typeof n}${t?`; constructor: ${t}`:""}${sn(n)}`)}return e}function sn(n){if(typeof n!=="object"||n===null)return"";const e=Object.getOwnPropertyNames(n);return`; props: [${e.map(t=>`"${t}"`).join(", ")}]`}var y=class{constructor(e){this._client=e}};var as=Symbol.for("brand.privateNullableHeaders");function*on(n){if(!n)return;if(as in n){const{values:r,nulls:s}=n;yield*r.entries();for(const o of s){yield[o,null]}return}let e=false;let t;if(n instanceof Headers){t=n.entries()}else if(Zt(n)){t=n}else{e=true;t=Object.entries(n??{})}for(let r of t){const s=r[0];if(typeof s!=="string")throw new TypeError("expected header name to be a string");const o=Zt(r[1])?r[1]:[r[1]];let a=false;for(const c of o){if(c===void 0)continue;if(e&&!a){a=true;yield[s,null]}yield[s,c]}}}var u=n=>{const e=new Headers;const t=new Set;for(const r of n){const s=new Set;for(const[o,a]of on(r)){const c=o.toLowerCase();if(!s.has(c)){e.delete(o);s.add(c)}if(a===null){e.delete(o);t.add(c)}else{e.append(o,a);t.delete(c)}}}return{[as]:true,values:e,nulls:t}};function cs(n){return n.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var is=Object.freeze(Object.create(null));var an=(n=cs)=>function e(t,...r){if(t.length===1)return t[0];let s=false;const o=[];const a=t.reduce((f,m,x)=>{if(/[?#]/.test(m)){s=true}const _=r[x];let E=(s?encodeURIComponent:n)(""+_);if(x!==r.length&&(_==null||typeof _==="object"&&_.toString===Object.getPrototypeOf(Object.getPrototypeOf(_.hasOwnProperty??is)??is)?.toString)){E=_+"";o.push({start:f.length+m.length,length:E.length,error:`Value of type ${Object.prototype.toString.call(_).slice(8,-1)} is not a valid path parameter`})}return f+m+(x===r.length?"":E)},"");const c=a.split(/[?#]/,1)[0];const l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;let h;while((h=l.exec(c))!==null){o.push({start:h.index,length:h[0].length,error:`Value "${h[0]}" can't be safely passed as a path parameter`})}o.sort((f,m)=>f.start-m.start);if(o.length>0){let f=0;const m=o.reduce((x,_)=>{const E=" ".repeat(_.start-f);const b="^".repeat(_.length);f=_.start+_.length;return x+E+b},"");throw new g(`Path parameters result in path with invalid segments:
3
+ ${o.map(x=>x.error).join("\n")}
4
+ ${a}
5
+ ${m}`)}return a};var d=an(cs);var ve=class extends y{create(e,t){const{betas:r,...s}=e;return this._client.post("/v1/environments?beta=true",{body:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}retrieve(e,t={},r){const{betas:s}=t??{};return this._client.get(d`/v1/environments/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){const{betas:s,...o}=t;return this._client.post(d`/v1/environments/${e}?beta=true`,{body:o,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},t){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/environments?beta=true",k,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}delete(e,t={},r){const{betas:s}=t??{};return this._client.delete(d`/v1/environments/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,t={},r){const{betas:s}=t??{};return this._client.post(d`/v1/environments/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};var Ye=Symbol("anthropic.sdk.stainlessHelper");function At(n){return typeof n==="object"&&n!==null&&Ye in n}function ur(n,e){const t=new Set;if(n){for(const r of n){if(At(r)){t.add(r[Ye])}}}if(e){for(const r of e){if(At(r)){t.add(r[Ye])}if(Array.isArray(r.content)){for(const s of r.content){if(At(s)){t.add(s[Ye])}}}}}return Array.from(t)}function Pt(n,e){const t=ur(n,e);if(t.length===0)return{};return{"x-stainless-helper":t.join(", ")}}function ls(n){if(At(n)){return{"x-stainless-helper":n[Ye]}}return{}}var Ae=class extends y{list(e={},t){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/files?beta=true",N,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},t?.headers])})}delete(e,t={},r){const{betas:s}=t??{};return this._client.delete(d`/v1/files/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"files-api-2025-04-14"].toString()},r?.headers])})}download(e,t={},r){const{betas:s}=t??{};return this._client.get(d`/v1/files/${e}/content?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},r?.headers]),__binaryResponse:true})}retrieveMetadata(e,t={},r){const{betas:s}=t??{};return this._client.get(d`/v1/files/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"files-api-2025-04-14"].toString()},r?.headers])})}upload(e,t){const{betas:r,...s}=e;return this._client.post("/v1/files?beta=true",ke({body:s,...t,headers:u([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},ls(s.file),t?.headers])},this._client))}};var Pe=class extends y{retrieve(e,t={},r){const{betas:s}=t??{};return this._client.get(d`/v1/models/${e}?beta=true`,{...r,headers:u([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},r?.headers])})}list(e={},t){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/models?beta=true",N,{query:s,...t,headers:u([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},t?.headers])})}};var Ee=class extends y{create(e,t){const{betas:r,...s}=e;return this._client.post("/v1/user_profiles?beta=true",{body:s,...t,headers:u([{"anthropic-beta":[...r??[],"user-profiles-2026-03-24"].toString()},t?.headers])})}retrieve(e,t={},r){const{betas:s}=t??{};return this._client.get(d`/v1/user_profiles/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"user-profiles-2026-03-24"].toString()},r?.headers])})}update(e,t,r){const{betas:s,...o}=t;return this._client.post(d`/v1/user_profiles/${e}?beta=true`,{body:o,...r,headers:u([{"anthropic-beta":[...s??[],"user-profiles-2026-03-24"].toString()},r?.headers])})}list(e={},t){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/user_profiles?beta=true",k,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"user-profiles-2026-03-24"].toString()},t?.headers])})}createEnrollmentURL(e,t={},r){const{betas:s}=t??{};return this._client.post(d`/v1/user_profiles/${e}/enrollment_url?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"user-profiles-2026-03-24"].toString()},r?.headers])})}};var Re=class extends y{list(e,t={},r){const{betas:s,...o}=t??{};return this._client.getAPIList(d`/v1/agents/${e}/versions?beta=true`,k,{query:o,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};var oe=class extends y{constructor(){super(...arguments);this.versions=new Re(this._client)}create(e,t){const{betas:r,...s}=e;return this._client.post("/v1/agents?beta=true",{body:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}retrieve(e,t={},r){const{betas:s,...o}=t??{};return this._client.get(d`/v1/agents/${e}?beta=true`,{query:o,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){const{betas:s,...o}=t;return this._client.post(d`/v1/agents/${e}?beta=true`,{body:o,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},t){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/agents?beta=true",k,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}archive(e,t={},r){const{betas:s}=t??{};return this._client.post(d`/v1/agents/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};oe.Versions=Re;var Me=class extends y{create(e,t,r){const{view:s,betas:o,...a}=t;return this._client.post(d`/v1/memory_stores/${e}/memories?beta=true`,{query:{view:s},body:a,...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}retrieve(e,t,r){const{memory_store_id:s,betas:o,...a}=t;return this._client.get(d`/v1/memory_stores/${s}/memories/${e}?beta=true`,{query:a,...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){const{memory_store_id:s,view:o,betas:a,...c}=t;return this._client.post(d`/v1/memory_stores/${s}/memories/${e}?beta=true`,{query:{view:o},body:c,...r,headers:u([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e,t={},r){const{betas:s,...o}=t??{};return this._client.getAPIList(d`/v1/memory_stores/${e}/memories?beta=true`,k,{query:o,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}delete(e,t,r){const{memory_store_id:s,expected_content_sha256:o,betas:a}=t;return this._client.delete(d`/v1/memory_stores/${s}/memories/${e}?beta=true`,{query:{expected_content_sha256:o},...r,headers:u([{"anthropic-beta":[...a??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};var Te=class extends y{retrieve(e,t,r){const{memory_store_id:s,betas:o,...a}=t;return this._client.get(d`/v1/memory_stores/${s}/memory_versions/${e}?beta=true`,{query:a,...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e,t={},r){const{betas:s,...o}=t??{};return this._client.getAPIList(d`/v1/memory_stores/${e}/memory_versions?beta=true`,k,{query:o,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}redact(e,t,r){const{memory_store_id:s,betas:o}=t;return this._client.post(d`/v1/memory_stores/${s}/memory_versions/${e}/redact?beta=true`,{...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};var Q=class extends y{constructor(){super(...arguments);this.memories=new Me(this._client);this.memoryVersions=new Te(this._client)}create(e,t){const{betas:r,...s}=e;return this._client.post("/v1/memory_stores?beta=true",{body:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}retrieve(e,t={},r){const{betas:s}=t??{};return this._client.get(d`/v1/memory_stores/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){const{betas:s,...o}=t;return this._client.post(d`/v1/memory_stores/${e}?beta=true`,{body:o,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},t){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/memory_stores?beta=true",k,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}delete(e,t={},r){const{betas:s}=t??{};return this._client.delete(d`/v1/memory_stores/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,t={},r){const{betas:s}=t??{};return this._client.post(d`/v1/memory_stores/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};Q.Memories=Me;Q.MemoryVersions=Te;var Et={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};function us(n){return n?.output_format??n?.output_config?.format}function hr(n,e,t){const r=us(e);if(!e||!("parse"in(r??{}))){return{...n,content:n.content.map(s=>{if(s.type==="text"){const o=Object.defineProperty({...s},"parsed_output",{value:null,enumerable:false});return Object.defineProperty(o,"parsed",{get(){t.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead.");return null},enumerable:false})}return s}),parsed_output:null}}return dr(n,e,t)}function dr(n,e,t){let r=null;const s=n.content.map(o=>{if(o.type==="text"){const a=_n(e,o.text);if(r===null){r=a}const c=Object.defineProperty({...o},"parsed_output",{value:a,enumerable:false});return Object.defineProperty(c,"parsed",{get(){t.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead.");return a},enumerable:false})}return o});return{...n,content:s,parsed_output:r}}function _n(n,e){const t=us(n);if(t?.type!=="json_schema"){return null}try{if("parse"in t){return t.parse(e)}return JSON.parse(e)}catch(r){throw new g(`Failed to parse structured output: ${r}`)}}var bn=n=>{let e=0;let t=[];while(e<n.length){let r=n[e];if(r==="\\"){e++;continue}if(r==="{"){t.push({type:"brace",value:"{"});e++;continue}if(r==="}"){t.push({type:"brace",value:"}"});e++;continue}if(r==="["){t.push({type:"paren",value:"["});e++;continue}if(r==="]"){t.push({type:"paren",value:"]"});e++;continue}if(r===":"){t.push({type:"separator",value:":"});e++;continue}if(r===","){t.push({type:"delimiter",value:","});e++;continue}if(r==='"'){let c="";let l=false;r=n[++e];while(r!=='"'){if(e===n.length){l=true;break}if(r==="\\"){e++;if(e===n.length){l=true;break}c+=r+n[e];r=n[++e]}else{c+=r;r=n[++e]}}r=n[++e];if(!l){t.push({type:"string",value:c})}continue}let s=/\s/;if(r&&s.test(r)){e++;continue}let o=/[0-9]/;if(r&&o.test(r)||r==="-"||r==="."){let c="";if(r==="-"){c+=r;r=n[++e]}while(r&&o.test(r)||r==="."){c+=r;r=n[++e]}t.push({type:"number",value:c});continue}let a=/[a-z]/i;if(r&&a.test(r)){let c="";while(r&&a.test(r)){if(e===n.length){break}c+=r;r=n[++e]}if(c=="true"||c=="false"||c==="null"){t.push({type:"name",value:c})}else{e++;continue}continue}e++}return t};var Ie=n=>{if(n.length===0){return n}let e=n[n.length-1];switch(e.type){case"separator":n=n.slice(0,n.length-1);return Ie(n);break;case"number":let t=e.value[e.value.length-1];if(t==="."||t==="-"){n=n.slice(0,n.length-1);return Ie(n)}case"string":let r=n[n.length-2];if(r?.type==="delimiter"){n=n.slice(0,n.length-1);return Ie(n)}else if(r?.type==="brace"&&r.value==="{"){n=n.slice(0,n.length-1);return Ie(n)}break;case"delimiter":n=n.slice(0,n.length-1);return Ie(n);break}return n};var yn=n=>{let e=[];n.map(t=>{if(t.type==="brace"){if(t.value==="{"){e.push("}")}else{e.splice(e.lastIndexOf("}"),1)}}if(t.type==="paren"){if(t.value==="["){e.push("]")}else{e.splice(e.lastIndexOf("]"),1)}}});if(e.length>0){e.reverse().map(t=>{if(t==="}"){n.push({type:"brace",value:"}"})}else if(t==="]"){n.push({type:"paren",value:"]"})}})}return n};var wn=n=>{let e="";n.map(t=>{switch(t.type){case"string":e+='"'+t.value+'"';break;default:e+=t.value;break}});return e};var Rt=n=>JSON.parse(wn(yn(Ie(bn(n)))));var F;var Y;var Ce;var Ze;var Mt;var et;var tt;var Tt;var rt;var J;var st;var It;var Ct;var ae;var $t;var Ot;var nt;var pr;var hs;var Bt;var fr;var mr;var gr;var ds;var ps="__json_buf";function fs(n){return n.type==="tool_use"||n.type==="server_tool_use"||n.type==="mcp_tool_use"}var Lt=class n{constructor(e,t){F.add(this);this.messages=[];this.receivedMessages=[];Y.set(this,void 0);Ce.set(this,null);this.controller=new AbortController;Ze.set(this,void 0);Mt.set(this,()=>{});et.set(this,()=>{});tt.set(this,void 0);Tt.set(this,()=>{});rt.set(this,()=>{});J.set(this,{});st.set(this,false);It.set(this,false);Ct.set(this,false);ae.set(this,false);$t.set(this,void 0);Ot.set(this,void 0);nt.set(this,void 0);Bt.set(this,r=>{p(this,It,true,"f");if(H(r)){r=new T}if(r instanceof T){p(this,Ct,true,"f");return this._emit("abort",r)}if(r instanceof g){return this._emit("error",r)}if(r instanceof Error){const s=new g(r.message);s.cause=r;return this._emit("error",s)}return this._emit("error",new g(String(r)))});p(this,Ze,new Promise((r,s)=>{p(this,Mt,r,"f");p(this,et,s,"f")}),"f");p(this,tt,new Promise((r,s)=>{p(this,Tt,r,"f");p(this,rt,s,"f")}),"f");i(this,Ze,"f").catch(()=>{});i(this,tt,"f").catch(()=>{});p(this,Ce,e,"f");p(this,nt,t?.logger??console,"f")}get response(){return i(this,$t,"f")}get request_id(){return i(this,Ot,"f")}async withResponse(){p(this,ae,true,"f");const e=await i(this,Ze,"f");if(!e){throw new Error("Could not resolve a `Response` object")}return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){const t=new n(null);t._run(()=>t._fromReadableStream(e));return t}static createMessage(e,t,r,{logger:s}={}){const o=new n(t,{logger:s});for(const a of t.messages){o._addMessageParam(a)}p(o,Ce,{...t,stream:true},"f");o._run(()=>o._createMessage(e,{...t,stream:true},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}}));return o}_run(e){e().then(()=>{this._emitFinal();this._emit("end")},i(this,Bt,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=true){this.receivedMessages.push(e);if(t){this._emit("message",e)}}async _createMessage(e,t,r){const s=r?.signal;let o;if(s){if(s.aborted)this.controller.abort();o=this.controller.abort.bind(this.controller);s.addEventListener("abort",o)}try{i(this,F,"m",fr).call(this);const{response:a,data:c}=await e.create({...t,stream:true},{...r,signal:this.controller.signal}).withResponse();this._connected(a);for await(const l of c){i(this,F,"m",mr).call(this,l)}if(c.controller.signal?.aborted){throw new T}i(this,F,"m",gr).call(this)}finally{if(s&&o){s.removeEventListener("abort",o)}}}_connected(e){if(this.ended)return;p(this,$t,e,"f");p(this,Ot,e?.headers.get("request-id"),"f");i(this,Mt,"f").call(this,e);this._emit("connect")}get ended(){return i(this,st,"f")}get errored(){return i(this,It,"f")}get aborted(){return i(this,Ct,"f")}abort(){this.controller.abort()}on(e,t){const r=i(this,J,"f")[e]||(i(this,J,"f")[e]=[]);r.push({listener:t});return this}off(e,t){const r=i(this,J,"f")[e];if(!r)return this;const s=r.findIndex(o=>o.listener===t);if(s>=0)r.splice(s,1);return this}once(e,t){const r=i(this,J,"f")[e]||(i(this,J,"f")[e]=[]);r.push({listener:t,once:true});return this}emitted(e){return new Promise((t,r)=>{p(this,ae,true,"f");if(e!=="error")this.once("error",r);this.once(e,t)})}async done(){p(this,ae,true,"f");await i(this,tt,"f")}get currentMessage(){return i(this,Y,"f")}async finalMessage(){await this.done();return i(this,F,"m",pr).call(this)}async finalText(){await this.done();return i(this,F,"m",hs).call(this)}_emit(e,...t){if(i(this,st,"f"))return;if(e==="end"){p(this,st,true,"f");i(this,Tt,"f").call(this)}const r=i(this,J,"f")[e];if(r){i(this,J,"f")[e]=r.filter(s=>!s.once);r.forEach(({listener:s})=>s(...t))}if(e==="abort"){const s=t[0];if(!i(this,ae,"f")&&!r?.length){Promise.reject(s)}i(this,et,"f").call(this,s);i(this,rt,"f").call(this,s);this._emit("end");return}if(e==="error"){const s=t[0];if(!i(this,ae,"f")&&!r?.length){Promise.reject(s)}i(this,et,"f").call(this,s);i(this,rt,"f").call(this,s);this._emit("end")}}_emitFinal(){const e=this.receivedMessages.at(-1);if(e){this._emit("finalMessage",i(this,F,"m",pr).call(this))}}async _fromReadableStream(e,t){const r=t?.signal;let s;if(r){if(r.aborted)this.controller.abort();s=this.controller.abort.bind(this.controller);r.addEventListener("abort",s)}try{i(this,F,"m",fr).call(this);this._connected(null);const o=U.fromReadableStream(e,this.controller);for await(const a of o){i(this,F,"m",mr).call(this,a)}if(o.controller.signal?.aborted){throw new T}i(this,F,"m",gr).call(this)}finally{if(r&&s){r.removeEventListener("abort",s)}}}[(Y=new WeakMap,Ce=new WeakMap,Ze=new WeakMap,Mt=new WeakMap,et=new WeakMap,tt=new WeakMap,Tt=new WeakMap,rt=new WeakMap,J=new WeakMap,st=new WeakMap,It=new WeakMap,Ct=new WeakMap,ae=new WeakMap,$t=new WeakMap,Ot=new WeakMap,nt=new WeakMap,Bt=new WeakMap,F=new WeakSet,pr=function e(){if(this.receivedMessages.length===0){throw new g("stream ended without producing a Message with role=assistant")}return this.receivedMessages.at(-1)},hs=function e(){if(this.receivedMessages.length===0){throw new g("stream ended without producing a Message with role=assistant")}const t=this.receivedMessages.at(-1).content.filter(r=>r.type==="text").map(r=>r.text);if(t.length===0){throw new g("stream ended without producing a content block with type=text")}return t.join(" ")},fr=function e(){if(this.ended)return;p(this,Y,void 0,"f")},mr=function e(t){if(this.ended)return;const r=i(this,F,"m",ds).call(this,t);this._emit("streamEvent",t,r);switch(t.type){case"content_block_delta":{const s=r.content.at(-1);switch(t.delta.type){case"text_delta":{if(s.type==="text"){this._emit("text",t.delta.text,s.text||"")}break}case"citations_delta":{if(s.type==="text"){this._emit("citation",t.delta.citation,s.citations??[])}break}case"input_json_delta":{if(fs(s)&&s.input){this._emit("inputJson",t.delta.partial_json,s.input)}break}case"thinking_delta":{if(s.type==="thinking"){this._emit("thinking",t.delta.thinking,s.thinking)}break}case"signature_delta":{if(s.type==="thinking"){this._emit("signature",s.signature)}break}case"compaction_delta":{if(s.type==="compaction"&&s.content){this._emit("compaction",s.content)}break}default:ms(t.delta)}break}case"message_stop":{this._addMessageParam(r);this._addMessage(hr(r,i(this,Ce,"f"),{logger:i(this,nt,"f")}),true);break}case"content_block_stop":{this._emit("contentBlock",r.content.at(-1));break}case"message_start":{p(this,Y,r,"f");break}case"content_block_start":case"message_delta":break}},gr=function e(){if(this.ended){throw new g(`stream has ended, this shouldn't happen`)}const t=i(this,Y,"f");if(!t){throw new g(`request ended without sending any chunks`)}p(this,Y,void 0,"f");return hr(t,i(this,Ce,"f"),{logger:i(this,nt,"f")})},ds=function e(t){let r=i(this,Y,"f");if(t.type==="message_start"){if(r){throw new g(`Unexpected event order, got ${t.type} before receiving "message_stop"`)}return t.message}if(!r){throw new g(`Unexpected event order, got ${t.type} before "message_start"`)}switch(t.type){case"message_stop":return r;case"message_delta":r.container=t.delta.container;r.stop_reason=t.delta.stop_reason;r.stop_sequence=t.delta.stop_sequence;r.usage.output_tokens=t.usage.output_tokens;r.context_management=t.context_management;if(t.usage.input_tokens!=null){r.usage.input_tokens=t.usage.input_tokens}if(t.usage.cache_creation_input_tokens!=null){r.usage.cache_creation_input_tokens=t.usage.cache_creation_input_tokens}if(t.usage.cache_read_input_tokens!=null){r.usage.cache_read_input_tokens=t.usage.cache_read_input_tokens}if(t.usage.server_tool_use!=null){r.usage.server_tool_use=t.usage.server_tool_use}if(t.usage.iterations!=null){r.usage.iterations=t.usage.iterations}return r;case"content_block_start":r.content.push(t.content_block);return r;case"content_block_delta":{const s=r.content.at(t.index);switch(t.delta.type){case"text_delta":{if(s?.type==="text"){r.content[t.index]={...s,text:(s.text||"")+t.delta.text}}break}case"citations_delta":{if(s?.type==="text"){r.content[t.index]={...s,citations:[...s.citations??[],t.delta.citation]}}break}case"input_json_delta":{if(s&&fs(s)){let o=s[ps]||"";o+=t.delta.partial_json;const a={...s};Object.defineProperty(a,ps,{value:o,enumerable:false,writable:true});if(o){try{a.input=Rt(o)}catch(c){const l=new g(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${c}. JSON: ${o}`);i(this,Bt,"f").call(this,l)}}r.content[t.index]=a}break}case"thinking_delta":{if(s?.type==="thinking"){r.content[t.index]={...s,thinking:s.thinking+t.delta.thinking}}break}case"signature_delta":{if(s?.type==="thinking"){r.content[t.index]={...s,signature:t.delta.signature}}break}case"compaction_delta":{if(s?.type==="compaction"){r.content[t.index]={...s,content:(s.content||"")+t.delta.content}}break}default:ms(t.delta)}return r}case"content_block_stop":return r}},Symbol.asyncIterator)](){const e=[];const t=[];let r=false;this.on("streamEvent",s=>{const o=t.shift();if(o){o.resolve(s)}else{e.push(s)}});this.on("end",()=>{r=true;for(const s of t){s.resolve(void 0)}t.length=0});this.on("abort",s=>{r=true;for(const o of t){o.reject(s)}t.length=0});this.on("error",s=>{r=true;for(const o of t){o.reject(s)}t.length=0});return{next:async()=>{if(!e.length){if(r){return{value:void 0,done:true}}return new Promise((o,a)=>t.push({resolve:o,reject:a})).then(o=>o?{value:o,done:false}:{value:void 0,done:true})}const s=e.shift();return{value:s,done:false}},return:async()=>{this.abort();return{value:void 0,done:true}}}}toReadableStream(){const e=new U(this[Symbol.asyncIterator].bind(this),this.controller);return e.toReadableStream()}};function ms(n){}var ie=class extends Error{constructor(e){const t=typeof e==="string"?e:e.map(r=>{if(r.type==="text")return r.text;return`[${r.type}]`}).join(" ");super(t);this.name="ToolError";this.content=e}};var gs=1e5;var _s=`You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
6
+ 1. Task Overview
7
+ The user's core request and success criteria
8
+ Any clarifications or constraints they specified
9
+ 2. Current State
10
+ What has been completed so far
11
+ Files created, modified, or analyzed (with paths if relevant)
12
+ Key outputs or artifacts produced
13
+ 3. Important Discoveries
14
+ Technical constraints or requirements uncovered
15
+ Decisions made and their rationale
16
+ Errors encountered and how they were resolved
17
+ What approaches were tried that didn't work (and why)
18
+ 4. Next Steps
19
+ Specific actions needed to complete the task
20
+ Any blockers or open questions to resolve
21
+ Priority order if multiple steps remain
22
+ 5. Context to Preserve
23
+ User preferences or style requirements
24
+ Domain-specific details that aren't obvious
25
+ Any promises made to the user
26
+ Be concise but complete\u2014err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
27
+ Wrap your summary in <summary></summary> tags.`;var ot;var $e;var ce;var P;var C;var B;var V;var Z;var at;var bs;var _r;function ys(){let n;let e;const t=new Promise((r,s)=>{n=r;e=s});return{promise:t,resolve:n,reject:e}}var Oe=class{constructor(e,t,r){ot.add(this);this.client=e;$e.set(this,false);ce.set(this,false);P.set(this,void 0);C.set(this,void 0);B.set(this,void 0);V.set(this,void 0);Z.set(this,void 0);at.set(this,0);p(this,P,{params:{...t,messages:structuredClone(t.messages)}},"f");const s=ur(t.tools,t.messages);const o=["BetaToolRunner",...s].join(", ");p(this,C,{...r,headers:u([{"x-stainless-helper":o},r?.headers])},"f");p(this,Z,ys(),"f");if(t.compactionControl?.enabled){console.warn('Anthropic: The `compactionControl` parameter is deprecated and will be removed in a future version. Use server-side compaction instead by passing `edits: [{ type: "compact_20260112" }]` in the params passed to `toolRunner()`. See https://platform.claude.com/docs/en/build-with-claude/compaction')}}async*[($e=new WeakMap,ce=new WeakMap,P=new WeakMap,C=new WeakMap,B=new WeakMap,V=new WeakMap,Z=new WeakMap,at=new WeakMap,ot=new WeakSet,bs=async function e(){const t=i(this,P,"f").params.compactionControl;if(!t||!t.enabled){return false}let r=0;if(i(this,B,"f")!==void 0){try{const h=await i(this,B,"f");const f=h.usage.input_tokens+(h.usage.cache_creation_input_tokens??0)+(h.usage.cache_read_input_tokens??0);r=f+h.usage.output_tokens}catch{return false}}const s=t.contextTokenThreshold??gs;if(r<s){return false}const o=t.model??i(this,P,"f").params.model;const a=t.summaryPrompt??_s;const c=i(this,P,"f").params.messages;if(c[c.length-1].role==="assistant"){const h=c[c.length-1];if(Array.isArray(h.content)){const f=h.content.filter(m=>m.type!=="tool_use");if(f.length===0){c.pop()}else{h.content=f}}}const l=await this.client.beta.messages.create({model:o,messages:[...c,{role:"user",content:[{type:"text",text:a}]}],max_tokens:i(this,P,"f").params.max_tokens},{signal:i(this,C,"f").signal,headers:u([i(this,C,"f").headers,{"x-stainless-helper":"compaction"}])});if(l.content[0]?.type!=="text"){throw new g("Expected text response for compaction")}i(this,P,"f").params.messages=[{role:"user",content:l.content}];return true},Symbol.asyncIterator)](){var e;if(i(this,$e,"f")){throw new g("Cannot iterate over a consumed stream")}p(this,$e,true,"f");p(this,ce,true,"f");p(this,V,void 0,"f");try{while(true){let t;try{if(i(this,P,"f").params.max_iterations&&i(this,at,"f")>=i(this,P,"f").params.max_iterations){break}p(this,ce,false,"f");p(this,V,void 0,"f");p(this,at,(e=i(this,at,"f"),e++,e),"f");p(this,B,void 0,"f");const{max_iterations:r,compactionControl:s,...o}=i(this,P,"f").params;if(o.stream){t=this.client.beta.messages.stream({...o},i(this,C,"f"));p(this,B,t.finalMessage(),"f");i(this,B,"f").catch(()=>{});yield t}else{p(this,B,this.client.beta.messages.create({...o,stream:false},i(this,C,"f")),"f");yield i(this,B,"f")}const a=await i(this,ot,"m",bs).call(this);if(!a){if(!i(this,ce,"f")){const{role:l,content:h}=await i(this,B,"f");i(this,P,"f").params.messages.push({role:l,content:h})}const c=await i(this,ot,"m",_r).call(this,i(this,P,"f").params.messages.at(-1));if(c){i(this,P,"f").params.messages.push(c)}else if(!i(this,ce,"f")){break}}}finally{if(t){t.abort()}}}if(!i(this,B,"f")){throw new g("ToolRunner concluded without a message from the server")}i(this,Z,"f").resolve(await i(this,B,"f"))}catch(t){p(this,$e,false,"f");i(this,Z,"f").promise.catch(()=>{});i(this,Z,"f").reject(t);p(this,Z,ys(),"f");throw t}}setMessagesParams(e){if(typeof e==="function"){i(this,P,"f").params=e(i(this,P,"f").params)}else{i(this,P,"f").params=e}p(this,ce,true,"f");p(this,V,void 0,"f")}setRequestOptions(e){if(typeof e==="function"){p(this,C,e(i(this,C,"f")),"f")}else{p(this,C,{...i(this,C,"f"),...e},"f")}}async generateToolResponse(e=i(this,C,"f").signal){const t=await i(this,B,"f")??this.params.messages.at(-1);if(!t){return null}return i(this,ot,"m",_r).call(this,t,e)}done(){return i(this,Z,"f").promise}async runUntilDone(){if(!i(this,$e,"f")){for await(const e of this){}}return this.done()}get params(){return i(this,P,"f").params}pushMessages(...e){this.setMessagesParams(t=>({...t,messages:[...t.messages,...e]}))}then(e,t){return this.runUntilDone().then(e,t)}};_r=async function n(e,t=i(this,C,"f").signal){if(i(this,V,"f")!==void 0){return i(this,V,"f")}p(this,V,xn(i(this,P,"f").params,e,{...i(this,C,"f"),signal:t}),"f");return i(this,V,"f")};async function xn(n,e=n.messages.at(-1),t){if(!e||e.role!=="assistant"||!e.content||typeof e.content==="string"){return null}const r=e.content.filter(o=>o.type==="tool_use");if(r.length===0){return null}const s=await Promise.all(r.map(async o=>{const a=n.tools.find(c=>("name"in c?c.name:c.mcp_server_name)===o.name);if(!a||!("run"in a)){return{type:"tool_result",tool_use_id:o.id,content:`Error: Tool '${o.name}' not found`,is_error:true}}try{let c=o.input;if("parse"in a&&a.parse){c=a.parse(c)}const l=await a.run(c,{toolUseBlock:o,signal:t?.signal});return{type:"tool_result",tool_use_id:o.id,content:l}}catch(c){return{type:"tool_result",tool_use_id:o.id,content:c instanceof ie?c.content:`Error: ${c instanceof Error?c.message:String(c)}`,is_error:true}}}));return{role:"user",content:s}}var Be=class n{constructor(e,t){this.iterator=e;this.controller=t}async*decoder(){const e=new D;for await(const t of this.iterator){for(const r of e.decode(t)){yield JSON.parse(r)}}for(const t of e.flush()){yield JSON.parse(t)}}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,t){if(!e.body){t.abort();if(typeof globalThis.navigator!=="undefined"&&globalThis.navigator.product==="ReactNative"){throw new g(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`)}throw new g(`Attempted to iterate over a response with no body`)}return new n(Je(e.body),t)}};var Le=class extends y{create(e,t){const{betas:r,...s}=e;return this._client.post("/v1/messages/batches?beta=true",{body:s,...t,headers:u([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},t?.headers])})}retrieve(e,t={},r){const{betas:s}=t??{};return this._client.get(d`/v1/messages/batches/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString()},r?.headers])})}list(e={},t){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/messages/batches?beta=true",N,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},t?.headers])})}delete(e,t={},r){const{betas:s}=t??{};return this._client.delete(d`/v1/messages/batches/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString()},r?.headers])})}cancel(e,t={},r){const{betas:s}=t??{};return this._client.post(d`/v1/messages/batches/${e}/cancel?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"message-batches-2024-09-24"].toString()},r?.headers])})}async results(e,t={},r){const s=await this.retrieve(e);if(!s.results_url){throw new g(`No batch \`results_url\`; Has it finished processing? ${s.processing_status} - ${s.id}`)}const{betas:o}=t??{};return this._client.get(s.results_url,{...r,headers:u([{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},r?.headers]),stream:true,__binaryResponse:true})._thenUnwrap((a,c)=>Be.fromResponse(c.response,c.controller))}};var ws={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026"};var kn=["claude-mythos-preview","claude-opus-4-6"];var X=class extends y{constructor(){super(...arguments);this.batches=new Le(this._client)}create(e,t){const r=xs(e);const{betas:s,...o}=r;if(o.model in ws){console.warn(`The model '${o.model}' is deprecated and will reach end-of-life on ${ws[o.model]}
28
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`)}if(kn.includes(o.model)&&o.thinking&&o.thinking.type==="enabled"){console.warn(`Using Claude with ${o.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`)}let a=this._client._options.timeout;if(!o.stream&&a==null){const l=Et[o.model]??void 0;a=this._client.calculateNonstreamingTimeout(o.max_tokens,l)}const c=Pt(o.tools,o.messages);return this._client.post("/v1/messages?beta=true",{body:o,timeout:a??6e5,...t,headers:u([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},c,t?.headers]),stream:r.stream??false})}parse(e,t){t={...t,headers:u([{"anthropic-beta":[...e.betas??[],"structured-outputs-2025-12-15"].toString()},t?.headers])};return this.create(e,t).then(r=>dr(r,e,{logger:this._client.logger??console}))}stream(e,t){return Lt.createMessage(this,e,t)}countTokens(e,t){const r=xs(e);const{betas:s,...o}=r;return this._client.post("/v1/messages/count_tokens?beta=true",{body:o,...t,headers:u([{"anthropic-beta":[...s??[],"token-counting-2024-11-01"].toString()},t?.headers])})}toolRunner(e,t){return new Oe(this._client,e,t)}};function xs(n){if(!n.output_format){return n}if(n.output_config?.format){throw new g("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).")}const{output_format:e,...t}=n;return{...t,output_config:{...n.output_config,format:e}}}X.Batches=Le;X.BetaToolRunner=Oe;X.ToolError=ie;var Ne=class extends y{list(e,t={},r){const{betas:s,...o}=t??{};return this._client.getAPIList(d`/v1/sessions/${e}/events?beta=true`,k,{query:o,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}send(e,t,r){const{betas:s,...o}=t;return this._client.post(d`/v1/sessions/${e}/events?beta=true`,{body:o,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}stream(e,t={},r){const{betas:s}=t??{};return this._client.get(d`/v1/sessions/${e}/events/stream?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers]),stream:true})}};var Fe=class extends y{retrieve(e,t,r){const{session_id:s,betas:o}=t;return this._client.get(d`/v1/sessions/${s}/resources/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){const{session_id:s,betas:o,...a}=t;return this._client.post(d`/v1/sessions/${s}/resources/${e}?beta=true`,{body:a,...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e,t={},r){const{betas:s,...o}=t??{};return this._client.getAPIList(d`/v1/sessions/${e}/resources?beta=true`,k,{query:o,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}delete(e,t,r){const{session_id:s,betas:o}=t;return this._client.delete(d`/v1/sessions/${s}/resources/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}add(e,t,r){const{betas:s,...o}=t;return this._client.post(d`/v1/sessions/${e}/resources?beta=true`,{body:o,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};var ee=class extends y{constructor(){super(...arguments);this.events=new Ne(this._client);this.resources=new Fe(this._client)}create(e,t){const{betas:r,...s}=e;return this._client.post("/v1/sessions?beta=true",{body:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}retrieve(e,t={},r){const{betas:s}=t??{};return this._client.get(d`/v1/sessions/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){const{betas:s,...o}=t;return this._client.post(d`/v1/sessions/${e}?beta=true`,{body:o,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},t){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/sessions?beta=true",k,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}delete(e,t={},r){const{betas:s}=t??{};return this._client.delete(d`/v1/sessions/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,t={},r){const{betas:s}=t??{};return this._client.post(d`/v1/sessions/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};ee.Events=Ne;ee.Resources=Fe;var je=class extends y{create(e,t={},r){const{betas:s,...o}=t??{};return this._client.post(d`/v1/skills/${e}/versions?beta=true`,ke({body:o,...r,headers:u([{"anthropic-beta":[...s??[],"skills-2025-10-02"].toString()},r?.headers])},this._client))}retrieve(e,t,r){const{skill_id:s,betas:o}=t;return this._client.get(d`/v1/skills/${s}/versions/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...o??[],"skills-2025-10-02"].toString()},r?.headers])})}list(e,t={},r){const{betas:s,...o}=t??{};return this._client.getAPIList(d`/v1/skills/${e}/versions?beta=true`,k,{query:o,...r,headers:u([{"anthropic-beta":[...s??[],"skills-2025-10-02"].toString()},r?.headers])})}delete(e,t,r){const{skill_id:s,betas:o}=t;return this._client.delete(d`/v1/skills/${s}/versions/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...o??[],"skills-2025-10-02"].toString()},r?.headers])})}};var le=class extends y{constructor(){super(...arguments);this.versions=new je(this._client)}create(e={},t){const{betas:r,...s}=e??{};return this._client.post("/v1/skills?beta=true",ke({body:s,...t,headers:u([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},t?.headers])},this._client,false))}retrieve(e,t={},r){const{betas:s}=t??{};return this._client.get(d`/v1/skills/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"skills-2025-10-02"].toString()},r?.headers])})}list(e={},t){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/skills?beta=true",k,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},t?.headers])})}delete(e,t={},r){const{betas:s}=t??{};return this._client.delete(d`/v1/skills/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"skills-2025-10-02"].toString()},r?.headers])})}};le.Versions=je;var qe=class extends y{create(e,t,r){const{betas:s,...o}=t;return this._client.post(d`/v1/vaults/${e}/credentials?beta=true`,{body:o,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}retrieve(e,t,r){const{vault_id:s,betas:o}=t;return this._client.get(d`/v1/vaults/${s}/credentials/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){const{vault_id:s,betas:o,...a}=t;return this._client.post(d`/v1/vaults/${s}/credentials/${e}?beta=true`,{body:a,...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e,t={},r){const{betas:s,...o}=t??{};return this._client.getAPIList(d`/v1/vaults/${e}/credentials?beta=true`,k,{query:o,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}delete(e,t,r){const{vault_id:s,betas:o}=t;return this._client.delete(d`/v1/vaults/${s}/credentials/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,t,r){const{vault_id:s,betas:o}=t;return this._client.post(d`/v1/vaults/${s}/credentials/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};var ue=class extends y{constructor(){super(...arguments);this.credentials=new qe(this._client)}create(e,t){const{betas:r,...s}=e;return this._client.post("/v1/vaults?beta=true",{body:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}retrieve(e,t={},r){const{betas:s}=t??{};return this._client.get(d`/v1/vaults/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,t,r){const{betas:s,...o}=t;return this._client.post(d`/v1/vaults/${e}?beta=true`,{body:o,...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},t){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/vaults?beta=true",k,{query:s,...t,headers:u([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},t?.headers])})}delete(e,t={},r){const{betas:s}=t??{};return this._client.delete(d`/v1/vaults/${e}?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,t={},r){const{betas:s}=t??{};return this._client.post(d`/v1/vaults/${e}/archive?beta=true`,{...r,headers:u([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};ue.Credentials=qe;var I=class extends y{constructor(){super(...arguments);this.models=new Pe(this._client);this.messages=new X(this._client);this.agents=new oe(this._client);this.environments=new ve(this._client);this.sessions=new ee(this._client);this.vaults=new ue(this._client);this.memoryStores=new Q(this._client);this.files=new Ae(this._client);this.skills=new le(this._client);this.userProfiles=new Ee(this._client)}};I.Models=Pe;I.Messages=X;I.Agents=oe;I.Environments=ve;I.Sessions=ee;I.Vaults=ue;I.MemoryStores=Q;I.Files=Ae;I.Skills=le;I.UserProfiles=Ee;var he=class extends y{create(e,t){const{betas:r,...s}=e;return this._client.post("/v1/complete",{body:s,timeout:this._client._options.timeout??6e5,...t,headers:u([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},t?.headers]),stream:e.stream??false})}};function Ss(n){return n?.output_config?.format}function br(n,e,t){const r=Ss(e);if(!e||!("parse"in(r??{}))){return{...n,content:n.content.map(s=>{if(s.type==="text"){const o=Object.defineProperty({...s},"parsed_output",{value:null,enumerable:false});return o}return s}),parsed_output:null}}return yr(n,e,t)}function yr(n,e,t){let r=null;const s=n.content.map(o=>{if(o.type==="text"){const a=Cn(e,o.text);if(r===null){r=a}const c=Object.defineProperty({...o},"parsed_output",{value:a,enumerable:false});return c}return o});return{...n,content:s,parsed_output:r}}function Cn(n,e){const t=Ss(n);if(t?.type!=="json_schema"){return null}try{if("parse"in t){return t.parse(e)}return JSON.parse(e)}catch(r){throw new g(`Failed to parse structured output: ${r}`)}}var j;var te;var Ue;var it;var Nt;var ct;var lt;var Ft;var ut;var K;var ht;var jt;var qt;var de;var Ut;var Ht;var dt;var wr;var ks;var xr;var Sr;var kr;var vr;var vs;var As="__json_buf";function Ps(n){return n.type==="tool_use"||n.type==="server_tool_use"}var Dt=class n{constructor(e,t){j.add(this);this.messages=[];this.receivedMessages=[];te.set(this,void 0);Ue.set(this,null);this.controller=new AbortController;it.set(this,void 0);Nt.set(this,()=>{});ct.set(this,()=>{});lt.set(this,void 0);Ft.set(this,()=>{});ut.set(this,()=>{});K.set(this,{});ht.set(this,false);jt.set(this,false);qt.set(this,false);de.set(this,false);Ut.set(this,void 0);Ht.set(this,void 0);dt.set(this,void 0);xr.set(this,r=>{p(this,jt,true,"f");if(H(r)){r=new T}if(r instanceof T){p(this,qt,true,"f");return this._emit("abort",r)}if(r instanceof g){return this._emit("error",r)}if(r instanceof Error){const s=new g(r.message);s.cause=r;return this._emit("error",s)}return this._emit("error",new g(String(r)))});p(this,it,new Promise((r,s)=>{p(this,Nt,r,"f");p(this,ct,s,"f")}),"f");p(this,lt,new Promise((r,s)=>{p(this,Ft,r,"f");p(this,ut,s,"f")}),"f");i(this,it,"f").catch(()=>{});i(this,lt,"f").catch(()=>{});p(this,Ue,e,"f");p(this,dt,t?.logger??console,"f")}get response(){return i(this,Ut,"f")}get request_id(){return i(this,Ht,"f")}async withResponse(){p(this,de,true,"f");const e=await i(this,it,"f");if(!e){throw new Error("Could not resolve a `Response` object")}return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){const t=new n(null);t._run(()=>t._fromReadableStream(e));return t}static createMessage(e,t,r,{logger:s}={}){const o=new n(t,{logger:s});for(const a of t.messages){o._addMessageParam(a)}p(o,Ue,{...t,stream:true},"f");o._run(()=>o._createMessage(e,{...t,stream:true},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}}));return o}_run(e){e().then(()=>{this._emitFinal();this._emit("end")},i(this,xr,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=true){this.receivedMessages.push(e);if(t){this._emit("message",e)}}async _createMessage(e,t,r){const s=r?.signal;let o;if(s){if(s.aborted)this.controller.abort();o=this.controller.abort.bind(this.controller);s.addEventListener("abort",o)}try{i(this,j,"m",Sr).call(this);const{response:a,data:c}=await e.create({...t,stream:true},{...r,signal:this.controller.signal}).withResponse();this._connected(a);for await(const l of c){i(this,j,"m",kr).call(this,l)}if(c.controller.signal?.aborted){throw new T}i(this,j,"m",vr).call(this)}finally{if(s&&o){s.removeEventListener("abort",o)}}}_connected(e){if(this.ended)return;p(this,Ut,e,"f");p(this,Ht,e?.headers.get("request-id"),"f");i(this,Nt,"f").call(this,e);this._emit("connect")}get ended(){return i(this,ht,"f")}get errored(){return i(this,jt,"f")}get aborted(){return i(this,qt,"f")}abort(){this.controller.abort()}on(e,t){const r=i(this,K,"f")[e]||(i(this,K,"f")[e]=[]);r.push({listener:t});return this}off(e,t){const r=i(this,K,"f")[e];if(!r)return this;const s=r.findIndex(o=>o.listener===t);if(s>=0)r.splice(s,1);return this}once(e,t){const r=i(this,K,"f")[e]||(i(this,K,"f")[e]=[]);r.push({listener:t,once:true});return this}emitted(e){return new Promise((t,r)=>{p(this,de,true,"f");if(e!=="error")this.once("error",r);this.once(e,t)})}async done(){p(this,de,true,"f");await i(this,lt,"f")}get currentMessage(){return i(this,te,"f")}async finalMessage(){await this.done();return i(this,j,"m",wr).call(this)}async finalText(){await this.done();return i(this,j,"m",ks).call(this)}_emit(e,...t){if(i(this,ht,"f"))return;if(e==="end"){p(this,ht,true,"f");i(this,Ft,"f").call(this)}const r=i(this,K,"f")[e];if(r){i(this,K,"f")[e]=r.filter(s=>!s.once);r.forEach(({listener:s})=>s(...t))}if(e==="abort"){const s=t[0];if(!i(this,de,"f")&&!r?.length){Promise.reject(s)}i(this,ct,"f").call(this,s);i(this,ut,"f").call(this,s);this._emit("end");return}if(e==="error"){const s=t[0];if(!i(this,de,"f")&&!r?.length){Promise.reject(s)}i(this,ct,"f").call(this,s);i(this,ut,"f").call(this,s);this._emit("end")}}_emitFinal(){const e=this.receivedMessages.at(-1);if(e){this._emit("finalMessage",i(this,j,"m",wr).call(this))}}async _fromReadableStream(e,t){const r=t?.signal;let s;if(r){if(r.aborted)this.controller.abort();s=this.controller.abort.bind(this.controller);r.addEventListener("abort",s)}try{i(this,j,"m",Sr).call(this);this._connected(null);const o=U.fromReadableStream(e,this.controller);for await(const a of o){i(this,j,"m",kr).call(this,a)}if(o.controller.signal?.aborted){throw new T}i(this,j,"m",vr).call(this)}finally{if(r&&s){r.removeEventListener("abort",s)}}}[(te=new WeakMap,Ue=new WeakMap,it=new WeakMap,Nt=new WeakMap,ct=new WeakMap,lt=new WeakMap,Ft=new WeakMap,ut=new WeakMap,K=new WeakMap,ht=new WeakMap,jt=new WeakMap,qt=new WeakMap,de=new WeakMap,Ut=new WeakMap,Ht=new WeakMap,dt=new WeakMap,xr=new WeakMap,j=new WeakSet,wr=function e(){if(this.receivedMessages.length===0){throw new g("stream ended without producing a Message with role=assistant")}return this.receivedMessages.at(-1)},ks=function e(){if(this.receivedMessages.length===0){throw new g("stream ended without producing a Message with role=assistant")}const t=this.receivedMessages.at(-1).content.filter(r=>r.type==="text").map(r=>r.text);if(t.length===0){throw new g("stream ended without producing a content block with type=text")}return t.join(" ")},Sr=function e(){if(this.ended)return;p(this,te,void 0,"f")},kr=function e(t){if(this.ended)return;const r=i(this,j,"m",vs).call(this,t);this._emit("streamEvent",t,r);switch(t.type){case"content_block_delta":{const s=r.content.at(-1);switch(t.delta.type){case"text_delta":{if(s.type==="text"){this._emit("text",t.delta.text,s.text||"")}break}case"citations_delta":{if(s.type==="text"){this._emit("citation",t.delta.citation,s.citations??[])}break}case"input_json_delta":{if(Ps(s)&&s.input){this._emit("inputJson",t.delta.partial_json,s.input)}break}case"thinking_delta":{if(s.type==="thinking"){this._emit("thinking",t.delta.thinking,s.thinking)}break}case"signature_delta":{if(s.type==="thinking"){this._emit("signature",s.signature)}break}default:Es(t.delta)}break}case"message_stop":{this._addMessageParam(r);this._addMessage(br(r,i(this,Ue,"f"),{logger:i(this,dt,"f")}),true);break}case"content_block_stop":{this._emit("contentBlock",r.content.at(-1));break}case"message_start":{p(this,te,r,"f");break}case"content_block_start":case"message_delta":break}},vr=function e(){if(this.ended){throw new g(`stream has ended, this shouldn't happen`)}const t=i(this,te,"f");if(!t){throw new g(`request ended without sending any chunks`)}p(this,te,void 0,"f");return br(t,i(this,Ue,"f"),{logger:i(this,dt,"f")})},vs=function e(t){let r=i(this,te,"f");if(t.type==="message_start"){if(r){throw new g(`Unexpected event order, got ${t.type} before receiving "message_stop"`)}return t.message}if(!r){throw new g(`Unexpected event order, got ${t.type} before "message_start"`)}switch(t.type){case"message_stop":return r;case"message_delta":r.stop_reason=t.delta.stop_reason;r.stop_sequence=t.delta.stop_sequence;r.usage.output_tokens=t.usage.output_tokens;if(t.usage.input_tokens!=null){r.usage.input_tokens=t.usage.input_tokens}if(t.usage.cache_creation_input_tokens!=null){r.usage.cache_creation_input_tokens=t.usage.cache_creation_input_tokens}if(t.usage.cache_read_input_tokens!=null){r.usage.cache_read_input_tokens=t.usage.cache_read_input_tokens}if(t.usage.server_tool_use!=null){r.usage.server_tool_use=t.usage.server_tool_use}return r;case"content_block_start":r.content.push({...t.content_block});return r;case"content_block_delta":{const s=r.content.at(t.index);switch(t.delta.type){case"text_delta":{if(s?.type==="text"){r.content[t.index]={...s,text:(s.text||"")+t.delta.text}}break}case"citations_delta":{if(s?.type==="text"){r.content[t.index]={...s,citations:[...s.citations??[],t.delta.citation]}}break}case"input_json_delta":{if(s&&Ps(s)){let o=s[As]||"";o+=t.delta.partial_json;const a={...s};Object.defineProperty(a,As,{value:o,enumerable:false,writable:true});if(o){a.input=Rt(o)}r.content[t.index]=a}break}case"thinking_delta":{if(s?.type==="thinking"){r.content[t.index]={...s,thinking:s.thinking+t.delta.thinking}}break}case"signature_delta":{if(s?.type==="thinking"){r.content[t.index]={...s,signature:t.delta.signature}}break}default:Es(t.delta)}return r}case"content_block_stop":return r}},Symbol.asyncIterator)](){const e=[];const t=[];let r=false;this.on("streamEvent",s=>{const o=t.shift();if(o){o.resolve(s)}else{e.push(s)}});this.on("end",()=>{r=true;for(const s of t){s.resolve(void 0)}t.length=0});this.on("abort",s=>{r=true;for(const o of t){o.reject(s)}t.length=0});this.on("error",s=>{r=true;for(const o of t){o.reject(s)}t.length=0});return{next:async()=>{if(!e.length){if(r){return{value:void 0,done:true}}return new Promise((o,a)=>t.push({resolve:o,reject:a})).then(o=>o?{value:o,done:false}:{value:void 0,done:true})}const s=e.shift();return{value:s,done:false}},return:async()=>{this.abort();return{value:void 0,done:true}}}}toReadableStream(){const e=new U(this[Symbol.asyncIterator].bind(this),this.controller);return e.toReadableStream()}};function Es(n){}var He=class extends y{create(e,t){return this._client.post("/v1/messages/batches",{body:e,...t})}retrieve(e,t){return this._client.get(d`/v1/messages/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/v1/messages/batches",N,{query:e,...t})}delete(e,t){return this._client.delete(d`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post(d`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){const r=await this.retrieve(e);if(!r.results_url){throw new g(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`)}return this._client.get(r.results_url,{...t,headers:u([{Accept:"application/binary"},t?.headers]),stream:true,__binaryResponse:true})._thenUnwrap((s,o)=>Be.fromResponse(o.response,o.controller))}};var re=class extends y{constructor(){super(...arguments);this.batches=new He(this._client)}create(e,t){if(e.model in Rs){console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${Rs[e.model]}
29
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`)}if(On.includes(e.model)&&e.thinking&&e.thinking.type==="enabled"){console.warn(`Using Claude with ${e.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`)}let r=this._client._options.timeout;if(!e.stream&&r==null){const o=Et[e.model]??void 0;r=this._client.calculateNonstreamingTimeout(e.max_tokens,o)}const s=Pt(e.tools,e.messages);return this._client.post("/v1/messages",{body:e,timeout:r??6e5,...t,headers:u([s,t?.headers]),stream:e.stream??false})}parse(e,t){return this.create(e,t).then(r=>yr(r,e,{logger:this._client.logger??console}))}stream(e,t){return Dt.createMessage(this,e,t,{logger:this._client.logger??console})}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}};var Rs={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026","claude-3-5-haiku-latest":"February 19th, 2026","claude-3-5-haiku-20241022":"February 19th, 2026","claude-opus-4-0":"June 15th, 2026","claude-opus-4-20250514":"June 15th, 2026","claude-sonnet-4-0":"June 15th, 2026","claude-sonnet-4-20250514":"June 15th, 2026"};var On=["claude-mythos-preview","claude-opus-4-6"];re.Batches=He;var pe=class extends y{retrieve(e,t={},r){const{betas:s}=t??{};return this._client.get(d`/v1/models/${e}`,{...r,headers:u([{...s?.toString()!=null?{"anthropic-beta":s?.toString()}:void 0},r?.headers])})}list(e={},t){const{betas:r,...s}=e??{};return this._client.getAPIList("/v1/models",N,{query:s,...t,headers:u([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},t?.headers])})}};var pt=n=>{if(typeof globalThis.process!=="undefined"){return globalThis.process.env?.[n]?.trim()||void 0}if(typeof globalThis.Deno!=="undefined"){return globalThis.Deno.env?.get?.(n)?.trim()||void 0}return void 0};var Ar;var Pr;var Wt;var Ms;var Ts="\\n\\nHuman:";var Is="\\n\\nAssistant:";var v=class{constructor({baseURL:e=pt("ANTHROPIC_BASE_URL"),apiKey:t=pt("ANTHROPIC_API_KEY")??null,authToken:r=pt("ANTHROPIC_AUTH_TOKEN")??null,...s}={}){Ar.add(this);Wt.set(this,void 0);const o={apiKey:t,authToken:r,...s,baseURL:e||`https://api.anthropic.com`};if(!o.dangerouslyAllowBrowser&&Xr()){throw new g("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew Anthropic({ apiKey, dangerouslyAllowBrowser: true });\n")}this.baseURL=o.baseURL;this.timeout=o.timeout??Pr.DEFAULT_TIMEOUT;this.logger=o.logger??console;const a="warn";this.logLevel=a;this.logLevel=sr(o.logLevel,"ClientOptions.logLevel",this)??sr(pt("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??a;this.fetchOptions=o.fetchOptions;this.maxRetries=o.maxRetries??2;this.fetch=o.fetch??Gr();p(this,Wt,Qr,"f");this._options=o;this.apiKey=typeof t==="string"?t:null;this.authToken=r}withOptions(e){const t=new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e});return t}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(e.get("x-api-key")||e.get("authorization")){return}if(this.apiKey&&e.get("x-api-key")){return}if(t.has("x-api-key")){return}if(this.authToken&&e.get("authorization")){return}if(t.has("authorization")){return}throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders(e){return u([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey==null){return void 0}return u([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken==null){return void 0}return u([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Yr(e)}getUserAgent(){return`${this.constructor.name}/JS ${z}`}defaultIdempotencyKey(){return`stainless-node-retry-${Qt()}`}makeStatusError(e,t,r,s){return R.generate(e,t,r,s)}buildURL(e,t,r){const s=!i(this,Ar,"m",Ms).call(this)&&r||this.baseURL;const o=qr(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e));const a=this.defaultQuery();const c=Object.fromEntries(o.searchParams);if(!er(a)||!er(c)){t={...c,...a,...t}}if(typeof t==="object"&&t&&!Array.isArray(t)){o.search=this.stringifyQuery(t)}return o.toString()}_calculateNonstreamingTimeout(e){const t=10*60;const r=60*60*e/128e3;if(r>t){throw new g("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details")}return t*1e3}async prepareOptions(e){}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then(s=>{return{method:e,path:t,...s}}))}request(e,t=null){return new se(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){const s=await e;const o=s.maxRetries??this.maxRetries;if(t==null){t=o}await this.prepareOptions(s);const{req:a,url:c,timeout:l}=await this.buildRequest(s,{retryCount:o-t});await this.prepareRequest(a,{url:c,options:s});const h="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0");const f=r===void 0?"":`, retryOf: ${r}`;const m=Date.now();M(this).debug(`[${h}] sending request`,W({retryOfRequestLogID:r,method:s.method,url:c,options:s,headers:a.headers}));if(s.signal?.aborted){throw new T}const x=new AbortController;const _=await this.fetchWithTimeout(c,a,l,x).catch(We);const E=Date.now();if(_ instanceof globalThis.Error){const w=`retrying, ${t} attempts remaining`;if(s.signal?.aborted){throw new T}const A=H(_)||/timed? ?out/i.test(String(_)+("cause"in _?String(_.cause):""));if(t){M(this).info(`[${h}] connection ${A?"timed out":"failed"} - ${w}`);M(this).debug(`[${h}] connection ${A?"timed out":"failed"} (${w})`,W({retryOfRequestLogID:r,url:c,durationMs:E-m,message:_.message}));return this.retryRequest(s,t,r??h)}M(this).info(`[${h}] connection ${A?"timed out":"failed"} - error; no more retries left`);M(this).debug(`[${h}] connection ${A?"timed out":"failed"} (error; no more retries left)`,W({retryOfRequestLogID:r,url:c,durationMs:E-m,message:_.message}));if(A){throw new fe}throw new G({cause:_})}const b=[..._.headers.entries()].filter(([w])=>w==="request-id").map(([w,A])=>", "+w+": "+JSON.stringify(A)).join("");const S=`[${h}${f}${b}] ${a.method} ${c} ${_.ok?"succeeded":"failed"} with status ${_.status} in ${E-m}ms`;if(!_.ok){const w=await this.shouldRetry(_);if(t&&w){const mt=`retrying, ${t} attempts remaining`;await zr(_.body);M(this).info(`${S} - ${mt}`);M(this).debug(`[${h}] response error (${mt})`,W({retryOfRequestLogID:r,url:_.url,status:_.status,headers:_.headers,durationMs:E-m}));return this.retryRequest(s,t,r??h,_.headers)}const A=w?`error; no more retries left`:`error; not retryable`;M(this).info(`${S} - ${A}`);const De=await _.text().catch(mt=>We(mt).message);const ft=_t(De);const Rr=ft?void 0:De;M(this).debug(`[${h}] response error (${A})`,W({retryOfRequestLogID:r,url:_.url,status:_.status,headers:_.headers,message:Rr,durationMs:Date.now()-m}));const Fs=this.makeStatusError(_.status,ft,Rr,_.headers);throw Fs}M(this).info(S);M(this).debug(`[${h}] response start`,W({retryOfRequestLogID:r,url:_.url,status:_.status,headers:_.headers,durationMs:E-m}));return{response:_,options:s,controller:x,requestLogID:h,retryOfRequestLogID:r,startTime:m}}getAPIList(e,t,r){return this.requestAPIList(t,r&&"then"in r?r.then(s=>({method:"get",path:e,...s})):{method:"get",path:e,...r})}requestAPIList(e,t){const r=this.makeRequest(t,null,void 0);return new ze(this,r,e)}async fetchWithTimeout(e,t,r,s){const{signal:o,method:a,...c}=t||{};const l=this._makeAbort(s);if(o)o.addEventListener("abort",l,{once:true});const h=setTimeout(l,r);const f=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||typeof c.body==="object"&&c.body!==null&&Symbol.asyncIterator in c.body;const m={signal:s.signal,...f?{duplex:"half"}:{},method:"GET",...c};if(a){m.method=a.toUpperCase()}try{return await this.fetch.call(void 0,e,m)}finally{clearTimeout(h)}}async shouldRetry(e){const t=e.headers.get("x-should-retry");if(t==="true")return true;if(t==="false")return false;if(e.status===408)return true;if(e.status===409)return true;if(e.status===429)return true;if(e.status>=500)return true;return false}async retryRequest(e,t,r,s){let o;const a=s?.get("retry-after-ms");if(a){const l=parseFloat(a);if(!Number.isNaN(l)){o=l}}const c=s?.get("retry-after");if(c&&!o){const l=parseFloat(c);if(!Number.isNaN(l)){o=l*1e3}else{o=Date.parse(c)-Date.now()}}if(o===void 0){const l=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(t,l)}await Dr(o);return this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){const r=.5;const s=8;const o=t-e;const a=Math.min(r*Math.pow(2,o),s);const c=1-Math.random()*.25;return a*c*1e3}calculateNonstreamingTimeout(e,t){const r=60*60*1e3;const s=60*10*1e3;const o=r*e/128e3;if(o>s||t!=null&&e>t){throw new g("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details")}return s}async buildRequest(e,{retryCount:t=0}={}){const r={...e};const{method:s,path:o,query:a,defaultBaseURL:c}=r;const l=this.buildURL(o,a,c);if("timeout"in r)Hr("timeout",r.timeout);r.timeout=r.timeout??this.timeout;const{bodyHeaders:h,body:f}=this.buildBody({options:r});const m=await this.buildHeaders({options:e,method:s,bodyHeaders:h,retryCount:t});const x={method:s,headers:m,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&f instanceof globalThis.ReadableStream&&{duplex:"half"},...f&&{body:f},...this.fetchOptions??{},...r.fetchOptions??{}};return{req:x,url:l,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:s}){let o={};if(this.idempotencyHeader&&t!=="get"){if(!e.idempotencyKey)e.idempotencyKey=this.defaultIdempotencyKey();o[this.idempotencyHeader]=e.idempotencyKey}const a=u([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Kr(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);this.validateHeaders(a);return a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e){return{bodyHeaders:void 0,body:void 0}}const r=u([t]);if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e==="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream){return{bodyHeaders:void 0,body:e}}else if(typeof e==="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next==="function")){return{bodyHeaders:void 0,body:bt(e)}}else if(typeof e==="object"&&r.values.get("content-type")==="application/x-www-form-urlencoded"){return{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}}else{return i(this,Wt,"f").call(this,{body:e,headers:r})}}};Pr=v,Wt=new WeakMap,Ar=new WeakSet,Ms=function n(){return this.baseURL!=="https://api.anthropic.com"};v.Anthropic=Pr;v.HUMAN_PROMPT=Ts;v.AI_PROMPT=Is;v.DEFAULT_TIMEOUT=6e5;v.AnthropicError=g;v.APIError=R;v.APIConnectionError=G;v.APIConnectionTimeoutError=fe;v.APIUserAbortError=T;v.NotFoundError=be;v.ConflictError=ye;v.RateLimitError=xe;v.BadRequestError=me;v.AuthenticationError=ge;v.InternalServerError=Se;v.PermissionDeniedError=_e;v.UnprocessableEntityError=we;v.toFile=vt;var L=class extends v{constructor(){super(...arguments);this.completions=new he(this);this.messages=new re(this);this.models=new pe(this);this.beta=new I(this)}};L.Completions=he;L.Messages=re;L.Models=pe;L.Beta=I;function Os(n){if(n){return n}if(typeof process!=="undefined"&&process.env.PI_CACHE_RETENTION==="long"){return"long"}return"short"}function Ln(n,e){const t=Os(e);if(t==="none"){return{retention:t}}const r=t==="long"&&Kt(n).supportsLongCacheRetention?"1h":void 0;return{retention:t,cacheControl:{type:"ephemeral",...r&&{ttl:r}}}}var Nn="2.1.75";var Fn=["Read","Write","Edit","Bash","Grep","Glob","AskUserQuestion","EnterPlanMode","ExitPlanMode","KillShell","NotebookEdit","Skill","Task","TaskOutput","TodoWrite","WebFetch","WebSearch"];var jn=new Map(Fn.map(n=>[n.toLowerCase(),n]));var Bs=n=>jn.get(n.toLowerCase())??n;var qn=(n,e)=>{if(e&&e.length>0){const t=n.toLowerCase();const r=e.find(s=>s.name.toLowerCase()===t);if(r)return r.name}return n};function Cs(n){const e=n.some(s=>s.type==="image");if(!e){return q(n.map(s=>s.text).join("\n"))}const t=n.map(s=>{if(s.type==="text"){return{type:"text",text:q(s.text)}}return{type:"image",source:{type:"base64",media_type:s.mimeType,data:s.data}}});const r=t.some(s=>s.type==="text");if(!r){t.unshift({type:"text",text:"(see attached image)"})}return t}var Un=["claude-opus-5","claude-sonnet-5","claude-fable-5","claude-mythos-5","claude-mythos-preview"];function Ls(n){if(typeof n!=="string")return false;const e=n.trim().toLowerCase();const t=e.replace(/\[1m\]$/u,"");return Un.includes(t)}var Hn="fine-grained-tool-streaming-2025-05-14";var Dn="interleaved-thinking-2025-05-14";function Kt(n){const e=n.provider==="fireworks";const t=n.provider==="cloudflare-ai-gateway"&&n.baseUrl.includes("anthropic");return{supportsEagerToolInputStreaming:n.compat?.supportsEagerToolInputStreaming??!e,supportsLongCacheRetention:n.compat?.supportsLongCacheRetention??!e,sendSessionAffinityHeaders:n.compat?.sendSessionAffinityHeaders??!!(e||t),supportsCacheControlOnTools:n.compat?.supportsCacheControlOnTools??!e,supportsTemperature:n.compat?.supportsTemperature??true,allowEmptySignature:n.compat?.allowEmptySignature??false}}function Jt(...n){const e={};for(const t of n){if(t){Object.assign(e,t)}}return e}var Wn=new Set(["message_start","message_delta","message_stop","content_block_start","content_block_delta","content_block_stop"]);function Ns(n){if(!n.event&&n.data.length===0){return null}const e={event:n.event,data:n.data.join("\n"),raw:[...n.raw]};n.event=null;n.data=[];n.raw=[];return e}function Er(n,e){if(n===""){return Ns(e)}e.raw.push(n);if(n.startsWith(":")){return null}const t=n.indexOf(":");const r=t===-1?n:n.slice(0,t);let s=t===-1?"":n.slice(t+1);if(s.startsWith(" ")){s=s.slice(1)}if(r==="event"){e.event=s}else if(r==="data"){e.data.push(s)}return null}function Jn(n){const e=n.indexOf("\r");const t=n.indexOf("\n");if(e===-1){return t}if(t===-1){return e}return Math.min(e,t)}function Vt(n){const e=Jn(n);if(e===-1){return null}let t=e+1;if(n[e]==="\r"&&n[t]==="\n"){t+=1}return{line:n.slice(0,e),rest:n.slice(t)}}async function*Vn(n,e){const t=n.getReader();const r=new TextDecoder;const s={event:null,data:[],raw:[]};let o="";const a=()=>{void t.cancel(e?.reason).catch(()=>{})};e?.addEventListener("abort",a,{once:true});if(e?.aborted)a();try{while(true){if(e?.aborted){throw new Error("Request was aborted")}const{value:h,done:f}=await t.read();if(e?.aborted){throw new Error("Request was aborted")}if(f){break}o+=r.decode(h,{stream:true});let m=Vt(o);while(m){o=m.rest;const x=Er(m.line,s);if(x){yield x}m=Vt(o)}}o+=r.decode();let c=Vt(o);while(c){o=c.rest;const h=Er(c.line,s);if(h){yield h}c=Vt(o)}if(o.length>0){const h=Er(o,s);if(h){yield h}}const l=Ns(s);if(l){yield l}}finally{e?.removeEventListener("abort",a);t.releaseLock()}}async function*Xn(n,e){if(!n.body){throw new Error("Attempted to iterate over an Anthropic response with no body")}let t=false;let r=false;let s=false;const o=Date.now();let a=0;let c=0;let l=0;let h=null;let f=null;for await(const m of Vn(n.body,e)){a+=1;const x=Date.now()-o;h??=x;f=x;if(m.event==="error"){throw new Error(m.data)}if(!Wn.has(m.event??"")){continue}try{const _=Ir(m.data);c+=1;if(_.type==="message_start"){t=true}else if(_.type==="message_stop"){r=true}else if(_.type==="message_delta"){l+=1;const E=_.delta?.stop_reason;if(typeof E==="string"&&E.length>0){s=true}}yield _}catch(_){const E=_ instanceof Error?_.message:String(_);throw new Error(`Could not parse Anthropic SSE event ${m.event}: ${E}; data=${m.data}; raw=${m.raw.join("\\n")}`)}}if(e?.aborted){return}if(!t){const m=`rawEventCount=${a}; messageEventCount=${c}; firstEventAtMs=${h??"none"}; lastEventAtMs=${f??"none"}; eofAtMs=${Date.now()-o}`;throw new Error(r?`Anthropic stream ended without message_start (${m})`:`Anthropic stream ended without any message events (${m})`)}if(t&&!r){throw new Error("Anthropic stream ended before message_stop")}if(t&&r&&!s){const m=`messageDeltaCount=${l}; rawEventCount=${a}; messageEventCount=${c}; lastEventAtMs=${f??"none"}; eofAtMs=${Date.now()-o}`;throw new Error(`Anthropic stream ended without stop_reason (${m})`)}}var Xt=(n,e,t)=>{const r=new Tr;(async()=>{const s={role:"assistant",content:[],api:n.api,provider:n.provider,model:n.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};let o;try{let a;let c;if(t?.client){a=t.client;c=false}else{const b=t?.apiKey;if(!b){throw new Error(`No API key for provider: ${n.provider}`)}let S;if(n.provider==="github-copilot"){const ft=Br(e.messages);S=Lr({messages:e.messages,hasImages:ft})}const w=t?.cacheRetention??Os();const A=w==="none"?void 0:t?.sessionId;const De=Gn(n,b,t?.interleavedThinking??true,Zn(n,e),t?.headers,S,A,t?.fetch);a=De.client;c=De.isOAuthToken}let l=zn(n,e,c,t);const h=await t?.onPayload?.(l,n);if(h!==void 0){l=h}const f={...t?.signal?{signal:t.signal}:{},...t?.timeoutMs!==void 0?{timeout:t.timeoutMs}:{},maxRetries:t?.maxRetries??0};const m=await a.messages.create({...l,stream:true},f).asResponse();await t?.onResponse?.({status:m.status,headers:Mr(m.headers)},n);r.push({type:"start",partial:s});const x=s.content;const _=Xn(m,t?.signal);const E=$r(_,t?.onProviderStreamEvent,n);for await(const b of E){if(b.type==="message_start"){s.responseId=b.message.id;s.usage.input=b.message.usage.input_tokens||0;s.usage.output=b.message.usage.output_tokens||0;s.usage.cacheRead=b.message.usage.cache_read_input_tokens||0;s.usage.cacheWrite=b.message.usage.cache_creation_input_tokens||0;s.usage.totalTokens=s.usage.input+s.usage.output+s.usage.cacheRead+s.usage.cacheWrite;Gt(n,s.usage)}else if(b.type==="content_block_start"){if(b.content_block.type==="text"){const S={type:"text",text:"",index:b.index};s.content.push(S);r.push({type:"text_start",contentIndex:s.content.length-1,partial:s})}else if(b.content_block.type==="thinking"){const S={type:"thinking",thinking:"",thinkingSignature:"",index:b.index};s.content.push(S);r.push({type:"thinking_start",contentIndex:s.content.length-1,partial:s})}else if(b.content_block.type==="redacted_thinking"){const S={type:"thinking",thinking:"[Reasoning redacted]",thinkingSignature:b.content_block.data,redacted:true,index:b.index};s.content.push(S);r.push({type:"thinking_start",contentIndex:s.content.length-1,partial:s})}else if(b.content_block.type==="tool_use"){const S={type:"toolCall",id:b.content_block.id,name:c?qn(b.content_block.name,e.tools):b.content_block.name,arguments:b.content_block.input??{},partialJson:"",index:b.index};s.content.push(S);r.push({type:"toolcall_start",contentIndex:s.content.length-1,partial:s})}}else if(b.type==="content_block_delta"){if(b.delta.type==="text_delta"){const S=x.findIndex(A=>A.index===b.index);const w=x[S];if(w&&w.type==="text"){w.text+=b.delta.text;r.push({type:"text_delta",contentIndex:S,delta:b.delta.text,partial:s})}}else if(b.delta.type==="thinking_delta"){const S=x.findIndex(A=>A.index===b.index);const w=x[S];if(w&&w.type==="thinking"){w.thinking+=b.delta.thinking;r.push({type:"thinking_delta",contentIndex:S,delta:b.delta.thinking,partial:s})}}else if(b.delta.type==="input_json_delta"){const S=x.findIndex(A=>A.index===b.index);const w=x[S];if(w&&w.type==="toolCall"){w.partialJson+=b.delta.partial_json;w.arguments=zt(w.partialJson);r.push({type:"toolcall_delta",contentIndex:S,delta:b.delta.partial_json,partial:s})}}else if(b.delta.type==="signature_delta"){const S=x.findIndex(A=>A.index===b.index);const w=x[S];if(w&&w.type==="thinking"){w.thinkingSignature=w.thinkingSignature||"";w.thinkingSignature+=b.delta.signature}}}else if(b.type==="content_block_stop"){const S=x.findIndex(A=>A.index===b.index);const w=x[S];if(w){delete w.index;if(w.type==="text"){r.push({type:"text_end",contentIndex:S,content:w.text,partial:s})}else if(w.type==="thinking"){r.push({type:"thinking_end",contentIndex:S,content:w.thinking,partial:s})}else if(w.type==="toolCall"){w.arguments=zt(w.partialJson);delete w.partialJson;r.push({type:"toolcall_end",contentIndex:S,toolCall:w,partial:s})}}}else if(b.type==="message_delta"){if(b.delta.stop_reason){s.stopReason=so(b.delta.stop_reason);if(b.delta.stop_reason==="refusal"){o=to(b.delta)}}if(b.usage.input_tokens!=null){s.usage.input=b.usage.input_tokens}if(b.usage.output_tokens!=null){s.usage.output=b.usage.output_tokens}if(b.usage.cache_read_input_tokens!=null){s.usage.cacheRead=b.usage.cache_read_input_tokens}if(b.usage.cache_creation_input_tokens!=null){s.usage.cacheWrite=b.usage.cache_creation_input_tokens}s.usage.totalTokens=s.usage.input+s.usage.output+s.usage.cacheRead+s.usage.cacheWrite;Gt(n,s.usage)}}if(t?.signal?.aborted){throw new Error("Request was aborted")}if(o){throw new Error(ro(o))}if(s.stopReason==="aborted"||s.stopReason==="error"){throw new Error("An unknown error occurred")}r.push({type:"done",reason:s.stopReason,message:s});r.end()}catch(a){Cr(t?.onProviderError,a,n);for(const c of s.content){delete c.index;delete c.partialJson}s.stopReason=t?.signal?.aborted?"aborted":"error";s.errorMessage=a instanceof Error?a.message:JSON.stringify(a);r.push({type:"error",reason:s.stopReason,error:s});r.end()}})();return r};function $s(n,e){const t=e?n.thinkingLevelMap?.[e]:void 0;if(typeof t==="string")return t;switch(e){case"minimal":case"low":return"low";case"medium":return"medium";case"high":return"high";default:return"high"}}var Kl=(n,e,t)=>{const r=t?.apiKey;if(!r){throw new Error(`No API key for provider: ${n.provider}`)}const s=Nr(n,t,r);if(!t?.reasoning){return Xt(n,e,{...s,thinkingEnabled:false})}if(Ls(n.id)){const a=$s(n,t.reasoning);return Xt(n,e,{...s,thinkingEnabled:true,effort:a})}if(n.compat?.forceAdaptiveThinking===true){const a=$s(n,t.reasoning);return Xt(n,e,{...s,thinkingEnabled:true,effort:a})}const o=Fr(s.maxTokens,n.maxTokens,t.reasoning,t.thinkingBudgets);return Xt(n,e,{...s,maxTokens:o.maxTokens,thinkingEnabled:true,thinkingBudgetTokens:o.thinkingBudget})};function Kn(n){return n.includes("sk-ant-oat")}function Gn(n,e,t,r,s,o,a,c){const l=t&&n.compat?.forceAdaptiveThinking!==true;const h=[];if(r){h.push(Hn)}if(l){h.push(Dn)}const f=c?{fetch:c}:{};if(n.provider==="cloudflare-ai-gateway"){const _=new L({apiKey:null,authToken:null,baseURL:Or(n),dangerouslyAllowBrowser:true,...f,defaultHeaders:Jt({accept:"application/json","anthropic-dangerous-direct-browser-access":"true","cf-aig-authorization":`Bearer ${e}`,"x-api-key":null,Authorization:null,...h.length>0?{"anthropic-beta":h.join(",")}:{}},n.headers,s)});return{client:_,isOAuthToken:false}}if(n.provider==="github-copilot"){const _=new L({apiKey:null,authToken:e,baseURL:n.baseUrl,dangerouslyAllowBrowser:true,...f,defaultHeaders:Jt({accept:"application/json","anthropic-dangerous-direct-browser-access":"true",...h.length>0?{"anthropic-beta":h.join(",")}:{}},n.headers,o,s)});return{client:_,isOAuthToken:false}}if(Kn(e)){const _=new L({apiKey:null,authToken:e,baseURL:n.baseUrl,dangerouslyAllowBrowser:true,...f,defaultHeaders:Jt({accept:"application/json","anthropic-dangerous-direct-browser-access":"true","anthropic-beta":["claude-code-20250219","oauth-2025-04-20",...h].join(","),"user-agent":`claude-cli/${Nn}`,"x-app":"cli"},n.headers,s)});return{client:_,isOAuthToken:true}}const m=a&&Kt(n).sendSessionAffinityHeaders?{"x-session-affinity":a}:{};const x=new L({apiKey:e,authToken:null,baseURL:n.baseUrl,dangerouslyAllowBrowser:true,...f,defaultHeaders:Jt({accept:"application/json","anthropic-dangerous-direct-browser-access":"true",...h.length>0?{"anthropic-beta":h.join(",")}:{}},m,n.headers,s)});return{client:x,isOAuthToken:false}}function zn(n,e,t,r){const{cacheControl:s}=Ln(n,r?.cacheRetention);const o=Kt(n);const a={model:n.id,messages:Yn(e.messages,n,t,s,o.allowEmptySignature),max_tokens:r?.maxTokens??n.maxTokens,stream:true};if(t){a.system=[{type:"text",text:"You are Claude Code, Anthropic's official CLI for Claude.",...s?{cache_control:s}:{}}];if(e.systemPrompt){a.system.push({type:"text",text:q(e.systemPrompt),...s?{cache_control:s}:{}})}}else if(e.systemPrompt){a.system=[{type:"text",text:q(e.systemPrompt),...s?{cache_control:s}:{}}]}if(r?.temperature!==void 0&&!r?.thinkingEnabled&&o.supportsTemperature){a.temperature=r.temperature}if(e.tools&&e.tools.length>0){a.tools=eo(e.tools,t,o.supportsEagerToolInputStreaming,o.supportsCacheControlOnTools?s:void 0)}if(n.reasoning){if(r?.thinkingEnabled){const c=r.thinkingDisplay??"summarized";if(Ls(n.id)){if(r.effort){a.output_config={effort:r.effort}}}else if(n.compat?.forceAdaptiveThinking===true){a.thinking={type:"adaptive",display:c};if(r.effort){a.output_config=r.effort==="xhigh"?{effort:r.effort}:{effort:r.effort}}}else{a.thinking={type:"enabled",budget_tokens:r.thinkingBudgetTokens||1024,display:c}}}else if(r?.thinkingEnabled===false){a.thinking={type:"disabled"}}}if(r?.metadata){const c=r.metadata.user_id;if(typeof c==="string"){a.metadata={user_id:c}}}if(r?.toolChoice){if(typeof r.toolChoice==="string"){a.tool_choice={type:r.toolChoice}}else{a.tool_choice=r.toolChoice}}return a}function Qn(n){return n.replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)}function Yn(n,e,t,r,s=false){const o=[];const a=jr(n,e,Qn);for(let c=0;c<a.length;c++){const l=a[c];if(l.role==="user"){if(typeof l.content==="string"){if(l.content.trim().length>0){o.push({role:"user",content:q(l.content)})}}else{const h=l.content.map(m=>{if(m.type==="text"){return{type:"text",text:q(m.text)}}else{return{type:"image",source:{type:"base64",media_type:m.mimeType,data:m.data}}}});const f=h.filter(m=>{if(m.type==="text"){return m.text.trim().length>0}return true});if(f.length===0)continue;o.push({role:"user",content:f})}}else if(l.role==="assistant"){const h=[];for(const f of l.content){if(f.type==="text"){if(f.text.trim().length===0)continue;h.push({type:"text",text:q(f.text)})}else if(f.type==="thinking"){if(f.redacted){h.push({type:"redacted_thinking",data:f.thinkingSignature});continue}const m=f.thinkingSignature;const x=!!m&&m.trim().length>0;if(f.thinking.trim().length===0&&!x)continue;if(!x){h.push(s?{type:"thinking",thinking:q(f.thinking),signature:""}:{type:"text",text:q(f.thinking)})}else{h.push({type:"thinking",thinking:q(f.thinking),signature:m})}}else if(f.type==="toolCall"){h.push({type:"tool_use",id:f.id,name:t?Bs(f.name):f.name,input:f.arguments??{}})}}if(h.length===0)continue;o.push({role:"assistant",content:h})}else if(l.role==="toolResult"){const h=[];h.push({type:"tool_result",tool_use_id:l.toolCallId,content:Cs(l.content),is_error:l.isError});let f=c+1;while(f<a.length&&a[f].role==="toolResult"){const m=a[f];h.push({type:"tool_result",tool_use_id:m.toolCallId,content:Cs(m.content),is_error:m.isError});f++}c=f-1;o.push({role:"user",content:h})}}if(r&&o.length>0){const c=o[o.length-1];if(c.role==="user"){if(Array.isArray(c.content)){const l=c.content[c.content.length-1];if(l&&(l.type==="text"||l.type==="image"||l.type==="tool_result")){l.cache_control=r}}else if(typeof c.content==="string"){c.content=[{type:"text",text:c.content,cache_control:r}]}}}return o}function Zn(n,e){return!!e.tools?.length&&!Kt(n).supportsEagerToolInputStreaming}function eo(n,e,t,r){if(!n)return[];return n.map((s,o)=>{const a=s.parameters;return{name:e?Bs(s.name):s.name,description:s.description,...t?{eager_input_streaming:true}:{},input_schema:{type:"object",properties:a.properties??{},required:a.required??[]},...r&&o===n.length-1?{cache_control:r}:{}}})}function to(n){const e=n.stop_details;if(!e||typeof e!=="object")return{};const{category:t,explanation:r}=e;return{...typeof t==="string"&&t.trim()?{category:t.trim()}:{},...typeof r==="string"&&r.trim()?{explanation:r.trim()}:{}}}function ro(n){const e=n.category?`; category: ${n.category}`:"";const t=n.explanation?`: ${n.explanation}`:"";return`Model declined the request (stop_reason: refusal${e})${t}`}function so(n){switch(n){case"end_turn":return"stop";case"max_tokens":return"length";case"tool_use":return"toolUse";case"refusal":return"error";case"pause_turn":return"stop";case"stop_sequence":return"stop";case"sensitive":return"error";default:throw new Error(`Unhandled stop reason: ${n}`)}}export{Un as a,Ls as b,Xt as c,Kl as d};
@@ -0,0 +1,4 @@
1
+ import { createRequire as __alran_cR } from "module"; import { basename as __alran_basename, dirname as __alran_dirname, join as __alran_join } from "path"; import { fileURLToPath as __alran_fileURLToPath, pathToFileURL as __alran_pathToFileURL } from "url"; const __alran_tuiCurrentModuleDir = __alran_dirname(__alran_fileURLToPath(import.meta.url)); const __alran_tuiPackageRoot = __alran_basename(__alran_tuiCurrentModuleDir) === "chunks" ? __alran_dirname(__alran_tuiCurrentModuleDir) : __alran_tuiCurrentModuleDir; const __alran_tuiPackageEntryUrl = __alran_pathToFileURL(__alran_join(__alran_tuiPackageRoot, "cli.js")).href; const require = __alran_cR(__alran_tuiPackageEntryUrl); const __dirname = __alran_tuiPackageRoot;
2
+ import{o as q}from"./chunk-XFCC2CI2.js";var Q="alran.store/v1";var ee="alran.store.installed/v1";var be="alran.store.sources/v1";var F="ottili";var Ne="https://ai.ottili.one/v1/store/index.json";var ge="off";var he="ALRAN_STORE_URL";var O={indexBytes:8*1024*1024,entries:5e3,fetchTimeoutMs:2e4,freshForMs:10*60*1e3};var ye=["Office","Studio","Design & Sites","Code","Business","Sales","Productivity","Science & Healthcare","Education","Other"];var u=class extends Error{constructor(r,n,o){super(n,o);this.code=r;this.name="StoreError"}code};var te=/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u;var ne=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;var Se=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;var re=/^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-((?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/u;var Oe=/^[0-9a-f]{64}$/u;var Pe=/^sha256-tree-v1:[0-9a-f]{64}$/u;import ln from"node:path";import{randomBytes as ct}from"node:crypto";import{mkdirSync as dt,renameSync as Ce,rmSync as ut}from"node:fs";import{mkdir as we,readFile as ft,rename as pt,rm as Ee,stat as ve,writeFile as mt}from"node:fs/promises";import oe from"node:path";function x(t){return oe.join(t,"store")}function H(){return ct(6).toString("hex")}function De(t){return typeof t==="object"&&t!==null&&"code"in t&&t.code==="ENOENT"}async function P(t){try{return await ft(t,"utf8")}catch(e){if(De(e))return void 0;throw e}}async function V(t,e){await we(oe.dirname(t),{recursive:true});const r=`${t}.${H()}.tmp`;try{await mt(r,e,{encoding:"utf8",mode:384});q(()=>Ce(r,t))}catch(n){await Ee(r,{force:true});throw n}}function ie(t,e){dt(oe.dirname(e),{recursive:true});q(()=>Ce(t,e))}function se(t){q(()=>ut(t,{recursive:true,force:true}))}async function j(t){try{await ve(t);return true}catch(e){if(De(e))return false;throw e}}var gt=6e4;var ht=15e3;async function U(t,e){const r=oe.join(x(t),"lock");await we(x(t),{recursive:true});const n=Date.now()+ht;for(;;){try{await we(r);break}catch(o){if(typeof o!=="object"||o===null||!("code"in o))throw o;if(o.code!=="EEXIST")throw o;const i=await ve(r).then(a=>Date.now()-a.mtimeMs,()=>0);if(i>gt){await Ee(r,{recursive:true,force:true});continue}if(Date.now()>n)throw new Error("The Store is busy in another Alran process.");await new Promise(a=>{setTimeout(a,100)})}}try{return await e()}finally{const o=`${r}.${H()}.released`;await pt(r,o).then(()=>Ee(o,{recursive:true,force:true}),()=>void 0)}}import{existsSync as wt}from"node:fs";import{readdir as Et,readFile as It}from"node:fs/promises";import{fileURLToPath as At}from"node:url";import $t from"node:path";var yt=/[\u0000-\u001f\u007f-\u009f؜‎‏‪-‮⁦-⁩]/gu;function C(t){return t.replace(yt,e=>`\\u{${e.codePointAt(0)?.toString(16)}}`)}function T(t){return C(t.replace(/\s+/gu," ").trim())}function Ue(t,e){const r=new Map(t.map(I=>[I.path,I.content]));const n=r.get(".alran-plugin/plugin.json");if(!n)y("has no .alran-plugin/plugin.json");const o=ae(n,".alran-plugin/plugin.json");if(o.schemaVersion!==1)y("manifest schemaVersion must be 1");const i=_(o.name,"manifest name");if(!te.test(i)||i!==e.name){y(`manifest name "${i}" is not the listed name "${e.name}"`)}const a=_(o.version,"manifest version");if(!re.test(a)||a!==e.version){y(`manifest version "${a}" is not the listed version "${e.version}"`)}const s=_(o.icon,"manifest icon");if(!r.has(s))y(`icon ${s} is missing`);const l=z(o.skills,"skills").map(I=>{const m=_(I,"skills entry");const A=/^skills\/([A-Za-z0-9._-]+)\/SKILL\.md$/u.exec(m);if(!A?.[1])y(`skill reference ${m} is not skills/<name>/SKILL.md`);const $=r.get(m);if(!$)y(`${m} is missing`);const w=G($.toString("utf8"),m);if(w.name!==A[1])y(`${m} names the skill "${w.name}"`);return{name:w.name,description:T(w.description),hasScripts:[...r.keys()].some(b=>b.startsWith(`skills/${A[1]}/scripts/`))}});const c=[];const d=[];for(const I of z(o.mcpServers,"mcpServers")){const m=_(I,"mcpServers entry");const A=ae(Ie(r,m),m);const $=W(A.mcpServers,`${m} mcpServers`);for(const[w,b]of Object.entries($)){const k=W(b,`${m} server ${w}`);d.push(C(w));if(k.type==="stdio"){const N=Array.isArray(k.args)?k.args.map(String):[];c.push({kind:"mcp-stdio",line:C(`MCP server "${w}" runs: ${[String(k.command),...N].join(" ")}`)})}else{c.push({kind:"mcp-remote",line:C(`MCP server "${w}" connects to: ${String(k.url)}`)})}}}const p=[];for(const I of z(o.apps,"apps")){const m=_(I,"apps entry");const A=_(ae(Ie(r,m),m).provider,`${m} provider`);p.push(C(A));c.push({kind:"app",line:C(`Connector "${A}" asks to link an account`)})}let h=0;for(const I of z(o.hooks,"hooks")){const m=_(I,"hooks entry");const A=ae(Ie(r,m),m);for(const[$,w]of Object.entries(W(A.hooks,`${m} hooks`))){for(const b of z(w,`${m} ${$}`)){for(const k of z(W(b,`${m} ${$} group`).hooks,"hooks")){const N=W(k,`${m} ${$} handler`);if(N.type!=="command")continue;h+=1;c.push({kind:"hook",line:C(`Hook on ${$} runs: ${String(N.command)}`)})}}}}const D=typeof o.displayName==="string"&&o.displayName.trim()?o.displayName.trim():i;return{kind:"plugin",name:i,version:a,displayName:T(D),description:T(_(o.description,"manifest description")),author:T(_(o.author,"manifest author")),category:_(o.category,"manifest category"),skills:l,mcpServers:d,apps:p,hooks:h,files:t.length,executes:c,requiresConsent:c.length>0}}function Me(t,e){if(!ne.test(e.name))y(`"${e.name}" is not a Skill name`);const r=t.find(o=>o.path==="SKILL.md");if(!r)y("has no SKILL.md at its root");const n=G(r.content.toString("utf8"),"SKILL.md");if(n.name!==e.name){y(`SKILL.md names the skill "${n.name}", the store lists "${e.name}"`)}return{kind:"skill",name:n.name,description:T(n.description),files:t.length,hasScripts:t.some(o=>o.path.startsWith("scripts/")),executes:[],requiresConsent:false}}function G(t,e){if(t.charCodeAt(0)===65279)y(`${e} starts with a byte order mark`);const r=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u.exec(t);if(!r?.[1])y(`${e} has no YAML frontmatter`);const n=St(r[1]);const o=n.get("name");const i=n.get("description");if(!o)y(`${e} frontmatter has no name`);if(!i)y(`${e} frontmatter has no description`);return{name:o,description:i}}function St(t){const e=new Map;const r=t.split(/\r?\n/u);for(let n=0;n<r.length;n+=1){const o=r[n]??"";const i=/^([A-Za-z0-9_-]+)\s*:\s*(.*)$/u.exec(o);if(!i?.[1])continue;const a=i[1];let s=(i[2]??"").trim();if(/^[|>][+-]?$/u.test(s)){const l=s.startsWith(">");const c=[];while(n+1<r.length&&/^(\s+|$)/u.test(r[n+1]??"")){n+=1;c.push((r[n]??"").trim())}s=c.filter((d,p)=>d||p<c.length-1).join(l?" ":"\n").trim()}else if(s.startsWith('"')&&s.endsWith('"')&&s.length>=2){try{s=JSON.parse(s)}catch{s=s.slice(1,-1)}}else if(s.startsWith("'")&&s.endsWith("'")&&s.length>=2){s=s.slice(1,-1).replace(/''/gu,"'")}else if(s===""){const l=[];while(n+1<r.length&&/^\s+\S/u.test(r[n+1]??"")){n+=1;l.push((r[n]??"").trim())}s=l.join(" ")}if(!e.has(a))e.set(a,s)}return e}function ae(t,e){let r;try{r=JSON.parse(t.toString("utf8"))}catch{y(`${e} is not valid JSON`)}return W(r,e)}function Ie(t,e){const r=t.get(e);if(!r)y(`${e} is listed in the manifest but missing`);return r}function W(t,e){if(typeof t!=="object"||t===null||Array.isArray(t)){y(`${e} must be an object`)}return t}function z(t,e){if(t===void 0)return[];if(!Array.isArray(t))y(`${e} must be an array`);return t}function _(t,e){if(typeof t!=="string"||!t.trim())y(`${e} must be a non-empty string`);return t.trim()}function y(t){throw new u("PACKAGE_INVALID",`The package ${t}.`)}function Be(t){const e=["../assets/skills/","./assets/skills/","../../../local-runtime/assets/skills/"];for(const r of e){const n=At(new URL(r,t));if(wt(n))return n}return void 0}async function Fe(t){let e;try{e=await Et(t)}catch{return[]}const r=[];for(const n of e.sort()){try{const o=await It($t.join(t,n,"SKILL.md"),"utf8");const i=G(o,`${n}/SKILL.md`);r.push({name:i.name,description:T(i.description)})}catch{}}return r}import{mkdir as Ze,writeFile as Zt}from"node:fs/promises";import B from"node:path";import{createHash as He}from"node:crypto";var L={archiveBytes:64*1024*1024,entries:2048,files:1024,fileBytes:16*1024*1024,totalBytes:64*1024*1024,pathBytes:512,segmentBytes:128,pathSegments:16};var J=class extends Error{constructor(r,n){super(`${r}: ${n}`);this.code=r;this.detail=n;this.name="StoreArchiveError"}code;detail};var kt=67324752;var xt=33639248;var _t=101010256;var Rt=61440;var Lt=32768;var Tt=16384;var bt=40960;var Nt=/^[A-Za-z0-9._-]+$/u;var Ot=new Set(["con","prn","aux","nul",...Array.from({length:9},(t,e)=>`com${e+1}`),...Array.from({length:9},(t,e)=>`lpt${e+1}`)]);var Pt=Buffer.from("ALRAN-PLUGIN-CONTENT-DIGEST\0","ascii");function Ct(t){if(!t)f("INVALID_PATH","path is empty");if(!/^[\x00-\x7f]*$/u.test(t)){f("NON_PORTABLE_PATH",`${JSON.stringify(t)} is not ASCII`)}if(t.startsWith("/")||/^[A-Za-z]:/u.test(t)){f("ABSOLUTE_PATH",`${JSON.stringify(t)} is absolute`)}if(t.includes("\\")){f("BACKSLASH_PATH",`${JSON.stringify(t)} contains a backslash`)}if(t.endsWith("/")){f("INVALID_PATH",`${JSON.stringify(t)} has a trailing slash`)}if(/[\x00-\x1f\x7f]/u.test(t)){f("CONTROL_CHARACTER",`${JSON.stringify(t)} contains a control character`)}if(t.length>L.pathBytes){f("PATH_TOO_LONG",`${JSON.stringify(t)} exceeds the path limit`)}const e=t.split("/");if(e.length>L.pathSegments){f("PATH_TOO_DEEP",`${JSON.stringify(t)} has too many segments`)}for(const r of e){if(!r||r==="."||r===".."){f("PATH_TRAVERSAL",`${JSON.stringify(t)} has an empty or dot segment`)}if(r.length>L.segmentBytes){f("SEGMENT_TOO_LONG",`${JSON.stringify(r)} exceeds the segment limit`)}if(!Nt.test(r)||r.endsWith(".")){f("NON_PORTABLE_PATH",`${JSON.stringify(r)} is not portable`)}const[n=""]=r.split(".",1);if(Ot.has(n.toLowerCase())){f("WINDOWS_RESERVED_PATH",`${JSON.stringify(r)} is reserved on Windows`)}}}function vt(t){const e=[...t].sort((n,o)=>Buffer.compare(Buffer.from(n.path,"ascii"),Buffer.from(o.path,"ascii")));const r=He("sha256");r.update(Pt);r.update(Ae(1));r.update(Ae(e.length));for(const n of e){const o=Buffer.from(n.path,"ascii");r.update(Buffer.from([70]));r.update(Ae(o.length));r.update(o);r.update(jt(n.content.length));r.update(n.content)}return`sha256-tree-v1:${r.digest("hex")}`}function Ve(t){return He("sha256").update(t).digest("hex")}function je(t){if(t.length>L.archiveBytes){f("ARCHIVE_TOO_LARGE",`${t.length} bytes exceed the archive limit`)}if(t.length<22)f("INVALID_ZIP","end-of-central-directory record is missing");const e=Dt(t);const r=Ut(t,e);const n=[];const o=[];const i=new Set;const a=new Map;const s=new Set;let l=0;for(const d of r){const p=Mt(t,d,e.centralOffset);o.push({start:d.localOffset,end:p.end});const h=t.subarray(p.data,p.end);if(Wt(h)!==d.crc)f("CRC_MISMATCH",`${d.path} has an invalid CRC`);if(d.kind==="symlink")f("SYMLINK_NOT_ALLOWED",`${d.path} is a symlink`);if(d.kind==="special")f("SPECIAL_ENTRY_NOT_ALLOWED",`${d.path} is special`);Ct(d.path);if(i.has(d.path))f("DUPLICATE_PATH",`${d.path} appears twice`);i.add(d.path);Ht(d.path,a);if(d.kind==="directory")continue;s.add(d.path);if(h.length>L.fileBytes){f("FILE_TOO_LARGE",`${d.path} exceeds the per-file limit`)}l+=h.length;if(l>L.totalBytes){f("TOTAL_SIZE_LIMIT","unpacked size exceeds the total limit")}n.push({path:d.path,content:h})}if(n.length>L.files)f("TOO_MANY_FILES",`${n.length} files`);Ft(o);Vt(i,s);const c=[...n].sort((d,p)=>Buffer.compare(Buffer.from(d.path,"ascii"),Buffer.from(p.path,"ascii")));return{files:c,contentDigest:vt(c),totalBytes:l}}function Dt(t){const e=t.length-22;$e(t,e,_t,"end-of-central-directory");const r=E(t,e+4);const n=E(t,e+6);const o=E(t,e+8);const i=E(t,e+10);const a=R(t,e+12);const s=R(t,e+16);if(E(t,e+20)!==0)f("ARCHIVE_COMMENT_NOT_ALLOWED","comment not empty");if(r!==0||n!==0||o!==i){f("MULTI_DISK_NOT_ALLOWED","multi-disk ZIP is not supported")}if(i===65535||a===4294967295||s===4294967295){f("ZIP64_NOT_ALLOWED","ZIP64 sentinel values are not supported")}if(i>L.entries)f("TOO_MANY_ENTRIES",`${i} entries`);if(s+a!==e){f("INVALID_ZIP","central directory bounds do not match the archive")}return{endOffset:e,entryCount:i,centralOffset:s}}function Ut(t,e){const r=[];let n=e.centralOffset;for(let o=0;o<e.entryCount;o+=1){M(t,n,46,"central directory header");$e(t,n,xt,"central directory");const i=E(t,n+4);const a=E(t,n+8);const s=E(t,n+10);const l=R(t,n+16);const c=R(t,n+20);const d=R(t,n+24);const p=E(t,n+28);const h=E(t,n+30);const D=E(t,n+32);const I=E(t,n+34);const m=R(t,n+38);const A=R(t,n+42);ze(a);if(s!==0)f("UNSUPPORTED_COMPRESSION",`ZIP method ${s} is not STORE`);if(c===4294967295||d===4294967295){f("ZIP64_NOT_ALLOWED","ZIP64 entry values are not supported")}if(A===4294967295)f("ZIP64_NOT_ALLOWED","ZIP64 offset");if(h!==0)f("EXTRA_FIELD_NOT_ALLOWED","ZIP extra fields are not supported");if(D!==0)f("ENTRY_COMMENT_NOT_ALLOWED","entry comments are not supported");if(I!==0)f("MULTI_DISK_NOT_ALLOWED","entry on a non-zero disk");if(c!==d)f("SIZE_MISMATCH","STORE sizes differ");const $=n+46+p;M(t,n+46,p,"central entry name");if($>e.endOffset)f("INVALID_ZIP","central entry exceeds the directory");const w=t.subarray(n+46,$);if(w.length===0)f("INVALID_PATH","ZIP entry name is empty");if(w.some(lt=>lt>127))f("NON_PORTABLE_PATH","entry name is not ASCII");const b=w.toString("ascii");const k=b.endsWith("/");const N=k?b.slice(0,-1):b;const X=Bt(i,m,k);if(X==="directory"&&!k)f("INVALID_DIRECTORY_ENTRY",N);if(X!=="directory"&&k)f("INVALID_DIRECTORY_ENTRY",N);if(X==="directory"&&d!==0)f("INVALID_DIRECTORY_ENTRY",N);r.push({path:N,rawName:w,kind:X,flags:a,method:s,crc:l,compressedSize:c,uncompressedSize:d,localOffset:A});n=$}if(n!==e.endOffset)f("INVALID_ZIP","central directory entry count is inconsistent");return r}function Mt(t,e,r){const n=e.localOffset;M(t,n,30,"local file header");$e(t,n,kt,"local file");const o=E(t,n+6);const i=E(t,n+8);const a=R(t,n+14);const s=R(t,n+18);const l=R(t,n+22);const c=E(t,n+26);const d=E(t,n+28);ze(o);if(d!==0)f("EXTRA_FIELD_NOT_ALLOWED","local ZIP extra field is not empty");if(o!==e.flags||i!==e.method||a!==e.crc||s!==e.compressedSize||l!==e.uncompressedSize){f("LOCAL_HEADER_MISMATCH",`${e.path} local and central headers differ`)}M(t,n+30,c,"local entry name");if(!t.subarray(n+30,n+30+c).equals(e.rawName)){f("LOCAL_HEADER_MISMATCH",`${e.path} local and central names differ`)}const p=n+30+c;const h=p+s;if(h>r)f("INVALID_ZIP",`${e.path} data overlaps the directory`);return{data:p,end:h}}function Bt(t,e,r){if(t>>>8===3){const n=e>>>16&Rt;if(n===bt)return"symlink";if(n===Tt)return"directory";if(n===Lt||n===0)return r?"directory":"file";return"special"}return(e&16)!==0||r?"directory":"file"}function ze(t){if((t&1)!==0)f("ENCRYPTION_NOT_ALLOWED","encrypted ZIP entry");if((t&8)!==0)f("DATA_DESCRIPTOR_NOT_ALLOWED","data descriptor ZIP entry");if(t!==0)f("UNSUPPORTED_ZIP_FLAGS",`unsupported ZIP flags 0x${t.toString(16)}`)}function Ft(t){t.sort((e,r)=>e.start-r.start);for(let e=1;e<t.length;e+=1){const r=t[e];const n=t[e-1];if(r&&n&&r.start<n.end){f("OVERLAPPING_ENTRIES","local ZIP entries overlap")}}}function Ht(t,e){const r=t.split("/");for(let n=1;n<=r.length;n+=1){const o=r.slice(0,n).join("/");const i=o.toLowerCase();const a=e.get(i);if(a!==void 0&&a!==o){f("CASE_COLLISION",`${o} and ${a} differ only by case`)}e.set(i,o)}}function Vt(t,e){for(const r of t){const n=r.split("/");for(let o=1;o<n.length;o+=1){const i=n.slice(0,o).join("/");if(e.has(i)){f("PATH_TYPE_CONFLICT",`${i} is a file but ${r} lies beneath it`)}}}}function $e(t,e,r,n){M(t,e,4,`${n} signature`);if(R(t,e)!==r)f("INVALID_ZIP",`${n} signature is invalid`)}function M(t,e,r,n){if(e<0||r<0||e+r>t.length){f("INVALID_ZIP",`${n} exceeds archive bounds`)}}function E(t,e){M(t,e,2,"uint16");return t.readUInt16LE(e)}function R(t,e){M(t,e,4,"uint32");return t.readUInt32LE(e)}function Ae(t){const e=Buffer.alloc(4);e.writeUInt32BE(t);return e}function jt(t){const e=Buffer.alloc(8);e.writeBigUInt64BE(BigInt(t));return e}var zt=Array.from({length:256},(t,e)=>{let r=e;for(let n=0;n<8;n+=1){r=(r&1)===1?3988292384^r>>>1:r>>>1}return r>>>0});function Wt(t){let e=4294967295;for(const r of t)e=(zt[(e^r)&255]??0)^e>>>8;return(e^4294967295)>>>0}function f(t,e){throw new J(t,e)}import{rename as Gt}from"node:fs/promises";import Kt from"node:path";var We={schema:ee,plugins:{},skills:{}};var le=class{constructor(e){this.dataDir=e}dataDir;async read(){const e=this.file();const r=await P(e);if(r===void 0)return We;try{const n=JSON.parse(r);if(n.schema!==ee)throw new Error("unknown schema");return{schema:ee,plugins:Ke(n.plugins),skills:Ke(n.skills)}}catch{await Gt(e,`${e}.corrupt-${H()}`).catch(()=>void 0);return We}}async record(e,r,n){const o=await this.read();const i=Ge(o,e,r,n);await this.write(i);return i}async forget(e,r){const n=await this.read();const o=Ge(n,e,r,void 0);await this.write(o);return o}async write(e){await V(this.file(),`${JSON.stringify(e,null,2)}
3
+ `)}file(){return Kt.join(x(this.dataDir),"installed.json")}};function Ge(t,e,r,n){const o=e==="plugin"?"plugins":"skills";const i={...t[o]};if(n)i[r]=n;else delete i[r];return{...t,[o]:i}}function Ke(t){const e={};if(typeof t!=="object"||t===null)return e;for(const[r,n]of Object.entries(t)){if(typeof n!=="object"||n===null)continue;const{source:o,version:i,contentDigest:a,installedAt:s}=n;if(typeof o==="string"&&typeof i==="string"&&typeof a==="string"&&typeof s==="string"){e[r]={source:o,version:i,contentDigest:a,installedAt:s}}}return e}var ce=class{constructor(e){this.options=e;this.ledgerFile=new le(e.dataDir);this.now=e.now??(()=>new Date)}options;ledgerFile;now;ledger(){return this.ledgerFile.read()}installDirectory(e,r){return B.join(this.options.dataDir,e==="plugin"?"plugins":"skills",r)}async stage(e,r,n={}){const o=await this.ledgerFile.read();const i=e.kind==="plugin"?o.plugins:o.skills;const a=i[e.name];const s=this.installDirectory(e.kind,e.name);if(a&&a.source!==r){throw new u("CONFLICT",`"${e.name}" is installed from the "${a.source}" store; remove it before installing it from "${r}".`)}if(!a&&await j(s)){throw new u("CONFLICT",`${s} already exists and was not installed by the Store. Move or remove it first; the Store never overwrites a ${e.kind} you put there.`)}const l=await this.options.transport.readBytes(e.archive.url,{maxBytes:e.archive.size,...n.signal?{signal:n.signal}:{}});if(l.length!==e.archive.size){throw new u("DIGEST_MISMATCH",`${e.name}: the archive is ${l.length} bytes, the index says ${e.archive.size}.`)}if(Ve(l)!==e.archive.archiveSha256){throw new u("DIGEST_MISMATCH",`${e.name}: the downloaded archive does not match the SHA-256 in the index. Nothing was installed.`)}let c;let d;try{({files:c,contentDigest:d}=je(l))}catch(h){if(h instanceof J){throw new u("ARCHIVE_INVALID",`${e.name}: ${h.message}`,{cause:h})}throw h}if(d!==e.archive.contentDigest){throw new u("DIGEST_MISMATCH",`${e.name}: the unpacked files do not match the content digest in the index. Nothing was installed.`)}const p=e.kind==="plugin"?Ue(c,{name:e.name,version:e.version}):Me(c,{name:e.name});return{entry:e,sourceId:r,inspection:p,...a?{replacesVersion:a.version}:{},target:s,files:c,contentDigest:d}}async commit(e,r){if(e.inspection.requiresConsent&&!r.consent){throw new u("CONSENT_REQUIRED",`${e.entry.name} runs commands or connects to services (${e.inspection.executes.length}); it was not installed because it was not approved.`)}return U(this.options.dataDir,async()=>{const n=await this.ledgerFile.read();const o=e.entry.kind==="plugin"?n.plugins:n.skills;const i=o[e.entry.name];const a=await j(e.target);if(a&&(!i||i.source!==e.sourceId)){throw new u("CONFLICT",`${e.target} appeared while installing; left alone.`)}const s=H();const l=B.join(x(this.options.dataDir),"staging",s);const c=B.join(x(this.options.dataDir),"trash",s);try{await Jt(l,e.files);if(a)ie(e.target,c);try{ie(l,e.target)}catch(p){if(a)ie(c,e.target);throw p}}catch(p){se(l);if(p instanceof u)throw p;throw new u("INSTALL_FAILED",`Could not install ${e.entry.name}: ${p instanceof Error?p.message:String(p)}`,{cause:p})}se(c);const d={source:e.sourceId,version:e.entry.version,contentDigest:e.contentDigest,installedAt:this.now().toISOString()};await this.ledgerFile.record(e.entry.kind,e.entry.name,d);return d})}async remove(e,r){return U(this.options.dataDir,async()=>{const n=await this.ledgerFile.read();const o=(e==="plugin"?n.plugins:n.skills)[r];if(!o){throw new u("NOT_FOUND",`"${r}" was not installed by the Store, so the Store will not delete it.`)}const i=this.installDirectory(e,r);const a=await j(i);if(a)se(i);await this.ledgerFile.forget(e,r);return a})}async forget(e,r){await U(this.options.dataDir,async()=>{await this.ledgerFile.forget(e,r)})}};async function Jt(t,e){await Ze(t,{recursive:true});const r=B.resolve(t);for(const n of e){const o=B.resolve(r,...n.path.split("/"));if(!o.startsWith(`${r}${B.sep}`)){throw new u("ARCHIVE_INVALID",`${n.path} would be written outside the package.`)}await Ze(B.dirname(o),{recursive:true});await Zt(o,n.content,{flag:"wx",mode:420})}}import en from"node:path";function de(t,e){let r;try{r=JSON.parse(t)}catch(l){throw g("",`is not JSON (${l instanceof Error?l.message:String(l)})`)}const n=Z(r,"");if(n.schema!==Q){throw g("schema",`must be "${Q}"`)}const o=K(n.plugins??[],"plugins").map((l,c)=>Yt(l,`plugins[${c}]`,e));const i=K(n.skills??[],"skills").map((l,c)=>qt(l,`skills[${c}]`,e));if(o.length+i.length>O.entries){throw g("",`holds more than ${O.entries} entries`)}Je(o.map(l=>l.name),"plugins");Je(i.map(l=>l.name),"skills");const a=v(n.description,"description",2e3);const s=v(n.updatedAt,"updatedAt",64);return{schema:Q,name:S(n.name,"name",80),...a?{description:a}:{},...s?{updatedAt:s}:{},plugins:o,skills:i}}function Yt(t,e,r){const n=Z(t,e);const o=S(n.name,`${e}.name`,80);if(!te.test(o))throw g(`${e}.name`,"is not a Plugin name");const i=S(n.category,`${e}.category`,64);if(!ye.includes(i)){throw g(`${e}.category`,`must be one of ${ye.join(", ")}`)}const a=v(n.license,`${e}.license`,128);const s=Qt(n.homepage,`${e}.homepage`);return{kind:"plugin",name:o,displayName:v(n.displayName,`${e}.displayName`,200)??o,version:Xe(n.version,`${e}.version`),description:S(n.description,`${e}.description`,2e3),author:S(n.author,`${e}.author`,200),category:i,...a?{license:a}:{},...s?{homepage:s}:{},exampleQueries:K(n.exampleQueries??[],`${e}.exampleQueries`).slice(0,3).map((l,c)=>S(l,`${e}.exampleQueries[${c}]`,500)),contents:Xt(n.contents,`${e}.contents`),archive:Ye(n.archive,`${e}.archive`,r)}}function Xt(t,e){const r=Z(t,e);return{skills:K(r.skills??[],`${e}.skills`).map((n,o)=>{const i=Z(n,`${e}.skills[${o}]`);const a=v(i.description,`${e}.skills[${o}].description`,4e3);return{name:S(i.name,`${e}.skills[${o}].name`,80),...a?{description:a}:{}}}),mcpServers:K(r.mcpServers??[],`${e}.mcpServers`).map((n,o)=>S(n,`${e}.mcpServers[${o}]`,80)),apps:K(r.apps??[],`${e}.apps`).map((n,o)=>S(n,`${e}.apps[${o}]`,80)),hooks:ke(r.hooks??0,`${e}.hooks`,0,64)}}function qt(t,e,r){const n=Z(t,e);const o=S(n.name,`${e}.name`,64);if(!ne.test(o))throw g(`${e}.name`,"is not a Skill name");const i=v(n.author,`${e}.author`,200);const a=v(n.license,`${e}.license`,128);return{kind:"skill",name:o,title:v(n.title,`${e}.title`,200)??o,version:Xe(n.version,`${e}.version`),description:S(n.description,`${e}.description`,4e3),group:S(n.group,`${e}.group`,80),...i?{author:i}:{},...a?{license:a}:{},files:ke(n.files,`${e}.files`,1,L.files),archive:Ye(n.archive,`${e}.archive`,r)}}function Ye(t,e,r){const n=Z(t,e);const o=S(n.url,`${e}.url`,2048);let i;try{i=new URL(o,r)}catch{throw g(`${e}.url`,"is not a URL")}const a=/^https?:$/u.test(new URL(r).protocol);if(i.protocol!=="https:"&&i.protocol!=="http:"&&i.protocol!=="file:"){throw g(`${e}.url`,"must be an https or file URL")}if(a&&i.protocol==="file:"){throw g(`${e}.url`,"must not be a file URL in an index that was fetched")}const s=i.toString();const l=S(n.archiveSha256,`${e}.archiveSha256`,64);if(!Oe.test(l)){throw g(`${e}.archiveSha256`,"must be 64 lowercase hex digits")}const c=S(n.contentDigest,`${e}.contentDigest`,80);if(!Pe.test(c)){throw g(`${e}.contentDigest`,"must be sha256-tree-v1:<64 lowercase hex digits>")}return{url:s,size:ke(n.size,`${e}.size`,22,L.archiveBytes),archiveSha256:l,contentDigest:c}}function Xe(t,e){const r=S(t,e,128);if(!re.test(r))throw g(e,"must be a SemVer version");return r}function Z(t,e){if(typeof t!=="object"||t===null||Array.isArray(t)){throw g(e,"must be an object")}return t}function K(t,e){if(!Array.isArray(t))throw g(e,"must be an array");return t}function S(t,e,r){if(typeof t!=="string")throw g(e,"must be a string");const n=T(t);if(!n)throw g(e,"must not be empty");if(n.length>r)throw g(e,`must be at most ${r} characters`);return n}function v(t,e,r){return t===void 0?void 0:S(t,e,r)}function Qt(t,e){if(t===void 0)return void 0;const r=S(t,e,2048);let n;try{n=new URL(r)}catch{throw g(e,"is not a URL")}if(n.protocol!=="https:")throw g(e,"must be an https URL");return n.toString()}function ke(t,e,r,n){if(typeof t!=="number"||!Number.isInteger(t)||t<r||t>n){throw g(e,`must be an integer from ${r} to ${n}`)}return t}function Je(t,e){const r=new Set;for(const n of t){if(r.has(n))throw g(e,`lists "${n}" twice`);r.add(n)}}function g(t,e){return new u("INDEX_INVALID",`Store index ${t?`field ${t} `:""}${e}.`)}var ue=class{constructor(e){this.options=e;this.now=e.now??Date.now;this.freshForMs=e.freshForMs??O.freshForMs}options;now;freshForMs;async load(e,r={}){const n=e.url.startsWith("file:");const o=n?void 0:await this.readCache(e);if(o&&!r.refresh&&this.now()-o.fetchedAtMs<this.freshForMs){const i=qe(o.text,e.url);if(i)return{source:e,index:i,stale:false,fetchedAtMs:o.fetchedAtMs}}try{const i=await this.options.transport.readText(e.url,{maxBytes:O.indexBytes,...o?.etag?{etag:o.etag}:{},...r.signal?{signal:r.signal}:{}});const a=this.now();if(i.status==="not-modified"&&o){const l=de(o.text,e.url);await this.writeCache(e,{...o,fetchedAtMs:a});return{source:e,index:l,stale:false,fetchedAtMs:a}}if(i.status!=="ok"){throw new u("SOURCE_UNREACHABLE",`${e.url} answered 304 with nothing cached.`)}const s=de(i.text,e.url);if(!n){await this.writeCache(e,{url:e.url,fetchedAtMs:a,...i.etag?{etag:i.etag}:{},text:i.text})}return{source:e,index:s,stale:false,fetchedAtMs:a}}catch(i){if(r.signal?.aborted)throw i;const a=i instanceof Error?i.message:String(i);const s=o?qe(o.text,e.url):void 0;if(o&&s){return{source:e,index:s,stale:true,fetchedAtMs:o.fetchedAtMs,error:a}}return{source:e,stale:false,error:a}}}cacheFile(e){return en.join(x(this.options.dataDir),"cache",`${e.id}.json`)}async readCache(e){const r=await P(this.cacheFile(e));if(r===void 0)return void 0;try{const n=JSON.parse(r);if(n.url===e.url&&typeof n.text==="string"&&typeof n.fetchedAtMs==="number"){return{url:n.url,fetchedAtMs:n.fetchedAtMs,text:n.text,...typeof n.etag==="string"?{etag:n.etag}:{}}}}catch{}return void 0}async writeCache(e,r){try{await V(this.cacheFile(e),JSON.stringify(r))}catch{}}};function qe(t,e){try{return de(t,e)}catch{return void 0}}import Le from"node:path";import{pathToFileURL as sn}from"node:url";import{open as tn,stat as nn}from"node:fs/promises";import{fileURLToPath as rn}from"node:url";function rt(t={}){const e=t.fetch??fetch;const r=t.timeoutMs??O.fetchTimeoutMs;return{async readText(n,o){if(Qe(n)){return{status:"ok",text:(await et(n,o.maxBytes)).toString("utf8")}}const i=await tt(e,n,r,o.signal,{...o.etag?{"if-none-match":o.etag}:{},accept:"application/json"});if(i.status===304)return{status:"not-modified"};const a=await nt(i,o.maxBytes,n);const s=i.headers.get("etag")??void 0;return{status:"ok",text:a.toString("utf8"),...s?{etag:s}:{}}},async readBytes(n,o){if(Qe(n))return et(n,o.maxBytes);const i=await tt(e,n,r,o.signal,{accept:"application/octet-stream"});return nt(i,o.maxBytes,n)}}}function fe(t){let e;try{e=new URL(t)}catch{throw new u("SOURCE_INVALID",`"${t}" is not a URL.`)}if(e.protocol==="https:"||e.protocol==="file:")return e;if(e.protocol==="http:"&&on(e.hostname))return e;throw new u("SOURCE_INVALID",`"${t}" must use https (plain http is only allowed for localhost).`)}function on(t){const e=t.replace(/^\[|\]$/gu,"").toLowerCase();return e==="localhost"||e==="::1"||/^127(?:\.\d{1,3}){3}$/u.test(e)}function Qe(t){return t.startsWith("file:")}async function et(t,e){let r;try{r=rn(t)}catch(n){throw new u("SOURCE_UNREACHABLE",`"${t}" is not a usable file URL.`,{cause:n})}try{const n=await nn(r);if(!n.isFile())throw new u("SOURCE_UNREACHABLE",`${r} is not a file.`);if(n.size>e)throw xe(t,e);const o=await tn(r,"r");try{return await o.readFile()}finally{await o.close()}}catch(n){if(n instanceof u)throw n;throw new u("SOURCE_UNREACHABLE",`Could not read ${r}: ${_e(n)}`,{cause:n})}}async function tt(t,e,r,n,o){fe(e);const i=AbortSignal.timeout(r);let a;try{a=await t(e,{headers:o,redirect:"follow",signal:n?AbortSignal.any([n,i]):i})}catch(s){if(n?.aborted)throw s;throw new u("SOURCE_UNREACHABLE",`${e} could not be reached (${i.aborted?"timed out":_e(s)}).`,{cause:s})}if(a.url&&a.url!==e){try{fe(a.url)}catch{throw new u("SOURCE_UNREACHABLE",`${e} redirected to a URL that is not allowed.`)}}if(a.status!==304&&!a.ok){throw new u("SOURCE_UNREACHABLE",`${e} answered ${a.status}${a.statusText?` ${a.statusText}`:""}.`)}return a}async function nt(t,e,r){const n=Number(t.headers.get("content-length"));if(Number.isFinite(n)&&n>e)throw xe(r,e);if(!t.body)return Buffer.alloc(0);const o=[];let i=0;const a=t.body.getReader();try{for(;;){const{done:s,value:l}=await a.read();if(s)break;i+=l.length;if(i>e){await a.cancel();throw xe(r,e)}o.push(Buffer.from(l))}}catch(s){if(s instanceof u)throw s;throw new u("SOURCE_UNREACHABLE",`${r} broke off (${_e(s)}).`,{cause:s})}return Buffer.concat(o,i)}function xe(t,e){return new u("SOURCE_UNREACHABLE",`${t} is larger than ${e} bytes.`)}function _e(t){if(t instanceof Error){const e=t.cause instanceof Error?` (${t.cause.message})`:"";return`${t.message}${e}`}return String(t)}var pe=class{constructor(e,r=process.env){this.dataDir=e;this.environment=r}dataDir;environment;async list(){const e=this.environment[he]?.trim();const r=e?.toLowerCase()===ge?void 0:e||Ne;const n=r?[{id:F,url:Re(r),label:"Alran store",builtin:true}]:[];return[...n,...await this.readAdded()]}async add(e){const r=Re(e.url);return U(this.dataDir,async()=>{const n=await this.readAdded();const o=[{id:F},...n];const i=n.find(c=>c.url===r);if(i){throw new u("SOURCE_EXISTS",`That store is already added as "${i.id}".`)}const a=e.id?.trim()||an(r,new Set(o.map(c=>c.id)));if(!Se.test(a)||a.length>40){throw new u("SOURCE_INVALID",`"${a}" is not a store name: use lowercase letters, digits and dashes, starting with a letter.`)}if(o.some(c=>c.id===a)){throw new u("SOURCE_EXISTS",`A store named "${a}" already exists.`)}const s=e.label?.trim();const l={id:a,url:r,...s?{label:s}:{}};await this.writeAdded([...n,l]);return l})}async remove(e){if(e===F){throw new u("SOURCE_INVALID",`"${F}" is the default store; set ${he}=${ge} to drop it.`)}return U(this.dataDir,async()=>{const r=await this.readAdded();const n=r.find(o=>o.id===e);if(!n)throw new u("SOURCE_NOT_FOUND",`No store named "${e}".`);await this.writeAdded(r.filter(o=>o.id!==e));return n})}file(){return Le.join(x(this.dataDir),"sources.json")}async readAdded(){const e=await P(this.file());if(e===void 0)return[];let r;try{r=JSON.parse(e)}catch(i){throw new u("SOURCE_INVALID",`${this.file()} is not valid JSON.`,{cause:i})}const n=typeof r==="object"&&r!==null&&"sources"in r?r.sources:void 0;if(!Array.isArray(n)){throw new u("SOURCE_INVALID",`${this.file()} has no "sources" list.`)}const o=[];for(const i of n){if(typeof i!=="object"||i===null)continue;const{id:a,url:s,label:l}=i;if(typeof a!=="string"||typeof s!=="string")continue;if(!Se.test(a)||a===F)continue;o.push({id:a,url:Re(s),...typeof l==="string"&&l.trim()?{label:l.trim()}:{}})}return o}async writeAdded(e){await V(this.file(),`${JSON.stringify({schema:be,sources:e},null,2)}
4
+ `)}};function Re(t){const e=t.trim();if(!e)throw new u("SOURCE_INVALID","A store location is empty.");const r=/^[A-Za-z]:[\\/]/u.test(e);const n=e.startsWith("/")||r?sn(e):fe(e);if(!n.pathname.endsWith(".json")){n.pathname=`${n.pathname.replace(/\/+$/u,"")}/index.json`}n.hash="";return n.toString()}function an(t,e){const r=new URL(t);const n=r.protocol==="file:"?Le.basename(Le.dirname(decodeURIComponent(r.pathname))):`${r.hostname}${r.pathname.replace(/\/index\.json$/u,"")}`;let o=n.toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"").slice(0,32);if(!/^[a-z]/u.test(o))o=`store-${o}`.replace(/-+$/u,"");if(!e.has(o))return o;for(let i=2;;i+=1){const a=`${o}-${i}`;if(!e.has(a))return a}}var Te="built-in";function me(t){return t.origin===Te}var ot=class{constructor(e){this.options=e;const r=e.transport??rt();this.environment=e.environment??process.env;this.sources=new pe(e.dataDir,this.environment);this.loader=new ue({dataDir:e.dataDir,transport:r,...e.now?{now:e.now}:{},...e.freshForMs!==void 0?{freshForMs:e.freshForMs}:{}});this.installer=new ce({dataDir:e.dataDir,transport:r});this.plugins=e.plugins;this.bundledSkills=e.bundledSkills??(async()=>{const n=Be(__alran_tuiPackageEntryUrl);return n?Fe(n):[]})}options;sources;loader;installer;plugins;environment;bundledSkills;bundledSkillsCache;async catalog(e={}){const r=e.offline?[]:await this.sources.list();const[n,o,i,a]=await Promise.all([Promise.all(r.map(d=>this.loader.load(d,e))),this.installer.ledger(),this.readInstalledPlugins(),this.readOfficialPlugins()]);const s=[];const l=new Map(i.filter(d=>d.marketplace==="local").map(d=>[d.name,d]));const c=new Set((await this.readBundledSkills()).map(d=>d.name));for(const d of n){if(!d.index)continue;for(const p of[...d.index.plugins,...d.index.skills]){s.push(await this.itemFor(p,d.source,o,l,c))}}s.push(...this.itemsWithoutEntry(s,o,i,a));s.push(...await this.orphanedSkills(s,o));s.push(...await this.builtInItems());return{items:s,sources:n}}resolve(e,r,n){const o=n.lastIndexOf("@");const i=o>0?n.slice(0,o):n;const a=o>0?n.slice(o+1):void 0;const s=e.items.filter(c=>c.kind===r&&c.name===i&&(!a||c.origin===a));if(s.length===0){throw new u("NOT_FOUND",`No ${r} named "${n}". Try: alran ${r==="plugin"?"plugin":"skills"} search`)}const l=s.filter(c=>c.installed);if(s.length>1&&l.length===1)return l[0];if(s.length>1){throw new u("AMBIGUOUS",`"${i}" exists in several places (${s.map(c=>`${i}@${c.origin}`).join(", ")}); name one of them.`)}return s[0]}stage(e,r={}){if(!e.entry){throw new u("NOT_FOUND",`${e.name} has no store entry to install from.`)}if(e.conflict==="built-in"){throw new u("CONFLICT",`A Skill named "${e.name}" is built in to Alran Code; installing this one would replace it, so the Store does not.`)}if(e.conflict){throw new u("CONFLICT",`A ${e.kind} named "${e.name}" is already installed outside the Store; the Store leaves it alone.`)}return this.installer.stage(e.entry,e.origin,r)}async commit(e,r){const n=await this.installer.commit(e,r);const o=[];if(e.entry.kind==="plugin")await this.reloadPlugins(o);return{record:n,warnings:o}}async remove(e){if(me(e)){throw new u("INSTALL_FAILED",`${e.name} is built in to Alran Code and cannot be removed.`)}const r=[];if(e.kind==="skill"){await this.installer.remove("skill",e.name);return r}if(e.origin==="official"||e.origin==="local"){await this.requirePlugins().mutatePlugin({action:"remove",plugin:{name:e.name,marketplace:e.origin}});return r}await this.plugins?.mutatePlugin({action:"remove",plugin:{name:e.name,marketplace:"local"}}).catch(()=>void 0);await this.installer.remove("plugin",e.name);await this.reloadPlugins(r);return r}async setEnabled(e,r){if(e.kind!=="plugin"){throw new u("INSTALL_FAILED","Only Plugins can be switched on and off.")}const n=e.origin==="official"?"official":"local";await this.requirePlugins().mutatePlugin({action:r?"enable":"disable",plugin:{name:e.name,marketplace:n}})}async installOfficial(e){await this.requirePlugins().mutatePlugin({action:"install",plugin:{name:e.name,marketplace:"official"}})}async refreshRuntime(){await this.plugins?.refreshPlugins()}requirePlugins(){if(!this.plugins)throw new u("INSTALL_FAILED","Plugin management is unavailable.");return this.plugins}async reloadPlugins(e){try{await this.plugins?.refreshPlugins()}catch(r){e.push(`The Plugin is in place but Alran could not reload Plugins (${r instanceof Error?r.message:String(r)}). Restart Alran or run /reload.`)}}async readInstalledPlugins(){if(!this.plugins)return[];return this.plugins.listInstalledPlugins().catch(()=>[])}async readOfficialPlugins(){if(!this.plugins||!this.environment.ALRAN_PLUGIN_REGISTRY_URL?.trim())return[];return this.plugins.listMarketplacePlugins({marketplace:"official"}).catch(()=>[])}async itemFor(e,r,n,o,i){const a=e.kind==="plugin"?n.plugins:n.skills;const s=a[e.name];const l=s?.source===r.id?s:void 0;const c=e.kind==="plugin"?o.get(e.name):void 0;const d=this.installer.installDirectory(e.kind,e.name);const p=c!==void 0||await j(d);const h=e.kind==="skill"&&i.has(e.name)?"built-in":p&&!s?"local":void 0;const D=l!==void 0&&p;const I={id:`${e.kind}:${e.name}@${r.id}`,kind:e.kind,name:e.name,origin:r.id,version:e.version,installed:D,enabled:D&&(e.kind==="skill"||(c?c.enabled:this.plugins===void 0)),updateAvailable:D&&l!==void 0&&(l.version!==e.version||l.contentDigest!==e.archive.contentDigest),...l?{installedVersion:l.version}:{},...h?{conflict:h}:{},entry:e,...c?{plugin:c}:{}};if(e.kind==="plugin"){return{...I,displayName:e.displayName,description:e.description,author:e.author,group:e.category,...e.license?{license:e.license}:{},summary:cn(e)}}return{...I,displayName:e.title,description:e.description,...e.author?{author:e.author}:{},group:e.group,...e.license?{license:e.license}:{},summary:`${e.files} ${e.files===1?"file":"files"}`}}itemsWithoutEntry(e,r,n,o){const i=new Set(e.filter(s=>s.kind==="plugin").map(s=>s.name));const a=[];for(const s of[...n,...o]){if(s.marketplace==="local"&&i.has(s.name))continue;const l=s.marketplace==="local"?r.plugins[s.name]:void 0;const c=l?l.source:s.marketplace;const d=`plugin:${s.name}@${c}`;if(a.some(p=>p.id===d))continue;a.push({id:d,kind:"plugin",name:s.name,displayName:s.displayName,description:s.description??"",...s.author?{author:s.author}:{},...s.version?{version:s.version,installedVersion:s.version}:{},origin:c,installed:s.installed,enabled:s.enabled,updateAvailable:false,summary:dn(s),plugin:s})}return a}readBundledSkills(){this.bundledSkillsCache??=this.bundledSkills().catch(()=>[]);return this.bundledSkillsCache}async builtInItems(){return(await this.readBundledSkills()).map(e=>({id:`skill:${e.name}@${Te}`,kind:"skill",name:e.name,displayName:e.name,description:e.description,group:"Built in",origin:Te,installed:true,enabled:true,updateAvailable:false,summary:""}))}async orphanedSkills(e,r){const n=new Set(e.filter(i=>i.kind==="skill").map(i=>i.name));const o=[];for(const[i,a]of Object.entries(r.skills)){if(n.has(i))continue;const s=this.installer.installDirectory("skill",i);const l=await P(ln.join(s,"SKILL.md"));if(l===void 0)continue;let c="";try{c=G(l,"SKILL.md").description}catch{}o.push({id:`skill:${i}@${a.source}`,kind:"skill",name:i,displayName:i,description:c,version:a.version,installedVersion:a.version,origin:a.source,installed:true,enabled:true,updateAvailable:false,summary:"installed"})}return o}};function cn(t){const e=[];const{skills:r,mcpServers:n,apps:o,hooks:i}=t.contents;if(r.length)e.push(`${r.length} ${r.length===1?"skill":"skills"}`);if(n.length)e.push(`${n.length} MCP`);if(o.length)e.push(`${o.length} ${o.length===1?"app":"apps"}`);if(i)e.push(`${i} ${i===1?"hook":"hooks"}`);return e.join(" \xB7 ")||"empty"}function dn(t){const{appCount:e,mcpServerCount:r,skillCount:n,agentCount:o}=t.capabilities;const i=[];if(n)i.push(`${n} ${n===1?"skill":"skills"}`);if(r)i.push(`${r} MCP`);if(e)i.push(`${e} ${e===1?"app":"apps"}`);if(o)i.push(`${o} subagents`);return i.join(" \xB7 ")||"empty"}function un(t){if(t.conflict)return"[!]";if(!t.installed)return"[ ]";return t.enabled?"[*]":"[-]"}function st(t){if(me(t))return"built in";if(t.conflict==="built-in")return"same name as a built-in skill";if(t.conflict)return"installed outside the Store";if(!t.installed)return"available";if(t.updateAvailable)return`update available (${t.installedVersion??"?"} \u2192 ${t.version??"?"})`;if(t.kind==="plugin"&&!t.enabled)return"installed, disabled";return"installed"}function at(t){return t.origin==="ottili"||me(t)?t.name:`${t.name}@${t.origin}`}function fn(t,e,r=""){const n=Math.max(20,e-r.length);const o=[];let i="";for(const a of t.split(/\s+/u).filter(Boolean)){if(i&&i.length+1+a.length>n){o.push(`${r}${i}`);i=a}else{i=i?`${i} ${a}`:a}}if(i)o.push(`${r}${i}`);return o}function it(t,e){if(e<=1)return t.slice(0,Math.max(0,e));return t.length<=e?t:`${t.slice(0,e-1)}\u2026`}function $r(t,e=100){if(t.length===0)return"";const r=t.map(at);const n=Math.min(34,Math.max(...r.map(i=>i.length)));const o=Math.max(...t.map(i=>(i.version??"").length),5);return t.map((i,a)=>{const s=`${un(i)} ${it(r[a]??"",n).padEnd(n)} ${(i.version??"").padEnd(o)} `;const l=i.installed||i.conflict?` ${st(i)}`:"";const c=Math.max(10,e-s.length-l.length);return`${s}${it(i.description,c)}${l}`}).join("\n")}function kr(t,e,r=100){const n=[`${t.displayName} (${at(t)})`,` ${st(t)}${t.version?` \xB7 version ${t.version}`:""}`,"",...fn(t.description,r," "),""];const o=[["Kind",t.kind==="plugin"?"Plugin":"Skill"],["From",t.origin],["Author",t.author],[t.kind==="plugin"?"Category":"Group",t.group],["License",t.license],["Contains",t.summary]];for(const[a,s]of o)if(s)n.push(` ${`${a}:`.padEnd(10)}${s}`);const i=t.entry;if(i?.kind==="plugin"){if(i.homepage)n.push(` ${"Homepage:".padEnd(10)}${i.homepage}`);if(i.contents.skills.length>0){n.push(""," Skills:");for(const a of i.contents.skills)n.push(` ${a.name}`)}if(i.exampleQueries.length>0){n.push(""," Try:");for(const a of i.exampleQueries)n.push(` \u201C${a}\u201D`)}}if(e&&e.executes.length>0){n.push("",...pn(e.executes.map(a=>a.line)).split("\n"))}return n.join("\n")}function pn(t){return[" This package will run commands or connect to services:",...t.map(e=>` \u2022 ${e}`)].join("\n")}var Y=(t,e,r)=>{const n=t.toLowerCase();if(n===e)return r*4;if(n.startsWith(e))return r*3;if(n.includes(e))return r*2;return 0};function xr(t,e){const r=e.toLowerCase().split(/\s+/u).filter(Boolean);if(r.length===0)return[...t];const n=[];t.forEach((o,i)=>{let a=0;for(const s of r){const l=Y(o.name,s,50)+Y(o.displayName,s,30)+Y(o.group??"",s,10)+Y(o.author??"",s,5)+Y(o.description,s,1);if(l===0)return;a+=l}n.push({item:o,points:a,index:i})});return n.sort((o,i)=>i.points-o.points||o.index-i.index).map(({item:o})=>o)}export{u as a,C as b,me as c,ot as d,un as e,at as f,$r as g,kr as h,pn as i,xr as j};