hive-skills 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (238) hide show
  1. package/LICENSE +28 -0
  2. package/README.md +235 -0
  3. package/assets/LICENSE +32 -0
  4. package/assets/THIRD_PARTY_NOTICES.md +72 -0
  5. package/assets/manifest.json +1290 -0
  6. package/assets/skills/authored/code-review/composable/BUNDLE.md +192 -0
  7. package/assets/skills/authored/code-review/composable/INDEX.md +13 -0
  8. package/assets/skills/authored/code-review/composable/VERSION +1 -0
  9. package/assets/skills/authored/code-review/composable/mini/01-review-method.md +34 -0
  10. package/assets/skills/authored/code-review/composable/mini/02-security-review.md +20 -0
  11. package/assets/skills/authored/code-review/composable/mini/03-correctness-bugs.md +19 -0
  12. package/assets/skills/authored/code-review/composable/mini/04-concurrency.md +16 -0
  13. package/assets/skills/authored/code-review/composable/mini/05-error-handling.md +12 -0
  14. package/assets/skills/authored/code-review/composable/mini/06-performance.md +11 -0
  15. package/assets/skills/authored/code-review/composable/mini/07-api-design.md +20 -0
  16. package/assets/skills/authored/code-review/composable/mini/08-missing-tests.md +25 -0
  17. package/assets/skills/authored/code-review/composable/mini/09-refactoring-and-communication.md +32 -0
  18. package/assets/skills/authored/data-analysis/composable/BUNDLE.md +186 -0
  19. package/assets/skills/authored/data-analysis/composable/INDEX.md +13 -0
  20. package/assets/skills/authored/data-analysis/composable/VERSION +1 -0
  21. package/assets/skills/authored/data-analysis/composable/mini/01-data-quality-profiling.md +26 -0
  22. package/assets/skills/authored/data-analysis/composable/mini/02-aggregation-pitfalls.md +21 -0
  23. package/assets/skills/authored/data-analysis/composable/mini/03-time-series.md +19 -0
  24. package/assets/skills/authored/data-analysis/composable/mini/04-segmentation.md +23 -0
  25. package/assets/skills/authored/data-analysis/composable/mini/05-discount-pricing.md +17 -0
  26. package/assets/skills/authored/data-analysis/composable/mini/06-insight-generation.md +25 -0
  27. package/assets/skills/authored/data-analysis/composable/mini/07-executive-writing.md +26 -0
  28. package/assets/skills/authored/data-analysis/composable/mini/08-recommendations.md +20 -0
  29. package/assets/skills/authored/data-analysis/composable/mini/09-reproducibility-assumptions.md +20 -0
  30. package/assets/skills/authored/financial-analysis/composable/BUNDLE.md +1293 -0
  31. package/assets/skills/authored/financial-analysis/composable/INDEX.md +17 -0
  32. package/assets/skills/authored/financial-analysis/composable/VERSION +1 -0
  33. package/assets/skills/authored/financial-analysis/composable/mini/00-core.md +69 -0
  34. package/assets/skills/authored/financial-analysis/composable/mini/01-profitability-efficiency-ratios.md +173 -0
  35. package/assets/skills/authored/financial-analysis/composable/mini/02-liquidity-leverage-ratios.md +120 -0
  36. package/assets/skills/authored/financial-analysis/composable/mini/03-valuation-ratios-interpretation.md +107 -0
  37. package/assets/skills/authored/financial-analysis/composable/mini/04-dcf-projection-wacc.md +122 -0
  38. package/assets/skills/authored/financial-analysis/composable/mini/05-dcf-terminal-value-sensitivity.md +75 -0
  39. package/assets/skills/authored/financial-analysis/composable/mini/06-comparables-precedents.md +78 -0
  40. package/assets/skills/authored/financial-analysis/composable/mini/07-budget-variance-analysis.md +47 -0
  41. package/assets/skills/authored/financial-analysis/composable/mini/08-driver-based-forecasting-scenarios.md +111 -0
  42. package/assets/skills/authored/financial-analysis/composable/mini/09-rolling-forecasts-accuracy.md +114 -0
  43. package/assets/skills/authored/financial-analysis/composable/mini/10-reporting-exec-summary.md +58 -0
  44. package/assets/skills/authored/financial-analysis/composable/mini/11-industry-adaptations.md +130 -0
  45. package/assets/skills/authored/financial-analysis/composable/mini/12-toolkit-scripts-io.md +102 -0
  46. package/assets/skills/authored/python-api/composable/BUNDLE.md +389 -0
  47. package/assets/skills/authored/python-api/composable/INDEX.md +13 -0
  48. package/assets/skills/authored/python-api/composable/VERSION +1 -0
  49. package/assets/skills/authored/python-api/composable/mini/01-project-structure.md +44 -0
  50. package/assets/skills/authored/python-api/composable/mini/02-routing-and-app.md +38 -0
  51. package/assets/skills/authored/python-api/composable/mini/03-pydantic-models.md +45 -0
  52. package/assets/skills/authored/python-api/composable/mini/04-validation-and-errors.md +59 -0
  53. package/assets/skills/authored/python-api/composable/mini/05-dependencies-and-auth.md +60 -0
  54. package/assets/skills/authored/python-api/composable/mini/06-pagination-filtering.md +44 -0
  55. package/assets/skills/authored/python-api/composable/mini/07-async-performance.md +30 -0
  56. package/assets/skills/authored/python-api/composable/mini/08-testing.md +45 -0
  57. package/assets/skills/authored/python-api/composable/mini/09-middleware-observability.md +29 -0
  58. package/assets/skills/authored/tech-writing/composable/BUNDLE.md +220 -0
  59. package/assets/skills/authored/tech-writing/composable/INDEX.md +12 -0
  60. package/assets/skills/authored/tech-writing/composable/VERSION +1 -0
  61. package/assets/skills/authored/tech-writing/composable/mini/01-audience-analysis.md +26 -0
  62. package/assets/skills/authored/tech-writing/composable/mini/02-document-types.md +27 -0
  63. package/assets/skills/authored/tech-writing/composable/mini/03-readme-quickstart-changelog.md +22 -0
  64. package/assets/skills/authored/tech-writing/composable/mini/04-information-architecture.md +21 -0
  65. package/assets/skills/authored/tech-writing/composable/mini/05-style-clarity.md +29 -0
  66. package/assets/skills/authored/tech-writing/composable/mini/06-breaking-changes-migrations.md +33 -0
  67. package/assets/skills/authored/tech-writing/composable/mini/07-troubleshooting-security.md +30 -0
  68. package/assets/skills/authored/tech-writing/composable/mini/08-faq-voice-tone.md +32 -0
  69. package/assets/skills/converted/claude-api/composable/BUNDLE.md +14996 -0
  70. package/assets/skills/converted/claude-api/composable/INDEX.md +98 -0
  71. package/assets/skills/converted/claude-api/composable/VERSION +1 -0
  72. package/assets/skills/converted/claude-api/composable/mini/00-core.md +235 -0
  73. package/assets/skills/converted/claude-api/composable/mini/01-model-api-quick-reference.md +258 -0
  74. package/assets/skills/converted/claude-api/composable/mini/02-common-pitfalls.md +42 -0
  75. package/assets/skills/converted/claude-api/composable/mini/10-models.md +135 -0
  76. package/assets/skills/converted/claude-api/composable/mini/11-platform-availability.md +96 -0
  77. package/assets/skills/converted/claude-api/composable/mini/12-claude-platform-on-aws.md +59 -0
  78. package/assets/skills/converted/claude-api/composable/mini/13-live-sources.md +143 -0
  79. package/assets/skills/converted/claude-api/composable/mini/14-error-codes.md +256 -0
  80. package/assets/skills/converted/claude-api/composable/mini/15-prompt-caching.md +223 -0
  81. package/assets/skills/converted/claude-api/composable/mini/16-token-counting.md +56 -0
  82. package/assets/skills/converted/claude-api/composable/mini/17-tool-use-concepts.md +444 -0
  83. package/assets/skills/converted/claude-api/composable/mini/18-agent-design.md +101 -0
  84. package/assets/skills/converted/claude-api/composable/mini/19-anthropic-cli.md +246 -0
  85. package/assets/skills/converted/claude-api/composable/mini/20-model-migration.md +1301 -0
  86. package/assets/skills/converted/claude-api/composable/mini/30-managed-agents-overview.md +71 -0
  87. package/assets/skills/converted/claude-api/composable/mini/31-managed-agents-core.md +278 -0
  88. package/assets/skills/converted/claude-api/composable/mini/32-managed-agents-environments.md +219 -0
  89. package/assets/skills/converted/claude-api/composable/mini/33-managed-agents-tools.md +366 -0
  90. package/assets/skills/converted/claude-api/composable/mini/34-managed-agents-events.md +252 -0
  91. package/assets/skills/converted/claude-api/composable/mini/35-managed-agents-outcomes.md +106 -0
  92. package/assets/skills/converted/claude-api/composable/mini/36-managed-agents-multiagent.md +101 -0
  93. package/assets/skills/converted/claude-api/composable/mini/37-managed-agents-webhooks.md +123 -0
  94. package/assets/skills/converted/claude-api/composable/mini/38-managed-agents-memory.md +197 -0
  95. package/assets/skills/converted/claude-api/composable/mini/39-managed-agents-scheduled-deployments.md +146 -0
  96. package/assets/skills/converted/claude-api/composable/mini/40-managed-agents-client-patterns.md +211 -0
  97. package/assets/skills/converted/claude-api/composable/mini/41-managed-agents-onboarding.md +82 -0
  98. package/assets/skills/converted/claude-api/composable/mini/42-managed-agents-api-reference.md +441 -0
  99. package/assets/skills/converted/claude-api/composable/mini/43-managed-agents-self-hosted-sandboxes.md +174 -0
  100. package/assets/skills/converted/claude-api/composable/mini/50-python-readme.md +564 -0
  101. package/assets/skills/converted/claude-api/composable/mini/51-python-tool-use.md +590 -0
  102. package/assets/skills/converted/claude-api/composable/mini/52-python-streaming-batches-files.md +549 -0
  103. package/assets/skills/converted/claude-api/composable/mini/53-python-managed-agents.md +335 -0
  104. package/assets/skills/converted/claude-api/composable/mini/55-typescript-readme.md +404 -0
  105. package/assets/skills/converted/claude-api/composable/mini/56-typescript-tool-use.md +548 -0
  106. package/assets/skills/converted/claude-api/composable/mini/57-typescript-streaming-batches-files.md +384 -0
  107. package/assets/skills/converted/claude-api/composable/mini/58-typescript-managed-agents.md +358 -0
  108. package/assets/skills/converted/claude-api/composable/mini/60-csharp-readme.md +361 -0
  109. package/assets/skills/converted/claude-api/composable/mini/61-csharp-tool-use.md +163 -0
  110. package/assets/skills/converted/claude-api/composable/mini/62-csharp-streaming-batches-files.md +64 -0
  111. package/assets/skills/converted/claude-api/composable/mini/65-go-readme.md +185 -0
  112. package/assets/skills/converted/claude-api/composable/mini/66-go-tool-use.md +219 -0
  113. package/assets/skills/converted/claude-api/composable/mini/67-go-streaming-files.md +63 -0
  114. package/assets/skills/converted/claude-api/composable/mini/68-go-managed-agents.md +564 -0
  115. package/assets/skills/converted/claude-api/composable/mini/70-java-readme.md +237 -0
  116. package/assets/skills/converted/claude-api/composable/mini/71-java-tool-use.md +227 -0
  117. package/assets/skills/converted/claude-api/composable/mini/72-java-streaming-files.md +49 -0
  118. package/assets/skills/converted/claude-api/composable/mini/73-java-managed-agents.md +443 -0
  119. package/assets/skills/converted/claude-api/composable/mini/75-php-readme.md +173 -0
  120. package/assets/skills/converted/claude-api/composable/mini/76-php-tool-use.md +252 -0
  121. package/assets/skills/converted/claude-api/composable/mini/77-php-streaming-batches-files.md +53 -0
  122. package/assets/skills/converted/claude-api/composable/mini/78-php-managed-agents.md +443 -0
  123. package/assets/skills/converted/claude-api/composable/mini/80-ruby-readme.md +133 -0
  124. package/assets/skills/converted/claude-api/composable/mini/81-ruby-tool-use-streaming.md +56 -0
  125. package/assets/skills/converted/claude-api/composable/mini/82-ruby-managed-agents.md +394 -0
  126. package/assets/skills/converted/claude-api/composable/mini/85-curl-examples.md +255 -0
  127. package/assets/skills/converted/claude-api/composable/mini/86-curl-managed-agents.md +340 -0
  128. package/assets/skills/converted/claude-api/composable/presets/csharp.md +1151 -0
  129. package/assets/skills/converted/claude-api/composable/presets/curl.md +1154 -0
  130. package/assets/skills/converted/claude-api/composable/presets/go.md +1598 -0
  131. package/assets/skills/converted/claude-api/composable/presets/java.md +1523 -0
  132. package/assets/skills/converted/claude-api/composable/presets/php.md +1488 -0
  133. package/assets/skills/converted/claude-api/composable/presets/python.md +2605 -0
  134. package/assets/skills/converted/claude-api/composable/presets/ruby.md +1146 -0
  135. package/assets/skills/converted/claude-api/composable/presets/shared.md +6478 -0
  136. package/assets/skills/converted/claude-api/composable/presets/typescript.md +2261 -0
  137. package/assets/skills/converted/docx/composable/BUNDLE.md +617 -0
  138. package/assets/skills/converted/docx/composable/INDEX.md +12 -0
  139. package/assets/skills/converted/docx/composable/VERSION +1 -0
  140. package/assets/skills/converted/docx/composable/mini/00-core.md +26 -0
  141. package/assets/skills/converted/docx/composable/mini/01-reading-converting.md +36 -0
  142. package/assets/skills/converted/docx/composable/mini/02-creating-setup-layout.md +85 -0
  143. package/assets/skills/converted/docx/composable/mini/03-creating-elements.md +257 -0
  144. package/assets/skills/converted/docx/composable/mini/04-editing-existing.md +57 -0
  145. package/assets/skills/converted/docx/composable/mini/05-xml-reference.md +128 -0
  146. package/assets/skills/converted/internal-comms/composable/BUNDLE.md +220 -0
  147. package/assets/skills/converted/internal-comms/composable/INDEX.md +11 -0
  148. package/assets/skills/converted/internal-comms/composable/VERSION +1 -0
  149. package/assets/skills/converted/internal-comms/composable/mini/00-core.md +30 -0
  150. package/assets/skills/converted/internal-comms/composable/mini/01-3p-updates.md +49 -0
  151. package/assets/skills/converted/internal-comms/composable/mini/02-company-newsletter.md +67 -0
  152. package/assets/skills/converted/internal-comms/composable/mini/03-faq-answers.md +32 -0
  153. package/assets/skills/converted/internal-comms/composable/mini/04-general-comms.md +18 -0
  154. package/assets/skills/converted/mcp-builder/composable/BUNDLE.md +2460 -0
  155. package/assets/skills/converted/mcp-builder/composable/INDEX.md +23 -0
  156. package/assets/skills/converted/mcp-builder/composable/VERSION +1 -0
  157. package/assets/skills/converted/mcp-builder/composable/mini/00-core.md +43 -0
  158. package/assets/skills/converted/mcp-builder/composable/mini/01-workflow-research-planning.md +54 -0
  159. package/assets/skills/converted/mcp-builder/composable/mini/02-implementation-process.md +78 -0
  160. package/assets/skills/converted/mcp-builder/composable/mini/03-naming-conventions.md +33 -0
  161. package/assets/skills/converted/mcp-builder/composable/mini/04-response-formats.md +21 -0
  162. package/assets/skills/converted/mcp-builder/composable/mini/05-pagination.md +24 -0
  163. package/assets/skills/converted/mcp-builder/composable/mini/06-transport.md +47 -0
  164. package/assets/skills/converted/mcp-builder/composable/mini/07-annotations.md +20 -0
  165. package/assets/skills/converted/mcp-builder/composable/mini/08-security.md +35 -0
  166. package/assets/skills/converted/mcp-builder/composable/mini/09-error-handling.md +32 -0
  167. package/assets/skills/converted/mcp-builder/composable/mini/10-testing-and-documentation.md +21 -0
  168. package/assets/skills/converted/mcp-builder/composable/mini/11-python-implementation.md +432 -0
  169. package/assets/skills/converted/mcp-builder/composable/mini/12-python-advanced-and-checklist.md +233 -0
  170. package/assets/skills/converted/mcp-builder/composable/mini/13-node-implementation.md +717 -0
  171. package/assets/skills/converted/mcp-builder/composable/mini/14-node-advanced-and-checklist.md +200 -0
  172. package/assets/skills/converted/mcp-builder/composable/mini/15-evaluation-design.md +200 -0
  173. package/assets/skills/converted/mcp-builder/composable/mini/16-evaluation-running.md +198 -0
  174. package/assets/skills/converted/mcp-builder/composable/presets/node-server.md +1381 -0
  175. package/assets/skills/converted/mcp-builder/composable/presets/python-server.md +1129 -0
  176. package/assets/skills/converted/pdf/composable/BUNDLE.md +1284 -0
  177. package/assets/skills/converted/pdf/composable/INDEX.md +14 -0
  178. package/assets/skills/converted/pdf/composable/VERSION +1 -0
  179. package/assets/skills/converted/pdf/composable/mini/00-core.md +46 -0
  180. package/assets/skills/converted/pdf/composable/mini/01-creation.md +176 -0
  181. package/assets/skills/converted/pdf/composable/mini/02-extraction.md +178 -0
  182. package/assets/skills/converted/pdf/composable/mini/03-merge-split-manipulate.md +240 -0
  183. package/assets/skills/converted/pdf/composable/mini/04-images-ocr.md +168 -0
  184. package/assets/skills/converted/pdf/composable/mini/05-encryption.md +51 -0
  185. package/assets/skills/converted/pdf/composable/mini/06-forms.md +300 -0
  186. package/assets/skills/converted/pdf/composable/mini/07-libraries-reference.md +89 -0
  187. package/assets/skills/converted/pptx/composable/BUNDLE.md +911 -0
  188. package/assets/skills/converted/pptx/composable/INDEX.md +12 -0
  189. package/assets/skills/converted/pptx/composable/VERSION +1 -0
  190. package/assets/skills/converted/pptx/composable/mini/00-core.md +37 -0
  191. package/assets/skills/converted/pptx/composable/mini/01-reading.md +37 -0
  192. package/assets/skills/converted/pptx/composable/mini/02-creating-from-scratch.md +422 -0
  193. package/assets/skills/converted/pptx/composable/mini/03-editing-templates.md +207 -0
  194. package/assets/skills/converted/pptx/composable/mini/04-design.md +89 -0
  195. package/assets/skills/converted/pptx/composable/mini/05-qa-and-rendering.md +91 -0
  196. package/assets/skills/converted/pptx/composable/presets/creating.md +659 -0
  197. package/assets/skills/converted/pptx/composable/presets/editing.md +485 -0
  198. package/assets/skills/converted/skill-creator/composable/BUNDLE.md +1681 -0
  199. package/assets/skills/converted/skill-creator/composable/INDEX.md +21 -0
  200. package/assets/skills/converted/skill-creator/composable/VERSION +1 -0
  201. package/assets/skills/converted/skill-creator/composable/mini/00-core.md +59 -0
  202. package/assets/skills/converted/skill-creator/composable/mini/01-creating-a-skill.md +27 -0
  203. package/assets/skills/converted/skill-creator/composable/mini/02-skill-writing-guide.md +71 -0
  204. package/assets/skills/converted/skill-creator/composable/mini/03-test-cases.md +21 -0
  205. package/assets/skills/converted/skill-creator/composable/mini/04-running-and-evaluating.md +128 -0
  206. package/assets/skills/converted/skill-creator/composable/mini/05-improving-the-skill.md +30 -0
  207. package/assets/skills/converted/skill-creator/composable/mini/06-blind-comparison.md +5 -0
  208. package/assets/skills/converted/skill-creator/composable/mini/07-description-optimization.md +74 -0
  209. package/assets/skills/converted/skill-creator/composable/mini/08-packaging.md +11 -0
  210. package/assets/skills/converted/skill-creator/composable/mini/09-environment-specific.md +38 -0
  211. package/assets/skills/converted/skill-creator/composable/mini/10-scripts-and-references.md +34 -0
  212. package/assets/skills/converted/skill-creator/composable/mini/11-json-schemas.md +414 -0
  213. package/assets/skills/converted/skill-creator/composable/mini/12-agent-grader.md +225 -0
  214. package/assets/skills/converted/skill-creator/composable/mini/13-agent-comparator.md +204 -0
  215. package/assets/skills/converted/skill-creator/composable/mini/14-agent-analyzer.md +276 -0
  216. package/assets/skills/converted/skill-creator/composable/presets/authoring.md +198 -0
  217. package/assets/skills/converted/skill-creator/composable/presets/evaluating.md +1334 -0
  218. package/assets/skills/converted/skill-creator/composable/presets/optimizing.md +160 -0
  219. package/assets/skills/converted/skill-creator/composable/presets.json +5 -0
  220. package/assets/skills/meta/ccs-skill-creator/composable/BUNDLE.md +465 -0
  221. package/assets/skills/meta/ccs-skill-creator/composable/INDEX.md +8 -0
  222. package/assets/skills/meta/ccs-skill-creator/composable/VERSION +1 -0
  223. package/assets/skills/meta/ccs-skill-creator/composable/mini/00-core.md +46 -0
  224. package/assets/skills/meta/ccs-skill-creator/composable/mini/01-create-new-skill.md +167 -0
  225. package/assets/skills/meta/ccs-skill-creator/composable/mini/02-convert-existing-skill.md +120 -0
  226. package/assets/skills/meta/ccs-skill-creator/composable/mini/03-review-and-maintain.md +112 -0
  227. package/assets/skills/sources/anthropic/PROVENANCE.md +3 -0
  228. package/assets/skills/sources/anthropic/claude-api/LICENSE.txt +202 -0
  229. package/assets/skills/sources/anthropic/docx/LICENSE.txt +30 -0
  230. package/assets/skills/sources/anthropic/internal-comms/LICENSE.txt +202 -0
  231. package/assets/skills/sources/anthropic/mcp-builder/LICENSE.txt +202 -0
  232. package/assets/skills/sources/anthropic/pdf/LICENSE.txt +30 -0
  233. package/assets/skills/sources/anthropic/pptx/LICENSE.txt +30 -0
  234. package/assets/skills/sources/anthropic/skill-creator/LICENSE.txt +202 -0
  235. package/assets/skills/sources/financial-analyst/PROVENANCE.md +1 -0
  236. package/assets/tools/hive.py +728 -0
  237. package/dist/cli.js +7494 -0
  238. package/package.json +40 -0
@@ -0,0 +1,1488 @@
1
+ <!-- GENERATED by tools/hive.py compile — do not hand-edit. -->
2
+ # claude-api — Compiled Skill Bundle — Preset: php (v1.0.0)
3
+
4
+ All composable mini-skills for `claude-api` concatenated in index order, frontmatter stripped. Regenerate with `tools/hive.py compile <skill-dir>` — do not edit by hand.
5
+
6
+ ---
7
+ <!-- module: 00-core.md -->
8
+
9
+ # Building LLM-Powered Applications with Claude
10
+
11
+ This skill helps you build LLM-powered applications with Claude. Choose the right surface based on your needs, detect the project language, then read the relevant language-specific documentation.
12
+
13
+ ## Before You Start
14
+
15
+ Scan the target file (or, if no target file, the prompt and project) for non-Anthropic provider markers — `import openai`, `from openai`, `langchain_openai`, `OpenAI(`, `gpt-4`, `gpt-5`, file names like `agent-openai.py` or `*-generic.py`, or any explicit instruction to keep the code provider-neutral. If you find any, stop and tell the user that this skill produces Claude/Anthropic SDK code; ask whether they want to switch the file to Claude or want a non-Claude implementation. Do not edit a non-Anthropic file with Anthropic SDK calls.
16
+
17
+ ## Output Requirement
18
+
19
+ When the user asks you to add, modify, or implement a Claude feature, your code must call Claude through one of:
20
+
21
+ 1. **The official Anthropic SDK** for the project's language (`anthropic`, `@anthropic-ai/sdk`, `com.anthropic.*`, etc.). This is the default whenever a supported SDK exists for the project.
22
+ 2. **Raw HTTP** (`curl`, `requests`, `fetch`, `httpx`, etc.) — only when the user explicitly asks for cURL/REST/raw HTTP, the project is a shell/cURL project, or the language has no official SDK.
23
+
24
+ Never mix the two — don't reach for `requests`/`fetch` in a Python or TypeScript project just because it feels lighter. Never fall back to OpenAI-compatible shims.
25
+
26
+ **Never guess SDK usage.** Function names, class names, namespaces, method signatures, and import paths must come from explicit documentation — either the `{lang}/` files in this skill or the official SDK repositories or documentation links listed in `shared/live-sources.md`. If the binding you need is not explicitly documented in the skill files, WebFetch the relevant SDK repo from `shared/live-sources.md` before writing code. Do not infer Ruby/Java/Go/PHP/C# APIs from cURL shapes or from another language's SDK.
27
+
28
+ **If WebFetch or repository access fails** (network restricted, timeouts, clone blocked): do not keep retrying — write code from the patterns and namespace/package tables in the `{lang}/` file, run the compiler or interpreter on it, and iterate on the error output. For statically-typed SDKs (C#, Java, Go) a compile-fix loop against local errors reaches working code faster than blocked network research.
29
+
30
+ ## Defaults
31
+
32
+ Unless the user requests otherwise:
33
+
34
+ For the Claude model version, please use Claude Opus 4.8, which you can access via the exact model string `claude-opus-4-8`. Please default to using adaptive thinking (`thinking: {type: "adaptive"}`) for anything remotely complicated. And finally, please default to streaming for any request that may involve long input, long output, or high `max_tokens` — it prevents hitting request timeouts. Use the SDK's `.get_final_message()` / `.finalMessage()` helper to get the complete response if you don't need to handle individual stream events
35
+
36
+ ## ⚠️ API Drift — Your Training Prior May Be Stale
37
+
38
+ Several common Claude API shapes changed in 2025–2026. If you recall a pattern from training, verify it against the `{lang}/` files in this skill before writing — the rows below are the most frequent drift points:
39
+
40
+ | Area | Stale prior | Current API |
41
+ |---|---|---|
42
+ | Extended thinking | `thinking: {type: "enabled", budget_tokens: N}` | On Claude 4.6+ models: `thinking: {type: "adaptive"}`. `budget_tokens` is deprecated on Opus 4.6 / Sonnet 4.6 and **rejected with a 400** on Fable 5 / Sonnet 5 / Opus 4.8 / 4.7. Pre-4.6 models still use `budget_tokens`. |
43
+ | Web search / web fetch tool type | `web_search_20250305`, `web_fetch_20250910` | `web_search_20260209`, `web_fetch_20260209` (dynamic filtering) on Opus 4.8/4.7/4.6, Sonnet 5, and Sonnet 4.6. Older models keep the basic variants; on Vertex AI only basic `web_search_20250305` is available (web fetch is not on Vertex) — see the Server Tools QR below. |
44
+ | PHP parameter names | snake_case wire names as named args (`max_tokens`) | Top-level named args are camelCase (`maxTokens`). Nested array keys vary by feature (e.g. `'taskBudget'`, `'skillID'`, `'mcp_server_name'`) — copy the exact key from the documented example; do not bulk-convert. |
45
+
46
+ The `{lang}/` files in this skill are authoritative over recalled patterns.
47
+
48
+ ## Subcommands
49
+
50
+ If the User Request at the bottom of this prompt is a bare subcommand string (no prose), search every **Subcommands** table in this document — including any in sections appended below — and follow the matching Action column directly. This lets users invoke specific flows via `/claude-api <subcommand>`. If no table in the document matches, treat the request as normal prose.
51
+
52
+ | Subcommand | Action |
53
+ |---|---|
54
+ | `migrate` | Migrate existing Claude API code to a newer model. **Read `shared/model-migration.md` immediately** and follow it in order: Step 0 (confirm scope — ask which files/directories before any edit), Step 1 (classify each file), then the per-target breaking-changes section. Do not summarize the guide — execute it. If the user did not name a target model, ask which model to migrate to in the same turn as the scope question. |
55
+
56
+ ## Language Detection
57
+
58
+ Before reading code examples, determine which language the user is working in:
59
+
60
+ 1. **Look at project files** to infer the language:
61
+
62
+ - `*.py`, `requirements.txt`, `pyproject.toml`, `setup.py`, `Pipfile` → **Python** — read from `python/`
63
+ - `*.ts`, `*.tsx`, `package.json`, `tsconfig.json` → **TypeScript** — read from `typescript/`
64
+ - `*.js`, `*.jsx` (no `.ts` files present) → **TypeScript** — JS uses the same SDK, read from `typescript/`
65
+ - `*.java`, `pom.xml`, `build.gradle` → **Java** — read from `java/`
66
+ - `*.kt`, `*.kts`, `build.gradle.kts` → **Java** — Kotlin uses the Java SDK, read from `java/`
67
+ - `*.scala`, `build.sbt` → **Java** — Scala uses the Java SDK, read from `java/`
68
+ - `*.go`, `go.mod` → **Go** — read from `go/`
69
+ - `*.rb`, `Gemfile` → **Ruby** — read from `ruby/`
70
+ - `*.cs`, `*.csproj` → **C#** — read from `csharp/`
71
+ - `*.php`, `composer.json` → **PHP** — read from `php/`
72
+
73
+ 2. **If multiple languages detected** (e.g., both Python and TypeScript files):
74
+
75
+ - Check which language the user's current file or question relates to
76
+ - If still ambiguous, ask: "I detected both Python and TypeScript files. Which language are you using for the Claude API integration?"
77
+
78
+ 3. **If language can't be inferred** (empty project, no source files, or unsupported language):
79
+
80
+ - Use AskUserQuestion with options: Python, TypeScript, Java, Go, Ruby, cURL/raw HTTP, C#, PHP
81
+ - If AskUserQuestion is unavailable, default to Python examples and note: "Showing Python examples. Let me know if you need a different language."
82
+
83
+ 4. **If unsupported language detected** (Rust, Swift, C++, Elixir, etc.):
84
+
85
+ - Suggest cURL/raw HTTP examples from `curl/` and note that community SDKs may exist
86
+ - Offer to show Python or TypeScript examples as reference implementations
87
+
88
+ 5. **If user needs cURL/raw HTTP examples**, read from `curl/`.
89
+
90
+ ### Language-Specific Feature Support
91
+
92
+ | Language | Tool Runner | Managed Agents | Notes |
93
+ | ---------- | ----------- | -------------- | ------------------------------------- |
94
+ | Python | Yes (beta) | Yes (beta) | Full support — `@beta_tool` decorator |
95
+ | TypeScript | Yes (beta) | Yes (beta) | Full support — `betaZodTool` + Zod |
96
+ | Java | Yes (beta) | Yes (beta) | Beta tool use with annotated classes |
97
+ | Go | Yes (beta) | Yes (beta) | `BetaToolRunner` in `toolrunner` pkg |
98
+ | Ruby | Yes (beta) | Yes (beta) | `BaseTool` + `tool_runner` in beta |
99
+ | C# | Yes (beta) | Yes (beta) | `BetaToolRunner` + raw JSON schema |
100
+ | PHP | Yes (beta) | Yes (beta) | `BetaRunnableTool` + `toolRunner()` |
101
+ | cURL | N/A | Yes (beta) | Raw HTTP, no SDK features |
102
+
103
+ > **Managed Agents code examples**: dedicated language-specific READMEs are provided for Python, TypeScript, Go, Ruby, PHP, Java, and cURL (`{lang}/managed-agents/README.md`, `curl/managed-agents.md`). Read your language's README plus the language-agnostic `shared/managed-agents-*.md` concept files. **Agents are persistent — create once, reference by ID.** Store the agent ID returned by `agents.create` and pass it to every subsequent `sessions.create`; do not call `agents.create` in the request path. The Anthropic CLI (`ant`) is one convenient way to create agents and environments from version-controlled YAML — see `shared/anthropic-cli.md`. If a binding you need isn't shown in the README, WebFetch the relevant entry from `shared/live-sources.md` rather than guess. C# has beta Managed Agents support via `client.Beta.Agents` and related namespaces.
104
+
105
+ ## Which Surface Should I Use?
106
+
107
+ > **Start simple.** Default to the simplest tier that meets your needs. Single API calls and workflows handle most use cases — only reach for agents when the task genuinely requires open-ended, model-driven exploration.
108
+
109
+ | Use Case | Tier | Recommended Surface | Why |
110
+ | ----------------------------------------------- | --------------- | ------------------------- | ------------------------------------------------------------ |
111
+ | Classification, summarization, extraction, Q&A | Single LLM call | **Claude API** | One request, one response |
112
+ | Batch processing or embeddings | Single LLM call | **Claude API** | Specialized endpoints |
113
+ | Multi-step pipelines with code-controlled logic | Workflow | **Claude API + tool use** | You orchestrate the loop |
114
+ | Custom agent with your own tools | Agent | **Claude API + tool use** | Maximum flexibility |
115
+ | Server-managed stateful agent with workspace | Agent | **Managed Agents** | Anthropic runs the loop and hosts the tool-execution sandbox |
116
+ | Persisted, versioned agent configs | Agent | **Managed Agents** | Agents are stored objects; sessions pin to a version |
117
+ | Long-running multi-turn agent with file mounts | Agent | **Managed Agents** | Per-session containers, SSE event stream, Skills + MCP |
118
+
119
+ > **Note:** Managed Agents is the right choice when you want Anthropic to run the agent loop *and* host the container where tools execute — file ops, bash, code execution all run in the per-session workspace. If you want to host the compute yourself or run your own custom tool runtime, Claude API + tool use is the right choice — use the tool runner for automatic loop handling, or the manual loop for fine-grained control (approval gates, custom logging, conditional execution).
120
+
121
+ > **Cloud-provider access.** **Claude Platform on AWS** is Anthropic-operated with same-day API parity — see `shared/claude-platform-on-aws.md` for client setup. For per-feature availability on **Claude Platform on AWS**, **Amazon Bedrock**, **Google Vertex AI**, and **Microsoft Foundry**, see `shared/platform-availability.md` — that table is the single source of truth in this skill; do not infer availability from anywhere else.
122
+
123
+ ### Decision Tree
124
+
125
+ ```
126
+ What does your application need?
127
+
128
+ 0. Which provider?
129
+ ├── First-party API or Claude Platform on AWS → continue (full surface available; per-feature exceptions in shared/platform-availability.md).
130
+ └── Amazon Bedrock, Google Vertex AI, or Microsoft Foundry → Claude API (+ tool use for agents); see shared/platform-availability.md for per-feature support.
131
+
132
+ 1. Single LLM call (classification, summarization, extraction, Q&A)
133
+ └── Claude API — one request, one response
134
+
135
+ 2. Do you want Anthropic to run the agent loop and host a per-session
136
+ container where Claude executes tools (bash, file ops, code)?
137
+ └── Yes → Managed Agents — server-managed sessions, persisted agent configs,
138
+ SSE event stream, Skills + MCP, file mounts.
139
+ Examples: "stateful coding agent with a workspace per task",
140
+ "long-running research agent that streams events to a UI",
141
+ "agent with persisted, versioned config used across many sessions"
142
+
143
+ 3. Workflow (multi-step, code-orchestrated, with your own tools)
144
+ └── Claude API with tool use — you control the loop
145
+
146
+ 4. Open-ended agent (model decides its own trajectory, your own tools, you host the compute)
147
+ └── Claude API agentic loop (maximum flexibility)
148
+ ```
149
+
150
+ ### Should I Build an Agent?
151
+
152
+ Before choosing the agent tier, check all four criteria:
153
+
154
+ - **Complexity** — Is the task multi-step and hard to fully specify in advance? (e.g., "turn this design doc into a PR" vs. "extract the title from this PDF")
155
+ - **Value** — Does the outcome justify higher cost and latency?
156
+ - **Viability** — Is Claude capable at this task type?
157
+ - **Cost of error** — Can errors be caught and recovered from? (tests, review, rollback)
158
+
159
+ If the answer is "no" to any of these, stay at a simpler tier (single call or workflow).
160
+
161
+ ## Architecture
162
+
163
+ Everything goes through `POST /v1/messages`. Tools and output constraints are features of this single endpoint — not separate APIs.
164
+
165
+ **User-defined tools** — You define tools (via decorators, Zod schemas, or raw JSON), and the SDK's tool runner handles calling the API, executing your functions, and looping until Claude is done. For full control, you can write the loop manually.
166
+
167
+ **Server-side tools** — Anthropic-hosted tools that run on Anthropic's infrastructure. Code execution is fully server-side (declare it in `tools`, Claude runs code automatically). Computer use can be server-hosted or self-hosted.
168
+
169
+ **Structured outputs** — Constrains the Messages API response format (`output_config.format`) and/or tool parameter validation (`strict: true`). The recommended approach is `client.messages.parse()` which validates responses against your schema automatically. Note: the old `output_format` parameter is deprecated; use `output_config: {format: {...}}` on `messages.create()`.
170
+
171
+ **Supporting endpoints** — Batches (`POST /v1/messages/batches`), Files (`POST /v1/files`), Token Counting (`POST /v1/messages/count_tokens` — see `shared/token-counting.md`), and Models (`GET /v1/models`, `GET /v1/models/{id}` — live capability/context-window discovery) feed into or support Messages API requests.
172
+
173
+ ## Reading Guide
174
+
175
+ After detecting the language, read the relevant files based on what the user needs.
176
+
177
+ **All SDK languages use the same multi-file layout** — directory `{lang}/claude-api/` containing `README.md` (install, client init, basic request, thinking, caching, stop details, misc), `tool-use.md` (tool definitions, agentic loop, Anthropic-defined tools, structured outputs), `streaming.md`, `batches.md`, `files-api.md`. Not every language has every file (e.g., Ruby has no `batches.md`); if a file is absent, that feature's example is not yet documented for that language — fall back to the cURL shape or WebFetch the SDK repo from `shared/live-sources.md`. **cURL** → `curl/examples.md`.
178
+
179
+ The Quick Task Reference below uses the `{lang}/claude-api/FILE.md` path notation for all languages.
180
+
181
+ ### Quick Task Reference
182
+
183
+ **Single text classification/summarization/extraction/Q&A:**
184
+ → Read only `{lang}/claude-api/README.md`
185
+
186
+ **Chat UI or real-time response display:**
187
+ → Read `{lang}/claude-api/README.md` + `{lang}/claude-api/streaming.md`
188
+
189
+ **Long-running conversations (may exceed context window):**
190
+ → Read `{lang}/claude-api/README.md` — see Compaction section
191
+ **Migrating to a newer model (Fable 5 / Opus 4.8 / Opus 4.7 / Opus 4.6 / Sonnet 5 / Sonnet 4.6) or replacing a retired model:**
192
+ → Read `shared/model-migration.md`
193
+ **Prompting or tuning Fable 5 (long turns, effort, verbosity, autonomous runs, sub-agents):**
194
+ → Read `shared/model-migration.md` → Migrating to Fable 5 → Behavioral shifts (prompt-tunable) + Long-running agent recommendations
195
+ **Prompt caching / optimize caching / "why is my cache hit rate low":**
196
+ → Read `shared/prompt-caching.md` + `{lang}/claude-api/README.md` (Prompt Caching section)
197
+ **Count tokens in a file / prompt / diff ("how many tokens is X"):**
198
+ → Read `shared/token-counting.md` — use `messages.count_tokens`, never `tiktoken`
199
+
200
+ **Function calling / tool use / agents:**
201
+ → Read `{lang}/claude-api/README.md` + `shared/tool-use-concepts.md` + `{lang}/claude-api/tool-use.md`
202
+
203
+ **Agent design (tool surface, context management, caching strategy):**
204
+ → Read `shared/agent-design.md`
205
+
206
+ **Batch processing (non-latency-sensitive):**
207
+ → Read `{lang}/claude-api/README.md` + `{lang}/claude-api/batches.md`
208
+
209
+ **File uploads across multiple requests:**
210
+ → Read `{lang}/claude-api/README.md` + `{lang}/claude-api/files-api.md`
211
+
212
+ **Managed Agents (server-managed stateful agents with workspace):**
213
+ → Read `shared/managed-agents-overview.md` + the rest of the `shared/managed-agents-*.md` files. For Python, TypeScript, Go, Ruby, PHP, and Java, read `{lang}/managed-agents/README.md` for code examples. For cURL, read `curl/managed-agents.md`. **Agents are persistent — create once, reference by ID.** Store the agent ID returned by `agents.create` and pass it to every subsequent `sessions.create`; do not call `agents.create` in the request path. The Anthropic CLI (`ant`) is one convenient way to create agents and environments from version-controlled YAML — see `shared/anthropic-cli.md`. If a binding you need isn't shown in the language README, WebFetch the relevant entry from `shared/live-sources.md` rather than guess. C# has beta Managed Agents support — see `csharp/claude-api/README.md` for details, or `curl/managed-agents.md` for raw HTTP reference.
214
+
215
+ ### Claude API (Full File Reference)
216
+
217
+ Read the **language-specific Claude API source** — `{language}/claude-api/` for every SDK language, `curl/examples.md` for cURL:
218
+
219
+ 1. **`{language}/claude-api/README.md`** — **Read this first.** Installation, quick start, common patterns, error handling.
220
+ 2. **`shared/tool-use-concepts.md`** — Read when the user needs function calling, code execution, memory, or structured outputs. Covers conceptual foundations.
221
+ 3. **`shared/agent-design.md`** — Read when designing an agent: bash vs. dedicated tools, programmatic tool calling, tool search/skills, context editing vs. compaction vs. memory, caching principles.
222
+ 4. **`{language}/claude-api/tool-use.md`** — Read for language-specific tool use code examples (tool runner, manual loop, code execution, memory, structured outputs).
223
+ 5. **`{language}/claude-api/streaming.md`** — Read when building chat UIs or interfaces that display responses incrementally.
224
+ 6. **`{language}/claude-api/batches.md`** — Read when processing many requests offline (not latency-sensitive). Runs asynchronously at 50% cost.
225
+ 7. **`{language}/claude-api/files-api.md`** — Read when sending the same file across multiple requests without re-uploading.
226
+ 8. **`shared/prompt-caching.md`** — Read when adding or optimizing prompt caching. Covers prefix-stability design, breakpoint placement, and anti-patterns that silently invalidate cache.
227
+ 9. **`shared/error-codes.md`** — Read when debugging HTTP errors or implementing error handling. Includes the per-SDK typed exception class table and the Go `errors.As` pattern.
228
+ 10. **`shared/model-migration.md`** — Read when upgrading to newer models, replacing retired models, or translating `budget_tokens` / prefill patterns to the current API.
229
+ 11. **`shared/live-sources.md`** — WebFetch URLs for fetching the latest official documentation.
230
+
231
+ Not every language has every file (e.g., Ruby has no `batches.md`); if a file is absent, that feature's example is not yet documented for that language.
232
+
233
+ > **Note:** For the Managed Agents file reference, see the `## Managed Agents (Beta)` section above — it lists every `shared/managed-agents-*.md` file and the language-specific READMEs.
234
+
235
+ ## When to Use WebFetch
236
+
237
+ Use WebFetch to get the latest documentation when:
238
+
239
+ - User asks for "latest" or "current" information
240
+ - Cached data seems incorrect
241
+ - User asks about features not covered here
242
+
243
+ Live documentation URLs are in `shared/live-sources.md`.
244
+
245
+ ---
246
+ <!-- module: 01-model-api-quick-reference.md -->
247
+
248
+ # Claude API Quick Reference (Models, Auth, Params, Surfaces)
249
+
250
+ ## Current Models (cached: 2026-06-24)
251
+
252
+ | Model | Model ID | Context | Input $/1M | Output $/1M |
253
+ | ----------------- | ------------------- | -------------- | ---------- | ----------- |
254
+ | Claude Fable 5 | `claude-fable-5` | 1M | $10.00 | $50.00 |
255
+ | Claude Mythos 5 (Project Glasswing only) | `claude-mythos-5` | 1M | $10.00 | $50.00 |
256
+ | Claude Opus 4.8 | `claude-opus-4-8` | 1M | $5.00 | $25.00 |
257
+ | Claude Opus 4.7 | `claude-opus-4-7` | 1M | $5.00 | $25.00 |
258
+ | Claude Opus 4.6 | `claude-opus-4-6` | 1M | $5.00 | $25.00 |
259
+ | Claude Sonnet 5 | `claude-sonnet-5` | 1M | $3.00 ($2.00 intro through 2026-08-31) | $15.00 ($10.00 intro) |
260
+ | Claude Sonnet 4.6 | `claude-sonnet-4-6` | 1M | $3.00 | $15.00 |
261
+ | Claude Haiku 4.5 | `claude-haiku-4-5` | 200K | $1.00 | $5.00 |
262
+
263
+ **ALWAYS use `claude-opus-4-8` unless the user explicitly names a different model.** This is non-negotiable. Do not use `claude-sonnet-5`, `claude-sonnet-4-6`, or any other model unless the user literally says "use sonnet" or "use haiku". Never downgrade for cost — that's the user's decision, not yours. Use `claude-fable-5` only when the user explicitly asks for Claude Fable 5, "fable", or Anthropic's most capable model — it has different API behavior than the Opus family (see below) and pricing that exceeds Opus-tier.
264
+
265
+ ### Claude Fable 5 (`claude-fable-5`) — most capable widely released model
266
+
267
+ Claude Fable 5 is Anthropic's most capable widely released model, for the most demanding reasoning and long-horizon agentic work. **Claude Mythos 5** (`claude-mythos-5`) offers the same capabilities, pricing, and API surface through Project Glasswing (participation is the only way to access it), succeeding the invitation-only Claude Mythos Preview (`claude-mythos-preview`) — everything below applies to both models. 1M context window (the maximum is also the default), 128K max output. Key API differences from Opus-tier — see `shared/model-migration.md` → Migrating to Claude Fable 5 for details:
268
+
269
+ - **Thinking is always on** — omit the `thinking` parameter entirely (or send `{type: "adaptive"}`). Any other explicit configuration is rejected: `{type: "disabled"}` and `{type: "enabled", budget_tokens: N}` both return a 400. Control depth with `output_config.effort` (supports `low` through `xhigh` and `max`).
270
+ - **The raw chain of thought is never returned** — responses carry regular `thinking` blocks (not `redacted_thinking`): `display: "summarized"` returns a readable summary, `"omitted"` (the default) leaves the `thinking` field as an empty string. Replay rules: pass thinking blocks back exactly as received on the same model (including empty-text blocks — the API rejects *modified* blocks, not read ones); a **different** model **drops** them from the prompt (typically silently — not an error; the drop happens before pricing, so dropped blocks aren't billed and there's nothing to strip). Regular thinking blocks from other models replay across models freely.
271
+ - **Tokenizer** — same tokenizer as Opus 4.8 (introduced with Opus 4.7). Token counts are roughly unchanged when migrating from Opus 4.7/4.8; per-token pricing differs. Coming from Opus 4.6, Sonnet, Haiku, or older, re-baseline with `count_tokens`.
272
+ - **`refusal` stop reason — handle it, and opt into fallbacks by default** — safety classifiers may decline a request (HTTP 200, `stop_reason: "refusal"`, with a `stop_details` category). A pre-output refusal has an empty `content` array and is not billed at all; a mid-stream refusal bills the already-streamed output — discard the partial output. Always check `stop_reason` before reading `content`. Recovery is **opt-in on the API**: most Claude consumer surfaces ship with built-in Claude Opus 4.8 fallbacks, but an API request that doesn't opt in simply stops on a refusal — and false positives on benign adjacent work (security tooling, life-sciences tasks) do happen. **When you write `claude-fable-5` code, include the server-side `fallbacks` parameter by default** (`betas: ["server-side-fallback-2026-06-01"]` + `fallbacks: [{"model": "claude-opus-4-8"}]`; Claude API and Claude Platform on AWS): a declined request is transparently re-served by the fallback model inside the same call, with credit-style repricing applied automatically (a decline before any output isn't billed; the rescue bills at the fallback model's own rates). Tell the user you've enabled it; drop it only if they decline. The GA SDKs' client-side `BetaRefusalFallbackMiddleware` + `BetaFallbackState` handle retry everywhere server-side fallbacks aren't supported (incl. Amazon Bedrock, Vertex AI, Microsoft Foundry); fallback credit refunds the cache-switch cost of client-side retries. Code examples: the Refusal Fallbacks section of your language's claude-api doc; full semantics in the migration guide's refusal section.
273
+ - **No assistant prefill** — same as the rest of the 4.6+ family.
274
+ - **30-day data retention required** — Claude Fable 5 is not available under zero data retention; requests from an org whose retention configuration doesn't meet the requirement return `400 invalid_request_error`.
275
+ - **Longer turns, different prompting** — single requests on hard tasks can run many minutes (plan timeouts/streaming/progress UX); effort sweeps should include low/medium for routine work; prompts written for prior models are often too prescriptive and reduce output quality. See `shared/model-migration.md` → Migrating to Claude Fable 5 → Behavioral shifts (prompt-tunable) for the recommended prompt snippets (anti-overplanning, no-tidying, grounded progress claims, boundaries, async sub-agents, memory, `send_to_user`).
276
+
277
+ **CRITICAL: Use only the exact model ID strings from the table above — they are complete as-is. Do not append date suffixes.** For example, use `claude-sonnet-4-6`, never `claude-sonnet-4-6-20251114` or any other date-suffixed variant you might recall from training data. If the user requests an older model not in the table (e.g., "opus 4.5", "sonnet 3.7"), read `shared/models.md` for the exact ID — do not construct one yourself.
278
+
279
+ A note: if any of the model strings above look unfamiliar to you, that's to be expected — that just means they were released after your training data cutoff. Rest assured they are real models; we wouldn't mess with you like that.
280
+
281
+ **Live capability lookup:** The table above is cached. When the user asks "what's the context window for X", "does X support vision/thinking/effort", or "which models support Y", query the Models API (`client.models.retrieve(id)` / `client.models.list()`) — see `shared/models.md` for the field reference and capability-filter examples.
282
+
283
+ ## Authentication (Quick Reference)
284
+
285
+ **An unset `ANTHROPIC_API_KEY` does NOT mean there are no credentials.** The SDKs and the `ant` CLI resolve credentials in this order (first match wins): `ANTHROPIC_API_KEY` → `ANTHROPIC_AUTH_TOKEN` → the `ANTHROPIC_PROFILE`-selected or active OAuth profile from `ant auth login` → Workload Identity Federation env vars → the default profile on disk. A bare `Anthropic()` / `new Anthropic()` / `anthropic.NewClient()` works after `ant auth login` with no env var set.
286
+
287
+ **When you need to call the API and `ANTHROPIC_API_KEY` is unset, don't ask the user for a key.** First run `ant auth status` — it shows which credential source and profile is active. If it reports an active profile:
288
+
289
+ - **SDK code or `ant` CLI:** just run it. The zero-arg client constructor and every `ant …` subcommand pick up the profile automatically — no env var needed.
290
+ - **Raw `curl` / HTTP:** get a short-lived token with `ant auth print-credentials --access-token` and send it as `Authorization: Bearer <token>` **plus** the header `anthropic-beta: oauth-2025-04-20` (OAuth tokens go on `Authorization: Bearer`, not `x-api-key:` — converting a curl from an API key is a header change, not a key swap). Always pass `--access-token`; the no-flag form prints JSON, not a bare token.
291
+
292
+ Only ask the user for a key if `ant auth status` reports no active credential source (or `ant` itself isn't installed). Suggest `ant auth login` as the first option — it stores a profile under `~/.config/anthropic/` that the SDKs read automatically — and an exported `ANTHROPIC_API_KEY` as the alternative.
293
+
294
+ Full auth details (named profiles, scopes, the API-key-shadows-profile trap, refresh-token expiry): `shared/anthropic-cli.md`.
295
+
296
+ ## Thinking & Effort (Quick Reference)
297
+
298
+ **Fable 5 / Opus 4.8 / 4.7 / Sonnet 5 — Adaptive thinking only:** Use `thinking: {type: "adaptive"}`. `thinking: {type: "enabled", budget_tokens: N}` returns a 400 — adaptive is the only on-mode. On Opus 4.8, Opus 4.7, and Sonnet 5, `{type: "disabled"}` and omitting `thinking` both work (on Sonnet 5, omitting runs adaptive; on Opus 4.7/4.8, omitting runs without thinking — set `{type: "adaptive"}` explicitly); on Fable 5, an explicit `{type: "disabled"}` returns a 400 — omit the `thinking` param entirely instead. Sampling parameters (`temperature`, `top_p`, `top_k`) are also removed and will 400. Opus 4.8 keeps the same request surface as 4.7 (no new breaking changes) — see `shared/model-migration.md` → Migrating to Opus 4.8 for the behavioral re-tuning, and → Migrating to Opus 4.7 for the full breaking-change list when coming from 4.6 or earlier. Note: with `thinking` disabled, Opus 4.8 may write longer reasoning into the visible response — leave adaptive thinking on, or add a final-answer-only instruction (see the migration guide).
299
+ **Opus 4.6 — Adaptive thinking (recommended):** Use `thinking: {type: "adaptive"}`. Claude dynamically decides when and how much to think. No `budget_tokens` needed — `budget_tokens` is deprecated on Opus 4.6 and Sonnet 4.6 and should not be used for new code. Adaptive thinking also automatically enables interleaved thinking (no beta header needed). **When the user asks for "extended thinking", a "thinking budget", or `budget_tokens`: always use Fable 5, Opus 4.8, 4.7, or 4.6 with `thinking: {type: "adaptive"}`. The concept of a fixed token budget for thinking is deprecated — adaptive thinking replaces it. Do NOT use `budget_tokens` for new 4.6/4.7/4.8 code and do NOT switch to an older model.** *Gradual-migration carve-out:* `budget_tokens` is still functional on Opus 4.6 and Sonnet 4.6 as a transitional escape hatch — if you're migrating existing code and need a hard token ceiling before you've tuned `effort`, see `shared/model-migration.md` → Transitional escape hatch. Note: this carve-out does **not** apply to Fable 5, Opus 4.7 or 4.8 — `budget_tokens` is fully removed there.
300
+ **Effort parameter (GA, no beta header):** Controls thinking depth and overall token spend via `output_config: {effort: "low"|"medium"|"high"|"max"}` (inside `output_config`, not top-level). Default is `high` (equivalent to omitting it). `max` is supported on Fable 5, Opus 4.6 and later, Sonnet 5, and Sonnet 4.6 (not Haiku or earlier Sonnets). Opus 4.7 added `"xhigh"` (between `high` and `max`) — the best setting for most coding and agentic use cases on Fable 5 / Opus 4.7/4.8 / Sonnet 5, and the default in Claude Code; use a minimum of `high` for most intelligence-sensitive work. Works on Fable 5, Opus 4.5, Opus 4.6, Opus 4.7, Opus 4.8, Sonnet 5, and Sonnet 4.6. Will error on Sonnet 4.5 / Haiku 4.5. On Fable 5, Opus 4.7/4.8, and Sonnet 5, effort matters more than on any prior model in their tier — re-tune it when migrating, and run long-horizon/agentic tasks at `high`/`xhigh` with the full task spec given up front. Combine with adaptive thinking for the best cost-quality tradeoffs. Lower effort means fewer and more-consolidated tool calls, less preamble, and terser confirmations — `high` is often the sweet spot balancing quality and token efficiency; use `max` when correctness matters more than cost; use `low` for subagents or simple tasks.
301
+
302
+ **Thinking display — `"omitted"` by default on Fable 5 / Mythos 5 / Opus 4.8 / 4.7 / Sonnet 5:** `display: "summarized"` returns a readable summary of the reasoning; `"omitted"` (the default on all five — a silent change from Opus 4.6 and Sonnet 4.6, where it was `"summarized"`) streams `thinking` blocks with empty text. `display` controls visibility only — thinking happens and is billed the same under every setting; the raw chain of thought is never exposed on any model. If you stream reasoning to users, the default looks like a long pause before output — set `thinking: {type: "adaptive", display: "summarized"}` explicitly. (Independent of display, echo thinking blocks back unchanged when continuing on the same model; other models silently ignore them — see the migration guide.)
303
+
304
+ **Task Budgets (beta, Fable 5 / Opus 4.7 / 4.8 / Sonnet 5):** `output_config: {task_budget: {type: "tokens", total: N}}` tells the model how many tokens it has for a full agentic loop — it sees a running countdown and self-moderates (minimum 20,000; beta header `task-budgets-2026-03-13`). Distinct from `max_tokens`, which is an enforced per-response ceiling the model is not aware of. See `shared/model-migration.md` → Task Budgets.
305
+
306
+ **Sonnet 4.6:** Supports adaptive thinking (`thinking: {type: "adaptive"}`). `budget_tokens` is deprecated on Sonnet 4.6 — use adaptive thinking instead.
307
+
308
+ **Older models (only if explicitly requested):** If the user specifically asks for Sonnet 4.5 or another older model, use `thinking: {type: "enabled", budget_tokens: N}`. `budget_tokens` must be less than `max_tokens` (minimum 1024). Never choose an older model just because the user mentions `budget_tokens` — use Opus 4.8 with adaptive thinking instead.
309
+
310
+ ## Compaction (Quick Reference)
311
+
312
+ **Beta, Fable 5, Opus 4.8, Opus 4.7, Opus 4.6, Sonnet 5, and Sonnet 4.6.** For long-running conversations that may exceed the 1M context window, enable server-side compaction. The API automatically summarizes earlier context when it approaches the trigger threshold (default: 150K tokens). Requires beta header `compact-2026-01-12`.
313
+
314
+ **Critical:** Append `response.content` (not just the text) back to your messages on every turn. Compaction blocks in the response must be preserved — the API uses them to replace the compacted history on the next request. Extracting only the text string and appending that will silently lose the compaction state.
315
+
316
+ See `{lang}/claude-api/README.md` (Compaction section) for code examples. Full docs via WebFetch in `shared/live-sources.md`.
317
+
318
+ ## Prompt Caching (Quick Reference)
319
+
320
+ **Prefix match.** Any byte change anywhere in the prefix invalidates everything after it. Render order is `tools` → `system` → `messages`. Keep stable content first (frozen system prompt, deterministic tool list), put volatile content (timestamps, per-request IDs, varying questions) after the last `cache_control` breakpoint.
321
+
322
+ **Mid-conversation operator instructions** (Claude Opus 4.8 only; no beta header): append `{"role": "system", ...}` to `messages[]` instead of editing top-level `system`. Preserves the cached history prefix and is the prompt-injection-safe operator channel. See `shared/prompt-caching.md` § Mid-conversation system messages.
323
+
324
+ **Top-level auto-caching** (`cache_control: {type: "ephemeral"}` on `messages.create()`) is the simplest option when you don't need fine-grained placement. Max 4 breakpoints per request. Minimum cacheable prefix is ~1024 tokens — shorter prefixes silently won't cache.
325
+
326
+ **Verify with `usage.cache_read_input_tokens`** — if it's zero across repeated requests, a silent invalidator is at work (`datetime.now()` in system prompt, unsorted JSON, varying tool set).
327
+
328
+ For placement patterns, architectural guidance, and the silent-invalidator audit checklist: read `shared/prompt-caching.md`. Language-specific syntax: `{lang}/claude-api/README.md` (Prompt Caching section).
329
+
330
+ ## Fast Mode (Quick Reference)
331
+
332
+ **Research preview, Opus 4.8 / 4.7 only.** Opus 4.7 fast mode is deprecated — after removal, `speed: "fast"` on 4.7 returns an error. Opus 4.8 is the durable fast-capable tier. Fast mode runs the same model at up to 2.5x higher output tokens per second, at premium pricing. Three things are required on every request: use the **beta** messages endpoint (`client.beta.messages.…`), pass the beta flag `fast-mode-2026-02-01`, and set `speed: "fast"` as a top-level request parameter (not a header, not in `extra_body`).
333
+
334
+ ```python
335
+ client.beta.messages.create(
336
+ model="claude-opus-4-8", max_tokens=4096,
337
+ speed="fast", betas=["fast-mode-2026-02-01"],
338
+ messages=[...],
339
+ )
340
+ ```
341
+
342
+ | Language | Beta flag | Speed parameter |
343
+ |---|---|---|
344
+ | Python | `betas=["fast-mode-2026-02-01"]` | `speed="fast"` |
345
+ | TypeScript / Ruby | `betas: ["fast-mode-2026-02-01"]` | `speed: "fast"` |
346
+ | Go | `[]anthropic.AnthropicBeta{anthropic.AnthropicBetaFastMode2026_02_01}` | `Speed: anthropic.BetaMessageNewParamsSpeedFast` |
347
+ | Java | `.addBeta(AnthropicBeta.FAST_MODE_2026_02_01)` | `.speed(MessageCreateParams.Speed.FAST)` |
348
+ | C# | `Betas = ["fast-mode-2026-02-01"]` | `Speed = Speed.Fast` (`Anthropic.Models.Beta.Messages`) |
349
+ | PHP | `betas: ['fast-mode-2026-02-01']` | `speed: 'fast'` |
350
+ | cURL | `anthropic-beta: fast-mode-2026-02-01` header | `"speed": "fast"` in body |
351
+
352
+ `response.usage.speed` reports which speed was used. Fast mode has its own rate limit separate from standard Opus; on 429, either retry after the `retry-after` delay or drop `speed` and fall back to standard (note: switching speed invalidates prompt cache). Not available with Batch API, Priority Tier, Claude Platform on AWS, or third-party platforms.
353
+
354
+ ## Task Budgets (Quick Reference)
355
+
356
+ **Beta, Fable 5 / Sonnet 5 / Opus 4.8 / 4.7.** A task budget gives Claude a token ceiling for an agentic loop so it paces itself and finishes gracefully instead of being cut off. Set `task_budget` inside `output_config` on `client.beta.messages.stream(...)` with beta flag `task-budgets-2026-03-13` — use streaming so the large `max_tokens` doesn't hit HTTP timeouts:
357
+
358
+ ```python
359
+ with client.beta.messages.stream(
360
+ model="claude-opus-4-8", max_tokens=128000,
361
+ output_config={"effort": "high", "task_budget": {"type": "tokens", "total": 64000}},
362
+ betas=["task-budgets-2026-03-13"],
363
+ messages=[...], tools=[...],
364
+ ) as stream:
365
+ response = stream.get_final_message()
366
+ ```
367
+
368
+ `task_budget` fields: `type` (always `"tokens"`), `total`, and optional `remaining` (defaults to `total`). The server injects a countdown marker Claude sees during generation; the budget counts what Claude generates and the tool results it reads this turn — **not** the full history you resend each request.
369
+
370
+ **Observing spend:** accumulate `response.usage.output_tokens` (plus the token count of the tool-result blocks you append) across loop iterations if you want to display progress. Leave `remaining` unset in the normal loop — the server tracks the countdown itself, and passing a client-computed `remaining` while also resending full history under-reports the budget. **Only pass `remaining`** when you compact or rewrite history between requests and the server can no longer derive prior spend.
371
+
372
+ ## Provider Clients (Quick Reference)
373
+
374
+ When targeting Claude on a third-party platform, use that platform's dedicated client class — not the first-party `Anthropic()` client with a `base_url` override. After construction the client exposes the same `messages.create` / `.stream` surface as the first-party SDK.
375
+
376
+ ### Amazon Bedrock
377
+
378
+ Use the **Mantle** client (Messages-API Bedrock endpoint). Bedrock model IDs take an `anthropic.` prefix (e.g. `"anthropic.claude-opus-4-8"`). Region is required.
379
+
380
+ | Language | Client |
381
+ |---|---|
382
+ | Python | `from anthropic import AnthropicBedrockMantle` → `AnthropicBedrockMantle(aws_region="…")` |
383
+ | TypeScript | `import { AnthropicBedrockMantle } from "@anthropic-ai/bedrock-sdk"` → `new AnthropicBedrockMantle({ awsRegion: "…" })` |
384
+ | Go | `bedrock.NewMantleClient(ctx, bedrock.MantleClientConfig{ AWSRegion: "…" })` |
385
+ | Java | `AnthropicOkHttpClient.builder().backend(BedrockMantleBackend.fromEnv()).build()` (from `com.anthropic.bedrock.backends`) |
386
+ | C# | `new AnthropicBedrockMantleClient(new() { AwsRegion = "…" })` (package `Anthropic.Bedrock`) |
387
+ | PHP | `use Anthropic\Bedrock\MantleClient;` → `new MantleClient(awsRegion: '…')` |
388
+ | Ruby | `Anthropic::BedrockMantleClient.new(aws_region: "…")` |
389
+
390
+ `AnthropicBedrock` / `BedrockClient` / `BedrockBackend` (without `Mantle`) are the legacy `bedrock-runtime` InvokeModel path — prefer the Mantle client for new code.
391
+
392
+ ### Microsoft Foundry
393
+
394
+ | Language | Client |
395
+ |---|---|
396
+ | Python | `from anthropic import AnthropicFoundry` → `AnthropicFoundry(api_key=…, resource="…")` |
397
+ | TypeScript | `import AnthropicFoundry from "@anthropic-ai/foundry-sdk"` → `new AnthropicFoundry({ … })` |
398
+ | Java | `AnthropicOkHttpClient.builder().backend(FoundryBackend.fromEnv()).build()` (from `com.anthropic.foundry.backends`) |
399
+ | C# | `new AnthropicFoundryClient(new AnthropicFoundryApiKeyCredentials(…))` (package `Anthropic.Foundry`) |
400
+ | PHP | `Foundry\Client::withCredentials(…)` |
401
+
402
+ The Go and Ruby SDKs do not currently support Foundry. For Ruby, use the standard `Anthropic::Client.new(base_url: "<foundry endpoint>")` as a fallback (Entra ID auth is not built in). For Claude Platform on AWS, see `shared/claude-platform-on-aws.md`.
403
+
404
+ ### Google Cloud Vertex AI
405
+
406
+ Two required constructor args: GCP `project_id` and `region`. Vertex model IDs take **no prefix** — current-generation models (Opus 4.8/4.7/4.6, Sonnet 5, Sonnet 4.6) use the bare first-party ID (e.g. `"claude-opus-4-8"`); dated-snapshot models use an `@` version separator (e.g. `claude-opus-4-5@20251101`, **not** `claude-opus-4-5-20251101`). Auth is GCP ADC (`gcloud auth application-default login`); no Anthropic API key. `region` can be `"global"` (recommended), a multi-region (`"us"`/`"eu"`), or a specific region. After construction, use the same `messages.create` / `.stream` surface.
407
+
408
+ | Language | Client |
409
+ |---|---|
410
+ | Python | `from anthropic import AnthropicVertex` → `AnthropicVertex(project_id="…", region="…")` (install `"anthropic[vertex]"`) |
411
+ | TypeScript | `import { AnthropicVertex } from "@anthropic-ai/vertex-sdk"` → `new AnthropicVertex({ projectId, region })` |
412
+ | Go | `import "github.com/anthropics/anthropic-sdk-go/vertex"` → `anthropic.NewClient(vertex.WithGoogleAuth(ctx, region, projectID))` |
413
+ | Java | `AnthropicOkHttpClient.builder().backend(VertexBackend.builder().region("…").project("…").build()).build()` (from `com.anthropic.vertex.backends`) |
414
+ | C# | `new AnthropicClient { Backend = new VertexBackend(projectId, region) }` (package `Anthropic.Vertex`) |
415
+ | PHP | `use Anthropic\Vertex;` → `Vertex\Client::fromEnvironment(location: '…', projectId: '…')` — note `location`, not `region` |
416
+ | Ruby | `Anthropic::VertexClient.new(region: "…", project_id: "…")` |
417
+
418
+ ## Context Editing (Quick Reference)
419
+
420
+ **Beta.** Context editing **clears** old tool results or thinking blocks from the conversation before the model sees it; it is **not compaction** (which summarizes). On `client.beta.messages.*` with beta `context-management-2025-06-27`, pass `context_management.edits` with a strategy type:
421
+
422
+ ```python
423
+ client.beta.messages.create(
424
+ model="claude-opus-4-8", max_tokens=4096,
425
+ betas=["context-management-2025-06-27"],
426
+ context_management={"edits": [{"type": "clear_tool_uses_20250919"}]},
427
+ tools=[...], messages=[...],
428
+ )
429
+ ```
430
+
431
+ Strategy types: `clear_tool_uses_20250919` (clears old tool results; optional `clear_tool_inputs: true` also clears the tool_use params) and `clear_thinking_20251015` (clears thinking blocks). Do **not** use `compact_20260112` or beta `compact-2026-01-12` — those are the separate compaction feature.
432
+
433
+ ## Mid-Conversation System Messages (Quick Reference)
434
+
435
+ **Claude Opus 4.8 only; no beta header.** Append `{"role": "system", "content": "…"}` to the `messages` array (not the top-level `system` field) to add an operator instruction mid-conversation without invalidating the cached prefix. Use the regular `client.messages.create` — there is no beta. A mid-conversation system message must follow a `user` message (or an `assistant` message ending in server-tool use), and must be either the last entry in `messages` or be followed by an `assistant` turn — it cannot be `messages[0]`. Availability: `shared/platform-availability.md`. See `shared/prompt-caching.md` § Mid-conversation system messages.
436
+
437
+ ## Managed Agents (Beta)
438
+
439
+ **Managed Agents** is a third surface: server-managed stateful agents with Anthropic-hosted tool execution. You create a persisted, versioned Agent config (`POST /v1/agents`), then start Sessions that reference it. Each session provisions a container as the agent's workspace — bash, file ops, and code execution run there; the agent loop itself runs on Anthropic's orchestration layer and acts on the container via tools. The session streams events; you send messages and tool results back.
440
+
441
+ Availability: `shared/platform-availability.md`. For agents on Bedrock / Vertex / Foundry (where Managed Agents is unsupported), use Claude API + tool use.
442
+
443
+ **Mandatory flow:** Agent (once) → Session (every run). `model`/`system`/`tools` live on the agent, never the session. See `shared/managed-agents-overview.md` for the full reading guide, beta headers, and pitfalls.
444
+
445
+ **Beta headers:** `managed-agents-2026-04-01` — the SDK sets this automatically for all `client.beta.{agents,environments,sessions,vaults,memory_stores,deployments,deployment_runs}.*` calls. Skills API uses `skills-2025-10-02` and Files API uses `files-api-2025-04-14`, but you don't need to explicitly pass those in for endpoints other than `/v1/skills` and `/v1/files`.
446
+
447
+ **Subcommands** — invoke directly with `/claude-api <subcommand>`:
448
+
449
+ | Subcommand | Action |
450
+ |---|---|
451
+ | `managed-agents-onboard` | Walk the user through setting up a Managed Agent from scratch. **Read `shared/managed-agents-onboarding.md` immediately** and follow its interview script: **describe → configure the agent (propose, don't interrogate) → environment → session** (same arc as the Console quickstart, auth deferred to the session step) — defaults and inline suggestions do the work, with a silent viability gate (job vs tools/credentials/data) before any code is emitted. Do not summarize — run the interview. |
452
+
453
+ **Reading guide:** Start with `shared/managed-agents-overview.md`, then the topical `shared/managed-agents-*.md` files (core, environments, tools, events, outcomes, multiagent, webhooks, memory, scheduled-deployments, client-patterns, onboarding, api-reference). For Python, TypeScript, Go, Ruby, PHP, and Java, read `{lang}/managed-agents/README.md` for code examples. For cURL, read `curl/managed-agents.md`. **Agents are persistent — create once, reference by ID.** Store the agent ID returned by `agents.create` and pass it to every subsequent `sessions.create`; do not call `agents.create` in the request path. The Anthropic CLI (`ant`) is one convenient way to create agents and environments from version-controlled YAML — see `shared/anthropic-cli.md`. If a binding you need isn't shown in the language README, WebFetch the relevant entry from `shared/live-sources.md` rather than guess. C# has beta Managed Agents support via `client.Beta.Agents` and related namespaces.
454
+
455
+ **When the user wants to set up a Managed Agent from scratch** (e.g. "how do I get started", "walk me through creating one", "set up a new agent"): read `shared/managed-agents-onboarding.md` and run its interview — same flow as the `managed-agents-onboard` subcommand.
456
+
457
+ **When the user asks "how do I write the client code for X":** reach for `shared/managed-agents-client-patterns.md` — covers lossless stream reconnect, `processed_at` queued/processed gate, interrupt, `tool_confirmation` round-trip, the correct idle/terminated break gate, post-idle status race, stream-first ordering, file-mount gotchas, keeping credentials host-side via custom tools, etc.
458
+
459
+ **When the user wants the agent to run on a schedule** (cron, "every night", "weekly report"): read `shared/managed-agents-scheduled-deployments.md` — deployments fire sessions autonomously on a cron cadence, with per-firing run records and lifecycle controls (pause/unpause/archive).
460
+
461
+ ## Server Tools (Quick Reference)
462
+
463
+ Server-side tools run on Anthropic's infrastructure — no client-side execution loop. Declare in `tools`; results arrive as content blocks in the same response. **No beta header** unless noted. **Prefer the latest type variant your model supports.** The `_20260209` web search / web fetch variants below (dynamic filtering) require Opus 4.8/4.7/4.6, Sonnet 5, or Sonnet 4.6; the basic variants for older models are listed after the table.
464
+
465
+ | Tool | `type` | `name` | Key optional params | Result block type |
466
+ |---|---|---|---|---|
467
+ | Web search | `web_search_20260209` | `web_search` | `max_uses`, `allowed_domains`/`blocked_domains`, `user_location` | `web_search_tool_result` → `.content` is a list of `web_search_result` |
468
+ | Web fetch | `web_fetch_20260209` | `web_fetch` | `max_uses`, `allowed_domains`/`blocked_domains`, `citations`, `max_content_tokens` | `web_fetch_tool_result` → `.content` is a `web_fetch_result` with a `document` block |
469
+ | Code execution | `code_execution_20260521` | `code_execution` | none | `bash_code_execution_tool_result` → `.content.stdout` / `.stderr` / `.return_code` |
470
+ | Tool search (regex) | `tool_search_tool_regex_20251119` | `tool_search_tool_regex` | mark other tools `defer_loading: true` | `tool_search_tool_result` |
471
+ | Tool search (BM25) | `tool_search_tool_bm25_20251119` | `tool_search_tool_bm25` | mark other tools `defer_loading: true` | `tool_search_tool_result` |
472
+
473
+ `web_search_20260209` / `web_fetch_20260209` have built-in dynamic filtering — code execution runs under the hood, so do **not** separately declare `code_execution` in `tools` (a second execution environment confuses the model). For models older than Opus 4.6 / Sonnet 4.6, use the basic variants `web_search_20250305` / `web_fetch_20250910` instead; on Vertex AI only basic `web_search_20250305` is available. `code_execution_20260120` (REPL persistence + programmatic tool calling) runs on Opus 4.5+ / Sonnet 4.5+. **Go SDK only**: `code_execution_20260521` lives under `client.Beta.Messages.New` with `Betas: []anthropic.AnthropicBeta{"code-execution-2025-08-25"}` (other languages use plain `client.messages.create`); `code_execution_20260120` uses the non-beta `client.Messages.New` in Go like everywhere else. Web fetch only fetches URLs already present in the conversation. Provider availability varies by tool — see `shared/platform-availability.md`. See `shared/tool-use-concepts.md` for `pause_turn` handling.
474
+
475
+ ## Document & File Input (Quick Reference)
476
+
477
+ **PDF (base64, no beta):** `{"type": "document", "source": {"type": "base64", "media_type": "application/pdf", "data": <b64 string>}}` in user content, placed before the text block. Base64 string must have no newlines. Limits: 32 MB request, 600 pages (100 for 200k-context models). Java: `ContentBlockParam.ofDocument(DocumentBlockParam... Base64PdfSource.builder().data(...))`.
478
+
479
+ **Files API (beta `files-api-2025-04-14`):** upload via `client.beta.files.upload(...)` → response `id` is the `file_id`. Reference it as `{"type": "document", "source": {"type": "file", "file_id": "..."}}` for PDF/text, or `{"type": "image", ...}` for images — the content-block type must match the file's MIME type. The beta header is required on **both** the upload and the `messages.create` that references the file. Availability: `shared/platform-availability.md`.
480
+
481
+ **Citations (no beta):** set `citations: {enabled: true}` on each `document` content block (all or none). Response splits into multiple `text` blocks; cited blocks carry a `citations` array. Each citation has `cited_text`, `document_index`, `document_title`, and a location by `type`: `char_location` (`start_char_index`/`end_char_index`) for plain text, `page_location` (`start_page_number`/`end_page_number`, 1-indexed) for PDF, `content_block_location` for custom content. Incompatible with `output_config.format`.
482
+
483
+ ## Tool Use Patterns (Quick Reference)
484
+
485
+ **Strict tool use (no beta):** set `strict: true` as a top-level field on the tool definition (alongside `name`/`description`/`input_schema`), **not** on `tool_choice`. Schema must have `additionalProperties: false` + `required`. Guarantees `tool_use.input` validates exactly. Go: `Strict: anthropic.Bool(true)` + `additionalProperties` via `InputSchema.ExtraFields`; Java: `.strict(true)` + `.putAdditionalProperty("additionalProperties", JsonValue.from(false))`.
486
+
487
+ **Parallel tool use (default on):** one assistant message may contain multiple `tool_use` blocks. Execute them concurrently, then return **all** `tool_result` blocks in a **single** user message (don't split across multiple messages). For a failed tool, return `tool_result` with `is_error: true` — don't drop it.
488
+
489
+ **Tool Runner (SDK beta helper):** drives the tool-call loop for you via `client.beta.messages.*`. Python: `@beta_tool` decorator + `client.beta.messages.tool_runner(...)` → `runner.until_done()`. TypeScript: `betaZodTool({...})` from `@anthropic-ai/sdk/helpers/beta/zod` + `client.beta.messages.toolRunner(...)` → `await runner`. Go: `toolrunner.NewBetaToolFromJSONSchema(...)` + `client.Beta.Messages.NewToolRunner(...)` → `.RunToCompletion(ctx)`. Java requires `.addBeta("structured-outputs-2025-11-13")`. Ruby: `Anthropic::BaseTool` subclass + `client.beta.messages.tool_runner(...)`. PHP: `BetaRunnableTool` + `->toolRunner(...)`. C#: raw JSON-schema tools + `BetaToolRunner` via `client.Beta.Messages.ToolRunner(...)`.
490
+
491
+ **Programmatic tool calling (no beta header):** Claude calls your custom tool from inside code execution. Add `{"type": "code_execution_20260120", "name": "code_execution"}` **and** set `"allowed_callers": ["code_execution_20260120"]` on your custom tool. Opus 4.5+ / Sonnet 4.5+ (availability: `shared/platform-availability.md`). When responding to a pending programmatic call, the user message must contain **only** `tool_result` blocks (no text). Not compatible with `strict: true`, `disable_parallel_tool_use`, forced `tool_choice`, or MCP tools.
492
+
493
+ ## Other API Surfaces (Quick Reference)
494
+
495
+ **Message Batches (no beta; availability: `shared/platform-availability.md`):** `client.messages.batches.create(requests=[{custom_id, params}, ...])` → poll `client.messages.batches.retrieve(id).processing_status` until `"ended"` → stream `client.messages.batches.results(id)`. Each result has `.custom_id` + `.result.type` (`succeeded`/`errored`/`canceled`/`expired`); on success read `.result.message.content`. Python wraps requests as `Request(custom_id=..., params=MessageCreateParamsNonStreaming(...))`. Results arrive in **any order** — key by `custom_id`, never by position.
496
+
497
+ **Models API (no beta; availability: `shared/platform-availability.md`):** `client.models.list()` (auto-paginates) and `client.models.retrieve("claude-opus-4-8")`. Each model object has `id`, `display_name`, `created_at`, and — since Mar 2026 — `max_input_tokens` (the context window), `max_tokens` (the output cap), and `capabilities`. There is no `context_window` field.
498
+
499
+ **Stop details (GA, Opus 4.7+):** `response.stop_details` is populated **only when `stop_reason == "refusal"`** (fields: `type: "refusal"`, `category: "cyber"|"bio"|null`, `explanation`). It is `null` for every other `stop_reason` (`end_turn`, `max_tokens`, `tool_use`, `pause_turn`, …) — always guard before reading.
500
+
501
+ **Client config (no beta):** `timeout` default 10 min; **units differ by SDK** — Python/Ruby: seconds; TypeScript: **milliseconds**; Go `option.WithRequestTimeout(time.Duration)`; Java `Duration`; C# `TimeSpan`. TS scales the default up to 60 min for large `max_tokens` on non-streaming requests; Java does so for streaming requests (Java non-streaming scales 30s–10 min). `max_retries`/`maxRetries` default 2 (retries 408/409/429/5xx + connection errors). `base_url` (or `ANTHROPIC_BASE_URL` env). Per-request override: Python `client.with_options(timeout=5.0).messages.create(...)`; TS `client.messages.create({...}, {timeout: 5_000})`; Ruby `request_options: {timeout: 5}`. Timeouts are retried — wall-clock can reach `timeout × (max_retries+1)`.
502
+
503
+ ## Workload Identity Federation (Quick Reference)
504
+
505
+ **GA, no beta header.** Construct the normal zero-arg client (`Anthropic()` / `new Anthropic()` / `anthropic.NewClient()` / `AnthropicOkHttpClient.fromEnv()`); the SDK auto-detects WIF when **all** of `ANTHROPIC_FEDERATION_RULE_ID`, `ANTHROPIC_ORGANIZATION_ID`, `ANTHROPIC_SERVICE_ACCOUNT_ID`, and `ANTHROPIC_IDENTITY_TOKEN_FILE` (or `ANTHROPIC_IDENTITY_TOKEN`) are set, exchanges the JWT at `/v1/oauth/token`, and auto-refreshes. `ANTHROPIC_WORKSPACE_ID` does not gate activation — required only when the federation rule spans multiple workspaces (else 400 `workspace_id_required`), optional for single-workspace rules. `ANTHROPIC_API_KEY` or `ANTHROPIC_AUTH_TOKEN` (even empty) outrank WIF, and a set `ANTHROPIC_PROFILE` also wins over the federation env vars (a missing named profile is an error, not a fall-through) — unset all three.
506
+
507
+ ---
508
+ <!-- module: 02-common-pitfalls.md -->
509
+
510
+ # Common Pitfalls
511
+
512
+ ## Common Pitfalls
513
+
514
+ - **No `ANTHROPIC_API_KEY` ≠ no credentials.** Don't bail or ask the user for a key just because the env var is unset — run `ant auth status` first. After `ant auth login`, a bare `Anthropic()` client and `ant …` work with no env var; for raw curl, use `Authorization: Bearer $(ant auth print-credentials --access-token)` plus header `anthropic-beta: oauth-2025-04-20`. See the Authentication quick reference above and `shared/anthropic-cli.md`.
515
+ - Don't truncate inputs when passing files or content to the API. If the content is too long to fit in the context window, notify the user and discuss options (chunking, summarization, etc.) rather than silently truncating.
516
+ - **Fable 5 / Sonnet 5 / Opus 4.8 / 4.7 thinking:** Adaptive only. `thinking: {type: "enabled", budget_tokens: N}` returns 400 — `budget_tokens` is fully removed (along with `temperature`, `top_p`, `top_k`). Use `thinking: {type: "adaptive"}`. Opus 4.8 inherits this surface from 4.7 with no new breaking changes; Fable 5 adds one — an explicit `thinking: {type: "disabled"}` returns a 400 (accepted on Sonnet 5 / 4.7 / 4.8); omit the param instead.
517
+ - **Opus 4.6 / Sonnet 4.6 thinking:** Use `thinking: {type: "adaptive"}` — do NOT use `budget_tokens` for new 4.6 code (deprecated on both Opus 4.6 and Sonnet 4.6; for gradual migration of existing code, see the transitional escape hatch in `shared/model-migration.md` — note this carve-out does not apply to Fable 5, Opus 4.7 or 4.8). For older models, `budget_tokens` must be less than `max_tokens` (minimum 1024). This will throw an error if you get it wrong.
518
+ - **Prefill removed (Fable 5 and the 4.6/4.7/4.8 family):** Assistant message prefills (last-assistant-turn prefills) return a 400 error on Fable 5, Opus 4.6, Opus 4.7, Opus 4.8, and Sonnet 4.6. Use structured outputs (`output_config.format`) or system prompt instructions to control response format instead. (One exception: the fallback-credit prefill claim — when redeeming a credit with `fallback_has_prefill_claim: true`, the server accepts the echoed assistant message; see the migration guide's refusal section.)
519
+ - **Fable 5 `refusal` stop reason:** Safety classifiers may decline a request — a successful HTTP 200 with `stop_reason: "refusal"` (pre-output: empty `content`, nothing billed; mid-stream: partial output billed — discard it). Check `stop_reason` before reading `response.content[0]`, or you'll hit index errors on refused requests. To retry on another model, replay the history as-is — other models drop the refused model's thinking blocks from the prompt, unbilled; no stripping needed (and a fallback-credit redemption must echo the refused body exactly anyway, thinking blocks included). Fallbacks are **opt-in** — new `claude-fable-5` code should include the server-side `fallbacks` parameter by default so a refusal doesn't fail the request outright; see the Claude Fable 5 section above.
520
+ - **Fable 5 tokenizer:** Same tokenizer as Opus 4.8 — token counts are roughly unchanged when migrating from Opus 4.7/4.8. Coming from Opus 4.6, Sonnet, Haiku, or older, token counts differ (the Opus 4.7 tokenizer uses ~1×–1.35× as many tokens) — re-measure by calling `count_tokens` once with each model and comparing `input_tokens`.
521
+ - **Confirm migration scope before editing:** When a user asks to migrate code to a newer Claude model without naming a specific file, directory, or file list, **ask which scope to apply first** — the entire working directory, a specific subdirectory, or a specific set of files. Do not start editing until the user confirms. Imperative phrasings like "migrate my codebase", "move my project to X", "upgrade to Sonnet 4.6", or bare "migrate to Opus 4.8" are **still ambiguous** — they tell you what to do but not where, so ask. Proceed without asking only when the prompt names an exact file, a specific directory, or an explicit file list ("migrate `app.py`", "migrate everything under `services/`", "update `a.py` and `b.py`"). See `shared/model-migration.md` Step 0.
522
+ - **`max_tokens` defaults:** Don't lowball `max_tokens` — hitting the cap truncates output mid-thought and requires a retry. For non-streaming requests, default to `~16000` (keeps responses under SDK HTTP timeouts). For streaming requests, default to `~64000` (timeouts aren't a concern, so give the model room). Only go lower when you have a hard reason: classification (`~256`), cost caps, deliberately short outputs, or **`max_tokens: 0`** for cache pre-warming (see `shared/prompt-caching.md` → Pre-warming).
523
+ - **128K output tokens:** Fable 5, Opus 4.6, Opus 4.7, Opus 4.8, Sonnet 5, and Sonnet 4.6 support up to 128K `max_tokens`, but the SDKs require streaming for values that large to avoid HTTP timeouts. Use `.stream()` with `.get_final_message()` / `.finalMessage()`.
524
+ - **Tool call JSON parsing (Fable 5 and the 4.6/4.7/4.8 family):** Fable 5, Opus 4.6, Opus 4.7, Opus 4.8, and Sonnet 4.6 may produce different JSON string escaping in tool call `input` fields (e.g., Unicode or forward-slash escaping). Always parse tool inputs with `json.loads()` / `JSON.parse()` — never do raw string matching on the serialized input.
525
+ - **Structured outputs (all models):** Use `output_config: {format: {...}}` instead of the deprecated `output_format` parameter on `messages.create()`. This is a general API change, not 4.6-specific.
526
+ - **Don't reimplement SDK functionality:** The SDK provides high-level helpers — use them instead of building from scratch. Specifically: use `stream.finalMessage()` instead of wrapping `.on()` events in `new Promise()`; use typed exception classes (`Anthropic.RateLimitError`, etc.) instead of string-matching error messages; use SDK types (`Anthropic.MessageParam`, `Anthropic.Tool`, `Anthropic.Message`, etc.) instead of redefining equivalent interfaces.
527
+ - **Error handling — catch a chain, not one broad class.** A single `except APIStatusError` / `catch (AnthropicServiceException)` / `rescue APIError` loses the distinction between retryable (429, ≥500, network) and non-retryable (400/404) failures. Write a most-specific-first chain — e.g. `NotFoundError` → `RateLimitError` → `APIStatusError` → `APIConnectionError` (or the Go equivalent: `errors.As` into `*anthropic.Error` then `switch apierr.StatusCode { case 404: …; case 429: …; default: … }`). Per-language class names and namespaces are in `shared/error-codes.md`.
528
+ - **Don't research SDK types — write first.** If a type name isn't shown in the documentation included in this skill, write the code file from the namespace/package tables in the language-specific doc and let the compiler's error point you to the right name. Do not spend turns on WebFetch, SDK-repo clones, or compiling-and-running a separate reflection program to discover type names before writing — produce the source file first, then fix what the compiler reports. A quick `strings` / `jar tf` / `javap` against the installed SDK is acceptable for locating names (it returns in seconds), but don't escalate beyond that. A file with a wrong type name is recoverable; a session spent on discovery with no file written is not.
529
+ - **Bash and text editor tools are Anthropic-defined, schema-less.** Declare `{"type": "bash_20250124", "name": "bash"}` / `{"type": "text_editor_20250728", "name": "str_replace_based_edit_tool"}` — no `input_schema`. A custom tool with your own schema named `"bash"` is a different tool. Handler paths and security checks are in `shared/tool-use-concepts.md` § Client-Side Tools.
530
+ - **Advisor tool model pairing.** The advisor tool's `model` must be at least as capable as the request's top-level `model` — e.g. executor `claude-sonnet-5` → advisor `claude-opus-4-8` or `claude-opus-4-7`. An invalid pair returns 400. Pairing table in `shared/tool-use-concepts.md` § Advisor. Availability: `shared/platform-availability.md`.
531
+ - **Agent Skills ≠ Managed Agents.** To have Claude generate a `.pptx`/`.xlsx`/etc. via Agent Skills, call `client.beta.messages.create` with `container={"skills": [...]}`, the `code_execution_20260521` tool, and both `code-execution-2025-08-25` + `skills-2025-10-02` betas. Do not use `client.beta.agents` / `sessions` / `environments` here — those are the Managed Agents surface, not Agent Skills.
532
+ - **MCP connector needs both halves.** `mcp_servers=[{type:"url", url, name}]` alone is rejected as a validation error — also add `tools=[{type:"mcp_toolset", mcp_server_name:<same name>}]` with beta `mcp-client-2025-11-20`. Availability: `shared/platform-availability.md`.
533
+ - **Context editing ≠ compaction.** Context editing *clears* tool results and thinking blocks; compaction *summarizes* history. For context editing, use `context_management.edits` with type `clear_tool_uses_20250919` (or `clear_thinking_20251015`) on `client.beta.messages.*` with beta `context-management-2025-06-27` — not the `compact_20260112` type or `compact-2026-01-12` beta, which are compaction.
534
+ - **`inference_geo` is a direct top-level request parameter** — `client.messages.create(..., inference_geo="us")` / `.inferenceGeo("us")`. Do not put it in `extra_body` / `putAdditionalBodyProperty`. Supported on Opus 4.6 / Sonnet 4.6 and later; availability: `shared/platform-availability.md`. `response.usage.inference_geo` reports where inference ran.
535
+ - **Fine-grained tool streaming is not a beta feature.** Set `eager_input_streaming: true` on the tool definition and call the regular `client.messages.stream(...)`. There is no beta header and no `client.beta.*` path.
536
+ - **Cache diagnostics is beta.** Use `client.beta.messages.*` with beta `cache-diagnosis-2026-04-07`. Pass `diagnostics: {previous_message_id: null}` on the first turn and `diagnostics: {previous_message_id: <previous response id>}` on subsequent turns; the result is on `response.diagnostics`. Availability: `shared/platform-availability.md`.
537
+ - **Memory tool type is `memory_20250818`.** Declare `{"type": "memory_20250818", "name": "memory"}`. Go uses the beta-namespace type `{OfMemoryTool20250818: &anthropic.BetaMemoryTool20250818Param{}}` on `client.Beta.Messages.New`; Python/TypeScript/Ruby/PHP/C# use the non-beta `client.messages.create`; Java has both a non-beta `MemoryTool20250818` and a beta tool-runner path. Python/TypeScript provide `BetaAbstractMemoryTool` / `betaMemoryTool` helpers for implementing the backend.
538
+ - **Use a model the feature actually supports.** Some features are restricted to specific model tiers — fast mode is Opus 4.8 / 4.7 only, task budgets are Fable 5 / Sonnet 5 / Opus 4.8 / 4.7 only, and the advisor tool requires a valid executor↔advisor pair. If the user's prompt names a model that the feature doesn't support, use a supported model instead and note the substitution in the output.
539
+ - **Bedrock / Foundry: use the platform client class.** For Bedrock use the `…BedrockMantle…` client (e.g. Python `AnthropicBedrockMantle`, Java `BedrockMantleBackend`) with `anthropic.`-prefixed model IDs; `AnthropicBedrock`/`BedrockBackend` without `Mantle` is the legacy path. For Foundry use `AnthropicFoundry` / `FoundryBackend` / `AnthropicFoundryClient` where the SDK supports it (C#, Java, PHP, Python, TypeScript); Go and Ruby have no Foundry client — Ruby's documented fallback is the first-party client with a custom `base_url`. Per-language table above.
540
+ - **Don't define custom types for SDK data structures:** The SDK exports types for all API objects. Use `Anthropic.MessageParam` for messages, `Anthropic.Tool` for tool definitions, `Anthropic.ToolUseBlock` / `Anthropic.ToolResultBlockParam` for tool results, `Anthropic.Message` for responses. Defining your own `interface ChatMessage { role: string; content: unknown }` duplicates what the SDK already provides and loses type safety.
541
+ - **Report and document output:** For tasks that produce reports, documents, or visualizations, the code execution sandbox has `python-docx`, `python-pptx`, `matplotlib`, `pillow`, and `pypdf` pre-installed. Claude can generate formatted files (DOCX, PDF, charts) and return them via the Files API — consider this for "report" or "document" type requests instead of plain stdout text.
542
+ - **Server-tool errors don't raise.** Web search and web fetch errors return HTTP 200 with a `web_search_tool_result` / `web_fetch_tool_result` block whose `content` is a single error object (e.g. `{error_code: "max_uses_exceeded"}`) — not a raised exception. For web search, a success `content` is a *list*; an error `content` is an *object* — branch on that before indexing.
543
+ - **Code execution output block type:** `code_execution_20260521` returns `bash_code_execution_tool_result` (with `.content.stdout`), **not** the legacy bare `code_execution_tool_result`. Iterate `response.content` and match on the correct type.
544
+ - **Tool search: never defer everything.** The search tool itself must not have `defer_loading: true`, and at least one tool in `tools` must be non-deferred, or the API returns 400 `All tools have defer_loading set`.
545
+ - **`strict: true` goes on the tool, not `tool_choice`.** Putting `strict` on `tool_choice` does nothing; it's a sibling of `name`/`description`/`input_schema` on the tool definition itself.
546
+ - **Parallel tool results go in ONE user message.** Splitting `tool_result` blocks across multiple user messages silently trains Claude to stop making parallel calls. One assistant message of `tool_use` blocks → one user message of `tool_result` blocks.
547
+ - **Citations + structured outputs are incompatible.** Enabling `citations: {enabled: true}` on a document while also setting `output_config.format` returns a 400.
548
+ - **Batch results are unordered.** Match by `custom_id`, never by position in the results stream.
549
+ - **Vertex model IDs have no prefix.** Unlike Bedrock's `anthropic.`-prefixed IDs, Vertex takes the bare first-party ID for current-generation models (e.g. `"claude-opus-4-8"`); dated-snapshot models use an `@` separator (e.g. `claude-haiku-4-5@20251001`).
550
+ - **`stop_details` is `null` unless `stop_reason == "refusal"`.** For `max_tokens`, `end_turn`, etc., `stop_details` is `null` — guard before reading `.category`.
551
+ - **WIF auth: unset `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, and `ANTHROPIC_PROFILE`.** `ANTHROPIC_API_KEY` and `ANTHROPIC_AUTH_TOKEN` (even set to `""`) outrank Workload Identity Federation in the SDK's precedence chain and silently win; a set `ANTHROPIC_PROFILE` also wins (a missing named profile is an error, not a fall-through). `unset` them, don't blank them.
552
+
553
+ ---
554
+ <!-- module: 75-php-readme.md -->
555
+
556
+ # Claude API — PHP
557
+
558
+ > **Note:** The PHP SDK is the official Anthropic SDK for PHP. A beta tool runner is available via `$client->beta->messages->toolRunner()`. Structured output helpers are supported via `StructuredOutputModel` classes. Agent SDK is not available. Bedrock, Vertex AI, and Foundry clients are supported.
559
+
560
+ ## Installation
561
+
562
+ ```bash
563
+ composer require "anthropic-ai/sdk"
564
+ ```
565
+
566
+ ## Client Initialization
567
+
568
+ ```php
569
+ use Anthropic\Client;
570
+
571
+ // Using API key from environment variable
572
+ $client = new Client(apiKey: getenv("ANTHROPIC_API_KEY"));
573
+ ```
574
+
575
+ ### Amazon Bedrock
576
+
577
+ ```php
578
+ use Anthropic\Bedrock\MantleClient;
579
+
580
+ // Messages-API Bedrock endpoint. Reads AWS credentials from env.
581
+ $client = new MantleClient(awsRegion: 'us-east-1');
582
+ ```
583
+
584
+ Model IDs on Bedrock take an `anthropic.` prefix — e.g. `model: 'anthropic.claude-opus-4-8'`.
585
+
586
+ ### Google Vertex AI
587
+
588
+ ```php
589
+ use Anthropic\Vertex;
590
+
591
+ // Constructor is private. Parameter is `location`, not `region`.
592
+ $client = Vertex\Client::fromEnvironment(
593
+ location: 'us-east5',
594
+ projectId: 'my-project-id',
595
+ );
596
+ ```
597
+
598
+ ### Anthropic Foundry
599
+
600
+ ```php
601
+ use Anthropic\Foundry;
602
+
603
+ // Constructor is private. baseUrl or resource is required.
604
+ $client = Foundry\Client::withCredentials(
605
+ apiKey: getenv('ANTHROPIC_FOUNDRY_API_KEY'),
606
+ baseUrl: 'https://<resource>.services.ai.azure.com/anthropic/v1',
607
+ );
608
+ ```
609
+
610
+ ---
611
+
612
+ ## Basic Message Request
613
+
614
+ ```php
615
+ $message = $client->messages->create(
616
+ model: 'claude-opus-4-8',
617
+ maxTokens: 16000,
618
+ messages: [
619
+ ['role' => 'user', 'content' => 'What is the capital of France?'],
620
+ ],
621
+ );
622
+
623
+ // content is an array of polymorphic blocks (TextBlock, ToolUseBlock,
624
+ // ThinkingBlock). Accessing ->text on content[0] without checking the block
625
+ // type will throw if the first block is not a TextBlock (e.g., when extended
626
+ // thinking is enabled and a ThinkingBlock comes first). Always guard:
627
+ foreach ($message->content as $block) {
628
+ if ($block->type === 'text') {
629
+ echo $block->text;
630
+ }
631
+ }
632
+ ```
633
+
634
+ If you only want the first text block:
635
+
636
+ ```php
637
+ foreach ($message->content as $block) {
638
+ if ($block->type === 'text') {
639
+ echo $block->text;
640
+ break;
641
+ }
642
+ }
643
+ ```
644
+
645
+ ---
646
+
647
+ ## Extended Thinking
648
+
649
+ **Adaptive thinking is the recommended mode for Claude 4.6+ models.** Claude decides dynamically when and how much to think.
650
+
651
+ ```php
652
+ use Anthropic\Messages\ThinkingBlock;
653
+
654
+ $message = $client->messages->create(
655
+ model: 'claude-opus-4-8',
656
+ maxTokens: 16000,
657
+ thinking: ['type' => 'adaptive', 'display' => 'summarized'], // display opt-in: default is omitted (empty thinking text) on Fable 5 / Mythos 5 / Opus 4.8 / 4.7
658
+ messages: [
659
+ ['role' => 'user', 'content' => 'Solve: 27 * 453'],
660
+ ],
661
+ );
662
+
663
+ // ThinkingBlock(s) precede TextBlock in content
664
+ foreach ($message->content as $block) {
665
+ if ($block instanceof ThinkingBlock) {
666
+ echo "Thinking:\n{$block->thinking}\n\n";
667
+ // $block->signature is an opaque string — preserve verbatim if
668
+ // passing thinking blocks back in multi-turn conversations
669
+ } elseif ($block->type === 'text') {
670
+ echo "Answer: {$block->text}\n";
671
+ }
672
+ }
673
+ ```
674
+
675
+ > **Fable 5, Opus 4.8, Opus 4.7, Opus 4.6, and Sonnet 4.6:** Use adaptive thinking (above). `['type' => 'enabled', 'budgetTokens' => N]` is removed on Fable 5, Opus 4.8, and 4.7 (400 if sent); deprecated on Opus 4.6 and Sonnet 4.6.
676
+ > **Older models:** Use `thinking: ['type' => 'enabled', 'budgetTokens' => N]` (budget must be < `maxTokens`, min 1024).
677
+
678
+ `$block->type === 'thinking'` also works for the check; `instanceof` narrows for PHPStan.
679
+
680
+ ---
681
+
682
+ ## Prompt Caching
683
+
684
+ `system:` takes an array of text blocks; set `cacheControl` on the last block. Array-shape syntax (camelCase keys) is idiomatic. For placement patterns and the silent-invalidator audit checklist, see `shared/prompt-caching.md`.
685
+
686
+ ```php
687
+ $message = $client->messages->create(
688
+ model: 'claude-opus-4-8',
689
+ maxTokens: 16000,
690
+ system: [
691
+ ['type' => 'text', 'text' => $longSystemPrompt, 'cacheControl' => ['type' => 'ephemeral']],
692
+ ],
693
+ messages: [['role' => 'user', 'content' => 'Summarize the key points']],
694
+ );
695
+ ```
696
+
697
+ For 1-hour TTL: `'cacheControl' => ['type' => 'ephemeral', 'ttl' => '1h']`. There's also a top-level `cacheControl:` on `messages->create(...)` that auto-places on the last cacheable block.
698
+
699
+ Verify hits via `$message->usage->cacheCreationInputTokens` / `$message->usage->cacheReadInputTokens`.
700
+
701
+ ---
702
+
703
+ ## Stop Details
704
+
705
+ When `stopReason` is `'refusal'`, the response includes structured `stopDetails`:
706
+
707
+ ```php
708
+ if ($message->stopReason === 'refusal' && $message->stopDetails !== null) {
709
+ echo "Category: " . $message->stopDetails->category . "\n"; // e.g. "cyber", "bio", "reasoning_extraction", "frontier_llm", or null — see docs for the full set
710
+ echo "Explanation: " . $message->stopDetails->explanation . "\n";
711
+ }
712
+ ```
713
+
714
+ **Refusal fallbacks (Claude Fable 5) — opt in by default.** Fallbacks are opt-in: without them a refused request simply stops. New `claude-fable-5` code should include the server-side `fallbacks` parameter (beta header `server-side-fallback-2026-06-01`, fallback model `claude-opus-4-8`, on the beta messages call) by default. The exact PHP binding (and the client-side middleware for providers without server-side support) is not documented here — WebFetch the PHP SDK repo's `examples/` from `shared/live-sources.md`; full semantics in `shared/model-migration.md` → Migrating to Claude Fable 5 → `refusal` stop reason.
715
+
716
+ ---
717
+
718
+ ## Error Type
719
+
720
+ `APIStatusException` exposes a `->type` property for programmatic error classification:
721
+
722
+ ```php
723
+ try {
724
+ $client->messages->create(...);
725
+ } catch (\Anthropic\Core\Exceptions\APIStatusException $e) {
726
+ echo $e->type?->value; // "rate_limit_error", "overloaded_error", etc.
727
+ }
728
+ ```
729
+
730
+ ---
731
+ <!-- module: 76-php-tool-use.md -->
732
+
733
+ # Tool Use — PHP
734
+
735
+ For conceptual overview (tool definitions, tool choice, tips), see [shared/tool-use-concepts.md](../../shared/tool-use-concepts.md).
736
+
737
+ ## Tool Use
738
+
739
+ ### Tool Runner (Beta)
740
+
741
+ **Beta:** The PHP SDK provides a tool runner via `$client->beta->messages->toolRunner()`. Define tools with `BetaRunnableTool` — a definition array plus a `run` closure:
742
+
743
+ ```php
744
+ use Anthropic\Lib\Tools\BetaRunnableTool;
745
+
746
+ $weatherTool = new BetaRunnableTool(
747
+ definition: [
748
+ 'name' => 'get_weather',
749
+ 'description' => 'Get the current weather for a location.',
750
+ 'inputSchema' => [
751
+ 'type' => 'object',
752
+ 'properties' => [
753
+ 'location' => ['type' => 'string', 'description' => 'City and state'],
754
+ ],
755
+ 'required' => ['location'],
756
+ ],
757
+ ],
758
+ run: function (array $input): string {
759
+ return "The weather in {$input['location']} is sunny and 72°F.";
760
+ },
761
+ );
762
+
763
+ $runner = $client->beta->messages->toolRunner(
764
+ maxTokens: 16000,
765
+ messages: [['role' => 'user', 'content' => 'What is the weather in Paris?']],
766
+ model: 'claude-opus-4-8',
767
+ tools: [$weatherTool],
768
+ );
769
+
770
+ foreach ($runner as $message) {
771
+ foreach ($message->content as $block) {
772
+ if ($block->type === 'text') {
773
+ echo $block->text;
774
+ }
775
+ }
776
+ }
777
+ ```
778
+
779
+ ### Manual Loop
780
+
781
+ Tools are passed as arrays. **The SDK uses camelCase keys** (`inputSchema`, `toolUseID`, `stopReason`) and auto-maps to the API's snake_case on the wire — since v0.5.0. See [shared tool use concepts](../../shared/tool-use-concepts.md) for the loop pattern.
782
+
783
+ ```php
784
+ use Anthropic\Messages\ToolUseBlock;
785
+
786
+ $tools = [
787
+ [
788
+ 'name' => 'get_weather',
789
+ 'description' => 'Get the current weather in a given location',
790
+ 'inputSchema' => [ // camelCase, not input_schema
791
+ 'type' => 'object',
792
+ 'properties' => [
793
+ 'location' => ['type' => 'string', 'description' => 'City and state'],
794
+ ],
795
+ 'required' => ['location'],
796
+ ],
797
+ ],
798
+ ];
799
+
800
+ $messages = [['role' => 'user', 'content' => 'What is the weather in SF?']];
801
+
802
+ $response = $client->messages->create(
803
+ model: 'claude-opus-4-8',
804
+ maxTokens: 16000,
805
+ tools: $tools,
806
+ messages: $messages,
807
+ );
808
+
809
+ while ($response->stopReason === 'tool_use') { // camelCase property
810
+ $toolResults = [];
811
+ foreach ($response->content as $block) {
812
+ if ($block instanceof ToolUseBlock) {
813
+ // $block->name : string — tool name to dispatch on
814
+ // $block->input : array<string,mixed> — parsed JSON input
815
+ // $block->id : string — pass back as toolUseID
816
+ $result = executeYourTool($block->name, $block->input);
817
+ $toolResults[] = [
818
+ 'type' => 'tool_result',
819
+ 'toolUseID' => $block->id, // camelCase, not tool_use_id
820
+ 'content' => $result,
821
+ ];
822
+ }
823
+ }
824
+
825
+ // Append assistant turn + user turn with tool results
826
+ $messages[] = ['role' => 'assistant', 'content' => $response->content];
827
+ $messages[] = ['role' => 'user', 'content' => $toolResults];
828
+
829
+ $response = $client->messages->create(
830
+ model: 'claude-opus-4-8',
831
+ maxTokens: 16000,
832
+ tools: $tools,
833
+ messages: $messages,
834
+ );
835
+ }
836
+
837
+ // Final text response
838
+ foreach ($response->content as $block) {
839
+ if ($block->type === 'text') {
840
+ echo $block->text;
841
+ }
842
+ }
843
+ ```
844
+
845
+ `$block->type === 'tool_use'` also works; `instanceof ToolUseBlock` narrows for PHPStan.
846
+
847
+
848
+ ---
849
+
850
+ ## Structured Outputs
851
+
852
+ ### Using StructuredOutputModel (Recommended)
853
+
854
+ Define a PHP class implementing `StructuredOutputModel` and pass it as `outputConfig`:
855
+
856
+ ```php
857
+ use Anthropic\Lib\Contracts\StructuredOutputModel;
858
+ use Anthropic\Lib\Concerns\StructuredOutputModelTrait;
859
+ use Anthropic\Lib\Attributes\Constrained;
860
+
861
+ class Person implements StructuredOutputModel
862
+ {
863
+ use StructuredOutputModelTrait;
864
+
865
+ #[Constrained(description: 'Full name')]
866
+ public string $name;
867
+
868
+ public int $age;
869
+
870
+ public ?string $email = null; // nullable = optional field
871
+ }
872
+
873
+ $message = $client->messages->create(
874
+ model: 'claude-opus-4-8',
875
+ maxTokens: 16000,
876
+ messages: [['role' => 'user', 'content' => 'Generate a profile for Alice, age 30']],
877
+ outputConfig: ['format' => Person::class],
878
+ );
879
+
880
+ $person = $message->parsedOutput(); // Person instance
881
+ echo $person->name;
882
+ ```
883
+
884
+ Types are inferred from PHP type hints. Use `#[Constrained(description: '...')]` to add descriptions. Nullable properties (`?string`) become optional fields.
885
+
886
+ ### Raw Schema
887
+
888
+ ```php
889
+ $message = $client->messages->create(
890
+ model: 'claude-opus-4-8',
891
+ maxTokens: 16000,
892
+ messages: [['role' => 'user', 'content' => 'Extract: John (john@co.com), Enterprise plan']],
893
+ outputConfig: [
894
+ 'format' => [
895
+ 'type' => 'json_schema',
896
+ 'schema' => [
897
+ 'type' => 'object',
898
+ 'properties' => [
899
+ 'name' => ['type' => 'string'],
900
+ 'email' => ['type' => 'string'],
901
+ 'plan' => ['type' => 'string'],
902
+ ],
903
+ 'required' => ['name', 'email', 'plan'],
904
+ 'additionalProperties' => false,
905
+ ],
906
+ ],
907
+ ],
908
+ );
909
+
910
+ // First text block contains valid JSON
911
+ foreach ($message->content as $block) {
912
+ if ($block->type === 'text') {
913
+ $data = json_decode($block->text, true);
914
+ break;
915
+ }
916
+ }
917
+ ```
918
+
919
+ ---
920
+
921
+ ## Beta Features & Anthropic-Defined Tools
922
+
923
+ **`betas:` is NOT a param on `$client->messages->create()`** — it only exists on the beta namespace. Use it for features that need an explicit opt-in header:
924
+
925
+ ```php
926
+ use Anthropic\Beta\Messages\BetaRequestMCPServerURLDefinition;
927
+
928
+ $response = $client->beta->messages->create(
929
+ model: 'claude-opus-4-8',
930
+ maxTokens: 16000,
931
+ mcpServers: [
932
+ BetaRequestMCPServerURLDefinition::with(
933
+ name: 'my-server',
934
+ url: 'https://example.com/mcp',
935
+ ),
936
+ ],
937
+ betas: ['mcp-client-2025-11-20'], // only valid on ->beta->messages
938
+ messages: [['role' => 'user', 'content' => 'Use the MCP tools']],
939
+ );
940
+ ```
941
+
942
+ ### Task budgets
943
+
944
+ ```php
945
+ $response = $client->beta->messages->create(
946
+ model: 'claude-opus-4-8',
947
+ maxTokens: 16000,
948
+ outputConfig: ['taskBudget' => ['type' => 'tokens', 'total' => 64000]],
949
+ tools: [...],
950
+ messages: [...],
951
+ betas: ['task-budgets-2026-03-13'],
952
+ );
953
+ ```
954
+
955
+ ### Cache diagnostics
956
+
957
+ Pass the previous response's `id` on the next request; print the `diagnostics` object on the response:
958
+
959
+ ```php
960
+ $r2 = $client->beta->messages->create(
961
+ model: 'claude-opus-4-8', maxTokens: 1024,
962
+ diagnostics: ['previousMessageId' => $r1->id],
963
+ betas: ['cache-diagnosis-2026-04-07'],
964
+ messages: [...],
965
+ );
966
+ ```
967
+
968
+ **Anthropic-defined tools** (bash, web_search, text_editor, code_execution) are GA and work on both paths. Of these, web_search and code_execution are server-executed; bash and text_editor are client-executed (you handle the `tool_use` locally) — `Anthropic\Messages\ToolBash20250124` / `WebSearchTool20260209` / `ToolTextEditor20250728` / `CodeExecutionTool20260120` for non-beta, `Anthropic\Beta\Messages\BetaToolBash20250124` / `BetaWebSearchTool20260209` / `BetaToolTextEditor20250728` / `BetaCodeExecutionTool20260120` for beta. No `betas:` header needed for these.
969
+
970
+ ### Tool search (non-beta, server-side)
971
+
972
+ ```php
973
+ tools: [
974
+ ['type' => 'tool_search_tool_regex_20251119', 'name' => 'tool_search_tool_regex'],
975
+ ['name' => 'get_weather', 'description' => '...', 'inputSchema' => [...], 'deferLoading' => true],
976
+ // ... other user tools with 'deferLoading' => true
977
+ ],
978
+ ```
979
+
980
+ ### Memory tool (non-beta, client-executed)
981
+
982
+ Declare `['type' => 'memory_20250818', 'name' => 'memory']`. Handle the `tool_use` by reading/writing files under a fixed `/memories` directory. **Validate every model-supplied path**: resolve to its canonical form and verify it remains within the memory directory; reject traversal (`..`, symlinks) — see `shared/tool-use-concepts.md` § Client-Side Tools.
983
+
984
+ ---
985
+
986
+ ---
987
+ <!-- module: 77-php-streaming-batches-files.md -->
988
+
989
+ # Streaming — PHP
990
+
991
+ ## Streaming
992
+
993
+ > **Requires SDK v0.5.0+.** v0.4.0 and earlier used a single `$params` array; calling with named parameters throws `Unknown named parameter $model`. Upgrade: `composer require "anthropic-ai/sdk:^0.7"`
994
+
995
+ ```php
996
+ use Anthropic\Messages\RawContentBlockDeltaEvent;
997
+ use Anthropic\Messages\TextDelta;
998
+
999
+ $stream = $client->messages->createStream(
1000
+ model: 'claude-opus-4-8',
1001
+ maxTokens: 64000,
1002
+ messages: [
1003
+ ['role' => 'user', 'content' => 'Write a haiku'],
1004
+ ],
1005
+ );
1006
+
1007
+ foreach ($stream as $event) {
1008
+ if ($event instanceof RawContentBlockDeltaEvent && $event->delta instanceof TextDelta) {
1009
+ echo $event->delta->text;
1010
+ }
1011
+ }
1012
+ ```
1013
+
1014
+ ---
1015
+
1016
+ # Message Batches — PHP
1017
+
1018
+ ## Message Batches API
1019
+
1020
+ ```php
1021
+ $batch = $client->messages->batches->create(requests: [
1022
+ ['customId' => 'req-1', 'params' => ['model' => 'claude-opus-4-8', 'maxTokens' => 1024, 'messages' => [...]]],
1023
+ ['customId' => 'req-2', 'params' => [...]],
1024
+ ]);
1025
+ // Poll $client->messages->batches->retrieve($batch->id) until processingStatus === 'ended',
1026
+ // then iterate $client->messages->batches->results($batch->id).
1027
+ ```
1028
+
1029
+ ---
1030
+
1031
+ # Files API — PHP
1032
+
1033
+ ## Files API
1034
+
1035
+ ```php
1036
+ $file = $client->beta->files->upload(
1037
+ file: fopen('upload_me.txt', 'r'),
1038
+ betas: ['files-api-2025-04-14'],
1039
+ );
1040
+ // Reference $file->id as a file content block on ->beta->messages->create().
1041
+ ```
1042
+
1043
+ ---
1044
+ <!-- module: 78-php-managed-agents.md -->
1045
+
1046
+ # Managed Agents — PHP
1047
+
1048
+ > **Bindings not shown here:** This README covers the most common managed-agents flows for PHP. If you need a class, method, namespace, field, or behavior that isn't shown, WebFetch the PHP SDK repo **or the relevant docs page** from `shared/live-sources.md` rather than guess. Do not extrapolate from cURL shapes or another language's SDK.
1049
+
1050
+ > **Agents are persistent — create once, reference by ID.** Store the agent ID returned by `$client->beta->agents->create` and pass it to every subsequent `->sessions->create`; do not call `agents->create` in the request path. The Anthropic CLI is one convenient way to create agents and environments from version-controlled YAML — its URL is in `shared/live-sources.md`. The examples below show in-code creation for completeness; in production the create call belongs in setup, not in the request path.
1051
+
1052
+ ## Installation
1053
+
1054
+ ```bash
1055
+ composer require "anthropic-ai/sdk" "guzzlehttp/guzzle:^7"
1056
+ ```
1057
+
1058
+ ## Client Initialization
1059
+
1060
+ ```php
1061
+ use Anthropic\Client;
1062
+
1063
+ // Default (uses ANTHROPIC_API_KEY env var)
1064
+ $client = new Client();
1065
+
1066
+ // Explicit API key
1067
+ $client = new Client(apiKey: 'your-api-key');
1068
+ ```
1069
+
1070
+ ---
1071
+
1072
+ ## Create an Environment
1073
+
1074
+ ```php
1075
+ $environment = $client->beta->environments->create(
1076
+ name: 'my-dev-env',
1077
+ config: ['type' => 'cloud', 'networking' => ['type' => 'unrestricted']],
1078
+ );
1079
+ echo "Environment ID: {$environment->id}\n"; // env_...
1080
+ ```
1081
+
1082
+ ---
1083
+
1084
+ ## Create an Agent (required first step)
1085
+
1086
+ > ⚠️ **There is no inline agent config.** `model`/`system`/`tools` live on the agent object, not the session. Always start with `$client->beta->agents->create()` — the session takes either `agent: $agent->id` or the typed `BetaManagedAgentsAgentParams::with(type: 'agent', id: $agent->id, version: $agent->version)`.
1087
+
1088
+ ### Minimal
1089
+
1090
+ ```php
1091
+ use Anthropic\Beta\Agents\BetaManagedAgentsAgentToolset20260401Params;
1092
+
1093
+ // 1. Create the agent (reusable, versioned)
1094
+ $agent = $client->beta->agents->create(
1095
+ name: 'Coding Assistant',
1096
+ model: 'claude-opus-4-8',
1097
+ system: 'You are a helpful coding assistant.',
1098
+ tools: [
1099
+ BetaManagedAgentsAgentToolset20260401Params::with(
1100
+ type: 'agent_toolset_20260401',
1101
+ ),
1102
+ ],
1103
+ );
1104
+
1105
+ // 2. Start a session
1106
+ $session = $client->beta->sessions->create(
1107
+ agent: ['type' => 'agent', 'id' => $agent->id, 'version' => $agent->version],
1108
+ environmentID: $environment->id,
1109
+ title: 'Quickstart session',
1110
+ );
1111
+ echo "Session ID: {$session->id}\n";
1112
+ echo "Trace: https://platform.claude.com/workspaces/default/sessions/{$session->id}\n";
1113
+ ```
1114
+
1115
+ ### Updating an Agent
1116
+
1117
+ Updates create new versions; the agent object is immutable per version.
1118
+
1119
+ ```php
1120
+ $updatedAgent = $client->beta->agents->update(
1121
+ $agent->id,
1122
+ version: $agent->version,
1123
+ system: 'You are a helpful coding agent. Always write tests.',
1124
+ );
1125
+ echo "New version: {$updatedAgent->version}\n";
1126
+
1127
+ // List all versions
1128
+ foreach ($client->beta->agents->versions->list($agent->id)->pagingEachItem() as $version) {
1129
+ echo "Version {$version->version}: {$version->updatedAt->format(DateTimeInterface::ATOM)}\n";
1130
+ }
1131
+
1132
+ // Archive the agent
1133
+ $archived = $client->beta->agents->archive($agent->id);
1134
+ echo "Archived at: {$archived->archivedAt->format(DateTimeInterface::ATOM)}\n";
1135
+ ```
1136
+
1137
+ ---
1138
+
1139
+ ## Send a User Message
1140
+
1141
+ ```php
1142
+ $client->beta->sessions->events->send(
1143
+ $session->id,
1144
+ events: [
1145
+ [
1146
+ 'type' => 'user.message',
1147
+ 'content' => [['type' => 'text', 'text' => 'Review the auth module']],
1148
+ ],
1149
+ ],
1150
+ );
1151
+ ```
1152
+
1153
+ > 💡 **Stream-first:** Open the stream *before* (or concurrently with) sending the message. The stream only delivers events that occur after it opens — stream-after-send means early events arrive buffered in one batch. See [Steering Patterns](../../shared/managed-agents-events.md#steering-patterns).
1154
+
1155
+ ---
1156
+
1157
+ ## Stream Events (SSE)
1158
+
1159
+ > ℹ️ **Streaming transporter:** PHP's default buffered PSR-18 client never returns for the open-ended session event stream. Use a streaming Guzzle transporter for `streamStream()` calls — other calls keep the default client.
1160
+
1161
+ ```php
1162
+ $streamingClient = new GuzzleHttp\Client(['stream' => true]);
1163
+
1164
+ // Open the stream first, then send the user message
1165
+ $stream = $client->beta->sessions->events->streamStream(
1166
+ $session->id,
1167
+ requestOptions: ['transporter' => $streamingClient],
1168
+ );
1169
+ $client->beta->sessions->events->send(
1170
+ $session->id,
1171
+ events: [
1172
+ [
1173
+ 'type' => 'user.message',
1174
+ 'content' => [['type' => 'text', 'text' => 'Summarize the repo README']],
1175
+ ],
1176
+ ],
1177
+ );
1178
+
1179
+ foreach ($stream as $event) {
1180
+ match ($event->type) {
1181
+ 'agent.message' => array_walk(
1182
+ $event->content,
1183
+ static fn($block) => $block->type === 'text' ? print($block->text) : null,
1184
+ ),
1185
+ 'agent.tool_use' => print("\n[Using tool: {$event->name}]\n"),
1186
+ 'session.error' => printf("\n[Error: %s]", $event->error?->message ?? 'unknown'),
1187
+ default => null,
1188
+ };
1189
+ if ($event->type === 'session.status_idle' || $event->type === 'session.error') {
1190
+ break;
1191
+ }
1192
+ }
1193
+ $stream->close();
1194
+ ```
1195
+
1196
+ ### Reconnecting and Tailing
1197
+
1198
+ When reconnecting mid-session, list past events first to dedupe, then tail live events:
1199
+
1200
+ ```php
1201
+ $stream = $client->beta->sessions->events->streamStream(
1202
+ $session->id,
1203
+ requestOptions: ['transporter' => $streamingClient],
1204
+ );
1205
+
1206
+ // Stream is open and buffering. List history before tailing live.
1207
+ $seenEventIds = [];
1208
+ foreach ($client->beta->sessions->events->list($session->id)->pagingEachItem() as $event) {
1209
+ $seenEventIds[$event->id] = true;
1210
+ }
1211
+
1212
+ // Tail live events, skipping anything already seen
1213
+ foreach ($stream as $event) {
1214
+ if (isset($seenEventIds[$event->id])) {
1215
+ continue;
1216
+ }
1217
+ $seenEventIds[$event->id] = true;
1218
+ match ($event->type) {
1219
+ 'agent.message' => array_walk(
1220
+ $event->content,
1221
+ static fn($block) => $block->type === 'text' ? print($block->text) : null,
1222
+ ),
1223
+ default => null,
1224
+ };
1225
+ if ($event->type === 'session.status_idle') {
1226
+ break;
1227
+ }
1228
+ }
1229
+ $stream->close();
1230
+ ```
1231
+
1232
+ ---
1233
+
1234
+ ## Provide Custom Tool Result
1235
+
1236
+ > ℹ️ The PHP managed-agents bindings for `user.custom_tool_result` are not yet documented in this skill or in the apps source examples. Refer to `shared/managed-agents-events.md` for the wire format and the `anthropic-ai/sdk` PHP repository for the corresponding params.
1237
+
1238
+ ---
1239
+
1240
+ ## Poll Events
1241
+
1242
+ ```php
1243
+ foreach ($client->beta->sessions->events->list($session->id)->pagingEachItem() as $event) {
1244
+ echo "{$event->type}: {$event->id}\n";
1245
+ }
1246
+ ```
1247
+
1248
+ ---
1249
+
1250
+ ## Upload a File
1251
+
1252
+ > ℹ️ **PHP file upload:** The PHP SDK's beta managed-agents file upload binding is not shown in the apps source examples; the canonical PHP example uses raw cURL against `POST /v1/files`. If your codebase prefers the SDK, WebFetch the `anthropic-ai/sdk` PHP repository for the latest binding before writing code.
1253
+
1254
+ ```php
1255
+ use Anthropic\Beta\Sessions\BetaManagedAgentsFileResourceParams;
1256
+
1257
+ // Raw cURL upload (canonical example from the apps source)
1258
+ $csvPath = 'data.csv';
1259
+ $ch = curl_init('https://api.anthropic.com/v1/files');
1260
+ curl_setopt_array($ch, [
1261
+ CURLOPT_RETURNTRANSFER => true,
1262
+ CURLOPT_POST => true,
1263
+ CURLOPT_HTTPHEADER => [
1264
+ 'x-api-key: ' . getenv('ANTHROPIC_API_KEY'),
1265
+ 'anthropic-version: 2023-06-01',
1266
+ 'anthropic-beta: files-api-2025-04-14',
1267
+ ],
1268
+ CURLOPT_POSTFIELDS => ['file' => new CURLFile($csvPath, 'text/csv', 'data.csv')],
1269
+ ]);
1270
+ $file = json_decode(curl_exec($ch));
1271
+ echo "File ID: {$file->id}\n";
1272
+
1273
+ // Mount in a session
1274
+ $session = $client->beta->sessions->create(
1275
+ agent: $agent->id,
1276
+ environmentID: $environment->id,
1277
+ resources: [
1278
+ BetaManagedAgentsFileResourceParams::with(
1279
+ type: 'file',
1280
+ fileID: $file->id,
1281
+ mountPath: '/workspace/data.csv',
1282
+ ),
1283
+ ],
1284
+ );
1285
+ ```
1286
+
1287
+ ### Add and Manage Resources on an Existing Session
1288
+
1289
+ ```php
1290
+ // Attach an additional file to an open session
1291
+ $resource = $client->beta->sessions->resources->add(
1292
+ $session->id,
1293
+ type: 'file',
1294
+ fileID: $file->id,
1295
+ );
1296
+ echo "{$resource->id}\n"; // "sesrsc_01ABC..."
1297
+
1298
+ // List resources on the session
1299
+ $listed = $client->beta->sessions->resources->list($session->id);
1300
+ foreach ($listed->data as $entry) {
1301
+ echo "{$entry->id} {$entry->type}\n";
1302
+ }
1303
+
1304
+ // Detach a resource
1305
+ $client->beta->sessions->resources->delete($resource->id, sessionID: $session->id);
1306
+ ```
1307
+
1308
+ ---
1309
+
1310
+ ## List and Download Session Files
1311
+
1312
+ ```php
1313
+ $files = $client->beta->files->list(
1314
+ scopeID: 'sesn_abc123',
1315
+ betas: ['managed-agents-2026-04-01'],
1316
+ );
1317
+ $content = $client->beta->files->download($files->data[0]->id);
1318
+ file_put_contents('output.txt', $content);
1319
+ ```
1320
+
1321
+ ---
1322
+
1323
+ ## Session Management
1324
+
1325
+ ```php
1326
+ // List environments
1327
+ $environments = $client->beta->environments->list();
1328
+
1329
+ // Retrieve a specific environment
1330
+ $env = $client->beta->environments->retrieve($environment->id);
1331
+
1332
+ // Archive an environment (read-only, existing sessions continue)
1333
+ $client->beta->environments->archive($environment->id);
1334
+
1335
+ // Delete an environment (only if no sessions reference it)
1336
+ $client->beta->environments->delete($environment->id);
1337
+
1338
+ // Delete a session
1339
+ $client->beta->sessions->delete($session->id);
1340
+ ```
1341
+
1342
+ ---
1343
+
1344
+ ## MCP Server Integration
1345
+
1346
+ ```php
1347
+ use Anthropic\Beta\Agents\BetaManagedAgentsAgentToolset20260401Params;
1348
+ use Anthropic\Beta\Agents\BetaManagedAgentsMCPToolsetParams;
1349
+ use Anthropic\Beta\Agents\BetaManagedAgentsURLMCPServerParams;
1350
+ use Anthropic\Beta\Sessions\BetaManagedAgentsAgentParams;
1351
+
1352
+ // Agent declares MCP server (no auth here — auth goes in a vault)
1353
+ $agent = $client->beta->agents->create(
1354
+ name: 'GitHub Assistant',
1355
+ model: 'claude-opus-4-8',
1356
+ mcpServers: [
1357
+ BetaManagedAgentsURLMCPServerParams::with(
1358
+ type: 'url',
1359
+ name: 'github',
1360
+ url: 'https://api.githubcopilot.com/mcp/',
1361
+ ),
1362
+ ],
1363
+ tools: [
1364
+ BetaManagedAgentsAgentToolset20260401Params::with(type: 'agent_toolset_20260401'),
1365
+ BetaManagedAgentsMCPToolsetParams::with(
1366
+ type: 'mcp_toolset',
1367
+ mcpServerName: 'github',
1368
+ ),
1369
+ ],
1370
+ );
1371
+
1372
+ // Session attaches vault(s) containing credentials for those MCP server URLs
1373
+ $session = $client->beta->sessions->create(
1374
+ agent: BetaManagedAgentsAgentParams::with(
1375
+ type: 'agent',
1376
+ id: $agent->id,
1377
+ version: $agent->version,
1378
+ ),
1379
+ environmentID: $environment->id,
1380
+ vaultIDs: [$vault->id],
1381
+ );
1382
+ ```
1383
+
1384
+ See `shared/managed-agents-tools.md` §Vaults for creating vaults and adding credentials.
1385
+
1386
+ ---
1387
+
1388
+ ## Vaults
1389
+
1390
+ ```php
1391
+ // Create a vault
1392
+ $vault = $client->beta->vaults->create(
1393
+ displayName: 'Alice',
1394
+ metadata: ['external_user_id' => 'usr_abc123'],
1395
+ );
1396
+ echo $vault->id . "\n"; // "vlt_01ABC..."
1397
+
1398
+ // Add an OAuth credential
1399
+ $credential = $client->beta->vaults->credentials->create(
1400
+ vaultID: $vault->id,
1401
+ displayName: "Alice's Slack",
1402
+ auth: [
1403
+ 'type' => 'mcp_oauth',
1404
+ 'mcp_server_url' => 'https://mcp.slack.com/mcp',
1405
+ 'access_token' => 'xoxp-...',
1406
+ 'expires_at' => '2026-04-15T00:00:00Z',
1407
+ 'refresh' => [
1408
+ 'token_endpoint' => 'https://slack.com/api/oauth.v2.access',
1409
+ 'client_id' => '1234567890.0987654321',
1410
+ 'scope' => 'channels:read chat:write',
1411
+ 'refresh_token' => 'xoxe-1-...',
1412
+ 'token_endpoint_auth' => [
1413
+ 'type' => 'client_secret_post',
1414
+ 'client_secret' => 'abc123...',
1415
+ ],
1416
+ ],
1417
+ ],
1418
+ );
1419
+
1420
+ // Rotate the credential (e.g., after a token refresh)
1421
+ $client->beta->vaults->credentials->update(
1422
+ $credential->id,
1423
+ vaultID: $vault->id,
1424
+ auth: [
1425
+ 'type' => 'mcp_oauth',
1426
+ 'access_token' => 'xoxp-new-...',
1427
+ 'expires_at' => '2026-05-15T00:00:00Z',
1428
+ 'refresh' => ['refresh_token' => 'xoxe-1-new-...'],
1429
+ ],
1430
+ );
1431
+
1432
+ // Archive a vault
1433
+ $client->beta->vaults->archive($vault->id);
1434
+ ```
1435
+
1436
+ ---
1437
+
1438
+ ## GitHub Repository Integration
1439
+
1440
+ Mount a GitHub repository as a session resource (a vault holds the GitHub MCP credential):
1441
+
1442
+ ```php
1443
+ $session = $client->beta->sessions->create(
1444
+ agent: $agent->id,
1445
+ environmentID: $environment->id,
1446
+ vaultIDs: [$vault->id],
1447
+ resources: [
1448
+ [
1449
+ 'type' => 'github_repository',
1450
+ 'url' => 'https://github.com/org/repo',
1451
+ 'mount_path' => '/workspace/repo',
1452
+ 'authorization_token' => 'ghp_your_github_token',
1453
+ ],
1454
+ ],
1455
+ );
1456
+ ```
1457
+
1458
+ Multiple repositories on the same session:
1459
+
1460
+ ```php
1461
+ $resources = [
1462
+ [
1463
+ 'type' => 'github_repository',
1464
+ 'url' => 'https://github.com/org/frontend',
1465
+ 'mount_path' => '/workspace/frontend',
1466
+ 'authorization_token' => 'ghp_your_github_token',
1467
+ ],
1468
+ [
1469
+ 'type' => 'github_repository',
1470
+ 'url' => 'https://github.com/org/backend',
1471
+ 'mount_path' => '/workspace/backend',
1472
+ 'authorization_token' => 'ghp_your_github_token',
1473
+ ],
1474
+ ];
1475
+ ```
1476
+
1477
+ Rotating a repository's authorization token:
1478
+
1479
+ ```php
1480
+ $listed = $client->beta->sessions->resources->list($session->id);
1481
+ $repoResourceId = $listed->data[0]->id;
1482
+
1483
+ $client->beta->sessions->resources->update(
1484
+ $repoResourceId,
1485
+ sessionID: $session->id,
1486
+ authorizationToken: 'ghp_your_new_github_token',
1487
+ );
1488
+ ```